• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dariusbakunas / cogrs / 13403057309

19 Feb 2025 12:48AM UTC coverage: 38.963% (-0.2%) from 39.154%
13403057309

push

github

dariusbakunas
refactor: cleanup play and add some missing fields

0 of 111 new or added lines in 7 files covered. (0.0%)

2 existing lines in 2 files now uncovered.

639 of 1640 relevant lines covered (38.96%)

1.16 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/cogrs-core/src/executor/task_queue_manager.rs
1
use crate::executor::play_iterator::PlayIterator;
2
use crate::inventory::host::Host;
3
use crate::inventory::manager::InventoryManager;
4
use crate::playbook::play::Play;
5
use crate::strategy::linear::LinearStrategy;
6
use crate::strategy::Strategy;
7
use crate::vars::manager::VariableManager;
8
use anyhow::Result;
9
use cogrs_plugins::callback::{CallbackPlugin, EventType};
10
use serde_json::Value;
11
use std::cmp::min;
12
use std::collections::HashMap;
13
use std::sync::Arc;
14

15
pub struct TaskQueueManager {
16
    forks: usize,
17
    callbacks_loaded: bool,
18
    callbacks: HashMap<EventType, Vec<Arc<dyn CallbackPlugin>>>,
19
    terminated: bool,
20
    unreachable_hosts: HashMap<String, Host>,
21
    workers: Vec<tokio::task::JoinHandle<()>>,
22
}
23

24
const DEFAULT_FORKS: usize = 5;
25

26
impl TaskQueueManager {
27
    pub fn new(forks: Option<usize>) -> Self {
×
28
        Self {
29
            callbacks: HashMap::new(),
×
30
            callbacks_loaded: false,
31
            forks: forks.unwrap_or(DEFAULT_FORKS),
×
32
            terminated: false,
33
            unreachable_hosts: HashMap::new(),
×
34
            workers: Vec::with_capacity(forks.unwrap_or(DEFAULT_FORKS)),
×
35
        }
36
    }
37

38
    pub fn get_worker(&mut self, index: usize) -> Option<&tokio::task::JoinHandle<()>> {
×
39
        self.workers.get(index)
×
40
    }
41

42
    pub fn set_worker(&mut self, index: usize, worker: tokio::task::JoinHandle<()>) {
×
43
        self.workers.insert(index, worker);
×
44
    }
45

46
    /// Iterates over the roles/tasks in a play, using the given (or default)
47
    /// strategy for queueing tasks. The default is the linear strategy, which
48
    /// operates like classic Ansible by keeping all hosts in lock-step with
49
    /// a given task (meaning no hosts move on to the next task until all hosts
50
    /// are done with the current task).
UNCOV
51
    pub async fn run(
×
52
        &mut self,
53
        play: Play,
54
        variable_manager: &VariableManager,
55
        inventory_manager: &InventoryManager,
56
    ) -> Result<()> {
57
        self.load_callbacks(
×
58
            // TODO: add logic to get callback plugin path
59
            "/Users/darius/Programming/cogrs/dist/minimal-apple_x86_64-apple-darwin",
60
        );
61
        let all_vars = variable_manager.get_vars(Some(&play), None, None, true, true);
×
62

63
        self.emit_event(EventType::PlaybookOnPlayStart, None).await;
×
64

65
        let strategy = *play.strategy();
×
66

67
        let mut play_iterator = PlayIterator::new(play);
×
68
        play_iterator.init(inventory_manager)?;
×
69

70
        let forks = min(self.forks, play_iterator.batch_size());
×
71

72
        match strategy {
×
73
            Strategy::Linear => {
74
                let mut strategy = LinearStrategy::new(self, inventory_manager, variable_manager);
×
75
                strategy.run(&mut play_iterator).await?;
×
76
            }
77
            Strategy::Free => {
78
                todo!()
79
            }
80
        }
81

82
        Ok(())
×
83
    }
84

85
    pub fn register_callback(&mut self, callback: Box<dyn CallbackPlugin>) {
×
86
        let callback: Arc<dyn CallbackPlugin> = Arc::from(callback);
×
87
        for event in callback.get_interested_events() {
×
88
            self.callbacks
×
89
                .entry(event)
90
                .or_insert_with(Vec::new)
91
                .push(callback.clone());
×
92
        }
93
    }
94

95
    pub fn get_unreachable_hosts(&self) -> &HashMap<String, Host> {
×
96
        &self.unreachable_hosts
×
97
    }
98

99
    pub fn is_terminated(&self) -> bool {
×
100
        self.terminated
×
101
    }
102

103
    fn load_callbacks(&mut self, plugin_dir: &str) {
×
104
        use libloading::{Library, Symbol};
105
        use std::fs;
106

107
        let plugin_extension = if cfg!(target_os = "windows") {
108
            "dll"
109
        } else if cfg!(target_os = "macos") {
110
            "dylib"
111
        } else {
112
            "so"
×
113
        };
114

115
        if self.callbacks_loaded {
×
116
            return;
117
        }
118

119
        for entry in fs::read_dir(plugin_dir).expect("Invalid plugin directory") {
×
120
            let path = entry.expect("Failed to read entry").path();
×
121
            if path.extension().and_then(|e| e.to_str()) == Some(plugin_extension) {
×
122
                unsafe {
123
                    let lib = Library::new(&path).expect("Failed to load plugin");
×
124

125
                    // Dynamically load the callback creation function
126
                    let create_callback: Symbol<fn() -> Box<dyn CallbackPlugin>> = lib
×
127
                        .get(b"create_plugin")
128
                        .expect("Failed to find create_plugin function");
129

130
                    let plugin = create_callback();
×
131

132
                    // Register the plugin for events
133
                    self.register_callback(plugin);
×
134
                }
135
            }
136
        }
137

138
        self.callbacks_loaded = true
×
139
    }
140

141
    pub async fn emit_event(&self, event: EventType, data: Option<Value>) {
×
142
        if let Some(callbacks) = self.callbacks.get(&event) {
×
143
            // Spawn and collect tasks
144
            let tasks: Vec<_> = callbacks
×
145
                .iter()
146
                .map(|callback| {
×
147
                    let callback = callback.clone();
×
148
                    let event = event.clone();
×
149
                    let data = data.clone();
×
150
                    tokio::spawn(async move {
×
151
                        callback.on_event(&event, data.as_ref()); // Async invocation
×
152
                    })
153
                })
154
                .collect();
155

156
            // Wait for all spawned tasks to complete
157
            for task in tasks {
×
158
                if let Err(err) = task.await {
×
159
                    eprintln!("Callback task panicked: {:?}", err);
×
160
                }
161
            }
162
        }
163
    }
164

165
    pub fn forks(&self) -> usize {
×
166
        self.forks
×
167
    }
168
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc