gcsfs.go 23 KB

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