azblobfs.go 27 KB

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