azblobfs.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. // +build !noazblob
  2. package vfs
  3. import (
  4. "bytes"
  5. "context"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Azure/azure-storage-blob-go/azblob"
  20. "github.com/eikenb/pipeat"
  21. "github.com/pkg/sftp"
  22. "github.com/drakkan/sftpgo/logger"
  23. "github.com/drakkan/sftpgo/metrics"
  24. "github.com/drakkan/sftpgo/version"
  25. )
  26. const azureDefaultEndpoint = "blob.core.windows.net"
  27. // max time of an azure web request response window (whether or not data is flowing)
  28. // this is the same value used in rclone
  29. var maxTryTimeout = time.Hour * 24 * 365
  30. // AzureBlobFs is a Fs implementation for Azure Blob storage.
  31. type AzureBlobFs struct {
  32. connectionID string
  33. localTempDir string
  34. config *AzBlobFsConfig
  35. svc *azblob.ServiceURL
  36. containerURL azblob.ContainerURL
  37. ctxTimeout time.Duration
  38. ctxLongTimeout time.Duration
  39. }
  40. func init() {
  41. version.AddFeature("+azblob")
  42. }
  43. // NewAzBlobFs returns an AzBlobFs object that allows to interact with Azure Blob storage
  44. func NewAzBlobFs(connectionID, localTempDir string, config AzBlobFsConfig) (Fs, error) {
  45. fs := &AzureBlobFs{
  46. connectionID: connectionID,
  47. localTempDir: localTempDir,
  48. config: &config,
  49. ctxTimeout: 30 * time.Second,
  50. ctxLongTimeout: 300 * time.Second,
  51. }
  52. if err := fs.config.Validate(); err != nil {
  53. return fs, err
  54. }
  55. if fs.config.AccountKey.IsEncrypted() {
  56. err := fs.config.AccountKey.Decrypt()
  57. if err != nil {
  58. return fs, err
  59. }
  60. }
  61. fs.setConfigDefaults()
  62. version := version.Get()
  63. telemetryValue := fmt.Sprintf("SFTPGo-%v_%v", version.Version, version.CommitHash)
  64. if fs.config.SASURL != "" {
  65. u, err := url.Parse(fs.config.SASURL)
  66. if err != nil {
  67. return fs, fmt.Errorf("invalid credentials: %v", err)
  68. }
  69. pipeline := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{
  70. Retry: azblob.RetryOptions{
  71. TryTimeout: maxTryTimeout,
  72. },
  73. Telemetry: azblob.TelemetryOptions{
  74. Value: telemetryValue,
  75. },
  76. })
  77. // Check if we have container level SAS or account level SAS
  78. parts := azblob.NewBlobURLParts(*u)
  79. if parts.ContainerName != "" {
  80. if fs.config.Container != "" && fs.config.Container != parts.ContainerName {
  81. return fs, fmt.Errorf("Container name in SAS URL %#v and container provided %#v do not match",
  82. parts.ContainerName, fs.config.Container)
  83. }
  84. fs.svc = nil
  85. fs.containerURL = azblob.NewContainerURL(*u, pipeline)
  86. } else {
  87. if fs.config.Container == "" {
  88. return fs, errors.New("container is required with this SAS URL")
  89. }
  90. serviceURL := azblob.NewServiceURL(*u, pipeline)
  91. fs.svc = &serviceURL
  92. fs.containerURL = fs.svc.NewContainerURL(fs.config.Container)
  93. }
  94. return fs, nil
  95. }
  96. credential, err := azblob.NewSharedKeyCredential(fs.config.AccountName, fs.config.AccountKey.GetPayload())
  97. if err != nil {
  98. return fs, fmt.Errorf("invalid credentials: %v", err)
  99. }
  100. var u *url.URL
  101. if fs.config.UseEmulator {
  102. // for the emulator we expect the endpoint prefixed with the protocol, for example:
  103. // http://127.0.0.1:10000
  104. u, err = url.Parse(fmt.Sprintf("%s/%s", fs.config.Endpoint, fs.config.AccountName))
  105. } else {
  106. u, err = url.Parse(fmt.Sprintf("https://%s.%s", fs.config.AccountName, fs.config.Endpoint))
  107. }
  108. if err != nil {
  109. return fs, fmt.Errorf("invalid credentials: %v", err)
  110. }
  111. pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{
  112. Retry: azblob.RetryOptions{
  113. TryTimeout: maxTryTimeout,
  114. },
  115. Telemetry: azblob.TelemetryOptions{
  116. Value: telemetryValue,
  117. },
  118. })
  119. serviceURL := azblob.NewServiceURL(*u, pipeline)
  120. fs.svc = &serviceURL
  121. fs.containerURL = fs.svc.NewContainerURL(fs.config.Container)
  122. return fs, nil
  123. }
  124. // Name returns the name for the Fs implementation
  125. func (fs *AzureBlobFs) Name() string {
  126. if fs.config.SASURL != "" {
  127. return fmt.Sprintf("Azure Blob SAS URL %#v", fs.config.Container)
  128. }
  129. return fmt.Sprintf("Azure Blob container %#v", fs.config.Container)
  130. }
  131. // ConnectionID returns the connection ID associated to this Fs implementation
  132. func (fs *AzureBlobFs) ConnectionID() string {
  133. return fs.connectionID
  134. }
  135. // Stat returns a FileInfo describing the named file
  136. func (fs *AzureBlobFs) Stat(name string) (os.FileInfo, error) {
  137. if name == "" || name == "." {
  138. if fs.svc != nil {
  139. err := fs.checkIfBucketExists()
  140. if err != nil {
  141. return nil, err
  142. }
  143. }
  144. return NewFileInfo(name, true, 0, time.Now(), false), nil
  145. }
  146. if fs.config.KeyPrefix == name+"/" {
  147. return NewFileInfo(name, true, 0, time.Now(), false), nil
  148. }
  149. attrs, err := fs.headObject(name)
  150. if err == nil {
  151. isDir := (attrs.ContentType() == dirMimeType)
  152. metrics.AZListObjectsCompleted(nil)
  153. return NewFileInfo(name, isDir, attrs.ContentLength(), attrs.LastModified(), false), nil
  154. }
  155. if !fs.IsNotExist(err) {
  156. return nil, err
  157. }
  158. // now check if this is a prefix (virtual directory)
  159. hasContents, err := fs.hasContents(name)
  160. if err != nil {
  161. return nil, err
  162. }
  163. if hasContents {
  164. return NewFileInfo(name, true, 0, time.Now(), false), nil
  165. }
  166. return nil, errors.New("404 no such file or directory")
  167. }
  168. // Lstat returns a FileInfo describing the named file
  169. func (fs *AzureBlobFs) Lstat(name string) (os.FileInfo, error) {
  170. return fs.Stat(name)
  171. }
  172. // Open opens the named file for reading
  173. func (fs *AzureBlobFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  174. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  175. if err != nil {
  176. return nil, nil, nil, err
  177. }
  178. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  179. ctx, cancelFn := context.WithCancel(context.Background())
  180. blobDownloadResponse, err := blobBlockURL.Download(ctx, offset, azblob.CountToEnd, azblob.BlobAccessConditions{}, false,
  181. azblob.ClientProvidedKeyOptions{})
  182. if err != nil {
  183. r.Close()
  184. w.Close()
  185. cancelFn()
  186. return nil, nil, nil, err
  187. }
  188. body := blobDownloadResponse.Body(azblob.RetryReaderOptions{
  189. MaxRetryRequests: 3,
  190. })
  191. go func() {
  192. defer cancelFn()
  193. defer body.Close()
  194. n, err := io.Copy(w, body)
  195. w.CloseWithError(err) //nolint:errcheck
  196. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  197. metrics.AZTransferCompleted(n, 1, err)
  198. }()
  199. return nil, r, cancelFn, nil
  200. }
  201. // Create creates or opens the named file for writing
  202. func (fs *AzureBlobFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  203. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  204. if err != nil {
  205. return nil, nil, nil, err
  206. }
  207. p := NewPipeWriter(w)
  208. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  209. ctx, cancelFn := context.WithCancel(context.Background())
  210. headers := azblob.BlobHTTPHeaders{}
  211. var contentType string
  212. if flag == -1 {
  213. contentType = dirMimeType
  214. } else {
  215. contentType = mime.TypeByExtension(path.Ext(name))
  216. }
  217. if contentType != "" {
  218. headers.ContentType = contentType
  219. }
  220. go func() {
  221. defer cancelFn()
  222. /*uploadOptions := azblob.UploadStreamToBlockBlobOptions{
  223. BufferSize: int(fs.config.UploadPartSize),
  224. BlobHTTPHeaders: headers,
  225. MaxBuffers: fs.config.UploadConcurrency,
  226. }
  227. // UploadStreamToBlockBlob seems to have issues if there is an error, for example
  228. // if we shutdown Azurite while uploading it hangs, so we use our own wrapper for
  229. // the low level functions
  230. _, err := azblob.UploadStreamToBlockBlob(ctx, r, blobBlockURL, uploadOptions)*/
  231. err := fs.handleMultipartUpload(ctx, r, blobBlockURL, headers)
  232. r.CloseWithError(err) //nolint:errcheck
  233. p.Done(err)
  234. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v", name, r.GetReadedBytes(), err)
  235. metrics.AZTransferCompleted(r.GetReadedBytes(), 0, err)
  236. }()
  237. return nil, p, cancelFn, nil
  238. }
  239. // Rename renames (moves) source to target.
  240. // We don't support renaming non empty directories since we should
  241. // rename all the contents too and this could take long time: think
  242. // about directories with thousands of files, for each file we should
  243. // execute a StartCopyFromURL call.
  244. func (fs *AzureBlobFs) Rename(source, target string) error {
  245. if source == target {
  246. return nil
  247. }
  248. fi, err := fs.Stat(source)
  249. if err != nil {
  250. return err
  251. }
  252. if fi.IsDir() {
  253. hasContents, err := fs.hasContents(source)
  254. if err != nil {
  255. return err
  256. }
  257. if hasContents {
  258. return fmt.Errorf("Cannot rename non empty directory: %#v", source)
  259. }
  260. }
  261. dstBlobURL := fs.containerURL.NewBlobURL(target)
  262. srcURL := fs.containerURL.NewBlobURL(source).URL()
  263. md := azblob.Metadata{}
  264. mac := azblob.ModifiedAccessConditions{}
  265. bac := azblob.BlobAccessConditions{}
  266. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  267. defer cancelFn()
  268. resp, err := dstBlobURL.StartCopyFromURL(ctx, srcURL, md, mac, bac, azblob.AccessTierType(fs.config.AccessTier), nil)
  269. if err != nil {
  270. metrics.AZCopyObjectCompleted(err)
  271. return err
  272. }
  273. copyStatus := resp.CopyStatus()
  274. nErrors := 0
  275. for copyStatus == azblob.CopyStatusPending {
  276. // Poll until the copy is complete.
  277. time.Sleep(500 * time.Millisecond)
  278. propertiesResp, err := dstBlobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
  279. if err != nil {
  280. // A GetProperties failure may be transient, so allow a couple
  281. // of them before giving up.
  282. nErrors++
  283. if ctx.Err() != nil || nErrors == 3 {
  284. metrics.AZCopyObjectCompleted(err)
  285. return err
  286. }
  287. } else {
  288. copyStatus = propertiesResp.CopyStatus()
  289. }
  290. }
  291. if copyStatus != azblob.CopyStatusSuccess {
  292. err := fmt.Errorf("Copy failed with status: %s", copyStatus)
  293. metrics.AZCopyObjectCompleted(err)
  294. return err
  295. }
  296. metrics.AZCopyObjectCompleted(nil)
  297. return fs.Remove(source, fi.IsDir())
  298. }
  299. // Remove removes the named file or (empty) directory.
  300. func (fs *AzureBlobFs) Remove(name string, isDir bool) error {
  301. if isDir {
  302. hasContents, err := fs.hasContents(name)
  303. if err != nil {
  304. return err
  305. }
  306. if hasContents {
  307. return fmt.Errorf("Cannot remove non empty directory: %#v", name)
  308. }
  309. }
  310. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  311. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  312. defer cancelFn()
  313. _, err := blobBlockURL.Delete(ctx, azblob.DeleteSnapshotsOptionNone, azblob.BlobAccessConditions{})
  314. metrics.AZDeleteObjectCompleted(err)
  315. return err
  316. }
  317. // Mkdir creates a new directory with the specified name and default permissions
  318. func (fs *AzureBlobFs) Mkdir(name string) error {
  319. _, err := fs.Stat(name)
  320. if !fs.IsNotExist(err) {
  321. return err
  322. }
  323. _, w, _, err := fs.Create(name, -1)
  324. if err != nil {
  325. return err
  326. }
  327. return w.Close()
  328. }
  329. // Symlink creates source as a symbolic link to target.
  330. func (*AzureBlobFs) Symlink(source, target string) error {
  331. return ErrVfsUnsupported
  332. }
  333. // Readlink returns the destination of the named symbolic link
  334. func (*AzureBlobFs) Readlink(name string) (string, error) {
  335. return "", ErrVfsUnsupported
  336. }
  337. // Chown changes the numeric uid and gid of the named file.
  338. func (*AzureBlobFs) Chown(name string, uid int, gid int) error {
  339. return ErrVfsUnsupported
  340. }
  341. // Chmod changes the mode of the named file to mode.
  342. func (*AzureBlobFs) Chmod(name string, mode os.FileMode) error {
  343. return ErrVfsUnsupported
  344. }
  345. // Chtimes changes the access and modification times of the named file.
  346. func (*AzureBlobFs) Chtimes(name string, atime, mtime time.Time) error {
  347. return ErrVfsUnsupported
  348. }
  349. // Truncate changes the size of the named file.
  350. // Truncate by path is not supported, while truncating an opened
  351. // file is handled inside base transfer
  352. func (*AzureBlobFs) Truncate(name string, size int64) error {
  353. return ErrVfsUnsupported
  354. }
  355. // ReadDir reads the directory named by dirname and returns
  356. // a list of directory entries.
  357. func (fs *AzureBlobFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  358. var result []os.FileInfo
  359. // dirname must be already cleaned
  360. prefix := ""
  361. if dirname != "" && dirname != "." {
  362. prefix = strings.TrimPrefix(dirname, "/")
  363. if !strings.HasSuffix(prefix, "/") {
  364. prefix += "/"
  365. }
  366. }
  367. prefixes := make(map[string]bool)
  368. for marker := (azblob.Marker{}); marker.NotDone(); {
  369. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  370. defer cancelFn()
  371. listBlob, err := fs.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
  372. Details: azblob.BlobListingDetails{
  373. Copy: false,
  374. Metadata: false,
  375. Snapshots: false,
  376. UncommittedBlobs: false,
  377. Deleted: false,
  378. },
  379. Prefix: prefix,
  380. })
  381. if err != nil {
  382. metrics.AZListObjectsCompleted(err)
  383. return nil, err
  384. }
  385. marker = listBlob.NextMarker
  386. for _, blobPrefix := range listBlob.Segment.BlobPrefixes {
  387. // we don't support prefixes == "/" this will be sent if a key starts with "/"
  388. if blobPrefix.Name == "/" {
  389. continue
  390. }
  391. // sometime we have duplicate prefixes, maybe an Azurite bug
  392. name := strings.TrimPrefix(blobPrefix.Name, prefix)
  393. if _, ok := prefixes[strings.TrimSuffix(name, "/")]; ok {
  394. continue
  395. }
  396. result = append(result, NewFileInfo(name, true, 0, time.Now(), false))
  397. prefixes[strings.TrimSuffix(name, "/")] = true
  398. }
  399. for _, blobInfo := range listBlob.Segment.BlobItems {
  400. name := strings.TrimPrefix(blobInfo.Name, prefix)
  401. size := int64(0)
  402. if blobInfo.Properties.ContentLength != nil {
  403. size = *blobInfo.Properties.ContentLength
  404. }
  405. isDir := false
  406. if blobInfo.Properties.ContentType != nil {
  407. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  408. if isDir {
  409. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  410. if _, ok := prefixes[name]; ok {
  411. continue
  412. }
  413. prefixes[name] = true
  414. }
  415. }
  416. result = append(result, NewFileInfo(name, isDir, size, blobInfo.Properties.LastModified, false))
  417. }
  418. }
  419. metrics.AZListObjectsCompleted(nil)
  420. return result, nil
  421. }
  422. // IsUploadResumeSupported returns true if upload resume is supported.
  423. // Upload Resume is not supported on Azure Blob
  424. func (*AzureBlobFs) IsUploadResumeSupported() bool {
  425. return false
  426. }
  427. // IsAtomicUploadSupported returns true if atomic upload is supported.
  428. // Azure Blob uploads are already atomic, we don't need to upload to a temporary
  429. // file
  430. func (*AzureBlobFs) IsAtomicUploadSupported() bool {
  431. return false
  432. }
  433. // IsNotExist returns a boolean indicating whether the error is known to
  434. // report that a file or directory does not exist
  435. func (*AzureBlobFs) IsNotExist(err error) bool {
  436. if err == nil {
  437. return false
  438. }
  439. if storageErr, ok := err.(azblob.StorageError); ok {
  440. if storageErr.Response().StatusCode == http.StatusNotFound { //nolint:bodyclose
  441. return true
  442. }
  443. if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
  444. storageErr.ServiceCode() == azblob.ServiceCodeBlobNotFound {
  445. return true
  446. }
  447. }
  448. return strings.Contains(err.Error(), "404")
  449. }
  450. // IsPermission returns a boolean indicating whether the error is known to
  451. // report that permission is denied.
  452. func (*AzureBlobFs) IsPermission(err error) bool {
  453. if err == nil {
  454. return false
  455. }
  456. if storageErr, ok := err.(azblob.StorageError); ok {
  457. code := storageErr.Response().StatusCode //nolint:bodyclose
  458. if code == http.StatusForbidden || code == http.StatusUnauthorized {
  459. return true
  460. }
  461. if storageErr.ServiceCode() == azblob.ServiceCodeInsufficientAccountPermissions ||
  462. storageErr.ServiceCode() == azblob.ServiceCodeInvalidAuthenticationInfo ||
  463. storageErr.ServiceCode() == azblob.ServiceCodeUnauthorizedBlobOverwrite {
  464. return true
  465. }
  466. }
  467. return strings.Contains(err.Error(), "403")
  468. }
  469. // IsNotSupported returns true if the error indicate an unsupported operation
  470. func (*AzureBlobFs) IsNotSupported(err error) bool {
  471. if err == nil {
  472. return false
  473. }
  474. return err == ErrVfsUnsupported
  475. }
  476. // CheckRootPath creates the specified local root directory if it does not exists
  477. func (fs *AzureBlobFs) CheckRootPath(username string, uid int, gid int) bool {
  478. // we need a local directory for temporary files
  479. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, nil)
  480. return osFs.CheckRootPath(username, uid, gid)
  481. }
  482. // ScanRootDirContents returns the number of files contained in the bucket,
  483. // and their size
  484. func (fs *AzureBlobFs) ScanRootDirContents() (int, int64, error) {
  485. numFiles := 0
  486. size := int64(0)
  487. for marker := (azblob.Marker{}); marker.NotDone(); {
  488. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  489. defer cancelFn()
  490. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{
  491. Details: azblob.BlobListingDetails{
  492. Copy: false,
  493. Metadata: false,
  494. Snapshots: false,
  495. UncommittedBlobs: false,
  496. Deleted: false,
  497. },
  498. Prefix: fs.config.KeyPrefix,
  499. })
  500. if err != nil {
  501. metrics.AZListObjectsCompleted(err)
  502. return numFiles, size, err
  503. }
  504. marker = listBlob.NextMarker
  505. for _, blobInfo := range listBlob.Segment.BlobItems {
  506. isDir := false
  507. if blobInfo.Properties.ContentType != nil {
  508. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  509. }
  510. blobSize := int64(0)
  511. if blobInfo.Properties.ContentLength != nil {
  512. blobSize = *blobInfo.Properties.ContentLength
  513. }
  514. if isDir && blobSize == 0 {
  515. continue
  516. }
  517. numFiles++
  518. size += blobSize
  519. }
  520. }
  521. metrics.AZListObjectsCompleted(nil)
  522. return numFiles, size, nil
  523. }
  524. // GetDirSize returns the number of files and the size for a folder
  525. // including any subfolders
  526. func (*AzureBlobFs) GetDirSize(dirname string) (int, int64, error) {
  527. return 0, 0, ErrVfsUnsupported
  528. }
  529. // GetAtomicUploadPath returns the path to use for an atomic upload.
  530. // Azure Blob Storage uploads are already atomic, we never call this method
  531. func (*AzureBlobFs) GetAtomicUploadPath(name string) string {
  532. return ""
  533. }
  534. // GetRelativePath returns the path for a file relative to the user's home dir.
  535. // This is the path as seen by SFTPGo users
  536. func (fs *AzureBlobFs) GetRelativePath(name string) string {
  537. rel := path.Clean(name)
  538. if rel == "." {
  539. rel = ""
  540. }
  541. if !path.IsAbs(rel) {
  542. rel = "/" + rel
  543. }
  544. if fs.config.KeyPrefix != "" {
  545. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  546. rel = "/"
  547. }
  548. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  549. }
  550. return rel
  551. }
  552. // Walk walks the file tree rooted at root, calling walkFn for each file or
  553. // directory in the tree, including root
  554. func (fs *AzureBlobFs) Walk(root string, walkFn filepath.WalkFunc) error {
  555. prefix := ""
  556. if root != "" && root != "." {
  557. prefix = strings.TrimPrefix(root, "/")
  558. if !strings.HasSuffix(prefix, "/") {
  559. prefix += "/"
  560. }
  561. }
  562. for marker := (azblob.Marker{}); marker.NotDone(); {
  563. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  564. defer cancelFn()
  565. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{
  566. Details: azblob.BlobListingDetails{
  567. Copy: false,
  568. Metadata: false,
  569. Snapshots: false,
  570. UncommittedBlobs: false,
  571. Deleted: false,
  572. },
  573. Prefix: prefix,
  574. })
  575. if err != nil {
  576. metrics.AZListObjectsCompleted(err)
  577. return err
  578. }
  579. marker = listBlob.NextMarker
  580. for _, blobInfo := range listBlob.Segment.BlobItems {
  581. isDir := false
  582. if blobInfo.Properties.ContentType != nil {
  583. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  584. }
  585. if fs.isEqual(blobInfo.Name, prefix) {
  586. continue
  587. }
  588. blobSize := int64(0)
  589. if blobInfo.Properties.ContentLength != nil {
  590. blobSize = *blobInfo.Properties.ContentLength
  591. }
  592. err = walkFn(blobInfo.Name, NewFileInfo(blobInfo.Name, isDir, blobSize, blobInfo.Properties.LastModified, false), nil)
  593. if err != nil {
  594. return err
  595. }
  596. }
  597. }
  598. metrics.AZListObjectsCompleted(nil)
  599. return walkFn(root, NewFileInfo(root, true, 0, time.Now(), false), nil)
  600. }
  601. // Join joins any number of path elements into a single path
  602. func (*AzureBlobFs) Join(elem ...string) string {
  603. return strings.TrimPrefix(path.Join(elem...), "/")
  604. }
  605. // HasVirtualFolders returns true if folders are emulated
  606. func (*AzureBlobFs) HasVirtualFolders() bool {
  607. return true
  608. }
  609. // ResolvePath returns the matching filesystem path for the specified sftp path
  610. func (fs *AzureBlobFs) ResolvePath(virtualPath string) (string, error) {
  611. if !path.IsAbs(virtualPath) {
  612. virtualPath = path.Clean("/" + virtualPath)
  613. }
  614. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  615. }
  616. func (fs *AzureBlobFs) headObject(name string) (*azblob.BlobGetPropertiesResponse, error) {
  617. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  618. defer cancelFn()
  619. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  620. response, err := blobBlockURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
  621. metrics.AZHeadObjectCompleted(err)
  622. return response, err
  623. }
  624. // GetMimeType returns the content type
  625. func (fs *AzureBlobFs) GetMimeType(name string) (string, error) {
  626. response, err := fs.headObject(name)
  627. if err != nil {
  628. return "", err
  629. }
  630. return response.ContentType(), nil
  631. }
  632. // Close closes the fs
  633. func (*AzureBlobFs) Close() error {
  634. return nil
  635. }
  636. // GetAvailableDiskSize return the available size for the specified path
  637. func (*AzureBlobFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  638. return nil, ErrStorageSizeUnavailable
  639. }
  640. func (fs *AzureBlobFs) isEqual(key string, virtualName string) bool {
  641. if key == virtualName {
  642. return true
  643. }
  644. if key == virtualName+"/" {
  645. return true
  646. }
  647. if key+"/" == virtualName {
  648. return true
  649. }
  650. return false
  651. }
  652. func (fs *AzureBlobFs) setConfigDefaults() {
  653. if fs.config.Endpoint == "" {
  654. fs.config.Endpoint = azureDefaultEndpoint
  655. }
  656. if fs.config.UploadPartSize == 0 {
  657. fs.config.UploadPartSize = 4
  658. }
  659. fs.config.UploadPartSize *= 1024 * 1024
  660. if fs.config.UploadConcurrency == 0 {
  661. fs.config.UploadConcurrency = 2
  662. }
  663. if fs.config.AccessTier == "" {
  664. fs.config.AccessTier = string(azblob.AccessTierNone)
  665. }
  666. }
  667. func (fs *AzureBlobFs) checkIfBucketExists() error {
  668. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  669. defer cancelFn()
  670. _, err := fs.containerURL.GetProperties(ctx, azblob.LeaseAccessConditions{})
  671. metrics.AZHeadContainerCompleted(err)
  672. return err
  673. }
  674. func (fs *AzureBlobFs) hasContents(name string) (bool, error) {
  675. result := false
  676. prefix := ""
  677. if name != "" && name != "." {
  678. prefix = strings.TrimPrefix(name, "/")
  679. if !strings.HasSuffix(prefix, "/") {
  680. prefix += "/"
  681. }
  682. }
  683. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  684. defer cancelFn()
  685. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, azblob.Marker{}, azblob.ListBlobsSegmentOptions{
  686. Details: azblob.BlobListingDetails{
  687. Copy: false,
  688. Metadata: false,
  689. Snapshots: false,
  690. UncommittedBlobs: false,
  691. Deleted: false,
  692. },
  693. Prefix: prefix,
  694. MaxResults: 1,
  695. })
  696. metrics.AZListObjectsCompleted(err)
  697. if err != nil {
  698. return result, err
  699. }
  700. result = len(listBlob.Segment.BlobItems) > 0
  701. return result, err
  702. }
  703. func (fs *AzureBlobFs) handleMultipartUpload(ctx context.Context, reader io.Reader, blockBlobURL azblob.BlockBlobURL,
  704. httpHeaders azblob.BlobHTTPHeaders) error {
  705. partSize := fs.config.UploadPartSize
  706. guard := make(chan struct{}, fs.config.UploadConcurrency)
  707. blockCtxTimeout := time.Duration(fs.config.UploadPartSize/(1024*1024)) * time.Minute
  708. // sync.Pool seems to use a lot of memory so prefer our own, very simple, allocator
  709. // we only need to recycle few byte slices
  710. pool := newBufferAllocator(int(partSize))
  711. finished := false
  712. binaryBlockID := make([]byte, 8)
  713. var blocks []string
  714. var wg sync.WaitGroup
  715. var errOnce sync.Once
  716. var poolError error
  717. poolCtx, poolCancel := context.WithCancel(ctx)
  718. defer poolCancel()
  719. for part := 0; !finished; part++ {
  720. buf := pool.getBuffer()
  721. n, err := fs.readFill(reader, buf)
  722. if err == io.EOF {
  723. // read finished, if n > 0 we need to process the last data chunck
  724. if n == 0 {
  725. pool.releaseBuffer(buf)
  726. break
  727. }
  728. finished = true
  729. } else if err != nil {
  730. pool.releaseBuffer(buf)
  731. pool.free()
  732. return err
  733. }
  734. fs.incrementBlockID(binaryBlockID)
  735. blockID := base64.StdEncoding.EncodeToString(binaryBlockID)
  736. blocks = append(blocks, blockID)
  737. guard <- struct{}{}
  738. if poolError != nil {
  739. fsLog(fs, logger.LevelDebug, "pool error, upload for part %v not started", part)
  740. pool.releaseBuffer(buf)
  741. break
  742. }
  743. wg.Add(1)
  744. go func(blockID string, buf []byte, bufSize int) {
  745. defer wg.Done()
  746. bufferReader := bytes.NewReader(buf[:bufSize])
  747. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  748. defer cancelFn()
  749. _, err := blockBlobURL.StageBlock(innerCtx, blockID, bufferReader, azblob.LeaseAccessConditions{}, nil,
  750. azblob.ClientProvidedKeyOptions{})
  751. if err != nil {
  752. errOnce.Do(func() {
  753. poolError = err
  754. fsLog(fs, logger.LevelDebug, "multipart upload error: %v", poolError)
  755. poolCancel()
  756. })
  757. }
  758. pool.releaseBuffer(buf)
  759. <-guard
  760. }(blockID, buf, n)
  761. }
  762. wg.Wait()
  763. close(guard)
  764. pool.free()
  765. if poolError != nil {
  766. return poolError
  767. }
  768. _, err := blockBlobURL.CommitBlockList(ctx, blocks, httpHeaders, azblob.Metadata{}, azblob.BlobAccessConditions{},
  769. azblob.AccessTierType(fs.config.AccessTier), nil, azblob.ClientProvidedKeyOptions{})
  770. return err
  771. }
  772. // copied from rclone
  773. func (fs *AzureBlobFs) readFill(r io.Reader, buf []byte) (n int, err error) {
  774. var nn int
  775. for n < len(buf) && err == nil {
  776. nn, err = r.Read(buf[n:])
  777. n += nn
  778. }
  779. return n, err
  780. }
  781. // copied from rclone
  782. func (fs *AzureBlobFs) incrementBlockID(blockID []byte) {
  783. for i, digit := range blockID {
  784. newDigit := digit + 1
  785. blockID[i] = newDigit
  786. if newDigit >= digit {
  787. // exit if no carry
  788. break
  789. }
  790. }
  791. }
  792. type bufferAllocator struct {
  793. sync.Mutex
  794. available [][]byte
  795. bufferSize int
  796. finalized bool
  797. }
  798. func newBufferAllocator(size int) *bufferAllocator {
  799. return &bufferAllocator{
  800. bufferSize: size,
  801. finalized: false,
  802. }
  803. }
  804. func (b *bufferAllocator) getBuffer() []byte {
  805. b.Lock()
  806. defer b.Unlock()
  807. if len(b.available) > 0 {
  808. var result []byte
  809. truncLength := len(b.available) - 1
  810. result = b.available[truncLength]
  811. b.available[truncLength] = nil
  812. b.available = b.available[:truncLength]
  813. return result
  814. }
  815. return make([]byte, b.bufferSize)
  816. }
  817. func (b *bufferAllocator) releaseBuffer(buf []byte) {
  818. b.Lock()
  819. defer b.Unlock()
  820. if b.finalized || len(buf) != b.bufferSize {
  821. return
  822. }
  823. b.available = append(b.available, buf)
  824. }
  825. func (b *bufferAllocator) free() {
  826. b.Lock()
  827. defer b.Unlock()
  828. b.available = nil
  829. b.finalized = true
  830. }