gdrivefs.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // gdrivemount implements a google drive fuse driver
  2. package gdrivefs
  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("gdrivefs")
  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. // GDriveFS
  29. type GDriveFS struct {
  30. fuseutil.NotImplementedFileSystem // Defaults
  31. config *core.Config //core *core.Core // Core Config instead?
  32. client *drive.Service
  33. //root *FileEntry // hiearchy reference
  34. root *FileContainer
  35. fileHandles map[fuseops.HandleID]*Handle
  36. fileEntries map[fuseops.InodeID]*FileEntry
  37. nextRefresh time.Time
  38. handleMU *sync.Mutex
  39. //fileMap map[string]
  40. // Map IDS with FileEntries
  41. }
  42. func New(core *core.Core) core.Driver {
  43. fs := &GDriveFS{
  44. config: &core.Config,
  45. fileHandles: map[fuseops.HandleID]*Handle{},
  46. handleMU: &sync.Mutex{},
  47. }
  48. fs.initClient() // Init Oauth2 client
  49. fs.root = NewFileContainer(fs)
  50. fs.root.uid = core.Config.UID
  51. fs.root.gid = core.Config.GID
  52. //fs.root = rootEntry
  53. // Temporary entry
  54. entry := fs.root.tree.AppendGFile(&drive.File{Id: "0", Name: "Loading..."}, 999999)
  55. entry.Attr.Mode = os.FileMode(0)
  56. return fs
  57. }
  58. func (fs *GDriveFS) Start() {
  59. fs.timedRefresh() // start synching
  60. }
  61. ////////////////////////////////////////////////////////
  62. // TOOLS & HELPERS
  63. ////////////////////////////////////////////////////////
  64. func (fs *GDriveFS) createHandle() *Handle {
  65. // Lock here instead
  66. fs.handleMU.Lock()
  67. defer fs.handleMU.Unlock()
  68. var handleID fuseops.HandleID
  69. for handleID = 1; handleID < 99999; handleID++ {
  70. _, ok := fs.fileHandles[handleID]
  71. if !ok {
  72. break
  73. }
  74. }
  75. handle := &Handle{ID: handleID}
  76. fs.fileHandles[handleID] = handle
  77. return handle
  78. }
  79. func (fs *GDriveFS) timedRefresh() {
  80. go func() {
  81. for {
  82. if time.Now().After(fs.nextRefresh) {
  83. fs.Refresh()
  84. }
  85. time.Sleep(fs.config.RefreshTime) // 2 minutes
  86. }
  87. }()
  88. }
  89. // Refresh service files
  90. func (fs *GDriveFS) Refresh() {
  91. fs.nextRefresh = time.Now().Add(1 * time.Minute)
  92. fileList := []*drive.File{}
  93. fileMap := map[string]*drive.File{} // Temporary map by google drive fileID
  94. gdFields := googleapi.Field("nextPageToken, files(id,name,size,quotaBytesUsed, mimeType,parents,createdTime,modifiedTime)")
  95. log.Println("Loading file entries from gdrive")
  96. r, err := fs.client.Files.List().
  97. OrderBy("createdTime").
  98. PageSize(1000).
  99. SupportsTeamDrives(true).
  100. IncludeTeamDriveItems(true).
  101. Fields(gdFields).
  102. Do()
  103. if err != nil {
  104. // Sometimes gdrive returns error 500 randomly
  105. log.Println("GDrive ERR:", err)
  106. fs.Refresh() // retry
  107. return
  108. }
  109. fileList = append(fileList, r.Files...)
  110. // Rest of the pages
  111. for r.NextPageToken != "" {
  112. r, err = fs.client.Files.List().
  113. OrderBy("createdTime").
  114. PageToken(r.NextPageToken).
  115. Fields(gdFields).
  116. Do()
  117. if err != nil {
  118. log.Println("GDrive ERR:", err)
  119. fs.Refresh() // retry // Same as above
  120. return
  121. }
  122. fileList = append(fileList, r.Files...)
  123. }
  124. log.Println("Total entries:", len(fileList))
  125. // Cache ID for faster retrieval, might not be necessary
  126. for _, f := range fileList {
  127. fileMap[f.Id] = f
  128. }
  129. if err != nil || r == nil {
  130. log.Println("Unable to retrieve files", err)
  131. return
  132. }
  133. // Create clean fileList
  134. root := NewFileContainer(fs)
  135. // Helper func to recurse
  136. // Everything loaded we add to our entries
  137. // Add file and its parents priorizing it parent
  138. var appendFile func(df *drive.File)
  139. appendFile = func(df *drive.File) {
  140. for _, pID := range df.Parents {
  141. parentFile, ok := fileMap[pID]
  142. if !ok {
  143. parentFile, err = fs.client.Files.Get(pID).Do()
  144. if err != nil {
  145. panic(err)
  146. }
  147. fileMap[parentFile.Id] = parentFile
  148. }
  149. appendFile(parentFile) // Recurse
  150. }
  151. // Find existing entry
  152. var inode fuseops.InodeID
  153. entry := fs.root.FindByGID(df.Id)
  154. // Store for later add
  155. if entry == nil {
  156. inode = fs.root.FileEntry().Inode // Register new inode on Same Root fs
  157. //inode = root.FileEntry().Inode // This can be a problem if next time a existing inode comes? Allocate new file entry with new Inode
  158. } else {
  159. inode = entry.Inode // Reuse existing root fs inode
  160. }
  161. newEntry := root.tree.solveAppendGFile(df, inode) // Find right parent
  162. if entry != nil && entry.GFile.Name == df.Name { // Copy name from old entry
  163. newEntry.Name = entry.Name
  164. }
  165. // add File
  166. }
  167. for _, f := range fileList { // Ordered
  168. appendFile(f) // Check parent first
  169. }
  170. log.Println("Refresh done, update root")
  171. fs.root = root
  172. //fs.root.children = root.children
  173. log.Println("File count:", len(fs.root.fileEntries))
  174. }
  175. ///////////////////////////////
  176. // Fuse operations
  177. ////////////
  178. // OpenDir return nil error allows open dir
  179. func (fs *GDriveFS) OpenDir(ctx context.Context, op *fuseops.OpenDirOp) (err error) {
  180. entry := fs.root.FindByInode(op.Inode)
  181. if entry == nil {
  182. return fuse.ENOENT
  183. }
  184. handle := fs.createHandle()
  185. handle.entry = entry
  186. op.Handle = handle.ID
  187. return // No error allow, dir open
  188. }
  189. // ReadDir lists files into readdirop
  190. func (fs *GDriveFS) ReadDir(ctx context.Context, op *fuseops.ReadDirOp) (err error) {
  191. fh, ok := fs.fileHandles[op.Handle]
  192. if !ok {
  193. log.Fatal("Handle does not exists")
  194. }
  195. if op.Offset == 0 { // Rebuild/rewind dir list
  196. fh.entries = []fuseutil.Dirent{}
  197. for i, v := range fh.entry.children {
  198. fusetype := fuseutil.DT_File
  199. if v.IsDir() {
  200. fusetype = fuseutil.DT_Directory
  201. }
  202. dirEnt := fuseutil.Dirent{
  203. Inode: v.Inode,
  204. Name: v.Name,
  205. Type: fusetype,
  206. Offset: fuseops.DirOffset(i) + 1,
  207. }
  208. // written += fuseutil.WriteDirent(fh.buf[written:], dirEnt)
  209. fh.entries = append(fh.entries, dirEnt)
  210. }
  211. }
  212. index := int(op.Offset)
  213. if index > len(fh.entries) {
  214. return fuse.EINVAL
  215. }
  216. if index > 0 {
  217. index++
  218. }
  219. for i := index; i < len(fh.entries); i++ {
  220. n := fuseutil.WriteDirent(op.Dst[op.BytesRead:], fh.entries[i])
  221. //log.Println("Written:", n)
  222. if n == 0 {
  223. break
  224. }
  225. op.BytesRead += n
  226. }
  227. return
  228. }
  229. // SetInodeAttributes Not sure what attributes gdrive support we just leave this blank for now
  230. func (fs *GDriveFS) SetInodeAttributes(ctx context.Context, op *fuseops.SetInodeAttributesOp) (err error) {
  231. // Hack to truncate file?
  232. if op.Size != nil {
  233. f := fs.root.FindByInode(op.Inode)
  234. if *op.Size != 0 { // We only allow truncate to 0
  235. return fuse.ENOSYS
  236. }
  237. // Delete and create another on truncate 0
  238. err = fs.client.Files.Delete(f.GFile.Id).Do() // XXX: Careful on this
  239. createdFile, err := fs.client.Files.Create(&drive.File{Parents: f.GFile.Parents, Name: f.GFile.Name}).Do()
  240. if err != nil {
  241. return fuse.EINVAL
  242. }
  243. f.SetGFile(createdFile) // Set new file
  244. }
  245. return
  246. }
  247. //GetInodeAttributes return attributes
  248. func (fs *GDriveFS) GetInodeAttributes(ctx context.Context, op *fuseops.GetInodeAttributesOp) (err error) {
  249. f := fs.root.FindByInode(op.Inode)
  250. if f == nil {
  251. return fuse.ENOENT
  252. }
  253. op.Attributes = f.Attr
  254. op.AttributesExpiration = time.Now().Add(time.Minute)
  255. return
  256. }
  257. // ReleaseDirHandle deletes file handle entry
  258. func (fs *GDriveFS) ReleaseDirHandle(ctx context.Context, op *fuseops.ReleaseDirHandleOp) (err error) {
  259. delete(fs.fileHandles, op.Handle)
  260. return
  261. }
  262. // LookUpInode based on Parent and Name we return a self cached inode
  263. func (fs *GDriveFS) LookUpInode(ctx context.Context, op *fuseops.LookUpInodeOp) (err error) {
  264. parentFile := fs.root.FindByInode(op.Parent) // true means transverse all
  265. if parentFile == nil {
  266. return fuse.ENOENT
  267. }
  268. now := time.Now()
  269. // Transverse only local
  270. f := parentFile.FindByName(op.Name, false)
  271. if f == nil {
  272. return fuse.ENOENT
  273. }
  274. op.Entry = fuseops.ChildInodeEntry{
  275. Attributes: f.Attr,
  276. Child: f.Inode,
  277. AttributesExpiration: now.Add(time.Second),
  278. EntryExpiration: now.Add(time.Second),
  279. }
  280. return
  281. }
  282. // StatFS basically allows StatFS to run
  283. /*func (fs *GDriveFS) StatFS(ctx context.Context, op *fuseops.StatFSOp) (err error) {
  284. return
  285. }*/
  286. // ForgetInode allows to forgetInode
  287. func (fs *GDriveFS) ForgetInode(ctx context.Context, op *fuseops.ForgetInodeOp) (err error) {
  288. return
  289. }
  290. // GetXAttr special attributes
  291. func (fs *GDriveFS) GetXAttr(ctx context.Context, op *fuseops.GetXattrOp) (err error) {
  292. return
  293. }
  294. //////////////////////////////////////////////////////////////////////////
  295. // File OPS
  296. //////////////////////////////////////////////////////////////////////////
  297. // OpenFile creates a temporary handle to be handled on read or write
  298. func (fs *GDriveFS) OpenFile(ctx context.Context, op *fuseops.OpenFileOp) (err error) {
  299. f := fs.root.FindByInode(op.Inode) // might not exists
  300. // Generate new handle
  301. handle := fs.createHandle()
  302. handle.entry = f
  303. op.Handle = handle.ID
  304. op.UseDirectIO = true
  305. return
  306. }
  307. // ReadFile if the first time we download the google drive file into a local temporary file
  308. func (fs *GDriveFS) ReadFile(ctx context.Context, op *fuseops.ReadFileOp) (err error) {
  309. handle := fs.fileHandles[op.Handle]
  310. localFile := handle.entry.Cache()
  311. op.BytesRead, err = localFile.ReadAt(op.Dst, op.Offset)
  312. if err == io.EOF { // fuse does not expect a EOF
  313. err = nil
  314. }
  315. return
  316. }
  317. // CreateFile creates empty file in google Drive and returns its ID and attributes, only allows file creation on 'My Drive'
  318. func (fs *GDriveFS) CreateFile(ctx context.Context, op *fuseops.CreateFileOp) (err error) {
  319. parentFile := fs.root.FindByInode(op.Parent)
  320. if parentFile == nil {
  321. return fuse.ENOENT
  322. }
  323. // Only write on child folders
  324. if parentFile.Inode == fuseops.RootInodeID {
  325. return syscall.EPERM
  326. }
  327. existsFile := parentFile.FindByName(op.Name, false)
  328. if existsFile != nil {
  329. return fuse.EEXIST
  330. }
  331. newFile := &drive.File{
  332. Parents: []string{parentFile.GFile.Id},
  333. Name: op.Name,
  334. }
  335. createdFile, err := fs.client.Files.Create(newFile).Do()
  336. if err != nil {
  337. err = fuse.EINVAL
  338. return
  339. }
  340. // Temp
  341. entry := fs.root.FileEntry()
  342. entry = parentFile.AppendGFile(createdFile, entry.Inode) // Add new created file
  343. if entry == nil {
  344. err = fuse.EINVAL
  345. return
  346. }
  347. // Associate a temp file to a new handle
  348. // Local copy
  349. // Lock
  350. handle := fs.createHandle()
  351. handle.entry = entry
  352. handle.uploadOnDone = true
  353. //
  354. op.Handle = handle.ID
  355. op.Entry = fuseops.ChildInodeEntry{
  356. Attributes: entry.Attr,
  357. Child: entry.Inode,
  358. AttributesExpiration: time.Now().Add(time.Minute),
  359. EntryExpiration: time.Now().Add(time.Minute),
  360. }
  361. op.Mode = entry.Attr.Mode
  362. return
  363. }
  364. // WriteFile as ReadFile it creates a temporary file on first read
  365. // Maybe the ReadFile should be called here aswell to cache current contents since we are using writeAt
  366. func (fs *GDriveFS) WriteFile(ctx context.Context, op *fuseops.WriteFileOp) (err error) {
  367. handle, ok := fs.fileHandles[op.Handle]
  368. if !ok {
  369. return fuse.EIO
  370. }
  371. localFile := handle.entry.Cache()
  372. if localFile == nil {
  373. return fuse.EINVAL
  374. }
  375. _, err = localFile.WriteAt(op.Data, op.Offset)
  376. if err != nil {
  377. err = fuse.EIO
  378. return
  379. }
  380. handle.uploadOnDone = true
  381. return
  382. }
  383. // FlushFile just returns no error, maybe upload should be handled here
  384. func (fs *GDriveFS) FlushFile(ctx context.Context, op *fuseops.FlushFileOp) (err error) {
  385. handle, ok := fs.fileHandles[op.Handle]
  386. if !ok {
  387. return fuse.EIO
  388. }
  389. if handle.entry.tempFile == nil {
  390. return
  391. }
  392. if handle.uploadOnDone { // or if content changed basically
  393. err = handle.entry.Sync()
  394. if err != nil {
  395. return fuse.EINVAL
  396. }
  397. }
  398. return
  399. }
  400. // ReleaseFileHandle closes and deletes any temporary files, upload in case if changed locally
  401. func (fs *GDriveFS) ReleaseFileHandle(ctx context.Context, op *fuseops.ReleaseFileHandleOp) (err error) {
  402. handle := fs.fileHandles[op.Handle]
  403. handle.entry.ClearCache()
  404. delete(fs.fileHandles, op.Handle)
  405. return
  406. }
  407. // Unlink remove file and remove from local cache entry
  408. func (fs *GDriveFS) Unlink(ctx context.Context, op *fuseops.UnlinkOp) (err error) {
  409. parentEntry := fs.root.FindByInode(op.Parent)
  410. if parentEntry == nil {
  411. return fuse.ENOENT
  412. }
  413. if parentEntry.Inode == fuseops.RootInodeID {
  414. return syscall.EPERM
  415. }
  416. fileEntry := parentEntry.FindByName(op.Name, false)
  417. if fileEntry == nil {
  418. return fuse.ENOATTR
  419. }
  420. err = fs.client.Files.Delete(fileEntry.GFile.Id).Do()
  421. if err != nil {
  422. return fuse.EIO
  423. }
  424. fs.root.RemoveEntry(fileEntry)
  425. parentEntry.RemoveChild(fileEntry)
  426. return
  427. }
  428. // MkDir creates a directory on a parent dir
  429. func (fs *GDriveFS) MkDir(ctx context.Context, op *fuseops.MkDirOp) (err error) {
  430. parentFile := fs.root.FindByInode(op.Parent)
  431. if parentFile == nil {
  432. return fuse.ENOENT
  433. }
  434. if parentFile.Inode == fuseops.RootInodeID {
  435. return syscall.EPERM
  436. }
  437. // Should check existent first too
  438. fi, err := fs.client.Files.Create(&drive.File{
  439. Parents: []string{parentFile.GFile.Id},
  440. MimeType: "application/vnd.google-apps.folder",
  441. Name: op.Name,
  442. }).Do()
  443. if err != nil {
  444. return fuse.ENOATTR
  445. }
  446. entry := fs.root.FileEntry()
  447. entry = parentFile.AppendGFile(fi, entry.Inode)
  448. if entry == nil {
  449. return fuse.EINVAL
  450. }
  451. op.Entry = fuseops.ChildInodeEntry{
  452. Attributes: entry.Attr,
  453. Child: entry.Inode,
  454. AttributesExpiration: time.Now().Add(time.Minute),
  455. EntryExpiration: time.Now().Add(time.Microsecond),
  456. }
  457. return
  458. }
  459. // RmDir fuse implementation
  460. func (fs *GDriveFS) RmDir(ctx context.Context, op *fuseops.RmDirOp) (err error) {
  461. parentFile := fs.root.FindByInode(op.Parent)
  462. if parentFile == nil {
  463. return fuse.ENOENT
  464. }
  465. if parentFile.Inode == fuseops.RootInodeID {
  466. return syscall.EPERM
  467. }
  468. theFile := parentFile.FindByName(op.Name, false)
  469. err = fs.client.Files.Delete(theFile.GFile.Id).Do()
  470. if err != nil {
  471. return fuse.ENOTEMPTY
  472. }
  473. parentFile.RemoveChild(theFile)
  474. // Remove from entry somehow
  475. return
  476. }
  477. // Rename fuse implementation
  478. func (fs *GDriveFS) Rename(ctx context.Context, op *fuseops.RenameOp) (err error) {
  479. oldParentFile := fs.root.FindByInode(op.OldParent)
  480. if oldParentFile == nil {
  481. return fuse.ENOENT
  482. }
  483. newParentFile := fs.root.FindByInode(op.NewParent)
  484. if newParentFile == nil {
  485. return fuse.ENOENT
  486. }
  487. if oldParentFile.Inode == fuseops.RootInodeID || newParentFile.Inode == fuseops.RootInodeID {
  488. return syscall.EPERM
  489. }
  490. oldFile := oldParentFile.FindByName(op.OldName, false)
  491. // Although GDrive allows duplicate names, there is some issue with inode caching
  492. // So we prevent a rename to a file with same name
  493. existsFile := newParentFile.FindByName(op.NewName, false)
  494. if existsFile != nil {
  495. return fuse.EEXIST
  496. }
  497. ngFile := &drive.File{
  498. Name: op.NewName,
  499. }
  500. updateCall := fs.client.Files.Update(oldFile.GFile.Id, ngFile)
  501. if oldParentFile != newParentFile {
  502. updateCall.RemoveParents(oldParentFile.GFile.Id)
  503. updateCall.AddParents(newParentFile.GFile.Id)
  504. }
  505. updatedFile, err := updateCall.Do()
  506. oldParentFile.RemoveChild(oldFile)
  507. newParentFile.AppendGFile(updatedFile, oldFile.Inode)
  508. return
  509. }