forked from vieter-v/vieter
Compare commits
2 Commits
fe5b9b8cfd
...
5cbe8052ff
| Author | SHA1 | Date |
|---|---|---|
|
|
5cbe8052ff | |
|
|
d8e3dcb34f |
|
|
@ -13,7 +13,7 @@ pub mut:
|
||||||
// Next timestamp from which point this job is allowed to be executed
|
// Next timestamp from which point this job is allowed to be executed
|
||||||
timestamp time.Time
|
timestamp time.Time
|
||||||
// Required for calculating next timestamp after having pop'ed a job
|
// Required for calculating next timestamp after having pop'ed a job
|
||||||
ce CronExpression
|
ce &CronExpression = unsafe { nil }
|
||||||
// Actual build config sent to the agent
|
// Actual build config sent to the agent
|
||||||
config BuildConfig
|
config BuildConfig
|
||||||
// Whether this is a one-time job
|
// Whether this is a one-time job
|
||||||
|
|
@ -30,7 +30,7 @@ fn (r1 BuildJob) < (r2 BuildJob) bool {
|
||||||
// for each architecture. Agents receive jobs from this queue.
|
// for each architecture. Agents receive jobs from this queue.
|
||||||
pub struct BuildJobQueue {
|
pub struct BuildJobQueue {
|
||||||
// Schedule to use for targets without explicitely defined cron expression
|
// Schedule to use for targets without explicitely defined cron expression
|
||||||
default_schedule CronExpression
|
default_schedule &CronExpression
|
||||||
// Base image to use for targets without defined base image
|
// Base image to use for targets without defined base image
|
||||||
default_base_image string
|
default_base_image string
|
||||||
mut:
|
mut:
|
||||||
|
|
@ -44,9 +44,9 @@ mut:
|
||||||
}
|
}
|
||||||
|
|
||||||
// new_job_queue initializes a new job queue
|
// new_job_queue initializes a new job queue
|
||||||
pub fn new_job_queue(default_schedule CronExpression, default_base_image string) BuildJobQueue {
|
pub fn new_job_queue(default_schedule &CronExpression, default_base_image string) BuildJobQueue {
|
||||||
return BuildJobQueue{
|
return BuildJobQueue{
|
||||||
default_schedule: default_schedule
|
default_schedule: unsafe { default_schedule }
|
||||||
default_base_image: default_base_image
|
default_base_image: default_base_image
|
||||||
invalidated: map[int]time.Time{}
|
invalidated: map[int]time.Time{}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
module cron
|
|
||||||
|
|
||||||
import cli
|
|
||||||
import conf as vconf
|
|
||||||
|
|
||||||
struct Config {
|
|
||||||
pub:
|
|
||||||
log_level string = 'WARN'
|
|
||||||
api_key string
|
|
||||||
address string
|
|
||||||
data_dir string
|
|
||||||
base_image string = 'archlinux:base-devel'
|
|
||||||
max_concurrent_builds int = 1
|
|
||||||
api_update_frequency int = 15
|
|
||||||
image_rebuild_frequency int = 1440
|
|
||||||
// Replicates the behavior of the original cron system
|
|
||||||
global_schedule string = '0 3'
|
|
||||||
}
|
|
||||||
|
|
||||||
// cmd returns the cli module that handles the cron daemon.
|
|
||||||
pub fn cmd() cli.Command {
|
|
||||||
return cli.Command{
|
|
||||||
name: 'cron'
|
|
||||||
description: 'Start the cron service that periodically runs builds.'
|
|
||||||
execute: fn (cmd cli.Command) ! {
|
|
||||||
config_file := cmd.flags.get_string('config-file')!
|
|
||||||
conf := vconf.load<Config>(prefix: 'VIETER_', default_path: config_file)!
|
|
||||||
|
|
||||||
cron(conf)!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
module cron
|
|
||||||
|
|
||||||
import log
|
|
||||||
import cron.daemon
|
|
||||||
import cron.expression
|
|
||||||
import os
|
|
||||||
|
|
||||||
const log_file_name = 'vieter.cron.log'
|
|
||||||
|
|
||||||
// cron starts a cron daemon & starts periodically scheduling builds.
|
|
||||||
pub fn cron(conf Config) ! {
|
|
||||||
// Configure logger
|
|
||||||
log_level := log.level_from_tag(conf.log_level) or {
|
|
||||||
return error('Invalid log level. The allowed values are FATAL, ERROR, WARN, INFO & DEBUG.')
|
|
||||||
}
|
|
||||||
|
|
||||||
mut logger := log.Log{
|
|
||||||
level: log_level
|
|
||||||
}
|
|
||||||
|
|
||||||
log_file := os.join_path_single(conf.data_dir, cron.log_file_name)
|
|
||||||
logger.set_full_logpath(log_file)
|
|
||||||
logger.log_to_console_too()
|
|
||||||
|
|
||||||
ce := expression.parse_expression(conf.global_schedule) or {
|
|
||||||
return error('Error while parsing global cron expression: $err.msg()')
|
|
||||||
}
|
|
||||||
|
|
||||||
mut d := daemon.init_daemon(logger, conf.address, conf.api_key, conf.base_image, ce,
|
|
||||||
conf.max_concurrent_builds, conf.api_update_frequency, conf.image_rebuild_frequency)!
|
|
||||||
|
|
||||||
d.run()
|
|
||||||
}
|
|
||||||
|
|
@ -1,115 +0,0 @@
|
||||||
module daemon
|
|
||||||
|
|
||||||
import time
|
|
||||||
import sync.stdatomic
|
|
||||||
import build
|
|
||||||
import os
|
|
||||||
|
|
||||||
const (
|
|
||||||
build_empty = 0
|
|
||||||
build_running = 1
|
|
||||||
build_done = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
// clean_finished_builds removes finished builds from the build slots & returns
|
|
||||||
// them.
|
|
||||||
fn (mut d Daemon) clean_finished_builds() []ScheduledBuild {
|
|
||||||
mut out := []ScheduledBuild{}
|
|
||||||
|
|
||||||
for i in 0 .. d.atomics.len {
|
|
||||||
if stdatomic.load_u64(&d.atomics[i]) == daemon.build_done {
|
|
||||||
stdatomic.store_u64(&d.atomics[i], daemon.build_empty)
|
|
||||||
out << d.builds[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// update_builds starts as many builds as possible.
|
|
||||||
fn (mut d Daemon) start_new_builds() {
|
|
||||||
now := time.now()
|
|
||||||
|
|
||||||
for d.queue.len() > 0 {
|
|
||||||
elem := d.queue.peek() or {
|
|
||||||
d.lerror("queue.peek() unexpectedly returned an error. This shouldn't happen.")
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if elem.timestamp < now {
|
|
||||||
sb := d.queue.pop() or {
|
|
||||||
d.lerror("queue.pop() unexpectedly returned an error. This shouldn't happen.")
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
// If this build couldn't be scheduled, no more will be possible.
|
|
||||||
if !d.start_build(sb) {
|
|
||||||
d.queue.insert(sb)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// start_build starts a build for the given ScheduledBuild object.
|
|
||||||
fn (mut d Daemon) start_build(sb ScheduledBuild) bool {
|
|
||||||
for i in 0 .. d.atomics.len {
|
|
||||||
if stdatomic.load_u64(&d.atomics[i]) == daemon.build_empty {
|
|
||||||
stdatomic.store_u64(&d.atomics[i], daemon.build_running)
|
|
||||||
d.builds[i] = sb
|
|
||||||
|
|
||||||
go d.run_build(i, sb)
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// run_build actually starts the build process for a given target.
|
|
||||||
fn (mut d Daemon) run_build(build_index int, sb ScheduledBuild) {
|
|
||||||
d.linfo('started build: $sb.target.url -> $sb.target.repo')
|
|
||||||
|
|
||||||
// 0 means success, 1 means failure
|
|
||||||
mut status := 0
|
|
||||||
|
|
||||||
res := build.build_target(d.client.address, d.client.api_key, d.builder_images.last(),
|
|
||||||
&sb.target, false) or {
|
|
||||||
d.ldebug('build_target error: $err.msg()')
|
|
||||||
status = 1
|
|
||||||
|
|
||||||
build.BuildResult{}
|
|
||||||
}
|
|
||||||
|
|
||||||
if status == 0 {
|
|
||||||
d.linfo('finished build: $sb.target.url -> $sb.target.repo; uploading logs...')
|
|
||||||
|
|
||||||
build_arch := os.uname().machine
|
|
||||||
d.client.add_build_log(sb.target.id, res.start_time, res.end_time, build_arch,
|
|
||||||
res.exit_code, res.logs) or {
|
|
||||||
d.lerror('Failed to upload logs for build: $sb.target.url -> $sb.target.repo')
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
d.linfo('an error occured during build: $sb.target.url -> $sb.target.repo')
|
|
||||||
}
|
|
||||||
|
|
||||||
stdatomic.store_u64(&d.atomics[build_index], daemon.build_done)
|
|
||||||
}
|
|
||||||
|
|
||||||
// current_build_count returns how many builds are currently running.
|
|
||||||
fn (mut d Daemon) current_build_count() int {
|
|
||||||
mut res := 0
|
|
||||||
|
|
||||||
for i in 0 .. d.atomics.len {
|
|
||||||
if stdatomic.load_u64(&d.atomics[i]) == daemon.build_running {
|
|
||||||
res += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
@ -1,274 +0,0 @@
|
||||||
module daemon
|
|
||||||
|
|
||||||
import time
|
|
||||||
import log
|
|
||||||
import datatypes { MinHeap }
|
|
||||||
import cron.expression { CronExpression, parse_expression }
|
|
||||||
import math
|
|
||||||
import build
|
|
||||||
import docker
|
|
||||||
import os
|
|
||||||
import client
|
|
||||||
import models { Target }
|
|
||||||
|
|
||||||
const (
|
|
||||||
// How many seconds to wait before retrying to update API if failed
|
|
||||||
api_update_retry_timeout = 5
|
|
||||||
// How many seconds to wait before retrying to rebuild image if failed
|
|
||||||
rebuild_base_image_retry_timout = 30
|
|
||||||
)
|
|
||||||
|
|
||||||
struct ScheduledBuild {
|
|
||||||
pub:
|
|
||||||
target Target
|
|
||||||
timestamp time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overloaded operator for comparing ScheduledBuild objects
|
|
||||||
fn (r1 ScheduledBuild) < (r2 ScheduledBuild) bool {
|
|
||||||
return r1.timestamp < r2.timestamp
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Daemon {
|
|
||||||
mut:
|
|
||||||
client client.Client
|
|
||||||
base_image string
|
|
||||||
builder_images []string
|
|
||||||
global_schedule CronExpression
|
|
||||||
api_update_frequency int
|
|
||||||
image_rebuild_frequency int
|
|
||||||
// Targets currently loaded from API.
|
|
||||||
targets []Target
|
|
||||||
// At what point to update the list of targets.
|
|
||||||
api_update_timestamp time.Time
|
|
||||||
image_build_timestamp time.Time
|
|
||||||
queue MinHeap<ScheduledBuild>
|
|
||||||
// Which builds are currently running
|
|
||||||
builds []ScheduledBuild
|
|
||||||
// Atomic variables used to detect when a build has finished; length is the
|
|
||||||
// same as builds
|
|
||||||
atomics []u64
|
|
||||||
logger shared log.Log
|
|
||||||
}
|
|
||||||
|
|
||||||
// init_daemon initializes a new Daemon object. It renews the targets &
|
|
||||||
// populates the build queue for the first time.
|
|
||||||
pub fn init_daemon(logger log.Log, address string, api_key string, base_image string, global_schedule CronExpression, max_concurrent_builds int, api_update_frequency int, image_rebuild_frequency int) !Daemon {
|
|
||||||
mut d := Daemon{
|
|
||||||
client: client.new(address, api_key)
|
|
||||||
base_image: base_image
|
|
||||||
global_schedule: global_schedule
|
|
||||||
api_update_frequency: api_update_frequency
|
|
||||||
image_rebuild_frequency: image_rebuild_frequency
|
|
||||||
atomics: []u64{len: max_concurrent_builds}
|
|
||||||
builds: []ScheduledBuild{len: max_concurrent_builds}
|
|
||||||
logger: logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize the targets & queue
|
|
||||||
d.renew_targets()
|
|
||||||
d.renew_queue()
|
|
||||||
if !d.rebuild_base_image() {
|
|
||||||
return error('The base image failed to build. The Vieter cron daemon cannot run without an initial builder image.')
|
|
||||||
}
|
|
||||||
|
|
||||||
return d
|
|
||||||
}
|
|
||||||
|
|
||||||
// run starts the actual daemon process. It runs builds when possible &
|
|
||||||
// periodically refreshes the list of targets to ensure we stay in sync.
|
|
||||||
pub fn (mut d Daemon) run() {
|
|
||||||
for {
|
|
||||||
finished_builds := d.clean_finished_builds()
|
|
||||||
|
|
||||||
// Update the API's contents if needed & renew the queue
|
|
||||||
if time.now() >= d.api_update_timestamp {
|
|
||||||
d.renew_targets()
|
|
||||||
d.renew_queue()
|
|
||||||
}
|
|
||||||
// The finished builds should only be rescheduled if the API contents
|
|
||||||
// haven't been renewed.
|
|
||||||
else {
|
|
||||||
for sb in finished_builds {
|
|
||||||
d.schedule_build(sb.target)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO remove old builder images.
|
|
||||||
// This issue is less trivial than it sounds, because a build could
|
|
||||||
// still be running when the image has to be rebuilt. That would
|
|
||||||
// prevent the image from being removed. Therefore, we will need to
|
|
||||||
// keep track of a list or something & remove an image once we have
|
|
||||||
// made sure it isn't being used anymore.
|
|
||||||
if time.now() >= d.image_build_timestamp {
|
|
||||||
d.rebuild_base_image()
|
|
||||||
// In theory, executing this function here allows an old builder
|
|
||||||
// image to exist for at most image_rebuild_frequency minutes.
|
|
||||||
d.clean_old_base_images()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Schedules new builds when possible
|
|
||||||
d.start_new_builds()
|
|
||||||
|
|
||||||
// If there are builds currently running, the daemon should refresh
|
|
||||||
// every second to clean up any finished builds & start new ones.
|
|
||||||
mut delay := time.Duration(1 * time.second)
|
|
||||||
|
|
||||||
// Sleep either until we have to refresh the targets or when the next
|
|
||||||
// build has to start, with a minimum of 1 second.
|
|
||||||
if d.current_build_count() == 0 {
|
|
||||||
now := time.now()
|
|
||||||
delay = d.api_update_timestamp - now
|
|
||||||
|
|
||||||
if d.queue.len() > 0 {
|
|
||||||
elem := d.queue.peek() or {
|
|
||||||
d.lerror("queue.peek() unexpectedly returned an error. This shouldn't happen.")
|
|
||||||
|
|
||||||
// This is just a fallback option. In theory, queue.peek()
|
|
||||||
// should *never* return an error or none, because we check
|
|
||||||
// its len beforehand.
|
|
||||||
time.sleep(1)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
time_until_next_job := elem.timestamp - now
|
|
||||||
|
|
||||||
delay = math.min(delay, time_until_next_job)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// We sleep for at least one second. This is to prevent the program
|
|
||||||
// from looping agressively when a cronjob can be scheduled, but
|
|
||||||
// there's no spots free for it to be started.
|
|
||||||
delay = math.max(delay, 1 * time.second)
|
|
||||||
|
|
||||||
d.ldebug('Sleeping for ${delay}...')
|
|
||||||
|
|
||||||
time.sleep(delay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// schedule_build adds the next occurence of the given targets build to the
|
|
||||||
// queue.
|
|
||||||
fn (mut d Daemon) schedule_build(target Target) {
|
|
||||||
ce := if target.schedule != '' {
|
|
||||||
parse_expression(target.schedule) or {
|
|
||||||
// TODO This shouldn't return an error if the expression is empty.
|
|
||||||
d.lerror("Error while parsing cron expression '$target.schedule' (id $target.id): $err.msg()")
|
|
||||||
|
|
||||||
d.global_schedule
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
d.global_schedule
|
|
||||||
}
|
|
||||||
|
|
||||||
// A target that can't be scheduled will just be skipped for now
|
|
||||||
timestamp := ce.next_from_now() or {
|
|
||||||
d.lerror("Couldn't calculate next timestamp from '$target.schedule'; skipping")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
d.queue.insert(ScheduledBuild{
|
|
||||||
target: target
|
|
||||||
timestamp: timestamp
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// renew_targets requests the newest list of targets from the server & replaces
|
|
||||||
// the old one.
|
|
||||||
fn (mut d Daemon) renew_targets() {
|
|
||||||
d.linfo('Renewing targets...')
|
|
||||||
|
|
||||||
mut new_targets := d.client.get_all_targets() or {
|
|
||||||
d.lerror('Failed to renew targets. Retrying in ${daemon.api_update_retry_timeout}s...')
|
|
||||||
d.api_update_timestamp = time.now().add_seconds(daemon.api_update_retry_timeout)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter out any targets that shouldn't run on this architecture
|
|
||||||
cur_arch := os.uname().machine
|
|
||||||
new_targets = new_targets.filter(it.arch.any(it.value == cur_arch))
|
|
||||||
|
|
||||||
d.targets = new_targets
|
|
||||||
|
|
||||||
d.api_update_timestamp = time.now().add_seconds(60 * d.api_update_frequency)
|
|
||||||
}
|
|
||||||
|
|
||||||
// renew_queue replaces the old queue with a new one that reflects the newest
|
|
||||||
// values in targets.
|
|
||||||
fn (mut d Daemon) renew_queue() {
|
|
||||||
d.linfo('Renewing queue...')
|
|
||||||
mut new_queue := MinHeap<ScheduledBuild>{}
|
|
||||||
|
|
||||||
// Move any jobs that should have already started from the old queue onto
|
|
||||||
// the new one
|
|
||||||
now := time.now()
|
|
||||||
|
|
||||||
// For some reason, using
|
|
||||||
// ```v
|
|
||||||
// for d.queue.len() > 0 && d.queue.peek() !.timestamp < now {
|
|
||||||
//```
|
|
||||||
// here causes the function to prematurely just exit, without any errors or anything, very weird
|
|
||||||
// https://github.com/vlang/v/issues/14042
|
|
||||||
for d.queue.len() > 0 {
|
|
||||||
elem := d.queue.pop() or {
|
|
||||||
d.lerror("queue.pop() returned an error. This shouldn't happen.")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if elem.timestamp < now {
|
|
||||||
new_queue.insert(elem)
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
d.queue = new_queue
|
|
||||||
|
|
||||||
// For each target in targets, parse their cron expression (or use the
|
|
||||||
// default one if not present) & add them to the queue
|
|
||||||
for target in d.targets {
|
|
||||||
d.schedule_build(target)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// rebuild_base_image recreates the builder image.
|
|
||||||
fn (mut d Daemon) rebuild_base_image() bool {
|
|
||||||
d.linfo('Rebuilding builder image....')
|
|
||||||
|
|
||||||
d.builder_images << build.create_build_image(d.base_image) or {
|
|
||||||
d.lerror('Failed to rebuild base image. Retrying in ${daemon.rebuild_base_image_retry_timout}s...')
|
|
||||||
d.image_build_timestamp = time.now().add_seconds(daemon.rebuild_base_image_retry_timout)
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
d.image_build_timestamp = time.now().add_seconds(60 * d.image_rebuild_frequency)
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// clean_old_base_images tries to remove any old but still present builder
|
|
||||||
// images.
|
|
||||||
fn (mut d Daemon) clean_old_base_images() {
|
|
||||||
mut i := 0
|
|
||||||
|
|
||||||
mut dd := docker.new_conn() or {
|
|
||||||
d.lerror('Failed to connect to Docker socket.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer {
|
|
||||||
dd.close() or {}
|
|
||||||
}
|
|
||||||
|
|
||||||
for i < d.builder_images.len - 1 {
|
|
||||||
// For each builder image, we try to remove it by calling the Docker
|
|
||||||
// API. If the function returns an error or false, that means the image
|
|
||||||
// wasn't deleted. Therefore, we move the index over. If the function
|
|
||||||
// returns true, the array's length has decreased by one so we don't
|
|
||||||
// move the index.
|
|
||||||
dd.image_remove(d.builder_images[i]) or { i += 1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
module daemon
|
|
||||||
|
|
||||||
import log
|
|
||||||
|
|
||||||
// log reate a log message with the given level
|
|
||||||
pub fn (mut d Daemon) log(msg string, level log.Level) {
|
|
||||||
lock d.logger {
|
|
||||||
d.logger.send_output(msg, level)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// lfatal create a log message with the fatal level
|
|
||||||
pub fn (mut d Daemon) lfatal(msg string) {
|
|
||||||
d.log(msg, log.Level.fatal)
|
|
||||||
}
|
|
||||||
|
|
||||||
// lerror create a log message with the error level
|
|
||||||
pub fn (mut d Daemon) lerror(msg string) {
|
|
||||||
d.log(msg, log.Level.error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// lwarn create a log message with the warn level
|
|
||||||
pub fn (mut d Daemon) lwarn(msg string) {
|
|
||||||
d.log(msg, log.Level.warn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// linfo create a log message with the info level
|
|
||||||
pub fn (mut d Daemon) linfo(msg string) {
|
|
||||||
d.log(msg, log.Level.info)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ldebug create a log message with the debug level
|
|
||||||
pub fn (mut d Daemon) ldebug(msg string) {
|
|
||||||
d.log(msg, log.Level.debug)
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +1,20 @@
|
||||||
#include "expression.h"
|
#include "expression.h"
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
const uint8_t month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
const uint8_t month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
||||||
|
|
||||||
|
CronExpression *ce_init() {
|
||||||
|
return malloc(sizeof(CronExpression));
|
||||||
|
}
|
||||||
|
|
||||||
|
void ce_free(CronExpression *ce) {
|
||||||
|
free(ce->months);
|
||||||
|
free(ce->days);
|
||||||
|
free(ce->hours);
|
||||||
|
free(ce->minutes);
|
||||||
|
free(ce);
|
||||||
|
}
|
||||||
|
|
||||||
int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref) {
|
int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref) {
|
||||||
// For all of these values, the rule is the following: if their value is
|
// For all of these values, the rule is the following: if their value is
|
||||||
// the length of their respective array in the CronExpression object, that
|
// the length of their respective array in the CronExpression object, that
|
||||||
|
|
@ -26,12 +39,12 @@ int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref) {
|
||||||
day_index++;
|
day_index++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (day_index < ce->days_count && ref->day == ce->days[day_index]) {
|
if (day_index < ce->day_count && ref->day == ce->days[day_index]) {
|
||||||
while (hour_index < ce->hour_count && ref->hour > ce->hours[hour_index]) {
|
while (hour_index < ce->hour_count && ref->hour > ce->hours[hour_index]) {
|
||||||
hour_index++;
|
hour_index++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hour_index < ce->hours_count && ref->hour == ce->hours[hour_index]) {
|
if (hour_index < ce->hour_count && ref->hour == ce->hours[hour_index]) {
|
||||||
// Minute is the only value where we explicitely make sure we
|
// Minute is the only value where we explicitely make sure we
|
||||||
// can't match sref's value exactly. This is to ensure we only
|
// can't match sref's value exactly. This is to ensure we only
|
||||||
// return values in the future.
|
// return values in the future.
|
||||||
|
|
@ -88,3 +101,20 @@ int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref) {
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int ce_next_from_now(SimpleTime *out, CronExpression *ce) {
|
||||||
|
time_t t = time(NULL);
|
||||||
|
struct tm gm;
|
||||||
|
gmtime_r(&t, &gm);
|
||||||
|
|
||||||
|
SimpleTime ref = {
|
||||||
|
.year = gm.tm_year,
|
||||||
|
// tm_mon goes from 0 to 11
|
||||||
|
.month = gm.tm_mon + 1,
|
||||||
|
.day = gm.tm_mday,
|
||||||
|
.hour = gm.tm_hour,
|
||||||
|
.minute = gm.tm_min
|
||||||
|
};
|
||||||
|
|
||||||
|
return ce_next(out, ce, &ref);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -29,9 +29,15 @@ typedef struct simple_time {
|
||||||
int minute;
|
int minute;
|
||||||
} SimpleTime;
|
} SimpleTime;
|
||||||
|
|
||||||
|
CronExpression *ce_init();
|
||||||
|
|
||||||
|
void ce_free(CronExpression *ce);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Given a
|
* Given a
|
||||||
*/
|
*/
|
||||||
int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref);
|
int ce_next(SimpleTime *out, CronExpression *ce, SimpleTime *ref);
|
||||||
|
|
||||||
|
int ce_next_from_now(SimpleTime *out, CronExpression *ce);
|
||||||
|
|
||||||
ParseError ce_parse_expression(CronExpression *out, char *s);
|
ParseError ce_parse_expression(CronExpression *out, char *s);
|
||||||
|
|
|
||||||
|
|
@ -2,17 +2,37 @@ module expression
|
||||||
|
|
||||||
#flag -I @VMODROOT/c
|
#flag -I @VMODROOT/c
|
||||||
#flag @VMODROOT/c/parse.o
|
#flag @VMODROOT/c/parse.o
|
||||||
|
#flag @VMODROOT/c/expression.o
|
||||||
#include "expression.h"
|
#include "expression.h"
|
||||||
|
|
||||||
|
[heap]
|
||||||
pub struct C.CronExpression {
|
pub struct C.CronExpression {
|
||||||
minutes &u8
|
minutes &u8
|
||||||
hours &u8
|
hours &u8
|
||||||
days &u8
|
days &u8
|
||||||
months &u8
|
months &u8
|
||||||
minute_count u8
|
minute_count u8
|
||||||
hour_count u8
|
hour_count u8
|
||||||
day_count u8
|
day_count u8
|
||||||
month_count u8
|
month_count u8
|
||||||
}
|
}
|
||||||
|
|
||||||
/* pub type CronExpression = C.CronExpression */
|
pub type CronExpression = C.CronExpression
|
||||||
|
|
||||||
|
struct C.SimpleTime {
|
||||||
|
year int
|
||||||
|
month int
|
||||||
|
day int
|
||||||
|
hour int
|
||||||
|
minute int
|
||||||
|
}
|
||||||
|
|
||||||
|
fn C.ce_init() &C.CronExpression
|
||||||
|
|
||||||
|
fn C.ce_free(ce &C.CronExpression)
|
||||||
|
|
||||||
|
fn C.ce_next(out &C.SimpleTime, ce &C.CronExpression, ref &C.SimpleTime) int
|
||||||
|
|
||||||
|
fn C.ce_next_from_now(out &C.SimpleTime, ce &C.CronExpression) int
|
||||||
|
|
||||||
|
fn C.ce_parse_expression(out &C.CronExpression, s &char) int
|
||||||
|
|
|
||||||
|
|
@ -2,123 +2,61 @@ module expression
|
||||||
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
pub struct CronExpression {
|
pub fn parse_expression(exp string) !&CronExpression {
|
||||||
minutes []int
|
out := C.ce_init()
|
||||||
hours []int
|
res := C.ce_parse_expression(out, exp.str)
|
||||||
days []int
|
|
||||||
months []int
|
if res != 0 {
|
||||||
|
return error('yuhh')
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn (ce &CronExpression) free() {
|
||||||
|
C.ce_free(ce)
|
||||||
}
|
}
|
||||||
|
|
||||||
// next calculates the earliest time this cron expression is valid. It will
|
|
||||||
// always pick a moment in the future, even if ref matches completely up to the
|
|
||||||
// minute. This function conciously does not take gap years into account.
|
|
||||||
pub fn (ce &CronExpression) next(ref time.Time) !time.Time {
|
pub fn (ce &CronExpression) next(ref time.Time) !time.Time {
|
||||||
// If the given ref matches the next cron occurence up to the minute, it
|
st := C.SimpleTime{
|
||||||
// will return that value. Because we always want to return a value in the
|
year: ref.year
|
||||||
// future, we artifically shift the ref 60 seconds to make sure we always
|
month: ref.month
|
||||||
// match in the future. A shift of 60 seconds is enough because the cron
|
day: ref.day
|
||||||
// expression does not allow for accuracy smaller than one minute.
|
hour: ref.hour
|
||||||
sref := ref
|
minute: ref.minute
|
||||||
|
|
||||||
// For all of these values, the rule is the following: if their value is
|
|
||||||
// the length of their respective array in the CronExpression object, that
|
|
||||||
// means we've looped back around. This means that the "bigger" value has
|
|
||||||
// to be incremented by one. For example, if the minutes have looped
|
|
||||||
// around, that means that the hour has to be incremented as well.
|
|
||||||
mut minute_index := 0
|
|
||||||
mut hour_index := 0
|
|
||||||
mut day_index := 0
|
|
||||||
mut month_index := 0
|
|
||||||
|
|
||||||
// This chain is the same logic multiple times, namely that if a "bigger"
|
|
||||||
// value loops around, then the smaller value will always reset as well.
|
|
||||||
// For example, if we're going to a new day, the hour & minute will always
|
|
||||||
// be their smallest value again.
|
|
||||||
for month_index < ce.months.len && sref.month > ce.months[month_index] {
|
|
||||||
month_index++
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if month_index < ce.months.len && sref.month == ce.months[month_index] {
|
out := C.SimpleTime{}
|
||||||
for day_index < ce.days.len && sref.day > ce.days[day_index] {
|
res := C.ce_next(&out, ce, &st)
|
||||||
day_index++
|
|
||||||
}
|
|
||||||
|
|
||||||
if day_index < ce.days.len && ce.days[day_index] == sref.day {
|
if res != 0 {
|
||||||
for hour_index < ce.hours.len && sref.hour > ce.hours[hour_index] {
|
return error('yuhh')
|
||||||
hour_index++
|
|
||||||
}
|
|
||||||
|
|
||||||
if hour_index < ce.hours.len && ce.hours[hour_index] == sref.hour {
|
|
||||||
// Minute is the only value where we explicitely make sure we
|
|
||||||
// can't match sref's value exactly. This is to ensure we only
|
|
||||||
// return values in the future.
|
|
||||||
for minute_index < ce.minutes.len && sref.minute >= ce.minutes[minute_index] {
|
|
||||||
minute_index++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Here, we increment the "bigger" values by one if the smaller ones loop
|
|
||||||
// around. The order is important, as it allows a sort-of waterfall effect
|
|
||||||
// to occur which updates all values if required.
|
|
||||||
if minute_index == ce.minutes.len && hour_index < ce.hours.len {
|
|
||||||
hour_index += 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if hour_index == ce.hours.len && day_index < ce.days.len {
|
|
||||||
day_index += 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if day_index == ce.days.len && month_index < ce.months.len {
|
|
||||||
month_index += 1
|
|
||||||
}
|
|
||||||
|
|
||||||
mut minute := ce.minutes[minute_index % ce.minutes.len]
|
|
||||||
mut hour := ce.hours[hour_index % ce.hours.len]
|
|
||||||
mut day := ce.days[day_index % ce.days.len]
|
|
||||||
|
|
||||||
// Sometimes, we end up with a day that does not exist within the selected
|
|
||||||
// month, e.g. day 30 in February. When this occurs, we reset day back to
|
|
||||||
// the smallest value & loop over to the next month that does have this
|
|
||||||
// day.
|
|
||||||
if day > time.month_days[ce.months[month_index % ce.months.len] - 1] {
|
|
||||||
day = ce.days[0]
|
|
||||||
month_index += 1
|
|
||||||
|
|
||||||
for day > time.month_days[ce.months[month_index & ce.months.len] - 1] {
|
|
||||||
month_index += 1
|
|
||||||
|
|
||||||
// If for whatever reason the day value ends up being something
|
|
||||||
// that can't be scheduled in any month, we have to make sure we
|
|
||||||
// don't create an infinite loop.
|
|
||||||
if month_index == 2 * ce.months.len {
|
|
||||||
return error('No schedulable moment.')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
month := ce.months[month_index % ce.months.len]
|
|
||||||
mut year := sref.year
|
|
||||||
|
|
||||||
// If the month loops over, we need to increment the year.
|
|
||||||
if month_index >= ce.months.len {
|
|
||||||
year++
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return time.new_time(time.Time{
|
return time.new_time(time.Time{
|
||||||
year: year
|
year: out.year
|
||||||
month: month
|
month: out.month
|
||||||
day: day
|
day: out.day
|
||||||
minute: minute
|
hour: out.hour
|
||||||
hour: hour
|
minute: out.minute
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// next_from_now returns the result of ce.next(ref) where ref is the result of
|
|
||||||
// time.now().
|
|
||||||
pub fn (ce &CronExpression) next_from_now() !time.Time {
|
pub fn (ce &CronExpression) next_from_now() !time.Time {
|
||||||
return ce.next(time.now())
|
out := C.SimpleTime{}
|
||||||
|
res := C.ce_next_from_now(&out, ce)
|
||||||
|
|
||||||
|
if res != 0 {
|
||||||
|
return error('yuhh')
|
||||||
|
}
|
||||||
|
|
||||||
|
return time.new_time(time.Time{
|
||||||
|
year: out.year
|
||||||
|
month: out.month
|
||||||
|
day: out.day
|
||||||
|
hour: out.hour
|
||||||
|
minute: out.minute
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// next_n returns the n next occurences of the expression, given a starting
|
// next_n returns the n next occurences of the expression, given a starting
|
||||||
|
|
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
module expression
|
|
||||||
|
|
||||||
import bitfield
|
|
||||||
|
|
||||||
// parse_range parses a given string into a range of sorted integers. Its
|
|
||||||
// result is a BitField with set bits for all numbers in the result.
|
|
||||||
fn parse_range(s string, min int, max int) !bitfield.BitField {
|
|
||||||
mut start := min
|
|
||||||
mut end := max
|
|
||||||
mut interval := 1
|
|
||||||
mut bf := bitfield.new(max - min + 1)
|
|
||||||
|
|
||||||
exps := s.split('/')
|
|
||||||
|
|
||||||
if exps.len > 2 {
|
|
||||||
return error('Invalid expression.')
|
|
||||||
}
|
|
||||||
|
|
||||||
if exps[0] != '*' {
|
|
||||||
dash_parts := exps[0].split('-')
|
|
||||||
|
|
||||||
if dash_parts.len > 2 {
|
|
||||||
return error('Invalid expression.')
|
|
||||||
}
|
|
||||||
|
|
||||||
start = dash_parts[0].int()
|
|
||||||
|
|
||||||
// The builtin parsing functions return zero if the string can't be
|
|
||||||
// parsed into a number, so we have to explicitely check whether they
|
|
||||||
// actually entered zero or if it's an invalid number.
|
|
||||||
if start == 0 && dash_parts[0] != '0' {
|
|
||||||
return error('Invalid number.')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check whether the start value is out of range
|
|
||||||
if start < min || start > max {
|
|
||||||
return error('Out of range.')
|
|
||||||
}
|
|
||||||
|
|
||||||
if dash_parts.len == 2 {
|
|
||||||
end = dash_parts[1].int()
|
|
||||||
|
|
||||||
if end == 0 && dash_parts[1] != '0' {
|
|
||||||
return error('Invalid number.')
|
|
||||||
}
|
|
||||||
|
|
||||||
if end < start || end > max {
|
|
||||||
return error('Out of range.')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if exps.len > 1 {
|
|
||||||
interval = exps[1].int()
|
|
||||||
|
|
||||||
// interval being zero is always invalid, but we want to check why
|
|
||||||
// it's invalid for better error messages.
|
|
||||||
if interval == 0 {
|
|
||||||
if exps[1] != '0' {
|
|
||||||
return error('Invalid number.')
|
|
||||||
} else {
|
|
||||||
return error('Step size zero not allowed.')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if interval > max - min {
|
|
||||||
return error('Step size too large.')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Here, s solely consists of a number, so that's the only value we
|
|
||||||
// should return.
|
|
||||||
else if exps[0] != '*' && !exps[0].contains('-') {
|
|
||||||
bf.set_bit(start - min)
|
|
||||||
return bf
|
|
||||||
}
|
|
||||||
|
|
||||||
for start <= end {
|
|
||||||
bf.set_bit(start - min)
|
|
||||||
start += interval
|
|
||||||
}
|
|
||||||
|
|
||||||
return bf
|
|
||||||
}
|
|
||||||
|
|
||||||
// bf_to_ints takes a BitField and converts it into the expected list of actual
|
|
||||||
// integers.
|
|
||||||
fn bf_to_ints(bf bitfield.BitField, min int) []int {
|
|
||||||
mut out := []int{}
|
|
||||||
|
|
||||||
for i in 0 .. bf.get_size() {
|
|
||||||
if bf.get_bit(i) == 1 {
|
|
||||||
out << min + i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse_part parses a given part of a cron expression & returns the
|
|
||||||
// corresponding array of ints.
|
|
||||||
fn parse_part(s string, min int, max int) ![]int {
|
|
||||||
mut bf := bitfield.new(max - min + 1)
|
|
||||||
|
|
||||||
for range in s.split(',') {
|
|
||||||
bf2 := parse_range(range, min, max)!
|
|
||||||
bf = bitfield.bf_or(bf, bf2)
|
|
||||||
}
|
|
||||||
|
|
||||||
return bf_to_ints(bf, min)
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse_expression parses an entire cron expression string into a
|
|
||||||
// CronExpression object, if possible.
|
|
||||||
pub fn parse_expression(exp string) !CronExpression {
|
|
||||||
// The filter allows for multiple spaces between parts
|
|
||||||
mut parts := exp.split(' ').filter(it != '')
|
|
||||||
|
|
||||||
if parts.len < 2 || parts.len > 4 {
|
|
||||||
return error('Expression must contain between 2 and 4 space-separated parts.')
|
|
||||||
}
|
|
||||||
|
|
||||||
// For ease of use, we allow the user to only specify as many parts as they
|
|
||||||
// need.
|
|
||||||
for parts.len < 4 {
|
|
||||||
parts << '*'
|
|
||||||
}
|
|
||||||
|
|
||||||
mut part_results := [][]int{}
|
|
||||||
|
|
||||||
mins := [0, 0, 1, 1]
|
|
||||||
maxs := [59, 23, 31, 12]
|
|
||||||
|
|
||||||
// This for loop allows us to more clearly propagate the error to the user.
|
|
||||||
for i, min in mins {
|
|
||||||
part_results << parse_part(parts[i], min, maxs[i]) or {
|
|
||||||
return error('An error occurred with part $i: $err.msg()')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return CronExpression{
|
|
||||||
minutes: part_results[0]
|
|
||||||
hours: part_results[1]
|
|
||||||
days: part_results[2]
|
|
||||||
months: part_results[3]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -9,7 +9,6 @@ import console.schedule
|
||||||
import console.man
|
import console.man
|
||||||
import console.aur
|
import console.aur
|
||||||
import console.repos
|
import console.repos
|
||||||
import cron
|
|
||||||
import agent
|
import agent
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|
@ -43,7 +42,6 @@ fn main() {
|
||||||
commands: [
|
commands: [
|
||||||
server.cmd(),
|
server.cmd(),
|
||||||
targets.cmd(),
|
targets.cmd(),
|
||||||
cron.cmd(),
|
|
||||||
logs.cmd(),
|
logs.cmd(),
|
||||||
schedule.cmd(),
|
schedule.cmd(),
|
||||||
man.cmd(),
|
man.cmd(),
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue