gcsfs.go 23 KB

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