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
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
mod channels;
mod config;
pub mod job;
mod message;
pub mod parameter;
pub mod worker;
pub use lapin::Channel;
pub use log::{debug, error, info, trace, warn};
pub use semver::Version;
pub use message::publish_job_progression;
pub use parameter::container::ParametersContainer;
pub use parameter::credential::Credential;
pub use parameter::{Parameter, Requirement};
use chrono::prelude::*;
use config::*;
use env_logger::Builder;
use futures_executor::LocalPool;
use futures_util::{future::FutureExt, stream::StreamExt, task::LocalSpawnExt};
use job::{Job, JobResult, JobStatus};
use lapin::{options::*, types::FieldTable, Connection, ConnectionProperties};
use std::{fs, io::Write, thread, time};
pub trait MessageEvent {
fn get_name(&self) -> String;
fn get_short_description(&self) -> String;
fn get_description(&self) -> String;
fn get_version(&self) -> semver::Version;
fn get_parameters(&self) -> Vec<worker::Parameter>;
fn process(
&self,
_channel: Option<&Channel>,
_job: &Job,
_job_result: JobResult,
) -> Result<JobResult, MessageError>
where
Self: std::marker::Sized,
{
Err(MessageError::NotImplemented())
}
}
#[derive(Debug, PartialEq)]
pub enum MessageError {
RuntimeError(String),
ProcessingError(JobResult),
RequirementsError(String),
NotImplemented(),
}
impl MessageError {
pub fn from(error: std::io::Error, job_result: JobResult) -> Self {
let result = job_result
.with_status(JobStatus::Error)
.with_message(&format!("IO Error: {}", error.to_string()));
MessageError::ProcessingError(result)
}
}
pub fn start_worker<ME: MessageEvent>(message_event: &'static ME)
where
ME: std::marker::Sync,
{
let mut builder = Builder::from_default_env();
let amqp_queue = get_amqp_queue();
let worker_configuration = worker::WorkerConfiguration::new(&amqp_queue, message_event);
let container_id = worker_configuration.get_instance_id();
builder
.format(move |stream, record| {
writeln!(
stream,
"{} - {} - {} - {} - {} - {}",
Utc::now(),
&container_id,
amqp_queue,
record.target().parse::<i64>().unwrap_or(-1),
record.level(),
record.args(),
)
})
.init();
let amqp_queue = get_amqp_queue();
info!(
"Worker: {}, version: {} (MCAI Worker SDK {})",
worker_configuration.get_worker_name(),
worker_configuration.get_worker_version(),
worker_configuration.get_sdk_version(),
);
if let Some(source_orders) = get_source_orders() {
warn!("Worker will process source orders");
for source_order in &source_orders {
info!("Start to process order: {:?}", source_order);
let count = None;
let channel = None;
let message_data = fs::read_to_string(source_order).unwrap();
let result = message::parse_and_process_message(
message_event,
&message_data,
count,
channel,
message::publish_job_progression,
);
match result {
Ok(job_result) => info!("Succeed process: {:?}", job_result),
Err(message) => {
error!("Error {:?}", message);
}
}
}
return;
}
loop {
let amqp_uri = get_amqp_uri();
let mut executor = LocalPool::new();
let spawner = executor.spawner();
executor.run_until(async {
let conn = Connection::connect_uri(
amqp_uri,
ConnectionProperties::default().with_default_executor(8),
)
.wait()
.unwrap();
info!("Connected");
let channel = channels::declare_consumer_channel(&conn, &worker_configuration);
let consumer = channel
.clone()
.basic_consume(
&amqp_queue,
"amqp_worker",
BasicConsumeOptions::default(),
FieldTable::default(),
)
.await
.unwrap();
let status_consumer = channel
.clone()
.basic_consume(
&worker_configuration.get_direct_messaging_queue_name(),
"status_amqp_worker",
BasicConsumeOptions::default(),
FieldTable::default(),
)
.await
.unwrap();
let status_channel = channel.clone();
let status_worker_configuration = worker_configuration.clone();
let _consumer = spawner.spawn_local(async move {
status_consumer
.for_each(move |delivery| {
let delivery = delivery.expect("error caught in in consumer");
worker::system_information::send_real_time_information(
delivery,
&status_channel,
&status_worker_configuration,
)
.map(|_| ())
})
.await
});
info!("Start to consume on queue {:?}", amqp_queue);
let clone_channel = channel.clone();
consumer
.for_each(move |delivery| {
let delivery = delivery.expect("error caught in in consumer");
message::process_message(message_event, delivery, &clone_channel).map(|_| ())
})
.await
});
let sleep_duration = time::Duration::new(1, 0);
thread::sleep(sleep_duration);
info!("Reconnection...");
}
}
#[test]
fn empty_message_event_impl() {
#[derive(Debug)]
struct CustomEvent {}
impl MessageEvent for CustomEvent {
fn get_name(&self) -> String {
"custom".to_string()
}
fn get_short_description(&self) -> String {
"short description".to_string()
}
fn get_description(&self) -> String {
"long description".to_string()
}
fn get_version(&self) -> semver::Version {
semver::Version::new(1, 2, 3)
}
fn get_parameters(&self) -> Vec<worker::Parameter> {
vec![]
}
}
let custom_event = CustomEvent {};
let job = job::Job {
job_id: 1234,
parameters: vec![],
};
let job_result = job::JobResult::new(1234);
let result = custom_event.process(None, &job, job_result);
assert!(result == Err(MessageError::NotImplemented()));
}