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
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
/*
 * 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.
 */

//!
//! Definitions and functions concerning the manipulation of task lists
//!

use crate::error::SchedulerError;
use crate::scheduler::SchedulerHandle;
use crate::task::Task;
use chrono::{DateTime, Utc};
use juniper::GraphQLObject;
use log::{error, info};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use std::thread;
use tokio::prelude::future::lazy;
use tokio::prelude::*;
use tokio::runtime::Runtime;

// Task list's contents
#[derive(Debug, GraphQLObject, Serialize, Deserialize)]
struct ListContents {
    pub tasks: Vec<Task>,
}

// Task list's metadata
#[derive(Debug, GraphQLObject)]
pub struct TaskList {
    pub tasks: Vec<Task>,
    pub path: String,
    pub filename: String,
    pub time_imported: String,
}

impl TaskList {
    pub fn from_path(path_obj: &Path) -> Result<TaskList, SchedulerError> {
        let path = path_obj
            .to_str()
            .map(|path| path.to_owned())
            .ok_or_else(|| SchedulerError::TaskListParseError {
                err: "Failed to convert path".to_owned(),
                name: "".to_owned(),
            })?;

        let filename = path_obj
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| SchedulerError::TaskListParseError {
                err: "Failed to read task list name".to_owned(),
                name: path.to_owned(),
            })?
            .to_owned();

        let data = path_obj
            .metadata()
            .map_err(|e| SchedulerError::TaskListParseError {
                err: format!("Failed to read file metadata: {}", e),
                name: filename.to_owned(),
            })?;

        let time_imported: DateTime<Utc> = data
            .modified()
            .map_err(|e| SchedulerError::TaskListParseError {
                err: format!("Failed to get modified time: {}", e),
                name: filename.to_owned(),
            })?
            .into();
        let time_imported = time_imported.format("%Y-%m-%d %H:%M:%S").to_string();

        let list_contents =
            fs::read_to_string(&path_obj).map_err(|e| SchedulerError::TaskListParseError {
                err: format!("Failed to read task list: {}", e),
                name: filename.to_owned(),
            })?;

        let list_contents: ListContents = serde_json::from_str(&list_contents).map_err(|e| {
            SchedulerError::TaskListParseError {
                err: format!("Failed to parse json: {}", e),
                name: filename.to_owned(),
            }
        })?;

        let tasks = list_contents.tasks;

        Ok(TaskList {
            path,
            filename,
            tasks,
            time_imported,
        })
    }

    // Schedules the tasks contained in this task list
    pub fn schedule_tasks(&self, app_service_url: &str) -> Result<SchedulerHandle, SchedulerError> {
        let (stopper, receiver) = channel::<()>();
        let service_url = app_service_url.to_owned();
        let tasks = self.tasks.to_vec();
        let thread_handle = thread::spawn(move || {
            let mut runner = Runtime::new().unwrap_or_else(|e| {
                error!("Failed to create timer runtime: {}", e);
                panic!("Failed to create timer runtime: {}", e);
            });

            runner.spawn(lazy(move || {
                for task in tasks {
                    info!("Scheduling task '{}'", &task.app.name);
                    tokio::spawn(task.schedule(service_url.clone()));
                }
                Ok(())
            }));

            // Wait on the stop message before ending the runtime
            receiver.recv().unwrap_or_else(|e| {
                error!("Failed to received thread stop: {:?}", e);
                panic!("Failed to received thread stop: {:?}", e);
            });
            runner.shutdown_now().wait().unwrap_or_else(|e| {
                error!("Failed to wait on runtime shutdown: {:?}", e);
                panic!("Failed to wait on runtime shutdown: {:?}", e);
            })
        });
        let thread_handle = Arc::new(Mutex::new(thread_handle));
        Ok(SchedulerHandle {
            thread_handle,
            stopper,
        })
    }
}

// Copy a task list into a mode directory
pub fn import_task_list(
    scheduler_dir: &str,
    raw_name: &str,
    path: &str,
    raw_mode: &str,
) -> Result<(), SchedulerError> {
    let name = raw_name.to_lowercase();
    let mode = raw_mode.to_lowercase();
    info!(
        "Importing task list '{}': {} into mode '{}'",
        name, path, mode
    );
    let schedule_dest = format!("{}/{}/{}.json", scheduler_dir, mode, name);

    if !Path::new(&format!("{}/{}", scheduler_dir, mode)).is_dir() {
        return Err(SchedulerError::ImportError {
            err: "Mode not found".to_owned(),
            name: name.to_owned(),
        });
    }

    fs::copy(path, &schedule_dest).map_err(|e| SchedulerError::ImportError {
        err: e.to_string(),
        name: name.to_owned(),
    })?;

    if let Err(e) = validate_task_list(&schedule_dest) {
        let _ = fs::remove_file(&schedule_dest);
        return Err(e);
    }

    Ok(())
}

// Import raw json into a task list into a mode directory
pub fn import_raw_task_list(
    scheduler_dir: &str,
    name: &str,
    mode: &str,
    json: &str,
) -> Result<(), SchedulerError> {
    let name = name.to_lowercase();
    let mode = mode.to_lowercase();
    info!("Importing raw task list '{}' into mode '{}'", name, mode);
    let schedule_dest = format!("{}/{}/{}.json", scheduler_dir, mode, name);

    if !Path::new(&format!("{}/{}", scheduler_dir, mode)).is_dir() {
        return Err(SchedulerError::ImportError {
            err: "Mode not found".to_owned(),
            name: name.to_owned(),
        });
    }

    let mut task_list =
        fs::File::create(&schedule_dest).map_err(|e| SchedulerError::ImportError {
            err: e.to_string(),
            name: name.to_owned(),
        })?;
    task_list
        .write_all(json.as_bytes())
        .map_err(|e| SchedulerError::ImportError {
            err: e.to_string(),
            name: name.to_owned(),
        })?;
    task_list
        .sync_all()
        .map_err(|e| SchedulerError::ImportError {
            err: e.to_string(),
            name: name.to_owned(),
        })?;

    if let Err(e) = validate_task_list(&schedule_dest) {
        let _ = fs::remove_file(&schedule_dest);
        return Err(e);
    }

    Ok(())
}

// Remove an existing task list from the mode's directory
pub fn remove_task_list(scheduler_dir: &str, name: &str, mode: &str) -> Result<(), SchedulerError> {
    let name = name.to_lowercase();
    let mode = mode.to_lowercase();
    info!("Removing task list '{}'", name);
    let sched_path = format!("{}/{}/{}.json", scheduler_dir, mode, name);

    if !Path::new(&format!("{}/{}", scheduler_dir, mode)).is_dir() {
        return Err(SchedulerError::RemoveError {
            err: "Mode not found".to_owned(),
            name: name.to_owned(),
        });
    }

    if !Path::new(&sched_path).is_file() {
        return Err(SchedulerError::RemoveError {
            err: "File not found".to_owned(),
            name: name.to_owned(),
        });
    }

    fs::remove_file(&sched_path).map_err(|e| SchedulerError::RemoveError {
        err: e.to_string(),
        name: name.to_owned(),
    })?;

    info!("Removed task list '{}'", name);
    Ok(())
}

// Retrieve list of the task lists in a mode's directory
pub fn get_mode_task_lists(mode_path: &str) -> Result<Vec<TaskList>, SchedulerError> {
    let mut schedules = vec![];

    let mut files_list: Vec<PathBuf> = fs::read_dir(mode_path)
        .map_err(|e| SchedulerError::GenericError {
            err: format!("Failed to read mode dir: {}", e),
        })?
        // Filter out invalid entries
        .filter_map(|x| x.ok())
        // Convert DirEntry -> PathBuf
        .map(|entry| entry.path())
        // Filter out non-directories
        .filter(|entry| entry.is_file())
        .collect();
    // Sort into predictable order
    files_list.sort();

    for path in files_list {
        schedules.push(TaskList::from_path(&path)?);
    }

    Ok(schedules)
}

// Validate the format and content of a task list
pub fn validate_task_list(path: &str) -> Result<(), SchedulerError> {
    let task_path = Path::new(path);
    let task_list = TaskList::from_path(task_path)?;
    for task in task_list.tasks {
        let _ = task.get_duration()?;
        let _ = task.get_period()?;
    }
    Ok(())
}