azblobfs.go 32 KB

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