1use crate::*;
2
3pub fn file_link(path: &str, zip: bool) -> Value {
4 let root = env("SNOWGLOBE_STORE_ROOT", "/srv");
5 let Some(relative) = std::path::Path::new(path).strip_prefix(&root).ok() else {
6 return Value::Null;
7 };
8 let path = relative
9 .components()
10 .map(|c| encoded(&c.as_os_str().to_string_lossy()))
11 .collect::<Vec<_>>()
12 .join("/");
13 let Ok(files) = std::env::var("SNOWGLOBE_FILES_URL") else {
14 return Value::Null;
15 };
16 json!(format!("{files}/{path}{}", if zip { "?zip" } else { "" }))
17}
18fn qbt_link(path: &str, zip: bool) -> Value {
19 file_link(
20 &if path == "/data/media" || path.starts_with("/data/media/") {
21 format!("/srv/clover/Media{}", &path[11..])
22 } else {
23 path.into()
24 },
25 zip,
26 )
27}
28async fn qbt(app: Arc<App>, route: &str, form: Option<Value>) -> Result<Value> {
29 let base = telemetry::endpoint(app.clone(), "qbittorrent")
30 .await
31 .map_err(|_| Error::new(503, "qBittorrent is unavailable. Check its service status."))?;
32 let mut request = if form.is_some() {
33 app.request(Method::POST, &format!("{base}/api/v2/{route}"))?
34 } else {
35 app.request(Method::GET, &format!("{base}/api/v2/{route}"))?
36 };
37 if let Some(form) = form {
38 request = request.form(&form);
39 }
40 let response = request.send().await?;
41 if !response.status().is_success() {
42 return Err(Error::new(
43 502,
44 format!(
45 "qBittorrent refused the request ({}). Retry from its page.",
46 response.status()
47 ),
48 ));
49 }
50 if response
51 .headers()
52 .get("content-type")
53 .and_then(|h| h.to_str().ok())
54 .is_some_and(|h| h.contains("json"))
55 {
56 Ok(response.json().await?)
57 } else {
58 Ok(json!(response.text().await?))
59 }
60}
61async fn seed_state(app: Arc<App>) -> Result<Arc<Document>> {
62 let state = app.clone();
63 app.cache
64 .get(
65 "seed-state".into(),
66 Duration::from_secs(5),
67 move || async move {
68 let (data, prefs) = tokio::try_join!(
69 qbt(state.clone(), "sync/maindata?rid=0", None),
70 qbt(state.clone(), "app/preferences", None)
71 )?;
72 let mut value = data["server_state"].clone();
73 if let (Some(value), Some(prefs)) = (value.as_object_mut(), prefs.as_object()) {
74 value.extend(prefs.clone());
75 }
76 let t = (now() / 5.0).floor() * 5.0;
77 let mut samples = state.seed_samples.lock().unwrap();
78 if samples.last().is_none_or(|s| s["t"] != t) {
79 samples.push(
80 json!({"t":t,"down":value["dl_info_speed"],"up":value["up_info_speed"]}),
81 );
82 }
83 samples.retain(|s| number(&s["t"]) >= t - 3600.0);
84 Ok(value)
85 },
86 )
87 .await
88}
89async fn vm_call(action: &str, payload: Option<Value>) -> Result<Value> {
90 let mut request = json!({"operation":format!("vm.{action}")});
91 if let Some(payload) = payload {
92 request["payload"] = payload;
93 }
94 host::call(request).await
95}
96
97/// Who has the GPU. The guest's power state says games; the GPU services' health says which service.
98async fn gpu(app: Arc<App>) -> Value {
99 let found = tokio::try_join!(core::managed(), core::scan(app)).ok();
100 let services = found.map(|(managed, scan)| {
101 scan.value
102 .as_object()
103 .into_iter()
104 .flat_map(|jobs| jobs.iter())
105 .filter(|(id, entry)| {
106 managed.contains(id) && array(&entry["job"]["TaskGroups"])
107 .iter()
108 .flat_map(|group| array(&group["Tasks"]))
109 .any(|task| {
110 array(&task["Config"]["devices"])
111 .iter()
112 .any(|device| string(device).starts_with("/dev/nvidia"))
113 })
114 })
115 .map(|(id, entry)| json!({"id":id,"name":entry["job"]["Meta"]["snowglobe_name"].as_str().unwrap_or(id),"health":entry["health"]}))
116 .collect::<Vec<_>>()
117 });
118 let run = host::call(json!({"operation":"deploy.last"}))
119 .await
120 .unwrap_or_default();
121 let ours = run["action"] == "gpu";
122 let failed = if !ours || run["code"].is_null() || run["code"] == 0 {
123 Value::Null
124 } else if run["code"] == 2 {
125 // The switch exits 2 with a message for the person on its last line.
126 let lines = host::call(json!({"operation":"deploy.run","id":run["id"]}))
127 .await
128 .unwrap_or_default();
129 array(&lines["lines"])
130 .iter()
131 .rev()
132 .nth(1)
133 .cloned()
134 .unwrap_or(json!("Couldn't switch the GPU."))
135 } else {
136 json!("Couldn't switch the GPU.")
137 };
138 let switching = if ours && run["code"].is_null() {
139 run["target"].clone()
140 } else {
141 Value::Null
142 };
143 json!({"services":services,"switching":switching,"failed":failed})
144}
145
146fn vm_name(name: &str) -> Result<()> {
147 if regex::Regex::new(r"^[a-z0-9][a-z0-9-]{0,62}$")
148 .unwrap()
149 .is_match(name)
150 {
151 Ok(())
152 } else {
153 Err(Error::new(400, "No VM has that name."))
154 }
155}
156fn validate_vm(mut spec: Value) -> Result<Value> {
157 vm_name(string(&spec["name"]))?;
158 spec["description"] = json!("");
159 spec["autostart"] = json!(false);
160 spec["start"] = json!(spec["mode"] == "preset");
161 if string(&spec["image"]).is_empty() {
162 return Err(Error::new(400, "Pick an OS image."));
163 }
164 for (key, min) in [
165 ("vcpus", 1.0),
166 ("memory", 536870912.0),
167 ("disk", 1073741824.0),
168 ] {
169 let n = number(&spec[key]);
170 if !spec[key].is_number() || n.fract() != 0.0 || n < min {
171 return Err(Error::new(400, format!("Invalid {key}.")));
172 }
173 }
174 Ok(spec)
175}
176async fn paper(app: Arc<App>, path: &str, body: Option<Value>) -> Result<Value> {
177 let jobs = core::scan(app.clone()).await?;
178 let host = jobs.value["clover-source-of-truth"]["job"]["Meta"]["snowglobe_hostname"]
179 .as_str()
180 .ok_or_else(|| Error::new(502, "Paper Clover is unavailable."))?;
181 let key = host::call(
182 json!({"operation":"deploy.secret.get","service":"clover-source-of-truth","key":"key"}),
183 )
184 .await?;
185 let key = key
186 .as_str()
187 .ok_or_else(|| Error::new(502, "Paper Clover is unavailable."))?;
188 let url = format!("https://{host}/{path}");
189 let request = if let Some(body) = body {
190 app.http.post(&url).json(&body)
191 } else {
192 app.http.get(&url)
193 };
194 let response = request
195 .header("Authorization", key)
196 .timeout(Duration::from_secs(10))
197 .send()
198 .await?;
199 if path == "scan" {
200 if response.status() == 409 {
201 return Err(Error::new(
202 409,
203 "File scans are off on this host. Turn on the Paper Clover indexer to use this action.",
204 ));
205 }
206 if response.status() != 202 {
207 return Err(Error::new(
208 502,
209 "Paper Clover couldn't start the scan. Check its service logs.",
210 ));
211 }
212 return Ok(Value::Null);
213 }
214 if !response.status().is_success() {
215 return Err(Error::new(
216 502,
217 format!("Paper Clover answered {}.", response.status()),
218 ));
219 }
220 Ok(response.json().await?)
221}
222
223pub async fn route(
224 app: Arc<App>,
225 method: &Method,
226 parts: &[&str],
227 query: &HashMap<String, String>,
228 me: &Value,
229 body: Value,
230) -> Result<Response> {
231 let value = match parts {
232 ["seedbox"] if method == Method::GET => {
233 let (state, mut torrents) = tokio::try_join!(
234 seed_state(app.clone()),
235 qbt(app.clone(), "torrents/info", None)
236 )?;
237 for torrent in torrents.as_array_mut().unwrap() {
238 let root = torrent["root_path"]
239 .as_str()
240 .filter(|s| !s.is_empty())
241 .unwrap_or(string(&torrent["save_path"]))
242 .to_owned();
243 torrent["folder"] = qbt_link(&root, false);
244 torrent["zip"] = if string(&torrent["root_path"]).is_empty() {
245 Value::Null
246 } else {
247 qbt_link(string(&torrent["root_path"]), true)
248 };
249 }
250 json!({"state":state.value,"downloads":qbt_link(string(&state.value["save_path"]),false),"torrents":torrents})
251 }
252 ["seedbox", "history"] if method == Method::GET => {
253 seed_state(app.clone()).await?;
254 let samples = app.seed_samples.lock().unwrap();
255 json!([("download","down"),("upload","up")].map(|(name,key)| json!({"name":name,"t":samples.iter().map(|s| s["t"].clone()).collect::<Vec<_>>(),"v":samples.iter().map(|s| s[key].clone()).collect::<Vec<_>>()})))
256 }
257 ["seedbox", "torrents"] if method == Method::POST => {
258 let url = string(&body["url"]).trim();
259 if !regex::Regex::new(r"(?i)^(magnet:\?|https?://)")
260 .unwrap()
261 .is_match(url)
262 {
263 return Err(Error::new(
264 400,
265 "Paste a magnet link or a link to a .torrent file",
266 ));
267 }
268 qbt(app, "torrents/add", Some(json!({"urls":url}))).await?;
269 Value::Null
270 }
271 ["seedbox", "torrents", hash, tail @ ..] => {
272 if !regex::Regex::new(r"^[0-9a-f]{40}$").unwrap().is_match(hash) {
273 return Err(Error::new(
274 400,
275 "Torrent hashes are 40 lowercase hex characters.",
276 ));
277 }
278 match tail {
279 ["files"] if method == Method::GET => {
280 let route = format!("torrents/files?{}", params(&[("hash", hash.to_string())]));
281 let (torrents, mut files) = tokio::try_join!(
282 qbt(app.clone(), "torrents/info", None),
283 qbt(app.clone(), &route, None)
284 )?;
285 let root = array(&torrents)
286 .iter()
287 .find(|t| t["hash"] == *hash)
288 .and_then(|t| t["save_path"].as_str());
289 for file in files.as_array_mut().unwrap() {
290 file["link"] = root
291 .map(|root| {
292 qbt_link(&format!("{root}/{}", string(&file["name"])), false)
293 })
294 .unwrap_or(Value::Null);
295 }
296 files
297 }
298 [action]
299 if method == Method::POST
300 && [
301 "stop",
302 "start",
303 "topPrio",
304 "increasePrio",
305 "decreasePrio",
306 "bottomPrio",
307 ]
308 .contains(action) =>
309 {
310 qbt(
311 app,
312 &format!("torrents/{action}"),
313 Some(json!({"hashes":hash})),
314 )
315 .await?;
316 Value::Null
317 }
318 [] if method == Method::DELETE => {
319 let files = query.get("files").map(String::as_str).unwrap_or("0");
320 if !["0", "1"].contains(&files) {
321 return Err(Error::new(400, "Invalid files option."));
322 }
323 qbt(app,"torrents/delete",Some(json!({"hashes":hash,"deleteFiles":if files=="1" {"true"} else {"false"}}))).await?;
324 Value::Null
325 }
326 _ => return Err(Error::new(404, "Not Found")),
327 }
328 }
329 ["vms"] if method == Method::GET => {
330 let mut values = Vec::new();
331 for (action, ttl) in [("node", 600), ("domains", 5), ("library", 15)] {
332 let value = app
333 .cache
334 .get(
335 format!("vms:{action}"),
336 Duration::from_secs(ttl),
337 move || async move { vm_call(action, None).await },
338 )
339 .await?;
340 values.push(value.value.clone());
341 }
342 let allocated: f64 = array(&values[1])
343 .iter()
344 .filter(|vm| vm["host"] == values[0]["name"] && !["shutoff", "crashed"].contains(&string(&vm["state"])))
345 .map(|vm| number(&vm["balloon"]))
346 .sum();
347 values[0]["availableMemory"] =
348 json!((number(&values[0]["memory"]) - allocated).max(0.0));
349 values[1]
350 .as_array_mut()
351 .unwrap()
352 .retain(|domain| vms::visible(me, domain));
353 for domain in values[1].as_array_mut().unwrap() {
354 domain["usage"] = app
355 .vm_usage
356 .lock()
357 .unwrap()
358 .get(string(&domain["name"]))
359 .cloned()
360 .unwrap_or(Value::Null);
361 domain["gpu"] = if domain["gpu"] == true {
362 gpu(app.clone()).await
363 } else {
364 Value::Null
365 };
366 }
367 json!({"node":values[0],"domains":values[1],"library":values[2],"canPublish":array(&me["sections"]).iter().any(|section| section == "admin")})
368 }
369 ["vms", "history"] if method == Method::GET => {
370 if let Some(name) = query.get("name") {
371 vms::authorize(me, name).await?;
372 }
373 let owned = vm_call("domains", None).await?;
374 let range = telemetry::query_number(query, "range", 300.0, 60.0, 86400.0)?;
375 let mut query = query.clone();
376 query.insert("range".into(), range.to_string());
377 if let Some(name) = query.get("name").cloned() {
378 query.insert("service".into(), name);
379 }
380 let (cpu, memory) = tokio::try_join!(
381 telemetry::metrics(app.clone(), "vm.cpu", &query, None, None),
382 telemetry::metrics(app.clone(), "vm.memory", &query, None, None)
383 )?;
384 let mut domains = serde_json::Map::new();
385 for (values, key) in [(&cpu.value, "cpu"), (&memory.value, "memory")] {
386 for series in array(values) {
387 if !array(&owned).iter().any(|domain| {
388 domain["name"] == series["name"] && vms::visible(me, domain)
389 }) {
390 continue;
391 }
392 let domain = domains
393 .entry(string(&series["name"]).to_owned())
394 .or_insert_with(|| json!({"cpu":[],"memory":[]}));
395 domain[key] = series["v"].clone();
396 }
397 }
398 json!({"t":cpu.value[0]["t"].as_array().or(memory.value[0]["t"].as_array()).cloned().unwrap_or_default(),"domains":domains})
399 }
400 ["vms"] if method == Method::POST => {
401 let mut spec = validate_vm(body)?;
402 spec["owner"] = me["id"].clone();
403 spec["username"] = me["name"].clone();
404 vm_call("create", Some(spec)).await?;
405 app.cache.invalidate("vms:domains");
406 Value::Null
407 }
408 ["vms", name, tail @ ..] => {
409 vm_name(name)?;
410 match tail {
411 ["clipboard"] if method == Method::POST => {
412 vm_call("clipboard", Some(json!({"name":name,"text":body["text"]}))).await?;
413 }
414 ["access"] if method == Method::GET => {
415 let mut response =
416 Document::new(vm_call("access", Some(json!({"name":name}))).await?)
417 .response();
418 response
419 .headers_mut()
420 .insert("cache-control", "no-store".parse().unwrap());
421 return Ok(response);
422 }
423 ["media"] if method == Method::PUT => {
424 vm_call("media", Some(json!({"name":name,"image":body["image"]}))).await?;
425 }
426 ["gpu"] if method == Method::POST => {
427 // Access to the guest that passes the GPU through is what grants the switch.
428 if !array(&vm_call("domains", None).await?)
429 .iter()
430 .any(|domain| domain["name"] == *name && domain["gpu"] == true)
431 {
432 return Err(Error::new(400, format!("{name} doesn't use the GPU.")));
433 }
434 host::call(json!({"operation":"deploy.start","action":"gpu","target":body["side"]}))
435 .await?;
436 app.cache.invalidate("deploys");
437 }
438 ["preset"] if method == Method::POST => {
439 need(me, "admin")?;
440 vm_call("preset", Some(json!({"name":name,"id":body["id"],"os":body["os"],"description":body["description"]}))).await?;
441 app.cache.invalidate("vms:library");
442 }
443 [] if method == Method::PATCH => {
444 let mut payload = json!({"name":name});
445 if let Some(v) = body.get("autostart") {
446 if !v.is_boolean() {
447 return Err(Error::new(400, "Invalid autostart."));
448 }
449 payload["autostart"] = v.clone();
450 }
451 if let Some(v) = body.get("description") {
452 let v = v
453 .as_str()
454 .ok_or_else(|| Error::new(400, "Enter a description."))?
455 .trim();
456 if v.chars().count() > 200 {
457 return Err(Error::new(
458 400,
459 "Keep the description under 200 characters.",
460 ));
461 }
462 payload["description"] = json!(v);
463 }
464 vm_call("update", Some(payload)).await?;
465 }
466 [] if method == Method::DELETE => {
467 let disks = query.get("disks").map(String::as_str).unwrap_or("1");
468 if !["0", "1"].contains(&disks) {
469 return Err(Error::new(400, "Invalid disks option."));
470 }
471 vm_call("remove", Some(json!({"name":name,"disks":disks=="1"}))).await?;
472 }
473 [action]
474 if method == Method::POST
475 && ["start", "shutdown", "reboot", "destroy", "resume", "suspend"]
476 .contains(action) =>
477 {
478 vm_call("act", Some(json!({"name":name,"action":action}))).await?;
479 }
480 _ => return Err(Error::new(404, "Not Found")),
481 }
482 app.cache.invalidate("vms:domains");
483 Value::Null
484 }
485 ["paper-clover"] if method == Method::GET => {
486 let mut value = paper(app, "stats", None).await?;
487 value["browse"] = std::env::var("SNOWGLOBE_PUBLISHED_ROOT")
488 .ok()
489 .map(|p| file_link(&p, false))
490 .unwrap_or(Value::Null);
491 value
492 }
493 ["paper-clover", "activity"] if method == Method::GET => {
494 paper(app, "activity", None).await?
495 }
496 ["paper-clover", "scan"] if method == Method::POST => {
497 let path = &body["path"];
498 if !path.is_null()
499 && (!path.is_string()
500 || !string(path).starts_with('/')
501 || string(path).split('/').any(|s| s == ".."))
502 {
503 return Err(Error::new(
504 400,
505 "Paths can't contain \"..\". Write the full path, like /2026/friends.",
506 ));
507 }
508 paper(
509 app,
510 "scan",
511 Some(if path.is_null() {
512 json!({})
513 } else {
514 json!({"path":path})
515 }),
516 )
517 .await?;
518 return Ok(StatusCode::ACCEPTED.into_response());
519 }
520 _ => return Err(Error::new(404, "Not Found")),
521 };
522 Ok(if value.is_null() {
523 StatusCode::NO_CONTENT.into_response()
524 } else {
525 Document::new(value).response()
526 })
527}