azblobfs.go 27 KB

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