gcsfs.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. // +build !nogcs
  2. package vfs
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime"
  9. "net/http"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "cloud.google.com/go/storage"
  16. "github.com/eikenb/pipeat"
  17. "google.golang.org/api/googleapi"
  18. "google.golang.org/api/iterator"
  19. "google.golang.org/api/option"
  20. "github.com/drakkan/sftpgo/logger"
  21. "github.com/drakkan/sftpgo/metrics"
  22. "github.com/drakkan/sftpgo/version"
  23. )
  24. var (
  25. gcsDefaultFieldsSelection = []string{"Name", "Size", "Deleted", "Updated"}
  26. )
  27. // GCSFs is a Fs implementation for Google Cloud Storage.
  28. type GCSFs struct {
  29. connectionID string
  30. localTempDir string
  31. config GCSFsConfig
  32. svc *storage.Client
  33. ctxTimeout time.Duration
  34. ctxLongTimeout time.Duration
  35. }
  36. func init() {
  37. version.AddFeature("+gcs")
  38. }
  39. // NewGCSFs returns an GCSFs object that allows to interact with Google Cloud Storage
  40. func NewGCSFs(connectionID, localTempDir string, config GCSFsConfig) (Fs, error) {
  41. var err error
  42. fs := GCSFs{
  43. connectionID: connectionID,
  44. localTempDir: localTempDir,
  45. config: config,
  46. ctxTimeout: 30 * time.Second,
  47. ctxLongTimeout: 300 * time.Second,
  48. }
  49. if err = ValidateGCSFsConfig(&fs.config, fs.config.CredentialFile); err != nil {
  50. return fs, err
  51. }
  52. ctx := context.Background()
  53. if fs.config.AutomaticCredentials > 0 {
  54. fs.svc, err = storage.NewClient(ctx)
  55. } else {
  56. fs.svc, err = storage.NewClient(ctx, option.WithCredentialsFile(fs.config.CredentialFile))
  57. }
  58. return fs, err
  59. }
  60. // Name returns the name for the Fs implementation
  61. func (fs GCSFs) Name() string {
  62. return fmt.Sprintf("GCSFs bucket: %#v", fs.config.Bucket)
  63. }
  64. // ConnectionID returns the SSH connection ID associated to this Fs implementation
  65. func (fs GCSFs) ConnectionID() string {
  66. return fs.connectionID
  67. }
  68. // Stat returns a FileInfo describing the named file
  69. func (fs GCSFs) Stat(name string) (os.FileInfo, error) {
  70. var result FileInfo
  71. var err error
  72. if len(name) == 0 || name == "." {
  73. err := fs.checkIfBucketExists()
  74. if err != nil {
  75. return result, err
  76. }
  77. return NewFileInfo(name, true, 0, time.Now(), false), nil
  78. }
  79. if fs.config.KeyPrefix == name+"/" {
  80. return NewFileInfo(name, true, 0, time.Now(), false), nil
  81. }
  82. prefix := fs.getPrefixForStat(name)
  83. query := &storage.Query{Prefix: prefix, Delimiter: "/"}
  84. err = query.SetAttrSelection(gcsDefaultFieldsSelection)
  85. if err != nil {
  86. return nil, err
  87. }
  88. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  89. defer cancelFn()
  90. bkt := fs.svc.Bucket(fs.config.Bucket)
  91. it := bkt.Objects(ctx, query)
  92. for {
  93. attrs, err := it.Next()
  94. if err == iterator.Done {
  95. break
  96. }
  97. if err != nil {
  98. metrics.GCSListObjectsCompleted(err)
  99. return result, err
  100. }
  101. if len(attrs.Prefix) > 0 {
  102. if fs.isEqual(attrs.Prefix, name) {
  103. result = NewFileInfo(name, true, 0, time.Now(), false)
  104. break
  105. }
  106. } else {
  107. if !attrs.Deleted.IsZero() {
  108. continue
  109. }
  110. if fs.isEqual(attrs.Name, name) {
  111. isDir := strings.HasSuffix(attrs.Name, "/")
  112. result = NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false)
  113. break
  114. }
  115. }
  116. }
  117. metrics.GCSListObjectsCompleted(nil)
  118. if len(result.Name()) == 0 {
  119. err = errors.New("404 no such file or directory")
  120. }
  121. return result, err
  122. }
  123. // Lstat returns a FileInfo describing the named file
  124. func (fs GCSFs) Lstat(name string) (os.FileInfo, error) {
  125. return fs.Stat(name)
  126. }
  127. // Open opens the named file for reading
  128. func (fs GCSFs) Open(name string, offset int64) (*os.File, *pipeat.PipeReaderAt, func(), error) {
  129. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  130. if err != nil {
  131. return nil, nil, nil, err
  132. }
  133. bkt := fs.svc.Bucket(fs.config.Bucket)
  134. obj := bkt.Object(name)
  135. ctx, cancelFn := context.WithCancel(context.Background())
  136. objectReader, err := obj.NewRangeReader(ctx, offset, -1)
  137. if err == nil && offset > 0 && objectReader.Attrs.ContentEncoding == "gzip" {
  138. err = fmt.Errorf("Range request is not possible for gzip content encoding, requested offset %v", offset)
  139. objectReader.Close()
  140. }
  141. if err != nil {
  142. r.Close()
  143. w.Close()
  144. cancelFn()
  145. return nil, nil, nil, err
  146. }
  147. go func() {
  148. defer cancelFn()
  149. defer objectReader.Close()
  150. n, err := io.Copy(w, objectReader)
  151. w.CloseWithError(err) //nolint:errcheck
  152. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  153. metrics.GCSTransferCompleted(n, 1, err)
  154. }()
  155. return nil, r, cancelFn, nil
  156. }
  157. // Create creates or opens the named file for writing
  158. func (fs GCSFs) Create(name string, flag int) (*os.File, *PipeWriter, func(), error) {
  159. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  160. if err != nil {
  161. return nil, nil, nil, err
  162. }
  163. p := NewPipeWriter(w)
  164. bkt := fs.svc.Bucket(fs.config.Bucket)
  165. obj := bkt.Object(name)
  166. ctx, cancelFn := context.WithCancel(context.Background())
  167. objectWriter := obj.NewWriter(ctx)
  168. contentType := mime.TypeByExtension(path.Ext(name))
  169. if contentType != "" {
  170. objectWriter.ObjectAttrs.ContentType = contentType
  171. }
  172. if len(fs.config.StorageClass) > 0 {
  173. objectWriter.ObjectAttrs.StorageClass = fs.config.StorageClass
  174. }
  175. go func() {
  176. defer cancelFn()
  177. defer objectWriter.Close()
  178. n, err := io.Copy(objectWriter, r)
  179. r.CloseWithError(err) //nolint:errcheck
  180. p.Done(err)
  181. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v", name, n, err)
  182. metrics.GCSTransferCompleted(n, 0, err)
  183. }()
  184. return nil, p, cancelFn, nil
  185. }
  186. // Rename renames (moves) source to target.
  187. // We don't support renaming non empty directories since we should
  188. // rename all the contents too and this could take long time: think
  189. // about directories with thousands of files, for each file we should
  190. // execute a CopyObject call.
  191. func (fs GCSFs) Rename(source, target string) error {
  192. if source == target {
  193. return nil
  194. }
  195. fi, err := fs.Stat(source)
  196. if err != nil {
  197. return err
  198. }
  199. if fi.IsDir() {
  200. contents, err := fs.ReadDir(source)
  201. if err != nil {
  202. return err
  203. }
  204. if len(contents) > 0 {
  205. return fmt.Errorf("Cannot rename non empty directory: %#v", source)
  206. }
  207. if !strings.HasSuffix(source, "/") {
  208. source += "/"
  209. }
  210. if !strings.HasSuffix(target, "/") {
  211. target += "/"
  212. }
  213. }
  214. src := fs.svc.Bucket(fs.config.Bucket).Object(source)
  215. dst := fs.svc.Bucket(fs.config.Bucket).Object(target)
  216. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  217. defer cancelFn()
  218. copier := dst.CopierFrom(src)
  219. if len(fs.config.StorageClass) > 0 {
  220. copier.StorageClass = fs.config.StorageClass
  221. }
  222. _, err = copier.Run(ctx)
  223. metrics.GCSCopyObjectCompleted(err)
  224. if err != nil {
  225. return err
  226. }
  227. return fs.Remove(source, fi.IsDir())
  228. }
  229. // Remove removes the named file or (empty) directory.
  230. func (fs GCSFs) Remove(name string, isDir bool) error {
  231. if isDir {
  232. contents, err := fs.ReadDir(name)
  233. if err != nil {
  234. return err
  235. }
  236. if len(contents) > 0 {
  237. return fmt.Errorf("Cannot remove non empty directory: %#v", name)
  238. }
  239. if !strings.HasSuffix(name, "/") {
  240. name += "/"
  241. }
  242. }
  243. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  244. defer cancelFn()
  245. err := fs.svc.Bucket(fs.config.Bucket).Object(name).Delete(ctx)
  246. metrics.GCSDeleteObjectCompleted(err)
  247. return err
  248. }
  249. // Mkdir creates a new directory with the specified name and default permissions
  250. func (fs GCSFs) Mkdir(name string) error {
  251. _, err := fs.Stat(name)
  252. if !fs.IsNotExist(err) {
  253. return err
  254. }
  255. if !strings.HasSuffix(name, "/") {
  256. name += "/"
  257. }
  258. _, w, _, err := fs.Create(name, 0)
  259. if err != nil {
  260. return err
  261. }
  262. return w.Close()
  263. }
  264. // Symlink creates source as a symbolic link to target.
  265. func (GCSFs) Symlink(source, target string) error {
  266. return errors.New("403 symlinks are not supported")
  267. }
  268. // Readlink returns the destination of the named symbolic link
  269. func (GCSFs) Readlink(name string) (string, error) {
  270. return "", errors.New("403 readlink is not supported")
  271. }
  272. // Chown changes the numeric uid and gid of the named file.
  273. // Silently ignored.
  274. func (GCSFs) Chown(name string, uid int, gid int) error {
  275. return nil
  276. }
  277. // Chmod changes the mode of the named file to mode.
  278. // Silently ignored.
  279. func (GCSFs) Chmod(name string, mode os.FileMode) error {
  280. return nil
  281. }
  282. // Chtimes changes the access and modification times of the named file.
  283. // Silently ignored.
  284. func (GCSFs) Chtimes(name string, atime, mtime time.Time) error {
  285. return errors.New("403 chtimes is not supported")
  286. }
  287. // Truncate changes the size of the named file.
  288. // Truncate by path is not supported, while truncating an opened
  289. // file is handled inside base transfer
  290. func (GCSFs) Truncate(name string, size int64) error {
  291. return errors.New("403 truncate is not supported")
  292. }
  293. // ReadDir reads the directory named by dirname and returns
  294. // a list of directory entries.
  295. func (fs GCSFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  296. var result []os.FileInfo
  297. // dirname must be already cleaned
  298. prefix := ""
  299. if len(dirname) > 0 && dirname != "." {
  300. prefix = strings.TrimPrefix(dirname, "/")
  301. if !strings.HasSuffix(prefix, "/") {
  302. prefix += "/"
  303. }
  304. }
  305. query := &storage.Query{Prefix: prefix, Delimiter: "/"}
  306. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  307. if err != nil {
  308. return nil, err
  309. }
  310. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  311. defer cancelFn()
  312. bkt := fs.svc.Bucket(fs.config.Bucket)
  313. it := bkt.Objects(ctx, query)
  314. for {
  315. attrs, err := it.Next()
  316. if err == iterator.Done {
  317. break
  318. }
  319. if err != nil {
  320. metrics.GCSListObjectsCompleted(err)
  321. return result, err
  322. }
  323. if len(attrs.Prefix) > 0 {
  324. name, _ := fs.resolve(attrs.Prefix, prefix)
  325. result = append(result, NewFileInfo(name, true, 0, time.Now(), false))
  326. } else {
  327. name, isDir := fs.resolve(attrs.Name, prefix)
  328. if len(name) == 0 {
  329. continue
  330. }
  331. if !attrs.Deleted.IsZero() {
  332. continue
  333. }
  334. fi := NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false)
  335. result = append(result, fi)
  336. }
  337. }
  338. metrics.GCSListObjectsCompleted(nil)
  339. return result, nil
  340. }
  341. // IsUploadResumeSupported returns true if upload resume is supported.
  342. // SFTP Resume is not supported on S3
  343. func (GCSFs) IsUploadResumeSupported() bool {
  344. return false
  345. }
  346. // IsAtomicUploadSupported returns true if atomic upload is supported.
  347. // S3 uploads are already atomic, we don't need to upload to a temporary
  348. // file
  349. func (GCSFs) IsAtomicUploadSupported() bool {
  350. return false
  351. }
  352. // IsNotExist returns a boolean indicating whether the error is known to
  353. // report that a file or directory does not exist
  354. func (GCSFs) IsNotExist(err error) bool {
  355. if err == nil {
  356. return false
  357. }
  358. if err == storage.ErrObjectNotExist || err == storage.ErrBucketNotExist {
  359. return true
  360. }
  361. if e, ok := err.(*googleapi.Error); ok {
  362. if e.Code == http.StatusNotFound {
  363. return true
  364. }
  365. }
  366. return strings.Contains(err.Error(), "404")
  367. }
  368. // IsPermission returns a boolean indicating whether the error is known to
  369. // report that permission is denied.
  370. func (GCSFs) IsPermission(err error) bool {
  371. if err == nil {
  372. return false
  373. }
  374. if e, ok := err.(*googleapi.Error); ok {
  375. if e.Code == http.StatusForbidden || e.Code == http.StatusUnauthorized {
  376. return true
  377. }
  378. }
  379. return strings.Contains(err.Error(), "403")
  380. }
  381. // CheckRootPath creates the specified local root directory if it does not exists
  382. func (fs GCSFs) CheckRootPath(username string, uid int, gid int) bool {
  383. // we need a local directory for temporary files
  384. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, nil)
  385. return osFs.CheckRootPath(username, uid, gid)
  386. }
  387. // ScanRootDirContents returns the number of files contained in the bucket,
  388. // and their size
  389. func (fs GCSFs) ScanRootDirContents() (int, int64, error) {
  390. numFiles := 0
  391. size := int64(0)
  392. query := &storage.Query{Prefix: fs.config.KeyPrefix}
  393. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  394. if err != nil {
  395. return numFiles, size, err
  396. }
  397. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  398. defer cancelFn()
  399. bkt := fs.svc.Bucket(fs.config.Bucket)
  400. it := bkt.Objects(ctx, query)
  401. for {
  402. attrs, err := it.Next()
  403. if err == iterator.Done {
  404. break
  405. }
  406. if err != nil {
  407. metrics.GCSListObjectsCompleted(err)
  408. return numFiles, size, err
  409. }
  410. if !attrs.Deleted.IsZero() {
  411. continue
  412. }
  413. numFiles++
  414. size += attrs.Size
  415. }
  416. metrics.GCSListObjectsCompleted(nil)
  417. return numFiles, size, err
  418. }
  419. // GetDirSize returns the number of files and the size for a folder
  420. // including any subfolders
  421. func (GCSFs) GetDirSize(dirname string) (int, int64, error) {
  422. return 0, 0, errUnsupported
  423. }
  424. // GetAtomicUploadPath returns the path to use for an atomic upload.
  425. // S3 uploads are already atomic, we never call this method for S3
  426. func (GCSFs) GetAtomicUploadPath(name string) string {
  427. return ""
  428. }
  429. // GetRelativePath returns the path for a file relative to the user's home dir.
  430. // This is the path as seen by SFTP users
  431. func (fs GCSFs) GetRelativePath(name string) string {
  432. rel := path.Clean(name)
  433. if rel == "." {
  434. rel = ""
  435. }
  436. if !path.IsAbs(rel) {
  437. rel = "/" + rel
  438. }
  439. if len(fs.config.KeyPrefix) > 0 {
  440. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  441. rel = "/"
  442. }
  443. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  444. }
  445. return rel
  446. }
  447. // Walk walks the file tree rooted at root, calling walkFn for each file or
  448. // directory in the tree, including root
  449. func (fs GCSFs) Walk(root string, walkFn filepath.WalkFunc) error {
  450. prefix := ""
  451. if len(root) > 0 && root != "." {
  452. prefix = strings.TrimPrefix(root, "/")
  453. if !strings.HasSuffix(prefix, "/") {
  454. prefix += "/"
  455. }
  456. }
  457. query := &storage.Query{Prefix: prefix}
  458. err := query.SetAttrSelection(gcsDefaultFieldsSelection)
  459. if err != nil {
  460. walkFn(root, nil, err) //nolint:errcheck
  461. return err
  462. }
  463. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  464. defer cancelFn()
  465. bkt := fs.svc.Bucket(fs.config.Bucket)
  466. it := bkt.Objects(ctx, query)
  467. for {
  468. attrs, err := it.Next()
  469. if err == iterator.Done {
  470. break
  471. }
  472. if err != nil {
  473. walkFn(root, nil, err) //nolint:errcheck
  474. metrics.GCSListObjectsCompleted(err)
  475. return err
  476. }
  477. if !attrs.Deleted.IsZero() {
  478. continue
  479. }
  480. isDir := strings.HasSuffix(attrs.Name, "/")
  481. name := path.Clean(attrs.Name)
  482. if len(name) == 0 {
  483. continue
  484. }
  485. err = walkFn(attrs.Name, NewFileInfo(name, isDir, attrs.Size, attrs.Updated, false), nil)
  486. if err != nil {
  487. break
  488. }
  489. }
  490. walkFn(root, NewFileInfo(root, true, 0, time.Now(), false), err) //nolint:errcheck
  491. metrics.GCSListObjectsCompleted(err)
  492. return err
  493. }
  494. // Join joins any number of path elements into a single path
  495. func (GCSFs) Join(elem ...string) string {
  496. return strings.TrimPrefix(path.Join(elem...), "/")
  497. }
  498. // HasVirtualFolders returns true if folders are emulated
  499. func (GCSFs) HasVirtualFolders() bool {
  500. return true
  501. }
  502. // ResolvePath returns the matching filesystem path for the specified sftp path
  503. func (fs GCSFs) ResolvePath(sftpPath string) (string, error) {
  504. if !path.IsAbs(sftpPath) {
  505. sftpPath = path.Clean("/" + sftpPath)
  506. }
  507. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(sftpPath, "/")), nil
  508. }
  509. func (fs *GCSFs) resolve(name string, prefix string) (string, bool) {
  510. result := strings.TrimPrefix(name, prefix)
  511. isDir := strings.HasSuffix(result, "/")
  512. if isDir {
  513. result = strings.TrimSuffix(result, "/")
  514. }
  515. return result, isDir
  516. }
  517. func (fs *GCSFs) isEqual(key string, sftpName string) bool {
  518. if key == sftpName {
  519. return true
  520. }
  521. if key == sftpName+"/" {
  522. return true
  523. }
  524. if key+"/" == sftpName {
  525. return true
  526. }
  527. return false
  528. }
  529. func (fs *GCSFs) checkIfBucketExists() error {
  530. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  531. defer cancelFn()
  532. bkt := fs.svc.Bucket(fs.config.Bucket)
  533. _, err := bkt.Attrs(ctx)
  534. metrics.GCSHeadBucketCompleted(err)
  535. return err
  536. }
  537. func (fs *GCSFs) getPrefixForStat(name string) string {
  538. prefix := path.Dir(name)
  539. if prefix == "/" || prefix == "." || len(prefix) == 0 {
  540. prefix = ""
  541. } else {
  542. prefix = strings.TrimPrefix(prefix, "/")
  543. if !strings.HasSuffix(prefix, "/") {
  544. prefix += "/"
  545. }
  546. }
  547. return prefix
  548. }
  549. // GetMimeType implements MimeTyper interface
  550. func (fs GCSFs) GetMimeType(name string) (string, error) {
  551. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  552. defer cancelFn()
  553. bkt := fs.svc.Bucket(fs.config.Bucket)
  554. obj := bkt.Object(name)
  555. attrs, err := obj.Attrs(ctx)
  556. if err != nil {
  557. return "", err
  558. }
  559. return attrs.ContentType, nil
  560. }