Repository navigation
Expand file tree
/
Copy pathagent.rs
More file actions
3553 lines (3414 loc) · 133 KB
/
Copy pathagent.rs
File metadata and controls
3553 lines (3414 loc) · 133 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors
* SPDX-License-Identifier: Apache-2.0
*/
//! The resident agent: one per host, started by systemd as `flare agent`.
//!
//! The agent owns its node key, its authorized controller set, and a cache of executables and
//! core files. Over an authenticated session it pairs with a controller, receives files,
//! fetches files from other nodes under a grant, runs this host's rank of a group under a grant,
//! and streams the rank's output to whoever attaches. It supervises the rank for the process's
//! life: a controller going away neither stops the rank nor loses its output, and a STOP from an
//! authorized controller sends SIGTERM.
//!
//! Request bodies are JSON except PUT, whose body is a little-endian `u32` header length, the
//! JSON header, and the transferred bytes in range order.
use std::collections::VecDeque;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{TcpListener, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
use std::time::{Duration, Instant};
use flare_helios::runtime_core::{Publisher, VerifiedCore};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::cache::{self, Pinned, Pins};
use super::gpu::{self, Gpu};
use super::grant::{Grant, Signed};
use super::identity::{Key, PublicKey};
use super::session::{FRAME_LIMIT, Role, Session};
use super::store::AgentDir;
use super::{Failure, PROTOCOL_VERSION, frame, hex, hmac_sha256, now};
/// The first frame each side sends: who it is and what it speaks.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Hello {
pub version: u32,
/// `controller` or `node`.
pub kind: String,
pub name: String,
pub public_key: String,
/// The controller-set revision the sender holds; 0 when unpaired or for a controller.
pub controllers_revision: u64,
#[serde(default)]
pub free_bytes: u64,
/// The node's installed Flare, used when RUN omits a cached binary name.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub executable: Option<PathBuf>,
/// The sender accepts live DOWNLOAD progress frames. The field is optional
/// so protocol-6 peers that predate it keep the previous request/response
/// behavior instead of receiving frames they do not expect.
#[serde(default)]
pub download_progress: bool,
}
impl Hello {
pub fn installed_executable(&self) -> Result<&Path, Failure> {
self.executable.as_deref().ok_or_else(|| {
"agent does not advertise an installed Flare executable; update it with `flare agent install`, or supply a node-compatible build with --executable PATH"
.into()
})
}
}
/// A repository download on the node, using a controller-resolved revision and access token.
#[derive(Serialize, Deserialize)]
pub struct DownloadRequest {
pub source: String,
pub options: crate::cli::HubOptions,
pub access_token: Option<String>,
/// Public publisher profiles supplied by the controller. Never private
/// material or controller-local paths.
#[serde(default)]
pub profiles: Vec<flare_helios::runtime_core::Publisher>,
}
/// Advisory free bytes for an acquisition's transport parent and model cache.
/// It is reported for sizing only; acquisition never rejects on these values.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
struct StorageEstimate {
/// `None` when the node cannot query that filesystem.
transport_free: Option<u64>,
core_cache_free: Option<u64>,
}
/// Replace any controller-supplied value with this node's configured hub cache.
/// The field is host-local and serde-skipped on the wire.
fn node_download_options(
hub_cache: Option<&Path>,
mut options: crate::cli::HubOptions,
) -> crate::cli::HubOptions {
options.hub_cache = hub_cache.map(Path::to_owned);
options
}
fn storage_estimate(options: &crate::cli::HubOptions) -> StorageEstimate {
let Ok(model_root) = crate::cache_support::model_root(options.core_cache.as_deref()) else {
return StorageEstimate::default();
};
let transport = crate::hub::transport_root(&model_root, options.cache_dir.as_deref());
StorageEstimate {
transport_free: crate::hub::available_bytes(&transport),
core_cache_free: crate::hub::available_bytes(&model_root),
}
}
fn download(
request: DownloadRequest,
counters: Option<flare_helios::core::progress::AcquisitionProgress>,
) -> Result<(Vec<u8>, flare_helios::core::cache::Entry), Failure> {
if request.options.revision.is_none() || request.options.token_file.is_some() {
return Err(
"DOWNLOAD requires an explicit revision; token-file paths stay on the controller"
.into(),
);
}
let path = crate::hub::download_watched(
&request.source,
&request.options,
0,
request.access_token,
&[],
None,
&request.profiles,
counters,
)
.map_err(|e| e.to_string())?;
// The response names a cache entry the controller will transfer from, so the
// lease must outlive this request rather than dropping with the Entry.
let directory = path.directory().to_path_buf();
Ok((serde_json::to_vec(&json!({"path": directory}))?, path))
}
/// How often a watched download samples its counters. Progress is advisory and
/// must never slow the acquisition it observes.
const DOWNLOAD_REPORT_INTERVAL: Duration = Duration::from_millis(250);
/// Run `work` while sampling its counters for a progress observer. A failed
/// report stops further reports but never cancels the work: the acquisition
/// owns durable cache state, not the controller connection observing it.
fn watch_download<T: Send>(
counters: &flare_helios::core::progress::AcquisitionProgress,
work: impl FnOnce() -> Result<T, Failure> + Send,
mut report: impl FnMut(&flare_helios::core::progress::AcquisitionSnapshot) -> Result<(), Failure>,
) -> Result<T, Failure> {
std::thread::scope(|scope| {
let worker = scope.spawn(work);
let mut previous = counters.snapshot();
let mut reporting = true;
while !worker.is_finished() {
thread::sleep(DOWNLOAD_REPORT_INTERVAL);
let snapshot = counters.snapshot();
if reporting
&& (snapshot.network_bytes != previous.network_bytes
|| snapshot.network_total != previous.network_total
|| snapshot.verification_bytes != previous.verification_bytes)
{
previous = snapshot;
if report(&snapshot).is_err() {
reporting = false;
}
}
}
worker
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
})
}
/// Exchange HELLO frames: the initiator sends first. The peer's HELLO must name the key that
/// authenticated the session and speak the same protocol.
pub fn exchange_hello(session: &mut Session, mine: &Hello) -> Result<Hello, Failure> {
let read = |session: &mut Session| -> Result<Hello, Failure> {
let body = session.expect(frame::HELLO)?;
let hello: Hello = serde_json::from_slice(&body)?;
if hello.version != PROTOCOL_VERSION {
return Err(format!(
"peer speaks agent protocol {}; this flare speaks {PROTOCOL_VERSION}",
hello.version
)
.into());
}
if PublicKey::from_hex(&hello.public_key)? != session.remote() {
return Err("peer's HELLO names a key other than the one it authenticated".into());
}
Ok(hello)
};
let body = serde_json::to_vec(mine)?;
match session.role() {
Role::Initiator => {
session.write_frame(frame::HELLO, &body)?;
read(session)
}
Role::Responder => {
let theirs = read(session)?;
session.write_frame(frame::HELLO, &body)?;
Ok(theirs)
}
}
}
fn now_millis() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
/// The URL of rank zero's metrics endpoint for its last `--host` and `--port` options;
/// a wildcard bind is reached through the loopback address.
pub fn metrics_url(rank_zero: &[String]) -> String {
let option = |name: &str| {
rank_zero
.iter()
.enumerate()
.rev()
.find_map(|(i, argument)| {
if argument == name {
rank_zero.get(i + 1).cloned()
} else {
argument
.strip_prefix(name)?
.strip_prefix('=')
.map(str::to_owned)
}
})
};
let host = match option("--host").as_deref() {
None | Some("0.0.0.0") | Some("::") => "127.0.0.1".to_owned(),
Some(host) if host.contains(':') => format!("[{host}]"),
Some(host) => host.to_owned(),
};
let port = option("--port").unwrap_or_else(|| "8000".into());
format!("http://{host}:{port}/metrics?format=json")
}
/// Free bytes on the filesystem holding `path`.
pub fn free_bytes(path: &Path) -> u64 {
let Ok(path) = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) else {
return 0;
};
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
// SAFETY: path is a valid C string and stat is a valid out-pointer.
if unsafe { libc::statvfs(path.as_ptr(), &mut stat) } != 0 {
return 0;
}
stat.f_bavail as u64 * stat.f_frsize as u64
}
/// The JSON body of a frame, read within [`FRAME_LIMIT`].
fn json_body(session: &mut Session, length: u64) -> Result<Value, Failure> {
Ok(serde_json::from_slice(
&session.read_body(length, FRAME_LIMIT)?,
)?)
}
fn field<'a>(request: &'a Value, name: &str) -> Result<&'a str, Failure> {
request[name]
.as_str()
.ok_or_else(|| format!("request lacks {name}").into())
}
// ---- groups ------------------------------------------------------------------------------------
enum Event {
Line(String),
Exit(i32),
}
struct Log {
lines: VecDeque<String>,
bytes: usize,
exit: Option<(i32, Instant)>,
subscribers: Vec<mpsc::Sender<Event>>,
/// Cache pins held while the rank runs.
pins: Option<Pinned>,
}
const RETAINED_BYTES: usize = 64 << 10;
/// A rank process this agent started and supervises.
pub struct Group {
pub id: String,
pub name: String,
pub rank: usize,
pub core: String,
/// UUIDs of the GPUs the rank holds while it runs.
pub gpus: Vec<String>,
pub pid: i32,
/// Rank zero's metrics URL, derived from its HTTP bind options; None for a peer rank.
pub metrics_url: Option<String>,
started: Instant,
log: Mutex<Log>,
/// The latest metrics document scraped from the rank, with the Unix millisecond it was read.
metrics: Mutex<Option<(u64, Value)>>,
}
impl Group {
fn push(&self, line: String) {
let mut log = self.log.lock().unwrap();
log.bytes += line.len();
log.lines.push_back(line.clone());
while log.bytes > RETAINED_BYTES && log.lines.len() > 1 {
let dropped = log.lines.pop_front().unwrap();
log.bytes -= dropped.len();
}
log.subscribers
.retain(|s| s.send(Event::Line(line.clone())).is_ok());
}
fn finish(&self, code: i32) {
let mut log = self.log.lock().unwrap();
log.exit = Some((code, Instant::now()));
log.subscribers
.retain(|s| s.send(Event::Exit(code)).is_ok());
log.subscribers.clear();
log.pins = None;
}
pub fn running(&self) -> bool {
self.log.lock().unwrap().exit.is_none()
}
pub fn exit(&self) -> Option<i32> {
self.log.lock().unwrap().exit.map(|(code, _)| code)
}
fn retained_at(&self, now: Instant) -> bool {
let log = self.log.lock().unwrap();
match log.exit {
None => true,
Some((0, finished)) => now.saturating_duration_since(finished) < SUCCESS_RETENTION,
Some(_) => true,
}
}
/// Read the rank's metrics endpoint and keep the document.
fn scrape(&self) {
let Some(url) = &self.metrics_url else { return };
static CLIENT: std::sync::OnceLock<ureq::Agent> = std::sync::OnceLock::new();
let client = CLIENT.get_or_init(|| {
ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(2)))
.build()
.into()
});
let document = client
.get(url)
.call()
.ok()
.and_then(|mut response| response.body_mut().read_to_string().ok())
.and_then(|text| serde_json::from_str::<Value>(&text).ok());
if let Some(document) = document {
*self.metrics.lock().unwrap() = Some((now_millis(), document));
}
}
/// The retained output, the exit status if finished, and a receiver of later events.
fn subscribe(&self) -> (Vec<String>, Option<i32>, mpsc::Receiver<Event>) {
let mut log = self.log.lock().unwrap();
let (sender, receiver) = mpsc::channel();
if log.exit.is_none() {
log.subscribers.push(sender);
}
(
log.lines.iter().cloned().collect(),
log.exit.map(|(code, _)| code),
receiver,
)
}
}
// ---- state -------------------------------------------------------------------------------------
/// Verifies a core's stored data at `primary` for `rank` (None for a complete copy) against
/// the publisher's signing key.
pub type Verifier =
Box<dyn Fn(&Path, Option<usize>, &Publisher) -> Result<(), Failure> + Send + Sync>;
/// The marker a core cache directory holds once its stored data verified.
const VERIFIED: &str = ".verified";
/// Successful runs retained for STATUS and ATTACH; failures require explicit removal.
const RETAINED_GROUPS: usize = 16;
const SUCCESS_RETENTION: Duration = Duration::from_secs(5 * 60);
/// Bound successful history by time since exit and count. Preserve running and failed ranks.
fn prune_groups(groups: &mut Vec<Arc<Group>>, now: Instant) {
groups.retain(|group| group.retained_at(now));
let mut excess = groups
.iter()
.filter(|group| group.exit() == Some(0))
.count()
.saturating_sub(RETAINED_GROUPS);
groups.retain(|group| {
if excess > 0 && group.exit() == Some(0) {
excess -= 1;
false
} else {
true
}
});
}
/// Enumerates the host's GPUs.
pub type Gpus = Box<dyn Fn() -> Result<Vec<Gpu>, Failure> + Send + Sync>;
fn verify_core(primary: &Path, rank: Option<usize>, publisher: &Publisher) -> Result<(), Failure> {
VerifiedCore::open(primary, std::slice::from_ref(publisher), rank)
.and_then(|core| core.verify_stored_data())
.map_err(|e| e.to_string())?;
Ok(())
}
pub struct Agent {
pub dir: AgentDir,
pub key: Key,
pub cache: PathBuf,
pub name: String,
/// Host-local Hugging Face cache from this agent's configuration; never from a controller.
hub_cache: Option<PathBuf>,
/// The executable running this agent, also used for serving unless RUN overrides it.
executable: PathBuf,
pins: Pins,
/// Groups started by this agent, oldest first; finished ones are retained up to a limit.
groups: Mutex<Vec<Arc<Group>>>,
verifier: Verifier,
gpus: Gpus,
/// The GPU inventory the sampler last read, with the Unix millisecond it was read.
sampled_gpus: Mutex<Option<(u64, Vec<Gpu>)>>,
#[cfg(test)]
fabric_endpoints: Option<Vec<u8>>,
}
/// How often the sampler reads GPUs and scrapes running rank-zero groups.
const SAMPLE_PERIOD: Duration = Duration::from_secs(1);
impl Agent {
pub fn new(dir: AgentDir, cache: PathBuf) -> Result<Self, Failure> {
Self::with_fakes(dir, cache, Box::new(verify_core), Box::new(gpu::enumerate))
}
/// An agent verifying fetched cores with `verifier` and enumerating GPUs with `gpus`
/// instead of Helios and NVML.
pub fn with_fakes(
dir: AgentDir,
cache: PathBuf,
verifier: Verifier,
gpus: Gpus,
) -> Result<Self, Failure> {
let key = dir.key()?;
for directory in ["bin", "publishers"] {
fs::create_dir_all(cache.join(directory))?;
}
fs::create_dir_all(cache::cores_directory(&cache))?;
Ok(Self {
dir,
key,
cache,
name: super::hostname(),
hub_cache: None,
executable: std::env::current_exe()?,
pins: Pins::default(),
groups: Mutex::new(Vec::new()),
verifier,
gpus,
sampled_gpus: Mutex::new(None),
#[cfg(test)]
fabric_endpoints: None,
})
}
/// Select the host-local Hugging Face cache from the agent process's own configuration.
fn with_hub_cache(mut self, hub_cache: Option<PathBuf>) -> Self {
self.hub_cache = hub_cache;
self
}
/// Read the GPUs and every running rank zero's metrics once.
pub fn sample(&self) {
if let Ok(gpus) = (self.gpus)() {
*self.sampled_gpus.lock().unwrap() = Some((now_millis(), gpus));
}
for group in self.groups().iter().filter(|g| g.running()) {
group.scrape();
}
}
/// The METRICS reply: the sampled GPUs with their holders, and every group with its latest
/// metrics document.
fn metrics(&self) -> Value {
let groups = self.groups();
let (gpus_at, gpus) = self
.sampled_gpus
.lock()
.unwrap()
.clone()
.unwrap_or((0, Vec::new()));
json!({
"at": now_millis(),
"gpus_at": gpus_at,
"gpus": gpus
.iter()
.map(|gpu| {
let holder = groups
.iter()
.find(|g| g.running() && g.gpus.contains(&gpu.uuid))
.map(|g| g.id.clone());
let mut value = serde_json::to_value(gpu).unwrap_or(Value::Null);
value["group"] = holder.into();
value
})
.collect::<Vec<_>>(),
"groups": groups
.iter()
.map(|g| {
let (metrics_at, metrics) = g
.metrics
.lock()
.unwrap()
.clone()
.map_or((Value::Null, Value::Null), |(at, m)| (at.into(), m));
json!({
"id": g.id,
"name": g.name,
"rank": g.rank,
"gpus": g.gpus,
"running": g.running(),
"exit": g.exit(),
"uptime_seconds": g.started.elapsed().as_secs(),
"metrics_at": metrics_at,
"metrics": metrics,
})
})
.collect::<Vec<_>>(),
})
}
pub fn hello(&self) -> Result<Hello, Failure> {
Ok(Hello {
version: PROTOCOL_VERSION,
kind: "node".into(),
name: self.name.clone(),
public_key: self.key.public().to_hex(),
controllers_revision: self.dir.controllers()?.map_or(0, |(_, set)| set.revision),
free_bytes: free_bytes(&self.cache),
executable: Some(self.executable.clone()),
download_progress: true,
})
}
fn is_controller(&self, key: &PublicKey) -> Result<bool, Failure> {
Ok(self
.dir
.controllers()?
.is_some_and(|(_, set)| set.contains(key)))
}
/// Verify a grant against this node's controllers.
fn grant(&self, signed: &Value) -> Result<Grant, Failure> {
let signed: Signed = serde_json::from_value(signed.clone())?;
let Some((_, set)) = self.dir.controllers()? else {
return Err("this node is not paired with any controller".into());
};
let grant: Grant = signed.verify(|k| set.contains(k))?;
if grant.members.is_empty() || grant.core.files.is_empty() {
return Err("grant names no members or files".into());
}
Ok(grant)
}
fn groups(&self) -> Vec<Arc<Group>> {
let mut groups = self.groups.lock().unwrap();
// The sampler calls this even when no controller is connected or launching work.
prune_groups(&mut groups, Instant::now());
groups.clone()
}
/// The group a request names, or the only group when it names none.
fn find_group(&self, id: Option<&str>) -> Result<Arc<Group>, Failure> {
let groups = self.groups();
match id {
Some(id) => groups
.iter()
.find(|g| g.id == id)
.cloned()
.ok_or_else(|| format!("group {id} is not on this node").into()),
None => match groups.as_slice() {
[] => Err("no group has run on this node".into()),
[only] => Ok(only.clone()),
several => Err(format!(
"several groups are on this node; name one: {}",
several
.iter()
.map(|g| g.id.as_str())
.collect::<Vec<_>>()
.join(", ")
)
.into()),
},
}
}
/// Core cache directories with their files and verification state.
fn cores(&self) -> Vec<Value> {
use std::os::unix::fs::MetadataExt;
let mut cores = Vec::new();
let Ok(entries) = fs::read_dir(cache::cores_directory(&self.cache)) else {
return cores;
};
let mut directories: Vec<PathBuf> = entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| {
p.is_dir()
&& !p
.file_name()
.is_none_or(|n| n.to_string_lossy().starts_with('.'))
})
.collect();
directories.sort();
for directory in directories {
let mut files = Vec::new();
let mut bytes = 0u64;
if let Ok(entries) = fs::read_dir(&directory) {
let mut names: Vec<PathBuf> =
entries.filter_map(|e| e.ok().map(|e| e.path())).collect();
names.sort();
for path in names {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let Ok(metadata) = fs::metadata(&path) else {
continue;
};
bytes += metadata.blocks() * 512;
if !name.starts_with('.') {
files.push(json!({"name": name, "size": metadata.len()}));
}
}
}
cores.push(json!({
"name": directory.file_name().unwrap().to_string_lossy(),
"files": files,
"verified": directory.join(VERIFIED).is_file(),
"bytes": bytes,
}));
}
cores
}
}
/// Serve sessions on `listen` until killed.
pub fn serve(
listen: &str,
dir: AgentDir,
cache: PathBuf,
hub_cache: PathBuf,
) -> Result<(), Failure> {
let listener =
TcpListener::bind(listen).map_err(|e| format!("cannot listen on {listen}: {e}"))?;
let agent = Arc::new(Agent::new(dir, cache)?.with_hub_cache(Some(hub_cache)));
eprintln!(
"flare agent {} ({}) listening on {}; cache {}; {}",
agent.name,
agent.key.public().fingerprint(),
listener.local_addr()?,
agent.cache.display(),
match agent.dir.controllers()? {
Some((_, set)) => format!("controller set revision {}", set.revision),
None => "unpaired".to_owned(),
}
);
serve_on(listener, agent)
}
pub fn serve_on(listener: TcpListener, agent: Arc<Agent>) -> Result<(), Failure> {
{
let agent = agent.clone();
thread::spawn(move || {
loop {
agent.sample();
thread::sleep(SAMPLE_PERIOD);
}
});
}
for connection in listener.incoming() {
let Ok(stream) = connection else { continue };
let agent = agent.clone();
thread::spawn(move || {
let peer = stream
.peer_addr()
.map(|a| a.to_string())
.unwrap_or_default();
if let Err(error) = session(&agent, stream) {
eprintln!("{peer}: {error}");
}
});
}
Ok(())
}
fn session(agent: &Arc<Agent>, stream: TcpStream) -> Result<(), Failure> {
let mut session = Session::accept(stream, &agent.key)?;
let hello = exchange_hello(&mut session, &agent.hello()?)?;
let mut pinned = Pinned::new(&agent.pins);
// Downloads stay leased for this controller session, which is the window in
// which its transfers read those entries, and drop when the session ends.
let mut downloads: Vec<flare_helios::core::cache::Entry> = Vec::new();
loop {
let (tag, length) = match session.read_header() {
Ok(header) => header,
Err(_) => return Ok(()),
};
let authorized = agent.is_controller(&session.remote())?;
let result = match tag {
frame::PAIR => {
let request = json_body(&mut session, length)?;
pair(agent, &mut session, &hello, &request)
}
frame::FETCH => {
let request = json_body(&mut session, length)?;
match fetch(agent, &mut session, &mut pinned, &request) {
Ok(()) => continue,
Err(error) => Err(error),
}
}
frame::FETCH_FABRIC => {
let request = json_body(&mut session, length)?;
match fetch_fabric(agent, &mut session, &mut pinned, &request) {
Ok(()) => continue,
Err(error) => Err(error),
}
}
_ if !authorized => Err(format!(
"{} is not an authorized controller of this node",
session.remote().fingerprint()
)
.into()),
frame::CONTROLLERS => {
let record: Signed = serde_json::from_value(json_body(&mut session, length)?)?;
agent
.dir
.apply_controllers(&record)
.map(|set| json!({"revision": set.revision}).to_string().into_bytes())
}
frame::HAVE => {
let request = json_body(&mut session, length)?;
have(agent, &mut pinned, &request)
}
frame::PUT => put(agent, &mut session, &mut pinned, length),
frame::TRANSFER => {
let request = json_body(&mut session, length)?;
transfer(agent, &mut pinned, &request)
}
frame::RUN | frame::ATTACH => {
let request = json_body(&mut session, length)?;
let started = if tag == frame::RUN {
run(agent, &request)
} else {
attach(agent, &request)
};
match started {
Ok(group) => {
session.ok(json!({"pid": group.pid, "group": group.id})
.to_string()
.as_bytes())?;
return stream_group(&mut session, &group);
}
Err(error) => Err(error),
}
}
frame::STOP => {
let request = json_body(&mut session, length)?;
stop(agent, &request)
}
frame::REMOVE => {
let request = json_body(&mut session, length)?;
remove(agent, &request)
}
frame::STATUS => {
let request = json_body(&mut session, length)?;
status(agent, &request)
}
frame::FABRIC => {
session.read_body(length, FRAME_LIMIT)?;
#[cfg(test)]
if let Some(endpoints) = &agent.fabric_endpoints {
session.ok(endpoints)?;
continue;
}
super::fabric::discover()
}
frame::METRICS => {
session.read_body(length, FRAME_LIMIT)?;
Ok(agent.metrics().to_string().into_bytes())
}
frame::GET => {
let request = json_body(&mut session, length)?;
match get(&mut session, &request) {
Ok(()) => continue,
Err(error) => Err(error),
}
}
frame::STAT => {
let request = json_body(&mut session, length)?;
stat(&request)
}
frame::DOWNLOAD => {
let mut request: DownloadRequest =
serde_json::from_value(json_body(&mut session, length)?)?;
request.options =
node_download_options(agent.hub_cache.as_deref(), request.options);
if hello.download_progress {
let storage = storage_estimate(&request.options);
let counters = flare_helios::core::progress::AcquisitionProgress::new();
let observed = counters.clone();
let result = watch_download(
&observed,
move || download(request, Some(counters)),
|snapshot| {
let body = json!({
"downloaded": snapshot.network_bytes,
"total": snapshot.network_total,
"verified": snapshot.verification_bytes,
"storage": storage,
});
session
.write_frame(frame::DOWNLOAD_PROGRESS, &serde_json::to_vec(&body)?)
},
);
match result {
Ok((reply, entry)) => {
let mut reply: Value = serde_json::from_slice(&reply)?;
let snapshot = observed.snapshot();
reply["downloaded"] = snapshot.network_bytes.into();
reply["total"] = snapshot.network_total.into();
reply["verified"] = snapshot.verification_bytes.into();
reply["storage"] = serde_json::to_value(storage)?;
downloads.push(entry);
Ok(serde_json::to_vec(&reply)?)
}
Err(error) => Err(error),
}
} else {
match download(request, None) {
Ok((reply, entry)) => {
downloads.push(entry);
Ok(reply)
}
Err(error) => Err(error),
}
}
}
_ => Err(format!("unknown request {tag}").into()),
};
match result {
Ok(reply) => session.ok(&reply)?,
Err(error) => {
session.error(&error.to_string())?;
return Err(error);
}
}
}
}
fn constant_time_equal(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0, |d, (x, y)| d | (x ^ y)) == 0
}
fn pair(
agent: &Agent,
session: &mut Session,
hello: &Hello,
request: &Value,
) -> Result<Vec<u8>, Failure> {
if agent.dir.controllers()?.is_some() {
return Err("this node is paired; add controllers with `flare orbit controllers add` or run `flare agent reset` on it".into());
}
let record: Signed = serde_json::from_value(request["controllers"].clone())
.map_err(|_| "pairing needs the controller-set record")?;
if record.signer()? != session.remote() {
return Err("the controller-set record must be signed by the pairing controller".into());
}
let mut reply = json!({
"name": agent.name,
"public_key": agent.key.public().to_hex(),
"fingerprint": agent.key.public().fingerprint(),
});
let hash = *session.handshake_hash();
match (agent.dir.join_code()?, request["proof"].as_str()) {
(Some(code), Some(proof)) => {
let expected = hmac_sha256(&code.key, &[b"controller".as_slice(), &hash].concat());
if !constant_time_equal(&super::unhex(proof)?, &expected) {
return Err("join code proof rejected".into());
}
let set = agent.dir.apply_controllers(&record)?;
agent.dir.consume_join_code()?;
agent.dir.clear_accept_first();
reply["proof"] = hex(&hmac_sha256(
&code.key,
&[b"node".as_slice(), &hash].concat(),
))
.into();
reply["revision"] = set.revision.into();
}
_ if agent.dir.accept_first() => {
let set = agent.dir.apply_controllers(&record)?;
agent.dir.clear_accept_first();
agent.dir.consume_join_code()?;
reply["revision"] = set.revision.into();
}
(Some(_), None) => return Err("this node requires its join code".into()),
(None, _) => {
return Err(
"this node accepts no pairing: install it with a join code or --accept-first"
.into(),
);
}
}
eprintln!(
"paired with controller {} ({})",
hello.name,
session.remote().fingerprint()
);
Ok(reply.to_string().into_bytes())
}
fn have(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result<Vec<u8>, Failure> {
let size = request["size"].as_u64().ok_or("request lacks size")?;
let held = cache::have(
&agent.cache,
field(request, "kind")?,
field(request, "name")?,
size,
)?;
if let Some(path) = &held {
pinned.pin(cache::unit(&agent.cache, path));
}
Ok(vec![held.is_some() as u8])
}
fn put(
agent: &Agent,
session: &mut Session,
pinned: &mut Pinned,
length: u64,
) -> Result<Vec<u8>, Failure> {
let mut body = session.body();
let mut prefix = [0u8; 4];
body.read_exact(&mut prefix)?;
let header_length = u32::from_le_bytes(prefix) as usize;
if header_length as u64 + 4 > length || header_length > FRAME_LIMIT as usize {
return Err("invalid PUT header".into());
}
let mut header = vec![0u8; header_length];
body.read_exact(&mut header)?;
let request: Value = serde_json::from_slice(&header)?;
let kind = field(&request, "kind")?;
let name = field(&request, "name")?;
let size = request["size"].as_u64().ok_or("request lacks size")?;
let ranges = cache::ranges_from_json(size, request.get("ranges"))?;
if cache::range_bytes(&ranges) + 4 + header_length as u64 != length {
return Err("PUT length does not match its ranges".into());
}
let entry = cache::entry(&agent.cache, cache::kind_directory(kind)?, name)?;
let _lease = cache::Lease::write(&cache::unit(&agent.cache, &entry))?;
let path = cache::store(&agent.cache, kind, name, size, &ranges, &mut body)?;
let unit = cache::unit(&agent.cache, &path);
if matches!(kind, "core" | "package") {
let _ = fs::remove_file(unit.join(VERIFIED));
}
pinned.pin(unit.clone());
for removed in cache::evict(unit.parent().unwrap(), &agent.pins)? {
eprintln!("removed superseded {}", removed.display());
}
Ok(Vec::new())
}
/// Fetch the files of a core from another node under a grant into the cache.
fn transfer(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result<Vec<u8>, Failure> {
let grant = agent.grant(&request["grant"])?;
let rank = grant
.member(&agent.key.public())
.map(|m| m.rank)
.ok_or("this node is not a member of the grant")?;
let publisher: Publisher = serde_json::from_value(request["publisher"].clone())
.map_err(|_| "TRANSFER lacks the publisher profile")?;
publisher.validate().map_err(|e| e.to_string())?;
let source_key = PublicKey::from_hex(field(&request["source"], "public_key")?)?;
let address = field(&request["source"], "address")?;
let directory = field(request, "directory")?;
let files = request["files"].as_array().ok_or("request lacks files")?;
let primary = cache::entry(
&agent.cache,
"cores",