gcsfs.go 14 KB

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