azurestorage.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package storage
  2. // Fork from Thanos S3 Bucket support to reuse configuration options
  3. // Licensed under the Apache License 2.0
  4. // https://github.com/thanos-io/thanos/blob/main/pkg/objstore/s3/s3.go
  5. import (
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "regexp"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/opencost/opencost/pkg/log"
  18. "github.com/Azure/azure-pipeline-go/pipeline"
  19. blob "github.com/Azure/azure-storage-blob-go/azblob"
  20. "github.com/Azure/go-autorest/autorest/adal"
  21. "github.com/Azure/go-autorest/autorest/azure/auth"
  22. "github.com/pkg/errors"
  23. "github.com/prometheus/common/model"
  24. "gopkg.in/yaml.v2"
  25. )
  26. const (
  27. azureDefaultEndpoint = "blob.core.windows.net"
  28. )
  29. var errorCodeRegex = regexp.MustCompile(`X-Ms-Error-Code:\D*\[(\w+)\]`)
  30. // Set default retry values to default Azure values. 0 = use Default Azure.
  31. var defaultAzureConfig = AzureConfig{
  32. PipelineConfig: PipelineConfig{
  33. MaxTries: 0,
  34. TryTimeout: 0,
  35. RetryDelay: 0,
  36. MaxRetryDelay: 0,
  37. },
  38. ReaderConfig: ReaderConfig{
  39. MaxRetryRequests: 0,
  40. },
  41. HTTPConfig: AzureHTTPConfig{
  42. IdleConnTimeout: model.Duration(90 * time.Second),
  43. ResponseHeaderTimeout: model.Duration(2 * time.Minute),
  44. TLSHandshakeTimeout: model.Duration(10 * time.Second),
  45. ExpectContinueTimeout: model.Duration(1 * time.Second),
  46. MaxIdleConns: 100,
  47. MaxIdleConnsPerHost: 100,
  48. MaxConnsPerHost: 0,
  49. DisableCompression: false,
  50. },
  51. }
  52. func init() {
  53. // Disable `ForceLog` in Azure storage module
  54. // As the time of this patch, the logging function in the storage module isn't correctly
  55. // detecting expected REST errors like 404 and so outputs them to syslog along with a stacktrace.
  56. // https://github.com/Azure/azure-storage-blob-go/issues/214
  57. //
  58. // This needs to be done at startup because the underlying variable is not thread safe.
  59. // https://github.com/Azure/azure-pipeline-go/blob/dc95902f1d32034f8f743ccc6c3f2eb36b84da27/pipeline/core.go#L276-L283
  60. pipeline.SetForceLogEnabled(false)
  61. }
  62. // AzureConfig Azure storage configuration.
  63. type AzureConfig struct {
  64. StorageAccountName string `yaml:"storage_account"`
  65. StorageAccountKey string `yaml:"storage_account_key"`
  66. ContainerName string `yaml:"container"`
  67. Endpoint string `yaml:"endpoint"`
  68. MaxRetries int `yaml:"max_retries"`
  69. MSIResource string `yaml:"msi_resource"`
  70. UserAssignedID string `yaml:"user_assigned_id"`
  71. PipelineConfig PipelineConfig `yaml:"pipeline_config"`
  72. ReaderConfig ReaderConfig `yaml:"reader_config"`
  73. HTTPConfig AzureHTTPConfig `yaml:"http_config"`
  74. }
  75. type ReaderConfig struct {
  76. MaxRetryRequests int `yaml:"max_retry_requests"`
  77. }
  78. type PipelineConfig struct {
  79. MaxTries int32 `yaml:"max_tries"`
  80. TryTimeout model.Duration `yaml:"try_timeout"`
  81. RetryDelay model.Duration `yaml:"retry_delay"`
  82. MaxRetryDelay model.Duration `yaml:"max_retry_delay"`
  83. }
  84. type AzureHTTPConfig struct {
  85. IdleConnTimeout model.Duration `yaml:"idle_conn_timeout"`
  86. ResponseHeaderTimeout model.Duration `yaml:"response_header_timeout"`
  87. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  88. TLSHandshakeTimeout model.Duration `yaml:"tls_handshake_timeout"`
  89. ExpectContinueTimeout model.Duration `yaml:"expect_continue_timeout"`
  90. MaxIdleConns int `yaml:"max_idle_conns"`
  91. MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host"`
  92. MaxConnsPerHost int `yaml:"max_conns_per_host"`
  93. DisableCompression bool `yaml:"disable_compression"`
  94. TLSConfig TLSConfig `yaml:"tls_config"`
  95. }
  96. // AzureStorage implements the storage.Storage interface against Azure APIs.
  97. type AzureStorage struct {
  98. name string
  99. containerURL blob.ContainerURL
  100. config *AzureConfig
  101. }
  102. // Validate checks to see if any of the config options are set.
  103. func (conf *AzureConfig) validate() error {
  104. var errMsg []string
  105. if conf.MSIResource == "" {
  106. if conf.UserAssignedID == "" {
  107. if conf.StorageAccountName == "" ||
  108. conf.StorageAccountKey == "" {
  109. errMsg = append(errMsg, "invalid Azure storage configuration")
  110. }
  111. if conf.StorageAccountName == "" && conf.StorageAccountKey != "" {
  112. errMsg = append(errMsg, "no Azure storage_account specified while storage_account_key is present in config file; both should be present")
  113. }
  114. if conf.StorageAccountName != "" && conf.StorageAccountKey == "" {
  115. errMsg = append(errMsg, "no Azure storage_account_key specified while storage_account is present in config file; both should be present")
  116. }
  117. } else {
  118. if conf.StorageAccountName == "" {
  119. errMsg = append(errMsg, "UserAssignedID is configured but storage account name is missing")
  120. }
  121. if conf.StorageAccountKey != "" {
  122. errMsg = append(errMsg, "UserAssignedID is configured but storage account key is used")
  123. }
  124. }
  125. } else {
  126. if conf.StorageAccountName == "" {
  127. errMsg = append(errMsg, "MSI resource is configured but storage account name is missing")
  128. }
  129. if conf.StorageAccountKey != "" {
  130. errMsg = append(errMsg, "MSI resource is configured but storage account key is used")
  131. }
  132. }
  133. if conf.ContainerName == "" {
  134. errMsg = append(errMsg, "no Azure container specified")
  135. }
  136. if conf.Endpoint == "" {
  137. conf.Endpoint = azureDefaultEndpoint
  138. }
  139. if conf.PipelineConfig.MaxTries < 0 {
  140. errMsg = append(errMsg, "The value of max_tries must be greater than or equal to 0 in the config file")
  141. }
  142. if conf.ReaderConfig.MaxRetryRequests < 0 {
  143. errMsg = append(errMsg, "The value of max_retry_requests must be greater than or equal to 0 in the config file")
  144. }
  145. if len(errMsg) > 0 {
  146. return errors.New(strings.Join(errMsg, ", "))
  147. }
  148. return nil
  149. }
  150. // parseAzureConfig unmarshals a buffer into a Config with default values.
  151. func parseAzureConfig(conf []byte) (AzureConfig, error) {
  152. config := defaultAzureConfig
  153. if err := yaml.UnmarshalStrict(conf, &config); err != nil {
  154. return AzureConfig{}, err
  155. }
  156. // If we don't have config specific retry values but we do have the generic MaxRetries.
  157. // This is for backwards compatibility but also ease of configuration.
  158. if config.MaxRetries > 0 {
  159. if config.PipelineConfig.MaxTries == 0 {
  160. config.PipelineConfig.MaxTries = int32(config.MaxRetries)
  161. }
  162. if config.ReaderConfig.MaxRetryRequests == 0 {
  163. config.ReaderConfig.MaxRetryRequests = config.MaxRetries
  164. }
  165. }
  166. return config, nil
  167. }
  168. // NewAzureStorage returns a new Storage using the provided Azure config.
  169. func NewAzureStorage(azureConfig []byte) (*AzureStorage, error) {
  170. log.Debugf("Creating new Azure Bucket Connection")
  171. conf, err := parseAzureConfig(azureConfig)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return NewAzureStorageWith(conf)
  176. }
  177. // NewAzureStorageWith returns a new Storage using the provided Azure config struct.
  178. func NewAzureStorageWith(conf AzureConfig) (*AzureStorage, error) {
  179. if err := conf.validate(); err != nil {
  180. return nil, err
  181. }
  182. ctx := context.Background()
  183. container, err := createContainer(ctx, conf)
  184. if err != nil {
  185. ret, ok := err.(blob.StorageError)
  186. if !ok {
  187. return nil, errors.Wrapf(err, "Azure API return unexpected error: %T\n", err)
  188. }
  189. if ret.ServiceCode() == "ContainerAlreadyExists" {
  190. log.Debugf("Getting connection to existing Azure blob container: %s", conf.ContainerName)
  191. container, err = getContainer(ctx, conf)
  192. if err != nil {
  193. return nil, errors.Wrapf(err, "cannot get existing Azure blob container: %s", container)
  194. }
  195. } else {
  196. return nil, errors.Wrapf(err, "error creating Azure blob container: %s", container)
  197. }
  198. } else {
  199. log.Infof("Azure blob container successfully created. Address: %s", container)
  200. }
  201. return &AzureStorage{
  202. name: conf.ContainerName,
  203. containerURL: container,
  204. config: &conf,
  205. }, nil
  206. }
  207. // Name returns the bucket name for azure storage.
  208. func (as *AzureStorage) Name() string {
  209. return as.name
  210. }
  211. // StorageType returns a string identifier for the type of storage used by the implementation.
  212. func (as *AzureStorage) StorageType() StorageType {
  213. return StorageTypeBucketAzure
  214. }
  215. // FullPath returns the storage working path combined with the path provided
  216. func (as *AzureStorage) FullPath(name string) string {
  217. name = trimLeading(name)
  218. return name
  219. }
  220. // Stat returns the StorageStats for the specific path.
  221. func (b *AzureStorage) Stat(name string) (*StorageInfo, error) {
  222. name = trimLeading(name)
  223. ctx := context.Background()
  224. blobURL := getBlobURL(name, b.containerURL)
  225. props, err := blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{})
  226. if err != nil {
  227. return nil, err
  228. }
  229. return &StorageInfo{
  230. Name: trimName(name),
  231. Size: props.ContentLength(),
  232. ModTime: props.LastModified(),
  233. }, nil
  234. }
  235. // Read uses the relative path of the storage combined with the provided path to
  236. // read the contents.
  237. func (b *AzureStorage) Read(name string) ([]byte, error) {
  238. name = trimLeading(name)
  239. ctx := context.Background()
  240. log.Debugf("AzureStorage::Read(%s)", name)
  241. reader, err := b.getBlobReader(ctx, name, 0, blob.CountToEnd)
  242. if err != nil {
  243. return nil, err
  244. }
  245. data, err := io.ReadAll(reader)
  246. if err != nil {
  247. return nil, err
  248. }
  249. return data, nil
  250. }
  251. // Write uses the relative path of the storage combined with the provided path
  252. // to write a new file or overwrite an existing file.
  253. func (b *AzureStorage) Write(name string, data []byte) error {
  254. name = trimLeading(name)
  255. ctx := context.Background()
  256. log.Debugf("AzureStorage::Write(%s)", name)
  257. blobURL := getBlobURL(name, b.containerURL)
  258. r := bytes.NewReader(data)
  259. if _, err := blob.UploadStreamToBlockBlob(ctx, r, blobURL,
  260. blob.UploadStreamToBlockBlobOptions{
  261. BufferSize: len(data),
  262. MaxBuffers: 1,
  263. },
  264. ); err != nil {
  265. return errors.Wrapf(err, "cannot upload Azure blob, address: %s", name)
  266. }
  267. return nil
  268. }
  269. // Remove uses the relative path of the storage combined with the provided path to
  270. // remove a file from storage permanently.
  271. func (b *AzureStorage) Remove(name string) error {
  272. name = trimLeading(name)
  273. log.Debugf("AzureStorage::Remove(%s)", name)
  274. ctx := context.Background()
  275. blobURL := getBlobURL(name, b.containerURL)
  276. if _, err := blobURL.Delete(ctx, blob.DeleteSnapshotsOptionInclude, blob.BlobAccessConditions{}); err != nil {
  277. return errors.Wrapf(err, "error deleting blob, address: %s", name)
  278. }
  279. return nil
  280. }
  281. // Exists uses the relative path of the storage combined with the provided path to
  282. // determine if the file exists.
  283. func (b *AzureStorage) Exists(name string) (bool, error) {
  284. name = trimLeading(name)
  285. ctx := context.Background()
  286. blobURL := getBlobURL(name, b.containerURL)
  287. if _, err := blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{}); err != nil {
  288. if b.isObjNotFoundErr(err) {
  289. return false, nil
  290. }
  291. return false, errors.Wrapf(err, "cannot get properties for Azure blob, address: %s", name)
  292. }
  293. return true, nil
  294. }
  295. // List uses the relative path of the storage combined with the provided path to return
  296. // storage information for the files.
  297. func (b *AzureStorage) List(path string) ([]*StorageInfo, error) {
  298. path = trimLeading(path)
  299. log.Debugf("AzureStorage::List(%s)", path)
  300. ctx := context.Background()
  301. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  302. // object itself as one prefix item.
  303. if path != "" {
  304. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  305. }
  306. marker := blob.Marker{}
  307. listOptions := blob.ListBlobsSegmentOptions{Prefix: path}
  308. var names []string
  309. for i := 1; ; i++ {
  310. var blobItems []blob.BlobItemInternal
  311. list, err := b.containerURL.ListBlobsHierarchySegment(ctx, marker, DirDelim, listOptions)
  312. if err != nil {
  313. return nil, errors.Wrapf(err, "cannot list hierarchy blobs with prefix %s (iteration #%d)", path, i)
  314. }
  315. marker = list.NextMarker
  316. blobItems = list.Segment.BlobItems
  317. for _, blob := range blobItems {
  318. names = append(names, blob.Name)
  319. }
  320. // Continue iterating if we are not done.
  321. if !marker.NotDone() {
  322. break
  323. }
  324. log.Debugf("Requesting next iteration of listing blobs. Entries: %d, iteration: %d", len(names), i)
  325. }
  326. // get the storage information for each blob (really unfortunate we have to do this)
  327. var lock sync.Mutex
  328. var stats []*StorageInfo
  329. var wg sync.WaitGroup
  330. wg.Add(len(names))
  331. for i := 0; i < len(names); i++ {
  332. go func(n string) {
  333. defer wg.Done()
  334. stat, err := b.Stat(n)
  335. if err != nil {
  336. log.Errorf("Error statting blob %s: %s", n, err)
  337. } else {
  338. lock.Lock()
  339. stats = append(stats, stat)
  340. lock.Unlock()
  341. }
  342. }(names[i])
  343. }
  344. wg.Wait()
  345. return stats, nil
  346. }
  347. func (b *AzureStorage) ListDirectories(path string) ([]*StorageInfo, error) {
  348. path = trimLeading(path)
  349. log.Debugf("AzureStorage::ListDirectories(%s)", path)
  350. ctx := context.Background()
  351. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  352. // object itself as one prefix item.
  353. if path != "" {
  354. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  355. }
  356. marker := blob.Marker{}
  357. listOptions := blob.ListBlobsSegmentOptions{Prefix: path}
  358. var stats []*StorageInfo
  359. for i := 1; ; i++ {
  360. var blobPrefixes []blob.BlobPrefix
  361. list, err := b.containerURL.ListBlobsHierarchySegment(ctx, marker, DirDelim, listOptions)
  362. if err != nil {
  363. return nil, errors.Wrapf(err, "cannot list hierarchy blobs with prefix %s (iteration #%d)", path, i)
  364. }
  365. marker = list.NextMarker
  366. blobPrefixes = list.Segment.BlobPrefixes
  367. for _, prefix := range blobPrefixes {
  368. stats = append(stats, &StorageInfo{
  369. Name: trimLeading(prefix.Name),
  370. })
  371. }
  372. // Continue iterating if we are not done.
  373. if !marker.NotDone() {
  374. break
  375. }
  376. log.Debugf("Requesting next iteration of listing blobs. Entries: %d, iteration: %d", len(stats), i)
  377. }
  378. return stats, nil
  379. }
  380. // IsObjNotFoundErr returns true if error means that object is not found. Relevant to Get operations.
  381. func (b *AzureStorage) isObjNotFoundErr(err error) bool {
  382. if err == nil {
  383. return false
  384. }
  385. errorCode := parseError(err.Error())
  386. if errorCode == "InvalidUri" || errorCode == "BlobNotFound" {
  387. return true
  388. }
  389. return false
  390. }
  391. func (b *AzureStorage) getBlobReader(ctx context.Context, name string, offset, length int64) (io.ReadCloser, error) {
  392. log.Debugf("Getting blob: %s, offset: %d, length: %d", name, offset, length)
  393. if name == "" {
  394. return nil, errors.New("X-Ms-Error-Code: [EmptyContainerName]")
  395. }
  396. exists, err := b.Exists(name)
  397. if err != nil {
  398. return nil, errors.Wrapf(err, "cannot get blob reader: %s", name)
  399. }
  400. if !exists {
  401. return nil, errors.New("X-Ms-Error-Code: [BlobNotFound]")
  402. }
  403. blobURL := getBlobURL(name, b.containerURL)
  404. if err != nil {
  405. return nil, errors.Wrapf(err, "cannot get Azure blob URL, address: %s", name)
  406. }
  407. var props *blob.BlobGetPropertiesResponse
  408. props, err = blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{})
  409. if err != nil {
  410. return nil, errors.Wrapf(err, "cannot get properties for container: %s", name)
  411. }
  412. var size int64
  413. // If a length is specified and it won't go past the end of the file,
  414. // then set it as the size.
  415. if length > 0 && length <= props.ContentLength()-offset {
  416. size = length
  417. log.Debugf("set size to length. size: %d, length: %d, offset: %d, name: %s", size, length, offset, name)
  418. } else {
  419. size = props.ContentLength() - offset
  420. log.Debugf("set size to go to EOF. contentlength: %d, size: %d, length: %d, offset: %d, name: %s", props.ContentLength(), size, length, offset, name)
  421. }
  422. destBuffer := make([]byte, size)
  423. if err := blob.DownloadBlobToBuffer(context.Background(), blobURL.BlobURL, offset, size,
  424. destBuffer, blob.DownloadFromBlobOptions{
  425. BlockSize: blob.BlobDefaultDownloadBlockSize,
  426. Parallelism: uint16(3),
  427. Progress: nil,
  428. RetryReaderOptionsPerBlock: blob.RetryReaderOptions{
  429. MaxRetryRequests: b.config.ReaderConfig.MaxRetryRequests,
  430. },
  431. },
  432. ); err != nil {
  433. return nil, errors.Wrapf(err, "cannot download blob, address: %s", blobURL.BlobURL)
  434. }
  435. return io.NopCloser(bytes.NewReader(destBuffer)), nil
  436. }
  437. func getAzureStorageCredentials(conf AzureConfig) (blob.Credential, error) {
  438. if conf.MSIResource != "" || conf.UserAssignedID != "" {
  439. spt, err := getServicePrincipalToken(conf)
  440. if err != nil {
  441. return nil, err
  442. }
  443. if err := spt.Refresh(); err != nil {
  444. return nil, err
  445. }
  446. return blob.NewTokenCredential(spt.Token().AccessToken, func(tc blob.TokenCredential) time.Duration {
  447. err := spt.Refresh()
  448. if err != nil {
  449. log.Errorf("could not refresh MSI token. err: %s", err)
  450. // Retry later as the error can be related to API throttling
  451. return 30 * time.Second
  452. }
  453. tc.SetToken(spt.Token().AccessToken)
  454. return spt.Token().Expires().Sub(time.Now().Add(2 * time.Minute))
  455. }), nil
  456. }
  457. credential, err := blob.NewSharedKeyCredential(conf.StorageAccountName, conf.StorageAccountKey)
  458. if err != nil {
  459. return nil, err
  460. }
  461. return credential, nil
  462. }
  463. func getServicePrincipalToken(conf AzureConfig) (*adal.ServicePrincipalToken, error) {
  464. resource := conf.MSIResource
  465. if resource == "" {
  466. resource = fmt.Sprintf("https://%s.%s", conf.StorageAccountName, conf.Endpoint)
  467. }
  468. msiConfig := auth.MSIConfig{
  469. Resource: resource,
  470. }
  471. if conf.UserAssignedID != "" {
  472. log.Debugf("using user assigned identity. clientId: %s", conf.UserAssignedID)
  473. msiConfig.ClientID = conf.UserAssignedID
  474. } else {
  475. log.Debugf("using system assigned identity")
  476. }
  477. return msiConfig.ServicePrincipalToken()
  478. }
  479. func getContainerURL(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  480. credentials, err := getAzureStorageCredentials(conf)
  481. if err != nil {
  482. return blob.ContainerURL{}, err
  483. }
  484. retryOptions := blob.RetryOptions{
  485. MaxTries: conf.PipelineConfig.MaxTries,
  486. TryTimeout: time.Duration(conf.PipelineConfig.TryTimeout),
  487. RetryDelay: time.Duration(conf.PipelineConfig.RetryDelay),
  488. MaxRetryDelay: time.Duration(conf.PipelineConfig.MaxRetryDelay),
  489. }
  490. if deadline, ok := ctx.Deadline(); ok {
  491. retryOptions.TryTimeout = time.Until(deadline)
  492. }
  493. dt, err := DefaultAzureTransport(conf)
  494. if err != nil {
  495. return blob.ContainerURL{}, err
  496. }
  497. client := http.Client{
  498. Transport: dt,
  499. }
  500. p := blob.NewPipeline(credentials, blob.PipelineOptions{
  501. Retry: retryOptions,
  502. Telemetry: blob.TelemetryOptions{Value: "Kubecost"},
  503. RequestLog: blob.RequestLogOptions{
  504. // Log a warning if an operation takes longer than the specified duration.
  505. // (-1=no logging; 0=default 3s threshold)
  506. LogWarningIfTryOverThreshold: -1,
  507. },
  508. Log: pipeline.LogOptions{
  509. ShouldLog: nil,
  510. },
  511. HTTPSender: pipeline.FactoryFunc(func(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.PolicyFunc {
  512. return func(ctx context.Context, request pipeline.Request) (pipeline.Response, error) {
  513. resp, err := client.Do(request.WithContext(ctx))
  514. return pipeline.NewHTTPResponse(resp), err
  515. }
  516. }),
  517. })
  518. u, err := url.Parse(fmt.Sprintf("https://%s.%s", conf.StorageAccountName, conf.Endpoint))
  519. if err != nil {
  520. return blob.ContainerURL{}, err
  521. }
  522. service := blob.NewServiceURL(*u, p)
  523. return service.NewContainerURL(conf.ContainerName), nil
  524. }
  525. func DefaultAzureTransport(config AzureConfig) (*http.Transport, error) {
  526. tlsConfig, err := NewTLSConfig(&config.HTTPConfig.TLSConfig)
  527. if err != nil {
  528. return nil, err
  529. }
  530. if config.HTTPConfig.InsecureSkipVerify {
  531. tlsConfig.InsecureSkipVerify = true
  532. }
  533. return &http.Transport{
  534. Proxy: http.ProxyFromEnvironment,
  535. DialContext: (&net.Dialer{
  536. Timeout: 30 * time.Second,
  537. KeepAlive: 30 * time.Second,
  538. DualStack: true,
  539. }).DialContext,
  540. MaxIdleConns: config.HTTPConfig.MaxIdleConns,
  541. MaxIdleConnsPerHost: config.HTTPConfig.MaxIdleConnsPerHost,
  542. IdleConnTimeout: time.Duration(config.HTTPConfig.IdleConnTimeout),
  543. MaxConnsPerHost: config.HTTPConfig.MaxConnsPerHost,
  544. TLSHandshakeTimeout: time.Duration(config.HTTPConfig.TLSHandshakeTimeout),
  545. ExpectContinueTimeout: time.Duration(config.HTTPConfig.ExpectContinueTimeout),
  546. ResponseHeaderTimeout: time.Duration(config.HTTPConfig.ResponseHeaderTimeout),
  547. DisableCompression: config.HTTPConfig.DisableCompression,
  548. TLSClientConfig: tlsConfig,
  549. }, nil
  550. }
  551. func getContainer(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  552. c, err := getContainerURL(ctx, conf)
  553. if err != nil {
  554. return blob.ContainerURL{}, err
  555. }
  556. // Getting container properties to check if it exists or not. Returns error which will be parsed further.
  557. _, err = c.GetProperties(ctx, blob.LeaseAccessConditions{})
  558. return c, err
  559. }
  560. func createContainer(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  561. c, err := getContainerURL(ctx, conf)
  562. if err != nil {
  563. return blob.ContainerURL{}, err
  564. }
  565. _, err = c.Create(
  566. ctx,
  567. blob.Metadata{},
  568. blob.PublicAccessNone)
  569. return c, err
  570. }
  571. func getBlobURL(blobName string, c blob.ContainerURL) blob.BlockBlobURL {
  572. return c.NewBlockBlobURL(blobName)
  573. }
  574. func parseError(errorCode string) string {
  575. match := errorCodeRegex.FindStringSubmatch(errorCode)
  576. if len(match) == 2 {
  577. return match[1]
  578. }
  579. return errorCode
  580. }