azblobfs.go 33 KB

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