gcsfs.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. //go:build !nogcs
  15. // +build !nogcs
  16. package vfs
  17. import (
  18. "context"
  19. "fmt"
  20. "io"
  21. "mime"
  22. "net/http"
  23. "os"
  24. "path"
  25. "path/filepath"
  26. "strings"
  27. "time"
  28. "cloud.google.com/go/storage"
  29. "github.com/eikenb/pipeat"
  30. "github.com/pkg/sftp"
  31. "google.golang.org/api/googleapi"
  32. "google.golang.org/api/iterator"
  33. "google.golang.org/api/option"
  34. "github.com/drakkan/sftpgo/v2/internal/logger"
  35. "github.com/drakkan/sftpgo/v2/internal/metric"
  36. "github.com/drakkan/sftpgo/v2/internal/plugin"
  37. "github.com/drakkan/sftpgo/v2/internal/util"
  38. "github.com/drakkan/sftpgo/v2/internal/version"
  39. )
  40. const (
  41. defaultGCSPageSize = 5000
  42. gcsfsName = "GCSFs"
  43. )
  44. var (
  45. gcsDefaultFieldsSelection = []string{"Name", "Size", "Deleted", "Updated", "ContentType"}
  46. )
  47. // GCSFs is a Fs implementation for Google Cloud Storage.
  48. type GCSFs struct {
  49. connectionID string
  50. localTempDir string
  51. // if not empty this fs is mouted as virtual folder in the specified path
  52. mountPath string
  53. config *GCSFsConfig
  54. svc *storage.Client
  55. ctxTimeout time.Duration
  56. ctxLongTimeout time.Duration
  57. }
  58. func init() {
  59. version.AddFeature("+gcs")
  60. }
  61. // NewGCSFs returns an GCSFs object that allows to interact with Google Cloud Storage
  62. func NewGCSFs(connectionID, localTempDir, mountPath string, config GCSFsConfig) (Fs, error) {
  63. if localTempDir == "" {
  64. if tempPath != "" {
  65. localTempDir = tempPath
  66. } else {
  67. localTempDir = filepath.Clean(os.TempDir())
  68. }
  69. }
  70. var err error
  71. fs := &GCSFs{
  72. connectionID: connectionID,
  73. localTempDir: localTempDir,
  74. mountPath: getMountPath(mountPath),
  75. config: &config,
  76. ctxTimeout: 30 * time.Second,
  77. ctxLongTimeout: 300 * time.Second,
  78. }
  79. if err = fs.config.validate(); err != nil {
  80. return fs, err
  81. }
  82. ctx := context.Background()
  83. if fs.config.AutomaticCredentials > 0 {
  84. fs.svc, err = storage.NewClient(ctx)
  85. } else {
  86. err = fs.config.Credentials.TryDecrypt()
  87. if err != nil {
  88. return fs, err
  89. }
  90. fs.svc, err = storage.NewClient(ctx, option.WithCredentialsJSON([]byte(fs.config.Credentials.GetPayload())))
  91. }
  92. return fs, err
  93. }
  94. // Name returns the name for the Fs implementation
  95. func (fs *GCSFs) Name() string {
  96. return fmt.Sprintf("%s bucket %q", gcsfsName, fs.config.Bucket)
  97. }
  98. // ConnectionID returns the connection ID associated to this Fs implementation
  99. func (fs *GCSFs) ConnectionID() string {
  100. return fs.connectionID
  101. }
  102. // Stat returns a FileInfo describing the named file
  103. func (fs *GCSFs) Stat(name string) (os.FileInfo, error) {
  104. if name == "" || name == "/" || name == "." {
  105. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  106. }
  107. if fs.config.KeyPrefix == name+"/" {
  108. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  109. }
  110. _, info, err := fs.getObjectStat(name)
  111. return info, err
  112. }
  113. // Lstat returns a FileInfo describing the named file
  114. func (fs *GCSFs) Lstat(name string) (os.FileInfo, error) {
  115. return fs.Stat(name)
  116. }
  117. // Open opens the named file for reading
  118. func (fs *GCSFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  119. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  120. if err != nil {
  121. return nil, nil, nil, err
  122. }
  123. bkt := fs.svc.Bucket(fs.config.Bucket)
  124. obj := bkt.Object(name)
  125. ctx, cancelFn := context.WithCancel(context.Background())
  126. objectReader, err := obj.NewRangeReader(ctx, offset, -1)
  127. if err == nil && offset > 0 && objectReader.Attrs.ContentEncoding == "gzip" {
  128. err = fmt.Errorf("range request is not possible for gzip content encoding, requested offset %v", offset)
  129. objectReader.Close()
  130. }
  131. if err != nil {
  132. r.Close()
  133. w.Close()
  134. cancelFn()
  135. return nil, nil, nil, err
  136. }
  137. go func() {
  138. defer cancelFn()
  139. defer objectReader.Close()
  140. n, err := io.Copy(w, objectReader)
  141. w.CloseWithError(err) //nolint:errcheck
  142. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %+v", name, n, err)
  143. metric.GCSTransferCompleted(n, 1, err)
  144. }()
  145. return nil, r, cancelFn, nil
  146. }
  147. // Create creates or opens the named file for writing
  148. func (fs *GCSFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  149. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  150. if err != nil {
  151. return nil, nil, nil, err
  152. }
  153. p := NewPipeWriter(w)
  154. bkt := fs.svc.Bucket(fs.config.Bucket)
  155. obj := bkt.Object(name)
  156. ctx, cancelFn := context.WithCancel(context.Background())
  157. objectWriter := obj.NewWriter(ctx)
  158. var contentType string
  159. if flag == -1 {
  160. contentType = dirMimeType
  161. } else {
  162. contentType = mime.TypeByExtension(path.Ext(name))
  163. }
  164. if contentType != "" {
  165. objectWriter.ObjectAttrs.ContentType = contentType
  166. }
  167. if fs.config.StorageClass != "" {
  168. objectWriter.ObjectAttrs.StorageClass = fs.config.StorageClass
  169. }
  170. if fs.config.ACL != "" {
  171. objectWriter.PredefinedACL = fs.config.ACL
  172. }
  173. go func() {
  174. defer cancelFn()
  175. n, err := io.Copy(objectWriter, r)
  176. closeErr := objectWriter.Close()
  177. if err == nil {
  178. err = closeErr
  179. }
  180. r.CloseWithError(err) //nolint:errcheck
  181. p.Done(err)
  182. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, acl: %#v, readed bytes: %v, err: %+v",
  183. name, fs.config.ACL, n, err)
  184. metric.GCSTransferCompleted(n, 0, err)
  185. }()
  186. return nil, p, cancelFn, nil
  187. }
  188. // Rename renames (moves) source to target.
  189. // We don't support renaming non empty directories since we should
  190. // rename all the contents too and this could take long time: think
  191. // about directories with thousands of files, for each file we should
  192. // execute a CopyObject call.
  193. func (fs *GCSFs) Rename(source, target string) error {
  194. if source == target {
  195. return nil
  196. }
  197. realSourceName, fi, err := fs.getObjectStat(source)
  198. if err != nil {
  199. return err
  200. }
  201. if fi.IsDir() {
  202. hasContents, err := fs.hasContents(source)
  203. if err != nil {
  204. return err
  205. }
  206. if hasContents {
  207. return fmt.Errorf("cannot rename non empty directory: %#v", source)
  208. }
  209. if err := fs.mkdirInternal(target); err != nil {
  210. return err
  211. }
  212. } else {
  213. src := fs.svc.Bucket(fs.config.Bucket).Object(realSourceName)
  214. dst := fs.svc.Bucket(fs.config.Bucket).Object(target)
  215. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  216. defer cancelFn()
  217. copier := dst.CopierFrom(src)
  218. if fs.config.StorageClass != "" {
  219. copier.StorageClass = fs.config.StorageClass
  220. }
  221. if fs.config.ACL != "" {
  222. copier.PredefinedACL = fs.config.ACL
  223. }
  224. contentType := mime.TypeByExtension(path.Ext(source))
  225. if contentType != "" {
  226. copier.ContentType = contentType
  227. }
  228. _, err = copier.Run(ctx)
  229. metric.GCSCopyObjectCompleted(err)
  230. if err != nil {
  231. return err
  232. }
  233. if plugin.Handler.HasMetadater() {
  234. err = plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(target),
  235. util.GetTimeAsMsSinceEpoch(fi.ModTime()))
  236. if err != nil {
  237. fsLog(fs, logger.LevelWarn, "unable to preserve modification time after renaming %#v -> %#v: %+v",
  238. source, target, err)
  239. }
  240. }
  241. }
  242. return fs.Remove(source, fi.IsDir())
  243. }
  244. // Remove removes the named file or (empty) directory.
  245. func (fs *GCSFs) Remove(name string, isDir bool) error {
  246. if isDir {
  247. hasContents, err := fs.hasContents(name)
  248. if err != nil {
  249. return err
  250. }
  251. if hasContents {
  252. return fmt.Errorf("cannot remove non empty directory: %#v", name)
  253. }
  254. if !strings.HasSuffix(name, "/") {
  255. name += "/"
  256. }
  257. }
  258. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  259. defer cancelFn()
  260. err := fs.svc.Bucket(fs.config.Bucket).Object(name).Delete(ctx)
  261. if fs.IsNotExist(err) && isDir {
  262. // we can have directories without a trailing "/" (created using v2.1.0 and before)
  263. err = fs.svc.Bucket(fs.config.Bucket).Object(strings.TrimSuffix(name, "/")).Delete(ctx)
  264. }
  265. metric.GCSDeleteObjectCompleted(err)
  266. if plugin.Handler.HasMetadater() && err == nil && !isDir {
  267. if errMetadata := plugin.Handler.RemoveMetadata(fs.getStorageID(), ensureAbsPath(name)); errMetadata != nil {
  268. fsLog(fs, logger.LevelWarn, "unable to remove metadata for path %#v: %+v", name, errMetadata)
  269. }
  270. }
  271. return err
  272. }
  273. // Mkdir creates a new directory with the specified name and default permissions
  274. func (fs *GCSFs) Mkdir(name string) error {
  275. _, err := fs.Stat(name)
  276. if !fs.IsNotExist(err) {
  277. return err
  278. }
  279. return fs.mkdirInternal(name)
  280. }
  281. // Symlink creates source as a symbolic link to target.
  282. func (*GCSFs) Symlink(source, target string) error {
  283. return ErrVfsUnsupported
  284. }
  285. // Readlink returns the destination of the named symbolic link
  286. func (*GCSFs) Readlink(name string) (string, error) {
  287. return "", ErrVfsUnsupported
  288. }
  289. // Chown changes the numeric uid and gid of the named file.
  290. func (*GCSFs) Chown(name string, uid int, gid int) error {
  291. return ErrVfsUnsupported
  292. }
  293. // Chmod changes the mode of the named file to mode.
  294. func (*GCSFs) Chmod(name string, mode os.FileMode) error {
  295. return ErrVfsUnsupported
  296. }
  297. // Chtimes changes the access and modification times of the named file.
  298. func (fs *GCSFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  299. if !plugin.Handler.HasMetadater() {
  300. return ErrVfsUnsupported
  301. }
  302. if !isUploading {
  303. info, err := fs.Stat(name)
  304. if err != nil {
  305. return err
  306. }
  307. if info.IsDir() {
  308. return ErrVfsUnsupported
  309. }
  310. }
  311. return plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(name),
  312. util.GetTimeAsMsSinceEpoch(mtime))
  313. }
  314. // Truncate changes the size of the named file.
  315. // Truncate by path is not supported, while truncating an opened
  316. // file is handled inside base transfer
  317. func (*GCSFs) Truncate(name string, size int64) error {
  318. return ErrVfsUnsupported
  319. }
  320. // ReadDir reads the directory named by dirname and returns
  321. // a list of directory entries.
  322. func (fs *GCSFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  323. var result []os.FileInfo
  324. // dirname must be already cleaned
  325. prefix := fs.getPrefix(dirname)
  326. query := &storage.Query{Prefix: prefix, Delimiter: "/"}
  327. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  328. if err != nil {
  329. return nil, err
  330. }
  331. modTimes, err := getFolderModTimes(fs.getStorageID(), dirname)
  332. if err != nil {
  333. return result, err
  334. }
  335. prefixes := make(map[string]bool)
  336. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  337. defer cancelFn()
  338. bkt := fs.svc.Bucket(fs.config.Bucket)
  339. it := bkt.Objects(ctx, query)
  340. pager := iterator.NewPager(it, defaultGCSPageSize, "")
  341. for {
  342. var objects []*storage.ObjectAttrs
  343. pageToken, err := pager.NextPage(&objects)
  344. if err != nil {
  345. metric.GCSListObjectsCompleted(err)
  346. return result, err
  347. }
  348. for _, attrs := range objects {
  349. if attrs.Prefix != "" {
  350. name, _ := fs.resolve(attrs.Prefix, prefix, attrs.ContentType)
  351. if name == "" {
  352. continue
  353. }
  354. if _, ok := prefixes[name]; ok {
  355. continue
  356. }
  357. result = append(result, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  358. prefixes[name] = true
  359. } else {
  360. name, isDir := fs.resolve(attrs.Name, prefix, attrs.ContentType)
  361. if name == "" {
  362. continue
  363. }
  364. if !attrs.Deleted.IsZero() {
  365. continue
  366. }
  367. if isDir {
  368. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  369. if _, ok := prefixes[name]; ok {
  370. continue
  371. }
  372. prefixes[name] = true
  373. }
  374. modTime := attrs.Updated
  375. if t, ok := modTimes[name]; ok {
  376. modTime = util.GetTimeFromMsecSinceEpoch(t)
  377. }
  378. result = append(result, NewFileInfo(name, isDir, attrs.Size, modTime, false))
  379. }
  380. }
  381. objects = nil
  382. if pageToken == "" {
  383. break
  384. }
  385. }
  386. metric.GCSListObjectsCompleted(nil)
  387. return result, nil
  388. }
  389. // IsUploadResumeSupported returns true if resuming uploads is supported.
  390. // Resuming uploads is not supported on GCS
  391. func (*GCSFs) IsUploadResumeSupported() bool {
  392. return false
  393. }
  394. // IsAtomicUploadSupported returns true if atomic upload is supported.
  395. // S3 uploads are already atomic, we don't need to upload to a temporary
  396. // file
  397. func (*GCSFs) IsAtomicUploadSupported() bool {
  398. return false
  399. }
  400. // IsNotExist returns a boolean indicating whether the error is known to
  401. // report that a file or directory does not exist
  402. func (*GCSFs) IsNotExist(err error) bool {
  403. if err == nil {
  404. return false
  405. }
  406. if err == storage.ErrObjectNotExist || err == storage.ErrBucketNotExist {
  407. return true
  408. }
  409. if e, ok := err.(*googleapi.Error); ok {
  410. if e.Code == http.StatusNotFound {
  411. return true
  412. }
  413. }
  414. return false
  415. }
  416. // IsPermission returns a boolean indicating whether the error is known to
  417. // report that permission is denied.
  418. func (*GCSFs) IsPermission(err error) bool {
  419. if err == nil {
  420. return false
  421. }
  422. if e, ok := err.(*googleapi.Error); ok {
  423. if e.Code == http.StatusForbidden || e.Code == http.StatusUnauthorized {
  424. return true
  425. }
  426. }
  427. return false
  428. }
  429. // IsNotSupported returns true if the error indicate an unsupported operation
  430. func (*GCSFs) IsNotSupported(err error) bool {
  431. if err == nil {
  432. return false
  433. }
  434. return err == ErrVfsUnsupported
  435. }
  436. // CheckRootPath creates the specified local root directory if it does not exists
  437. func (fs *GCSFs) CheckRootPath(username string, uid int, gid int) bool {
  438. // we need a local directory for temporary files
  439. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  440. return osFs.CheckRootPath(username, uid, gid)
  441. }
  442. // ScanRootDirContents returns the number of files contained in the bucket,
  443. // and their size
  444. func (fs *GCSFs) ScanRootDirContents() (int, int64, error) {
  445. numFiles := 0
  446. size := int64(0)
  447. query := &storage.Query{Prefix: fs.config.KeyPrefix}
  448. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  449. if err != nil {
  450. return numFiles, size, err
  451. }
  452. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  453. defer cancelFn()
  454. bkt := fs.svc.Bucket(fs.config.Bucket)
  455. it := bkt.Objects(ctx, query)
  456. pager := iterator.NewPager(it, defaultGCSPageSize, "")
  457. for {
  458. var objects []*storage.ObjectAttrs
  459. pageToken, err := pager.NextPage(&objects)
  460. if err != nil {
  461. metric.GCSListObjectsCompleted(err)
  462. return numFiles, size, err
  463. }
  464. for _, attrs := range objects {
  465. if !attrs.Deleted.IsZero() {
  466. continue
  467. }
  468. isDir := strings.HasSuffix(attrs.Name, "/") || attrs.ContentType == dirMimeType
  469. if isDir && attrs.Size == 0 {
  470. continue
  471. }
  472. numFiles++
  473. size += attrs.Size
  474. if numFiles%1000 == 0 {
  475. fsLog(fs, logger.LevelDebug, "root dir scan in progress, files: %d, size: %d", numFiles, size)
  476. }
  477. }
  478. objects = nil
  479. if pageToken == "" {
  480. break
  481. }
  482. }
  483. metric.GCSListObjectsCompleted(nil)
  484. return numFiles, size, err
  485. }
  486. func (fs *GCSFs) getFileNamesInPrefix(fsPrefix string) (map[string]bool, error) {
  487. fileNames := make(map[string]bool)
  488. prefix := ""
  489. if fsPrefix != "/" {
  490. prefix = strings.TrimPrefix(fsPrefix, "/")
  491. }
  492. query := &storage.Query{
  493. Prefix: prefix,
  494. Delimiter: "/",
  495. }
  496. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  497. if err != nil {
  498. return fileNames, err
  499. }
  500. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  501. defer cancelFn()
  502. bkt := fs.svc.Bucket(fs.config.Bucket)
  503. it := bkt.Objects(ctx, query)
  504. pager := iterator.NewPager(it, defaultGCSPageSize, "")
  505. for {
  506. var objects []*storage.ObjectAttrs
  507. pageToken, err := pager.NextPage(&objects)
  508. if err != nil {
  509. metric.GCSListObjectsCompleted(err)
  510. return fileNames, err
  511. }
  512. for _, attrs := range objects {
  513. if !attrs.Deleted.IsZero() {
  514. continue
  515. }
  516. if attrs.Prefix == "" {
  517. name, isDir := fs.resolve(attrs.Name, prefix, attrs.ContentType)
  518. if name == "" {
  519. continue
  520. }
  521. if isDir {
  522. continue
  523. }
  524. fileNames[name] = true
  525. }
  526. }
  527. objects = nil
  528. if pageToken == "" {
  529. break
  530. }
  531. }
  532. metric.GCSListObjectsCompleted(nil)
  533. return fileNames, nil
  534. }
  535. // CheckMetadata checks the metadata consistency
  536. func (fs *GCSFs) CheckMetadata() error {
  537. return fsMetadataCheck(fs, fs.getStorageID(), fs.config.KeyPrefix)
  538. }
  539. // GetDirSize returns the number of files and the size for a folder
  540. // including any subfolders
  541. func (*GCSFs) GetDirSize(dirname string) (int, int64, error) {
  542. return 0, 0, ErrVfsUnsupported
  543. }
  544. // GetAtomicUploadPath returns the path to use for an atomic upload.
  545. // GCS uploads are already atomic, we never call this method for GCS
  546. func (*GCSFs) GetAtomicUploadPath(name string) string {
  547. return ""
  548. }
  549. // GetRelativePath returns the path for a file relative to the user's home dir.
  550. // This is the path as seen by SFTPGo users
  551. func (fs *GCSFs) GetRelativePath(name string) string {
  552. rel := path.Clean(name)
  553. if rel == "." {
  554. rel = ""
  555. }
  556. if !path.IsAbs(rel) {
  557. rel = "/" + rel
  558. }
  559. if fs.config.KeyPrefix != "" {
  560. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  561. rel = "/"
  562. }
  563. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  564. }
  565. if fs.mountPath != "" {
  566. rel = path.Join(fs.mountPath, rel)
  567. }
  568. return rel
  569. }
  570. // Walk walks the file tree rooted at root, calling walkFn for each file or
  571. // directory in the tree, including root
  572. func (fs *GCSFs) Walk(root string, walkFn filepath.WalkFunc) error {
  573. prefix := fs.getPrefix(root)
  574. query := &storage.Query{Prefix: prefix}
  575. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  576. if err != nil {
  577. walkFn(root, nil, err) //nolint:errcheck
  578. return err
  579. }
  580. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  581. defer cancelFn()
  582. bkt := fs.svc.Bucket(fs.config.Bucket)
  583. it := bkt.Objects(ctx, query)
  584. pager := iterator.NewPager(it, defaultGCSPageSize, "")
  585. for {
  586. var objects []*storage.ObjectAttrs
  587. pageToken, err := pager.NextPage(&objects)
  588. if err != nil {
  589. walkFn(root, nil, err) //nolint:errcheck
  590. metric.GCSListObjectsCompleted(err)
  591. return err
  592. }
  593. for _, attrs := range objects {
  594. if !attrs.Deleted.IsZero() {
  595. continue
  596. }
  597. name, isDir := fs.resolve(attrs.Name, prefix, attrs.ContentType)
  598. if name == "" {
  599. continue
  600. }
  601. err = walkFn(attrs.Name, NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false), nil)
  602. if err != nil {
  603. return err
  604. }
  605. }
  606. objects = nil
  607. if pageToken == "" {
  608. break
  609. }
  610. }
  611. walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), err) //nolint:errcheck
  612. metric.GCSListObjectsCompleted(err)
  613. return err
  614. }
  615. // Join joins any number of path elements into a single path
  616. func (*GCSFs) Join(elem ...string) string {
  617. return strings.TrimPrefix(path.Join(elem...), "/")
  618. }
  619. // HasVirtualFolders returns true if folders are emulated
  620. func (GCSFs) HasVirtualFolders() bool {
  621. return true
  622. }
  623. // ResolvePath returns the matching filesystem path for the specified virtual path
  624. func (fs *GCSFs) ResolvePath(virtualPath string) (string, error) {
  625. if fs.mountPath != "" {
  626. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  627. }
  628. if !path.IsAbs(virtualPath) {
  629. virtualPath = path.Clean("/" + virtualPath)
  630. }
  631. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  632. }
  633. func (fs *GCSFs) resolve(name, prefix, contentType string) (string, bool) {
  634. result := strings.TrimPrefix(name, prefix)
  635. isDir := strings.HasSuffix(result, "/")
  636. if isDir {
  637. result = strings.TrimSuffix(result, "/")
  638. }
  639. if contentType == dirMimeType {
  640. isDir = true
  641. }
  642. return result, isDir
  643. }
  644. // getObjectStat returns the stat result and the real object name as first value
  645. func (fs *GCSFs) getObjectStat(name string) (string, os.FileInfo, error) {
  646. attrs, err := fs.headObject(name)
  647. var info os.FileInfo
  648. if err == nil {
  649. objSize := attrs.Size
  650. objectModTime := attrs.Updated
  651. isDir := attrs.ContentType == dirMimeType || strings.HasSuffix(attrs.Name, "/")
  652. info, err = updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, isDir, objSize, objectModTime, false))
  653. return name, info, err
  654. }
  655. if !fs.IsNotExist(err) {
  656. return "", nil, err
  657. }
  658. // now check if this is a prefix (virtual directory)
  659. hasContents, err := fs.hasContents(name)
  660. if err != nil {
  661. return "", nil, err
  662. }
  663. if hasContents {
  664. info, err = updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  665. return name, info, err
  666. }
  667. // finally check if this is an object with a trailing /
  668. attrs, err = fs.headObject(name + "/")
  669. if err != nil {
  670. return "", nil, err
  671. }
  672. info, err = updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, attrs.Size, attrs.Updated, false))
  673. return name + "/", info, err
  674. }
  675. func (fs *GCSFs) mkdirInternal(name string) error {
  676. if !strings.HasSuffix(name, "/") {
  677. name += "/"
  678. }
  679. _, w, _, err := fs.Create(name, -1)
  680. if err != nil {
  681. return err
  682. }
  683. return w.Close()
  684. }
  685. func (fs *GCSFs) hasContents(name string) (bool, error) {
  686. result := false
  687. prefix := fs.getPrefix(name)
  688. query := &storage.Query{Prefix: prefix}
  689. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  690. if err != nil {
  691. return result, err
  692. }
  693. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  694. defer cancelFn()
  695. bkt := fs.svc.Bucket(fs.config.Bucket)
  696. it := bkt.Objects(ctx, query)
  697. // if we have a dir object with a trailing slash it will be returned so we set the size to 2
  698. pager := iterator.NewPager(it, 2, "")
  699. var objects []*storage.ObjectAttrs
  700. _, err = pager.NextPage(&objects)
  701. if err != nil {
  702. metric.GCSListObjectsCompleted(err)
  703. return result, err
  704. }
  705. for _, attrs := range objects {
  706. name, _ := fs.resolve(attrs.Name, prefix, attrs.ContentType)
  707. // a dir object with a trailing slash will result in an empty name
  708. if name == "/" || name == "" {
  709. continue
  710. }
  711. result = true
  712. break
  713. }
  714. metric.GCSListObjectsCompleted(nil)
  715. return result, nil
  716. }
  717. func (fs *GCSFs) getPrefix(name string) string {
  718. prefix := ""
  719. if name != "" && name != "." && name != "/" {
  720. prefix = strings.TrimPrefix(name, "/")
  721. if !strings.HasSuffix(prefix, "/") {
  722. prefix += "/"
  723. }
  724. }
  725. return prefix
  726. }
  727. func (fs *GCSFs) headObject(name string) (*storage.ObjectAttrs, error) {
  728. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  729. defer cancelFn()
  730. bkt := fs.svc.Bucket(fs.config.Bucket)
  731. obj := bkt.Object(name)
  732. attrs, err := obj.Attrs(ctx)
  733. metric.GCSHeadObjectCompleted(err)
  734. return attrs, err
  735. }
  736. // GetMimeType returns the content type
  737. func (fs *GCSFs) GetMimeType(name string) (string, error) {
  738. attrs, err := fs.headObject(name)
  739. if err != nil {
  740. return "", err
  741. }
  742. return attrs.ContentType, nil
  743. }
  744. // Close closes the fs
  745. func (fs *GCSFs) Close() error {
  746. return nil
  747. }
  748. // GetAvailableDiskSize returns the available size for the specified path
  749. func (*GCSFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  750. return nil, ErrStorageSizeUnavailable
  751. }
  752. func (fs *GCSFs) getStorageID() string {
  753. return fmt.Sprintf("gs://%v", fs.config.Bucket)
  754. }