1#[allow(unused_imports)]
2#[macro_use]
3extern crate origen;
4#[macro_use]
5extern crate origen_metal;
6
7use pyapi_metal;
8
9#[macro_use]
10mod macros;
11
12mod current_command;
13mod dut;
14mod extensions;
15mod file_handler;
16mod infrastructure;
17mod meta;
18mod model;
19#[macro_use]
20mod pins;
21mod registers;
22mod services;
23#[macro_use]
24mod timesets;
25mod _frontend;
26mod _helpers;
27mod application;
28mod producer;
29mod prog_gen;
30mod standard_sub_blocks;
31pub mod tester;
32#[macro_use]
33mod utility;
34mod plugins;
35
36use crate::registers::bit_collection::BitCollection;
37use num_bigint::BigUint;
38use om::lazy_static::lazy_static;
39use origen::core::status::DependencySrc;
40use origen::{clean_target, Dut, Error, Operation, Result, Value, ORIGEN_CONFIG, STATUS, TEST};
41use origen_metal as om;
42use origen_metal::FLOW;
43use paste::paste;
44use pyapi_metal::{pypath, runtime_error};
45use pyo3::prelude::*;
46use pyo3::types::{PyAny, PyBytes, PyDict};
47use pyo3::wrap_pyfunction;
48use std::path::{Path, PathBuf};
49use std::str::FromStr;
50use std::sync::MutexGuard;
51use utility::location::Location;
52
53pub mod built_info {
54 include!(concat!(env!("OUT_DIR"), "/built.rs"));
56}
57
58#[pymodule]
59fn _origen(py: Python, m: &PyModule) -> PyResult<()> {
61 m.add_wrapped(wrap_pyfunction!(initialize))?;
62 m.add_wrapped(wrap_pyfunction!(status))?;
63 m.add_wrapped(wrap_pyfunction!(version))?;
64 m.add_wrapped(wrap_pyfunction!(config))?;
65 m.add_wrapped(wrap_pyfunction!(config_metadata))?;
66 m.add_wrapped(wrap_pyfunction!(app_config))?;
67 m.add_wrapped(wrap_pyfunction!(is_app_present))?;
68 m.add_wrapped(wrap_pyfunction!(clean_mode))?;
69 m.add_wrapped(wrap_pyfunction!(target_file))?;
70 m.add_wrapped(wrap_pyfunction!(test))?;
71 m.add_wrapped(wrap_pyfunction!(test_ast))?;
72 m.add_wrapped(wrap_pyfunction!(flow))?;
73 m.add_wrapped(wrap_pyfunction!(flow_ast))?;
74 m.add_wrapped(wrap_pyfunction!(output_directory))?;
75 m.add_wrapped(wrap_pyfunction!(website_output_directory))?;
76 m.add_wrapped(wrap_pyfunction!(website_source_directory))?;
77 m.add_wrapped(wrap_pyfunction!(prepare_for_target_load))?;
78 m.add_wrapped(wrap_pyfunction!(start_new_test))?;
79 m.add_wrapped(wrap_pyfunction!(unhandled_error_count))?;
80 m.add_wrapped(wrap_pyfunction!(set_output_dir))?;
81 m.add_wrapped(wrap_pyfunction!(set_reference_dir))?;
82 m.add_wrapped(wrap_pyfunction!(exit_pass))?;
83 m.add_wrapped(wrap_pyfunction!(exit_fail))?;
84 m.add_wrapped(wrap_pyfunction!(enable_debug))?;
85 m.add_wrapped(wrap_pyfunction!(set_operation))?;
86 m.add_wrapped(wrap_pyfunction!(boot_users))?;
87
88 dut::define(py, m)?;
89 tester::define(py, m)?;
90 application::define(py, m)?;
91 producer::define(py, m)?;
92 services::define(py, m)?;
93 utility::define(py, m)?;
94 standard_sub_blocks::define(py, m)?;
95 prog_gen::define(py, m)?;
96 file_handler::define(py, m)?;
97 plugins::define(py, m)?;
98 extensions::define(py, m)?;
99 current_command::define(py, m)?;
100 infrastructure::define(py, m)?;
101
102 pyapi_metal::define(py, m)?;
105 m.setattr(current_command::ATTR_NAME, py.None())?;
106 Ok(())
107}
108
109fn extract_value<'a>(
110 bits_or_val: &PyAny,
111 size: Option<u32>,
112 dut: &'a MutexGuard<Dut>,
113) -> Result<Value<'a>> {
114 let bits = bits_or_val.extract::<PyRef<BitCollection>>();
115 if bits.is_ok() {
116 return Ok(Value::Bits(bits.unwrap().materialize(dut)?, size));
117 }
118 let value = bits_or_val.extract::<BigUint>();
119 if value.is_ok() {
120 return match size {
121 Some(x) => Ok(Value::Data(value.unwrap(), x)),
122 None => Err(Error::new(
123 "A size argument must be supplied along with a data value",
124 )),
125 };
126 }
127 Err(Error::new("Illegal bits/value argument"))
128}
129
130fn unpack_transaction_options(
133 trans: &mut origen::Transaction,
134 kwargs: Option<&PyDict>,
135) -> PyResult<()> {
136 if let Some(opts) = kwargs {
137 if let Some(address) = opts.get_item("address")? {
138 trans.address = Some(address.extract::<BigUint>()?);
139 }
140 if let Some(w) = opts.get_item("address_width")? {
141 trans.address_width = Some(w.extract::<usize>()?);
142 }
143 if let Some(_mask) = opts.get_item("mask")? {
144 panic!("option not supported yet!");
145 }
146 if let Some(_overlay) = opts.get_item("overlay")? {
147 panic!("option not supported yet!");
148 }
149 if let Some(_overlay_str) = opts.get_item("overlay_str")? {
150 panic!("option not supported yet!");
151 }
152 }
153 Ok(())
154}
155
156fn unpack_capture_kwargs(
157 dut: &origen::Dut,
158 cap_trans: &mut origen::Capture,
159 kwargs: Option<&PyDict>,
160 pins_allowed: bool,
161 cycles_allowed: bool,
162) -> PyResult<()> {
163 if let Some(opts) = kwargs {
164 if let Some(sym) = opts.get_item("symbol")? {
165 cap_trans.symbol = Some(sym.extract::<String>()?);
166 }
167 if let Some(enables) = opts.get_item("mask")? {
168 cap_trans.enables = Some(enables.extract::<BigUint>()?);
169 }
170 if let Some(cycles) = opts.get_item("cycles")? {
171 if cycles_allowed {
172 cap_trans.cycles = Some(cycles.extract::<usize>()?);
173 } else {
174 return runtime_error!("'cycles' capture option is not valid in this context");
175 }
176 }
177 if let Some(pins) = opts.get_item("pins")? {
178 if pins_allowed {
179 let pins_vec = pins.extract::<Vec<&PyAny>>()?;
180 cap_trans.pin_ids = Some(pins::vec_to_ppin_ids(&dut, pins_vec)?);
181 } else {
182 return runtime_error!("'pins' capture option is not valid in this context");
183 }
184 }
185 }
186 Ok(())
187}
188
189fn unpack_transaction_kwargs(trans: &mut origen::Transaction, kwargs: &PyDict) -> PyResult<()> {
192 if let Some(mask) = kwargs.get_item("mask")? {
193 if let Ok(big_mask) = mask.extract::<num_bigint::BigUint>() {
194 trans.bit_enable = big_mask;
195 } else {
196 return crate::type_error!("Could not extract kwarg 'mask' as an integer");
197 }
198 }
199 if let Some(overlay) = kwargs.get_item("overlay")? {
200 let overlay_mask;
201 let overlay_symbol;
202 let overlay_cycles;
203 if let Some(mask) = kwargs.get_item("overlay_mask")? {
204 if let Ok(big_mask) = mask.extract::<num_bigint::BigUint>() {
205 overlay_mask = Some(big_mask);
206 } else {
207 return crate::type_error!("Could not extract kwarg 'overlay_mask' as an integer");
208 }
209 } else {
210 if let Some(ovl) = trans.overlay.as_ref() {
211 overlay_mask = ovl.enables.clone();
212 } else {
213 overlay_mask = None;
214 }
215 }
216 if let Some(s) = kwargs.get_item("overlay_symbol")? {
217 if let Ok(sym) = s.extract::<String>() {
218 overlay_symbol = Some(sym);
219 } else {
220 return crate::type_error!("Could not extract kwarg 'overlay_symbol' as a String");
221 }
222 } else {
223 if let Some(ovl) = trans.overlay.as_ref() {
224 overlay_symbol = ovl.symbol.clone();
225 } else {
226 overlay_symbol = None;
227 }
228 }
229 if let Some(c) = kwargs.get_item("overlay_cycles")? {
230 if let Ok(i) = c.extract::<usize>() {
231 overlay_cycles = Some(i);
232 } else {
233 return crate::type_error!(
234 "Could not extract kwarg 'overlay_cycles' as an Integer"
235 );
236 }
237 } else {
238 if let Some(ovl) = trans.overlay.as_ref() {
239 overlay_cycles = ovl.cycles.clone();
240 } else {
241 overlay_cycles = None;
242 }
243 }
244 if let Ok(should_overlay) = overlay.extract::<bool>() {
245 if should_overlay {
246 trans.apply_overlay(None, overlay_symbol, overlay_mask)?;
248 }
249 } else if let Ok(overlay_name) = overlay.extract::<String>() {
250 trans.apply_overlay(Some(overlay_name), overlay_symbol, overlay_mask)?;
251 if overlay_cycles.is_some() {
252 trans.overlay.as_mut().unwrap().cycles = overlay_cycles;
253 }
254 } else {
255 return crate::type_error!(
256 "Could not extract kwarg 'overlay' as either a bool or a string"
257 );
258 }
259 }
260 Ok(())
261}
262
263fn resolve_transaction(
268 dut: &std::sync::MutexGuard<origen::Dut>,
269 trans: &PyAny,
270 action: Option<origen::TransactionAction>,
271 kwargs: Option<&PyDict>,
272) -> PyResult<origen::Transaction> {
273 let mut width = 32;
274 if let Some(opts) = kwargs {
275 if let Some(w) = opts.get_item("width")? {
276 width = w.extract::<u32>()?;
277 }
278 }
279 let value = extract_value(trans, Some(width), &dut)?;
280 let mut trans;
281 if let Some(a) = action {
282 match a {
283 origen::TransactionAction::Write => trans = value.to_write_transaction(&dut)?,
284 origen::TransactionAction::Verify => trans = value.to_verify_transaction(&dut)?,
285 origen::TransactionAction::Capture => {
286 trans = value.to_capture_transaction(&dut)?;
287 unpack_capture_kwargs(
288 &dut,
289 &mut trans.capture.as_mut().unwrap(),
290 kwargs,
291 false,
292 false,
293 )?;
294 return Ok(trans);
295 }
296 _ => {
297 return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!(
298 "Resolving transactions for {:?} is not supported",
299 a
300 )))
301 }
302 }
303 } else {
304 trans = value.to_write_transaction(&dut)?;
305 trans.action = None;
306 }
307
308 if let Some(opts) = kwargs {
309 if let Some(address) = opts.get_item("address")? {
310 if !address.is_none() {
311 trans.address = Some(address.extract::<BigUint>()?);
312 }
313 }
314 if let Some(w) = opts.get_item("address_width")? {
315 trans.address_width = Some(w.extract::<usize>()?);
316 }
317 if let Some(_mask) = opts.get_item("mask")? {
318 panic!("option not supported yet!");
319 }
320 if let Some(_overlay) = opts.get_item("overlay")? {
321 panic!("option not supported yet!");
322 }
323 if let Some(_overlay_str) = opts.get_item("overlay_str")? {
324 panic!("option not supported yet!");
325 }
326 }
327 Ok(trans)
328}
329
330#[pyfunction]
332fn exit_fail() -> PyResult<()> {
333 exit_fail!();
334}
335
336#[pyfunction]
338fn exit_pass() -> PyResult<()> {
339 exit_pass!();
340}
341
342fn origen_mod_path() -> PyResult<PathBuf> {
343 Python::with_gil(|py| {
344 let p = PathBuf::from(
347 py.import("importlib.util")?
348 .call_method1("find_spec", ("_origen",))?
349 .getattr("origin")?
350 .extract::<String>()?,
351 );
352 Ok(p.parent().unwrap().to_path_buf())
353 })
354}
355
356#[pyfunction]
358#[pyo3(signature=(log_verbosity, verbosity_keywords, cli_location, cli_version, fe_pkg_loc, fe_exe_loc, invocation))]
359fn initialize(
360 py: Python,
361 log_verbosity: Option<u8>,
362 verbosity_keywords: Vec<String>,
363 cli_location: Option<String>,
364 cli_version: Option<String>,
365 fe_pkg_loc: Option<PathBuf>,
366 fe_exe_loc: Option<PathBuf>,
367 invocation: Option<(String, Option<PathBuf>)>,
368) -> PyResult<()> {
369 origen::initialize(
370 log_verbosity,
371 verbosity_keywords,
372 cli_location,
373 cli_version,
374 fe_pkg_loc,
375 fe_exe_loc,
376 );
377 origen::STATUS.update_other_build_info("pyapi_version", built_info::PKG_VERSION)?;
378 if let Some(invoc) = invocation {
379 match DependencySrc::try_from(invoc) {
380 Ok(d) => origen::STATUS.set_dependency_src(Some(d)),
381 Err(e) => log_error!("{}", e.to_string()),
382 }
383 }
384 origen::FRONTEND
385 .write()
386 .unwrap()
387 .set_frontend(Box::new(_frontend::Frontend::new()))?;
388
389 if let Some(app) = &STATUS.app {
390 origen::STATUS.set_in_origen_core_app(origen_mod_path()? == app.root);
391 } else {
392 origen::STATUS.set_in_origen_core_app(false);
393 }
394
395 use crate::pyapi_metal::prelude::frontend::*;
396 with_mut_py_data_stores(|py, mut py_ds| {
397 let pymod = PyModule::import(py, "_origen")?;
399 py_ds.add_category(
400 py,
401 "ldaps",
402 Some(pymod.getattr("utility")?.getattr("boot_ldaps")?.into()),
403 Some(true),
404 )?;
405 Ok(())
406 })?;
407 boot_users(py)?;
408 match origen::setup_sessions() {
409 Ok(_) => {}
410 Err(e) => log_error!(
411 "Failed to setup user and application sessions. Received error: \n{}",
412 e
413 ),
414 }
415 Ok(())
416}
417
418#[pyfunction]
419fn set_output_dir(dir: &str) -> PyResult<()> {
421 STATUS.set_output_dir(Path::new(dir));
422 Ok(())
423}
424
425#[pyfunction]
426fn set_reference_dir(dir: &str) -> PyResult<()> {
428 STATUS.set_reference_dir(Path::new(dir));
429 Ok(())
430}
431
432#[pyfunction]
433fn enable_debug() -> PyResult<()> {
435 STATUS.set_debug_enabled(true);
436 Ok(())
437}
438
439#[pyfunction]
440fn set_operation(name: String) -> PyResult<()> {
442 match Operation::from_str(&name) {
443 Ok(op) => {
444 STATUS.set_operation(op);
445 Ok(())
446 }
447 Err(e) => Err(PyErr::from(Error::new(&e))),
448 }
449}
450
451#[pyfunction]
452fn unhandled_error_count() -> PyResult<usize> {
457 Ok(STATUS.unhandled_error_count())
458}
459
460#[pyfunction]
462fn test() -> PyResult<()> {
463 println!("{}", TEST.to_string());
464 Ok(())
465}
466
467#[pyfunction]
469fn test_ast() -> PyResult<Vec<u8>> {
470 Ok(TEST.to_pickle())
471}
472
473#[pyfunction]
475fn flow() -> PyResult<()> {
476 println!("{}", FLOW.to_string());
477 Ok(())
478}
479
480#[pyfunction]
482fn flow_ast() -> PyResult<Vec<u8>> {
483 Ok(FLOW.to_pickle())
484}
485
486#[pyfunction]
489fn status(py: Python) -> PyResult<PyObject> {
490 let ret = PyDict::new(py);
491 let _ = ret.set_item("is_app_present", &STATUS.is_app_present);
493 if let Some(app) = origen::app() {
494 let _ = ret.set_item("root", format!("{}", app.root.display()));
495 }
496 let _ = ret.set_item("origen_version", &STATUS.origen_version.to_string());
497 let _ = ret.set_item("home", format!("{}", STATUS.home.display()));
498 let _ = ret.set_item("on_windows", om::running_on_windows());
499 ret.set_item(
500 "origen_core_support_version",
501 STATUS.origen_core_support_version.to_string(),
502 )?;
503 ret.set_item(
504 "origen_metal_backend_version",
505 STATUS.origen_metal_backend_version.to_string(),
506 )?;
507 ret.set_item(
508 "other_build_info",
509 pyapi_metal::_helpers::map_to_pydict(py, &mut STATUS.other_build_info().iter())?,
510 )?;
511 ret.set_item(
512 "cli_version",
513 match STATUS.cli_version() {
514 Some(v) => Some(v.to_string()).to_object(py),
515 None => py.None(),
516 },
517 )?;
518 ret.set_item(
519 "cli_location",
520 match STATUS.cli_location() {
521 Some(path) => pypath!(py, path.display()),
522 None => py.None(),
523 },
524 )?;
525 ret.set_item(
526 "is_app_in_origen_dev_mode",
527 STATUS.is_app_in_origen_dev_mode,
528 )?;
529 ret.set_item("in_origen_core_app", STATUS.in_origen_core_app())?;
530
531 infrastructure::pyproject::populate_status(py, ret)?;
533 Ok(ret.into())
534}
535
536#[pyfunction]
538fn version() -> PyResult<String> {
539 Ok(
540 origen_metal::utils::version::Version::new_pep440(&STATUS.origen_version.to_string())?
541 .to_string(),
542 )
543}
544
545#[pyfunction]
547fn config(py: Python) -> PyResult<PyObject> {
548 let ret = PyDict::new(py);
549 let _ = ret.set_item("python_cmd", &ORIGEN_CONFIG.python_cmd);
551 let _ = ret.set_item("pkg_server", &ORIGEN_CONFIG.pkg_server);
552 let _ = ret.set_item("pkg_server_push", &ORIGEN_CONFIG.pkg_server_push);
553 let _ = ret.set_item("pkg_server_pull", &ORIGEN_CONFIG.pkg_server_pull);
554 let _ = ret.set_item("some_val", &ORIGEN_CONFIG.some_val);
555 Ok(ret.into())
556}
557
558#[pyfunction]
559fn config_metadata<'py>(py: Python<'py>) -> PyResult<&'py PyDict> {
560 let m = origen::origen_config_metadata();
561 let retn = PyDict::new(py);
562 retn.set_item(
563 "files",
564 m.files
565 .iter()
566 .map(|p| Ok(pypath!(py, p.display())))
567 .collect::<PyResult<Vec<PyObject>>>()?,
568 )?;
569 Ok(retn)
570}
571
572#[pyfunction]
573fn is_app_present() -> PyResult<bool> {
574 Ok(STATUS.is_app_present)
575}
576
577#[pyfunction]
579fn app_config(py: Python) -> PyResult<Option<PyObject>> {
580 if let Some(app) = origen::app() {
581 let ret = PyDict::new(py);
582 let _ = app.with_config(|config| {
583 let _ = ret.set_item("name", &config.name);
584 let _ = ret.set_item("target", &config.target);
585 let _ = ret.set_item("mode", &config.mode);
586 let _ = ret.set_item("__output_directory__", &config.output_directory);
587 let _ = ret.set_item(
588 "__website_output_directory__",
589 &config.website_output_directory,
590 );
591 let _ = ret.set_item(
592 "__website_source_directory__",
593 &config.website_source_directory,
594 );
595 let _ = ret.set_item(
596 "website_release_location",
597 match &config.website_release_location {
598 Some(loc) => Py::new(
599 py,
600 Location {
601 location: (*loc).clone(),
602 },
603 )
604 .unwrap()
605 .to_object(py),
606 None => py.None(),
607 },
608 );
609 let _ = ret.set_item("website_release_name", &config.website_release_name);
610 let _ = ret.set_item("release", &config.release);
611 let program_generation = PyDict::new(py);
612 let _ = program_generation.set_item(
613 "flow_visualization",
614 config.program_generation.flow_visualization,
615 );
616 let _ = ret.set_item("program_generation", program_generation);
617 Ok(())
618 });
619 Ok(Some(ret.into()))
620 } else {
621 Ok(None)
622 }
623}
624
625#[pyfunction]
628fn clean_mode(name: &str) -> PyResult<String> {
629 let c = origen::clean_mode(name);
630 Ok(c)
631}
632
633#[pyfunction]
634fn target_file(name: &str, dir: &str) -> PyResult<String> {
638 let c = clean_target!(name, dir, true);
639 Ok(c)
640}
641
642#[pyfunction]
643fn output_directory(py: Python) -> PyResult<PyObject> {
644 let dir = origen::STATUS.output_dir();
645 Ok(pypath!(py, dir.display()))
646}
647
648#[pyfunction]
649fn website_output_directory(py: Python) -> PyResult<PyObject> {
650 let dir = origen::app().unwrap().website_output_directory();
651 Ok(pypath!(py, dir.display()))
652}
653
654#[pyfunction]
655fn website_source_directory(py: Python) -> PyResult<PyObject> {
656 let dir = origen::app().unwrap().website_source_directory();
657 Ok(pypath!(py, dir.display()))
658}
659
660#[pyfunction]
661fn prepare_for_target_load() -> PyResult<()> {
663 origen::prepare_for_target_load()?;
664 Ok(())
665}
666
667#[pyfunction]
668fn start_new_test(name: Option<String>) -> PyResult<()> {
670 origen::start_new_test(name);
671 Ok(())
672}
673
674pub fn pickle(py: Python, object: &PyAny) -> PyResult<Vec<u8>> {
675 let pickle = PyModule::import(py, "pickle")?;
676 pickle
677 .getattr("dumps")?
678 .call1((object,))?
679 .extract::<Vec<u8>>()
680}
681
682pub fn depickle<'a>(py: Python<'a>, object: &Vec<u8>) -> PyResult<&'a PyAny> {
683 let pickle = PyModule::import(py, "pickle")?;
684 let bytes = PyBytes::new(py, object);
685 pickle.getattr("loads")?.call1((bytes,))
686}
687
688pub fn with_pycallbacks<T, F>(mut func: F) -> PyResult<T>
689where
690 F: FnMut(Python, &PyAny) -> PyResult<T>,
691{
692 Python::with_gil(|py| {
693 let pycallbacks = py.import("origen.callbacks")?;
694 func(py, pycallbacks)
695 })
696}
697
698pub fn get_full_class_name(obj: &PyAny) -> PyResult<String> {
699 let cls = obj.getattr("__class__")?;
700 let mut n = cls.getattr("__module__")?.extract::<String>()?;
701 n.push_str(&format!(
702 ".{}",
703 cls.getattr("__qualname__")?.extract::<String>()?
704 ));
705 Ok(n)
706}
707
708#[pyfunction]
710pub fn boot_users(py: Python) -> PyResult<pyapi_metal::framework::users::Users> {
711 lazy_static! {
712 static ref BASE_MSG: &'static str = "Encountered an error when initializing users";
713 }
714
715 log_trace!("Initializing Users...");
716 if let Some(r) = &ORIGEN_CONFIG.session__user_root {
717 log_trace!("Setting user session root to {}", r);
718 let mut users = om::users_mut();
719 let sc = users.default_session_config_mut();
720 sc.root = Some(PathBuf::from(r));
721 }
722
723 let users = pyapi_metal::framework::users::users()?;
724
725 if let Some(pw_cache_option) = &crate::ORIGEN_CONFIG.user__password_cache_option {
726 match users.set_default_password_cache_option(Some(pw_cache_option)) {
727 Ok(_) => {}
728 Err(e) => {
729 om::log_error!(
730 "{}: Error encountered updating default password cache option",
731 *BASE_MSG
732 );
733 om::log_error!("{}", e);
734 }
735 }
736 }
737
738 if let Some(dsets) = &crate::ORIGEN_CONFIG.user__datasets {
739 let mut replace_default = true;
740 for (dn, config) in dsets {
741 log_trace!("Adding user dataset {}", dn);
742 match config.try_into() {
743 Ok(om_config) => {
744 match pyapi_metal::framework::users::UserDatasetConfig::new_py(py, om_config) {
745 Ok(py_config) => {
746 if replace_default {
747 match users.override_default_dataset(
748 dn,
749 Some(py_config.into_py(py).as_ref(py)),
750 ) {
751 Ok(_) => {
752 replace_default = false;
753 }
754 Err(e) => {
755 om::log_error!("{}: Error encountered updating default dataset with config '{}'", *BASE_MSG, dn);
756 om::log_error!("{}", e);
757 }
758 }
759 } else {
760 match users.add_dataset(
761 dn,
762 Some(
763 pyapi_metal::framework::users::UserDatasetConfig::new_py(
764 py,
765 config.try_into()?,
766 )?
767 .into_py(py)
768 .as_ref(py),
769 ),
770 false,
771 ) {
772 Ok(_) => {}
773 Err(e) => {
774 om::log_error!(
775 "{}: Error encountered adding dataset '{}'",
776 *BASE_MSG,
777 dn
778 );
779 om::log_error!("{}", e);
780 }
781 }
782 }
783 }
784 Err(e) => {
785 om::log_error!(
787 "{}: Error encountered processing dataset config for '{}'",
788 *BASE_MSG,
789 dn
790 );
791 om::log_error!("{}", e);
792 }
793 }
794 }
795 Err(e) => {
796 om::log_error!(
797 "{}: Error encountered processing dataset config for '{}'",
798 *BASE_MSG,
799 dn
800 );
801 om::log_error!("{}", e);
802 }
803 }
804 }
805 }
806
807 if let Some(hierarchy) = &crate::ORIGEN_CONFIG.user__data_lookup_hierarchy {
809 match users.apply_data_lookup_hierarchy(hierarchy.to_owned()) {
810 Ok(_) => {}
811 Err(e) => {
812 om::log_error!(
813 "{}: Error encountered setting the default lookup hierarchy",
814 *BASE_MSG
815 );
816 om::log_error!("{}", e);
817 om::log_error!("Forcing empty dataset lookup hierarchy...");
818 users.apply_data_lookup_hierarchy(vec![])?;
819 }
820 }
821 } else {
822 if crate::ORIGEN_CONFIG.user__datasets.is_some()
823 && crate::ORIGEN_CONFIG.user__datasets.as_ref().unwrap().len() > 1
824 {
825 users.apply_data_lookup_hierarchy(vec![])?;
828 }
829 }
830
831 for (m, ds) in &crate::ORIGEN_CONFIG.user__dataset_motives {
833 match users.add_motive(m, ds, false) {
834 Ok(_) => {}
835 Err(e) => {
836 om::log_error!(
837 "{}: Error encountered adding dataset motive '{}'",
838 *BASE_MSG,
839 m
840 );
841 om::log_error!("{}", e);
842 }
843 }
844 }
845
846 macro_rules! log_error__set_field_for_default_user {
847 ($u:expr, $field:tt, $val:expr, $name:expr ) => {
848 paste! {
849 match $u.[<set_ $field>]($val) {
850 Ok(_) => {},
851 Err(e) => {
852 log_error!("{}: Failed to initialize default user '{}'", *BASE_MSG, $name);
853 log_error!(" Failed to set field '{}'", stringify!($field));
854 log_error!("{}", e);
855 log_error!("Bailing on initializing default user '{}'", $name);
856 continue;
857 }
858 }
859 }
860 };
861 }
862
863 for (name, config) in &crate::ORIGEN_CONFIG.default_users {
865 match users.add(name, config.auto_populate) {
866 Ok(u) => {
867 if let Some(s) = config.should_validate_passwords {
868 log_error__set_field_for_default_user!(
869 u,
870 should_validate_passwords,
871 Some(s),
872 name
873 )
874 }
875 if let Some(uname) = &config.username {
876 log_error__set_field_for_default_user!(
877 u,
878 username,
879 Some(uname.to_owned()),
880 name
881 );
882 }
883 if let Some(pw) = &config.password {
884 log_error__set_field_for_default_user!(u, password, Some(pw.to_owned()), name);
885 }
886
887 if let Some(e) = &config.email {
888 log_error__set_field_for_default_user!(u, email, Some(e.to_owned()), name);
889 }
890 if let Some(f) = &config.first_name {
891 log_error__set_field_for_default_user!(u, first_name, Some(f.to_owned()), name);
892 }
893 if let Some(l) = &config.last_name {
894 log_error__set_field_for_default_user!(u, last_name, Some(l.to_owned()), name);
895 }
896 }
897 Err(e) => {
898 om::log_error!(
899 "{}: Failed to initialize default user '{}'",
900 *BASE_MSG,
901 name
902 );
903 log_error!("{}", e);
904 }
905 }
906 }
907
908 if let Some(func) = &crate::ORIGEN_CONFIG.user__current_user_lookup_function {
910 users.set_lookup_current_id_function(Some(
911 pyapi_metal::_helpers::get_qualified_attr(&func)?.as_ref(py),
912 ))?;
913 }
914
915 if ORIGEN_CONFIG
917 .initial_user
918 .as_ref()
919 .map_or(true, |u| u.initialize.unwrap_or(true))
920 {
921 match users.lookup_current_id(true) {
922 Ok(_) => {
923 if ORIGEN_CONFIG
924 .initial_user
925 .as_ref()
926 .map_or(true, |u| u.init_home_dir.unwrap_or(true))
927 {
928 match users.current_user() {
929 Ok(usr) => match usr {
930 Some(u) => match u.set_home_dir(None) {
931 Ok(_) => {}
932 Err(e) => {
933 log_error!(
934 "{}: Failed to lookup current user's home directory",
935 *BASE_MSG
936 );
937 log_error!("{}", e);
938 }
939 },
940 None => {
941 log_error!("{}: Failed to lookup current user", *BASE_MSG);
942 }
943 },
944 Err(e) => {
945 log_error!("{}: Failed to lookup current user", *BASE_MSG);
946 log_error!("{}", e);
947 }
948 }
949 }
950 }
951 Err(e) => {
952 log_error!("{}: Failed to lookup current user", *BASE_MSG);
953 log_error!("{}", e);
954 }
955 }
956 } else {
957 log_trace!("Bypassing current user initialization.");
958 }
959 Ok(users)
960}
961
962#[cfg(test)]
963mod tests {
964 use super::*;
965
966 #[test]
967 fn initializes_module_and_interoperates_with_pin_actions() -> PyResult<()> {
968 Python::with_gil(|py| {
969 let module = PyModule::new(py, "_origen")?;
970 _origen(py, module)?;
971
972 let pin_actions = module
973 .getattr("dut")?
974 .getattr("pins")?
975 .getattr("PinActions")?;
976 let created = pin_actions.call1(("1",))?;
977 let class_method = pin_actions.call_method0("DriveHigh")?;
978
979 assert!(created.eq(class_method)?);
980 let combined = pin_actions.call1((class_method,))?;
981 assert!(combined.eq(created)?);
982 Ok(())
983 })
984 }
985}