azblobfs.go 37 KB

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