Add support for routines; state messages

This commit is contained in:
garrettmills
2020-04-15 09:11:10 -05:00
parent e401809ad5
commit 8319859828
36 changed files with 1146 additions and 22 deletions

View File

@@ -0,0 +1,62 @@
const { Injectable } = require('flitter-di')
const RoutineExecutionResult = require('./RoutineExecutionResult')
const StepResult = require('./StepResult')
const InvalidRoutineTypeError = require('./error/InvalidRoutineTypeError')
class Routine extends Injectable {
static get services() {
return [...super.services, 'states', 'app']
}
_config
_hosts
_type
constructor(hosts, config, type = 'checks') {
super()
this.app.make(StepResult)
this.app.make(RoutineExecutionResult)
this._config = config
this._hosts = hosts
this._type = type
}
async execute() {
const result = await this._build_result()
for ( const step of result.steps ) {
if ( this._type === 'checks' ) {
step.status = (await step.step.check()) ? 'success' : 'fail'
step.message = step.status === 'success' ? 'Check passed.' : step.step.check_message()
} else if ( this._type === 'apply' ) {
if ( !(await step.step.check()) ) {
await step.step.apply()
step.status = (await step.step.check()) ? 'success' : 'fail'
step.message = step.status === 'success' ? 'State applied successfully.' : step.step.failure_message()
} else {
step.status = 'success'
step.message = 'Check passed.'
}
} else {
throw new InvalidRoutineTypeError(this._type)
}
}
result.overall_state = result.steps.every(x => x.status === 'success') ? 'success' : 'fail'
return result
}
async _build_result() {
const steps = []
for ( const step_config of this._config.steps ) {
const step = this.states.from_config(this._hosts[step_config.host], step_config)
const result = new StepResult(this, step)
steps.push(result)
}
return new RoutineExecutionResult(steps)
}
}
module.exports = exports = Routine

View File

@@ -0,0 +1,23 @@
const { Injectable } = require('flitter-di')
class RoutineExecutionResult extends Injectable {
steps = []
overall_state = 'pending' // pending | success | fail
constructor(steps = []) {
super()
this.steps = steps
}
get status() {
if ( this.steps.some(x => x.status === 'pending') ) return 'pending'
else if ( this.steps.some(x => x.status === 'fail') ) return 'fail'
else return 'success'
}
failures() {
return this.steps.filter(x => x.status === 'fail')
}
}
module.exports = exports = RoutineExecutionResult

View File

@@ -0,0 +1,16 @@
const { Injectable } = require('flitter-di')
class StepResult extends Injectable {
step
routine
status = 'pending' // pending | success | fail
message = ''
constructor(routine, step) {
super()
this.routine = routine
this.step = step
}
}
module.exports = exports = StepResult

View File

@@ -0,0 +1,7 @@
class InvalidRoutineTypeError extends Error {
constructor(routine_type) {
super(`Invalid routine type: ${routine_type}`)
}
}
module.exports = exports = InvalidRoutineTypeError