filesystem.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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/filesystem/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.BackupConfig{
  97. CycleCounter: 0,
  98. LastCycleTime: time.Now().Unix(),
  99. DiskUID: option.Uuid,
  100. DiskPath: option.Path,
  101. ParentUID: option.Parentuid,
  102. Mode: option.BackupMode,
  103. DeleteFileMarkers: map[string]int64{},
  104. }
  105. }
  106. //Create the fsdb for this handler
  107. fsdb, err := db.NewDatabase(filepath.ToSlash(filepath.Join(filepath.Clean(option.Path), "aofs.db")), false)
  108. if err != nil {
  109. return &FileSystemHandler{}, errors.New("Unable to create fsdb inside the target path. Is the directory read only?")
  110. }
  111. return &FileSystemHandler{
  112. Name: option.Name,
  113. UUID: option.Uuid,
  114. Path: filepath.ToSlash(filepath.Clean(option.Path)) + "/",
  115. ReadOnly: option.Access == "readonly",
  116. Parentuid: option.Parentuid,
  117. Hierarchy: option.Hierarchy,
  118. HierarchyConfig: hierarchySpecificConfig,
  119. InitiationTime: time.Now().Unix(),
  120. FilesystemDatabase: fsdb,
  121. Filesystem: fstype,
  122. Closed: false,
  123. }, nil
  124. }
  125. return nil, errors.New("Not supported file system: " + fstype)
  126. }
  127. //Create a file ownership record
  128. func (fsh *FileSystemHandler) CreateFileRecord(realpath string, owner string) error {
  129. rpabs, _ := filepath.Abs(realpath)
  130. fsrabs, _ := filepath.Abs(fsh.Path)
  131. reldir, err := filepath.Rel(fsrabs, rpabs)
  132. if err != nil {
  133. return err
  134. }
  135. fsh.FilesystemDatabase.NewTable("owner")
  136. fsh.FilesystemDatabase.Write("owner", "owner/"+reldir, owner)
  137. return nil
  138. }
  139. //Read the owner of a file
  140. func (fsh *FileSystemHandler) GetFileRecord(realpath string) (string, error) {
  141. rpabs, _ := filepath.Abs(realpath)
  142. fsrabs, _ := filepath.Abs(fsh.Path)
  143. reldir, err := filepath.Rel(fsrabs, rpabs)
  144. if err != nil {
  145. return "", err
  146. }
  147. fsh.FilesystemDatabase.NewTable("owner")
  148. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  149. owner := ""
  150. fsh.FilesystemDatabase.Read("owner", "owner/"+reldir, &owner)
  151. return owner, nil
  152. } else {
  153. return "", errors.New("Owner not exists")
  154. }
  155. }
  156. //Delete a file ownership record
  157. func (fsh *FileSystemHandler) DeleteFileRecord(realpath string) error {
  158. rpabs, _ := filepath.Abs(realpath)
  159. fsrabs, _ := filepath.Abs(fsh.Path)
  160. reldir, err := filepath.Rel(fsrabs, rpabs)
  161. if err != nil {
  162. return err
  163. }
  164. fsh.FilesystemDatabase.NewTable("owner")
  165. if fsh.FilesystemDatabase.KeyExists("owner", "owner/"+reldir) {
  166. fsh.FilesystemDatabase.Delete("owner", "owner/"+reldir)
  167. }
  168. return nil
  169. }
  170. //Close an openeded File System
  171. func (fsh *FileSystemHandler) Close() {
  172. //Close the fsh database
  173. fsh.FilesystemDatabase.Close()
  174. }
  175. //Helper function
  176. func inSlice(slice []string, val string) bool {
  177. for _, item := range slice {
  178. if item == val {
  179. return true
  180. }
  181. }
  182. return false
  183. }
  184. func FileExists(filename string) bool {
  185. return fileExists(filename)
  186. }
  187. //Check if file exists
  188. func fileExists(filename string) bool {
  189. _, err := os.Stat(filename)
  190. if os.IsNotExist(err) {
  191. return false
  192. }
  193. return true
  194. }