gcsfs.go 24 KB

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