azblobfs.go 35 KB

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