azblobfs.go 33 KB

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