azblobfs.go 35 KB

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