filesystem.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "log"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "time"
  17. db "imuslab.com/arozos/mod/database"
  18. "imuslab.com/arozos/mod/disk/hybridBackup"
  19. )
  20. //Options for creating new file system handler
  21. /*
  22. type FileSystemOpeningOptions struct{
  23. Name string `json:"name"` //Display name of this device
  24. Uuid string `json:"uuid"` //UUID of this device, e.g. S1
  25. Path string `json:"path"` //Path for the storage root
  26. Access string `json:"access,omitempty"` //Access right, allow {readonly, readwrite}
  27. Hierarchy string `json:"hierarchy"` //Folder hierarchy, allow {public, user}
  28. Automount bool `json:"automount"` //Automount this device if exists
  29. Filesystem string `json:"filesystem,omitempty"` //Support {"ext4","ext2", "ext3", "fat", "vfat", "ntfs"}
  30. Mountdev string `json:"mountdev,omitempty"` //Device file (e.g. /dev/sda1)
  31. Mountpt string `json:"mountpt,omitempty"` //Device mount point (e.g. /media/storage1)
  32. }
  33. */
  34. /*
  35. An interface for storing data related to a specific hierarchy settings.
  36. Example like the account information of network drive,
  37. backup mode of backup drive etc
  38. */
  39. type HierarchySpecificConfig interface{}
  40. //System Handler for returing
  41. type FileSystemHandler struct {
  42. Name string
  43. UUID string
  44. Path string
  45. Hierarchy string
  46. HierarchyConfig HierarchySpecificConfig
  47. ReadOnly bool
  48. Parentuid string
  49. InitiationTime int64
  50. FilesystemDatabase *db.Database
  51. Filesystem string
  52. Closed bool
  53. }
  54. //Create a list of file system handler from the given json content
  55. func NewFileSystemHandlersFromJSON(jsonContent []byte) ([]*FileSystemHandler, error) {
  56. //Generate a list of handler option from json file
  57. options, err := loadConfigFromJSON(jsonContent)
  58. if err != nil {
  59. return []*FileSystemHandler{}, err
  60. }
  61. resultingHandlers := []*FileSystemHandler{}
  62. for _, option := range options {
  63. thisHandler, err := NewFileSystemHandler(option)
  64. if err != nil {
  65. log.Println("Failed to create system handler for " + option.Name)
  66. log.Println(err.Error())
  67. continue
  68. }
  69. resultingHandlers = append(resultingHandlers, thisHandler)
  70. }
  71. return resultingHandlers, nil
  72. }
  73. //Create a new file system handler with the given config
  74. func NewFileSystemHandler(option FileSystemOption) (*FileSystemHandler, error) {
  75. fstype := strings.ToLower(option.Filesystem)
  76. if inSlice([]string{"ext4", "ext2", "ext3", "fat", "vfat", "ntfs"}, fstype) || fstype == "" {
  77. //Check if the target fs require mounting
  78. if option.Automount == true {
  79. err := MountDevice(option.Mountpt, option.Mountdev, option.Filesystem)
  80. if err != nil {
  81. return &FileSystemHandler{}, err
  82. }
  83. }
  84. //Check if the path exists
  85. if !fileExists(option.Path) {
  86. return &FileSystemHandler{}, errors.New("Mount point not exists!")
  87. }
  88. //Handle Hierarchy branching
  89. var hierarchySpecificConfig interface{} = nil
  90. if option.Hierarchy == "user" {
  91. //Create user hierarchy for this virtual device
  92. os.MkdirAll(filepath.ToSlash(filepath.Clean(option.Path))+"/users", 0755)
  93. }
  94. if option.Hierarchy == "backup" {
  95. //Backup disk. Create an Hierarchy Config for this drive
  96. hierarchySpecificConfig = hybridBackup.BackupTask{
  97. CycleCounter: 0,
  98. LastCycleTime: 0,
  99. DiskUID: option.Uuid,
  100. DiskPath: option.Path,
  101. ParentUID: option.Parentuid,
  102. Mode: option.BackupMode,
  103. DeleteFileMarkers: map[string]int64{},
  104. PanicStopped: false,
  105. }
  106. }
  107. //Create the fsdb for this handler
  108. var fsdb *db.Database = nil
  109. if option.Access != "readonly" {
  110. dbp, err := db.NewDatabase(filepath.ToSlash(filepath.Join(filepath.Clean(option.Path), "aofs.db")), false)
  111. if err != nil {
  112. return &FileSystemHandler{}, errors.New("Unable to create fsdb inside the target path. Is the directory read only?")
  113. }
  114. fsdb = dbp
  115. }
  116. return &FileSystemHandler{
  117. Name: option.Name,
  118. UUID: option.Uuid,
  119. Path: filepath.ToSlash(filepath.Clean(option.Path)) + "/",
  120. ReadOnly: option.Access == "readonly",
  121. Parentuid: option.Parentuid,
  122. Hierarchy: option.Hierarchy,
  123. HierarchyConfig: hierarchySpecificConfig,
  124. InitiationTime: time.Now().Unix(),
  125. FilesystemDatabase: fsdb,
  126. Filesystem: fstype,
  127. Closed: false,
  128. }, nil
  129. } else if option.Filesystem == "virtual" {
  130. //Virtual filesystem, use custom mapping logic to handle file access
  131. if option.Hierarchy == "share" {
  132. //Emulated share virtual file system. Use Share Manager structure
  133. return &FileSystemHandler{
  134. Name: option.Name,
  135. UUID: option.Uuid,
  136. Path: "",
  137. ReadOnly: option.Access == "readonly",
  138. Parentuid: option.Parentuid,
  139. Hierarchy: option.Hierarchy,
  140. HierarchyConfig: nil,
  141. InitiationTime: time.Now().Unix(),
  142. FilesystemDatabase: nil,
  143. Filesystem: fstype,
  144. Closed: false,
  145. }, nil
  146. }
  147. }
  148. return nil, errors.New("Not supported file system: " + fstype)
  149. }
  150. //Create a file ownership record
  151. func (fsh *FileSystemHandler) CreateFileRecord(realpath string, owner string) error {
  152. if fsh.FilesystemDatabase == nil {
  153. //Not supported file system type
  154. return errors.New("Not supported filesystem type")
  155. }
  156. rpabs, _ := filepath.Abs(realpath)
  157. fsrabs, _ := filepath.Abs(fsh.Path)
  158. reldir, err := filepath.Rel(fsrabs, rpabs)
  159. if err != nil {
  160. return err
  161. }
  162. fsh.FilesystemDatabase.NewTable("owner")
  163. fsh.FilesystemDatabase.Write("owner", "owner/"+reldir, owner)
  164. return nil
  165. }
  166. //Read the owner of a file
  167. func (fsh *FileSystemHandler) GetFileRecord(realpath string) (string, error) {
  168. if fsh.FilesystemDatabase == nil {
  169. //Not supported file system type
  170. return "", errors.New("Not supported filesystem type")
  171. }
  172. rpabs, _ := filepath.Abs(realpath)
  173. fsrabs, _ := filepath.Abs(fsh.Path)
  174. reldir, err := filepath.Rel(fsrabs, rpabs)
  175. if err != nil {
  176. return "", err
  177. }
  178. fsh.FilesystemDatabase.NewTable("owner")
  179. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  180. owner := ""
  181. fsh.FilesystemDatabase.Read("owner", "owner/"+reldir, &owner)
  182. return owner, nil
  183. } else {
  184. return "", errors.New("Owner not exists")
  185. }
  186. }
  187. //Delete a file ownership record
  188. func (fsh *FileSystemHandler) DeleteFileRecord(realpath string) error {
  189. if fsh.FilesystemDatabase == nil {
  190. //Not supported file system type
  191. return errors.New("Not supported filesystem type")
  192. }
  193. rpabs, _ := filepath.Abs(realpath)
  194. fsrabs, _ := filepath.Abs(fsh.Path)
  195. reldir, err := filepath.Rel(fsrabs, rpabs)
  196. if err != nil {
  197. return err
  198. }
  199. fsh.FilesystemDatabase.NewTable("owner")
  200. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  201. fsh.FilesystemDatabase.Delete("owner", "owner/"+reldir)
  202. }
  203. return nil
  204. }
  205. //Close an openeded File System
  206. func (fsh *FileSystemHandler) Close() {
  207. //Close the fsh database
  208. if fsh.FilesystemDatabase != nil {
  209. fsh.FilesystemDatabase.Close()
  210. }
  211. }
  212. //Helper function
  213. func inSlice(slice []string, val string) bool {
  214. for _, item := range slice {
  215. if item == val {
  216. return true
  217. }
  218. }
  219. return false
  220. }
  221. func FileExists(filename string) bool {
  222. return fileExists(filename)
  223. }
  224. //Check if file exists
  225. func fileExists(filename string) bool {
  226. _, err := os.Stat(filename)
  227. if os.IsNotExist(err) {
  228. return false
  229. }
  230. return true
  231. }