azblobfs.go 25 KB

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