azurestorage.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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/opencost/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. func (b *AzureStorage) StatDirectories(name string) (*StorageInfo, error) {
  237. name = trimLeading(name)
  238. ctx := context.Background()
  239. blobURL := getBlobURL(name, b.containerURL)
  240. props, err := blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{})
  241. if err != nil {
  242. return nil, err
  243. }
  244. if trimName(name) == "" {
  245. return &StorageInfo{
  246. Name: trimName(name),
  247. Size: props.ContentLength(),
  248. ModTime: props.LastModified(),
  249. }, nil
  250. } else {
  251. return nil, fmt.Errorf("non-directory in dir")
  252. }
  253. }
  254. // Read uses the relative path of the storage combined with the provided path to
  255. // read the contents.
  256. func (b *AzureStorage) Read(name string) ([]byte, error) {
  257. name = trimLeading(name)
  258. ctx := context.Background()
  259. log.Debugf("AzureStorage::Read(%s)", name)
  260. reader, err := b.getBlobReader(ctx, name, 0, blob.CountToEnd)
  261. if err != nil {
  262. return nil, err
  263. }
  264. data, err := io.ReadAll(reader)
  265. if err != nil {
  266. return nil, err
  267. }
  268. return data, nil
  269. }
  270. // Write uses the relative path of the storage combined with the provided path
  271. // to write a new file or overwrite an existing file.
  272. func (b *AzureStorage) Write(name string, data []byte) error {
  273. name = trimLeading(name)
  274. ctx := context.Background()
  275. log.Debugf("AzureStorage::Write(%s)", name)
  276. blobURL := getBlobURL(name, b.containerURL)
  277. r := bytes.NewReader(data)
  278. if _, err := blob.UploadStreamToBlockBlob(ctx, r, blobURL,
  279. blob.UploadStreamToBlockBlobOptions{
  280. BufferSize: len(data),
  281. MaxBuffers: 1,
  282. },
  283. ); err != nil {
  284. return errors.Wrapf(err, "cannot upload Azure blob, address: %s", name)
  285. }
  286. return nil
  287. }
  288. // Remove uses the relative path of the storage combined with the provided path to
  289. // remove a file from storage permanently.
  290. func (b *AzureStorage) Remove(name string) error {
  291. name = trimLeading(name)
  292. log.Debugf("AzureStorage::Remove(%s)", name)
  293. ctx := context.Background()
  294. blobURL := getBlobURL(name, b.containerURL)
  295. if _, err := blobURL.Delete(ctx, blob.DeleteSnapshotsOptionInclude, blob.BlobAccessConditions{}); err != nil {
  296. return errors.Wrapf(err, "error deleting blob, address: %s", name)
  297. }
  298. return nil
  299. }
  300. // Exists uses the relative path of the storage combined with the provided path to
  301. // determine if the file exists.
  302. func (b *AzureStorage) Exists(name string) (bool, error) {
  303. name = trimLeading(name)
  304. ctx := context.Background()
  305. blobURL := getBlobURL(name, b.containerURL)
  306. if _, err := blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{}); err != nil {
  307. if b.isObjNotFoundErr(err) {
  308. return false, nil
  309. }
  310. return false, errors.Wrapf(err, "cannot get properties for Azure blob, address: %s", name)
  311. }
  312. return true, nil
  313. }
  314. // List uses the relative path of the storage combined with the provided path to return
  315. // storage information for the files.
  316. func (b *AzureStorage) List(path string) ([]*StorageInfo, error) {
  317. path = trimLeading(path)
  318. log.Debugf("AzureStorage::List(%s)", path)
  319. ctx := context.Background()
  320. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  321. // object itself as one prefix item.
  322. if path != "" {
  323. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  324. }
  325. marker := blob.Marker{}
  326. listOptions := blob.ListBlobsSegmentOptions{Prefix: path}
  327. var names []string
  328. for i := 1; ; i++ {
  329. var blobItems []blob.BlobItemInternal
  330. list, err := b.containerURL.ListBlobsHierarchySegment(ctx, marker, DirDelim, listOptions)
  331. if err != nil {
  332. return nil, errors.Wrapf(err, "cannot list hierarchy blobs with prefix %s (iteration #%d)", path, i)
  333. }
  334. marker = list.NextMarker
  335. blobItems = list.Segment.BlobItems
  336. for _, blob := range blobItems {
  337. names = append(names, blob.Name)
  338. }
  339. // Continue iterating if we are not done.
  340. if !marker.NotDone() {
  341. break
  342. }
  343. log.Debugf("Requesting next iteration of listing blobs. Entries: %d, iteration: %d", len(names), i)
  344. }
  345. // get the storage information for each blob (really unfortunate we have to do this)
  346. var lock sync.Mutex
  347. var stats []*StorageInfo
  348. var wg sync.WaitGroup
  349. wg.Add(len(names))
  350. for i := 0; i < len(names); i++ {
  351. go func(n string) {
  352. defer wg.Done()
  353. stat, err := b.Stat(n)
  354. if err != nil {
  355. log.Errorf("Error statting blob %s: %s", n, err)
  356. } else {
  357. lock.Lock()
  358. stats = append(stats, stat)
  359. lock.Unlock()
  360. }
  361. }(names[i])
  362. }
  363. wg.Wait()
  364. return stats, nil
  365. }
  366. func (b *AzureStorage) ListDirectories(path string) ([]*StorageInfo, error) {
  367. path = trimLeading(path)
  368. log.Debugf("AzureStorage::List(%s)", path)
  369. ctx := context.Background()
  370. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  371. // object itself as one prefix item.
  372. if path != "" {
  373. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  374. }
  375. marker := blob.Marker{}
  376. listOptions := blob.ListBlobsSegmentOptions{Prefix: path}
  377. var names []string
  378. for i := 1; ; i++ {
  379. var blobItems []blob.BlobItemInternal
  380. list, err := b.containerURL.ListBlobsHierarchySegment(ctx, marker, DirDelim, listOptions)
  381. if err != nil {
  382. return nil, errors.Wrapf(err, "cannot list hierarchy blobs with prefix %s (iteration #%d)", path, i)
  383. }
  384. marker = list.NextMarker
  385. blobItems = list.Segment.BlobItems
  386. for _, blob := range blobItems {
  387. names = append(names, blob.Name)
  388. }
  389. // Continue iterating if we are not done.
  390. if !marker.NotDone() {
  391. break
  392. }
  393. log.Debugf("Requesting next iteration of listing blobs. Entries: %d, iteration: %d", len(names), i)
  394. }
  395. // get the storage information for each blob (really unfortunate we have to do this)
  396. var lock sync.Mutex
  397. var stats []*StorageInfo
  398. var wg sync.WaitGroup
  399. wg.Add(len(names))
  400. for i := 0; i < len(names); i++ {
  401. go func(n string) {
  402. defer wg.Done()
  403. stat, err := b.StatDirectories(n)
  404. if err != nil {
  405. log.Errorf("Error statting blob %s: %s", n, err)
  406. } else {
  407. lock.Lock()
  408. stats = append(stats, stat)
  409. lock.Unlock()
  410. }
  411. }(names[i])
  412. }
  413. wg.Wait()
  414. return stats, nil
  415. }
  416. // IsObjNotFoundErr returns true if error means that object is not found. Relevant to Get operations.
  417. func (b *AzureStorage) isObjNotFoundErr(err error) bool {
  418. if err == nil {
  419. return false
  420. }
  421. errorCode := parseError(err.Error())
  422. if errorCode == "InvalidUri" || errorCode == "BlobNotFound" {
  423. return true
  424. }
  425. return false
  426. }
  427. func (b *AzureStorage) getBlobReader(ctx context.Context, name string, offset, length int64) (io.ReadCloser, error) {
  428. log.Debugf("Getting blob: %s, offset: %d, length: %d", name, offset, length)
  429. if name == "" {
  430. return nil, errors.New("X-Ms-Error-Code: [EmptyContainerName]")
  431. }
  432. exists, err := b.Exists(name)
  433. if err != nil {
  434. return nil, errors.Wrapf(err, "cannot get blob reader: %s", name)
  435. }
  436. if !exists {
  437. return nil, errors.New("X-Ms-Error-Code: [BlobNotFound]")
  438. }
  439. blobURL := getBlobURL(name, b.containerURL)
  440. if err != nil {
  441. return nil, errors.Wrapf(err, "cannot get Azure blob URL, address: %s", name)
  442. }
  443. var props *blob.BlobGetPropertiesResponse
  444. props, err = blobURL.GetProperties(ctx, blob.BlobAccessConditions{}, blob.ClientProvidedKeyOptions{})
  445. if err != nil {
  446. return nil, errors.Wrapf(err, "cannot get properties for container: %s", name)
  447. }
  448. var size int64
  449. // If a length is specified and it won't go past the end of the file,
  450. // then set it as the size.
  451. if length > 0 && length <= props.ContentLength()-offset {
  452. size = length
  453. log.Debugf("set size to length. size: %d, length: %d, offset: %d, name: %s", size, length, offset, name)
  454. } else {
  455. size = props.ContentLength() - offset
  456. log.Debugf("set size to go to EOF. contentlength: %d, size: %d, length: %d, offset: %d, name: %s", props.ContentLength(), size, length, offset, name)
  457. }
  458. destBuffer := make([]byte, size)
  459. if err := blob.DownloadBlobToBuffer(context.Background(), blobURL.BlobURL, offset, size,
  460. destBuffer, blob.DownloadFromBlobOptions{
  461. BlockSize: blob.BlobDefaultDownloadBlockSize,
  462. Parallelism: uint16(3),
  463. Progress: nil,
  464. RetryReaderOptionsPerBlock: blob.RetryReaderOptions{
  465. MaxRetryRequests: b.config.ReaderConfig.MaxRetryRequests,
  466. },
  467. },
  468. ); err != nil {
  469. return nil, errors.Wrapf(err, "cannot download blob, address: %s", blobURL.BlobURL)
  470. }
  471. return ioutil.NopCloser(bytes.NewReader(destBuffer)), nil
  472. }
  473. func getAzureStorageCredentials(conf AzureConfig) (blob.Credential, error) {
  474. if conf.MSIResource != "" || conf.UserAssignedID != "" {
  475. spt, err := getServicePrincipalToken(conf)
  476. if err != nil {
  477. return nil, err
  478. }
  479. if err := spt.Refresh(); err != nil {
  480. return nil, err
  481. }
  482. return blob.NewTokenCredential(spt.Token().AccessToken, func(tc blob.TokenCredential) time.Duration {
  483. err := spt.Refresh()
  484. if err != nil {
  485. log.Errorf("could not refresh MSI token. err: %s", err)
  486. // Retry later as the error can be related to API throttling
  487. return 30 * time.Second
  488. }
  489. tc.SetToken(spt.Token().AccessToken)
  490. return spt.Token().Expires().Sub(time.Now().Add(2 * time.Minute))
  491. }), nil
  492. }
  493. credential, err := blob.NewSharedKeyCredential(conf.StorageAccountName, conf.StorageAccountKey)
  494. if err != nil {
  495. return nil, err
  496. }
  497. return credential, nil
  498. }
  499. func getServicePrincipalToken(conf AzureConfig) (*adal.ServicePrincipalToken, error) {
  500. resource := conf.MSIResource
  501. if resource == "" {
  502. resource = fmt.Sprintf("https://%s.%s", conf.StorageAccountName, conf.Endpoint)
  503. }
  504. msiConfig := auth.MSIConfig{
  505. Resource: resource,
  506. }
  507. if conf.UserAssignedID != "" {
  508. log.Debugf("using user assigned identity. clientId: %s", conf.UserAssignedID)
  509. msiConfig.ClientID = conf.UserAssignedID
  510. } else {
  511. log.Debugf("using system assigned identity")
  512. }
  513. return msiConfig.ServicePrincipalToken()
  514. }
  515. func getContainerURL(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  516. credentials, err := getAzureStorageCredentials(conf)
  517. if err != nil {
  518. return blob.ContainerURL{}, err
  519. }
  520. retryOptions := blob.RetryOptions{
  521. MaxTries: conf.PipelineConfig.MaxTries,
  522. TryTimeout: time.Duration(conf.PipelineConfig.TryTimeout),
  523. RetryDelay: time.Duration(conf.PipelineConfig.RetryDelay),
  524. MaxRetryDelay: time.Duration(conf.PipelineConfig.MaxRetryDelay),
  525. }
  526. if deadline, ok := ctx.Deadline(); ok {
  527. retryOptions.TryTimeout = time.Until(deadline)
  528. }
  529. dt, err := DefaultAzureTransport(conf)
  530. if err != nil {
  531. return blob.ContainerURL{}, err
  532. }
  533. client := http.Client{
  534. Transport: dt,
  535. }
  536. p := blob.NewPipeline(credentials, blob.PipelineOptions{
  537. Retry: retryOptions,
  538. Telemetry: blob.TelemetryOptions{Value: "Kubecost"},
  539. RequestLog: blob.RequestLogOptions{
  540. // Log a warning if an operation takes longer than the specified duration.
  541. // (-1=no logging; 0=default 3s threshold)
  542. LogWarningIfTryOverThreshold: -1,
  543. },
  544. Log: pipeline.LogOptions{
  545. ShouldLog: nil,
  546. },
  547. HTTPSender: pipeline.FactoryFunc(func(next pipeline.Policy, po *pipeline.PolicyOptions) pipeline.PolicyFunc {
  548. return func(ctx context.Context, request pipeline.Request) (pipeline.Response, error) {
  549. resp, err := client.Do(request.WithContext(ctx))
  550. return pipeline.NewHTTPResponse(resp), err
  551. }
  552. }),
  553. })
  554. u, err := url.Parse(fmt.Sprintf("https://%s.%s", conf.StorageAccountName, conf.Endpoint))
  555. if err != nil {
  556. return blob.ContainerURL{}, err
  557. }
  558. service := blob.NewServiceURL(*u, p)
  559. return service.NewContainerURL(conf.ContainerName), nil
  560. }
  561. func DefaultAzureTransport(config AzureConfig) (*http.Transport, error) {
  562. tlsConfig, err := NewTLSConfig(&config.HTTPConfig.TLSConfig)
  563. if err != nil {
  564. return nil, err
  565. }
  566. if config.HTTPConfig.InsecureSkipVerify {
  567. tlsConfig.InsecureSkipVerify = true
  568. }
  569. return &http.Transport{
  570. Proxy: http.ProxyFromEnvironment,
  571. DialContext: (&net.Dialer{
  572. Timeout: 30 * time.Second,
  573. KeepAlive: 30 * time.Second,
  574. DualStack: true,
  575. }).DialContext,
  576. MaxIdleConns: config.HTTPConfig.MaxIdleConns,
  577. MaxIdleConnsPerHost: config.HTTPConfig.MaxIdleConnsPerHost,
  578. IdleConnTimeout: time.Duration(config.HTTPConfig.IdleConnTimeout),
  579. MaxConnsPerHost: config.HTTPConfig.MaxConnsPerHost,
  580. TLSHandshakeTimeout: time.Duration(config.HTTPConfig.TLSHandshakeTimeout),
  581. ExpectContinueTimeout: time.Duration(config.HTTPConfig.ExpectContinueTimeout),
  582. ResponseHeaderTimeout: time.Duration(config.HTTPConfig.ResponseHeaderTimeout),
  583. DisableCompression: config.HTTPConfig.DisableCompression,
  584. TLSClientConfig: tlsConfig,
  585. }, nil
  586. }
  587. func getContainer(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  588. c, err := getContainerURL(ctx, conf)
  589. if err != nil {
  590. return blob.ContainerURL{}, err
  591. }
  592. // Getting container properties to check if it exists or not. Returns error which will be parsed further.
  593. _, err = c.GetProperties(ctx, blob.LeaseAccessConditions{})
  594. return c, err
  595. }
  596. func createContainer(ctx context.Context, conf AzureConfig) (blob.ContainerURL, error) {
  597. c, err := getContainerURL(ctx, conf)
  598. if err != nil {
  599. return blob.ContainerURL{}, err
  600. }
  601. _, err = c.Create(
  602. ctx,
  603. blob.Metadata{},
  604. blob.PublicAccessNone)
  605. return c, err
  606. }
  607. func getBlobURL(blobName string, c blob.ContainerURL) blob.BlockBlobURL {
  608. return c.NewBlockBlobURL(blobName)
  609. }
  610. func parseError(errorCode string) string {
  611. match := errorCodeRegex.FindStringSubmatch(errorCode)
  612. if len(match) == 2 {
  613. return match[1]
  614. }
  615. return errorCode
  616. }