azblobfs.go 35 KB

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