azurestorage.go 20 KB

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