gcsfs.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. // +build !nogcs
  2. package vfs
  3. import (
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "mime"
  10. "net/http"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "cloud.google.com/go/storage"
  17. "github.com/eikenb/pipeat"
  18. "github.com/pkg/sftp"
  19. "google.golang.org/api/googleapi"
  20. "google.golang.org/api/iterator"
  21. "google.golang.org/api/option"
  22. "github.com/drakkan/sftpgo/kms"
  23. "github.com/drakkan/sftpgo/logger"
  24. "github.com/drakkan/sftpgo/metrics"
  25. "github.com/drakkan/sftpgo/version"
  26. )
  27. var (
  28. gcsDefaultFieldsSelection = []string{"Name", "Size", "Deleted", "Updated", "ContentType"}
  29. )
  30. // GCSFs is a Fs implementation for Google Cloud Storage.
  31. type GCSFs struct {
  32. connectionID string
  33. localTempDir string
  34. // if not empty this fs is mouted as virtual folder in the specified path
  35. mountPath string
  36. config *GCSFsConfig
  37. svc *storage.Client
  38. ctxTimeout time.Duration
  39. ctxLongTimeout time.Duration
  40. }
  41. func init() {
  42. version.AddFeature("+gcs")
  43. }
  44. // NewGCSFs returns an GCSFs object that allows to interact with Google Cloud Storage
  45. func NewGCSFs(connectionID, localTempDir, mountPath string, config GCSFsConfig) (Fs, error) {
  46. if localTempDir == "" {
  47. if tempPath != "" {
  48. localTempDir = tempPath
  49. } else {
  50. localTempDir = filepath.Clean(os.TempDir())
  51. }
  52. }
  53. var err error
  54. fs := &GCSFs{
  55. connectionID: connectionID,
  56. localTempDir: localTempDir,
  57. mountPath: mountPath,
  58. config: &config,
  59. ctxTimeout: 30 * time.Second,
  60. ctxLongTimeout: 300 * time.Second,
  61. }
  62. if err = fs.config.Validate(fs.config.CredentialFile); err != nil {
  63. return fs, err
  64. }
  65. ctx := context.Background()
  66. if fs.config.AutomaticCredentials > 0 {
  67. fs.svc, err = storage.NewClient(ctx)
  68. } else if !fs.config.Credentials.IsEmpty() {
  69. err = fs.config.Credentials.TryDecrypt()
  70. if err != nil {
  71. return fs, err
  72. }
  73. fs.svc, err = storage.NewClient(ctx, option.WithCredentialsJSON([]byte(fs.config.Credentials.GetPayload())))
  74. } else {
  75. var creds []byte
  76. creds, err = os.ReadFile(fs.config.CredentialFile)
  77. if err != nil {
  78. return fs, err
  79. }
  80. secret := kms.NewEmptySecret()
  81. err = json.Unmarshal(creds, secret)
  82. if err != nil {
  83. return fs, err
  84. }
  85. err = secret.Decrypt()
  86. if err != nil {
  87. return fs, err
  88. }
  89. fs.svc, err = storage.NewClient(ctx, option.WithCredentialsJSON([]byte(secret.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. var result *FileInfo
  104. var err error
  105. if name == "" || name == "." {
  106. err := fs.checkIfBucketExists()
  107. if err != nil {
  108. return result, err
  109. }
  110. return NewFileInfo(name, true, 0, time.Now(), false), nil
  111. }
  112. if fs.config.KeyPrefix == name+"/" {
  113. return NewFileInfo(name, true, 0, time.Now(), false), nil
  114. }
  115. attrs, err := fs.headObject(name)
  116. if err == nil {
  117. objSize := attrs.Size
  118. objectModTime := attrs.Updated
  119. isDir := attrs.ContentType == dirMimeType || strings.HasSuffix(attrs.Name, "/")
  120. return NewFileInfo(name, isDir, objSize, objectModTime, false), nil
  121. }
  122. if !fs.IsNotExist(err) {
  123. return result, err
  124. }
  125. // now check if this is a prefix (virtual directory)
  126. hasContents, err := fs.hasContents(name)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if hasContents {
  131. return NewFileInfo(name, true, 0, time.Now(), false), nil
  132. }
  133. return nil, errors.New("404 no such file or directory")
  134. }
  135. // Lstat returns a FileInfo describing the named file
  136. func (fs *GCSFs) Lstat(name string) (os.FileInfo, error) {
  137. return fs.Stat(name)
  138. }
  139. // Open opens the named file for reading
  140. func (fs *GCSFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  141. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  142. if err != nil {
  143. return nil, nil, nil, err
  144. }
  145. bkt := fs.svc.Bucket(fs.config.Bucket)
  146. obj := bkt.Object(name)
  147. ctx, cancelFn := context.WithCancel(context.Background())
  148. objectReader, err := obj.NewRangeReader(ctx, offset, -1)
  149. if err == nil && offset > 0 && objectReader.Attrs.ContentEncoding == "gzip" {
  150. err = fmt.Errorf("range request is not possible for gzip content encoding, requested offset %v", offset)
  151. objectReader.Close()
  152. }
  153. if err != nil {
  154. r.Close()
  155. w.Close()
  156. cancelFn()
  157. return nil, nil, nil, err
  158. }
  159. go func() {
  160. defer cancelFn()
  161. defer objectReader.Close()
  162. n, err := io.Copy(w, objectReader)
  163. w.CloseWithError(err) //nolint:errcheck
  164. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  165. metrics.GCSTransferCompleted(n, 1, err)
  166. }()
  167. return nil, r, cancelFn, nil
  168. }
  169. // Create creates or opens the named file for writing
  170. func (fs *GCSFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  171. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  172. if err != nil {
  173. return nil, nil, nil, err
  174. }
  175. p := NewPipeWriter(w)
  176. bkt := fs.svc.Bucket(fs.config.Bucket)
  177. obj := bkt.Object(name)
  178. ctx, cancelFn := context.WithCancel(context.Background())
  179. objectWriter := obj.NewWriter(ctx)
  180. var contentType string
  181. if flag == -1 {
  182. contentType = dirMimeType
  183. } else {
  184. contentType = mime.TypeByExtension(path.Ext(name))
  185. }
  186. if contentType != "" {
  187. objectWriter.ObjectAttrs.ContentType = contentType
  188. }
  189. if fs.config.StorageClass != "" {
  190. objectWriter.ObjectAttrs.StorageClass = fs.config.StorageClass
  191. }
  192. go func() {
  193. defer cancelFn()
  194. n, err := io.Copy(objectWriter, r)
  195. closeErr := objectWriter.Close()
  196. if err == nil {
  197. err = closeErr
  198. }
  199. r.CloseWithError(err) //nolint:errcheck
  200. p.Done(err)
  201. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v", name, n, err)
  202. metrics.GCSTransferCompleted(n, 0, err)
  203. }()
  204. return nil, p, cancelFn, nil
  205. }
  206. // Rename renames (moves) source to target.
  207. // We don't support renaming non empty directories since we should
  208. // rename all the contents too and this could take long time: think
  209. // about directories with thousands of files, for each file we should
  210. // execute a CopyObject call.
  211. func (fs *GCSFs) Rename(source, target string) error {
  212. if source == target {
  213. return nil
  214. }
  215. fi, err := fs.Stat(source)
  216. if err != nil {
  217. return err
  218. }
  219. if fi.IsDir() {
  220. hasContents, err := fs.hasContents(source)
  221. if err != nil {
  222. return err
  223. }
  224. if hasContents {
  225. return fmt.Errorf("cannot rename non empty directory: %#v", source)
  226. }
  227. }
  228. src := fs.svc.Bucket(fs.config.Bucket).Object(source)
  229. dst := fs.svc.Bucket(fs.config.Bucket).Object(target)
  230. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  231. defer cancelFn()
  232. copier := dst.CopierFrom(src)
  233. if fs.config.StorageClass != "" {
  234. copier.StorageClass = fs.config.StorageClass
  235. }
  236. var contentType string
  237. if fi.IsDir() {
  238. contentType = dirMimeType
  239. } else {
  240. contentType = mime.TypeByExtension(path.Ext(source))
  241. }
  242. if contentType != "" {
  243. copier.ContentType = contentType
  244. }
  245. _, err = copier.Run(ctx)
  246. metrics.GCSCopyObjectCompleted(err)
  247. if err != nil {
  248. return err
  249. }
  250. return fs.Remove(source, fi.IsDir())
  251. }
  252. // Remove removes the named file or (empty) directory.
  253. func (fs *GCSFs) Remove(name string, isDir bool) error {
  254. if isDir {
  255. hasContents, err := fs.hasContents(name)
  256. if err != nil {
  257. return err
  258. }
  259. if hasContents {
  260. return fmt.Errorf("cannot remove non empty directory: %#v", 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. metrics.GCSDeleteObjectCompleted(err)
  267. return err
  268. }
  269. // Mkdir creates a new directory with the specified name and default permissions
  270. func (fs *GCSFs) Mkdir(name string) error {
  271. _, err := fs.Stat(name)
  272. if !fs.IsNotExist(err) {
  273. return err
  274. }
  275. _, w, _, err := fs.Create(name, -1)
  276. if err != nil {
  277. return err
  278. }
  279. return w.Close()
  280. }
  281. // MkdirAll does nothing, we don't have folder
  282. func (*GCSFs) MkdirAll(name string, uid int, gid int) error {
  283. return nil
  284. }
  285. // Symlink creates source as a symbolic link to target.
  286. func (*GCSFs) Symlink(source, target string) error {
  287. return ErrVfsUnsupported
  288. }
  289. // Readlink returns the destination of the named symbolic link
  290. func (*GCSFs) Readlink(name string) (string, error) {
  291. return "", ErrVfsUnsupported
  292. }
  293. // Chown changes the numeric uid and gid of the named file.
  294. func (*GCSFs) Chown(name string, uid int, gid int) error {
  295. return ErrVfsUnsupported
  296. }
  297. // Chmod changes the mode of the named file to mode.
  298. func (*GCSFs) Chmod(name string, mode os.FileMode) error {
  299. return ErrVfsUnsupported
  300. }
  301. // Chtimes changes the access and modification times of the named file.
  302. func (*GCSFs) Chtimes(name string, atime, mtime time.Time) error {
  303. return ErrVfsUnsupported
  304. }
  305. // Truncate changes the size of the named file.
  306. // Truncate by path is not supported, while truncating an opened
  307. // file is handled inside base transfer
  308. func (*GCSFs) Truncate(name string, size int64) error {
  309. return ErrVfsUnsupported
  310. }
  311. // ReadDir reads the directory named by dirname and returns
  312. // a list of directory entries.
  313. func (fs *GCSFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  314. var result []os.FileInfo
  315. // dirname must be already cleaned
  316. prefix := fs.getPrefix(dirname)
  317. query := &storage.Query{Prefix: prefix, Delimiter: "/"}
  318. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  319. if err != nil {
  320. return nil, err
  321. }
  322. prefixes := make(map[string]bool)
  323. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  324. defer cancelFn()
  325. bkt := fs.svc.Bucket(fs.config.Bucket)
  326. it := bkt.Objects(ctx, query)
  327. for {
  328. attrs, err := it.Next()
  329. if err == iterator.Done {
  330. break
  331. }
  332. if err != nil {
  333. metrics.GCSListObjectsCompleted(err)
  334. return result, err
  335. }
  336. if attrs.Prefix != "" {
  337. name, _ := fs.resolve(attrs.Prefix, prefix)
  338. if name == "" {
  339. continue
  340. }
  341. if _, ok := prefixes[name]; ok {
  342. continue
  343. }
  344. result = append(result, NewFileInfo(name, true, 0, time.Now(), false))
  345. prefixes[name] = true
  346. } else {
  347. name, isDir := fs.resolve(attrs.Name, prefix)
  348. if name == "" {
  349. continue
  350. }
  351. if !attrs.Deleted.IsZero() {
  352. continue
  353. }
  354. if attrs.ContentType == dirMimeType {
  355. isDir = true
  356. }
  357. if isDir {
  358. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  359. if _, ok := prefixes[name]; ok {
  360. continue
  361. }
  362. prefixes[name] = true
  363. }
  364. fi := NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false)
  365. result = append(result, fi)
  366. }
  367. }
  368. metrics.GCSListObjectsCompleted(nil)
  369. return result, nil
  370. }
  371. // IsUploadResumeSupported returns true if resuming uploads is supported.
  372. // Resuming uploads is not supported on GCS
  373. func (*GCSFs) IsUploadResumeSupported() bool {
  374. return false
  375. }
  376. // IsAtomicUploadSupported returns true if atomic upload is supported.
  377. // S3 uploads are already atomic, we don't need to upload to a temporary
  378. // file
  379. func (*GCSFs) IsAtomicUploadSupported() bool {
  380. return false
  381. }
  382. // IsNotExist returns a boolean indicating whether the error is known to
  383. // report that a file or directory does not exist
  384. func (*GCSFs) IsNotExist(err error) bool {
  385. if err == nil {
  386. return false
  387. }
  388. if err == storage.ErrObjectNotExist || err == storage.ErrBucketNotExist {
  389. return true
  390. }
  391. if e, ok := err.(*googleapi.Error); ok {
  392. if e.Code == http.StatusNotFound {
  393. return true
  394. }
  395. }
  396. return strings.Contains(err.Error(), "404")
  397. }
  398. // IsPermission returns a boolean indicating whether the error is known to
  399. // report that permission is denied.
  400. func (*GCSFs) IsPermission(err error) bool {
  401. if err == nil {
  402. return false
  403. }
  404. if e, ok := err.(*googleapi.Error); ok {
  405. if e.Code == http.StatusForbidden || e.Code == http.StatusUnauthorized {
  406. return true
  407. }
  408. }
  409. return strings.Contains(err.Error(), "403")
  410. }
  411. // IsNotSupported returns true if the error indicate an unsupported operation
  412. func (*GCSFs) IsNotSupported(err error) bool {
  413. if err == nil {
  414. return false
  415. }
  416. return err == ErrVfsUnsupported
  417. }
  418. // CheckRootPath creates the specified local root directory if it does not exists
  419. func (fs *GCSFs) CheckRootPath(username string, uid int, gid int) bool {
  420. // we need a local directory for temporary files
  421. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  422. return osFs.CheckRootPath(username, uid, gid)
  423. }
  424. // ScanRootDirContents returns the number of files contained in the bucket,
  425. // and their size
  426. func (fs *GCSFs) ScanRootDirContents() (int, int64, error) {
  427. numFiles := 0
  428. size := int64(0)
  429. query := &storage.Query{Prefix: fs.config.KeyPrefix}
  430. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  431. if err != nil {
  432. return numFiles, size, err
  433. }
  434. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  435. defer cancelFn()
  436. bkt := fs.svc.Bucket(fs.config.Bucket)
  437. it := bkt.Objects(ctx, query)
  438. for {
  439. attrs, err := it.Next()
  440. if err == iterator.Done {
  441. break
  442. }
  443. if err != nil {
  444. metrics.GCSListObjectsCompleted(err)
  445. return numFiles, size, err
  446. }
  447. if !attrs.Deleted.IsZero() {
  448. continue
  449. }
  450. isDir := strings.HasSuffix(attrs.Name, "/") || attrs.ContentType == dirMimeType
  451. if isDir && attrs.Size == 0 {
  452. continue
  453. }
  454. numFiles++
  455. size += attrs.Size
  456. }
  457. metrics.GCSListObjectsCompleted(nil)
  458. return numFiles, size, err
  459. }
  460. // GetDirSize returns the number of files and the size for a folder
  461. // including any subfolders
  462. func (*GCSFs) GetDirSize(dirname string) (int, int64, error) {
  463. return 0, 0, ErrVfsUnsupported
  464. }
  465. // GetAtomicUploadPath returns the path to use for an atomic upload.
  466. // GCS uploads are already atomic, we never call this method for GCS
  467. func (*GCSFs) GetAtomicUploadPath(name string) string {
  468. return ""
  469. }
  470. // GetRelativePath returns the path for a file relative to the user's home dir.
  471. // This is the path as seen by SFTPGo users
  472. func (fs *GCSFs) GetRelativePath(name string) string {
  473. rel := path.Clean(name)
  474. if rel == "." {
  475. rel = ""
  476. }
  477. if !path.IsAbs(rel) {
  478. rel = "/" + rel
  479. }
  480. if fs.config.KeyPrefix != "" {
  481. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  482. rel = "/"
  483. }
  484. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  485. }
  486. if fs.mountPath != "" {
  487. rel = path.Join(fs.mountPath, rel)
  488. }
  489. return rel
  490. }
  491. // Walk walks the file tree rooted at root, calling walkFn for each file or
  492. // directory in the tree, including root
  493. func (fs *GCSFs) Walk(root string, walkFn filepath.WalkFunc) error {
  494. prefix := ""
  495. if root != "" && root != "." {
  496. prefix = strings.TrimPrefix(root, "/")
  497. if !strings.HasSuffix(prefix, "/") {
  498. prefix += "/"
  499. }
  500. }
  501. query := &storage.Query{Prefix: prefix}
  502. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  503. if err != nil {
  504. walkFn(root, nil, err) //nolint:errcheck
  505. return err
  506. }
  507. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  508. defer cancelFn()
  509. bkt := fs.svc.Bucket(fs.config.Bucket)
  510. it := bkt.Objects(ctx, query)
  511. for {
  512. attrs, err := it.Next()
  513. if err == iterator.Done {
  514. break
  515. }
  516. if err != nil {
  517. walkFn(root, nil, err) //nolint:errcheck
  518. metrics.GCSListObjectsCompleted(err)
  519. return err
  520. }
  521. if !attrs.Deleted.IsZero() {
  522. continue
  523. }
  524. name, isDir := fs.resolve(attrs.Name, prefix)
  525. if name == "" {
  526. continue
  527. }
  528. if attrs.ContentType == dirMimeType {
  529. isDir = true
  530. }
  531. err = walkFn(attrs.Name, NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false), nil)
  532. if err != nil {
  533. return err
  534. }
  535. }
  536. walkFn(root, NewFileInfo(root, true, 0, time.Now(), false), err) //nolint:errcheck
  537. metrics.GCSListObjectsCompleted(err)
  538. return err
  539. }
  540. // Join joins any number of path elements into a single path
  541. func (*GCSFs) Join(elem ...string) string {
  542. return strings.TrimPrefix(path.Join(elem...), "/")
  543. }
  544. // HasVirtualFolders returns true if folders are emulated
  545. func (GCSFs) HasVirtualFolders() bool {
  546. return true
  547. }
  548. // ResolvePath returns the matching filesystem path for the specified virtual path
  549. func (fs *GCSFs) ResolvePath(virtualPath string) (string, error) {
  550. if fs.mountPath != "" {
  551. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  552. }
  553. if !path.IsAbs(virtualPath) {
  554. virtualPath = path.Clean("/" + virtualPath)
  555. }
  556. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  557. }
  558. func (fs *GCSFs) resolve(name string, prefix string) (string, bool) {
  559. result := strings.TrimPrefix(name, prefix)
  560. isDir := strings.HasSuffix(result, "/")
  561. if isDir {
  562. result = strings.TrimSuffix(result, "/")
  563. }
  564. return result, isDir
  565. }
  566. func (fs *GCSFs) checkIfBucketExists() error {
  567. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  568. defer cancelFn()
  569. bkt := fs.svc.Bucket(fs.config.Bucket)
  570. _, err := bkt.Attrs(ctx)
  571. metrics.GCSHeadBucketCompleted(err)
  572. return err
  573. }
  574. func (fs *GCSFs) hasContents(name string) (bool, error) {
  575. result := false
  576. prefix := ""
  577. if name != "" && name != "." {
  578. prefix = strings.TrimPrefix(name, "/")
  579. if !strings.HasSuffix(prefix, "/") {
  580. prefix += "/"
  581. }
  582. }
  583. query := &storage.Query{Prefix: prefix}
  584. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  585. if err != nil {
  586. return result, err
  587. }
  588. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  589. defer cancelFn()
  590. bkt := fs.svc.Bucket(fs.config.Bucket)
  591. it := bkt.Objects(ctx, query)
  592. // if we have a dir object with a trailing slash it will be returned so we set the size to 2
  593. it.PageInfo().MaxSize = 2
  594. for {
  595. attrs, err := it.Next()
  596. if err == iterator.Done {
  597. break
  598. }
  599. if err != nil {
  600. metrics.GCSListObjectsCompleted(err)
  601. return result, err
  602. }
  603. name, _ := fs.resolve(attrs.Name, prefix)
  604. // a dir object with a trailing slash will result in an empty name
  605. if name == "/" || name == "" {
  606. continue
  607. }
  608. result = true
  609. break
  610. }
  611. metrics.GCSListObjectsCompleted(err)
  612. return result, nil
  613. }
  614. func (fs *GCSFs) getPrefix(name string) string {
  615. prefix := ""
  616. if name != "" && name != "." && name != "/" {
  617. prefix = strings.TrimPrefix(name, "/")
  618. if !strings.HasSuffix(prefix, "/") {
  619. prefix += "/"
  620. }
  621. }
  622. return prefix
  623. }
  624. func (fs *GCSFs) headObject(name string) (*storage.ObjectAttrs, error) {
  625. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  626. defer cancelFn()
  627. bkt := fs.svc.Bucket(fs.config.Bucket)
  628. obj := bkt.Object(name)
  629. attrs, err := obj.Attrs(ctx)
  630. metrics.GCSHeadObjectCompleted(err)
  631. return attrs, err
  632. }
  633. // GetMimeType returns the content type
  634. func (fs *GCSFs) GetMimeType(name string) (string, error) {
  635. attrs, err := fs.headObject(name)
  636. if err != nil {
  637. return "", err
  638. }
  639. return attrs.ContentType, nil
  640. }
  641. // Close closes the fs
  642. func (fs *GCSFs) Close() error {
  643. return nil
  644. }
  645. // GetAvailableDiskSize return the available size for the specified path
  646. func (*GCSFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  647. return nil, ErrStorageSizeUnavailable
  648. }