basefs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // basefs implements a google drive fuse driver
  2. package basefs
  3. import (
  4. "errors"
  5. "io"
  6. "math"
  7. "os"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "dev.hexasoftware.com/hxs/cloudmount/internal/core"
  12. "dev.hexasoftware.com/hxs/prettylog"
  13. "golang.org/x/net/context"
  14. "google.golang.org/api/googleapi"
  15. "github.com/jacobsa/fuse"
  16. "github.com/jacobsa/fuse/fuseops"
  17. "github.com/jacobsa/fuse/fuseutil"
  18. )
  19. const maxInodes = math.MaxUint64
  20. var (
  21. log = prettylog.New("basefs")
  22. // ErrNotImplemented basic Not implemented error
  23. ErrNotImplemented = errors.New("Not implemented")
  24. )
  25. type handle struct {
  26. ID fuseops.HandleID
  27. entry *FileEntry
  28. uploadOnDone bool
  29. // Handling for dir
  30. entries []fuseutil.Dirent
  31. }
  32. // BaseFS data
  33. type BaseFS struct {
  34. fuseutil.NotImplementedFileSystem // Defaults
  35. Config *core.Config //core *core.Core // Core Config instead?
  36. Root *FileContainer
  37. fileHandles map[fuseops.HandleID]*handle
  38. handleMU *sync.Mutex
  39. Service Service
  40. }
  41. // New Creates a new BaseFS with config based on core
  42. func New(core *core.Core) *BaseFS {
  43. fs := &BaseFS{
  44. Config: &core.Config,
  45. fileHandles: map[fuseops.HandleID]*handle{},
  46. handleMU: &sync.Mutex{},
  47. }
  48. fs.Root = NewFileContainer(fs)
  49. fs.Root.uid = core.Config.UID
  50. fs.Root.gid = core.Config.GID
  51. loadingFile := File{Name: "Loading...", ID: "0"}
  52. entry := fs.Root.FileEntry(&loadingFile, maxInodes) // Last inode
  53. entry.Attr.Mode = os.FileMode(0)
  54. return fs
  55. }
  56. // Refresh should be renamed to Load or something
  57. func (fs *BaseFS) Refresh() {
  58. // Try
  59. files, err := fs.Service.ListAll()
  60. if err == nil { // Do something repeat maybe?
  61. }
  62. root := NewFileContainer(fs)
  63. for _, file := range files {
  64. root.FileEntry(file) // Try to find in previous root
  65. }
  66. log.Println("File count:", root.Count())
  67. fs.Root = root
  68. }
  69. ////////////////////////////////////////////////////////
  70. // TOOLS & HELPERS
  71. ////////////////////////////////////////////////////////
  72. // COMMON
  73. func (fs *BaseFS) createHandle() *handle {
  74. // Lock here instead
  75. fs.handleMU.Lock()
  76. defer fs.handleMU.Unlock()
  77. var handleID fuseops.HandleID
  78. for handleID = 1; handleID < math.MaxUint64; handleID++ {
  79. _, ok := fs.fileHandles[handleID]
  80. if !ok {
  81. break
  82. }
  83. }
  84. h := &handle{ID: handleID}
  85. fs.fileHandles[handleID] = h
  86. return h
  87. }
  88. // Client is still here
  89. const fileFields = googleapi.Field("id, name, size,mimeType, parents,createdTime,modifiedTime")
  90. const gdFields = googleapi.Field("files(" + fileFields + ")")
  91. ///////////////////////////////
  92. // Fuse operations
  93. ////////////
  94. // OpenDir return nil error allows open dir
  95. // COMMON for drivers
  96. func (fs *BaseFS) OpenDir(ctx context.Context, op *fuseops.OpenDirOp) (err error) {
  97. entry := fs.Root.FindByInode(op.Inode)
  98. if entry == nil {
  99. return fuse.ENOENT
  100. }
  101. handle := fs.createHandle()
  102. handle.entry = entry
  103. op.Handle = handle.ID
  104. return // No error allow, dir open
  105. }
  106. // ReadDir lists files into readdirop
  107. // Common for drivers
  108. func (fs *BaseFS) ReadDir(ctx context.Context, op *fuseops.ReadDirOp) (err error) {
  109. fh, ok := fs.fileHandles[op.Handle]
  110. if !ok {
  111. log.Fatal("Handle does not exists")
  112. }
  113. if op.Offset == 0 { // Rebuild/rewind dir list
  114. fh.entries = []fuseutil.Dirent{}
  115. children := fs.Root.ListByParent(fh.entry)
  116. for i, v := range children {
  117. fusetype := fuseutil.DT_File
  118. if v.IsDir() {
  119. fusetype = fuseutil.DT_Directory
  120. }
  121. dirEnt := fuseutil.Dirent{
  122. Inode: v.Inode,
  123. Name: v.Name,
  124. Type: fusetype,
  125. Offset: fuseops.DirOffset(i) + 1,
  126. }
  127. // written += fuseutil.WriteDirent(fh.buf[written:], dirEnt)
  128. fh.entries = append(fh.entries, dirEnt)
  129. }
  130. }
  131. index := int(op.Offset)
  132. if index > len(fh.entries) {
  133. return fuse.EINVAL
  134. }
  135. if index > 0 {
  136. index++
  137. }
  138. for i := index; i < len(fh.entries); i++ {
  139. n := fuseutil.WriteDirent(op.Dst[op.BytesRead:], fh.entries[i])
  140. if n == 0 {
  141. break
  142. }
  143. op.BytesRead += n
  144. }
  145. return
  146. }
  147. // SetInodeAttributes Not sure what attributes gdrive support we just leave this blank for now
  148. // SPECIFIC code
  149. func (fs *BaseFS) SetInodeAttributes(ctx context.Context, op *fuseops.SetInodeAttributesOp) (err error) {
  150. // Hack to truncate file?
  151. if op.Size != nil {
  152. entry := fs.Root.FindByInode(op.Inode)
  153. if *op.Size != 0 { // We only allow truncate to 0
  154. return fuse.ENOSYS
  155. }
  156. err = fs.Root.Truncate(entry)
  157. }
  158. return
  159. }
  160. //GetInodeAttributes return attributes
  161. // COMMON
  162. func (fs *BaseFS) GetInodeAttributes(ctx context.Context, op *fuseops.GetInodeAttributesOp) (err error) {
  163. f := fs.Root.FindByInode(op.Inode)
  164. if f == nil {
  165. return fuse.ENOENT
  166. }
  167. op.Attributes = f.Attr
  168. op.AttributesExpiration = time.Now().Add(time.Minute)
  169. return
  170. }
  171. // ReleaseDirHandle deletes file handle entry
  172. // COMMON
  173. func (fs *BaseFS) ReleaseDirHandle(ctx context.Context, op *fuseops.ReleaseDirHandleOp) (err error) {
  174. delete(fs.fileHandles, op.Handle)
  175. return
  176. }
  177. // LookUpInode based on Parent and Name we return a self cached inode
  178. // Cloud be COMMON but has specific ID
  179. func (fs *BaseFS) LookUpInode(ctx context.Context, op *fuseops.LookUpInodeOp) (err error) {
  180. parentFile := fs.Root.FindByInode(op.Parent) // true means transverse all
  181. if parentFile == nil {
  182. return fuse.ENOENT
  183. }
  184. entry := fs.Root.Lookup(parentFile, op.Name)
  185. if entry == nil {
  186. return fuse.ENOENT
  187. }
  188. // Transverse only local
  189. now := time.Now()
  190. op.Entry = fuseops.ChildInodeEntry{
  191. Attributes: entry.Attr,
  192. Child: entry.Inode,
  193. AttributesExpiration: now.Add(time.Second),
  194. EntryExpiration: now.Add(time.Second),
  195. }
  196. return
  197. }
  198. // StatFS basically allows StatFS to run
  199. /*func (fs *BaseFS) StatFS(ctx context.Context, op *fuseops.StatFSOp) (err error) {
  200. return
  201. }*/
  202. // ForgetInode allows to forgetInode
  203. // COMMON
  204. func (fs *BaseFS) ForgetInode(ctx context.Context, op *fuseops.ForgetInodeOp) (err error) {
  205. return
  206. }
  207. // GetXAttr special attributes
  208. // COMMON
  209. func (fs *BaseFS) GetXAttr(ctx context.Context, op *fuseops.GetXattrOp) (err error) {
  210. return
  211. }
  212. //////////////////////////////////////////////////////////////////////////
  213. // File OPS
  214. //////////////////////////////////////////////////////////////////////////
  215. // OpenFile creates a temporary handle to be handled on read or write
  216. // COMMON
  217. func (fs *BaseFS) OpenFile(ctx context.Context, op *fuseops.OpenFileOp) (err error) {
  218. f := fs.Root.FindByInode(op.Inode) // might not exists
  219. // Generate new handle
  220. handle := fs.createHandle()
  221. handle.entry = f
  222. op.Handle = handle.ID
  223. op.UseDirectIO = true
  224. return
  225. }
  226. // ReadFile if the first time we download the google drive file into a local temporary file
  227. // COMMON but specific in cache
  228. func (fs *BaseFS) ReadFile(ctx context.Context, op *fuseops.ReadFileOp) (err error) {
  229. handle := fs.fileHandles[op.Handle]
  230. localFile := fs.Root.Cache(handle.entry)
  231. op.BytesRead, err = localFile.ReadAt(op.Dst, op.Offset)
  232. if err == io.EOF { // fuse does not expect a EOF
  233. err = nil
  234. }
  235. return
  236. }
  237. // CreateFile creates empty file in google Drive and returns its ID and attributes, only allows file creation on 'My Drive'
  238. // Cloud SPECIFIC
  239. func (fs *BaseFS) CreateFile(ctx context.Context, op *fuseops.CreateFileOp) (err error) {
  240. parentFile := fs.Root.FindByInode(op.Parent)
  241. if parentFile == nil {
  242. return fuse.ENOENT
  243. }
  244. // Only write on child folders
  245. if parentFile == fs.Root.FileEntries[fuseops.RootInodeID] {
  246. return syscall.EPERM
  247. }
  248. existsFile := fs.Root.Lookup(parentFile, op.Name)
  249. //existsFile := parentFile.FindByName(op.Name, false)
  250. if existsFile != nil {
  251. return fuse.EEXIST
  252. }
  253. // Parent entry/Name
  254. entry, err := fs.Root.CreateFile(parentFile, op.Name, false)
  255. if err != nil {
  256. return err
  257. }
  258. // Associate a temp file to a new handle
  259. // Local copy
  260. // Lock
  261. handle := fs.createHandle()
  262. handle.entry = entry
  263. handle.uploadOnDone = true
  264. //
  265. op.Handle = handle.ID
  266. op.Entry = fuseops.ChildInodeEntry{
  267. Attributes: entry.Attr,
  268. Child: entry.Inode,
  269. AttributesExpiration: time.Now().Add(time.Minute),
  270. EntryExpiration: time.Now().Add(time.Minute),
  271. }
  272. op.Mode = entry.Attr.Mode
  273. return
  274. }
  275. // WriteFile as ReadFile it creates a temporary file on first read
  276. // Maybe the ReadFile should be called here aswell to cache current contents since we are using writeAt
  277. // CLOUD SPECIFIC
  278. func (fs *BaseFS) WriteFile(ctx context.Context, op *fuseops.WriteFileOp) (err error) {
  279. handle, ok := fs.fileHandles[op.Handle]
  280. if !ok {
  281. return fuse.EIO
  282. }
  283. localFile := fs.Root.Cache(handle.entry)
  284. if localFile == nil {
  285. return fuse.EINVAL
  286. }
  287. _, err = localFile.WriteAt(op.Data, op.Offset)
  288. if err != nil {
  289. err = fuse.EIO
  290. return
  291. }
  292. handle.uploadOnDone = true
  293. return
  294. }
  295. // FlushFile just returns no error, maybe upload should be handled here
  296. // COMMON
  297. func (fs *BaseFS) FlushFile(ctx context.Context, op *fuseops.FlushFileOp) (err error) {
  298. handle, ok := fs.fileHandles[op.Handle]
  299. if !ok {
  300. return fuse.EIO
  301. }
  302. if handle.entry.tempFile == nil {
  303. return
  304. }
  305. if handle.uploadOnDone { // or if content changed basically
  306. err = fs.Root.Sync(handle.entry)
  307. if err != nil {
  308. return fuse.EINVAL
  309. }
  310. }
  311. return
  312. }
  313. // ReleaseFileHandle closes and deletes any temporary files, upload in case if changed locally
  314. // COMMON
  315. func (fs *BaseFS) ReleaseFileHandle(ctx context.Context, op *fuseops.ReleaseFileHandleOp) (err error) {
  316. handle := fs.fileHandles[op.Handle]
  317. fs.Root.ClearCache(handle.entry)
  318. delete(fs.fileHandles, op.Handle)
  319. return
  320. }
  321. // Unlink remove file and remove from local cache entry
  322. // SPECIFIC
  323. func (fs *BaseFS) Unlink(ctx context.Context, op *fuseops.UnlinkOp) (err error) {
  324. if op.Parent == fuseops.RootInodeID {
  325. return syscall.EPERM
  326. }
  327. parentEntry := fs.Root.FindByInode(op.Parent)
  328. if parentEntry == nil {
  329. return fuse.ENOENT
  330. }
  331. fileEntry := fs.Root.Lookup(parentEntry, op.Name)
  332. //fileEntry := parentEntry.FindByName(op.Name, false)
  333. if fileEntry == nil {
  334. return fuse.ENOATTR
  335. }
  336. return fs.Root.DeleteFile(fileEntry)
  337. }
  338. // MkDir creates a directory on a parent dir
  339. func (fs *BaseFS) MkDir(ctx context.Context, op *fuseops.MkDirOp) (err error) {
  340. if op.Parent == fuseops.RootInodeID {
  341. return syscall.EPERM
  342. }
  343. parentFile := fs.Root.FindByInode(op.Parent)
  344. if parentFile == nil {
  345. return fuse.ENOENT
  346. }
  347. entry, err := fs.Root.CreateFile(parentFile, op.Name, true)
  348. if err != nil {
  349. return err
  350. }
  351. op.Entry = fuseops.ChildInodeEntry{
  352. Attributes: entry.Attr,
  353. Child: entry.Inode,
  354. AttributesExpiration: time.Now().Add(time.Minute),
  355. EntryExpiration: time.Now().Add(time.Microsecond),
  356. }
  357. return
  358. }
  359. // RmDir fuse implementation
  360. func (fs *BaseFS) RmDir(ctx context.Context, op *fuseops.RmDirOp) (err error) {
  361. if op.Parent == fuseops.RootInodeID {
  362. return syscall.EPERM
  363. }
  364. parentFile := fs.Root.FindByInode(op.Parent)
  365. if parentFile == nil {
  366. return fuse.ENOENT
  367. }
  368. theFile := fs.Root.Lookup(parentFile, op.Name)
  369. err = fs.Root.DeleteFile(theFile)
  370. if err != nil {
  371. return fuse.ENOTEMPTY
  372. }
  373. return
  374. }
  375. // Rename fuse implementation
  376. func (fs *BaseFS) Rename(ctx context.Context, op *fuseops.RenameOp) (err error) {
  377. if op.OldParent == fuseops.RootInodeID || op.NewParent == fuseops.RootInodeID {
  378. return syscall.EPERM
  379. }
  380. oldParentFile := fs.Root.FindByInode(op.OldParent)
  381. if oldParentFile == nil {
  382. return fuse.ENOENT
  383. }
  384. newParentFile := fs.Root.FindByInode(op.NewParent)
  385. if newParentFile == nil {
  386. return fuse.ENOENT
  387. }
  388. //oldFile := oldParentFile.FindByName(op.OldName, false)
  389. oldEntry := fs.Root.Lookup(oldParentFile, op.OldName)
  390. // Although GDrive allows duplicate names, there is some issue with inode caching
  391. // So we prevent a rename to a file with same name
  392. //existsFile := newParentFile.FindByName(op.NewName, false)
  393. existsEntry := fs.Root.Lookup(newParentFile, op.NewName)
  394. if existsEntry != nil {
  395. return fuse.EEXIST
  396. }
  397. nFile, err := fs.Service.Move(oldEntry.File, newParentFile.File, op.NewName)
  398. if err != nil {
  399. return fuse.EINVAL
  400. }
  401. //oldEntry.SetFile(nFile, fs.Config.UID, fs.Config.GID)
  402. // Why remove and add instead of setting file, is just in case we have an existing name FileEntry solves the name adding duplicates helpers
  403. fs.Root.RemoveEntry(oldEntry)
  404. fs.Root.FileEntry(nFile, oldEntry.Inode) // Use this same inode
  405. //oldParentFile.RemoveChild(oldFile)
  406. //newParentFile.AppendGFile(updatedFile, oldFile.Inode)
  407. return
  408. }