-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscanner_binary_manager.rs
More file actions
262 lines (217 loc) · 8.01 KB
/
scanner_binary_manager.rs
File metadata and controls
262 lines (217 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#![allow(dead_code)] // FIXME: to be removed later, when this is used
use regex::Regex;
use semver::Version;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use thiserror::Error;
use tokio::process::Command;
#[derive(Error, Debug)]
pub(in crate::infra) enum ScannerBinaryManagerError {
#[error("operating system is not supported, current supported systems are linux and darwin")]
UnsupportedOS,
#[error("architecture is not supported, current supported architectures are arm64 and amd64")]
UnsupportedArch,
#[error("the scanner is not installed")]
NotInstalled,
#[error("the installed scanner is not executable")]
NotExecutable,
#[error("i/o error: {0}")]
IOError(#[from] std::io::Error),
#[error("error extracting the version from output: {0}")]
VersionExtractionError(String),
#[error("error parsing version: {0}")]
VersionParsingError(#[from] semver::Error),
#[error("error performing http request: {0}")]
HTTPError(#[from] reqwest::Error),
}
#[derive(Clone, Default)]
pub(super) struct ScannerBinaryManager {}
impl ScannerBinaryManager {
const fn version(&self) -> Version {
Version::new(1, 22, 6)
}
pub async fn install_expected_version_if_not_present(
&mut self,
) -> Result<PathBuf, ScannerBinaryManagerError> {
let expected_version = self.version();
let binary_path = self.binary_path_for_version(&expected_version);
if self
.needs_to_install_it(&binary_path, &expected_version)
.await?
{
self.install_expected_version(&binary_path, &expected_version)
.await?;
}
Ok(binary_path)
}
async fn needs_to_install_it(
&self,
binary_path: &Path,
expected_version: &Version,
) -> Result<bool, ScannerBinaryManagerError> {
match self.get_current_installed_version_from(binary_path).await {
Ok(current_version) => Ok(¤t_version < expected_version),
Err(err) => match err {
ScannerBinaryManagerError::NotInstalled => Ok(true),
_ => Err(err),
},
}
}
async fn install_expected_version(
&self,
binary_path: &Path,
expected_version: &Version,
) -> Result<(), ScannerBinaryManagerError> {
let response = reqwest::get(self.download_url(expected_version)?).await?;
let body = response.bytes().await?;
let parent_path = binary_path.parent().ok_or_else(|| {
ScannerBinaryManagerError::IOError(std::io::Error::new(
std::io::ErrorKind::NotFound,
"parent not found",
))
})?;
tokio::fs::create_dir_all(parent_path).await?;
tokio::fs::write(&binary_path, &body).await?;
#[cfg(unix)]
tokio::fs::set_permissions(&binary_path, std::fs::Permissions::from_mode(0o755)).await?;
Ok(())
}
fn download_url(&self, version: &Version) -> Result<String, ScannerBinaryManagerError> {
let os = match std::env::consts::OS {
"linux" => "linux",
"macos" => "darwin",
_ => return Err(ScannerBinaryManagerError::UnsupportedOS),
};
let arch = match std::env::consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
_ => return Err(ScannerBinaryManagerError::UnsupportedArch),
};
Ok(format!(
"https://download.sysdig.com/scanning/bin/sysdig-cli-scanner/{version}/{os}/{arch}/sysdig-cli-scanner"
))
}
async fn get_current_installed_version_from(
&self,
binary_path: &Path,
) -> Result<semver::Version, ScannerBinaryManagerError> {
if !binary_path.exists() {
return Err(ScannerBinaryManagerError::NotInstalled);
}
if !self.is_executable(binary_path).await {
return Err(ScannerBinaryManagerError::NotExecutable);
}
let output = Command::new(binary_path).arg("--version").output().await?;
if !output.status.success() {
return Err(ScannerBinaryManagerError::IOError(std::io::Error::other(
format!(
"status command is not succesful: {}",
output.status.code().unwrap_or(0)
),
)));
}
// We merge both stdout and stderr in case they switch from one or another. Happened from 1.17.0 to 1.20.0
let stdout =
String::from_utf8_lossy(&output.stdout) + String::from_utf8_lossy(&output.stderr);
let version_str = Regex::new(r"Sysdig CLI Scanner (\d+\.\d+\.\d+)")
.unwrap()
.captures(&stdout)
.and_then(|captures| captures.get(1))
.map(|x| x.as_str())
.ok_or_else(|| {
ScannerBinaryManagerError::VersionExtractionError(stdout.clone().into_owned())
})?;
Ok(Version::parse(version_str)?)
}
async fn is_executable(&self, binary_path: &Path) -> bool {
#[cfg(unix)]
{
match tokio::fs::metadata(binary_path).await {
Ok(metadata) => {
let permissions = metadata.permissions();
permissions.mode() & 0o111 != 0
}
_ => false,
}
}
#[cfg(windows)]
{
if let Some(ext) = binary_path.extension() {
matches!(ext.to_str(), Some("exe") | Some("bat") | Some("cmd"))
} else {
false
}
}
}
fn binary_path_for_version(&self, version: &Version) -> PathBuf {
let mut cache_dir = dirs::cache_dir().unwrap_or_else(|| PathBuf::from("."));
cache_dir.push("sysdig-cli-scanner");
cache_dir.push(format!("sysdig-cli-scanner.{version}"));
cache_dir
}
}
#[cfg(test)]
mod tests {
use super::ScannerBinaryManager;
use core::panic;
use semver::Version;
use serial_test::file_serial;
#[tokio::test]
async fn it_gets_the_wanted_version() {
let mgr = ScannerBinaryManager::default();
assert_eq!(mgr.version().to_string(), "1.22.6");
}
#[tokio::test]
async fn it_retrieves_the_binary_path() {
let mgr = ScannerBinaryManager::default();
assert!(
mgr.binary_path_for_version(&Version::new(1, 22, 1))
.ends_with(".cache/sysdig-cli-scanner/sysdig-cli-scanner.1.22.1")
);
}
#[tokio::test]
async fn it_will_download_from_the_correct_url() {
let mgr = ScannerBinaryManager::default();
assert_eq!(
mgr.download_url(&Version::new(1, 22, 1)).unwrap(),
"https://download.sysdig.com/scanning/bin/sysdig-cli-scanner/1.22.1/linux/amd64/sysdig-cli-scanner"
);
}
#[tokio::test]
#[file_serial]
async fn it_downloads_if_it_doesnt_exist() {
let mut mgr = ScannerBinaryManager::default();
let binary_path = mgr.binary_path_for_version(&mgr.version());
let _ = tokio::fs::remove_file(&binary_path).await;
mgr.install_expected_version_if_not_present()
.await
.unwrap_or_else(|e| panic!("{}", e));
assert_eq!(
mgr.get_current_installed_version_from(&binary_path)
.await
.unwrap()
.to_string(),
"1.22.6"
);
}
#[tokio::test]
#[file_serial]
async fn it_doesnt_download_if_it_exists() {
let mut mgr = ScannerBinaryManager::default();
let binary_path = mgr.binary_path_for_version(&mgr.version());
mgr.install_expected_version_if_not_present()
.await
.unwrap_or_else(|e| panic!("{}", e));
mgr.install_expected_version_if_not_present()
.await
.unwrap_or_else(|e| panic!("{}", e));
assert_eq!(
mgr.get_current_installed_version_from(&binary_path)
.await
.unwrap()
.to_string(),
"1.22.6"
);
}
}