basefs.go 14 KB

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