azblobfs.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. //go:build !noazblob
  15. // +build !noazblob
  16. package vfs
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/base64"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "mime"
  25. "net/http"
  26. "os"
  27. "path"
  28. "path/filepath"
  29. "strconv"
  30. "strings"
  31. "sync"
  32. "sync/atomic"
  33. "time"
  34. "github.com/Azure/azure-sdk-for-go/sdk/azcore"
  35. "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
  36. "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
  37. "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
  38. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
  39. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
  40. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
  41. "github.com/eikenb/pipeat"
  42. "github.com/google/uuid"
  43. "github.com/pkg/sftp"
  44. "github.com/drakkan/sftpgo/v2/internal/logger"
  45. "github.com/drakkan/sftpgo/v2/internal/metric"
  46. "github.com/drakkan/sftpgo/v2/internal/util"
  47. "github.com/drakkan/sftpgo/v2/internal/version"
  48. )
  49. const (
  50. azureDefaultEndpoint = "blob.core.windows.net"
  51. azFolderKey = "hdi_isfolder"
  52. )
  53. var (
  54. azureBlobDefaultPageSize = int32(5000)
  55. )
  56. // AzureBlobFs is a Fs implementation for Azure Blob storage.
  57. type AzureBlobFs struct {
  58. connectionID string
  59. localTempDir string
  60. // if not empty this fs is mouted as virtual folder in the specified path
  61. mountPath string
  62. config *AzBlobFsConfig
  63. containerClient *container.Client
  64. ctxTimeout time.Duration
  65. ctxLongTimeout time.Duration
  66. }
  67. func init() {
  68. version.AddFeature("+azblob")
  69. }
  70. // NewAzBlobFs returns an AzBlobFs object that allows to interact with Azure Blob storage
  71. func NewAzBlobFs(connectionID, localTempDir, mountPath string, config AzBlobFsConfig) (Fs, error) {
  72. if localTempDir == "" {
  73. localTempDir = getLocalTempDir()
  74. }
  75. fs := &AzureBlobFs{
  76. connectionID: connectionID,
  77. localTempDir: localTempDir,
  78. mountPath: getMountPath(mountPath),
  79. config: &config,
  80. ctxTimeout: 30 * time.Second,
  81. ctxLongTimeout: 90 * time.Second,
  82. }
  83. if err := fs.config.validate(); err != nil {
  84. return fs, err
  85. }
  86. if err := fs.config.tryDecrypt(); err != nil {
  87. return fs, err
  88. }
  89. fs.setConfigDefaults()
  90. if fs.config.SASURL.GetPayload() != "" {
  91. return fs.initFromSASURL()
  92. }
  93. credential, err := blob.NewSharedKeyCredential(fs.config.AccountName, fs.config.AccountKey.GetPayload())
  94. if err != nil {
  95. return fs, fmt.Errorf("invalid credentials: %v", err)
  96. }
  97. var endpoint string
  98. if fs.config.UseEmulator {
  99. endpoint = fmt.Sprintf("%s/%s", fs.config.Endpoint, fs.config.AccountName)
  100. } else {
  101. endpoint = fmt.Sprintf("https://%s.%s/", fs.config.AccountName, fs.config.Endpoint)
  102. }
  103. containerURL := runtime.JoinPaths(endpoint, fs.config.Container)
  104. svc, err := container.NewClientWithSharedKeyCredential(containerURL, credential, getAzContainerClientOptions())
  105. if err != nil {
  106. return fs, fmt.Errorf("invalid credentials: %v", err)
  107. }
  108. fs.containerClient = svc
  109. return fs, err
  110. }
  111. func (fs *AzureBlobFs) initFromSASURL() (Fs, error) {
  112. parts, err := blob.ParseURL(fs.config.SASURL.GetPayload())
  113. if err != nil {
  114. return fs, fmt.Errorf("invalid SAS URL: %w", err)
  115. }
  116. if parts.BlobName != "" {
  117. return fs, fmt.Errorf("SAS URL with blob name not supported")
  118. }
  119. if parts.ContainerName != "" {
  120. if fs.config.Container != "" && fs.config.Container != parts.ContainerName {
  121. return fs, fmt.Errorf("container name in SAS URL %q and container provided %q do not match",
  122. parts.ContainerName, fs.config.Container)
  123. }
  124. svc, err := container.NewClientWithNoCredential(fs.config.SASURL.GetPayload(), getAzContainerClientOptions())
  125. if err != nil {
  126. return fs, fmt.Errorf("invalid credentials: %v", err)
  127. }
  128. fs.config.Container = parts.ContainerName
  129. fs.containerClient = svc
  130. return fs, nil
  131. }
  132. if fs.config.Container == "" {
  133. return fs, errors.New("container is required with this SAS URL")
  134. }
  135. sasURL := runtime.JoinPaths(fs.config.SASURL.GetPayload(), fs.config.Container)
  136. svc, err := container.NewClientWithNoCredential(sasURL, getAzContainerClientOptions())
  137. if err != nil {
  138. return fs, fmt.Errorf("invalid credentials: %v", err)
  139. }
  140. fs.containerClient = svc
  141. return fs, nil
  142. }
  143. // Name returns the name for the Fs implementation
  144. func (fs *AzureBlobFs) Name() string {
  145. if !fs.config.SASURL.IsEmpty() {
  146. return fmt.Sprintf("%s with SAS URL, container %q", azBlobFsName, fs.config.Container)
  147. }
  148. return fmt.Sprintf("%s container %q", azBlobFsName, fs.config.Container)
  149. }
  150. // ConnectionID returns the connection ID associated to this Fs implementation
  151. func (fs *AzureBlobFs) ConnectionID() string {
  152. return fs.connectionID
  153. }
  154. // Stat returns a FileInfo describing the named file
  155. func (fs *AzureBlobFs) Stat(name string) (os.FileInfo, error) {
  156. if name == "" || name == "/" || name == "." {
  157. return NewFileInfo(name, true, 0, time.Unix(0, 0), false), nil
  158. }
  159. if fs.config.KeyPrefix == name+"/" {
  160. return NewFileInfo(name, true, 0, time.Unix(0, 0), false), nil
  161. }
  162. attrs, err := fs.headObject(name)
  163. if err == nil {
  164. contentType := util.GetStringFromPointer(attrs.ContentType)
  165. isDir := checkDirectoryMarkers(contentType, attrs.Metadata)
  166. lastModified := util.GetTimeFromPointer(attrs.LastModified)
  167. if val := getAzureLastModified(attrs.Metadata); val > 0 {
  168. lastModified = util.GetTimeFromMsecSinceEpoch(val)
  169. }
  170. return NewFileInfo(name, isDir, util.GetIntFromPointer(attrs.ContentLength), lastModified, false), nil
  171. }
  172. if !fs.IsNotExist(err) {
  173. return nil, err
  174. }
  175. // now check if this is a prefix (virtual directory)
  176. hasContents, err := fs.hasContents(name)
  177. if err != nil {
  178. return nil, err
  179. }
  180. if hasContents {
  181. return NewFileInfo(name, true, 0, time.Unix(0, 0), false), nil
  182. }
  183. return nil, os.ErrNotExist
  184. }
  185. // Lstat returns a FileInfo describing the named file
  186. func (fs *AzureBlobFs) Lstat(name string) (os.FileInfo, error) {
  187. return fs.Stat(name)
  188. }
  189. // Open opens the named file for reading
  190. func (fs *AzureBlobFs) Open(name string, offset int64) (File, PipeReader, func(), error) {
  191. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  192. if err != nil {
  193. return nil, nil, nil, err
  194. }
  195. p := NewPipeReader(r)
  196. ctx, cancelFn := context.WithCancel(context.Background())
  197. go func() {
  198. defer cancelFn()
  199. blockBlob := fs.containerClient.NewBlockBlobClient(name)
  200. err := fs.handleMultipartDownload(ctx, blockBlob, offset, w, p)
  201. w.CloseWithError(err) //nolint:errcheck
  202. fsLog(fs, logger.LevelDebug, "download completed, path: %q size: %v, err: %+v", name, w.GetWrittenBytes(), err)
  203. metric.AZTransferCompleted(w.GetWrittenBytes(), 1, err)
  204. }()
  205. return nil, p, cancelFn, nil
  206. }
  207. // Create creates or opens the named file for writing
  208. func (fs *AzureBlobFs) Create(name string, flag, checks int) (File, PipeWriter, func(), error) {
  209. if checks&CheckParentDir != 0 {
  210. _, err := fs.Stat(path.Dir(name))
  211. if err != nil {
  212. return nil, nil, nil, err
  213. }
  214. }
  215. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  216. if err != nil {
  217. return nil, nil, nil, err
  218. }
  219. ctx, cancelFn := context.WithCancel(context.Background())
  220. var p PipeWriter
  221. if checks&CheckResume != 0 {
  222. p = newPipeWriterAtOffset(w, 0)
  223. } else {
  224. p = NewPipeWriter(w)
  225. }
  226. headers := blob.HTTPHeaders{}
  227. var contentType string
  228. var metadata map[string]*string
  229. if flag == -1 {
  230. contentType = dirMimeType
  231. metadata = map[string]*string{
  232. azFolderKey: util.NilIfEmpty("true"),
  233. }
  234. } else {
  235. contentType = mime.TypeByExtension(path.Ext(name))
  236. }
  237. if contentType != "" {
  238. headers.BlobContentType = &contentType
  239. }
  240. go func() {
  241. defer cancelFn()
  242. blockBlob := fs.containerClient.NewBlockBlobClient(name)
  243. err := fs.handleMultipartUpload(ctx, r, blockBlob, &headers, metadata)
  244. r.CloseWithError(err) //nolint:errcheck
  245. p.Done(err)
  246. fsLog(fs, logger.LevelDebug, "upload completed, path: %q, readed bytes: %v, err: %+v", name, r.GetReadedBytes(), err)
  247. metric.AZTransferCompleted(r.GetReadedBytes(), 0, err)
  248. }()
  249. if checks&CheckResume != 0 {
  250. readCh := make(chan error, 1)
  251. go func() {
  252. n, err := fs.downloadToWriter(name, p)
  253. pw := p.(*pipeWriterAtOffset)
  254. pw.offset = 0
  255. pw.writeOffset = n
  256. readCh <- err
  257. }()
  258. err = <-readCh
  259. if err != nil {
  260. cancelFn()
  261. p.Close()
  262. fsLog(fs, logger.LevelDebug, "download before resume failed, writer closed and read cancelled")
  263. return nil, nil, nil, err
  264. }
  265. }
  266. if uploadMode&16 != 0 {
  267. return nil, p, nil, nil
  268. }
  269. return nil, p, cancelFn, nil
  270. }
  271. // Rename renames (moves) source to target.
  272. func (fs *AzureBlobFs) Rename(source, target string) (int, int64, error) {
  273. if source == target {
  274. return -1, -1, nil
  275. }
  276. _, err := fs.Stat(path.Dir(target))
  277. if err != nil {
  278. return -1, -1, err
  279. }
  280. fi, err := fs.Stat(source)
  281. if err != nil {
  282. return -1, -1, err
  283. }
  284. return fs.renameInternal(source, target, fi, 0)
  285. }
  286. // Remove removes the named file or (empty) directory.
  287. func (fs *AzureBlobFs) Remove(name string, isDir bool) error {
  288. if isDir {
  289. hasContents, err := fs.hasContents(name)
  290. if err != nil {
  291. return err
  292. }
  293. if hasContents {
  294. return fmt.Errorf("cannot remove non empty directory: %q", name)
  295. }
  296. }
  297. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  298. defer cancelFn()
  299. blobBlock := fs.containerClient.NewBlockBlobClient(name)
  300. var deletSnapshots blob.DeleteSnapshotsOptionType
  301. if !isDir {
  302. deletSnapshots = blob.DeleteSnapshotsOptionTypeInclude
  303. }
  304. _, err := blobBlock.Delete(ctx, &blob.DeleteOptions{
  305. DeleteSnapshots: &deletSnapshots,
  306. })
  307. if err != nil && isDir {
  308. if fs.isBadRequestError(err) {
  309. deletSnapshots = blob.DeleteSnapshotsOptionTypeInclude
  310. _, err = blobBlock.Delete(ctx, &blob.DeleteOptions{
  311. DeleteSnapshots: &deletSnapshots,
  312. })
  313. }
  314. }
  315. metric.AZDeleteObjectCompleted(err)
  316. return err
  317. }
  318. // Mkdir creates a new directory with the specified name and default permissions
  319. func (fs *AzureBlobFs) Mkdir(name string) error {
  320. _, err := fs.Stat(name)
  321. if !fs.IsNotExist(err) {
  322. return err
  323. }
  324. return fs.mkdirInternal(name)
  325. }
  326. // Symlink creates source as a symbolic link to target.
  327. func (*AzureBlobFs) Symlink(_, _ string) error {
  328. return ErrVfsUnsupported
  329. }
  330. // Readlink returns the destination of the named symbolic link
  331. func (*AzureBlobFs) Readlink(_ string) (string, error) {
  332. return "", ErrVfsUnsupported
  333. }
  334. // Chown changes the numeric uid and gid of the named file.
  335. func (*AzureBlobFs) Chown(_ string, _ int, _ int) error {
  336. return ErrVfsUnsupported
  337. }
  338. // Chmod changes the mode of the named file to mode.
  339. func (*AzureBlobFs) Chmod(_ string, _ os.FileMode) error {
  340. return ErrVfsUnsupported
  341. }
  342. // Chtimes changes the access and modification times of the named file.
  343. func (fs *AzureBlobFs) Chtimes(name string, _, mtime time.Time, isUploading bool) error {
  344. if isUploading {
  345. return nil
  346. }
  347. props, err := fs.headObject(name)
  348. if err != nil {
  349. return err
  350. }
  351. metadata := props.Metadata
  352. if metadata == nil {
  353. metadata = make(map[string]*string)
  354. }
  355. found := false
  356. for k := range metadata {
  357. if strings.ToLower(k) == lastModifiedField {
  358. metadata[k] = to.Ptr(strconv.FormatInt(mtime.UnixMilli(), 10))
  359. found = true
  360. break
  361. }
  362. }
  363. if !found {
  364. metadata[lastModifiedField] = to.Ptr(strconv.FormatInt(mtime.UnixMilli(), 10))
  365. }
  366. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  367. defer cancelFn()
  368. _, err = fs.containerClient.NewBlockBlobClient(name).SetMetadata(ctx, metadata, &blob.SetMetadataOptions{})
  369. return err
  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(_ string, _ int64) error {
  375. return ErrVfsUnsupported
  376. }
  377. // ReadDir reads the directory named by dirname and returns
  378. // a list of directory entries.
  379. func (fs *AzureBlobFs) ReadDir(dirname string) (DirLister, error) {
  380. // dirname must be already cleaned
  381. prefix := fs.getPrefix(dirname)
  382. pager := fs.containerClient.NewListBlobsHierarchyPager("/", &container.ListBlobsHierarchyOptions{
  383. Include: container.ListBlobsInclude{
  384. Metadata: true,
  385. },
  386. Prefix: &prefix,
  387. MaxResults: &azureBlobDefaultPageSize,
  388. })
  389. return &azureBlobDirLister{
  390. paginator: pager,
  391. timeout: fs.ctxTimeout,
  392. prefix: prefix,
  393. prefixes: make(map[string]bool),
  394. }, nil
  395. }
  396. // IsUploadResumeSupported returns true if resuming uploads is supported.
  397. // Resuming uploads is not supported on Azure Blob
  398. func (*AzureBlobFs) IsUploadResumeSupported() bool {
  399. return false
  400. }
  401. // IsConditionalUploadResumeSupported returns if resuming uploads is supported
  402. // for the specified size
  403. func (*AzureBlobFs) IsConditionalUploadResumeSupported(size int64) bool {
  404. return size <= resumeMaxSize
  405. }
  406. // IsAtomicUploadSupported returns true if atomic upload is supported.
  407. // Azure Blob uploads are already atomic, we don't need to upload to a temporary
  408. // file
  409. func (*AzureBlobFs) IsAtomicUploadSupported() bool {
  410. return false
  411. }
  412. // IsNotExist returns a boolean indicating whether the error is known to
  413. // report that a file or directory does not exist
  414. func (*AzureBlobFs) IsNotExist(err error) bool {
  415. if err == nil {
  416. return false
  417. }
  418. var respErr *azcore.ResponseError
  419. if errors.As(err, &respErr) {
  420. return respErr.StatusCode == http.StatusNotFound
  421. }
  422. // os.ErrNotExist can be returned internally by fs.Stat
  423. return errors.Is(err, os.ErrNotExist)
  424. }
  425. // IsPermission returns a boolean indicating whether the error is known to
  426. // report that permission is denied.
  427. func (*AzureBlobFs) IsPermission(err error) bool {
  428. if err == nil {
  429. return false
  430. }
  431. var respErr *azcore.ResponseError
  432. if errors.As(err, &respErr) {
  433. return respErr.StatusCode == http.StatusForbidden || respErr.StatusCode == http.StatusUnauthorized
  434. }
  435. return false
  436. }
  437. // IsNotSupported returns true if the error indicate an unsupported operation
  438. func (*AzureBlobFs) IsNotSupported(err error) bool {
  439. if err == nil {
  440. return false
  441. }
  442. return errors.Is(err, ErrVfsUnsupported)
  443. }
  444. func (*AzureBlobFs) isBadRequestError(err error) bool {
  445. if err == nil {
  446. return false
  447. }
  448. var respErr *azcore.ResponseError
  449. if errors.As(err, &respErr) {
  450. return respErr.StatusCode == http.StatusBadRequest
  451. }
  452. return false
  453. }
  454. // CheckRootPath creates the specified local root directory if it does not exists
  455. func (fs *AzureBlobFs) CheckRootPath(username string, uid int, gid int) bool {
  456. // we need a local directory for temporary files
  457. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "", nil)
  458. return osFs.CheckRootPath(username, uid, gid)
  459. }
  460. // ScanRootDirContents returns the number of files contained in the bucket,
  461. // and their size
  462. func (fs *AzureBlobFs) ScanRootDirContents() (int, int64, error) {
  463. return fs.GetDirSize(fs.config.KeyPrefix)
  464. }
  465. // GetDirSize returns the number of files and the size for a folder
  466. // including any subfolders
  467. func (fs *AzureBlobFs) GetDirSize(dirname string) (int, int64, error) {
  468. numFiles := 0
  469. size := int64(0)
  470. prefix := fs.getPrefix(dirname)
  471. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  472. Include: container.ListBlobsInclude{
  473. Metadata: true,
  474. },
  475. Prefix: &prefix,
  476. MaxResults: &azureBlobDefaultPageSize,
  477. })
  478. for pager.More() {
  479. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  480. defer cancelFn()
  481. resp, err := pager.NextPage(ctx)
  482. if err != nil {
  483. metric.AZListObjectsCompleted(err)
  484. return numFiles, size, err
  485. }
  486. for _, blobItem := range resp.ListBlobsFlatSegmentResponse.Segment.BlobItems {
  487. if blobItem.Properties != nil {
  488. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  489. isDir := checkDirectoryMarkers(contentType, blobItem.Metadata)
  490. blobSize := util.GetIntFromPointer(blobItem.Properties.ContentLength)
  491. if isDir && blobSize == 0 {
  492. continue
  493. }
  494. numFiles++
  495. size += blobSize
  496. }
  497. }
  498. fsLog(fs, logger.LevelDebug, "scan in progress for %q, files: %d, size: %d", dirname, numFiles, size)
  499. }
  500. metric.AZListObjectsCompleted(nil)
  501. return numFiles, size, nil
  502. }
  503. // GetAtomicUploadPath returns the path to use for an atomic upload.
  504. // Azure Blob Storage uploads are already atomic, we never call this method
  505. func (*AzureBlobFs) GetAtomicUploadPath(_ string) string {
  506. return ""
  507. }
  508. // GetRelativePath returns the path for a file relative to the user's home dir.
  509. // This is the path as seen by SFTPGo users
  510. func (fs *AzureBlobFs) GetRelativePath(name string) string {
  511. rel := path.Clean(name)
  512. if rel == "." {
  513. rel = ""
  514. }
  515. if !path.IsAbs(rel) {
  516. rel = "/" + rel
  517. }
  518. if fs.config.KeyPrefix != "" {
  519. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  520. rel = "/"
  521. }
  522. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  523. }
  524. if fs.mountPath != "" {
  525. rel = path.Join(fs.mountPath, rel)
  526. }
  527. return rel
  528. }
  529. // Walk walks the file tree rooted at root, calling walkFn for each file or
  530. // directory in the tree, including root
  531. func (fs *AzureBlobFs) Walk(root string, walkFn filepath.WalkFunc) error {
  532. prefix := fs.getPrefix(root)
  533. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  534. Include: container.ListBlobsInclude{
  535. Metadata: true,
  536. },
  537. Prefix: &prefix,
  538. MaxResults: &azureBlobDefaultPageSize,
  539. })
  540. for pager.More() {
  541. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  542. defer cancelFn()
  543. resp, err := pager.NextPage(ctx)
  544. if err != nil {
  545. metric.AZListObjectsCompleted(err)
  546. return err
  547. }
  548. for _, blobItem := range resp.ListBlobsFlatSegmentResponse.Segment.BlobItems {
  549. name := util.GetStringFromPointer(blobItem.Name)
  550. if fs.isEqual(name, prefix) {
  551. continue
  552. }
  553. blobSize := int64(0)
  554. lastModified := time.Unix(0, 0)
  555. isDir := false
  556. if blobItem.Properties != nil {
  557. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  558. isDir = checkDirectoryMarkers(contentType, blobItem.Metadata)
  559. blobSize = util.GetIntFromPointer(blobItem.Properties.ContentLength)
  560. lastModified = util.GetTimeFromPointer(blobItem.Properties.LastModified)
  561. if val := getAzureLastModified(blobItem.Metadata); val > 0 {
  562. lastModified = util.GetTimeFromMsecSinceEpoch(val)
  563. }
  564. }
  565. err := walkFn(name, NewFileInfo(name, isDir, blobSize, lastModified, false), nil)
  566. if err != nil {
  567. return err
  568. }
  569. }
  570. }
  571. metric.AZListObjectsCompleted(nil)
  572. return walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), nil)
  573. }
  574. // Join joins any number of path elements into a single path
  575. func (*AzureBlobFs) Join(elem ...string) string {
  576. return strings.TrimPrefix(path.Join(elem...), "/")
  577. }
  578. // HasVirtualFolders returns true if folders are emulated
  579. func (*AzureBlobFs) HasVirtualFolders() bool {
  580. return true
  581. }
  582. // ResolvePath returns the matching filesystem path for the specified sftp path
  583. func (fs *AzureBlobFs) ResolvePath(virtualPath string) (string, error) {
  584. if fs.mountPath != "" {
  585. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  586. }
  587. if !path.IsAbs(virtualPath) {
  588. virtualPath = path.Clean("/" + virtualPath)
  589. }
  590. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  591. }
  592. // CopyFile implements the FsFileCopier interface
  593. func (fs *AzureBlobFs) CopyFile(source, target string, srcSize int64) (int, int64, error) {
  594. numFiles := 1
  595. sizeDiff := srcSize
  596. attrs, err := fs.headObject(target)
  597. if err == nil {
  598. sizeDiff -= util.GetIntFromPointer(attrs.ContentLength)
  599. numFiles = 0
  600. } else {
  601. if !fs.IsNotExist(err) {
  602. return 0, 0, err
  603. }
  604. }
  605. if err := fs.copyFileInternal(source, target); err != nil {
  606. return 0, 0, err
  607. }
  608. return numFiles, sizeDiff, nil
  609. }
  610. func (fs *AzureBlobFs) headObject(name string) (blob.GetPropertiesResponse, error) {
  611. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  612. defer cancelFn()
  613. resp, err := fs.containerClient.NewBlockBlobClient(name).GetProperties(ctx, &blob.GetPropertiesOptions{})
  614. metric.AZHeadObjectCompleted(err)
  615. return resp, err
  616. }
  617. // GetMimeType returns the content type
  618. func (fs *AzureBlobFs) GetMimeType(name string) (string, error) {
  619. response, err := fs.headObject(name)
  620. if err != nil {
  621. return "", err
  622. }
  623. return util.GetStringFromPointer(response.ContentType), nil
  624. }
  625. // Close closes the fs
  626. func (*AzureBlobFs) Close() error {
  627. return nil
  628. }
  629. // GetAvailableDiskSize returns the available size for the specified path
  630. func (*AzureBlobFs) GetAvailableDiskSize(_ string) (*sftp.StatVFS, error) {
  631. return nil, ErrStorageSizeUnavailable
  632. }
  633. func (*AzureBlobFs) getPrefix(name string) string {
  634. prefix := ""
  635. if name != "" && name != "." {
  636. prefix = strings.TrimPrefix(name, "/")
  637. if !strings.HasSuffix(prefix, "/") {
  638. prefix += "/"
  639. }
  640. }
  641. return prefix
  642. }
  643. func (fs *AzureBlobFs) isEqual(key string, virtualName string) bool {
  644. if key == virtualName {
  645. return true
  646. }
  647. if key == virtualName+"/" {
  648. return true
  649. }
  650. if key+"/" == virtualName {
  651. return true
  652. }
  653. return false
  654. }
  655. func (fs *AzureBlobFs) setConfigDefaults() {
  656. if fs.config.Endpoint == "" {
  657. fs.config.Endpoint = azureDefaultEndpoint
  658. }
  659. if fs.config.UploadPartSize == 0 {
  660. fs.config.UploadPartSize = 5
  661. }
  662. if fs.config.UploadPartSize < 1024*1024 {
  663. fs.config.UploadPartSize *= 1024 * 1024
  664. }
  665. if fs.config.UploadConcurrency == 0 {
  666. fs.config.UploadConcurrency = 5
  667. }
  668. if fs.config.DownloadPartSize == 0 {
  669. fs.config.DownloadPartSize = 5
  670. }
  671. if fs.config.DownloadPartSize < 1024*1024 {
  672. fs.config.DownloadPartSize *= 1024 * 1024
  673. }
  674. if fs.config.DownloadConcurrency == 0 {
  675. fs.config.DownloadConcurrency = 5
  676. }
  677. }
  678. func (fs *AzureBlobFs) copyFileInternal(source, target string) error {
  679. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  680. defer cancelFn()
  681. srcBlob := fs.containerClient.NewBlockBlobClient(source)
  682. dstBlob := fs.containerClient.NewBlockBlobClient(target)
  683. resp, err := dstBlob.StartCopyFromURL(ctx, srcBlob.URL(), fs.getCopyOptions())
  684. if err != nil {
  685. metric.AZCopyObjectCompleted(err)
  686. return err
  687. }
  688. copyStatus := blob.CopyStatusType(util.GetStringFromPointer((*string)(resp.CopyStatus)))
  689. nErrors := 0
  690. for copyStatus == blob.CopyStatusTypePending {
  691. // Poll until the copy is complete.
  692. time.Sleep(500 * time.Millisecond)
  693. resp, err := dstBlob.GetProperties(ctx, &blob.GetPropertiesOptions{})
  694. if err != nil {
  695. // A GetProperties failure may be transient, so allow a couple
  696. // of them before giving up.
  697. nErrors++
  698. if ctx.Err() != nil || nErrors == 3 {
  699. metric.AZCopyObjectCompleted(err)
  700. return err
  701. }
  702. } else {
  703. copyStatus = blob.CopyStatusType(util.GetStringFromPointer((*string)(resp.CopyStatus)))
  704. }
  705. }
  706. if copyStatus != blob.CopyStatusTypeSuccess {
  707. err := fmt.Errorf("copy failed with status: %s", copyStatus)
  708. metric.AZCopyObjectCompleted(err)
  709. return err
  710. }
  711. metric.AZCopyObjectCompleted(nil)
  712. return nil
  713. }
  714. func (fs *AzureBlobFs) renameInternal(source, target string, fi os.FileInfo, recursion int) (int, int64, error) {
  715. var numFiles int
  716. var filesSize int64
  717. if fi.IsDir() {
  718. if renameMode == 0 {
  719. hasContents, err := fs.hasContents(source)
  720. if err != nil {
  721. return numFiles, filesSize, err
  722. }
  723. if hasContents {
  724. return numFiles, filesSize, fmt.Errorf("%w: cannot rename non empty directory: %q", ErrVfsUnsupported, source)
  725. }
  726. }
  727. if err := fs.mkdirInternal(target); err != nil {
  728. return numFiles, filesSize, err
  729. }
  730. if renameMode == 1 {
  731. files, size, err := doRecursiveRename(fs, source, target, fs.renameInternal, recursion)
  732. numFiles += files
  733. filesSize += size
  734. if err != nil {
  735. return numFiles, filesSize, err
  736. }
  737. }
  738. } else {
  739. if err := fs.copyFileInternal(source, target); err != nil {
  740. return numFiles, filesSize, err
  741. }
  742. numFiles++
  743. filesSize += fi.Size()
  744. }
  745. err := fs.skipNotExistErr(fs.Remove(source, fi.IsDir()))
  746. return numFiles, filesSize, err
  747. }
  748. func (fs *AzureBlobFs) skipNotExistErr(err error) error {
  749. if fs.IsNotExist(err) {
  750. return nil
  751. }
  752. return err
  753. }
  754. func (fs *AzureBlobFs) mkdirInternal(name string) error {
  755. _, w, _, err := fs.Create(name, -1, 0)
  756. if err != nil {
  757. return err
  758. }
  759. return w.Close()
  760. }
  761. func (fs *AzureBlobFs) hasContents(name string) (bool, error) {
  762. result := false
  763. prefix := fs.getPrefix(name)
  764. maxResults := int32(1)
  765. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  766. MaxResults: &maxResults,
  767. Prefix: &prefix,
  768. })
  769. if pager.More() {
  770. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  771. defer cancelFn()
  772. resp, err := pager.NextPage(ctx)
  773. if err != nil {
  774. metric.AZListObjectsCompleted(err)
  775. return result, err
  776. }
  777. result = len(resp.ListBlobsFlatSegmentResponse.Segment.BlobItems) > 0
  778. }
  779. metric.AZListObjectsCompleted(nil)
  780. return result, nil
  781. }
  782. func (fs *AzureBlobFs) downloadPart(ctx context.Context, blockBlob *blockblob.Client, buf []byte,
  783. w io.WriterAt, offset, count, writeOffset int64,
  784. ) error {
  785. if count == 0 {
  786. return nil
  787. }
  788. resp, err := blockBlob.DownloadStream(ctx, &blob.DownloadStreamOptions{
  789. Range: blob.HTTPRange{
  790. Offset: offset,
  791. Count: count,
  792. },
  793. })
  794. if err != nil {
  795. return err
  796. }
  797. defer resp.DownloadResponse.Body.Close()
  798. _, err = io.ReadAtLeast(resp.DownloadResponse.Body, buf, int(count))
  799. if err != nil {
  800. return err
  801. }
  802. _, err = fs.writeAtFull(w, buf, writeOffset, int(count))
  803. return err
  804. }
  805. func (fs *AzureBlobFs) handleMultipartDownload(ctx context.Context, blockBlob *blockblob.Client,
  806. offset int64, writer io.WriterAt, pipeReader PipeReader,
  807. ) error {
  808. props, err := blockBlob.GetProperties(ctx, &blob.GetPropertiesOptions{})
  809. metric.AZHeadObjectCompleted(err)
  810. if err != nil {
  811. fsLog(fs, logger.LevelError, "unable to get blob properties, download aborted: %+v", err)
  812. return err
  813. }
  814. if readMetadata > 0 && pipeReader != nil {
  815. pipeReader.setMetadataFromPointerVal(props.Metadata)
  816. }
  817. contentLength := util.GetIntFromPointer(props.ContentLength)
  818. sizeToDownload := contentLength - offset
  819. if sizeToDownload < 0 {
  820. fsLog(fs, logger.LevelError, "invalid multipart download size or offset, size: %v, offset: %v, size to download: %v",
  821. contentLength, offset, sizeToDownload)
  822. return errors.New("the requested offset exceeds the file size")
  823. }
  824. if sizeToDownload == 0 {
  825. fsLog(fs, logger.LevelDebug, "nothing to download, offset %v, content length %v", offset, contentLength)
  826. return nil
  827. }
  828. partSize := fs.config.DownloadPartSize
  829. guard := make(chan struct{}, fs.config.DownloadConcurrency)
  830. blockCtxTimeout := time.Duration(fs.config.DownloadPartSize/(1024*1024)) * time.Minute
  831. pool := newBufferAllocator(int(partSize))
  832. finished := false
  833. var wg sync.WaitGroup
  834. var errOnce sync.Once
  835. var hasError atomic.Bool
  836. var poolError error
  837. poolCtx, poolCancel := context.WithCancel(ctx)
  838. defer poolCancel()
  839. for part := 0; !finished; part++ {
  840. start := offset
  841. end := offset + partSize
  842. if end >= contentLength {
  843. end = contentLength
  844. finished = true
  845. }
  846. writeOffset := int64(part) * partSize
  847. offset = end
  848. guard <- struct{}{}
  849. if hasError.Load() {
  850. fsLog(fs, logger.LevelDebug, "pool error, download for part %v not started", part)
  851. break
  852. }
  853. buf := pool.getBuffer()
  854. wg.Add(1)
  855. go func(start, end, writeOffset int64, buf []byte) {
  856. defer func() {
  857. pool.releaseBuffer(buf)
  858. <-guard
  859. wg.Done()
  860. }()
  861. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  862. defer cancelFn()
  863. count := end - start
  864. err := fs.downloadPart(innerCtx, blockBlob, buf, writer, start, count, writeOffset)
  865. if err != nil {
  866. errOnce.Do(func() {
  867. fsLog(fs, logger.LevelError, "multipart download error: %+v", err)
  868. hasError.Store(true)
  869. poolError = fmt.Errorf("multipart download error: %w", err)
  870. poolCancel()
  871. })
  872. }
  873. }(start, end, writeOffset, buf)
  874. }
  875. wg.Wait()
  876. close(guard)
  877. pool.free()
  878. return poolError
  879. }
  880. func (fs *AzureBlobFs) handleMultipartUpload(ctx context.Context, reader io.Reader,
  881. blockBlob *blockblob.Client, httpHeaders *blob.HTTPHeaders, metadata map[string]*string,
  882. ) error {
  883. partSize := fs.config.UploadPartSize
  884. guard := make(chan struct{}, fs.config.UploadConcurrency)
  885. blockCtxTimeout := time.Duration(fs.config.UploadPartSize/(1024*1024)) * time.Minute
  886. // sync.Pool seems to use a lot of memory so prefer our own, very simple, allocator
  887. // we only need to recycle few byte slices
  888. pool := newBufferAllocator(int(partSize))
  889. finished := false
  890. var blocks []string
  891. var wg sync.WaitGroup
  892. var errOnce sync.Once
  893. var hasError atomic.Bool
  894. var poolError error
  895. poolCtx, poolCancel := context.WithCancel(ctx)
  896. defer poolCancel()
  897. for part := 0; !finished; part++ {
  898. buf := pool.getBuffer()
  899. n, err := fs.readFill(reader, buf)
  900. if err == io.EOF {
  901. // read finished, if n > 0 we need to process the last data chunck
  902. if n == 0 {
  903. pool.releaseBuffer(buf)
  904. break
  905. }
  906. finished = true
  907. } else if err != nil {
  908. pool.releaseBuffer(buf)
  909. pool.free()
  910. return err
  911. }
  912. // Block IDs are unique values to avoid issue if 2+ clients are uploading blocks
  913. // at the same time causing CommitBlockList to get a mix of blocks from all the clients.
  914. generatedUUID, err := uuid.NewRandom()
  915. if err != nil {
  916. pool.releaseBuffer(buf)
  917. pool.free()
  918. return fmt.Errorf("unable to generate block ID: %w", err)
  919. }
  920. blockID := base64.StdEncoding.EncodeToString([]byte(generatedUUID.String()))
  921. blocks = append(blocks, blockID)
  922. guard <- struct{}{}
  923. if hasError.Load() {
  924. fsLog(fs, logger.LevelError, "pool error, upload for part %d not started", part)
  925. pool.releaseBuffer(buf)
  926. break
  927. }
  928. wg.Add(1)
  929. go func(blockID string, buf []byte, bufSize int) {
  930. defer func() {
  931. pool.releaseBuffer(buf)
  932. <-guard
  933. wg.Done()
  934. }()
  935. bufferReader := &bytesReaderWrapper{
  936. Reader: bytes.NewReader(buf[:bufSize]),
  937. }
  938. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  939. defer cancelFn()
  940. _, err := blockBlob.StageBlock(innerCtx, blockID, bufferReader, &blockblob.StageBlockOptions{})
  941. if err != nil {
  942. errOnce.Do(func() {
  943. fsLog(fs, logger.LevelDebug, "multipart upload error: %+v", err)
  944. hasError.Store(true)
  945. poolError = fmt.Errorf("multipart upload error: %w", err)
  946. poolCancel()
  947. })
  948. }
  949. }(blockID, buf, n)
  950. }
  951. wg.Wait()
  952. close(guard)
  953. pool.free()
  954. if poolError != nil {
  955. return poolError
  956. }
  957. commitOptions := blockblob.CommitBlockListOptions{
  958. HTTPHeaders: httpHeaders,
  959. Metadata: metadata,
  960. }
  961. if fs.config.AccessTier != "" {
  962. commitOptions.Tier = (*blob.AccessTier)(&fs.config.AccessTier)
  963. }
  964. _, err := blockBlob.CommitBlockList(ctx, blocks, &commitOptions)
  965. return err
  966. }
  967. func (*AzureBlobFs) writeAtFull(w io.WriterAt, buf []byte, offset int64, count int) (int, error) {
  968. written := 0
  969. for written < count {
  970. n, err := w.WriteAt(buf[written:count], offset+int64(written))
  971. written += n
  972. if err != nil {
  973. return written, err
  974. }
  975. }
  976. return written, nil
  977. }
  978. // copied from rclone
  979. func (*AzureBlobFs) readFill(r io.Reader, buf []byte) (n int, err error) {
  980. var nn int
  981. for n < len(buf) && err == nil {
  982. nn, err = r.Read(buf[n:])
  983. n += nn
  984. }
  985. return n, err
  986. }
  987. func (fs *AzureBlobFs) getCopyOptions() *blob.StartCopyFromURLOptions {
  988. copyOptions := &blob.StartCopyFromURLOptions{}
  989. if fs.config.AccessTier != "" {
  990. copyOptions.Tier = (*blob.AccessTier)(&fs.config.AccessTier)
  991. }
  992. return copyOptions
  993. }
  994. func (fs *AzureBlobFs) downloadToWriter(name string, w PipeWriter) (int64, error) {
  995. fsLog(fs, logger.LevelDebug, "starting download before resuming upload, path %q", name)
  996. ctx, cancelFn := context.WithTimeout(context.Background(), preResumeTimeout)
  997. defer cancelFn()
  998. blockBlob := fs.containerClient.NewBlockBlobClient(name)
  999. err := fs.handleMultipartDownload(ctx, blockBlob, 0, w, nil)
  1000. n := w.GetWrittenBytes()
  1001. fsLog(fs, logger.LevelDebug, "download before resuming upload completed, path %q size: %d, err: %+v",
  1002. name, n, err)
  1003. metric.AZTransferCompleted(n, 1, err)
  1004. return n, err
  1005. }
  1006. func checkDirectoryMarkers(contentType string, metadata map[string]*string) bool {
  1007. if contentType == dirMimeType {
  1008. return true
  1009. }
  1010. for k, v := range metadata {
  1011. if strings.ToLower(k) == azFolderKey {
  1012. return strings.ToLower(util.GetStringFromPointer(v)) == "true"
  1013. }
  1014. }
  1015. return false
  1016. }
  1017. func getAzContainerClientOptions() *container.ClientOptions {
  1018. return &container.ClientOptions{
  1019. ClientOptions: azcore.ClientOptions{
  1020. Telemetry: policy.TelemetryOptions{
  1021. ApplicationID: version.GetVersionHash(),
  1022. },
  1023. },
  1024. }
  1025. }
  1026. type bytesReaderWrapper struct {
  1027. *bytes.Reader
  1028. }
  1029. func (b *bytesReaderWrapper) Close() error {
  1030. return nil
  1031. }
  1032. type bufferAllocator struct {
  1033. sync.Mutex
  1034. available [][]byte
  1035. bufferSize int
  1036. finalized bool
  1037. }
  1038. func newBufferAllocator(size int) *bufferAllocator {
  1039. return &bufferAllocator{
  1040. bufferSize: size,
  1041. finalized: false,
  1042. }
  1043. }
  1044. func (b *bufferAllocator) getBuffer() []byte {
  1045. b.Lock()
  1046. defer b.Unlock()
  1047. if len(b.available) > 0 {
  1048. var result []byte
  1049. truncLength := len(b.available) - 1
  1050. result = b.available[truncLength]
  1051. b.available[truncLength] = nil
  1052. b.available = b.available[:truncLength]
  1053. return result
  1054. }
  1055. return make([]byte, b.bufferSize)
  1056. }
  1057. func (b *bufferAllocator) releaseBuffer(buf []byte) {
  1058. b.Lock()
  1059. defer b.Unlock()
  1060. if b.finalized || len(buf) != b.bufferSize {
  1061. return
  1062. }
  1063. b.available = append(b.available, buf)
  1064. }
  1065. func (b *bufferAllocator) free() {
  1066. b.Lock()
  1067. defer b.Unlock()
  1068. b.available = nil
  1069. b.finalized = true
  1070. }
  1071. type azureBlobDirLister struct {
  1072. baseDirLister
  1073. paginator *runtime.Pager[container.ListBlobsHierarchyResponse]
  1074. timeout time.Duration
  1075. prefix string
  1076. prefixes map[string]bool
  1077. metricUpdated bool
  1078. }
  1079. func (l *azureBlobDirLister) Next(limit int) ([]os.FileInfo, error) {
  1080. if limit <= 0 {
  1081. return nil, errInvalidDirListerLimit
  1082. }
  1083. if len(l.cache) >= limit {
  1084. return l.returnFromCache(limit), nil
  1085. }
  1086. if !l.paginator.More() {
  1087. if !l.metricUpdated {
  1088. l.metricUpdated = true
  1089. metric.AZListObjectsCompleted(nil)
  1090. }
  1091. return l.returnFromCache(limit), io.EOF
  1092. }
  1093. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(l.timeout))
  1094. defer cancelFn()
  1095. page, err := l.paginator.NextPage(ctx)
  1096. if err != nil {
  1097. metric.AZListObjectsCompleted(err)
  1098. return l.cache, err
  1099. }
  1100. for _, blobPrefix := range page.ListBlobsHierarchySegmentResponse.Segment.BlobPrefixes {
  1101. name := util.GetStringFromPointer(blobPrefix.Name)
  1102. // we don't support prefixes == "/" this will be sent if a key starts with "/"
  1103. if name == "" || name == "/" {
  1104. continue
  1105. }
  1106. // sometime we have duplicate prefixes, maybe an Azurite bug
  1107. name = strings.TrimPrefix(name, l.prefix)
  1108. if _, ok := l.prefixes[strings.TrimSuffix(name, "/")]; ok {
  1109. continue
  1110. }
  1111. l.cache = append(l.cache, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  1112. l.prefixes[strings.TrimSuffix(name, "/")] = true
  1113. }
  1114. for _, blobItem := range page.ListBlobsHierarchySegmentResponse.Segment.BlobItems {
  1115. name := util.GetStringFromPointer(blobItem.Name)
  1116. name = strings.TrimPrefix(name, l.prefix)
  1117. size := int64(0)
  1118. isDir := false
  1119. modTime := time.Unix(0, 0)
  1120. if blobItem.Properties != nil {
  1121. size = util.GetIntFromPointer(blobItem.Properties.ContentLength)
  1122. modTime = util.GetTimeFromPointer(blobItem.Properties.LastModified)
  1123. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  1124. isDir = checkDirectoryMarkers(contentType, blobItem.Metadata)
  1125. if isDir {
  1126. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  1127. if _, ok := l.prefixes[name]; ok {
  1128. continue
  1129. }
  1130. l.prefixes[name] = true
  1131. }
  1132. if val := getAzureLastModified(blobItem.Metadata); val > 0 {
  1133. modTime = util.GetTimeFromMsecSinceEpoch(val)
  1134. }
  1135. }
  1136. l.cache = append(l.cache, NewFileInfo(name, isDir, size, modTime, false))
  1137. }
  1138. return l.returnFromCache(limit), nil
  1139. }
  1140. func (l *azureBlobDirLister) Close() error {
  1141. clear(l.prefixes)
  1142. return l.baseDirLister.Close()
  1143. }