azblobfs.go 26 KB

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