-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmanager.rs
More file actions
1472 lines (1292 loc) · 54.1 KB
/
Copy pathmanager.rs
File metadata and controls
1472 lines (1292 loc) · 54.1 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
use std::{
collections::{BTreeMap, BTreeSet},
io::Write,
sync::{Arc, RwLock},
time::{Instant, SystemTime},
};
use anyhow::{anyhow, Context as _};
use backoff::backoff::Backoff;
use base64::{prelude::BASE64_STANDARD, Engine};
use bytes::BufMut;
use futures_util::StreamExt;
use oasis_runtime_sdk::{
core::{
common::{
crypto::{hash::Hash, signature::PublicKey},
logger::get_logger,
process,
},
host::{bundle_manager, volume_manager},
},
modules::rofl::app::prelude::*,
types::address::Address,
};
use oasis_runtime_sdk_rofl_market::{
self as market,
policy::{ProviderLabel, LABEL_PROVIDER},
types::{Deployment, Instance, InstanceId, InstanceStatus},
};
use rand::Rng;
use sha2::{Digest, Sha512_256};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
time,
};
use tokio_util::compat::FuturesAsyncWriteCompatExt;
use super::{
client::{MarketClient, MarketQueryClient},
config::{LocalConfig, Resources},
manifest::{self, Manifest},
qcow2, types, SchedulerApp,
};
/// Metadata key used to configure the offer identifier.
const METADATA_KEY_OFFER: &str = "net.oasis.scheduler.offer";
/// Metadata key used to configure the deployment ORC bundle location.
const METADATA_KEY_DEPLOYMENT_ORC_REF: &str = "net.oasis.deployment.orc.ref";
/// Metadata key used to report errors.
const METADATA_KEY_ERROR: &str = "net.oasis.error";
/// Maximum length of the error message.
const METADATA_VALUE_ERROR_MAX_SIZE: usize = 1024;
/// Metadata key used to store the scheduler instance RAK.
const METADATA_KEY_SCHEDULER_RAK: &str = "net.oasis.scheduler.rak";
/// Name of the label used to store the deployment hash.
const LABEL_DEPLOYMENT_HASH: &str = "net.oasis.scheduler.deployment_hash";
/// Name of the label used to store the volume name.
const LABEL_VOLUME_NAME: &str = "net.oasis.scheduler.volume.name";
/// OCI media type for ORC config descriptors.
const OCI_TYPE_ORC_CONFIG: &str = "application/vnd.oasis.orc.config.v1+json";
/// OCI media type for ORC layer descriptors.
const OCI_TYPE_ORC_LAYER: &str = "application/vnd.oasis.orc.layer.v1";
/// Average number of seconds after which to remove instances that are not accepted. The scheduler
/// will randomize the value to minimize the chance of multiple schedulers removing at once.
const REMOVE_INSTANCE_AFTER_SECS: u64 = 1800;
/// Maximum size of the JSON-encoded ORC manifest.
const MAX_ORC_MANIFEST_SIZE: i64 = 16 * 1024; // 16 KiB
/// Maximum size of an ORC layer.
const MAX_ORC_LAYER_SIZE: i64 = 128 * 1024 * 1024; // 128 MiB
/// Maximum size of all ORC layers.
const MAX_ORC_TOTAL_SIZE: i64 = 128 * 1024 * 1024; // 128 MiB
/// OCI client read timeout in seconds.
const OCI_CLIENT_READ_TIMEOUT_SECS: u64 = 5;
/// OCI client connect timeout in seconds.
const OCI_CLIENT_CONNECT_TIMEOUT_SECS: u64 = 5;
/// OCI client manifest and config pull timeout in seconds.
const OCI_CLIENT_PULL_MANIFEST_TIMEOUT_SECS: u64 = 5;
#[derive(Clone, Default)]
struct InstanceUpdates {
complete_cmds: Option<market::types::CommandId>,
deployment: Option<Option<market::types::Deployment>>,
metadata: Option<BTreeMap<String, String>>,
node_id: Option<PublicKey>,
}
impl InstanceUpdates {
/// Whether there are any updates set.
fn has_updates(&self) -> bool {
self.complete_cmds.is_some()
|| self.deployment.is_some()
|| self.metadata.is_some()
|| self.node_id.is_some()
}
}
struct LocalState {
/// Market query client instance for a specific round.
client: Arc<MarketQueryClient>,
/// A map of all accepted instances.
accepted: BTreeMap<InstanceId, Instance>,
/// A list of our bundles running locally.
running: BTreeMap<InstanceId, bundle_manager::BundleInfo>,
/// A list of deployments that should already be running but are not.
pending_start: Vec<(Instance, Deployment, bool)>,
/// A list of instance identifiers that should have no running deployments.
pending_stop: Vec<(InstanceId, bool)>,
/// A map of instance updates.
instance_updates: BTreeMap<InstanceId, InstanceUpdates>,
/// A list of instance identifiers that should be accepted.
accept: Vec<InstanceId>,
/// A list of not-accepted instance identifiers and timestamps that should maybe be removed.
maybe_remove: Vec<(InstanceId, u64)>,
/// A list of instances to claim payment for.
claim_payment: Vec<InstanceId>,
/// Amounts of resources used.
resources_used: Resources,
}
/// Instance state.
#[derive(Default, Debug, Clone)]
pub struct InstanceState {
/// Address of the instance administrator.
admin: Address,
/// Last deployment.
last_deployment: Option<Deployment>,
/// Last error message corresponding to deploying `last_deployment`.
last_error: Option<String>,
// Whether to ignore instance start until the given time elapses.
ignore_start_until: Option<Instant>,
/// Backoff associated with ignoring instance start.
ignore_start_backoff: Option<backoff::ExponentialBackoff>,
}
impl InstanceState {
/// Address of the instance administrator.
pub fn admin(&self) -> &Address {
&self.admin
}
}
struct DeploymentInfo {
temporary_name: String,
manifest_hash: Hash,
volumes: Vec<String>,
}
/// Instance manager.
pub struct Manager {
env: Environment<SchedulerApp>,
client: Arc<MarketClient>,
cfg: Arc<LocalConfig>,
instances: RwLock<BTreeMap<InstanceId, InstanceState>>,
logger: slog::Logger,
}
impl Manager {
/// Create a new manager instance.
pub fn new(env: Environment<SchedulerApp>, cfg: Arc<LocalConfig>) -> Arc<Self> {
Arc::new(Self {
client: Arc::new(MarketClient::new(env.clone(), cfg.provider_address)),
env,
cfg,
instances: RwLock::new(BTreeMap::new()),
logger: get_logger("scheduler/manager"),
})
}
/// Find an instance state with the given identifier and return a copy.
pub fn get_instance(&self, instance_id: &InstanceId) -> Option<InstanceState> {
let instances = self.instances.read().unwrap();
instances.get(instance_id).cloned()
}
/// Main loop of the ROFL scheduler.
pub async fn run(self: Arc<Self>) {
let local_node_id = match self.env.host().identity().await {
Ok(local_node_id) => local_node_id,
Err(err) => {
slog::error!(self.logger, "failed to determine local node ID";
"err" => ?err,
);
process::abort();
}
};
let mut last_round = 0;
loop {
// Wait a bit before doing another pass.
time::sleep(time::Duration::from_secs(self.cfg.processing_interval_secs)).await;
// Discover local state.
let mut local_state = match self.discover(local_node_id).await {
Ok(local_state) => local_state,
Err(err) => {
slog::error!(self.logger, "failed to discover bundles"; "err" => ?err);
continue;
}
};
// Make sure to not re-process the same round multiple times.
if local_state.client.round() <= last_round {
continue;
}
// Process any pending instances.
if let Err(err) = self.process_pending(local_node_id, &mut local_state).await {
slog::error!(self.logger, "failed to process pending instances"; "err" => ?err);
continue;
}
slog::info!(self.logger, "instance status";
"accepted" => local_state.accepted.len(),
"running" => local_state.running.len(),
"pending_start" => local_state.pending_start.len(),
"pending_stop" => local_state.pending_stop.len(),
"instance_updates" => local_state.instance_updates.len(),
"maybe_remove" => local_state.maybe_remove.len(),
"claim_payment" => local_state.claim_payment.len(),
"resources_used" => ?local_state.resources_used,
);
// Spawn tasks to process all jobs.
if let Err(err) = self.process_jobs(&mut local_state).await {
slog::error!(self.logger, "failed to process jobs"; "err" => ?err);
continue;
}
last_round = local_state.client.round();
}
}
/// Discover local state.
async fn discover(&self, local_node_id: PublicKey) -> Result<LocalState> {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
// Encode scheduler RAK so we can set it in metadata.
let scheduler_rak = BASE64_STANDARD.encode(self.env.identity().public_rak().as_ref());
let client = self.client.queries_at_latest().await?;
let mut local_state = LocalState {
client,
accepted: BTreeMap::new(),
running: BTreeMap::new(),
pending_start: Vec::new(),
pending_stop: Vec::new(),
instance_updates: BTreeMap::new(),
accept: Vec::new(),
maybe_remove: Vec::new(),
claim_payment: Vec::new(),
resources_used: Default::default(),
};
// Discover local volumes.
let rsp = self
.env
.host()
.volume_manager()
.volume_list(volume_manager::VolumeListRequest {
labels: BTreeMap::new(), // We want all our volumes.
})
.await?;
let volumes = rsp.volumes.into_iter().filter_map(|bi| {
// Skip volumes with malformed labels.
let instance_id: InstanceId = bi
.labels
.get(bundle_manager::LABEL_INSTANCE_ID)?
.parse()
.ok()?;
Some(instance_id)
});
// Discover local bundles.
let rsp = self
.env
.host()
.bundle_manager()
.bundle_list(bundle_manager::BundleListRequest {
labels: BTreeMap::new(), // We want all our bundles.
})
.await?;
local_state.running = rsp
.bundles
.into_iter()
.filter_map(|bi| {
// Skip bundles with malformed labels.
let instance_id: InstanceId = bi
.labels
.get(bundle_manager::LABEL_INSTANCE_ID)?
.parse()
.ok()?;
Some((instance_id, bi))
})
.collect();
let mut running_unknown =
BTreeSet::from_iter(local_state.running.keys().copied().chain(volumes));
// Discover desired instance state.
let instances: Vec<Instance> = local_state.client.instances().await?;
for instance in instances {
match instance.status {
InstanceStatus::Created => {
// Instance has not yet been accepted, nothing to do.
continue;
}
InstanceStatus::Cancelled => {
// Instance has been cancelled.
local_state
.maybe_remove
.push((instance.id, instance.updated_at));
continue;
}
InstanceStatus::Accepted => {
// Instance has been accepted, check if we should be hosting it.
// NOTE: Safe to unwrap as all accepted instances must have a node set.
if instance.node_id.unwrap() != local_node_id {
continue;
}
}
}
// Remove known instances. Any remaining unknown instances will be stopped.
running_unknown.remove(&instance.id);
// Check if the instance is still paid for. If not, we immediately stop it and schedule
// its removal.
if instance.paid_until < now {
slog::info!(self.logger, "instance not paid for, stopping";
"id" => ?instance.id,
);
if local_state.running.contains_key(&instance.id) {
local_state.pending_stop.push((instance.id, true));
}
local_state
.maybe_remove
.push((instance.id, instance.paid_until));
continue;
}
local_state.accepted.insert(instance.id, instance.clone());
// Update administrator address.
{
let mut instances = self.instances.write().unwrap();
instances.entry(instance.id).or_default().admin = instance.admin;
}
// Compute total provisioned resources.
local_state.resources_used = local_state.resources_used.add(&instance.resources);
// Discover any pending commands to see if there is a "deploy" command somewhere in
// there. This allows us to immediately deploy the right thing instead of first
// deploying an old version and then immediately upgrading.
let cmds = local_state.client.instance_commands(instance.id).await?;
// Derive the desired instance state.
let mut wipe_storage = false;
let mut force_restart = false;
let mut last_processed_cmd = Default::default();
let mut desired = instance.deployment.clone();
for qc in &cmds {
last_processed_cmd = qc.id;
let cmd = match cbor::from_slice::<types::Command>(&qc.cmd) {
Ok(cmd) => cmd,
Err(_) => continue,
};
match cmd.method.as_str() {
types::METHOD_DEPLOY => {
match cbor::from_value::<types::DeployRequest>(cmd.args) {
Ok(deploy) => {
desired = Some(deploy.deployment);
wipe_storage = wipe_storage || deploy.wipe_storage;
}
Err(_) => continue,
}
}
types::METHOD_TERMINATE => {
match cbor::from_value::<types::TerminateRequest>(cmd.args) {
Ok(terminate) => {
desired = None;
wipe_storage = wipe_storage || terminate.wipe_storage;
}
Err(_) => continue,
}
}
types::METHOD_RESTART => {
match cbor::from_value::<types::RestartRequest>(cmd.args) {
Ok(restart) => {
wipe_storage = wipe_storage || restart.wipe_storage;
force_restart = true;
}
Err(_) => continue,
}
}
_ => continue,
}
}
if !cmds.is_empty() {
local_state
.instance_updates
.entry(instance.id)
.or_default()
.complete_cmds = Some(last_processed_cmd);
}
// Make sure that metadata is updated after processing all the commands.
if instance.deployment != desired {
local_state
.instance_updates
.entry(instance.id)
.or_default()
.deployment = Some(desired.clone());
}
// Make sure that scheduler RAK is set to the correct value.
if instance.metadata.get(METADATA_KEY_SCHEDULER_RAK) != Some(&scheduler_rak) {
local_state
.instance_updates
.entry(instance.id)
.or_default()
.metadata
.get_or_insert_default()
.insert(
METADATA_KEY_SCHEDULER_RAK.to_string(),
scheduler_rak.clone(),
);
}
// If the instance has been running for a while, make sure to claim payment. Use a fuzzy
// interval to distribute claims a bit.
let timeout = rand::distributions::Uniform::new(75, 125);
let payment_interval =
(self.cfg.claim_payment_interval_secs * rand::thread_rng().sample(timeout)) / 100;
if now > instance.paid_from.saturating_add(payment_interval) {
local_state.claim_payment.push(instance.id);
}
let actual = local_state.running.get(&instance.id);
match (actual, desired) {
(Some(actual), Some(desired)) => {
// Instance is running and should be running. Determine whether it is running
// the correct deployment by comparing its hash.
let actual_hash = actual
.labels
.get(LABEL_DEPLOYMENT_HASH)
.cloned()
.unwrap_or_default();
let desired_hash = deployment_hash(&desired);
if actual_hash != desired_hash || force_restart {
// Note that any old instances will be restarted in case they are already
// running and we add them to `pending_start`.
local_state
.pending_start
.push((instance, desired, wipe_storage));
}
}
(None, Some(desired)) => {
// Instance is not running and should be started.
local_state
.pending_start
.push((instance, desired, wipe_storage));
}
(Some(_), None) => {
// Instance is running and should be stopped.
local_state.pending_stop.push((instance.id, wipe_storage));
}
(None, None) => {
// Instance is not running and should be stopped. Nothing to do.
}
}
}
// Stop any unknown instances.
for instance_id in running_unknown {
slog::info!(self.logger, "stopping unknown instance";
"id" => ?instance_id,
);
local_state.pending_stop.push((instance_id, true));
}
slog::info!(self.logger, "discovered instances";
"accepted" => local_state.accepted.len(),
"running" => local_state.running.len(),
"pending_start" => local_state.pending_start.len(),
"pending_stop" => local_state.pending_stop.len(),
"instance_updates" => local_state.instance_updates.len(),
"maybe_remove" => local_state.maybe_remove.len(),
"claim_payment" => local_state.claim_payment.len(),
"resources_used" => ?local_state.resources_used,
);
Ok(local_state)
}
/// Process pending instances.
async fn process_pending(
self: &Arc<Self>,
local_node_id: PublicKey,
local_state: &mut LocalState,
) -> Result<()> {
let offers = local_state.client.offers().await?;
let instances = local_state.client.instances().await?;
let acceptable_offers: BTreeSet<market::types::OfferId> = offers
.into_iter()
.filter_map(|offer| {
let offer_key = offer.metadata.get(METADATA_KEY_OFFER)?;
if self.cfg.offers.is_empty() || self.cfg.offers.contains(offer_key) {
Some(offer.id)
} else {
None
}
})
.collect();
for instance in instances {
let mut transfer_instance = false;
match instance.status {
InstanceStatus::Created => {}
InstanceStatus::Accepted => {
// If the instance has already been accepted, check if we are not the owning
// node but we should transfer from it.
// NOTE: Safe to unwrap as all accepted instances must have a node set.
let owning_node = instance.node_id.unwrap();
if owning_node == local_node_id {
continue;
}
if !self.cfg.should_transfer_instance_from(&owning_node) {
continue;
}
transfer_instance = true;
}
_ => continue,
}
let mut maybe_remove = || {
if transfer_instance {
return;
}
local_state
.maybe_remove
.push((instance.id, instance.created_at))
};
slog::info!(self.logger, "evaluating instance";
"id" => ?instance.id,
"status" => ?instance.status,
"transfer" => transfer_instance,
);
// Check if creator is among the allowed creators.
if !self.cfg.is_creator_allowed(&instance.creator) {
slog::info!(self.logger, "creator not allowed";
"id" => ?instance.id,
"creator" => instance.creator,
"transfer" => transfer_instance,
);
maybe_remove();
continue;
}
// Check if offer is among the configured offers.
if !acceptable_offers.contains(&instance.offer) {
slog::info!(self.logger, "offer not acceptable for this instance";
"id" => ?instance.id,
"offer" => ?instance.offer,
"transfer" => transfer_instance,
);
maybe_remove();
continue;
}
// Check if we have enough local capacity.
let new_resource_use = local_state.resources_used.add(&instance.resources);
if !self.cfg.capacity.can_allocate(&new_resource_use) {
slog::info!(self.logger, "no more capacity for offer";
"id" => ?instance.id,
"offer" => ?instance.offer,
"transfer" => transfer_instance,
);
maybe_remove();
continue;
}
slog::info!(self.logger, "instance seems acceptable";
"id" => ?instance.id,
"offer" => ?instance.offer,
"transfer" => transfer_instance,
);
// Instance seems acceptable.
local_state.accept.push(instance.id);
local_state.accepted.insert(instance.id, instance.clone());
local_state.resources_used = new_resource_use;
// When transfering instances, queue a job to update their node ID.
if transfer_instance {
local_state
.instance_updates
.entry(instance.id)
.or_default()
.node_id = Some(local_node_id);
}
}
Ok(())
}
/// Process queued jobs.
async fn process_jobs(self: &Arc<Self>, local_state: &mut LocalState) -> Result<()> {
// Prepare job to accept instances.
let accept_jobs: Vec<_> = local_state
.accept
.chunks(16)
.map(|ids| self.clone().accept_instances(ids.to_vec()))
.collect();
// Prepare jobs to remove instances.
let remove_jobs: Vec<_> = local_state
.maybe_remove
.iter()
.map(|(id, ts)| self.clone().maybe_remove_instance(*id, *ts))
.collect();
// Prepare jobs to start instances.
let start_jobs: Vec<_> = local_state
.pending_start
.iter()
.map(|(instance, deployment, wipe_storage)| {
self.clone()
.start_instance(instance.clone(), deployment.clone(), *wipe_storage)
})
.collect();
// Prepare jobs to stop instances.
let stop_jobs: Vec<_> = local_state
.pending_stop
.iter()
.map(|(id, wipe_storage)| self.clone().stop_instance(*id, *wipe_storage))
.collect();
// Prepare jobs to claim payments.
let claim_payment_jobs: Vec<_> = local_state
.claim_payment
.chunks(16)
.map(|chunk| self.clone().claim_payment(chunk.to_vec()))
.collect();
// Execute all jobs in parallel.
let mut jobs = tokio::task::JoinSet::new();
for job in accept_jobs {
jobs.spawn(job);
}
for job in remove_jobs {
jobs.spawn(job);
}
for job in start_jobs {
jobs.spawn(job);
}
for job in stop_jobs {
jobs.spawn(job);
}
for job in claim_payment_jobs {
jobs.spawn(job);
}
slog::info!(self.logger, "running jobs"; "num_jobs" => jobs.len());
while let Some(result) = jobs.join_next().await {
match result {
Err(err) => {
slog::error!(self.logger, "task panicked"; "err" => ?err);
}
Ok(Err(err)) => {
slog::error!(self.logger, "task failed"; "err" => ?err);
}
Ok(Ok(_)) => {
// Ok.
}
}
}
slog::info!(self.logger, "running instance update jobs");
// After all instance jobs have completed, collect additional instance update jobs as those
// depend on last instance status.
let mut jobs = self.collect_instance_update_jobs(local_state);
while let Some(result) = jobs.join_next().await {
match result {
Err(err) => {
slog::error!(self.logger, "instance update task panicked"; "err" => ?err);
}
Ok(Err(err)) => {
slog::error!(self.logger, "instance update task failed"; "err" => ?err);
}
Ok(Ok(_)) => {
// Ok.
}
}
}
slog::info!(self.logger, "all jobs completed");
Ok(())
}
/// Inspect all instances and generate jobs to update their metadata.
fn collect_instance_update_jobs(
self: &Arc<Self>,
local_state: &mut LocalState,
) -> tokio::task::JoinSet<Result<()>> {
let instances = self.instances.read().unwrap();
// Determine the set of instances that need to be updated. These are either ones that have
// been explicitly requested by earlier phases or any that have errors set due to job
// processing.
let relevant_instances: BTreeSet<_> = local_state
.instance_updates
.keys()
.copied()
.chain(instances.keys().copied())
.collect();
// Iterate through all updates and fill in any unchanged fields from instances.
const CHUNK_SIZE: usize = 16;
let mut tasks = tokio::task::JoinSet::new();
let mut chunk = Vec::with_capacity(CHUNK_SIZE);
let mut spawn_task_chunk = |chunk: &mut Vec<_>| {
let chunk = std::mem::replace(chunk, Vec::with_capacity(CHUNK_SIZE));
tasks.spawn(self.clone().update_instance_metadata(chunk));
};
for instance_id in relevant_instances {
let instance = match local_state.accepted.get(&instance_id) {
Some(instance) => instance,
None => continue, // Skip any instances that no longer exist.
};
let state = instances.get(&instance_id);
let mut updates = local_state
.instance_updates
.remove(&instance_id)
.unwrap_or_default();
if updates.metadata.is_none() {
updates.metadata = Some(instance.metadata.clone());
}
// Set last error metadata entry.
if let Some(mut error) = state.and_then(|s| s.last_error.clone()) {
error.truncate(METADATA_VALUE_ERROR_MAX_SIZE);
updates
.metadata
.as_mut()
.unwrap()
.insert(METADATA_KEY_ERROR.to_string(), error);
} else {
updates
.metadata
.as_mut()
.unwrap()
.remove(METADATA_KEY_ERROR);
}
// If metadata would not change, do not update it.
if updates.metadata.as_ref().unwrap() == &instance.metadata {
updates.metadata = None;
}
// Skip updates that don't change anything.
if !updates.has_updates() {
continue;
}
chunk.push((instance.id, updates));
if chunk.len() >= chunk.capacity() {
spawn_task_chunk(&mut chunk);
}
}
if !chunk.is_empty() {
spawn_task_chunk(&mut chunk);
}
tasks
}
/// Accept the given instances.
async fn accept_instances(self: Arc<Self>, ids: Vec<InstanceId>) -> Result<()> {
self.client.accept_instances(ids, BTreeMap::new()).await
}
/// Maybe remove the given instances.
async fn maybe_remove_instance(self: Arc<Self>, instance: InstanceId, ts: u64) -> Result<()> {
// Determine whether the instance should be removed. We use a randomized interval to
// minimize the chance of multiple schedulers removing the same instances.
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
let timeout = rand::distributions::Uniform::new(75, 125);
let max_delta = (REMOVE_INSTANCE_AFTER_SECS * rand::thread_rng().sample(timeout)) / 100;
if now.saturating_sub(ts) < max_delta {
return Ok(());
}
// XXX: Temporarily skip instances that cannot be removed due to a claim bug.
let info = self
.client
.queries_at_latest()
.await?
.instance(instance)
.await?;
if info.paid_until == info.paid_from {
return Ok(());
}
self.client.remove_instance(instance).await?;
let mut instances = self.instances.write().unwrap();
instances.remove(&instance);
Ok(())
}
/// Start the given instance with the provided deployment.
async fn start_instance(
self: Arc<Self>,
instance: Instance,
deployment: Deployment,
wipe_storage: bool,
) -> Result<()> {
if !self.should_start_instance(instance.id, &deployment) {
return Ok(());
}
// Remove any existing bundles for this instance.
self.clone()
.stop_instance(instance.id, wipe_storage)
.await
.context("failed to stop existing instance")?;
self.set_last_instance_deployment(instance.id, &deployment);
match self.pull_and_deploy_instance(&instance, &deployment).await {
Ok(_) => {
self.allow_instance_start(instance.id);
Ok(())
}
Err(err) => {
slog::error!(self.logger, "failed to deploy instance";
"id" => ?instance.id,
"err" => ?err,
);
self.ignore_instance_start(instance.id, err.to_string());
Err(err)
}
}
}
fn set_last_instance_deployment(&self, instance_id: InstanceId, deployment: &Deployment) {
let mut instances = self.instances.write().unwrap();
let state = instances.entry(instance_id).or_default();
state.last_deployment = Some(deployment.clone());
state.last_error = None;
}
fn ignore_instance_start(&self, instance_id: InstanceId, reason: String) {
let mut instances = self.instances.write().unwrap();
let state = instances.entry(instance_id).or_default();
if state.ignore_start_backoff.is_none() {
state.ignore_start_backoff = Some(backoff::ExponentialBackoff {
max_elapsed_time: None,
..Default::default()
});
}
state.ignore_start_until = state
.ignore_start_backoff
.as_mut()
.unwrap()
.next_backoff()
.and_then(|d| Instant::now().checked_add(d));
state.last_error = Some(reason);
}
fn should_start_instance(&self, instance_id: InstanceId, deployment: &Deployment) -> bool {
let mut instances = self.instances.write().unwrap();
let state = instances.entry(instance_id).or_default();
if let Some(last_deployment) = &state.last_deployment {
// In case the deployment has changed, allow immediate start as the new deployment could
// fix startup and we should make sure to process it immediately.
if deployment != last_deployment {
return true;
}
}
if let Some(ignore_start_until) = state.ignore_start_until {
if Instant::now() < ignore_start_until {
return false;
}
}
true
}
fn allow_instance_start(&self, instance_id: InstanceId) {
let mut instances = self.instances.write().unwrap();
if let Some(state) = instances.get_mut(&instance_id) {
state.ignore_start_backoff = None;
state.ignore_start_until = None;
state.last_error = None;
}
}
/// Pull the given deployment and deploy it into the given instance.
async fn pull_and_deploy_instance(
self: &Arc<Self>,
instance: &Instance,
deployment: &Deployment,
) -> Result<()> {
let deployment_info = self
.pull_and_validate_deployment(instance, deployment)
.await?;
self.deploy_instance(instance, deployment, deployment_info)
.await
}
/// Deploy the given deployment on the given instance. Requires that the deployment has already
/// been pulled and is available on the host under the given temporary name.
async fn deploy_instance(
&self,
instance: &Instance,
deployment: &Deployment,
deployment_info: DeploymentInfo,
) -> Result<()> {
slog::info!(self.logger, "deploying bundle";
"id" => ?instance.id,
"temporary_name" => &deployment_info.temporary_name,
);
// Check if we need to add any volumes.
let mut volumes = BTreeMap::new();
// TODO: Properly support multiple volumes.
if deployment_info.volumes.len() > 1 {
return Err(anyhow!("multiple volumes not yet supported"));
}
for volume_name in deployment_info.volumes {
let mut volume_labels = labels_for_instance(instance.id);
volume_labels.insert(LABEL_VOLUME_NAME.to_string(), "000".to_string());
let rsp = self
.env
.host()
.volume_manager()
.volume_list(volume_manager::VolumeListRequest {
labels: volume_labels.clone(),
})
.await?;
if rsp.volumes.is_empty() {
// Create volume.
let rsp = self
.env
.host()
.volume_manager()
.volume_add(volume_manager::VolumeAddRequest {
labels: volume_labels,
})
.await?;
volumes.insert(volume_name, rsp.id);
} else {
// Use existing volume.
volumes.insert(volume_name, rsp.volumes[0].id.clone());
}
}
let mut labels = labels_for_instance(instance.id);
labels.insert(
LABEL_DEPLOYMENT_HASH.to_string(),
deployment_hash(deployment),