filesystem.go 12 KB

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