azblobfs.go 33 KB

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