azblobfs.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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/utils"
  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 := ValidateAzBlobFsConfig(&fs.config); err != nil {
  53. return fs, err
  54. }
  55. if fs.config.AccountKey != "" {
  56. accountKey, err := utils.DecryptData(fs.config.AccountKey)
  57. if err != nil {
  58. return fs, err
  59. }
  60. fs.config.AccountKey = accountKey
  61. }
  62. fs.setConfigDefaults()
  63. version := version.Get()
  64. telemetryValue := fmt.Sprintf("SFTPGo-%v_%v", version.Version, version.CommitHash)
  65. if fs.config.SASURL != "" {
  66. u, err := url.Parse(fs.config.SASURL)
  67. if err != nil {
  68. return fs, fmt.Errorf("invalid credentials: %v", err)
  69. }
  70. pipeline := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{
  71. Retry: azblob.RetryOptions{
  72. TryTimeout: maxTryTimeout,
  73. },
  74. Telemetry: azblob.TelemetryOptions{
  75. Value: telemetryValue,
  76. },
  77. })
  78. // Check if we have container level SAS or account level SAS
  79. parts := azblob.NewBlobURLParts(*u)
  80. if parts.ContainerName != "" {
  81. if fs.config.Container != "" && fs.config.Container != parts.ContainerName {
  82. return fs, fmt.Errorf("Container name in SAS URL %#v and container provided %#v do not match",
  83. parts.ContainerName, fs.config.Container)
  84. }
  85. fs.svc = nil
  86. fs.containerURL = azblob.NewContainerURL(*u, pipeline)
  87. } else {
  88. if fs.config.Container == "" {
  89. return fs, errors.New("container is required with this SAS URL")
  90. }
  91. serviceURL := azblob.NewServiceURL(*u, pipeline)
  92. fs.svc = &serviceURL
  93. fs.containerURL = fs.svc.NewContainerURL(fs.config.Container)
  94. }
  95. return fs, nil
  96. }
  97. credential, err := azblob.NewSharedKeyCredential(fs.config.AccountName, fs.config.AccountKey)
  98. if err != nil {
  99. return fs, fmt.Errorf("invalid credentials: %v", err)
  100. }
  101. var u *url.URL
  102. if fs.config.UseEmulator {
  103. // for the emulator we expect the endpoint prefixed with the protocol, for example:
  104. // http://127.0.0.1:10000
  105. u, err = url.Parse(fmt.Sprintf("%s/%s", fs.config.Endpoint, fs.config.AccountName))
  106. } else {
  107. u, err = url.Parse(fmt.Sprintf("https://%s.%s", fs.config.AccountName, fs.config.Endpoint))
  108. }
  109. if err != nil {
  110. return fs, fmt.Errorf("invalid credentials: %v", err)
  111. }
  112. pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{
  113. Retry: azblob.RetryOptions{
  114. TryTimeout: maxTryTimeout,
  115. },
  116. Telemetry: azblob.TelemetryOptions{
  117. Value: telemetryValue,
  118. },
  119. })
  120. serviceURL := azblob.NewServiceURL(*u, pipeline)
  121. fs.svc = &serviceURL
  122. fs.containerURL = fs.svc.NewContainerURL(fs.config.Container)
  123. return fs, nil
  124. }
  125. // Name returns the name for the Fs implementation
  126. func (fs *AzureBlobFs) Name() string {
  127. if fs.config.SASURL != "" {
  128. return fmt.Sprintf("Azure Blob SAS URL %#v", fs.config.Container)
  129. }
  130. return fmt.Sprintf("Azure Blob container %#v", fs.config.Container)
  131. }
  132. // ConnectionID returns the connection ID associated to this Fs implementation
  133. func (fs *AzureBlobFs) ConnectionID() string {
  134. return fs.connectionID
  135. }
  136. // Stat returns a FileInfo describing the named file
  137. func (fs *AzureBlobFs) Stat(name string) (os.FileInfo, error) {
  138. if name == "" || name == "." {
  139. if fs.svc != nil {
  140. err := fs.checkIfBucketExists()
  141. if err != nil {
  142. return nil, err
  143. }
  144. }
  145. return NewFileInfo(name, true, 0, time.Now(), false), nil
  146. }
  147. if fs.config.KeyPrefix == name+"/" {
  148. return NewFileInfo(name, true, 0, time.Now(), false), nil
  149. }
  150. attrs, err := fs.headObject(name)
  151. if err == nil {
  152. isDir := (attrs.ContentType() == dirMimeType)
  153. metrics.AZListObjectsCompleted(nil)
  154. return NewFileInfo(name, isDir, attrs.ContentLength(), attrs.LastModified(), false), nil
  155. }
  156. if !fs.IsNotExist(err) {
  157. return nil, err
  158. }
  159. // now check if this is a prefix (virtual directory)
  160. hasContents, err := fs.hasContents(name)
  161. if err != nil {
  162. return nil, err
  163. }
  164. if hasContents {
  165. return NewFileInfo(name, true, 0, time.Now(), false), nil
  166. }
  167. return nil, errors.New("404 no such file or directory")
  168. }
  169. // Lstat returns a FileInfo describing the named file
  170. func (fs *AzureBlobFs) Lstat(name string) (os.FileInfo, error) {
  171. return fs.Stat(name)
  172. }
  173. // Open opens the named file for reading
  174. func (fs *AzureBlobFs) Open(name string, offset int64) (*os.File, *pipeat.PipeReaderAt, func(), error) {
  175. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  176. if err != nil {
  177. return nil, nil, nil, err
  178. }
  179. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  180. ctx, cancelFn := context.WithCancel(context.Background())
  181. blobDownloadResponse, err := blobBlockURL.Download(ctx, offset, azblob.CountToEnd, azblob.BlobAccessConditions{}, false)
  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) (*os.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{})
  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 errors.New("403 symlinks are not supported")
  332. }
  333. // Readlink returns the destination of the named symbolic link
  334. func (*AzureBlobFs) Readlink(name string) (string, error) {
  335. return "", errors.New("403 readlink is not supported")
  336. }
  337. // Chown changes the numeric uid and gid of the named file.
  338. // Silently ignored.
  339. func (*AzureBlobFs) Chown(name string, uid int, gid int) error {
  340. return nil
  341. }
  342. // Chmod changes the mode of the named file to mode.
  343. // Silently ignored.
  344. func (*AzureBlobFs) Chmod(name string, mode os.FileMode) error {
  345. return nil
  346. }
  347. // Chtimes changes the access and modification times of the named file.
  348. // Silently ignored.
  349. func (*AzureBlobFs) Chtimes(name string, atime, mtime time.Time) error {
  350. return errors.New("403 chtimes is not supported")
  351. }
  352. // Truncate changes the size of the named file.
  353. // Truncate by path is not supported, while truncating an opened
  354. // file is handled inside base transfer
  355. func (*AzureBlobFs) Truncate(name string, size int64) error {
  356. return errors.New("403 truncate is not supported")
  357. }
  358. // ReadDir reads the directory named by dirname and returns
  359. // a list of directory entries.
  360. func (fs *AzureBlobFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  361. var result []os.FileInfo
  362. // dirname must be already cleaned
  363. prefix := ""
  364. if dirname != "" && dirname != "." {
  365. prefix = strings.TrimPrefix(dirname, "/")
  366. if !strings.HasSuffix(prefix, "/") {
  367. prefix += "/"
  368. }
  369. }
  370. prefixes := make(map[string]bool)
  371. for marker := (azblob.Marker{}); marker.NotDone(); {
  372. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  373. defer cancelFn()
  374. listBlob, err := fs.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
  375. Details: azblob.BlobListingDetails{
  376. Copy: false,
  377. Metadata: false,
  378. Snapshots: false,
  379. UncommittedBlobs: false,
  380. Deleted: false,
  381. },
  382. Prefix: prefix,
  383. })
  384. if err != nil {
  385. metrics.AZListObjectsCompleted(err)
  386. return nil, err
  387. }
  388. marker = listBlob.NextMarker
  389. for _, blobPrefix := range listBlob.Segment.BlobPrefixes {
  390. // we don't support prefixes == "/" this will be sent if a key starts with "/"
  391. if blobPrefix.Name == "/" {
  392. continue
  393. }
  394. // sometime we have duplicate prefixes, maybe an Azurite bug
  395. name := strings.TrimPrefix(blobPrefix.Name, prefix)
  396. if _, ok := prefixes[strings.TrimSuffix(name, "/")]; ok {
  397. continue
  398. }
  399. result = append(result, NewFileInfo(name, true, 0, time.Now(), false))
  400. prefixes[strings.TrimSuffix(name, "/")] = true
  401. }
  402. for _, blobInfo := range listBlob.Segment.BlobItems {
  403. name := strings.TrimPrefix(blobInfo.Name, prefix)
  404. size := int64(0)
  405. if blobInfo.Properties.ContentLength != nil {
  406. size = *blobInfo.Properties.ContentLength
  407. }
  408. isDir := false
  409. if blobInfo.Properties.ContentType != nil {
  410. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  411. if isDir {
  412. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  413. if _, ok := prefixes[name]; ok {
  414. continue
  415. }
  416. prefixes[name] = true
  417. }
  418. }
  419. result = append(result, NewFileInfo(name, isDir, size, blobInfo.Properties.LastModified, false))
  420. }
  421. }
  422. metrics.AZListObjectsCompleted(nil)
  423. return result, nil
  424. }
  425. // IsUploadResumeSupported returns true if upload resume is supported.
  426. // Upload Resume is not supported on Azure Blob
  427. func (*AzureBlobFs) IsUploadResumeSupported() bool {
  428. return false
  429. }
  430. // IsAtomicUploadSupported returns true if atomic upload is supported.
  431. // Azure Blob uploads are already atomic, we don't need to upload to a temporary
  432. // file
  433. func (*AzureBlobFs) IsAtomicUploadSupported() bool {
  434. return false
  435. }
  436. // IsNotExist returns a boolean indicating whether the error is known to
  437. // report that a file or directory does not exist
  438. func (*AzureBlobFs) IsNotExist(err error) bool {
  439. if err == nil {
  440. return false
  441. }
  442. if storageErr, ok := err.(azblob.StorageError); ok {
  443. if storageErr.Response().StatusCode == http.StatusNotFound { //nolint:bodyclose
  444. return true
  445. }
  446. if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
  447. storageErr.ServiceCode() == azblob.ServiceCodeBlobNotFound {
  448. return true
  449. }
  450. }
  451. return strings.Contains(err.Error(), "404")
  452. }
  453. // IsPermission returns a boolean indicating whether the error is known to
  454. // report that permission is denied.
  455. func (*AzureBlobFs) IsPermission(err error) bool {
  456. if err == nil {
  457. return false
  458. }
  459. if storageErr, ok := err.(azblob.StorageError); ok {
  460. code := storageErr.Response().StatusCode //nolint:bodyclose
  461. if code == http.StatusForbidden || code == http.StatusUnauthorized {
  462. return true
  463. }
  464. if storageErr.ServiceCode() == azblob.ServiceCodeInsufficientAccountPermissions ||
  465. storageErr.ServiceCode() == azblob.ServiceCodeInvalidAuthenticationInfo ||
  466. storageErr.ServiceCode() == azblob.ServiceCodeUnauthorizedBlobOverwrite {
  467. return true
  468. }
  469. }
  470. return strings.Contains(err.Error(), "403")
  471. }
  472. // CheckRootPath creates the specified local root directory if it does not exists
  473. func (fs *AzureBlobFs) CheckRootPath(username string, uid int, gid int) bool {
  474. // we need a local directory for temporary files
  475. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, nil)
  476. return osFs.CheckRootPath(username, uid, gid)
  477. }
  478. // ScanRootDirContents returns the number of files contained in the bucket,
  479. // and their size
  480. func (fs *AzureBlobFs) ScanRootDirContents() (int, int64, error) {
  481. numFiles := 0
  482. size := int64(0)
  483. for marker := (azblob.Marker{}); marker.NotDone(); {
  484. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  485. defer cancelFn()
  486. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{
  487. Details: azblob.BlobListingDetails{
  488. Copy: false,
  489. Metadata: false,
  490. Snapshots: false,
  491. UncommittedBlobs: false,
  492. Deleted: false,
  493. },
  494. Prefix: fs.config.KeyPrefix,
  495. })
  496. if err != nil {
  497. metrics.AZListObjectsCompleted(err)
  498. return numFiles, size, err
  499. }
  500. marker = listBlob.NextMarker
  501. for _, blobInfo := range listBlob.Segment.BlobItems {
  502. isDir := false
  503. if blobInfo.Properties.ContentType != nil {
  504. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  505. }
  506. blobSize := int64(0)
  507. if blobInfo.Properties.ContentLength != nil {
  508. blobSize = *blobInfo.Properties.ContentLength
  509. }
  510. if isDir && blobSize == 0 {
  511. continue
  512. }
  513. numFiles++
  514. size += blobSize
  515. }
  516. }
  517. metrics.AZListObjectsCompleted(nil)
  518. return numFiles, size, nil
  519. }
  520. // GetDirSize returns the number of files and the size for a folder
  521. // including any subfolders
  522. func (*AzureBlobFs) GetDirSize(dirname string) (int, int64, error) {
  523. return 0, 0, errUnsupported
  524. }
  525. // GetAtomicUploadPath returns the path to use for an atomic upload.
  526. // Azure Blob Storage uploads are already atomic, we never call this method
  527. func (*AzureBlobFs) GetAtomicUploadPath(name string) string {
  528. return ""
  529. }
  530. // GetRelativePath returns the path for a file relative to the user's home dir.
  531. // This is the path as seen by SFTPGo users
  532. func (fs *AzureBlobFs) GetRelativePath(name string) string {
  533. rel := path.Clean(name)
  534. if rel == "." {
  535. rel = ""
  536. }
  537. if !path.IsAbs(rel) {
  538. rel = "/" + rel
  539. }
  540. if fs.config.KeyPrefix != "" {
  541. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  542. rel = "/"
  543. }
  544. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  545. }
  546. return rel
  547. }
  548. // Walk walks the file tree rooted at root, calling walkFn for each file or
  549. // directory in the tree, including root
  550. func (fs *AzureBlobFs) Walk(root string, walkFn filepath.WalkFunc) error {
  551. prefix := ""
  552. if root != "" && root != "." {
  553. prefix = strings.TrimPrefix(root, "/")
  554. if !strings.HasSuffix(prefix, "/") {
  555. prefix += "/"
  556. }
  557. }
  558. for marker := (azblob.Marker{}); marker.NotDone(); {
  559. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  560. defer cancelFn()
  561. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{
  562. Details: azblob.BlobListingDetails{
  563. Copy: false,
  564. Metadata: false,
  565. Snapshots: false,
  566. UncommittedBlobs: false,
  567. Deleted: false,
  568. },
  569. Prefix: prefix,
  570. })
  571. if err != nil {
  572. metrics.AZListObjectsCompleted(err)
  573. return err
  574. }
  575. marker = listBlob.NextMarker
  576. for _, blobInfo := range listBlob.Segment.BlobItems {
  577. isDir := false
  578. if blobInfo.Properties.ContentType != nil {
  579. isDir = (*blobInfo.Properties.ContentType == dirMimeType)
  580. }
  581. if fs.isEqual(blobInfo.Name, prefix) {
  582. continue
  583. }
  584. blobSize := int64(0)
  585. if blobInfo.Properties.ContentLength != nil {
  586. blobSize = *blobInfo.Properties.ContentLength
  587. }
  588. err = walkFn(blobInfo.Name, NewFileInfo(blobInfo.Name, isDir, blobSize, blobInfo.Properties.LastModified, false), nil)
  589. if err != nil {
  590. return err
  591. }
  592. }
  593. }
  594. metrics.AZListObjectsCompleted(nil)
  595. return walkFn(root, NewFileInfo(root, true, 0, time.Now(), false), nil)
  596. }
  597. // Join joins any number of path elements into a single path
  598. func (*AzureBlobFs) Join(elem ...string) string {
  599. return strings.TrimPrefix(path.Join(elem...), "/")
  600. }
  601. // HasVirtualFolders returns true if folders are emulated
  602. func (*AzureBlobFs) HasVirtualFolders() bool {
  603. return true
  604. }
  605. // ResolvePath returns the matching filesystem path for the specified sftp path
  606. func (fs *AzureBlobFs) ResolvePath(virtualPath string) (string, error) {
  607. if !path.IsAbs(virtualPath) {
  608. virtualPath = path.Clean("/" + virtualPath)
  609. }
  610. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  611. }
  612. func (fs *AzureBlobFs) headObject(name string) (*azblob.BlobGetPropertiesResponse, error) {
  613. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  614. defer cancelFn()
  615. blobBlockURL := fs.containerURL.NewBlockBlobURL(name)
  616. response, err := blobBlockURL.GetProperties(ctx, azblob.BlobAccessConditions{})
  617. metrics.AZHeadObjectCompleted(err)
  618. return response, err
  619. }
  620. // GetMimeType returns the content type
  621. func (fs *AzureBlobFs) GetMimeType(name string) (string, error) {
  622. response, err := fs.headObject(name)
  623. if err != nil {
  624. return "", err
  625. }
  626. return response.ContentType(), nil
  627. }
  628. func (fs *AzureBlobFs) isEqual(key string, virtualName string) bool {
  629. if key == virtualName {
  630. return true
  631. }
  632. if key == virtualName+"/" {
  633. return true
  634. }
  635. if key+"/" == virtualName {
  636. return true
  637. }
  638. return false
  639. }
  640. func (fs *AzureBlobFs) setConfigDefaults() {
  641. if fs.config.Endpoint == "" {
  642. fs.config.Endpoint = azureDefaultEndpoint
  643. }
  644. if fs.config.UploadPartSize == 0 {
  645. fs.config.UploadPartSize = 4
  646. }
  647. fs.config.UploadPartSize *= 1024 * 1024
  648. if fs.config.UploadConcurrency == 0 {
  649. fs.config.UploadConcurrency = 2
  650. }
  651. if fs.config.AccessTier == "" {
  652. fs.config.AccessTier = string(azblob.AccessTierNone)
  653. }
  654. }
  655. func (fs *AzureBlobFs) checkIfBucketExists() error {
  656. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  657. defer cancelFn()
  658. _, err := fs.containerURL.GetProperties(ctx, azblob.LeaseAccessConditions{})
  659. metrics.AZHeadContainerCompleted(err)
  660. return err
  661. }
  662. func (fs *AzureBlobFs) hasContents(name string) (bool, error) {
  663. result := false
  664. prefix := ""
  665. if name != "" && name != "." {
  666. prefix = strings.TrimPrefix(name, "/")
  667. if !strings.HasSuffix(prefix, "/") {
  668. prefix += "/"
  669. }
  670. }
  671. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  672. defer cancelFn()
  673. listBlob, err := fs.containerURL.ListBlobsFlatSegment(ctx, azblob.Marker{}, azblob.ListBlobsSegmentOptions{
  674. Details: azblob.BlobListingDetails{
  675. Copy: false,
  676. Metadata: false,
  677. Snapshots: false,
  678. UncommittedBlobs: false,
  679. Deleted: false,
  680. },
  681. Prefix: prefix,
  682. MaxResults: 1,
  683. })
  684. metrics.AZListObjectsCompleted(err)
  685. if err != nil {
  686. return result, err
  687. }
  688. result = len(listBlob.Segment.BlobItems) > 0
  689. return result, err
  690. }
  691. func (fs *AzureBlobFs) handleMultipartUpload(ctx context.Context, reader io.Reader, blockBlobURL azblob.BlockBlobURL,
  692. httpHeaders azblob.BlobHTTPHeaders) error {
  693. partSize := fs.config.UploadPartSize
  694. guard := make(chan struct{}, fs.config.UploadConcurrency)
  695. blockCtxTimeout := time.Duration(fs.config.UploadPartSize/(1024*1024)) * time.Minute
  696. // sync.Pool seems to use a lot of memory so prefer our own, very simple, allocator
  697. // we only need to recycle few byte slices
  698. pool := newBufferAllocator(int(partSize))
  699. finished := false
  700. binaryBlockID := make([]byte, 8)
  701. var blocks []string
  702. var wg sync.WaitGroup
  703. var errOnce sync.Once
  704. var poolError error
  705. poolCtx, poolCancel := context.WithCancel(ctx)
  706. defer poolCancel()
  707. for part := 0; !finished; part++ {
  708. buf := pool.getBuffer()
  709. n, err := fs.readFill(reader, buf)
  710. if err == io.EOF {
  711. // read finished, if n > 0 we need to process the last data chunck
  712. if n == 0 {
  713. pool.releaseBuffer(buf)
  714. break
  715. }
  716. finished = true
  717. } else if err != nil {
  718. pool.releaseBuffer(buf)
  719. pool.free()
  720. return err
  721. }
  722. fs.incrementBlockID(binaryBlockID)
  723. blockID := base64.StdEncoding.EncodeToString(binaryBlockID)
  724. blocks = append(blocks, blockID)
  725. guard <- struct{}{}
  726. if poolError != nil {
  727. fsLog(fs, logger.LevelDebug, "pool error, upload for part %v not started", part)
  728. pool.releaseBuffer(buf)
  729. break
  730. }
  731. wg.Add(1)
  732. go func(blockID string, buf []byte, bufSize int) {
  733. defer wg.Done()
  734. bufferReader := bytes.NewReader(buf[:bufSize])
  735. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  736. defer cancelFn()
  737. _, err := blockBlobURL.StageBlock(innerCtx, blockID, bufferReader, azblob.LeaseAccessConditions{}, nil)
  738. if err != nil {
  739. errOnce.Do(func() {
  740. poolError = err
  741. fsLog(fs, logger.LevelDebug, "multipart upload error: %v", poolError)
  742. poolCancel()
  743. })
  744. }
  745. pool.releaseBuffer(buf)
  746. <-guard
  747. }(blockID, buf, n)
  748. }
  749. wg.Wait()
  750. close(guard)
  751. pool.free()
  752. if poolError != nil {
  753. return poolError
  754. }
  755. _, err := blockBlobURL.CommitBlockList(ctx, blocks, httpHeaders, azblob.Metadata{}, azblob.BlobAccessConditions{},
  756. azblob.AccessTierType(fs.config.AccessTier), nil)
  757. return err
  758. }
  759. // copied from rclone
  760. func (fs *AzureBlobFs) readFill(r io.Reader, buf []byte) (n int, err error) {
  761. var nn int
  762. for n < len(buf) && err == nil {
  763. nn, err = r.Read(buf[n:])
  764. n += nn
  765. }
  766. return n, err
  767. }
  768. // copied from rclone
  769. func (fs *AzureBlobFs) incrementBlockID(blockID []byte) {
  770. for i, digit := range blockID {
  771. newDigit := digit + 1
  772. blockID[i] = newDigit
  773. if newDigit >= digit {
  774. // exit if no carry
  775. break
  776. }
  777. }
  778. }
  779. type bufferAllocator struct {
  780. sync.Mutex
  781. available [][]byte
  782. bufferSize int
  783. finalized bool
  784. }
  785. func newBufferAllocator(size int) *bufferAllocator {
  786. return &bufferAllocator{
  787. bufferSize: size,
  788. finalized: false,
  789. }
  790. }
  791. func (b *bufferAllocator) getBuffer() []byte {
  792. b.Lock()
  793. defer b.Unlock()
  794. if len(b.available) > 0 {
  795. var result []byte
  796. truncLength := len(b.available) - 1
  797. result = b.available[truncLength]
  798. b.available[truncLength] = nil
  799. b.available = b.available[:truncLength]
  800. return result
  801. }
  802. return make([]byte, b.bufferSize)
  803. }
  804. func (b *bufferAllocator) releaseBuffer(buf []byte) {
  805. b.Lock()
  806. defer b.Unlock()
  807. if b.finalized || len(buf) != b.bufferSize {
  808. return
  809. }
  810. b.available = append(b.available, buf)
  811. }
  812. func (b *bufferAllocator) free() {
  813. b.Lock()
  814. defer b.Unlock()
  815. b.available = nil
  816. b.finalized = true
  817. }