-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.rs
More file actions
207 lines (181 loc) · 6.8 KB
/
Copy pathrunner.rs
File metadata and controls
207 lines (181 loc) · 6.8 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
use crate::{
client::DracoRuntimeStatusService,
config::AdapterConfig,
store::AdapterStore,
traits::{LoadConfig, Server as AdapterServer},
};
use code0_flow::flow_service::FlowUpdateService;
use std::sync::Arc;
use tokio::signal;
use tonic::transport::Server;
use tonic_health::pb::health_server::HealthServer;
use tucana::shared::{AdapterConfiguration, RuntimeFeature};
/// Context passed to adapter server implementations containing all shared resources
pub struct ServerContext<C: LoadConfig> {
pub server_config: Arc<C>,
pub adapter_config: Arc<AdapterConfig>,
pub adapter_store: Arc<AdapterStore>,
}
/// Main server runner that manages the complete adapter lifecycle
pub struct ServerRunner<C: LoadConfig> {
context: ServerContext<C>,
server: Box<dyn AdapterServer<C>>,
}
impl<C: LoadConfig> ServerRunner<C> {
pub fn get_server_config(&self) -> Arc<C> {
self.context.server_config.clone()
}
pub async fn new<S: AdapterServer<C>>(server: S) -> anyhow::Result<Self> {
env_logger::Builder::from_default_env()
.filter_level(log::LevelFilter::Debug)
.init();
code0_flow::flow_config::load_env_file();
let adapter_config = AdapterConfig::from_env();
let server_config = C::load();
let adapter_store = AdapterStore::from_url(
adapter_config.nats_url.clone(),
adapter_config.nats_bucket.clone(),
)
.await;
let context = ServerContext {
adapter_store: Arc::new(adapter_store),
adapter_config: Arc::new(adapter_config),
server_config: Arc::new(server_config),
};
Ok(Self {
context,
server: Box::new(server),
})
}
pub async fn serve(
self,
runtime_feature: Vec<RuntimeFeature>,
runtime_config: Vec<AdapterConfiguration>,
) -> anyhow::Result<()> {
let config = self.context.adapter_config.clone();
let mut runtime_status_service: Option<DracoRuntimeStatusService> = None;
log::info!("Starting Draco Variant: {}", config.draco_variant);
if !config.is_static() {
runtime_status_service = Some(
DracoRuntimeStatusService::from_url(
config.aquila_url.clone(),
config.draco_variant.clone(),
runtime_feature,
runtime_config,
)
.await,
);
if let Some(ser) = &runtime_status_service {
ser.update_runtime_status_by_status(
tucana::shared::adapter_runtime_status::Status::NotReady,
)
.await;
};
let definition_service = FlowUpdateService::from_url(
config.aquila_url.clone(),
config.definition_path.as_str(),
)
.await;
definition_service.send().await;
}
let health_task = if config.with_health_service {
let health_service =
code0_flow::flow_health::HealthService::new(config.nats_url.clone());
let address = format!("{}:{}", config.grpc_host, config.grpc_port).parse()?;
log::info!(
"Health server starting at {}:{}",
config.grpc_host,
config.grpc_port
);
Some(tokio::spawn(async move {
if let Err(err) = Server::builder()
.add_service(HealthServer::new(health_service))
.serve(address)
.await
{
log::error!("Health server error: {:?}", err);
} else {
log::info!("Health server stopped gracefully");
}
}))
} else {
None
};
let ServerRunner {
mut server,
context,
} = self;
// Init the adapter server (e.g. create underlying HTTP server)
server.init(&context).await?;
if let Some(ser) = &runtime_status_service {
ser.update_runtime_status_by_status(
tucana::shared::adapter_runtime_status::Status::Running,
)
.await;
};
log::info!("Draco successfully initialized.");
#[cfg(unix)]
let sigterm = async {
use tokio::signal::unix::{SignalKind, signal};
let mut term =
signal(SignalKind::terminate()).expect("failed to install SIGTERM handler");
term.recv().await;
};
#[cfg(not(unix))]
let sigterm = std::future::pending::<()>();
match health_task {
Some(mut ht) => {
tokio::select! {
// Main adapter server loop finished on its own
res = server.run(&context) => {
log::warn!("Adapter server finished, shutting down");
ht.abort();
res?;
}
// Health server ended first
_ = &mut ht => {
log::warn!("Health server task finished, shutting down adapter");
server.shutdown(&context).await?;
}
// Ctrl+C
_ = signal::ctrl_c() => {
log::info!("Ctrl+C/Exit signal received, shutting down adapter");
server.shutdown(&context).await?;
ht.abort();
}
_ = sigterm => {
log::info!("SIGTERM received, shutting down adapter");
server.shutdown(&context).await?;
ht.abort();
}
}
}
None => {
tokio::select! {
// Adapter server loop ends on its own
res = server.run(&context) => {
log::warn!("Adapter server finished");
res?;
}
// Ctrl+C
_ = signal::ctrl_c() => {
log::info!("Ctrl+C/Exit signal received, shutting down adapter");
server.shutdown(&context).await?;
}
_ = sigterm => {
log::info!("SIGTERM received, shutting down adapter");
server.shutdown(&context).await?;
}
}
}
}
if let Some(ser) = &runtime_status_service {
ser.update_runtime_status_by_status(
tucana::shared::adapter_runtime_status::Status::Stopped,
)
.await;
};
log::info!("Draco shutdown complete");
Ok(())
}
}