run.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package gcsupload
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "strings"
  21. "cloud.google.com/go/storage"
  22. "github.com/sirupsen/logrus"
  23. "google.golang.org/api/option"
  24. "k8s.io/test-infra/prow/kube"
  25. "k8s.io/test-infra/prow/pod-utils/downwardapi"
  26. "k8s.io/test-infra/prow/pod-utils/gcs"
  27. )
  28. // Run will upload files to GCS as prescribed by
  29. // the options. Any extra files can be passed as
  30. // a parameter and will have the prefix prepended
  31. // to their destination in GCS, so the caller can
  32. // operate relative to the base of the GCS dir.
  33. func (o Options) Run(spec *downwardapi.JobSpec, extra map[string]gcs.UploadFunc) error {
  34. uploadTargets := o.assembleTargets(spec, extra)
  35. if !o.DryRun {
  36. ctx := context.Background()
  37. gcsClient, err := storage.NewClient(ctx, option.WithCredentialsFile(o.GcsCredentialsFile))
  38. if err != nil {
  39. return fmt.Errorf("could not connect to GCS: %v", err)
  40. }
  41. if err := gcs.Upload(gcsClient.Bucket(o.Bucket), uploadTargets); err != nil {
  42. return fmt.Errorf("failed to upload to GCS: %v", err)
  43. }
  44. } else {
  45. for destination := range uploadTargets {
  46. logrus.WithField("dest", destination).Info("Would upload")
  47. }
  48. }
  49. logrus.Info("Finished upload to GCS")
  50. return nil
  51. }
  52. func (o Options) assembleTargets(spec *downwardapi.JobSpec, extra map[string]gcs.UploadFunc) map[string]gcs.UploadFunc {
  53. jobBasePath, gcsPath, builder := PathsForJob(o.GCSConfiguration, spec, o.SubDir)
  54. uploadTargets := map[string]gcs.UploadFunc{}
  55. // ensure that an alias exists for any
  56. // job we're uploading artifacts for
  57. if alias := gcs.AliasForSpec(spec); alias != "" {
  58. fullBasePath := "gs://" + path.Join(o.Bucket, jobBasePath)
  59. uploadTargets[alias] = gcs.DataUpload(strings.NewReader(fullBasePath))
  60. }
  61. if latestBuilds := gcs.LatestBuildForSpec(spec, builder); len(latestBuilds) > 0 {
  62. for _, latestBuild := range latestBuilds {
  63. uploadTargets[latestBuild] = gcs.DataUpload(strings.NewReader(spec.BuildID))
  64. }
  65. }
  66. for _, item := range o.Items {
  67. info, err := os.Stat(item)
  68. if err != nil {
  69. logrus.Warnf("Encountered error in resolving items to upload for %s: %v", item, err)
  70. continue
  71. }
  72. if info.IsDir() {
  73. gatherArtifacts(item, gcsPath, info.Name(), uploadTargets)
  74. } else {
  75. destination := path.Join(gcsPath, info.Name())
  76. if _, exists := uploadTargets[destination]; exists {
  77. logrus.Warnf("Encountered duplicate upload of %s, skipping...", destination)
  78. continue
  79. }
  80. uploadTargets[destination] = gcs.FileUpload(item)
  81. }
  82. }
  83. for destination, upload := range extra {
  84. uploadTargets[path.Join(gcsPath, destination)] = upload
  85. }
  86. return uploadTargets
  87. }
  88. // PathsForJob determines the following for a job:
  89. // - path in GCS under the bucket where job artifacts will be uploaded for:
  90. // - the job
  91. // - this specific run of the job (if any subdir is present)
  92. // The builder for the job is also returned for use in other path resolution.
  93. func PathsForJob(options *kube.GCSConfiguration, spec *downwardapi.JobSpec, subdir string) (string, string, gcs.RepoPathBuilder) {
  94. builder := builderForStrategy(options.PathStrategy, options.DefaultOrg, options.DefaultRepo)
  95. jobBasePath := gcs.PathForSpec(spec, builder)
  96. if options.PathPrefix != "" {
  97. jobBasePath = path.Join(options.PathPrefix, jobBasePath)
  98. }
  99. var gcsPath string
  100. if subdir == "" {
  101. gcsPath = jobBasePath
  102. } else {
  103. gcsPath = path.Join(jobBasePath, subdir)
  104. }
  105. return jobBasePath, gcsPath, builder
  106. }
  107. func builderForStrategy(strategy, defaultOrg, defaultRepo string) gcs.RepoPathBuilder {
  108. var builder gcs.RepoPathBuilder
  109. switch strategy {
  110. case kube.PathStrategyExplicit:
  111. builder = gcs.NewExplicitRepoPathBuilder()
  112. case kube.PathStrategyLegacy:
  113. builder = gcs.NewLegacyRepoPathBuilder(defaultOrg, defaultRepo)
  114. case kube.PathStrategySingle:
  115. builder = gcs.NewSingleDefaultRepoPathBuilder(defaultOrg, defaultRepo)
  116. }
  117. return builder
  118. }
  119. func gatherArtifacts(artifactDir, gcsPath, subDir string, uploadTargets map[string]gcs.UploadFunc) {
  120. logrus.Printf("Gathering artifacts from artifact directory: %s", artifactDir)
  121. filepath.Walk(artifactDir, func(fspath string, info os.FileInfo, err error) error {
  122. if info == nil || info.IsDir() {
  123. return nil
  124. }
  125. // we know path will be below artifactDir, but we can't
  126. // communicate that to the filepath module. We can ignore
  127. // this error as we can be certain it won't occur and best-
  128. // effort upload is OK in any case
  129. if relPath, err := filepath.Rel(artifactDir, fspath); err == nil {
  130. destination := path.Join(gcsPath, subDir, relPath)
  131. if _, exists := uploadTargets[destination]; exists {
  132. logrus.Warnf("Encountered duplicate upload of %s, skipping...", destination)
  133. return nil
  134. }
  135. logrus.Printf("Found %s in artifact directory. Uploading as %s\n", fspath, destination)
  136. uploadTargets[destination] = gcs.FileUpload(fspath)
  137. } else {
  138. logrus.Warnf("Encountered error in relative path calculation for %s under %s: %v", fspath, artifactDir, err)
  139. }
  140. return nil
  141. })
  142. }