gdrivefs.go 15 KB

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