jobs.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. Copyright 2017 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 config
  14. import (
  15. "fmt"
  16. "regexp"
  17. "time"
  18. buildv1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1"
  19. "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/util/sets"
  21. "k8s.io/test-infra/prow/kube"
  22. )
  23. // Preset is intended to match the k8s' PodPreset feature, and may be removed
  24. // if that feature goes beta.
  25. type Preset struct {
  26. Labels map[string]string `json:"labels"`
  27. Env []v1.EnvVar `json:"env"`
  28. Volumes []v1.Volume `json:"volumes"`
  29. VolumeMounts []v1.VolumeMount `json:"volumeMounts"`
  30. }
  31. func mergePreset(preset Preset, labels map[string]string, pod *v1.PodSpec) error {
  32. if pod == nil {
  33. return nil
  34. }
  35. for l, v := range preset.Labels {
  36. if v2, ok := labels[l]; !ok || v2 != v {
  37. return nil
  38. }
  39. }
  40. for _, e1 := range preset.Env {
  41. for i := range pod.Containers {
  42. for _, e2 := range pod.Containers[i].Env {
  43. if e1.Name == e2.Name {
  44. return fmt.Errorf("env var duplicated in pod spec: %s", e1.Name)
  45. }
  46. }
  47. pod.Containers[i].Env = append(pod.Containers[i].Env, e1)
  48. }
  49. }
  50. for _, v1 := range preset.Volumes {
  51. for _, v2 := range pod.Volumes {
  52. if v1.Name == v2.Name {
  53. return fmt.Errorf("volume duplicated in pod spec: %s", v1.Name)
  54. }
  55. }
  56. pod.Volumes = append(pod.Volumes, v1)
  57. }
  58. for _, vm1 := range preset.VolumeMounts {
  59. for i := range pod.Containers {
  60. for _, vm2 := range pod.Containers[i].VolumeMounts {
  61. if vm1.Name == vm2.Name {
  62. return fmt.Errorf("volume mount duplicated in pod spec: %s", vm1.Name)
  63. }
  64. }
  65. pod.Containers[i].VolumeMounts = append(pod.Containers[i].VolumeMounts, vm1)
  66. }
  67. }
  68. return nil
  69. }
  70. // JobBase contains attributes common to all job types
  71. type JobBase struct {
  72. // The name of the job.
  73. // e.g. pull-test-infra-bazel-build
  74. Name string `json:"name"`
  75. // Labels are added to prowjobs and pods created for this job.
  76. Labels map[string]string `json:"labels,omitempty"`
  77. // MaximumConcurrency of this job, 0 implies no limit.
  78. MaxConcurrency int `json:"max_concurrency,omitempty"`
  79. // Agent that will take care of running this job.
  80. Agent string `json:"agent"`
  81. // Cluster is the alias of the cluster to run this job in.
  82. // (Default: kube.DefaultClusterAlias)
  83. Cluster string `json:"cluster,omitempty"`
  84. // Namespace is the namespace in which pods schedule.
  85. // nil: results in config.PodNamespace (aka pod default)
  86. // empty: results in config.ProwJobNamespace (aka same as prowjob)
  87. Namespace *string `json:"namespace,omitempty"`
  88. // ErrorOnEviction indicates that the ProwJob should be completed and given
  89. // the ErrorState status if the pod that is executing the job is evicted.
  90. // If this field is unspecified or false, a new pod will be created to replace
  91. // the evicted one.
  92. ErrorOnEviction bool `json:"error_on_eviction,omitempty"`
  93. // SourcePath contains the path where this job is defined
  94. SourcePath string `json:"-"`
  95. // Spec is the Kubernetes pod spec used if Agent is kubernetes.
  96. Spec *v1.PodSpec `json:"spec,omitempty"`
  97. // BuildSpec is the Knative build spec used if Agent is knative-build.
  98. BuildSpec *buildv1alpha1.BuildSpec `json:"build_spec,omitempty"`
  99. UtilityConfig
  100. }
  101. // Presubmit runs on PRs.
  102. type Presubmit struct {
  103. JobBase
  104. // AlwaysRun automatically for every PR, or only when a comment triggers it.
  105. AlwaysRun bool `json:"always_run"`
  106. // RunIfChanged automatically run if the PR modifies a file that matches this regex.
  107. RunIfChanged string `json:"run_if_changed,omitempty"`
  108. // TrustedLabels automatically run if the PR has label in TrustedLabels
  109. TrustedLabels []string `json:"trusted_labels,omitempty"`
  110. // UntrustedLabels automatically not run if the PR has label in UntrustedLabels
  111. UntrustedLabels []string `json:"untrusted_labels,omitempty"`
  112. // RunPRPushed automatically run if the source branch pushed
  113. RunPRPushed bool `json:"run_pr_pushed"`
  114. // Context is the name of the GitHub status context for the job.
  115. Context string `json:"context"`
  116. // Optional indicates that the job's status context should not be required for merge.
  117. Optional bool `json:"optional,omitempty"`
  118. // SkipReport skips commenting and setting status on GitHub.
  119. SkipReport bool `json:"skip_report,omitempty"`
  120. // Trigger is the regular expression to trigger the job.
  121. // e.g. `@k8s-bot e2e test this`
  122. // RerunCommand must also be specified if this field is specified.
  123. // (Default: `(?m)^/test (?:.*? )?<job name>(?: .*?)?$`)
  124. Trigger string `json:"trigger"`
  125. // The RerunCommand to give users. Must match Trigger.
  126. // Trigger must also be specified if this field is specified.
  127. // (Default: `/test <job name>`)
  128. RerunCommand string `json:"rerun_command"`
  129. // RunAfterSuccess is a list of jobs to run after successfully running this one.
  130. RunAfterSuccess []Presubmit `json:"run_after_success,omitempty"`
  131. Brancher
  132. // We'll set these when we load it.
  133. re *regexp.Regexp // from Trigger.
  134. reChanges *regexp.Regexp // from RunIfChanged
  135. }
  136. // Postsubmit runs on push events.
  137. type Postsubmit struct {
  138. JobBase
  139. RegexpChangeMatcher
  140. Brancher
  141. // Run these jobs after successfully running this one.
  142. RunAfterSuccess []Postsubmit `json:"run_after_success,omitempty"`
  143. }
  144. // Periodic runs on a timer.
  145. type Periodic struct {
  146. JobBase
  147. // (deprecated)Interval to wait between two runs of the job.
  148. Interval string `json:"interval"`
  149. // Cron representation of job trigger time
  150. Cron string `json:"cron"`
  151. // Tags for config entries
  152. Tags []string `json:"tags,omitempty"`
  153. // Run these jobs after successfully running this one.
  154. RunAfterSuccess []Periodic `json:"run_after_success,omitempty"`
  155. interval time.Duration
  156. }
  157. // SetInterval updates interval, the frequency duration it runs.
  158. func (p *Periodic) SetInterval(d time.Duration) {
  159. p.interval = d
  160. }
  161. // GetInterval returns interval, the frequency duration it runs.
  162. func (p *Periodic) GetInterval() time.Duration {
  163. return p.interval
  164. }
  165. // RegexpChangeMatcher is for code shared between jobs that run only when certain files are changed.
  166. type RegexpChangeMatcher struct {
  167. // RunIfChanged defines a regex used to select which subset of file changes should trigger this job.
  168. // If any file in the changeset matches this regex, the job will be triggered
  169. RunIfChanged string `json:"run_if_changed,omitempty"`
  170. reChanges *regexp.Regexp // from RunIfChanged
  171. }
  172. // RunsAgainstChanges returns true if any of the changed input paths match the run_if_changed regex.
  173. func (cm RegexpChangeMatcher) RunsAgainstChanges(changes []string) bool {
  174. if cm.RunIfChanged == "" {
  175. return true
  176. }
  177. for _, change := range changes {
  178. if cm.reChanges.MatchString(change) {
  179. return true
  180. }
  181. }
  182. return false
  183. }
  184. // Brancher is for shared code between jobs that only run against certain
  185. // branches. An empty brancher runs against all branches.
  186. type Brancher struct {
  187. // Do not run against these branches. Default is no branches.
  188. SkipBranches []string `json:"skip_branches,omitempty"`
  189. // Only run against these branches. Default is all branches.
  190. Branches []string `json:"branches,omitempty"`
  191. // We'll set these when we load it.
  192. re *regexp.Regexp
  193. reSkip *regexp.Regexp
  194. }
  195. // RunsAgainstAllBranch returns true if there are both branches and skip_branches are unset
  196. func (br Brancher) RunsAgainstAllBranch() bool {
  197. return len(br.SkipBranches) == 0 && len(br.Branches) == 0
  198. }
  199. // RunsAgainstBranch returns true if the input branch matches, given the whitelist/blacklist.
  200. func (br Brancher) RunsAgainstBranch(branch string) bool {
  201. if br.RunsAgainstAllBranch() {
  202. return true
  203. }
  204. // Favor SkipBranches over Branches
  205. if len(br.SkipBranches) != 0 && br.reSkip.MatchString(branch) {
  206. return false
  207. }
  208. if len(br.Branches) == 0 || br.re.MatchString(branch) {
  209. return true
  210. }
  211. return false
  212. }
  213. // Intersects checks if other Brancher would trigger for the same branch.
  214. func (br Brancher) Intersects(other Brancher) bool {
  215. if br.RunsAgainstAllBranch() || other.RunsAgainstAllBranch() {
  216. return true
  217. }
  218. if len(br.Branches) > 0 {
  219. baseBranches := sets.NewString(br.Branches...)
  220. if len(other.Branches) > 0 {
  221. otherBranches := sets.NewString(other.Branches...)
  222. if baseBranches.Intersection(otherBranches).Len() > 0 {
  223. return true
  224. }
  225. return false
  226. }
  227. if !baseBranches.Intersection(sets.NewString(other.SkipBranches...)).Equal(baseBranches) {
  228. return true
  229. }
  230. return false
  231. }
  232. if len(other.Branches) == 0 {
  233. // There can only be one Brancher with skip_branches.
  234. return true
  235. }
  236. return other.Intersects(br)
  237. }
  238. // RunsAgainstChanges returns true if any of the changed input paths match the run_if_changed regex.
  239. func (ps Presubmit) RunsAgainstChanges(changes []string) bool {
  240. for _, change := range changes {
  241. if ps.reChanges.MatchString(change) {
  242. return true
  243. }
  244. }
  245. return false
  246. }
  247. // TriggerMatches returns true if the comment body should trigger this presubmit.
  248. //
  249. // This is usually a /test foo string.
  250. func (ps Presubmit) TriggerMatches(body string) bool {
  251. return ps.re.MatchString(body)
  252. }
  253. // ContextRequired checks whether a context is required from github points of view (required check).
  254. func (ps Presubmit) ContextRequired() bool {
  255. if ps.Optional || ps.SkipReport {
  256. return false
  257. }
  258. return true
  259. }
  260. // ChangedFilesProvider returns a slice of modified files.
  261. type ChangedFilesProvider func() ([]string, error)
  262. func matching(j Presubmit, body string, testAll bool) []Presubmit {
  263. // When matching ignore whether the job runs for the branch or whether the job runs for the
  264. // PR's changes. Even if the job doesn't run, it still matches the PR and may need to be marked
  265. // as skipped on github.
  266. var result []Presubmit
  267. if (testAll && (j.AlwaysRun || j.RunIfChanged != "")) || j.TriggerMatches(body) {
  268. result = append(result, j)
  269. }
  270. for _, child := range j.RunAfterSuccess {
  271. result = append(result, matching(child, body, testAll)...)
  272. }
  273. return result
  274. }
  275. // MatchingPresubmits returns a slice of presubmits to trigger based on the repo and a comment text.
  276. func (c *JobConfig) MatchingPresubmits(fullRepoName, body string, testAll bool) []Presubmit {
  277. var result []Presubmit
  278. if jobs, ok := c.Presubmits[fullRepoName]; ok {
  279. for _, job := range jobs {
  280. result = append(result, matching(job, body, testAll)...)
  281. }
  282. }
  283. return result
  284. }
  285. // UtilityConfig holds decoration metadata, such as how to clone and additional containers/etc
  286. type UtilityConfig struct {
  287. // Decorate determines if we decorate the PodSpec or not
  288. Decorate bool `json:"decorate,omitempty"`
  289. // PathAlias is the location under <root-dir>/src
  290. // where the repository under test is cloned. If this
  291. // is not set, <root-dir>/src/github.com/org/repo will
  292. // be used as the default.
  293. PathAlias string `json:"path_alias,omitempty"`
  294. // CloneURI is the URI that is used to clone the
  295. // repository. If unset, will default to
  296. // `https://github.com/org/repo.git`.
  297. CloneURI string `json:"clone_uri,omitempty"`
  298. // SkipSubmodules determines if submodules should be
  299. // cloned when the job is run. Defaults to true.
  300. SkipSubmodules bool `json:"skip_submodules,omitempty"`
  301. // ExtraRefs are auxiliary repositories that
  302. // need to be cloned, determined from config
  303. ExtraRefs []kube.Refs `json:"extra_refs,omitempty"`
  304. // DecorationConfig holds configuration options for
  305. // decorating PodSpecs that users provide
  306. DecorationConfig *kube.DecorationConfig `json:"decoration_config,omitempty"`
  307. }
  308. // RetestPresubmits returns all presubmits that should be run given a /retest command.
  309. // This is the set of all presubmits intersected with ((alwaysRun + runContexts) - skipContexts)
  310. func (c *JobConfig) RetestPresubmits(fullRepoName string, skipContexts, runContexts map[string]bool) []Presubmit {
  311. var result []Presubmit
  312. if jobs, ok := c.Presubmits[fullRepoName]; ok {
  313. for _, job := range jobs {
  314. if skipContexts[job.Context] {
  315. continue
  316. }
  317. if job.AlwaysRun || job.RunIfChanged != "" || runContexts[job.Context] {
  318. result = append(result, job)
  319. }
  320. }
  321. }
  322. return result
  323. }
  324. // GetPresubmit returns the presubmit job for the provided repo and job name.
  325. func (c *JobConfig) GetPresubmit(repo, jobName string) *Presubmit {
  326. presubmits := c.AllPresubmits([]string{repo})
  327. for i := range presubmits {
  328. ps := presubmits[i]
  329. if ps.Name == jobName {
  330. return &ps
  331. }
  332. }
  333. return nil
  334. }
  335. // SetPresubmits updates c.Presubmits to jobs, after compiling and validating their regexes.
  336. func (c *JobConfig) SetPresubmits(jobs map[string][]Presubmit) error {
  337. nj := map[string][]Presubmit{}
  338. for k, v := range jobs {
  339. nj[k] = make([]Presubmit, len(v))
  340. copy(nj[k], v)
  341. if err := SetPresubmitRegexes(nj[k]); err != nil {
  342. return err
  343. }
  344. }
  345. c.Presubmits = nj
  346. return nil
  347. }
  348. // SetPostsubmits updates c.Postsubmits to jobs, after compiling and validating their regexes.
  349. func (c *JobConfig) SetPostsubmits(jobs map[string][]Postsubmit) error {
  350. nj := map[string][]Postsubmit{}
  351. for k, v := range jobs {
  352. nj[k] = make([]Postsubmit, len(v))
  353. copy(nj[k], v)
  354. if err := SetPostsubmitRegexes(nj[k]); err != nil {
  355. return err
  356. }
  357. }
  358. c.Postsubmits = nj
  359. return nil
  360. }
  361. // listPresubmits list all the presubmit for a given repo including the run after success jobs.
  362. func listPresubmits(ps []Presubmit) []Presubmit {
  363. var res []Presubmit
  364. for _, p := range ps {
  365. res = append(res, p)
  366. res = append(res, listPresubmits(p.RunAfterSuccess)...)
  367. }
  368. return res
  369. }
  370. // AllPresubmits returns all prow presubmit jobs in repos.
  371. // if repos is empty, return all presubmits.
  372. func (c *JobConfig) AllPresubmits(repos []string) []Presubmit {
  373. var res []Presubmit
  374. for repo, v := range c.Presubmits {
  375. if len(repos) == 0 {
  376. res = append(res, listPresubmits(v)...)
  377. } else {
  378. for _, r := range repos {
  379. if r == repo {
  380. res = append(res, listPresubmits(v)...)
  381. break
  382. }
  383. }
  384. }
  385. }
  386. return res
  387. }
  388. // listPostsubmits list all the postsubmits for a given repo including the run after success jobs.
  389. func listPostsubmits(ps []Postsubmit) []Postsubmit {
  390. var res []Postsubmit
  391. for _, p := range ps {
  392. res = append(res, p)
  393. res = append(res, listPostsubmits(p.RunAfterSuccess)...)
  394. }
  395. return res
  396. }
  397. // AllPostsubmits returns all prow postsubmit jobs in repos.
  398. // if repos is empty, return all postsubmits.
  399. func (c *JobConfig) AllPostsubmits(repos []string) []Postsubmit {
  400. var res []Postsubmit
  401. for repo, v := range c.Postsubmits {
  402. if len(repos) == 0 {
  403. res = append(res, listPostsubmits(v)...)
  404. } else {
  405. for _, r := range repos {
  406. if r == repo {
  407. res = append(res, listPostsubmits(v)...)
  408. break
  409. }
  410. }
  411. }
  412. }
  413. return res
  414. }
  415. // AllPeriodics returns all prow periodic jobs.
  416. func (c *JobConfig) AllPeriodics() []Periodic {
  417. var listPeriodic func(ps []Periodic) []Periodic
  418. listPeriodic = func(ps []Periodic) []Periodic {
  419. var res []Periodic
  420. for _, p := range ps {
  421. res = append(res, p)
  422. res = append(res, listPeriodic(p.RunAfterSuccess)...)
  423. }
  424. return res
  425. }
  426. return listPeriodic(c.Periodics)
  427. }