basefs.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. // basefs implements a google drive fuse driver
  2. package basefs
  3. import (
  4. "errors"
  5. "io"
  6. "io/ioutil"
  7. glog "log"
  8. "math"
  9. "os"
  10. "sync"
  11. "syscall"
  12. "time"
  13. "dev.hexasoftware.com/hxs/cloudmount/internal/core"
  14. "dev.hexasoftware.com/hxs/prettylog"
  15. "golang.org/x/net/context"
  16. "google.golang.org/api/googleapi"
  17. "github.com/jacobsa/fuse"
  18. "github.com/jacobsa/fuse/fuseops"
  19. "github.com/jacobsa/fuse/fuseutil"
  20. )
  21. const maxInodes = math.MaxUint64
  22. var (
  23. log = glog.New(ioutil.Discard, "", 0)
  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("basefs")
  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 = core.Config.UID
  57. fs.Root.gid = core.Config.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.UID, fs.Config.GID)
  104. } else {
  105. //Create new one
  106. fs.Root.FileEntry(c.File) // Creating new one
  107. }
  108. }
  109. }
  110. ////////////////////////////////////////////////////////
  111. // TOOLS & HELPERS
  112. ////////////////////////////////////////////////////////
  113. // COMMON
  114. func (fs *BaseFS) createHandle() *handle {
  115. // Lock here instead
  116. fs.handleMU.Lock()
  117. defer fs.handleMU.Unlock()
  118. var handleID fuseops.HandleID
  119. for handleID = 1; handleID < math.MaxUint64; handleID++ {
  120. _, ok := fs.fileHandles[handleID]
  121. if !ok {
  122. break
  123. }
  124. }
  125. h := &handle{ID: handleID}
  126. fs.fileHandles[handleID] = h
  127. return h
  128. }
  129. // Client is still here
  130. const fileFields = googleapi.Field("id, name, size,mimeType, parents,createdTime,modifiedTime")
  131. const gdFields = googleapi.Field("files(" + fileFields + ")")
  132. ///////////////////////////////
  133. // Fuse operations
  134. ////////////
  135. // OpenDir return nil error allows open dir
  136. // COMMON for drivers
  137. func (fs *BaseFS) OpenDir(ctx context.Context, op *fuseops.OpenDirOp) (err error) {
  138. entry := fs.Root.FindByInode(op.Inode)
  139. if entry == nil {
  140. return fuse.ENOENT
  141. }
  142. handle := fs.createHandle()
  143. handle.entry = entry
  144. op.Handle = handle.ID
  145. return // No error allow, dir open
  146. }
  147. // ReadDir lists files into readdirop
  148. // Common for drivers
  149. func (fs *BaseFS) ReadDir(ctx context.Context, op *fuseops.ReadDirOp) (err error) {
  150. fh, ok := fs.fileHandles[op.Handle]
  151. if !ok {
  152. log.Fatal("Handle does not exists")
  153. }
  154. if op.Offset == 0 { // Rebuild/rewind dir list
  155. fh.entries = []fuseutil.Dirent{}
  156. children := fs.Root.ListByParent(fh.entry)
  157. for i, v := range children {
  158. fusetype := fuseutil.DT_File
  159. if v.IsDir() {
  160. fusetype = fuseutil.DT_Directory
  161. }
  162. dirEnt := fuseutil.Dirent{
  163. Inode: v.Inode,
  164. Name: v.Name,
  165. Type: fusetype,
  166. Offset: fuseops.DirOffset(i) + 1,
  167. }
  168. // written += fuseutil.WriteDirent(fh.buf[written:], dirEnt)
  169. fh.entries = append(fh.entries, dirEnt)
  170. }
  171. }
  172. index := int(op.Offset)
  173. if index > len(fh.entries) {
  174. return fuse.EINVAL
  175. }
  176. if index > 0 {
  177. index++
  178. }
  179. for i := index; i < len(fh.entries); i++ {
  180. n := fuseutil.WriteDirent(op.Dst[op.BytesRead:], fh.entries[i])
  181. if n == 0 {
  182. break
  183. }
  184. op.BytesRead += n
  185. }
  186. return
  187. }
  188. // SetInodeAttributes Not sure what attributes gdrive support we just leave this blank for now
  189. // SPECIFIC code
  190. func (fs *BaseFS) SetInodeAttributes(ctx context.Context, op *fuseops.SetInodeAttributesOp) (err error) {
  191. // Hack to truncate file?
  192. if op.Size != nil {
  193. entry := fs.Root.FindByInode(op.Inode)
  194. if *op.Size != 0 { // We only allow truncate to 0
  195. return fuse.ENOSYS
  196. }
  197. err = fs.Root.Truncate(entry)
  198. }
  199. return
  200. }
  201. //GetInodeAttributes return attributes
  202. // COMMON
  203. func (fs *BaseFS) GetInodeAttributes(ctx context.Context, op *fuseops.GetInodeAttributesOp) (err error) {
  204. f := fs.Root.FindByInode(op.Inode)
  205. if f == nil {
  206. return fuse.ENOENT
  207. }
  208. op.Attributes = f.Attr
  209. op.AttributesExpiration = time.Now().Add(time.Minute)
  210. return
  211. }
  212. // ReleaseDirHandle deletes file handle entry
  213. // COMMON
  214. func (fs *BaseFS) ReleaseDirHandle(ctx context.Context, op *fuseops.ReleaseDirHandleOp) (err error) {
  215. delete(fs.fileHandles, op.Handle)
  216. return
  217. }
  218. // LookUpInode based on Parent and Name we return a self cached inode
  219. // Cloud be COMMON but has specific ID
  220. func (fs *BaseFS) LookUpInode(ctx context.Context, op *fuseops.LookUpInodeOp) (err error) {
  221. parentFile := fs.Root.FindByInode(op.Parent) // true means transverse all
  222. if parentFile == nil {
  223. return fuse.ENOENT
  224. }
  225. entry := fs.Root.Lookup(parentFile, op.Name)
  226. if entry == nil {
  227. return fuse.ENOENT
  228. }
  229. // Transverse only local
  230. now := time.Now()
  231. op.Entry = fuseops.ChildInodeEntry{
  232. Attributes: entry.Attr,
  233. Child: entry.Inode,
  234. AttributesExpiration: now.Add(time.Second),
  235. EntryExpiration: now.Add(time.Second),
  236. }
  237. return
  238. }
  239. // StatFS basically allows StatFS to run
  240. /*func (fs *BaseFS) StatFS(ctx context.Context, op *fuseops.StatFSOp) (err error) {
  241. return
  242. }*/
  243. // ForgetInode allows to forgetInode
  244. // COMMON
  245. func (fs *BaseFS) ForgetInode(ctx context.Context, op *fuseops.ForgetInodeOp) (err error) {
  246. return
  247. }
  248. // GetXAttr special attributes
  249. // COMMON
  250. func (fs *BaseFS) GetXAttr(ctx context.Context, op *fuseops.GetXattrOp) (err error) {
  251. return
  252. }
  253. //////////////////////////////////////////////////////////////////////////
  254. // File OPS
  255. //////////////////////////////////////////////////////////////////////////
  256. // OpenFile creates a temporary handle to be handled on read or write
  257. // COMMON
  258. func (fs *BaseFS) OpenFile(ctx context.Context, op *fuseops.OpenFileOp) (err error) {
  259. f := fs.Root.FindByInode(op.Inode) // might not exists
  260. // Generate new handle
  261. handle := fs.createHandle()
  262. handle.entry = f
  263. op.Handle = handle.ID
  264. op.UseDirectIO = true
  265. return
  266. }
  267. // ReadFile if the first time we download the google drive file into a local temporary file
  268. // COMMON but specific in cache
  269. func (fs *BaseFS) ReadFile(ctx context.Context, op *fuseops.ReadFileOp) (err error) {
  270. handle := fs.fileHandles[op.Handle]
  271. localFile := fs.Root.Cache(handle.entry)
  272. op.BytesRead, err = localFile.ReadAt(op.Dst, op.Offset)
  273. if err == io.EOF { // fuse does not expect a EOF
  274. err = nil
  275. }
  276. return
  277. }
  278. // CreateFile creates empty file in google Drive and returns its ID and attributes, only allows file creation on 'My Drive'
  279. // Cloud SPECIFIC
  280. func (fs *BaseFS) CreateFile(ctx context.Context, op *fuseops.CreateFileOp) (err error) {
  281. parentFile := fs.Root.FindByInode(op.Parent)
  282. if parentFile == nil {
  283. return fuse.ENOENT
  284. }
  285. // Only write on child folders
  286. if fs.Config.Safemode && parentFile == fs.Root.FileEntries[fuseops.RootInodeID] {
  287. return syscall.EPERM
  288. }
  289. existsFile := fs.Root.Lookup(parentFile, op.Name)
  290. //existsFile := parentFile.FindByName(op.Name, false)
  291. if existsFile != nil {
  292. return fuse.EEXIST
  293. }
  294. // Parent entry/Name
  295. entry, err := fs.Root.CreateFile(parentFile, op.Name, false)
  296. if err != nil {
  297. return fuseErr(err)
  298. }
  299. // Associate a temp file to a new handle
  300. // Local copy
  301. // Lock
  302. handle := fs.createHandle()
  303. handle.entry = entry
  304. handle.uploadOnDone = true
  305. //
  306. op.Handle = handle.ID
  307. op.Entry = fuseops.ChildInodeEntry{
  308. Attributes: entry.Attr,
  309. Child: entry.Inode,
  310. AttributesExpiration: time.Now().Add(time.Minute),
  311. EntryExpiration: time.Now().Add(time.Minute),
  312. }
  313. op.Mode = entry.Attr.Mode
  314. return
  315. }
  316. // WriteFile as ReadFile it creates a temporary file on first read
  317. // Maybe the ReadFile should be called here aswell to cache current contents since we are using writeAt
  318. // CLOUD SPECIFIC
  319. func (fs *BaseFS) WriteFile(ctx context.Context, op *fuseops.WriteFileOp) (err error) {
  320. handle, ok := fs.fileHandles[op.Handle]
  321. if !ok {
  322. return fuse.EIO
  323. }
  324. localFile := fs.Root.Cache(handle.entry)
  325. if localFile == nil {
  326. return fuse.EINVAL
  327. }
  328. _, err = localFile.WriteAt(op.Data, op.Offset)
  329. if err != nil {
  330. err = fuse.EIO
  331. return
  332. }
  333. handle.uploadOnDone = true
  334. return
  335. }
  336. // FlushFile just returns no error, maybe upload should be handled here
  337. // COMMON
  338. func (fs *BaseFS) FlushFile(ctx context.Context, op *fuseops.FlushFileOp) (err error) {
  339. handle, ok := fs.fileHandles[op.Handle]
  340. if !ok {
  341. return fuse.EIO
  342. }
  343. if handle.entry.tempFile == nil {
  344. return
  345. }
  346. if handle.uploadOnDone { // or if content changed basically
  347. err = fs.Root.Sync(handle.entry)
  348. if err != nil {
  349. return fuseErr(err)
  350. }
  351. }
  352. return
  353. }
  354. // ReleaseFileHandle closes and deletes any temporary files, upload in case if changed locally
  355. // COMMON
  356. func (fs *BaseFS) ReleaseFileHandle(ctx context.Context, op *fuseops.ReleaseFileHandleOp) (err error) {
  357. handle := fs.fileHandles[op.Handle]
  358. fs.Root.ClearCache(handle.entry)
  359. delete(fs.fileHandles, op.Handle)
  360. return
  361. }
  362. // Unlink remove file and remove from local cache entry
  363. // SPECIFIC
  364. func (fs *BaseFS) Unlink(ctx context.Context, op *fuseops.UnlinkOp) (err error) {
  365. if fs.Config.Safemode && op.Parent == fuseops.RootInodeID {
  366. return syscall.EPERM
  367. }
  368. parentEntry := fs.Root.FindByInode(op.Parent)
  369. if parentEntry == nil {
  370. return fuse.ENOENT
  371. }
  372. fileEntry := fs.Root.Lookup(parentEntry, op.Name)
  373. //fileEntry := parentEntry.FindByName(op.Name, false)
  374. if fileEntry == nil {
  375. return fuse.ENOATTR
  376. }
  377. err = fs.Root.DeleteFile(fileEntry)
  378. return fuseErr(err)
  379. }
  380. // MkDir creates a directory on a parent dir
  381. func (fs *BaseFS) MkDir(ctx context.Context, op *fuseops.MkDirOp) (err error) {
  382. if fs.Config.Safemode && op.Parent == fuseops.RootInodeID {
  383. return syscall.EPERM
  384. }
  385. parentFile := fs.Root.FindByInode(op.Parent)
  386. if parentFile == nil {
  387. return fuse.ENOENT
  388. }
  389. entry, err := fs.Root.CreateFile(parentFile, op.Name, true)
  390. if err != nil {
  391. return fuseErr(err)
  392. }
  393. op.Entry = fuseops.ChildInodeEntry{
  394. Attributes: entry.Attr,
  395. Child: entry.Inode,
  396. AttributesExpiration: time.Now().Add(time.Minute),
  397. EntryExpiration: time.Now().Add(time.Microsecond),
  398. }
  399. return
  400. }
  401. // RmDir fuse implementation
  402. func (fs *BaseFS) RmDir(ctx context.Context, op *fuseops.RmDirOp) (err error) {
  403. if fs.Config.Safemode && op.Parent == fuseops.RootInodeID {
  404. return syscall.EPERM
  405. }
  406. parentFile := fs.Root.FindByInode(op.Parent)
  407. if parentFile == nil {
  408. return fuse.ENOENT
  409. }
  410. theFile := fs.Root.Lookup(parentFile, op.Name)
  411. err = fs.Root.DeleteFile(theFile)
  412. if err != nil {
  413. return fuseErr(err)
  414. }
  415. return
  416. }
  417. // Rename fuse implementation
  418. func (fs *BaseFS) Rename(ctx context.Context, op *fuseops.RenameOp) (err error) {
  419. if fs.Config.Safemode && (op.OldParent == fuseops.RootInodeID || op.NewParent == fuseops.RootInodeID) {
  420. return syscall.EPERM
  421. }
  422. oldParentEntry := fs.Root.FindByInode(op.OldParent)
  423. if oldParentEntry == nil {
  424. return fuse.ENOENT
  425. }
  426. newParentEntry := fs.Root.FindByInode(op.NewParent)
  427. if newParentEntry == nil {
  428. return fuse.ENOENT
  429. }
  430. //oldFile := oldParentFile.FindByName(op.OldName, false)
  431. oldEntry := fs.Root.Lookup(oldParentEntry, op.OldName)
  432. // Although GDrive allows duplicate names, there is some issue with inode caching
  433. // So we prevent a rename to a file with same name
  434. //existsFile := newParentFile.FindByName(op.NewName, false)
  435. existsEntry := fs.Root.Lookup(newParentEntry, op.NewName)
  436. if existsEntry != nil {
  437. return fuse.EEXIST
  438. }
  439. nFile, err := fs.Service.Move(oldEntry.File, newParentEntry.File, op.NewName)
  440. if err != nil {
  441. return fuseErr(err)
  442. }
  443. // Why remove and add instead of setting file, is just in case we have an existing name FileEntry solves the name adding duplicates helpers
  444. fs.Root.RemoveEntry(oldEntry)
  445. fs.Root.FileEntry(nFile, oldEntry.Inode) // Use this same inode
  446. return
  447. }
  448. func fuseErr(err error) error {
  449. switch err {
  450. case ErrPermission:
  451. return syscall.EPERM
  452. case ErrNotImplemented:
  453. return fuse.ENOSYS
  454. case nil:
  455. return nil
  456. default:
  457. return fuse.EINVAL
  458. }
  459. }