]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/toolstate.rs
Merge commit 'a98e7ab8b94485be6bd03e0c6b8682ecab5b52e6' into clippyup
[rust.git] / src / bootstrap / toolstate.rs
1 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
2 use build_helper::t;
3 use serde::{Deserialize, Serialize};
4 use std::collections::HashMap;
5 use std::env;
6 use std::fmt;
7 use std::fs;
8 use std::io::{Seek, SeekFrom};
9 use std::path::{Path, PathBuf};
10 use std::process::Command;
11 use std::time;
12
13 // Each cycle is 42 days long (6 weeks); the last week is 35..=42 then.
14 const BETA_WEEK_START: u64 = 35;
15
16 #[cfg(target_os = "linux")]
17 const OS: Option<&str> = Some("linux");
18
19 #[cfg(windows)]
20 const OS: Option<&str> = Some("windows");
21
22 #[cfg(all(not(target_os = "linux"), not(windows)))]
23 const OS: Option<&str> = None;
24
25 type ToolstateData = HashMap<Box<str>, ToolState>;
26
27 #[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd)]
28 #[serde(rename_all = "kebab-case")]
29 /// Whether a tool can be compiled, tested or neither
30 pub enum ToolState {
31     /// The tool compiles successfully, but the test suite fails
32     TestFail = 1,
33     /// The tool compiles successfully and its test suite passes
34     TestPass = 2,
35     /// The tool can't even be compiled
36     BuildFail = 0,
37 }
38
39 impl fmt::Display for ToolState {
40     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41         write!(
42             f,
43             "{}",
44             match self {
45                 ToolState::TestFail => "test-fail",
46                 ToolState::TestPass => "test-pass",
47                 ToolState::BuildFail => "build-fail",
48             }
49         )
50     }
51 }
52
53 impl Default for ToolState {
54     fn default() -> Self {
55         // err on the safe side
56         ToolState::BuildFail
57     }
58 }
59
60 /// Number of days after the last promotion of beta.
61 /// Its value is 41 on the Tuesday where "Promote master to beta (T-2)" happens.
62 /// The Wednesday after this has value 0.
63 /// We track this value to prevent regressing tools in the last week of the 6-week cycle.
64 fn days_since_beta_promotion() -> u64 {
65     let since_epoch = t!(time::SystemTime::UNIX_EPOCH.elapsed());
66     (since_epoch.as_secs() / 86400 - 20) % 42
67 }
68
69 // These tools must test-pass on the beta/stable channels.
70 //
71 // On the nightly channel, their build step must be attempted, but they may not
72 // be able to build successfully.
73 static STABLE_TOOLS: &[(&str, &str)] = &[
74     ("book", "src/doc/book"),
75     ("nomicon", "src/doc/nomicon"),
76     ("reference", "src/doc/reference"),
77     ("rust-by-example", "src/doc/rust-by-example"),
78     ("edition-guide", "src/doc/edition-guide"),
79     ("rls", "src/tools/rls"),
80 ];
81
82 // These tools are permitted to not build on the beta/stable channels.
83 //
84 // We do require that we checked whether they build or not on the tools builder,
85 // though, as otherwise we will be unable to file an issue if they start
86 // failing.
87 static NIGHTLY_TOOLS: &[(&str, &str)] = &[
88     ("miri", "src/tools/miri"),
89     ("embedded-book", "src/doc/embedded-book"),
90     // ("rustc-dev-guide", "src/doc/rustc-dev-guide"),
91 ];
92
93 fn print_error(tool: &str, submodule: &str) {
94     eprintln!();
95     eprintln!("We detected that this PR updated '{}', but its tests failed.", tool);
96     eprintln!();
97     eprintln!("If you do intend to update '{}', please check the error messages above and", tool);
98     eprintln!("commit another update.");
99     eprintln!();
100     eprintln!("If you do NOT intend to update '{}', please ensure you did not accidentally", tool);
101     eprintln!("change the submodule at '{}'. You may ask your reviewer for the", submodule);
102     eprintln!("proper steps.");
103     std::process::exit(3);
104 }
105
106 fn check_changed_files(toolstates: &HashMap<Box<str>, ToolState>) {
107     // Changed files
108     let output = std::process::Command::new("git")
109         .arg("diff")
110         .arg("--name-status")
111         .arg("HEAD")
112         .arg("HEAD^")
113         .output();
114     let output = match output {
115         Ok(o) => o,
116         Err(e) => {
117             eprintln!("Failed to get changed files: {:?}", e);
118             std::process::exit(1);
119         }
120     };
121
122     let output = t!(String::from_utf8(output.stdout));
123
124     for (tool, submodule) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) {
125         let changed = output.lines().any(|l| l.starts_with('M') && l.ends_with(submodule));
126         eprintln!("Verifying status of {}...", tool);
127         if !changed {
128             continue;
129         }
130
131         eprintln!("This PR updated '{}', verifying if status is 'test-pass'...", submodule);
132         if toolstates[*tool] != ToolState::TestPass {
133             print_error(tool, submodule);
134         }
135     }
136 }
137
138 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
139 pub struct ToolStateCheck;
140
141 impl Step for ToolStateCheck {
142     type Output = ();
143
144     /// Checks tool state status.
145     ///
146     /// This is intended to be used in the `checktools.sh` script. To use
147     /// this, set `save-toolstates` in `config.toml` so that tool status will
148     /// be saved to a JSON file. Then, run `x.py test --no-fail-fast` for all
149     /// of the tools to populate the JSON file. After that is done, this
150     /// command can be run to check for any status failures, and exits with an
151     /// error if there are any.
152     ///
153     /// This also handles publishing the results to the `history` directory of
154     /// the toolstate repo <https://github.com/rust-lang-nursery/rust-toolstate>
155     /// if the env var `TOOLSTATE_PUBLISH` is set. Note that there is a
156     /// *separate* step of updating the `latest.json` file and creating GitHub
157     /// issues and comments in `src/ci/publish_toolstate.sh`, which is only
158     /// performed on master. (The shell/python code is intended to be migrated
159     /// here eventually.)
160     ///
161     /// The rules for failure are:
162     /// * If the PR modifies a tool, the status must be test-pass.
163     ///   NOTE: There is intent to change this, see
164     ///   <https://github.com/rust-lang/rust/issues/65000>.
165     /// * All "stable" tools must be test-pass on the stable or beta branches.
166     /// * During beta promotion week, a PR is not allowed to "regress" a
167     ///   stable tool. That is, the status is not allowed to get worse
168     ///   (test-pass to test-fail or build-fail).
169     fn run(self, builder: &Builder<'_>) {
170         if builder.config.dry_run {
171             return;
172         }
173
174         let days_since_beta_promotion = days_since_beta_promotion();
175         let in_beta_week = days_since_beta_promotion >= BETA_WEEK_START;
176         let is_nightly = !(builder.config.channel == "beta" || builder.config.channel == "stable");
177         let toolstates = builder.toolstates();
178
179         let mut did_error = false;
180
181         for (tool, _) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) {
182             if !toolstates.contains_key(*tool) {
183                 did_error = true;
184                 eprintln!("error: Tool `{}` was not recorded in tool state.", tool);
185             }
186         }
187
188         if did_error {
189             std::process::exit(1);
190         }
191
192         check_changed_files(&toolstates);
193         checkout_toolstate_repo();
194         let old_toolstate = read_old_toolstate();
195
196         for (tool, _) in STABLE_TOOLS.iter() {
197             let state = toolstates[*tool];
198
199             if state != ToolState::TestPass {
200                 if !is_nightly {
201                     did_error = true;
202                     eprintln!("error: Tool `{}` should be test-pass but is {}", tool, state);
203                 } else if in_beta_week {
204                     let old_state = old_toolstate
205                         .iter()
206                         .find(|ts| ts.tool == *tool)
207                         .expect("latest.json missing tool")
208                         .state();
209                     if state < old_state {
210                         did_error = true;
211                         eprintln!(
212                             "error: Tool `{}` has regressed from {} to {} during beta week.",
213                             tool, old_state, state
214                         );
215                     } else {
216                         // This warning only appears in the logs, which most
217                         // people won't read. It's mostly here for testing and
218                         // debugging.
219                         eprintln!(
220                             "warning: Tool `{}` is not test-pass (is `{}`), \
221                             this should be fixed before beta is branched.",
222                             tool, state
223                         );
224                     }
225                 }
226                 // `publish_toolstate.py` is responsible for updating
227                 // `latest.json` and creating comments/issues warning people
228                 // if there is a regression. That all happens in a separate CI
229                 // job on the master branch once the PR has passed all tests
230                 // on the `auto` branch.
231             }
232         }
233
234         if did_error {
235             std::process::exit(1);
236         }
237
238         if builder.config.channel == "nightly" && env::var_os("TOOLSTATE_PUBLISH").is_some() {
239             commit_toolstate_change(&toolstates);
240         }
241     }
242
243     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
244         run.path("check-tools")
245     }
246
247     fn make_run(run: RunConfig<'_>) {
248         run.builder.ensure(ToolStateCheck);
249     }
250 }
251
252 impl Builder<'_> {
253     fn toolstates(&self) -> HashMap<Box<str>, ToolState> {
254         if let Some(ref path) = self.config.save_toolstates {
255             if let Some(parent) = path.parent() {
256                 // Ensure the parent directory always exists
257                 t!(std::fs::create_dir_all(parent));
258             }
259             let mut file =
260                 t!(fs::OpenOptions::new().create(true).write(true).read(true).open(path));
261
262             serde_json::from_reader(&mut file).unwrap_or_default()
263         } else {
264             Default::default()
265         }
266     }
267
268     /// Updates the actual toolstate of a tool.
269     ///
270     /// The toolstates are saved to the file specified by the key
271     /// `rust.save-toolstates` in `config.toml`. If unspecified, nothing will be
272     /// done. The file is updated immediately after this function completes.
273     pub fn save_toolstate(&self, tool: &str, state: ToolState) {
274         // If we're in a dry run setting we don't want to save toolstates as
275         // that means if we e.g. panic down the line it'll look like we tested
276         // everything (but we actually haven't).
277         if self.config.dry_run {
278             return;
279         }
280         // Toolstate isn't tracked for clippy or rustfmt, but since most tools do, we avoid checking
281         // in all the places we could save toolstate and just do so here.
282         if tool == "clippy-driver" || tool == "rustfmt" {
283             return;
284         }
285         if let Some(ref path) = self.config.save_toolstates {
286             if let Some(parent) = path.parent() {
287                 // Ensure the parent directory always exists
288                 t!(std::fs::create_dir_all(parent));
289             }
290             let mut file =
291                 t!(fs::OpenOptions::new().create(true).read(true).write(true).open(path));
292
293             let mut current_toolstates: HashMap<Box<str>, ToolState> =
294                 serde_json::from_reader(&mut file).unwrap_or_default();
295             current_toolstates.insert(tool.into(), state);
296             t!(file.seek(SeekFrom::Start(0)));
297             t!(file.set_len(0));
298             t!(serde_json::to_writer(file, &current_toolstates));
299         }
300     }
301 }
302
303 fn toolstate_repo() -> String {
304     env::var("TOOLSTATE_REPO")
305         .unwrap_or_else(|_| "https://github.com/rust-lang-nursery/rust-toolstate.git".to_string())
306 }
307
308 /// Directory where the toolstate repo is checked out.
309 const TOOLSTATE_DIR: &str = "rust-toolstate";
310
311 /// Checks out the toolstate repo into `TOOLSTATE_DIR`.
312 fn checkout_toolstate_repo() {
313     if let Ok(token) = env::var("TOOLSTATE_REPO_ACCESS_TOKEN") {
314         prepare_toolstate_config(&token);
315     }
316     if Path::new(TOOLSTATE_DIR).exists() {
317         eprintln!("Cleaning old toolstate directory...");
318         t!(fs::remove_dir_all(TOOLSTATE_DIR));
319     }
320
321     let status = Command::new("git")
322         .arg("clone")
323         .arg("--depth=1")
324         .arg(toolstate_repo())
325         .arg(TOOLSTATE_DIR)
326         .status();
327     let success = match status {
328         Ok(s) => s.success(),
329         Err(_) => false,
330     };
331     if !success {
332         panic!("git clone unsuccessful (status: {:?})", status);
333     }
334 }
335
336 /// Sets up config and authentication for modifying the toolstate repo.
337 fn prepare_toolstate_config(token: &str) {
338     fn git_config(key: &str, value: &str) {
339         let status = Command::new("git").arg("config").arg("--global").arg(key).arg(value).status();
340         let success = match status {
341             Ok(s) => s.success(),
342             Err(_) => false,
343         };
344         if !success {
345             panic!("git config key={} value={} failed (status: {:?})", key, value, status);
346         }
347     }
348
349     // If changing anything here, then please check that `src/ci/publish_toolstate.sh` is up to date
350     // as well.
351     git_config("user.email", "7378925+rust-toolstate-update@users.noreply.github.com");
352     git_config("user.name", "Rust Toolstate Update");
353     git_config("credential.helper", "store");
354
355     let credential = format!("https://{}:x-oauth-basic@github.com\n", token,);
356     let git_credential_path = PathBuf::from(t!(env::var("HOME"))).join(".git-credentials");
357     t!(fs::write(&git_credential_path, credential));
358 }
359
360 /// Reads the latest toolstate from the toolstate repo.
361 fn read_old_toolstate() -> Vec<RepoState> {
362     let latest_path = Path::new(TOOLSTATE_DIR).join("_data").join("latest.json");
363     let old_toolstate = t!(fs::read(latest_path));
364     t!(serde_json::from_slice(&old_toolstate))
365 }
366
367 /// This function `commit_toolstate_change` provides functionality for pushing a change
368 /// to the `rust-toolstate` repository.
369 ///
370 /// The function relies on a GitHub bot user, which should have a Personal access
371 /// token defined in the environment variable $TOOLSTATE_REPO_ACCESS_TOKEN. If for
372 /// some reason you need to change the token, please update the Azure Pipelines
373 /// variable group.
374 ///
375 ///   1. Generate a new Personal access token:
376 ///
377 ///       * Login to the bot account, and go to Settings -> Developer settings ->
378 ///           Personal access tokens
379 ///       * Click "Generate new token"
380 ///       * Enable the "public_repo" permission, then click "Generate token"
381 ///       * Copy the generated token (should be a 40-digit hexadecimal number).
382 ///           Save it somewhere secure, as the token would be gone once you leave
383 ///           the page.
384 ///
385 ///   2. Update the variable group in Azure Pipelines
386 ///
387 ///       * Ping a member of the infrastructure team to do this.
388 ///
389 ///   4. Replace the email address below if the bot account identity is changed
390 ///
391 ///       * See <https://help.github.com/articles/about-commit-email-addresses/>
392 ///           if a private email by GitHub is wanted.
393 fn commit_toolstate_change(current_toolstate: &ToolstateData) {
394     let message = format!("({} CI update)", OS.expect("linux/windows only"));
395     let mut success = false;
396     for _ in 1..=5 {
397         // Upload the test results (the new commit-to-toolstate mapping) to the toolstate repo.
398         // This does *not* change the "current toolstate"; that only happens post-landing
399         // via `src/ci/docker/publish_toolstate.sh`.
400         publish_test_results(&current_toolstate);
401
402         // `git commit` failing means nothing to commit.
403         let status = t!(Command::new("git")
404             .current_dir(TOOLSTATE_DIR)
405             .arg("commit")
406             .arg("-a")
407             .arg("-m")
408             .arg(&message)
409             .status());
410         if !status.success() {
411             success = true;
412             break;
413         }
414
415         let status = t!(Command::new("git")
416             .current_dir(TOOLSTATE_DIR)
417             .arg("push")
418             .arg("origin")
419             .arg("master")
420             .status());
421         // If we successfully push, exit.
422         if status.success() {
423             success = true;
424             break;
425         }
426         eprintln!("Sleeping for 3 seconds before retrying push");
427         std::thread::sleep(std::time::Duration::from_secs(3));
428         let status = t!(Command::new("git")
429             .current_dir(TOOLSTATE_DIR)
430             .arg("fetch")
431             .arg("origin")
432             .arg("master")
433             .status());
434         assert!(status.success());
435         let status = t!(Command::new("git")
436             .current_dir(TOOLSTATE_DIR)
437             .arg("reset")
438             .arg("--hard")
439             .arg("origin/master")
440             .status());
441         assert!(status.success());
442     }
443
444     if !success {
445         panic!("Failed to update toolstate repository with new data");
446     }
447 }
448
449 /// Updates the "history" files with the latest results.
450 ///
451 /// These results will later be promoted to `latest.json` by the
452 /// `publish_toolstate.py` script if the PR passes all tests and is merged to
453 /// master.
454 fn publish_test_results(current_toolstate: &ToolstateData) {
455     let commit = t!(std::process::Command::new("git").arg("rev-parse").arg("HEAD").output());
456     let commit = t!(String::from_utf8(commit.stdout));
457
458     let toolstate_serialized = t!(serde_json::to_string(&current_toolstate));
459
460     let history_path = Path::new(TOOLSTATE_DIR)
461         .join("history")
462         .join(format!("{}.tsv", OS.expect("linux/windows only")));
463     let mut file = t!(fs::read_to_string(&history_path));
464     let end_of_first_line = file.find('\n').unwrap();
465     file.insert_str(end_of_first_line, &format!("\n{}\t{}", commit.trim(), toolstate_serialized));
466     t!(fs::write(&history_path, file));
467 }
468
469 #[derive(Debug, Serialize, Deserialize)]
470 struct RepoState {
471     tool: String,
472     windows: ToolState,
473     linux: ToolState,
474     commit: String,
475     datetime: String,
476 }
477
478 impl RepoState {
479     fn state(&self) -> ToolState {
480         if cfg!(target_os = "linux") {
481             self.linux
482         } else if cfg!(windows) {
483             self.windows
484         } else {
485             unimplemented!()
486         }
487     }
488 }