-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathmod.rs
More file actions
2574 lines (2312 loc) · 94.9 KB
/
mod.rs
File metadata and controls
2574 lines (2312 loc) · 94.9 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
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Golem Source License v1.1 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod agent_config;
pub mod invocation;
mod invocation_loop;
pub mod status;
use self::agent_config::{
ensure_required_agent_secrets_are_configured, parse_worker_creation_agent_config,
};
use self::status::{
calculate_last_known_status_for_existing_worker, update_status_with_new_entries,
};
use crate::durable_host::recover_stderr_logs;
use crate::model::{AgentConfig, ExecutionStatus, LookupResult, ReadFileResult, TrapType};
use crate::services::events::{Event, EventsSubscription};
use crate::services::golem_config::SnapshotPolicy;
use crate::services::oplog::{CommitLevel, Oplog, OplogOps};
use crate::services::worker::GetWorkerMetadataResult;
use crate::services::worker_event::{WorkerEventService, WorkerEventServiceDefault};
use crate::services::{
All, HasActiveWorkers, HasAgentTypesService, HasAgentWebhooksService, HasAll,
HasBlobStoreService, HasComponentService, HasConfig, HasEnvironmentStateService, HasEvents,
HasExtraDeps, HasFileLoader, HasHttpConnectionPool, HasKeyValueService, HasOplog,
HasOplogService, HasPromiseService, HasRdbmsService, HasResourceLimits, HasRpc,
HasSchedulerService, HasShardService, HasWasmtimeEngine, HasWorkerEnumerationService,
HasWorkerForkService, HasWorkerProxy, HasWorkerService, UsesAllDeps,
};
use crate::worker::invocation_loop::InvocationLoop;
use crate::worker::status::calculate_last_known_status;
use crate::workerctx::WorkerCtx;
use anyhow::anyhow;
use chrono::Utc;
use futures::channel::oneshot;
use futures::FutureExt;
use golem_common::base_model::environment_plugin_grant::EnvironmentPluginGrantId;
use golem_common::model::account::AccountId;
use golem_common::model::agent::{
AgentMode, ParsedAgentId, Principal, Snapshotting, SnapshottingConfig,
};
use golem_common::model::component::ComponentFilePath;
use golem_common::model::component::ComponentRevision;
use golem_common::model::invocation_context::InvocationContextStack;
use golem_common::model::oplog::{OplogEntry, OplogIndex, UpdateDescription};
use golem_common::model::regions::{DeletedRegionsBuilder, OplogRegion};
use golem_common::model::worker::{RevertWorkerTarget, WorkerAgentConfigEntry};
use golem_common::model::AgentStatus;
use golem_common::model::RetryConfig;
use golem_common::model::{
AgentId, AgentInvocation, AgentInvocationOutput, AgentInvocationResult, AgentMetadata,
AgentStatusRecord, IdempotencyKey, OwnedAgentId, ScheduledAction, Timestamp,
TimestampedAgentInvocation,
};
use golem_common::one_shot::OneShotEvent;
use golem_common::read_only_lock;
use golem_service_base::error::worker_executor::{
GolemSpecificWasmTrap, InterruptKind, WorkerExecutorError,
};
use golem_service_base::model::GetFileSystemNodeResult;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::broadcast::Receiver;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::sync::{Mutex, MutexGuard, OwnedSemaphorePermit, RwLock};
use tokio::task::JoinHandle;
use tracing::{debug, info, span, warn, Instrument, Level, Span};
use uuid::Uuid;
use wasmtime::component::Instance;
use wasmtime::{Store, UpdateDeadline};
/// Represents worker that may be running or suspended.
///
/// It is responsible for receiving incoming worker invocations in a non-blocking way,
/// persisting them and also making sure that all the enqueued invocations eventually get
/// processed, in the same order as they came in.
///
/// Invocations have an associated idempotency key used to ensure that the same invocation
/// is not processed multiple times.
///
/// If the queue is empty, the service can trigger invocations directly as an optimization.
///
/// Every worker invocation should be done through this service.
pub struct Worker<Ctx: WorkerCtx> {
owned_agent_id: OwnedAgentId,
parsed_agent_id: Option<ParsedAgentId>,
oplog: Arc<dyn Oplog>,
worker_event_service: Arc<dyn WorkerEventService + Send + Sync>,
deps: All<Ctx>,
queue: Arc<RwLock<VecDeque<QueuedWorkerInvocation>>>,
external_invocation_spans: Arc<RwLock<HashMap<IdempotencyKey, Span>>>,
invocation_results: Arc<RwLock<HashMap<IdempotencyKey, InvocationResult>>>,
initial_worker_metadata: AgentMetadata,
last_known_status: Arc<RwLock<AgentStatusRecord>>,
last_known_status_detached: AtomicBool,
// Note: std lock for wasmtime reasons
execution_status: Arc<std::sync::RwLock<ExecutionStatus>>,
update_state_lock: Mutex<()>,
worker_estimate_coefficient: f64,
// IMPORTANT: Every external operation must acquire the instance lock, even briefly, to confirm the worker isn’t deleting.
instance: Arc<Mutex<WorkerInstance>>,
oom_retry_config: RetryConfig,
snapshot_policy: SnapshotPolicy,
last_resume_request: Mutex<Timestamp>,
pub(crate) snapshot_recovery_disabled: AtomicBool,
}
impl<Ctx: WorkerCtx> HasOplog for Worker<Ctx> {
fn oplog(&self) -> Arc<dyn Oplog> {
self.oplog.clone()
}
}
impl<Ctx: WorkerCtx> UsesAllDeps for Worker<Ctx> {
type Ctx = Ctx;
fn all(&self) -> &All<Self::Ctx> {
&self.deps
}
}
impl<Ctx: WorkerCtx> Worker<Ctx> {
/// Gets or creates a worker, but does not start it
pub async fn get_or_create_suspended<T>(
deps: &T,
account_id: AccountId,
owned_agent_id: &OwnedAgentId,
worker_env: Option<Vec<(String, String)>>,
worker_config_vars: Option<BTreeMap<String, String>>,
worker_agent_config: Vec<WorkerAgentConfigEntry>,
component_revision: Option<ComponentRevision>,
parent: Option<AgentId>,
invocation_context_stack: &InvocationContextStack,
principal: Principal,
) -> Result<Arc<Self>, WorkerExecutorError>
where
T: HasAll<Ctx> + Clone + Send + Sync + 'static,
{
deps.active_workers()
.get_or_add(
deps,
owned_agent_id,
account_id,
worker_env,
worker_config_vars,
worker_agent_config,
component_revision,
parent,
invocation_context_stack,
principal,
)
.await
}
/// Gets or creates a worker and makes sure it is running
pub async fn get_or_create_running<T>(
deps: &T,
account_id: AccountId,
owned_agent_id: &OwnedAgentId,
worker_env: Option<Vec<(String, String)>>,
worker_config_vars: Option<BTreeMap<String, String>>,
worker_agent_config: Vec<WorkerAgentConfigEntry>,
component_revision: Option<ComponentRevision>,
parent: Option<AgentId>,
invocation_context_stack: &InvocationContextStack,
principal: Principal,
) -> Result<Arc<Self>, WorkerExecutorError>
where
T: HasAll<Ctx> + Send + Sync + Clone + 'static,
{
let worker = Self::get_or_create_suspended(
deps,
account_id,
owned_agent_id,
worker_env,
worker_config_vars,
worker_agent_config,
component_revision,
parent,
invocation_context_stack,
principal,
)
.await?;
Self::start_if_needed(worker.clone()).await?;
Ok(worker)
}
pub async fn get_latest_metadata<T: HasAll<Ctx>>(
deps: &T,
owned_agent_id: &OwnedAgentId,
) -> Option<AgentMetadata> {
if let Some(worker) = deps.active_workers().try_get(owned_agent_id).await {
Some(worker.get_latest_worker_metadata().await)
} else if let Some(GetWorkerMetadataResult {
mut initial_worker_metadata,
last_known_status,
}) = deps.worker_service().get(owned_agent_id).await
{
// update with latest data from oplog
let last_known_status = calculate_last_known_status(
deps,
owned_agent_id,
last_known_status,
)
.await
.expect("Failed to calculate worker status for worker even though it is initialized");
initial_worker_metadata.last_known_status = last_known_status;
Some(initial_worker_metadata)
} else {
None
}
}
pub async fn new<T: HasAll<Ctx>>(
deps: &T,
account_id: &AccountId,
owned_agent_id: OwnedAgentId,
worker_env: Option<Vec<(String, String)>>,
worker_config: Option<BTreeMap<String, String>>,
worker_agent_config: Vec<WorkerAgentConfigEntry>,
component_revision: Option<ComponentRevision>,
parent: Option<AgentId>,
invocation_context_stack: &InvocationContextStack,
principal: Principal,
) -> Result<Self, WorkerExecutorError> {
let GetOrCreateWorkerResult {
initial_worker_metadata,
current_status,
execution_status,
agent_id,
snapshot_policy,
oplog,
} = Self::get_or_create_worker_metadata(
deps,
account_id,
&owned_agent_id,
component_revision,
worker_env,
worker_config,
worker_agent_config,
parent,
)
.await?;
let current_status_guard = current_status.read().await;
let initial_pending_invocations = current_status_guard.pending_invocations.clone();
let initial_invocation_results = current_status_guard.invocation_results.clone();
let last_oplog_idx = current_status_guard.oplog_idx;
drop(current_status_guard);
let mut spans_map = HashMap::new();
for inv in initial_pending_invocations {
if let Some(idempotency_key) = inv.invocation.idempotency_key() {
spans_map.insert(idempotency_key.clone(), Span::current());
}
}
let queue = Arc::new(RwLock::new(VecDeque::new()));
let external_invocation_spans = Arc::new(RwLock::new(spans_map));
let invocation_results = Arc::new(RwLock::new(HashMap::from_iter(
initial_invocation_results.iter().map(|(key, oplog_idx)| {
(
key.clone(),
InvocationResult::Lazy {
oplog_idx: *oplog_idx,
},
)
}),
)));
let instance = Arc::new(Mutex::new(WorkerInstance::Unloaded {
startup_failure: None,
}));
let worker = Worker {
owned_agent_id,
parsed_agent_id: agent_id.clone(),
oplog,
worker_event_service: Arc::new(WorkerEventServiceDefault::new(
deps.config().limits.event_broadcast_capacity,
deps.config().limits.event_history_size,
)),
deps: All::from_other(deps),
queue,
external_invocation_spans,
invocation_results,
instance,
execution_status,
initial_worker_metadata,
last_known_status: current_status,
worker_estimate_coefficient: deps.config().memory.worker_estimate_coefficient,
oom_retry_config: deps.config().memory.oom_retry_config.clone(),
snapshot_policy,
update_state_lock: Mutex::new(()),
last_known_status_detached: AtomicBool::new(false),
last_resume_request: Mutex::new(Timestamp::now_utc()),
snapshot_recovery_disabled: AtomicBool::new(false),
};
// just some sanity checking
assert!(last_oplog_idx >= OplogIndex::INITIAL);
// if the worker is an agent, we need to ensure the initialize invocation is the first enqueued action.
// We might have crashed between creating the oplog and writing it, so just check here for it.
if let Some(agent_id) = &agent_id {
if last_oplog_idx <= OplogIndex::from_u64(2) {
let init_idempotency_key =
IdempotencyKey::new(format!("init-{}", worker.agent_id()));
worker
.enqueue_worker_invocation(AgentInvocation::AgentInitialization {
idempotency_key: init_idempotency_key,
input: agent_id.parameters.clone().into(),
invocation_context: invocation_context_stack.clone(),
principal,
})
.await
.expect("Failed enqueuing initial agent invocations to worker");
}
} else {
warn!("Unexpected non-agentic worker"); // TODO: change this once oplog-processors are finalized
};
Ok(worker)
}
pub fn agent_id(&self) -> AgentId {
self.owned_agent_id.agent_id()
}
pub fn oom_retry_config(&self) -> &RetryConfig {
&self.oom_retry_config
}
pub(crate) fn snapshot_policy(&self) -> &SnapshotPolicy {
&self.snapshot_policy
}
pub async fn start_if_needed(this: Arc<Worker<Ctx>>) -> Result<bool, WorkerExecutorError> {
Self::start_if_needed_internal(this, 0).await
}
async fn start_if_needed_internal(
this: Arc<Worker<Ctx>>,
oom_retry_count: u32,
) -> Result<bool, WorkerExecutorError> {
{
*this.last_resume_request.lock().await = Timestamp::now_utc();
}
let mut instance_guard = this.lock_non_stopping_worker().await;
match &*instance_guard {
WorkerInstance::Unloaded { .. } => {
this.mark_as_loading();
*instance_guard = WorkerInstance::WaitingForPermit(WaitingWorker::new(
this.clone(),
this.memory_requirement().await?,
oom_retry_count,
));
Ok(true)
}
WorkerInstance::WaitingForPermit(_) | WorkerInstance::Running(_) => Ok(false),
WorkerInstance::Deleting => Err(WorkerExecutorError::invalid_request(
"Worker is being deleted",
)),
WorkerInstance::Stopping(_) => panic!("impossible"),
}
}
/// This method is supposed to be called on a worker for what `is_currently_idle_but_running`
/// previously returned true.
///
/// It is not guaranteed that the worker is still "running (loaded in memory) but idle" when
/// this method is called, so it rechecks this condition and only stops the worker if it
/// is still true. If it was not true, it returns false.
///
/// There are two conditions to this:
/// - the ExecutionStatus must be suspended; this means the worker is currently not running any invocations
/// - there must be no more pending invocations in the invocation queue
///
/// Here we first acquire the `instance` lock. This means the worker cannot be started/stopped while we
/// are processing this method.
/// If it was not running, then we don't have to stop it.
/// If it was running, then we recheck the conditions and then stop the worker.
///
/// We know that the conditions remain true because:
/// - the invocation queue is empty, so it cannot get into `ExecutionStatus::Running`, as there is nothing to run
/// - nothing can be added to the invocation queue because we are holding the `instance` lock
///
/// By passing the running lock to `stop_internal_running` it is never released and the stop eventually
/// drops the `RunningWorker` instance.
///
/// The `stopping` flag is only used to prevent re-entrance of the stopping sequence in case the invocation loop
/// triggers a stop (in case of a failure - by the way it should not happen here because the worker is idle).
pub async fn stop_if_idle(&self) -> bool {
let mut instance_guard = self.lock_non_stopping_worker().await;
let stop_result = match &*instance_guard {
WorkerInstance::Running(running) => {
if is_running_agent_idle(running).await {
let stop_result = self
.stop_internal_locked(
&mut instance_guard,
false,
None,
FinalWorkerState::Unloaded {
startup_failure: None,
},
)
.await;
Some(stop_result)
} else {
None
}
}
WorkerInstance::WaitingForPermit(_) => None,
WorkerInstance::Stopping(_) => None,
WorkerInstance::Unloaded { .. } => None,
WorkerInstance::Deleting => None,
};
drop(instance_guard);
if let Some(stop_result) = stop_result {
self.handle_stop_result(stop_result).await;
true
} else {
false
}
}
/// Transition the worker into a deleting state.
/// Rejects all new invocations and stops any running execution.
pub async fn start_deleting(&self) -> Result<(), WorkerExecutorError> {
let error = WorkerExecutorError::invalid_request("Worker is being deleted");
self.stop_internal(false, Some(error), FinalWorkerState::Deleting)
.await;
Ok(())
}
pub fn event_service(&self) -> Arc<dyn WorkerEventService + Send + Sync> {
self.worker_event_service.clone()
}
pub fn is_loading(&self) -> bool {
matches!(
*self.execution_status.read().unwrap(),
ExecutionStatus::Loading { .. }
)
}
fn mark_as_loading(&self) {
let mut execution_status = self.execution_status.write().unwrap();
*execution_status = ExecutionStatus::Loading {
agent_mode: execution_status.agent_mode(),
timestamp: Timestamp::now_utc(),
};
}
pub fn get_initial_worker_metadata(&self) -> AgentMetadata {
self.initial_worker_metadata.clone()
}
pub async fn get_latest_worker_metadata(&self) -> AgentMetadata {
let updated_status = self.last_known_status.read().await.clone();
let result = self.get_initial_worker_metadata();
AgentMetadata {
last_known_status: updated_status,
..result
}
}
// Outside of reverts and updates, this will return the same status as get_latest_worker_metadata.
// This just has an additional assert built in for when decisions need to be sure that they are fully up to date on the oplog.
// _NEVER_ call this from outside the invocation loop, as that is the only place that can reason about whether the status is detached or not.
pub async fn get_non_detached_last_known_status(&self) -> AgentStatusRecord {
// hold the update lock so we know that the atomic bool and state are consistent
let update_state_lock_guard = self.update_state_lock.lock().await;
let is_detached = self.last_known_status_detached.load(Ordering::Relaxed);
assert!(!is_detached);
let result = self.last_known_status.read().await.clone();
// ensure we hold mutex for the full duration
drop(update_state_lock_guard);
result
}
/// Marks the worker as interrupting - this should eventually make the worker interrupted.
/// There are several interruption modes but not all of them are supported by all worker
/// executor implementations.
///
/// - `Interrupt` means that the worker should be interrupted as soon as possible, and it should
/// remain interrupted.
/// - `Restart` is a simulated crash, the worker gets automatically restarted after it got interrupted,
/// but only if the worker context supports recovering workers.
/// - `Suspend` means that the worker should be moved out of memory and stay in suspended state,
/// automatically resumed when the worker is needed again. This only works if the worker context
/// supports recovering workers.
pub async fn set_interrupting(&self, interrupt_kind: InterruptKind) -> Option<Receiver<()>> {
if let WorkerInstance::Running(running) = &*self.lock_non_stopping_worker().await {
running.interrupt(interrupt_kind).await;
}
let mut execution_status = self.execution_status.write().unwrap();
let current_execution_status = execution_status.clone();
match current_execution_status {
ExecutionStatus::Running {
interrupt_signal, ..
} => {
let _ = interrupt_signal.send(interrupt_kind);
let (sender, receiver) = tokio::sync::broadcast::channel(1);
*execution_status = ExecutionStatus::Interrupting {
interrupt_kind,
await_interruption: Arc::new(sender),
agent_mode: execution_status.agent_mode(),
timestamp: Timestamp::now_utc(),
};
Some(receiver)
}
ExecutionStatus::Suspended { .. } => None,
ExecutionStatus::Interrupting {
await_interruption, ..
} => {
let receiver = await_interruption.subscribe();
Some(receiver)
}
ExecutionStatus::Loading { .. } => None,
}
}
pub async fn resume_replay(&self) -> Result<(), WorkerExecutorError> {
match &*self.lock_non_stopping_worker().await {
WorkerInstance::Running(running) => {
running
.sender
.send(WorkerCommand::ResumeReplay)
.expect("Failed to send resume command");
Ok(())
}
WorkerInstance::Unloaded { .. } | WorkerInstance::WaitingForPermit(_) => {
Err(WorkerExecutorError::invalid_request(
"Explicit resume is not supported for uninitialized workers",
))
}
WorkerInstance::Deleting => Err(WorkerExecutorError::invalid_request(
"Explicit resume is not supported for deleting workers",
)),
WorkerInstance::Stopping(_) => panic!("impossible"),
}
}
pub async fn invoke(
&self,
invocation: AgentInvocation,
) -> Result<ResultOrSubscription, WorkerExecutorError> {
let idempotency_key = invocation
.idempotency_key()
.ok_or_else(|| {
WorkerExecutorError::invalid_request("Invocation has no idempotency key")
})?
.clone();
// We need to create the subscription before checking whether the result is still pending, otherwise there is a race.
let subscription = self.events().subscribe();
let output = async { self.lookup_invocation_result(&idempotency_key).await }
.instrument(span!(Level::INFO, "lookup_invocation_result"))
.await;
match output {
LookupResult::Complete(output) => Ok(ResultOrSubscription::Finished(output)),
LookupResult::Interrupted => Err(InterruptKind::Interrupt(Timestamp::now_utc()).into()),
LookupResult::Pending => Ok(ResultOrSubscription::Pending(subscription)),
LookupResult::New => {
self.enqueue_worker_invocation(invocation).await?;
Ok(ResultOrSubscription::Pending(subscription))
}
}
}
/// Invokes the worker and awaits for a result.
pub async fn invoke_and_await(
&self,
invocation: AgentInvocation,
) -> Result<AgentInvocationOutput, WorkerExecutorError> {
let idempotency_key = invocation
.idempotency_key()
.ok_or_else(|| {
WorkerExecutorError::invalid_request("Invocation has no idempotency key")
})?
.clone();
match self.invoke(invocation).await? {
ResultOrSubscription::Finished(Ok(output)) => Ok(output),
ResultOrSubscription::Finished(Err(err)) => Err(err),
ResultOrSubscription::Pending(subscription) => {
debug!("Waiting for idempotency key to complete",);
let result = async {
self.wait_for_invocation_result(&idempotency_key, subscription)
.await
}
.instrument(span!(Level::INFO, "wait_for_invocation_result"))
.await;
match result {
Ok(LookupResult::Complete(Ok(output))) => Ok(output),
Ok(LookupResult::Complete(Err(err))) => Err(err),
Ok(LookupResult::Interrupted) => {
Err(InterruptKind::Interrupt(Timestamp::now_utc()).into())
}
Ok(LookupResult::Pending) => Err(WorkerExecutorError::unknown(
"Unexpected pending result after invoke",
)),
Ok(LookupResult::New) => Err(WorkerExecutorError::unknown(
"Unexpected missing result after invoke",
)),
Err(recv_error) => Err(WorkerExecutorError::unknown(format!(
"Failed waiting for invocation result: {recv_error}"
))),
}
}
}
}
/// Enqueue attempting an update.
///
/// The update itself is not performed by the invocation queue's processing loop,
/// it is going to affect how the worker is recovered next time.
pub async fn enqueue_update(&self, update_description: UpdateDescription) {
let entry = OplogEntry::pending_update(update_description.clone());
self.add_and_commit_oplog(entry).await;
}
/// Enqueues a manual update.
///
/// This enqueues a special function invocation that saves the component's state and
/// triggers a restart immediately.
pub async fn enqueue_manual_update(
&self,
target_revision: ComponentRevision,
) -> Result<(), WorkerExecutorError> {
self.enqueue_worker_invocation(AgentInvocation::ManualUpdate { target_revision })
.await
}
pub async fn pending_invocations(&self) -> Vec<TimestampedAgentInvocation> {
self.last_known_status
.read()
.await
.pending_invocations
.clone()
}
pub async fn invocation_results(&self) -> HashMap<IdempotencyKey, OplogIndex> {
self.last_known_status
.read()
.await
.invocation_results
.clone()
}
// should only be called from invocation loop
pub async fn store_invocation_success(
&self,
key: &IdempotencyKey,
output: AgentInvocationOutput,
) {
let mut map = self.invocation_results.write().await;
map.insert(
key.clone(),
InvocationResult::Cached {
result: Ok(output.clone()),
},
);
debug!("Stored invocation success for {key}");
self.events().publish(Event::InvocationCompleted {
agent_id: self.owned_agent_id.agent_id(),
idempotency_key: key.clone(),
result: Ok(output),
});
}
// should only be called from invocation loop
pub async fn store_invocation_failure(&self, key: &IdempotencyKey, trap_type: &TrapType) {
let pending = self.pending_invocations().await;
let keys_to_fail = [
vec![key],
pending
.iter()
.filter_map(|entry| entry.invocation.idempotency_key())
.collect(),
]
.concat();
let mut map = self.invocation_results.write().await;
for key in keys_to_fail {
let stderr = self.worker_event_service.get_last_invocation_errors();
map.insert(
key.clone(),
InvocationResult::Cached {
result: Err(FailedInvocationResult {
trap_type: trap_type.clone(),
stderr: stderr.clone(),
}),
},
);
let golem_error = trap_type.as_golem_error(&stderr);
if let Some(golem_error) = golem_error {
self.events().publish(Event::InvocationCompleted {
agent_id: self.owned_agent_id.agent_id(),
idempotency_key: key.clone(),
result: Err(golem_error),
});
}
}
}
pub(super) async fn store_invocation_resuming(&self, key: &IdempotencyKey) {
let mut map = self.invocation_results.write().await;
map.remove(key);
}
pub fn agent_mode(&self) -> AgentMode {
self.execution_status.read().unwrap().agent_mode()
}
/// Gets the estimated memory requirement of the worker
pub async fn memory_requirement(&self) -> Result<u64, WorkerExecutorError> {
let metadata = self.get_latest_worker_metadata().await;
let ml = metadata.last_known_status.total_linear_memory_size as f64;
let sw = metadata.last_known_status.component_size as f64;
let c = 2.0;
let x = self.worker_estimate_coefficient;
Ok((x * (ml + c * sw)) as u64)
}
/// Returns true if the worker is running, but it is not performing any invocations at the moment
/// (ExecutionStatus::Suspended) and has no pending invocation in its invocation queue.
///
/// These workers can be stopped to free up available worker memory.
pub async fn is_currently_idle_but_running(&self) -> bool {
match &*self.instance.lock().await {
WorkerInstance::Running(running) => {
let waiting_for_command = running.waiting_for_command.load(Ordering::Acquire);
let has_invocations = !self.pending_invocations().await.is_empty();
debug!("Worker {} is running, waiting_for_command: {waiting_for_command} has_invocations: {has_invocations}", self.owned_agent_id);
waiting_for_command && !has_invocations
}
WorkerInstance::WaitingForPermit(_) => {
debug!(
"Worker {} is waiting for permit, cannot be used to free up memory",
self.owned_agent_id
);
false
}
WorkerInstance::Unloaded { .. } => {
debug!(
"Worker {} is unloaded, cannot be used to free up memory",
self.owned_agent_id
);
false
}
// TODO: this probably wants to cooperate with memory free up
WorkerInstance::Stopping(_) => {
debug!(
"Worker {} is stopping, cannot be used to free up memory",
self.owned_agent_id
);
false
}
// TODO: this probably wants to cooperate with memory free up
WorkerInstance::Deleting => {
debug!(
"Worker {} is deleting, cannot be used to free up memory",
self.owned_agent_id
);
false
}
}
}
/// Gets the timestamp of the last time the execution status changed
pub fn last_execution_state_change(&self) -> Timestamp {
self.execution_status.read().unwrap().timestamp()
}
// Should only be called from invocation loop
pub async fn increase_memory(&self, delta: u64) -> anyhow::Result<()> {
match &mut *self.instance.lock().await {
WorkerInstance::Running(ref mut running) => {
if let Some(new_permits) = self.active_workers().try_acquire(delta).await {
running.merge_extra_permits(new_permits);
Ok(())
} else {
Err(anyhow!(GolemSpecificWasmTrap::WorkerOutOfMemory))
}
}
WorkerInstance::Stopping(_) => Ok(()),
WorkerInstance::WaitingForPermit(_) => Ok(()),
WorkerInstance::Unloaded { .. } => Ok(()),
WorkerInstance::Deleting => Ok(()),
}
}
/// Enqueue invocation of an exported function
async fn enqueue_worker_invocation(
&self,
invocation: AgentInvocation,
) -> Result<(), WorkerExecutorError> {
async {
let instance_guard = self.lock_non_stopping_worker().await;
if instance_guard.is_deleting() {
return Err(WorkerExecutorError::invalid_request(
"Cannot enqueue invocation to a deleting worker",
));
};
if let Some(err) = instance_guard.startup_failure() {
return Err(err.clone());
}
let (idempotency_key, invocation_payload, invocation_context) =
invocation.clone().into_parts();
let payload = self
.oplog
.upload_payload(&invocation_payload)
.await
.map_err(|e| {
WorkerExecutorError::invalid_request(format!(
"Failed to upload invocation payload: {e}"
))
})?;
let invocation_context_spans = invocation_context.to_oplog_data();
let entry = OplogEntry::pending_agent_invocation(
idempotency_key,
payload,
invocation_context.trace_id,
invocation_context.trace_states,
invocation_context_spans,
);
let timestamped_invocation = TimestampedAgentInvocation {
timestamp: entry.timestamp(),
invocation,
};
self.add_and_commit_oplog_internal(&instance_guard, entry)
.await;
if let Some(idempotency_key) = timestamped_invocation.invocation.idempotency_key() {
self.external_invocation_spans
.write()
.await
.insert(idempotency_key.clone(), Span::current());
}
if let WorkerInstance::Running(running) = &*instance_guard {
running.sender.send(WorkerCommand::Unblock).unwrap();
};
drop(instance_guard);
Ok(())
}
.instrument(span!(Level::INFO, "enqueue_invocation"))
.await
}
pub async fn get_file_system_node(
&self,
path: ComponentFilePath,
) -> Result<GetFileSystemNodeResult, WorkerExecutorError> {
let instance_guard = self.lock_non_stopping_worker().await;
if instance_guard.is_deleting() {
return Err(WorkerExecutorError::invalid_request(
"Cannot access filesystem of a deleting worker",
));
};
if let Some(err) = instance_guard.startup_failure() {
return Err(err.clone());
}
let (sender, receiver) = oneshot::channel();
self.queue
.write()
.await
.push_back(QueuedWorkerInvocation::GetFileSystemNode { path, sender });
// Two cases here:
// - Worker is running, we can send the invocation command, and the worker will look at the queue immediately
// - Worker is starting, it will process the request when it is started
if let WorkerInstance::Running(running) = &*instance_guard {
running.sender.send(WorkerCommand::Unblock).unwrap();
};
drop(instance_guard);
receiver.await.unwrap()
}
pub async fn read_file(
&self,
path: ComponentFilePath,
) -> Result<ReadFileResult, WorkerExecutorError> {
let instance_guard = self.lock_non_stopping_worker().await;
if instance_guard.is_deleting() {
return Err(WorkerExecutorError::invalid_request(
"Cannot access filesystem of a deleting worker",
));
};
if let Some(err) = instance_guard.startup_failure() {
return Err(err.clone());
}
let (sender, receiver) = oneshot::channel();
self.queue
.write()
.await
.push_back(QueuedWorkerInvocation::ReadFile { path, sender });
if let WorkerInstance::Running(running) = &*instance_guard {
running.sender.send(WorkerCommand::Unblock).unwrap();
};
drop(instance_guard);
receiver.await.unwrap()
}
pub async fn await_ready_to_process_commands(&self) -> Result<(), WorkerExecutorError> {
let instance_guard = self.lock_non_stopping_worker().await;
if instance_guard.is_deleting() {
return Err(WorkerExecutorError::invalid_request(
"Cannot await readiness of a deleting worker",
));
};
if let Some(err) = instance_guard.startup_failure() {
return Err(err.clone());
}
let (sender, receiver) = oneshot::channel();
self.queue
.write()
.await
.push_back(QueuedWorkerInvocation::AwaitReadyToProcessCommands { sender });
if let WorkerInstance::Running(running) = &*instance_guard {
running.sender.send(WorkerCommand::Unblock).unwrap();
};
drop(instance_guard);
receiver.await.unwrap()
}
// Should only be called from invocation loop
pub async fn add_to_oplog(&self, entry: OplogEntry) -> OplogIndex {
self.oplog.add(entry).await
}
pub async fn commit_oplog_and_update_state(&self, commit_level: CommitLevel) -> OplogIndex {
let (result, changed) = self
.commit_oplog_and_update_state_internal(commit_level)
.await;
if changed {
let instance_guard = self.instance.lock().await;
if let WorkerInstance::Running(running) = &*instance_guard {
running.sender.send(WorkerCommand::Unblock).unwrap();