azblobfs.go 36 KB

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