Skip to main content

avalanche_config_installer/
github.rs

1use std::{
2    env, fmt,
3    fs::{self, File},
4    io::{self, copy, Cursor, Error, ErrorKind},
5    os::unix::fs::PermissionsExt,
6};
7
8use reqwest::ClientBuilder;
9use serde::{Deserialize, Serialize};
10use tokio::time::{sleep, Duration};
11
12/// Downloads the latest from the github release page.
13pub async fn download_latest(
14    arch: Option<Arch>,
15    os: Option<Os>,
16    target_file_path: &str,
17) -> io::Result<()> {
18    download(arch, os, None, target_file_path).await
19}
20
21pub const DEFAULT_TAG_NAME: &str = "latest";
22
23/// Downloads the official binaries from the GitHub release page.
24/// Returns the path to the binary path.
25///
26/// Leave "release_tag" none to download the latest.
27///
28/// Leave "arch" and "os" empty to auto-detect from its local system.
29/// "arch" must be either "amd64" or "arm64".
30/// "os" must be either "macos", "linux", or "win".
31/// ref. https://github.com/ava-labs/avalanche-ops/releases
32pub async fn download(
33    arch: Option<Arch>,
34    os: Option<Os>,
35    release_tag: Option<String>,
36    target_file_path: &str,
37) -> io::Result<()> {
38    // e.g., "v0.0.45"
39    let tag_name = if let Some(v) = release_tag {
40        v
41    } else {
42        log::info!("fetching the latest git tags");
43        let mut release_info = ReleaseResponse::default();
44        for round in 0..20 {
45            let info = match crate::github::fetch_latest_release("ava-labs", "avalanche-ops").await
46            {
47                Ok(v) => v,
48                Err(e) => {
49                    log::warn!(
50                        "failed fetch_latest_release {} -- retrying {}...",
51                        e,
52                        round + 1
53                    );
54                    sleep(Duration::from_secs((round + 1) * 5)).await;
55                    continue;
56                }
57            };
58
59            release_info = info;
60            if release_info.tag_name.is_some() {
61                break;
62            }
63
64            log::warn!("release_info.tag_name is None -- retrying {}...", round + 1);
65            sleep(Duration::from_secs((round + 1) * 5)).await;
66        }
67
68        if release_info.tag_name.is_none() {
69            log::warn!("release_info.tag_name not found -- defaults to {DEFAULT_TAG_NAME}");
70            release_info.tag_name = Some(DEFAULT_TAG_NAME.to_string());
71        }
72
73        if release_info.prerelease {
74            log::warn!(
75                "latest release '{}' is prerelease, falling back to default tag name '{}'",
76                release_info.tag_name.unwrap(),
77                DEFAULT_TAG_NAME
78            );
79            DEFAULT_TAG_NAME.to_string()
80        } else {
81            release_info.tag_name.unwrap()
82        }
83    };
84
85    // ref. https://github.com/ava-labs/avalanche-ops/releases
86    log::info!(
87        "detecting arch and platform for the release version tag {}",
88        tag_name
89    );
90    let arch = {
91        if arch.is_none() {
92            match env::consts::ARCH {
93                "x86_64" => String::from("x86_64"),
94                "aarch64" => String::from("aarch64"),
95                _ => String::from(""),
96            }
97        } else {
98            let arch = arch.unwrap();
99            arch.to_string()
100        }
101    };
102
103    // TODO: handle Apple arm64 when the official binary is available
104    // ref. https://github.com/ava-labs/avalanche-ops/releases
105    let file_name = {
106        if os.is_none() {
107            if cfg!(target_os = "macos") {
108                format!("avalanche-config.{arch}-apple-darwin")
109            } else if cfg!(unix) {
110                format!("avalanche-config.{arch}-unknown-linux-gnu")
111            } else {
112                String::new()
113            }
114        } else {
115            let os = os.unwrap();
116            match os {
117                Os::MacOs => format!("avalanche-config.{arch}-apple-darwin"),
118                Os::Linux => format!("avalanche-config.{arch}-unknown-linux-gnu"),
119            }
120        }
121    };
122    if file_name.is_empty() {
123        return Err(Error::new(
124            ErrorKind::Other,
125            format!("unknown platform '{}'", env::consts::OS),
126        ));
127    }
128
129    log::info!("downloading latest '{}'", file_name);
130    let download_url = format!(
131        "https://github.com/ava-labs/avalanche-ops/releases/download/{}/{}",
132        tag_name, file_name
133    );
134    let tmp_file_path = random_manager::tmp_path(10, None)?;
135    download_file(&download_url, &tmp_file_path).await?;
136
137    {
138        let f = File::open(&tmp_file_path)?;
139        f.set_permissions(PermissionsExt::from_mode(0o777))?;
140    }
141    log::info!("copying {tmp_file_path} to {target_file_path}");
142    fs::copy(&tmp_file_path, &target_file_path)?;
143    fs::remove_file(&tmp_file_path)?;
144
145    Ok(())
146}
147
148/// ref. https://github.com/ava-labs/avalanche-ops/releases
149/// ref. https://api.github.com/repos/ava-labs/avalanche-ops/releases/latest
150pub async fn fetch_latest_release(org: &str, repo: &str) -> io::Result<ReleaseResponse> {
151    let ep = format!(
152        "https://api.github.com/repos/{}/{}/releases/latest",
153        org, repo
154    );
155    log::info!("fetching {}", ep);
156
157    let cli = ClientBuilder::new()
158        .user_agent(env!("CARGO_PKG_NAME"))
159        .danger_accept_invalid_certs(true)
160        .timeout(Duration::from_secs(15))
161        .connection_verbose(true)
162        .build()
163        .map_err(|e| {
164            Error::new(
165                ErrorKind::Other,
166                format!("failed ClientBuilder build {}", e),
167            )
168        })?;
169    let resp =
170        cli.get(&ep).send().await.map_err(|e| {
171            Error::new(ErrorKind::Other, format!("failed ClientBuilder send {}", e))
172        })?;
173    let out = resp
174        .bytes()
175        .await
176        .map_err(|e| Error::new(ErrorKind::Other, format!("failed ClientBuilder send {}", e)))?;
177    let out: Vec<u8> = out.into();
178
179    let resp: ReleaseResponse = match serde_json::from_slice(&out) {
180        Ok(p) => p,
181        Err(e) => {
182            return Err(Error::new(
183                ErrorKind::Other,
184                format!("failed to decode {}", e),
185            ));
186        }
187    };
188    Ok(resp)
189}
190
191/// ref. https://api.github.com/repos/ava-labs/avalanche-ops/releases/latest
192#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
193#[serde(rename_all = "snake_case")]
194pub struct ReleaseResponse {
195    /// Sometimes empty for github API consistency issue.
196    pub tag_name: Option<String>,
197    /// Sometimes empty for github API consistency issue.
198    pub assets: Option<Vec<Asset>>,
199
200    #[serde(default)]
201    pub prerelease: bool,
202}
203
204impl Default for ReleaseResponse {
205    fn default() -> Self {
206        Self::default()
207    }
208}
209
210impl ReleaseResponse {
211    pub fn default() -> Self {
212        Self {
213            tag_name: None,
214            assets: None,
215            prerelease: false,
216        }
217    }
218}
219
220/// ref. https://api.github.com/repos/ava-labs/avalanche-ops/releases/latest
221#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
222#[serde(rename_all = "snake_case")]
223pub struct Asset {
224    pub name: String,
225    pub browser_download_url: String,
226}
227
228/// Represents the release "arch".
229#[derive(Eq, PartialEq, Clone)]
230pub enum Arch {
231    Amd64,
232    Arm64,
233}
234
235/// ref. https://doc.rust-lang.org/std/string/trait.ToString.html
236/// ref. https://doc.rust-lang.org/std/fmt/trait.Display.html
237/// Use "Self.to_string()" to directly invoke this
238impl fmt::Display for Arch {
239    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240        match self {
241            Arch::Amd64 => write!(f, "amd64"),
242            Arch::Arm64 => write!(f, "arm64"),
243        }
244    }
245}
246
247impl Arch {
248    pub fn new(arch: &str) -> io::Result<Self> {
249        match arch {
250            "amd64" => Ok(Arch::Amd64),
251            "arm64" => Ok(Arch::Arm64),
252            _ => Err(Error::new(
253                ErrorKind::InvalidInput,
254                format!("unknown arch {}", arch),
255            )),
256        }
257    }
258}
259
260/// Represents the release "os".
261#[derive(Eq, PartialEq, Clone)]
262pub enum Os {
263    MacOs,
264    Linux,
265}
266
267/// ref. https://doc.rust-lang.org/std/string/trait.ToString.html
268/// ref. https://doc.rust-lang.org/std/fmt/trait.Display.html
269/// Use "Self.to_string()" to directly invoke this
270impl fmt::Display for Os {
271    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
272        match self {
273            Os::MacOs => write!(f, "macos"),
274            Os::Linux => write!(f, "linux"),
275        }
276    }
277}
278
279impl Os {
280    pub fn new(os: &str) -> io::Result<Self> {
281        match os {
282            "macos" => Ok(Os::MacOs),
283            "linux" => Ok(Os::Linux),
284            _ => Err(Error::new(
285                ErrorKind::InvalidInput,
286                format!("unknown os {}", os),
287            )),
288        }
289    }
290}
291
292/// Downloads a file to the "file_path".
293pub async fn download_file(ep: &str, file_path: &str) -> io::Result<()> {
294    log::info!("downloading the file via {}", ep);
295    let resp = reqwest::get(ep)
296        .await
297        .map_err(|e| Error::new(ErrorKind::Other, format!("failed reqwest::get {}", e)))?;
298
299    let mut content = Cursor::new(
300        resp.bytes()
301            .await
302            .map_err(|e| Error::new(ErrorKind::Other, format!("failed bytes {}", e)))?,
303    );
304
305    let mut f = File::create(file_path)?;
306    copy(&mut content, &mut f)?;
307
308    Ok(())
309}