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