azblobfs.go 36 KB

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