basefs.go 12 KB

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