azblobfs.go 37 KB

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