gcsfs.go 14 KB

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