forked from Normation/rudder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfengine.rs
442 lines (427 loc) · 17.5 KB
/
cfengine.rs
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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2019-2020 Normation SAS
use super::Generator;
use crate::ast::enums::*;
use crate::ast::resource::*;
use crate::ast::value::*;
use crate::ast::*;
use crate::parser::*;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use crate::error::*;
pub struct CFEngine {
// list of already formatted expression in current case
current_cases: Vec<String>,
// match enum local variables with class prefixes
var_prefixes: HashMap<String, String>,
// already used class prefix
prefixes: HashMap<String, u32>,
// condition to add for every other condition for early return
return_condition: Option<String>,
}
impl CFEngine {
pub fn new() -> CFEngine {
CFEngine {
current_cases: Vec::new(),
var_prefixes: HashMap::new(),
prefixes: HashMap::new(),
return_condition: None,
}
}
fn new_var(&mut self, prefix: &str) {
let id = self.prefixes.get(prefix).unwrap_or(&0) + 1;
self.prefixes.insert(prefix.to_string(), id);
let var = format!("{}{}", prefix, id);
self.var_prefixes.insert(prefix.to_string(), var);
}
fn reset_cases(&mut self) {
// TODO this make case in case fail
self.current_cases = Vec::new();
}
fn reset_context(&mut self) {
self.var_prefixes = HashMap::new();
self.return_condition = None;
}
fn parameter_to_cfengine(&mut self, param: &Value) -> Result<String> {
Ok(match param {
Value::String(s) =>
// TODO variable reinterpret (rudlang systemvar to cfengine systemvar)
{
"\"".to_owned()
+ s.format(
|x: &str| {
x.replace("\\", "\\\\") // backslash escape
.replace("\"", "\\\"") // quote escape
.replace("$", "${const.dollar}")
}, // dollar escape
|y: &str| "${".to_owned() + y + "}", // variable inclusion
)
.as_str()
+ "\""
}
Value::Number(_, _) => unimplemented!(),
Value::EnumExpression(_e) => "".into(), // TODO
Value::List(_) => unimplemented!(),
Value::Struct(_) => unimplemented!(),
})
}
fn format_class(&mut self, class: String) -> Result<String> {
self.current_cases.push(class.clone());
Ok(match &self.return_condition {
None => class,
Some(c) => format!("({}).({})", c, class),
})
}
fn format_case_expr(&mut self, gc: &AST, case: &EnumExpression) -> Result<String> {
Ok(match case {
EnumExpression::And(e1, e2) => {
let mut lexpr = self.format_case_expr(gc, e1)?;
let mut rexpr = self.format_case_expr(gc, e2)?;
if lexpr.contains("|") {
lexpr = format!("({})", lexpr);
}
if rexpr.contains("|") {
rexpr = format!("({})", rexpr);
}
format!("{}.{}", lexpr, rexpr)
},
EnumExpression::Or(e1, e2) => format!(
"{}|{}",
self.format_case_expr(gc, e1)?,
self.format_case_expr(gc, e2)?
),
// TODO what about classes that have not yet been set ? can it happen ?
EnumExpression::Not(e1) => {
let mut expr = self.format_case_expr(gc, e1)?;
if expr.contains("|") || expr.contains("&") {
expr = format!("!({})", expr);
}
format!("!{}", expr)
},
EnumExpression::Compare(var, e, item) => {
if gc.enum_list.is_global(*e) {
let final_enum = gc.enum_list.find_descendant_enum(*e, *item);
if *e == final_enum {
item.fragment().to_string() // here
} else {
let others = gc
.enum_list
.enum_iter(*e)
.filter(|i| {
(**i != *item)
&& gc.enum_list.is_ancestor(*e, **i, final_enum, *item)
})
.map(|i| i.fragment())
.collect::<Vec<_>>();
format!(
"{}.!({})",
item.fragment().to_string(),
(&others[..]).join("|")
)
}
} else {
// concat var name + item
let prefix = &self.var_prefixes[var.fragment()];
// TODO there may still be some conflicts with var or enum containing '_'
format!("{}_{}_{}", prefix, e.fragment(), item.fragment())
}
}
EnumExpression::Default(_) => {
// extract current cases and build an opposite expression
if self.current_cases.is_empty() {
"any".to_string()
} else {
format!("!({})", self.current_cases.join("|"))
}
}
})
}
// TODO simplify expression and remove useless conditions for more readable cfengine
// TODO underscore escapement
// TODO how does cfengine use utf8
// TODO variables
// TODO comments and metadata
// TODO use in_class everywhere
fn format_statement(
&mut self,
gc: &AST,
st: &Statement,
id: usize,
in_class: String,
) -> Result<String> {
match st {
Statement::StateDeclaration(sd) => {
if let Some(var) = sd.outcome {
self.new_var(&var);
}
let component = match sd.metadata.get(&"component".into()) {
// TODO use static_to_string
Some(Value::String(s)) => match &s.data[0] {
PInterpolatedElement::Static(st) => st.clone(),
_ => "any".to_string(),
},
_ => "any".to_string(),
};
// TODO setup mode and output var by calling ... bundle
let param_str = map_strings_results(
sd.resource_params.iter().chain(sd.state_params.iter()),
|x| self.parameter_to_cfengine(x),
", ",
)?;
let class = self.format_class(in_class)?;
println!("state param empty ? {:#?}", sd.state_params);
let state_param = if sd.resource_params.len() > 0 {
if let Ok(param) = self.parameter_to_cfengine(&sd.resource_params[0]) {
format!(", {}", param)
} else {
"".to_string()
}
} else {
"".to_string()
};
let method_reporting_context = &format!(
" \"{}_${{report_data.directive_id}}_{}\" usebundle => _method_reporting_context(\"{}\"{})",
component,
id,
component,
state_param,
);
let method = &format!(
" \"{}_${{report_data.directive_id}}_{}\" usebundle => {}_{}({})",
component,
id,
sd.resource.fragment(),
sd.state.fragment(),
param_str,
);
// facultative, only aesthetic to align the method `=>` with the conditonal `=>` like cfengine does
let padding_spaces = str::repeat(" ", component.len() + id.to_string().len() + 43);
if class == "any" {
Ok(format!("{};\n{};\n", method_reporting_context, method))
} else {
let condition = &format!("{}if => concat(\"{}\");", padding_spaces, class);
Ok(format!(
"{},\n{}\n{},\n{}\n",
method_reporting_context,
condition,
method,
condition
))
}
}
Statement::Case(_case, vec) => {
self.reset_cases();
map_strings_results(
vec.iter(),
|(case, vst)| {
// TODO case in case
let case_exp = self.format_case_expr(gc, case)?;
map_strings_results(
vst.iter(),
|st| self.format_statement(gc, st, id, case_exp.clone()),
"",
)
},
"",
)
}
Statement::Fail(msg) => Ok(format!(
" \"method_call\" usebundle => ncf_fail({});\n",
self.parameter_to_cfengine(msg)?
)),
Statement::Log(msg) => Ok(format!(
" \"method_call\" usebundle => ncf_log({});\n",
self.parameter_to_cfengine(msg)?
)),
Statement::Return(outcome) => {
// handle end of bundle
self.return_condition = Some(match self.current_cases.last() {
None => "!any".into(),
Some(c) => format!("!({})", c),
});
Ok(if *outcome == Token::new("", "kept") {
" \"method_call\" usebundle => success();\n".into()
} else if *outcome == Token::new("", "repaired") {
" \"method_call\" usebundle => repaired();\n".into()
} else {
" \"method_call\" usebundle => error();\n".into()
})
}
Statement::Noop => Ok(String::new()),
// TODO Statement::VariableDefinition()
_ => Ok(String::new()),
}
}
fn value_to_string(&mut self, value: &Value, string_delim: bool) -> Result<String> {
let delim = if string_delim { "\"" } else { "" };
Ok(match value {
Value::String(s) => format!(
"{}{}{}",
delim,
s.data
.iter()
.map(|t| match t {
PInterpolatedElement::Static(s) => {
// replace ${const.xx}
s.replace("$", "${consr.dollar}")
.replace("\\n", "${const.n}")
.replace("\\r", "${const.r}")
.replace("\\t", "${const.t}")
}
PInterpolatedElement::Variable(v) => {
// translate variable name
format!("${{{}}}", v)
}
})
.collect::<Vec<String>>()
.join(""),
delim
),
Value::Number(_, n) => format!("{}", n),
Value::EnumExpression(_e) => unimplemented!(),
Value::List(l) => format!(
"[ {} ]",
map_strings_results(l.iter(), |x| self.value_to_string(x, true), ",")?
),
Value::Struct(s) => format!(
"{{ {} }}",
map_strings_results(
s.iter(),
|(x, y)| Ok(format!(r#""{}":{}"#, x, self.value_to_string(y, true)?)),
","
)?
),
})
}
fn generate_parameters_metadatas<'src>(&mut self, parameters: Option<Value<'src>>) -> String {
let mut params_str = String::new();
let mut get_param_field = |param: &Value, entry: &str| -> String {
if let Value::Struct(param) = ¶m {
if let Some(val) = param.get(entry) {
if let Ok(val_s) = self.value_to_string(val, false) {
return match val {
Value::String(_) => format!("{:?}: {:?}", entry, val_s),
_ => format!("{:?}: {}", entry, val_s)
}
}
}
}
"".to_owned()
};
if let Some(Value::List(parameters)) = parameters {
parameters.iter().for_each(|param| {
params_str.push_str(&format!(
"# @parameter {{ {}, {}, {} }}\n",
get_param_field(param, "name"),
get_param_field(param, "id"),
get_param_field(param, "constraints")
));
});
};
params_str
}
fn generate_ncf_metadata(&mut self, _name: &Token, resource: &ResourceDef) -> Result<String> {
let mut meta = resource.metadata.clone();
// removes parameters from meta and returns it formatted
let parameters: String = self.generate_parameters_metadatas(meta.remove(&Token::from("parameters")));
// description must be the last field
let mut map = map_hashmap_results(meta.iter(), |(n, v)| {
Ok((n.fragment(), self.value_to_string(v, false)?))
})?;
let mut metadatas = String::new();
let mut push_metadata = |entry: &str| {
if let Some(val) = map.remove(entry) {
metadatas.push_str(&format!("# @{} {}\n", entry, val));
}
};
push_metadata("name");
push_metadata("description");
push_metadata("version");
metadatas.push_str(¶meters);
for (key, val) in map.iter() {
metadatas.push_str(&format!("# @{} {}\n", key, val));
}
metadatas.push('\n');
Ok(metadatas)
}
}
impl Generator for CFEngine {
// TODO methods differ if this is a technique generation or not
fn generate(&mut self, gc: &AST, input_file: Option<&Path>, output_file: Option<&Path>, technique_metadata: bool) -> Result<()> {
let mut files: HashMap<&str, String> = HashMap::new();
// TODO add global variable definitions
for (rn, res) in gc.resources.iter() {
for (sn, state) in res.states.iter() {
// This condition actually rejects every file that is not the input filename
// therefore preventing from having an output in another directory
// Solutions: check filename rather than path, or accept everything that is not from crate root lib
let file_to_create = match input_file {
Some(filepath) => {
if filepath != Path::new(sn.file()) {
continue;
}
// can unwrap here since if input_file is Some, so does output_file (see end of compile.rs)
match output_file.unwrap().to_str() {
Some(output_filename) => output_filename,
None => sn.file(),
}
}
None => sn.file(),
};
self.reset_context();
let mut content = "# generated by rudder-lang\n".to_owned();
let fileinfo = match files.get(file_to_create) {
Some(s) => s.to_string(),
None => {
if technique_metadata {
self.generate_ncf_metadata(rn, res)?
} else {
String::new()
}
}
};
content.push_str(&fileinfo);
let mut params = res
.parameters
.iter()
.chain(state.parameters.iter())
.map(|p| p.name.fragment())
.collect::<Vec<&str>>()
.join(",");
if params.len() > 0 {
params = format!("({})", params);
}
content.push_str(&format!(
"bundle agent {}_{}{}\n",
rn.fragment(),
sn.fragment(),
params
));
content.push_str(
"{\n vars:\n \"resources_dir\" string => \"${this.promise_dirname}/resources\";\n"
);
content.push_str(" methods:\n");
for (i, st) in state.statements.iter().enumerate() {
content.push_str(&self.format_statement(gc, st, i, "any".to_string())?);
}
content.push_str("}\n");
files.insert(file_to_create, content);
}
}
if files.len() == 0 {
match output_file {
Some(filename) => File::create(filename).expect("Could not create output file"),
None => return Err(Error::User("No file to create".to_owned()))
};
}
for (name, content) in files.iter() {
let mut file =
File::create(name).expect("Could not create output file");
file.write_all(content.as_bytes())
.expect("Could not write content into output file");
}
Ok(())
}
}