azblobfs.go 35 KB

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