filesystem.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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/sharefs"
  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 == "share" {
  209. shareFsAbstraction := sharefs.NewShareFileSystemAbstraction(
  210. "share",
  211. func(s string) (string, error) {
  212. log.Println(s)
  213. return "user:/", nil
  214. },
  215. )
  216. return &FileSystemHandler{
  217. Name: option.Name,
  218. UUID: option.Uuid,
  219. Path: "",
  220. ReadOnly: option.Access == "readonly",
  221. RequireBuffer: false,
  222. Parentuid: option.Parentuid,
  223. Hierarchy: option.Hierarchy,
  224. HierarchyConfig: nil,
  225. InitiationTime: time.Now().Unix(),
  226. FilesystemDatabase: nil,
  227. FileSystemAbstraction: shareFsAbstraction,
  228. Filesystem: fstype,
  229. Closed: false,
  230. }, nil
  231. } else if option.Filesystem == "virtual" {
  232. //Virtual filesystem, deprecated
  233. log.Println("Deprecated file system type: Virtual")
  234. }
  235. return nil, errors.New("Not supported file system: " + fstype)
  236. }
  237. //Check if a fsh is virtual (e.g. Network or fs Abstractions that cannot be listed with normal fs API)
  238. func (fsh *FileSystemHandler) IsVirtual() bool {
  239. if fsh.Hierarchy == "virtual" || fsh.Filesystem == "webdav" {
  240. //Check if the config return placeholder
  241. c, ok := fsh.HierarchyConfig.(EmptyHierarchySpecificConfig)
  242. if ok && c.HierarchyType == "placeholder" {
  243. //Real file system.
  244. return false
  245. }
  246. //Do more checking here if needed
  247. return true
  248. }
  249. return false
  250. }
  251. func (fsh *FileSystemHandler) IsRootOf(vpath string) bool {
  252. return strings.HasPrefix(vpath, fsh.UUID+":")
  253. }
  254. func (fsh *FileSystemHandler) GetDirctorySizeFromRealPath(rpath string, includeHidden bool) (int64, int) {
  255. var size int64 = 0
  256. var fileCount int = 0
  257. err := fsh.FileSystemAbstraction.Walk(rpath, func(thisFilename string, info os.FileInfo, err error) error {
  258. if err != nil {
  259. return err
  260. }
  261. if !info.IsDir() {
  262. if includeHidden {
  263. //append all into the file count and size
  264. size += info.Size()
  265. fileCount++
  266. } else {
  267. //Check if this is hidden
  268. if !IsInsideHiddenFolder(thisFilename) {
  269. size += info.Size()
  270. fileCount++
  271. }
  272. }
  273. }
  274. return nil
  275. })
  276. if err != nil {
  277. return 0, fileCount
  278. }
  279. return size, fileCount
  280. }
  281. func (fsh *FileSystemHandler) GetDirctorySizeFromVpath(vpath string, username string, includeHidden bool) (int64, int) {
  282. realpath, _ := fsh.FileSystemAbstraction.VirtualPathToRealPath(vpath, username)
  283. return fsh.GetDirctorySizeFromRealPath(realpath, includeHidden)
  284. }
  285. /*
  286. File Record Related Functions
  287. fsh database that keep track of which files is owned by whom
  288. */
  289. //Create a file ownership record
  290. func (fsh *FileSystemHandler) CreateFileRecord(realpath string, owner string) error {
  291. if fsh.FilesystemDatabase == nil {
  292. //Not supported file system type
  293. return errors.New("Not supported filesystem type")
  294. }
  295. rpabs, _ := filepath.Abs(realpath)
  296. fsrabs, _ := filepath.Abs(fsh.Path)
  297. reldir, err := filepath.Rel(fsrabs, rpabs)
  298. if err != nil {
  299. return err
  300. }
  301. fsh.FilesystemDatabase.NewTable("owner")
  302. fsh.FilesystemDatabase.Write("owner", "owner/"+reldir, owner)
  303. return nil
  304. }
  305. //Read the owner of a file
  306. func (fsh *FileSystemHandler) GetFileRecord(realpath string) (string, error) {
  307. if fsh.FilesystemDatabase == nil {
  308. //Not supported file system type
  309. return "", errors.New("Not supported filesystem type")
  310. }
  311. rpabs, _ := filepath.Abs(realpath)
  312. fsrabs, _ := filepath.Abs(fsh.Path)
  313. reldir, err := filepath.Rel(fsrabs, rpabs)
  314. if err != nil {
  315. return "", err
  316. }
  317. fsh.FilesystemDatabase.NewTable("owner")
  318. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  319. owner := ""
  320. fsh.FilesystemDatabase.Read("owner", "owner/"+reldir, &owner)
  321. return owner, nil
  322. } else {
  323. return "", errors.New("Owner not exists")
  324. }
  325. }
  326. //Delete a file ownership record
  327. func (fsh *FileSystemHandler) DeleteFileRecord(realpath string) error {
  328. if fsh.FilesystemDatabase == nil {
  329. //Not supported file system type
  330. return errors.New("Not supported filesystem type")
  331. }
  332. rpabs, _ := filepath.Abs(realpath)
  333. fsrabs, _ := filepath.Abs(fsh.Path)
  334. reldir, err := filepath.Rel(fsrabs, rpabs)
  335. if err != nil {
  336. return err
  337. }
  338. fsh.FilesystemDatabase.NewTable("owner")
  339. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  340. fsh.FilesystemDatabase.Delete("owner", "owner/"+reldir)
  341. }
  342. return nil
  343. }
  344. //Close an openeded File System
  345. func (fsh *FileSystemHandler) Close() {
  346. //Close the fsh database
  347. if fsh.FilesystemDatabase != nil {
  348. fsh.FilesystemDatabase.Close()
  349. }
  350. }
  351. //Helper function
  352. func inSlice(slice []string, val string) bool {
  353. for _, item := range slice {
  354. if item == val {
  355. return true
  356. }
  357. }
  358. return false
  359. }
  360. func FileExists(filename string) bool {
  361. return fileExists(filename)
  362. }
  363. //Check if file exists
  364. func fileExists(filename string) bool {
  365. _, err := os.Stat(filename)
  366. if os.IsNotExist(err) {
  367. return false
  368. }
  369. return true
  370. }