gdrivefs.go 15 KB

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