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
/*
 * 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 for dealing with tasks & scheduling
//!

use crate::app::App;
use crate::error::SchedulerError;
use chrono::offset::TimeZone;
use chrono::Utc;
use juniper::GraphQLObject;
use log::error;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use std::time::Instant;
use tokio::prelude::*;
use tokio::timer::Delay;
use tokio::timer::Interval;

// Configuration used to schedule app execution
#[derive(Clone, Debug, GraphQLObject, Serialize, Deserialize)]
pub struct Task {
    // Description of task
    pub description: String,
    // Start delay specified in Xh Ym Zs format
    // Used by init and recurring tasks
    pub delay: Option<String>,
    // Start time specified in yyyy-mm-dd hh:mm:ss format
    // Used by onetime tasks
    pub time: Option<String>,
    // Period of recurrence specified in Xh Ym Zs format
    // Used by recurring tasks
    pub period: Option<String>,
    // Details of the app to be executed
    pub app: App,
}

impl Task {
    // Parse timer delay duration from either delay or time fields
    pub fn get_duration(&self) -> Result<Duration, SchedulerError> {
        if self.delay.is_some() && self.time.is_some() {
            return Err(SchedulerError::TaskParseError {
                err: "Both delay and time defined".to_owned(),
                description: self.description.to_owned(),
            });
        }
        if let Some(delay) = &self.delay {
            Ok(parse_hms_field(delay.to_owned())?)
        } else if let Some(time) = &self.time {
            let run_time = Utc
                .datetime_from_str(&time, "%Y-%m-%d %H:%M:%S")
                .map_err(|e| SchedulerError::TaskParseError {
                    err: format!("Failed to parse time field '{}': {}", time, e),
                    description: self.description.to_owned(),
                })?;
            let now = chrono::Utc::now();

            if run_time < now {
                Err(SchedulerError::TaskTimeError {
                    err: format!("Task scheduled for past time: {}", time),
                    description: self.description.to_owned(),
                })
            } else if (run_time - now) > chrono::Duration::days(90) {
                Err(SchedulerError::TaskTimeError {
                    err: format!("Task scheduled beyond 90 days in the future: {}", time),
                    description: self.description.to_owned(),
                })
            } else {
                Ok((run_time - now)
                    .to_std()
                    .map_err(|e| SchedulerError::TaskParseError {
                        err: format!("Failed to calculate run time: {}", e),
                        description: self.description.to_owned(),
                    })?)
            }
        } else {
            Err(SchedulerError::TaskParseError {
                err: "No delay or time defined".to_owned(),
                description: self.description.to_owned(),
            })
        }
    }

    pub fn get_period(&self) -> Result<Option<Duration>, SchedulerError> {
        if let Some(period) = &self.period {
            Ok(Some(parse_hms_field(period.to_owned())?))
        } else {
            Ok(None)
        }
    }

    pub fn schedule(&self, service_url: String) -> Box<dyn Future<Item = (), Error = ()> + Send> {
        let name = self.app.name.to_owned();
        let duration = match self.get_duration() {
            Ok(d) => d,
            Err(e) => {
                error!(
                    "Failed to parse time specification for task '{}': {}",
                    name, e
                );
                return Box::new(future::err::<(), ()>(()));
            }
        };

        let when = Instant::now() + duration;
        let period = self.get_period();
        let app = self.app.clone();

        match period {
            Ok(Some(period)) => Box::new(
                Interval::new(when, period)
                    .for_each(move |_| {
                        app.execute(&service_url.clone());
                        Ok(())
                    })
                    .map_err(move |e| {
                        error!("Recurring interval errored for task '{}': {}", name, e);
                        panic!("Recurring interval errored for task '{}': {}", name, e)
                    }),
            ),
            _ => Box::new(
                Delay::new(when)
                    .and_then(move |_| {
                        app.execute(&service_url);
                        Ok(())
                    })
                    .map_err(move |e| {
                        error!("Delay errored for task '{}': {}", name, e);
                        panic!("Delay errored for task '{}': {}", name, e)
                    }),
            ),
        }
    }
}

fn parse_hms_field(field: String) -> Result<Duration, SchedulerError> {
    let field_parts: Vec<String> = field.split(' ').map(|s| s.to_owned()).collect();
    let mut duration: u64 = 0;
    if field_parts.is_empty() {
        return Err(SchedulerError::HmsParseError {
            err: "No parts found".to_owned(),
            field: field.to_owned(),
        });
    }
    for mut part in field_parts {
        let unit: Option<char> = part.pop();
        let num: Result<u64, _> = part.parse();
        if let Ok(num) = num {
            match unit {
                Some('s') => {
                    duration += num;
                }
                Some('m') => {
                    duration += num * 60;
                }
                Some('h') => {
                    duration += num * 60 * 60;
                }
                _ => {
                    return Err(SchedulerError::HmsParseError {
                        err: "Found invalid unit".to_owned(),
                        field: field.to_owned(),
                    });
                }
            }
        } else {
            return Err(SchedulerError::HmsParseError {
                err: "Failed to parse number".to_owned(),
                field: field.to_owned(),
            });
        }
    }
    Ok(Duration::from_secs(duration))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_seconds() {
        assert_eq!(
            parse_hms_field("21s".to_owned()),
            Ok(Duration::from_secs(21))
        );
    }

    #[test]
    fn test_parse_minutes() {
        assert_eq!(
            parse_hms_field("3m".to_owned()),
            Ok(Duration::from_secs(180))
        );
    }

    #[test]
    fn test_parse_hours() {
        assert_eq!(
            parse_hms_field("2h".to_owned()),
            Ok(Duration::from_secs(7200))
        );
    }

    #[test]
    fn test_parse_minutes_seconds() {
        assert_eq!(
            parse_hms_field("1m 1s".to_owned()),
            Ok(Duration::from_secs(61))
        );
    }

    #[test]
    fn test_parse_hours_minutes() {
        assert_eq!(
            parse_hms_field("3h 10m".to_owned()),
            Ok(Duration::from_secs(11400))
        );
    }

    #[test]
    fn test_parse_hours_seconds() {
        assert_eq!(
            parse_hms_field("5h 44s".to_owned()),
            Ok(Duration::from_secs(18044))
        );
    }

    #[test]
    fn test_parse_hours_minutes_seconds() {
        assert_eq!(
            parse_hms_field("2h 2m 2s".to_owned()),
            Ok(Duration::from_secs(7322))
        );
    }
}