filesystem.go 12 KB

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