filesystem.go 11 KB

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