azblobfs.go 26 KB

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