Files
adcs_api
cbor_protocol
channel_protocol
clyde_3g_eps_api
clyde_3g_eps_service
comms_service
db_test
eps_api
example_rust_c_service
example_rust_service
extern_lib
file_protocol
file_service
iobc_supervisor_service
isis_ants
isis_ants_api
isis_ants_service
isis_imtq_api
isis_iobc_supervisor
kubos_app
kubos_app_service
kubos_build_helper
kubos_file_client
kubos_service
kubos_shell_client
kubos_system
kubos_telemetry_db
large_download
large_upload
local_comms_service
mai400
mai400_api
mai400_service
monitor_service
novatel_oem6_api
novatel_oem6_service
nsl_duplex_d2
nsl_duplex_d2_comms_service
obc_hs
radio_api
rust_i2c
rust_mission_app
rust_uart
scheduler_service
serial_comms_service
shell_protocol
shell_service
telemetry_service
uart_comms_client
udp_client
utils
  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
/*
 * Copyright (C) 2019 Kubos Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//!
//! Structures and functions concerning the actual running of a schedule
//!

use crate::error::SchedulerError;
use crate::mode::{
    activate_mode, create_mode, get_active_mode, get_available_modes, is_mode_active,
};
use crate::task_list::{get_mode_task_lists, validate_task_list, TaskList};
use log::{error, info, warn};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;

pub static DEFAULT_SCHEDULES_DIR: &str = "/home/system/etc/schedules";
pub static SAFE_MODE: &str = "safe";

// Handle to primitives controlling scheduler runtime context
#[derive(Clone)]
pub struct SchedulerHandle {
    // Handle to thread running scheduler runtime
    pub thread_handle: Arc<Mutex<thread::JoinHandle<()>>>,
    // Sender for stopping scheduler runtime/thread
    pub stopper: Sender<()>,
}

#[derive(Clone)]
pub struct Scheduler {
    // Path to directory where schedules/modes are stored
    pub scheduler_dir: String,
    // URL of App Service - for start app queries
    app_service_url: String,
    // Map of active task list names and scheduler handles. This allows us to
    // start/stop tasks associated with individual task lists
    scheduler_map: Arc<Mutex<HashMap<String, SchedulerHandle>>>,
}

impl Scheduler {
    // Create new Scheduler
    pub fn new(sched_dir: &str, app_service_url: &str) -> Result<Scheduler, SchedulerError> {
        // Convert sched_dir to an absolute path
        let sched_dir_path = Path::new(sched_dir);
        let scheduler_dir = if sched_dir_path.is_relative() {
            let cwd = env::current_dir().map_err(|e| SchedulerError::GenericError {
                err: format!("Current working directory invalid: {}", e),
            })?;
            let sched_path = cwd.join(sched_dir_path);

            sched_path
                .to_str()
                .ok_or_else(|| SchedulerError::GenericError {
                    err: format!(
                        "Failed to create absolute schedules_dir path: {:?}",
                        sched_path
                    ),
                })?
                .to_owned()
        } else {
            sched_dir.to_owned()
        };

        Ok(Scheduler {
            scheduler_dir,
            scheduler_map: Arc::new(Mutex::new(HashMap::<String, SchedulerHandle>::new())),
            app_service_url: app_service_url.to_owned(),
        })
    }

    // Ensure that conditions are good for starting the scheduler
    pub fn init(&self) -> Result<(), SchedulerError> {
        if !Path::new(&self.scheduler_dir).is_dir() {
            if let Err(e) = fs::create_dir(&self.scheduler_dir) {
                return Err(SchedulerError::CreateError {
                    err: e.to_string(),
                    path: self.scheduler_dir.to_owned(),
                });
            }
        }

        match get_active_mode(&self.scheduler_dir) {
            // If we get some directory and no error, then do nothing
            Ok(Some(_)) => {}
            // Otherwise if we got an error OR if we found no active directory
            // then attempt to create and/or activate safe mode
            _ => {
                match get_available_modes(&self.scheduler_dir, Some(SAFE_MODE.to_owned())) {
                    // If this list isn't empty then we know safe mode exists
                    Ok(ref list) if !list.is_empty() => {}
                    // If the list is empty OR there was any sort of error retrieving it
                    // then attempt to create the safe mode
                    _ => {
                        create_mode(&self.scheduler_dir, SAFE_MODE)?;
                    }
                }
                activate_mode(&self.scheduler_dir, SAFE_MODE)?;
            }
        }
        Ok(())
    }

    // Checks if task list is in active mode and schedules tasks if needed
    pub fn check_start_task_list(
        &self,
        raw_name: &str,
        raw_mode: &str,
    ) -> Result<(), SchedulerError> {
        let name = raw_name.to_lowercase();
        let mode = raw_mode.to_lowercase();

        if is_mode_active(&self.scheduler_dir, &mode) {
            let list_path = format!("{}/{}/{}.json", self.scheduler_dir, mode, name);
            let list_path = Path::new(&list_path);
            let list = TaskList::from_path(&list_path)?;

            Ok(self.start_task_list(list)?)
        } else {
            Ok(())
        }
    }

    // Schedules tasks associated with task list
    fn start_task_list(&self, list: TaskList) -> Result<(), SchedulerError> {
        let mut schedules_map = self.scheduler_map.lock().unwrap();
        let scheduler_handle = list.schedule_tasks(&self.app_service_url)?;
        schedules_map.insert(list.filename, scheduler_handle);
        Ok(())
    }

    // Iterate through the active mode and kick off scheduling tasks
    // Validation and error returning is done here and caught in
    // start() for fail over.
    fn check_start(&self, mode_path: &str) -> Result<(), SchedulerError> {
        for list in get_mode_task_lists(&mode_path)? {
            match validate_task_list(&list.path) {
                Err(SchedulerError::TaskTimeError { description, .. }) => warn!(
                    "Found task '{}' in task list '{}' with out of bounds time",
                    description, list.filename
                ),
                Ok(()) => {}
                Err(e) => return Err(e),
            }
            self.start_task_list(list)?;
        }
        Ok(())
    }

    // Iterate through the active mode and kick off scheduling tasks
    pub fn start(&self) -> Result<(), SchedulerError> {
        if let Some(active_mode) = get_active_mode(&self.scheduler_dir)? {
            if let Err(err) = self.check_start(&active_mode.path) {
                if active_mode.name == SAFE_MODE {
                    error!("Failed to start safe mode: {}", err);
                    panic!("Failed to start safe mode: {}", err);
                } else {
                    error!(
                        "Failed to start mode '{}', failing over: {}",
                        active_mode.name, err
                    );
                    activate_mode(&self.scheduler_dir, &SAFE_MODE)?;
                    self.start()?;
                }
            }
            Ok(())
        } else {
            error!("Failed to find an active mode");
            panic!("Failed to find an active mode");
        }
    }

    // Stops all running tasks and clears of list of scheduler handles
    pub fn stop(&self) -> Result<(), SchedulerError> {
        let mut schedules_map = self.scheduler_map.lock().unwrap();
        for (name, handle) in schedules_map.drain().take(1) {
            info!("Stopping {}'s tasks", name);
            if let Err(e) = handle.stopper.send(()) {
                error!("Failed to send stop to {}'s tasks: {}", name, e);
            }
        }
        Ok(())
    }

    // Checks if a task list exists in an active mode and stops its scheduler if needed
    pub fn check_stop_task_list(
        &self,
        raw_name: &str,
        raw_mode: &str,
    ) -> Result<(), SchedulerError> {
        let name = raw_name.to_lowercase();
        let mode = raw_mode.to_lowercase();

        if is_mode_active(&self.scheduler_dir, &mode) {
            let mut schedules_map = self.scheduler_map.lock().unwrap();
            if let Some(handle) = schedules_map.remove(&name) {
                info!("Stopping {}'s tasks", name);
                if let Err(e) = handle.stopper.send(()) {
                    error!("Failed to send stop to {}'s tasks: {}", name, e);
                }
            }
            Ok(())
        } else {
            Ok(())
        }
    }
}