azblobfs.go 35 KB

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