gcsfs.go 19 KB

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