azblobfs.go 37 KB

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