azblobfs.go 37 KB

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