azblobfs.go 33 KB

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