gcsfs.go 23 KB

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