azblobfs.go 27 KB

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