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