filesystem.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. fsdb, err := db.NewDatabase(filepath.ToSlash(filepath.Join(filepath.Clean(option.Path), "aofs.db")), false)
  109. if err != nil {
  110. return &FileSystemHandler{}, errors.New("Unable to create fsdb inside the target path. Is the directory read only?")
  111. }
  112. return &FileSystemHandler{
  113. Name: option.Name,
  114. UUID: option.Uuid,
  115. Path: filepath.ToSlash(filepath.Clean(option.Path)) + "/",
  116. ReadOnly: option.Access == "readonly",
  117. Parentuid: option.Parentuid,
  118. Hierarchy: option.Hierarchy,
  119. HierarchyConfig: hierarchySpecificConfig,
  120. InitiationTime: time.Now().Unix(),
  121. FilesystemDatabase: fsdb,
  122. Filesystem: fstype,
  123. Closed: false,
  124. }, nil
  125. } else if option.Filesystem == "virtual" {
  126. //Virtual filesystem, use custom mapping logic to handle file access
  127. if option.Hierarchy == "share" {
  128. //Emulated share virtual file system. Use Share Manager structure
  129. return &FileSystemHandler{
  130. Name: option.Name,
  131. UUID: option.Uuid,
  132. Path: "",
  133. ReadOnly: option.Access == "readonly",
  134. Parentuid: option.Parentuid,
  135. Hierarchy: option.Hierarchy,
  136. HierarchyConfig: nil,
  137. InitiationTime: time.Now().Unix(),
  138. FilesystemDatabase: nil,
  139. Filesystem: fstype,
  140. Closed: false,
  141. }, nil
  142. }
  143. }
  144. return nil, errors.New("Not supported file system: " + fstype)
  145. }
  146. //Create a file ownership record
  147. func (fsh *FileSystemHandler) CreateFileRecord(realpath string, owner string) error {
  148. rpabs, _ := filepath.Abs(realpath)
  149. fsrabs, _ := filepath.Abs(fsh.Path)
  150. reldir, err := filepath.Rel(fsrabs, rpabs)
  151. if err != nil {
  152. return err
  153. }
  154. fsh.FilesystemDatabase.NewTable("owner")
  155. fsh.FilesystemDatabase.Write("owner", "owner/"+reldir, owner)
  156. return nil
  157. }
  158. //Read the owner of a file
  159. func (fsh *FileSystemHandler) GetFileRecord(realpath string) (string, error) {
  160. rpabs, _ := filepath.Abs(realpath)
  161. fsrabs, _ := filepath.Abs(fsh.Path)
  162. reldir, err := filepath.Rel(fsrabs, rpabs)
  163. if err != nil {
  164. return "", err
  165. }
  166. fsh.FilesystemDatabase.NewTable("owner")
  167. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  168. owner := ""
  169. fsh.FilesystemDatabase.Read("owner", "owner/"+reldir, &owner)
  170. return owner, nil
  171. } else {
  172. return "", errors.New("Owner not exists")
  173. }
  174. }
  175. //Delete a file ownership record
  176. func (fsh *FileSystemHandler) DeleteFileRecord(realpath string) error {
  177. rpabs, _ := filepath.Abs(realpath)
  178. fsrabs, _ := filepath.Abs(fsh.Path)
  179. reldir, err := filepath.Rel(fsrabs, rpabs)
  180. if err != nil {
  181. return err
  182. }
  183. fsh.FilesystemDatabase.NewTable("owner")
  184. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  185. fsh.FilesystemDatabase.Delete("owner", "owner/"+reldir)
  186. }
  187. return nil
  188. }
  189. //Close an openeded File System
  190. func (fsh *FileSystemHandler) Close() {
  191. //Close the fsh database
  192. if fsh.FilesystemDatabase != nil {
  193. fsh.FilesystemDatabase.Close()
  194. }
  195. }
  196. //Helper function
  197. func inSlice(slice []string, val string) bool {
  198. for _, item := range slice {
  199. if item == val {
  200. return true
  201. }
  202. }
  203. return false
  204. }
  205. func FileExists(filename string) bool {
  206. return fileExists(filename)
  207. }
  208. //Check if file exists
  209. func fileExists(filename string) bool {
  210. _, err := os.Stat(filename)
  211. if os.IsNotExist(err) {
  212. return false
  213. }
  214. return true
  215. }