filesystem.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package filesystem
  2. /*
  3. ArOZ Online File System Handler Wrappers
  4. author: tobychui
  5. This is a module design to do the followings
  6. 1. Mount / Create a fs when open
  7. 2. Provide the basic function and operations of a file system type
  8. 3. THIS MODULE **SHOULD NOT CONTAIN** CROSS FILE SYSTEM TYPE OPERATIONS
  9. */
  10. import (
  11. "errors"
  12. "io"
  13. "log"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. db "imuslab.com/arozos/mod/database"
  19. "imuslab.com/arozos/mod/disk/hybridBackup"
  20. "imuslab.com/arozos/mod/filesystem/abstractions/localfs"
  21. "imuslab.com/arozos/mod/filesystem/abstractions/webdavfs"
  22. )
  23. //Options for creating new file system handler
  24. /*
  25. type FileSystemOpeningOptions struct{
  26. Name string `json:"name"` //Display name of this device
  27. Uuid string `json:"uuid"` //UUID of this device, e.g. S1
  28. Path string `json:"path"` //Path for the storage root
  29. Access string `json:"access,omitempty"` //Access right, allow {readonly, readwrite}
  30. Hierarchy string `json:"hierarchy"` //Folder hierarchy, allow {public, user}
  31. Automount bool `json:"automount"` //Automount this device if exists
  32. Filesystem string `json:"filesystem,omitempty"` //Support {"ext4","ext2", "ext3", "fat", "vfat", "ntfs"}
  33. Mountdev string `json:"mountdev,omitempty"` //Device file (e.g. /dev/sda1)
  34. Mountpt string `json:"mountpt,omitempty"` //Device mount point (e.g. /media/storage1)
  35. }
  36. */
  37. /*
  38. An interface for storing data related to a specific hierarchy settings.
  39. Example like the account information of network drive,
  40. backup mode of backup drive etc
  41. */
  42. type HierarchySpecificConfig interface{}
  43. type FileSystemAbstraction interface {
  44. //Fundemental Functions
  45. Chmod(string, os.FileMode) error
  46. Chown(string, int, int) error
  47. Chtimes(string, time.Time, time.Time) error
  48. Create(string) (*os.File, error)
  49. Mkdir(string, os.FileMode) error
  50. MkdirAll(string, os.FileMode) error
  51. Name() string
  52. Open(string) (*os.File, error)
  53. OpenFile(string, int, os.FileMode) (*os.File, error)
  54. Remove(string) error
  55. RemoveAll(string) error
  56. Rename(string, string) error
  57. Stat(string) (os.FileInfo, error)
  58. //Utils Functions
  59. VirtualPathToRealPath(string, string) (string, error)
  60. RealPathToVirtualPath(string, string) (string, error)
  61. FileExists(string) bool
  62. IsDir(string) bool
  63. Glob(string) ([]string, error)
  64. GetFileSize(string) int64
  65. GetModTime(string) (int64, error)
  66. WriteFile(string, []byte, os.FileMode) error
  67. ReadFile(string) ([]byte, error)
  68. WriteStream(string, io.Reader, os.FileMode) error
  69. ReadStream(string) (io.ReadCloser, error)
  70. Walk(string, filepath.WalkFunc) error
  71. }
  72. //System Handler for returing
  73. type FileSystemHandler struct {
  74. Name string
  75. UUID string
  76. Path string
  77. Hierarchy string
  78. HierarchyConfig HierarchySpecificConfig
  79. ReadOnly bool
  80. RequireBuffer bool //Set this to true if the fsh do not provide file header functions like Open() or Create(), require WriteStream() and ReadStream()
  81. Parentuid string
  82. InitiationTime int64
  83. FilesystemDatabase *db.Database
  84. FileSystemAbstraction FileSystemAbstraction
  85. Filesystem string
  86. Closed bool
  87. }
  88. //Create a list of file system handler from the given json content
  89. func NewFileSystemHandlersFromJSON(jsonContent []byte) ([]*FileSystemHandler, error) {
  90. //Generate a list of handler option from json file
  91. options, err := loadConfigFromJSON(jsonContent)
  92. if err != nil {
  93. return []*FileSystemHandler{}, err
  94. }
  95. resultingHandlers := []*FileSystemHandler{}
  96. for _, option := range options {
  97. thisHandler, err := NewFileSystemHandler(option)
  98. if err != nil {
  99. log.Println("Failed to create system handler for " + option.Name)
  100. log.Println(err.Error())
  101. continue
  102. }
  103. resultingHandlers = append(resultingHandlers, thisHandler)
  104. }
  105. return resultingHandlers, nil
  106. }
  107. //Create a new file system handler with the given config
  108. func NewFileSystemHandler(option FileSystemOption) (*FileSystemHandler, error) {
  109. fstype := strings.ToLower(option.Filesystem)
  110. if inSlice([]string{"ext4", "ext2", "ext3", "fat", "vfat", "ntfs"}, fstype) || fstype == "" {
  111. //Check if the target fs require mounting
  112. if option.Automount == true {
  113. err := MountDevice(option.Mountpt, option.Mountdev, option.Filesystem)
  114. if err != nil {
  115. return &FileSystemHandler{}, err
  116. }
  117. }
  118. //Check if the path exists
  119. if !fileExists(option.Path) {
  120. return &FileSystemHandler{}, errors.New("Mount point not exists!")
  121. }
  122. //Handle Hierarchy branching
  123. if option.Hierarchy == "user" {
  124. //Create user hierarchy for this virtual device
  125. os.MkdirAll(filepath.ToSlash(filepath.Clean(option.Path))+"/users", 0755)
  126. }
  127. //Create the fsdb for this handler
  128. var fsdb *db.Database = nil
  129. dbp, err := db.NewDatabase(filepath.ToSlash(filepath.Join(filepath.Clean(option.Path), "aofs.db")), false)
  130. if err != nil {
  131. if option.Access != "readonly" {
  132. log.Println("[Filesystem] Invalid config: Trying to mount a read only path as read-write mount point. Changing " + option.Name + " mount point to READONLY.")
  133. option.Access = "readonly"
  134. }
  135. } else {
  136. fsdb = dbp
  137. }
  138. rootpath := filepath.ToSlash(filepath.Clean(option.Path)) + "/"
  139. if option.Hierarchy == "backup" {
  140. //Backup disk. Create an Hierarchy Config for this drive
  141. hsConfig := hybridBackup.BackupTask{
  142. CycleCounter: 0,
  143. LastCycleTime: 0,
  144. DiskUID: option.Uuid,
  145. DiskPath: option.Path,
  146. ParentUID: option.Parentuid,
  147. Mode: option.BackupMode,
  148. DeleteFileMarkers: map[string]int64{},
  149. PanicStopped: false,
  150. }
  151. return &FileSystemHandler{
  152. Name: option.Name,
  153. UUID: option.Uuid,
  154. Path: rootpath,
  155. ReadOnly: option.Access == "readonly",
  156. RequireBuffer: false,
  157. Parentuid: option.Parentuid,
  158. Hierarchy: option.Hierarchy,
  159. HierarchyConfig: hsConfig,
  160. InitiationTime: time.Now().Unix(),
  161. FilesystemDatabase: fsdb,
  162. FileSystemAbstraction: localfs.NewLocalFileSystemAbstraction(option.Uuid, rootpath, option.Hierarchy, option.Access == "readonly"),
  163. Filesystem: fstype,
  164. Closed: false,
  165. }, nil
  166. } else {
  167. return &FileSystemHandler{
  168. Name: option.Name,
  169. UUID: option.Uuid,
  170. Path: filepath.ToSlash(filepath.Clean(option.Path)) + "/",
  171. ReadOnly: option.Access == "readonly",
  172. RequireBuffer: false,
  173. Parentuid: option.Parentuid,
  174. Hierarchy: option.Hierarchy,
  175. HierarchyConfig: DefaultEmptyHierarchySpecificConfig,
  176. InitiationTime: time.Now().Unix(),
  177. FilesystemDatabase: fsdb,
  178. FileSystemAbstraction: localfs.NewLocalFileSystemAbstraction(option.Uuid, rootpath, option.Hierarchy, option.Access == "readonly"),
  179. Filesystem: fstype,
  180. Closed: false,
  181. }, nil
  182. }
  183. } else if fstype == "webdav" {
  184. //WebDAV. Create an object and mount it
  185. root := option.Path
  186. user := option.Username
  187. password := option.Password
  188. webdavfs, err := webdavfs.NewWebDAVMount(option.Uuid, option.Hierarchy, root, user, password, "./tmp/webdavBuff")
  189. if err != nil {
  190. return nil, err
  191. }
  192. return &FileSystemHandler{
  193. Name: option.Name,
  194. UUID: option.Uuid,
  195. Path: "",
  196. ReadOnly: option.Access == "readonly",
  197. RequireBuffer: true,
  198. Parentuid: option.Parentuid,
  199. Hierarchy: option.Hierarchy,
  200. HierarchyConfig: nil,
  201. InitiationTime: time.Now().Unix(),
  202. FilesystemDatabase: nil,
  203. FileSystemAbstraction: webdavfs,
  204. Filesystem: fstype,
  205. Closed: false,
  206. }, nil
  207. } else if option.Filesystem == "virtual" {
  208. //Virtual filesystem, deprecated
  209. log.Println("Deprecated file system type: Virtual")
  210. }
  211. return nil, errors.New("Not supported file system: " + fstype)
  212. }
  213. //Check if a fsh is virtual (e.g. Network or fs Abstractions that cannot be listed with normal fs API)
  214. /*
  215. func (fsh *FileSystemHandler) IsVirtual() bool {
  216. if fsh.Hierarchy == "virtual" || fsh.Filesystem == "webdav" {
  217. //Check if the config return placeholder
  218. c, ok := fsh.HierarchyConfig.(EmptyHierarchySpecificConfig)
  219. if ok && c.HierarchyType == "placeholder" {
  220. //Real file system.
  221. return false
  222. }
  223. //Do more checking here if needed
  224. return true
  225. }
  226. return false
  227. }
  228. */
  229. func (fsh *FileSystemHandler) IsRootOf(vpath string) bool {
  230. return strings.HasPrefix(vpath, fsh.UUID+":")
  231. }
  232. func (fsh *FileSystemHandler) GetDirctorySizeFromRealPath(rpath string, includeHidden bool) (int64, int) {
  233. var size int64 = 0
  234. var fileCount int = 0
  235. err := fsh.FileSystemAbstraction.Walk(rpath, func(thisFilename string, info os.FileInfo, err error) error {
  236. if err != nil {
  237. return err
  238. }
  239. if !info.IsDir() {
  240. if includeHidden {
  241. //append all into the file count and size
  242. size += info.Size()
  243. fileCount++
  244. } else {
  245. //Check if this is hidden
  246. if !IsInsideHiddenFolder(thisFilename) {
  247. size += info.Size()
  248. fileCount++
  249. }
  250. }
  251. }
  252. return nil
  253. })
  254. if err != nil {
  255. return 0, fileCount
  256. }
  257. return size, fileCount
  258. }
  259. func (fsh *FileSystemHandler) GetDirctorySizeFromVpath(vpath string, username string, includeHidden bool) (int64, int) {
  260. realpath, _ := fsh.FileSystemAbstraction.VirtualPathToRealPath(vpath, username)
  261. return fsh.GetDirctorySizeFromRealPath(realpath, includeHidden)
  262. }
  263. /*
  264. File Record Related Functions
  265. fsh database that keep track of which files is owned by whom
  266. */
  267. //Create a file ownership record
  268. func (fsh *FileSystemHandler) CreateFileRecord(realpath string, owner string) error {
  269. if fsh.FilesystemDatabase == nil {
  270. //Not supported file system type
  271. return errors.New("Not supported filesystem type")
  272. }
  273. rpabs, _ := filepath.Abs(realpath)
  274. fsrabs, _ := filepath.Abs(fsh.Path)
  275. reldir, err := filepath.Rel(fsrabs, rpabs)
  276. if err != nil {
  277. return err
  278. }
  279. fsh.FilesystemDatabase.NewTable("owner")
  280. fsh.FilesystemDatabase.Write("owner", "owner/"+reldir, owner)
  281. return nil
  282. }
  283. //Read the owner of a file
  284. func (fsh *FileSystemHandler) GetFileRecord(realpath string) (string, error) {
  285. if fsh.FilesystemDatabase == nil {
  286. //Not supported file system type
  287. return "", errors.New("Not supported filesystem type")
  288. }
  289. rpabs, _ := filepath.Abs(realpath)
  290. fsrabs, _ := filepath.Abs(fsh.Path)
  291. reldir, err := filepath.Rel(fsrabs, rpabs)
  292. if err != nil {
  293. return "", err
  294. }
  295. fsh.FilesystemDatabase.NewTable("owner")
  296. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  297. owner := ""
  298. fsh.FilesystemDatabase.Read("owner", "owner/"+reldir, &owner)
  299. return owner, nil
  300. } else {
  301. return "", errors.New("Owner not exists")
  302. }
  303. }
  304. //Delete a file ownership record
  305. func (fsh *FileSystemHandler) DeleteFileRecord(realpath string) error {
  306. if fsh.FilesystemDatabase == nil {
  307. //Not supported file system type
  308. return errors.New("Not supported filesystem type")
  309. }
  310. rpabs, _ := filepath.Abs(realpath)
  311. fsrabs, _ := filepath.Abs(fsh.Path)
  312. reldir, err := filepath.Rel(fsrabs, rpabs)
  313. if err != nil {
  314. return err
  315. }
  316. fsh.FilesystemDatabase.NewTable("owner")
  317. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  318. fsh.FilesystemDatabase.Delete("owner", "owner/"+reldir)
  319. }
  320. return nil
  321. }
  322. //Close an openeded File System
  323. func (fsh *FileSystemHandler) Close() {
  324. //Close the fsh database
  325. if fsh.FilesystemDatabase != nil {
  326. fsh.FilesystemDatabase.Close()
  327. }
  328. }
  329. //Helper function
  330. func inSlice(slice []string, val string) bool {
  331. for _, item := range slice {
  332. if item == val {
  333. return true
  334. }
  335. }
  336. return false
  337. }
  338. func FileExists(filename string) bool {
  339. return fileExists(filename)
  340. }
  341. //Check if file exists
  342. func fileExists(filename string) bool {
  343. _, err := os.Stat(filename)
  344. if os.IsNotExist(err) {
  345. return false
  346. }
  347. return true
  348. }