gcsfs.go 26 KB

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