filesystem.go 11 KB

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