Cron tasks working.

Starting to rearrange front end for better UX
This commit is contained in:
Andrew 2022-01-11 12:17:57 -05:00
parent c220c6d3d3
commit 5e7d0d64bd
6 changed files with 306 additions and 96 deletions

View File

@ -113,6 +113,7 @@ class Schedules(Model):
command = CharField(null=True)
comment = CharField()
one_time = BooleanField(default=False)
cron_string = CharField(default="")
class Meta:
table_name = 'schedules'
@ -206,7 +207,7 @@ class helpers_management:
# Schedules Methods
#************************************************************************************************
@staticmethod
def create_scheduled_task(server_id, action, interval, interval_type, start_time, command, comment=None, enabled=True, one_time=False):
def create_scheduled_task(server_id, action, interval, interval_type, start_time, command, comment=None, enabled=True, one_time=False, cron_string='* * * * *'):
sch_id = Schedules.insert({
Schedules.server_id: server_id,
Schedules.action: action,
@ -216,7 +217,9 @@ class helpers_management:
Schedules.start_time: start_time,
Schedules.command: command,
Schedules.comment: comment,
Schedules.one_time: one_time
Schedules.one_time: one_time,
Schedules.cron_string: cron_string
}).execute()
return sch_id

View File

@ -9,6 +9,7 @@ import asyncio
import shutil
from schedule import Scheduler
from tzlocal import get_localzone
import tzlocal
from pytz import HOUR, timezone
from app.classes.controllers.users_controller import Users_Controller
@ -54,7 +55,7 @@ class TasksManager:
self.controller = controller
self.tornado = Webserver(controller, self)
self.scheduler = BackgroundScheduler()
self.scheduler = BackgroundScheduler(timezone=str(tzlocal.get_localzone()))
self.users_controller = Users_Controller()
@ -163,33 +164,39 @@ class TasksManager:
def scheduler_thread(self):
schedules = management_helper.get_schedules_enabled()
tz = get_localzone()
self.scheduler.configure(timezone=tz)
self.scheduler.add_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED)
#self.scheduler.add_job(self.scheduler.print_jobs, 'interval', seconds=10, id='-1')
#load schedules from DB
for schedule in schedules:
if schedule.interval_type == 'hours':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = 0, hour = '*/'+str(schedule.interval), id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
elif schedule.interval_type == 'minutes':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = '*/'+str(schedule.interval), id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
elif schedule.interval_type == 'days':
time = schedule.start_time.split(':')
self.scheduler.add_job(management_helper.add_command, 'cron', day = '*/'+str(schedule.interval), hour=time[0], minute=time[1], id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
if schedule.cron_string != "":
cron = schedule.cron_string.split(' ')
self.scheduler.add_job(management_helper.add_command, 'cron', minute = cron[0], hour = cron[1], day = cron[2], month = cron[3], day_of_week = cron[4], id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
else:
if schedule.interval_type == 'hours':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = 0, hour = '*/'+str(schedule.interval), id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
elif schedule.interval_type == 'minutes':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = '*/'+str(schedule.interval), id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
elif schedule.interval_type == 'days':
time = schedule.start_time.split(':')
self.scheduler.add_job(management_helper.add_command, 'cron', day = '*/'+str(schedule.interval), hour=time[0], minute=time[1], id=str(schedule.schedule_id), args=[schedule.server_id, self.users_controller.get_id_by_name('system'), '127.0.0.1', schedule.command])
self.scheduler.start()
def schedule_job(self, job_data):
sch_id = management_helper.create_scheduled_task(job_data['server_id'], job_data['action'], job_data['interval'], job_data['interval_type'], job_data['time'], job_data['command'], "None", job_data['enabled'], job_data['one_time'])
sch_id = management_helper.create_scheduled_task(job_data['server_id'], job_data['action'], job_data['interval'], job_data['interval_type'], job_data['time'], job_data['command'], "None", job_data['enabled'], job_data['one_time'], job_data['cron_string'])
if job_data['enabled']:
if job_data['interval_type'] == 'hours':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = 0, hour = '*/'+str(job_data['interval']), id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']])
elif job_data['interval_type'] == 'minutes':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = '*/'+str(job_data['interval']), id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']])
elif job_data['interval_type'] == 'days':
time = job_data['time'].split(':')
self.scheduler.add_job(management_helper.add_command, 'cron', day = '*/'+str(job_data['interval']), hour = time[0], minute = time[1], id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']], )
if job_data['cron_string'] != "":
cron = job_data['cron_string'].split(' ')
self.scheduler.add_job(management_helper.add_command, 'cron', minute = cron[0], hour = cron[1], day = cron[2], month = cron[3], day_of_week = cron[4], id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']])
else:
if job_data['interval_type'] == 'hours':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = 0, hour = '*/'+str(job_data['interval']), id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']])
elif job_data['interval_type'] == 'minutes':
self.scheduler.add_job(management_helper.add_command, 'cron', minute = '*/'+str(job_data['interval']), id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']])
elif job_data['interval_type'] == 'days':
time = job_data['time'].split(':')
self.scheduler.add_job(management_helper.add_command, 'cron', day = '*/'+str(job_data['interval']), hour = time[0], minute = time[1], id=str(sch_id), args=[job_data['server_id'], self.users_controller.get_id_by_name('system'), '127.0.0.1', job_data['command']], )
def remove_job(self, sch_id):
management_helper.delete_scheduled_task(sch_id)

View File

@ -859,7 +859,10 @@ class PanelHandler(BaseHandler):
elif action == "backup":
command = "backup_server"
else:
interval_type = ''
cron_string = bleach.clean(self.get_argument('cron', ''))
if len(cron_string.split(' ')) != 5:
self.redirect("/panel/error?error=INVALID FORMAT: Invalid Cron Format. Cron must have a space between each character and only have a max of 5 characters * * * * *")
action = bleach.clean(self.get_argument('action', None))
if action == "command":
command = bleach.clean(self.get_argument('command', None))
@ -891,6 +894,13 @@ class PanelHandler(BaseHandler):
if not self.controller.servers.server_id_exists(server_id):
self.redirect("/panel/error?error=Invalid Server ID")
return
minute = datetime.datetime.now().minute
hour = datetime.datetime.now().hour
if minute < 10:
minute = '0' + str(minute)
if hour < 10:
hour = '0'+str(hour)
current_time = str(hour)+':'+str(minute)
if interval_type == "days":
job_data = {
@ -901,12 +911,17 @@ class PanelHandler(BaseHandler):
"command": command,
"time": time,
"enabled": enabled,
"one_time": one_time
"one_time": one_time,
"cron_string": ''
}
elif difficulty == "advanced":
job_data = {
"server_id": server_id,
"action": action,
"interval_type": '',
"interval": '',
"command": '',
"time": current_time,
"command": command,
"cron_string": cron_string,
"enabled": enabled,
@ -920,8 +935,9 @@ class PanelHandler(BaseHandler):
"interval": interval,
"command": command,
"enabled": enabled,
"time": '00:00',
"one_time": one_time
"time": current_time,
"one_time": one_time,
"cron_string": ''
}
self.tasks_manager.schedule_job(job_data)

View File

@ -35,79 +35,8 @@
{% include "parts/server_controls_list.html %}
<div class="row">
<div class="col-md-4 col-sm-12">
<form class="forms-sample" method="post" action="/panel/tasks">
{% raw xsrf_form_html() %}
<input type="hidden" name="id" value="{{ data['server_stats']['server_id']['server_id'] }}">
<input type="hidden" name="subpage" value="config">
<div class="form-group">
<label for="difficulty">Basic / Cron Select<small class="text-muted ml-1"></small> </label><br>
<select id="difficulty" name="difficulty" onchange="basicAdvanced(this);" class="form-control form-control-lg select-css">
<option value="basic">Basic</option>
<option value="advanced">Advanced</option>
</select>
</div>
<div class="form-group">
<label for="server_name">Action<small class="text-muted ml-1"></small> </label><br>
<select id="action" name="action" onchange="yesnoCheck(this);" class="form-control form-control-lg select-css">
<option value="start">Start Server</option>
<option value="restart">Restart Server</option>
<option value="shutdown">Shutdown Server</option>
<option value="backup">Backup Server</option>
<option value="command">Custon Command</option>
</select>
</div>
<div id="ifBasic">
<div class="form-group">
<label for="server_path">Interval <small class="text-muted ml-1"> - How often you want this task to execute</small> </label>
<input type="number" class="form-control" name="interval" id="interval" value="{{ data['server_stats']['server_id']['path'] }}" placeholder="Interval" required>
<br>
<br>
<select id="interval_type" name="interval_type" class="form-control form-control-lg select-css">
<option value="days">Days</option>
<option value="hours">Hours</option>
<option value="minutes">Minutes</option>
</select>
</div>
<div class="form-group">
<label for="time">Time <small class="text-muted ml-1"> - What time do you want your task to execute?</small> </label>
<input type="time" class="form-control" name="time" id="time" value="{{ data['server_stats']['server_id']['log_path'] }}" placeholder="Time">
</div>
</div>
<div id="ifYes" style="display: none;">
<div class="form-group">
<label for="command">Command <small class="text-muted ml-1"> - What command do you want us to execute? Do not include the '/'</small> </label>
<input type="input" class="form-control" name="command" id="command" value="" placeholder="Command">
</div>
</div>
<div id="ifAdvanced" style="display: none;">
<div class="form-group">
<label for="cron">Cron <small class="text-muted ml-1"> - Input your cron string</small> </label>
<input type="input" class="form-control" name="cron" id="cron" value="" placeholder="* * * * *">
</div>
</div>
<div class="form-check-flat">
<label for="enabled" class="form-check-label ml-4 mb-4">
<input type="checkbox" class="form-check-input" id="enabled" name="enabled" checked="" value="1">Enabled
</label>
</div>
<div class="form-check-flat">
<label for="one_time" class="form-check-label ml-4 mb-4">
<input type="checkbox" class="form-check-input" id="one_time" name="one_time" value="1">Delete After Execution
</label>
</div>
<button type="submit" class="btn btn-success mr-2"><i class="fas fa-save"></i> {{ translate('serverConfig', 'save', data['lang']) }}</button>
<button type="reset" class="btn btn-light"><i class="fas fa-times"></i> {{ translate('serverConfig', 'cancel', data['lang']) }}</button>
</form>
</div>
<div class="col-md-8 col-sm-12" style="overflow-x:auto;">
<a href="/panel/server_tasks_edit">Create Task</a>
<div class="col-md-12 col-sm-12" style="overflow-x:auto;">
<div class="card">
<div class="card-body">
<h4 class="card-title">Scheduled Tasks</h4>
@ -115,6 +44,7 @@
<thead>
<tr class="rounded">
<th>Action</th>
<th>Command</th>
<th>Interval</th>
<th>Start Time</th>
<th>Enabled</th>
@ -127,9 +57,17 @@
<td id="{{schedule.action}}" class="action">
<p>{{schedule.action}}</p>
</td>
<td id="{{schedule.command}}" class="action">
<p>{{schedule.command}}</p>
</td>
<td id="{{schedule.interval}}" class="action">
{% if schedule.interval != '' %}
<p>Every</p>
<p>{{schedule.interval}} {{schedule.interval_type}}</p>
{% else %}
<p>Cron String:</p>
<p>{{schedule.cron_string}}</p>
{% end %}
</td>
<td id="{{schedule.start_time}}" class="action">
<p>{{schedule.start_time}}</p>
@ -194,19 +132,34 @@
function yesnoCheck(that) {
if (that.value == "command") {
document.getElementById("ifYes").style.display = "block";
document.getElementById("command").required = true;
} else {
document.getElementById("ifYes").style.display = "none";
document.getElementById("command").required = false;
}
}
function basicAdvanced(that) {
if (that.value == "advanced") {
document.getElementById("ifAdvanced").style.display = "block";
document.getElementById("ifBasic").style.display = "none";
document.getElementById("interval").required = false;
document.getElementById("time").required = false;
} else {
document.getElementById("ifAdvanced").style.display = "none";
document.getElementById("ifBasic").style.display = "block";
document.getElementById("interval").required = true;
document.getElementById("time").required = true;
}
}
function ifDays(that) {
if (that.value == "days") {
document.getElementById("ifDays").style.display = "block";
document.getElementById("time").required = true;
} else {
document.getElementById("ifDays").style.display = "none";
document.getElementById("time").required = false;
}
}
$( ".del_button" ).click(function() {
var sch_id = $(this).data('sch');

View File

@ -0,0 +1,215 @@
{% extends ../base.html %}
{% block meta %}
<!-- <meta http-equiv="refresh" content="60">-->
{% end %}
{% block title %}Crafty Controller - {{ translate('serverDetails', 'serverDetails', data['lang']) }}{% end %}
{% block content %}
<div class="content-wrapper">
<!-- Page Title Header Starts-->
<div class="row page-title-header">
<div class="col-12">
<div class="page-header">
<h4 class="page-title">
{{ translate('serverDetails', 'serverDetails', data['lang']) }} - {{ data['server_stats']['server_id']['server_name'] }}
<br />
<small>UUID: {{ data['server_stats']['server_id']['server_uuid'] }}</small>
</h4>
</div>
</div>
</div>
<!-- Page Title Header Ends-->
{% include "parts/details_stats.html %}
<div class="row">
<div class="col-sm-12 grid-margin">
<div class="card">
<div class="card-body pt-0">
{% include "parts/server_controls_list.html %}
<div class="row">
<div class="col-md-12 col-sm-12">
<form class="forms-sample" method="post" action="/panel/tasks">
{% raw xsrf_form_html() %}
<input type="hidden" name="id" value="{{ data['server_stats']['server_id']['server_id'] }}">
<input type="hidden" name="subpage" value="config">
<div class="form-group">
<label for="difficulty">Basic / Cron Select<small class="text-muted ml-1"></small> </label><br>
<select id="difficulty" name="difficulty" onchange="basicAdvanced(this);" class="form-control form-control-lg select-css">
<option value="basic">Basic</option>
<option value="advanced">Advanced</option>
</select>
</div>
<div class="form-group">
<label for="server_name">Action<small class="text-muted ml-1"></small> </label><br>
<select id="action" name="action" onchange="yesnoCheck(this);" class="form-control form-control-lg select-css">
<option value="start">Start Server</option>
<option value="restart">Restart Server</option>
<option value="shutdown">Shutdown Server</option>
<option value="backup">Backup Server</option>
<option value="command">Custon Command</option>
</select>
</div>
<div id="ifBasic">
<div class="form-group">
<label for="server_path">Interval <small class="text-muted ml-1"> - How often you want this task to execute</small> </label>
<input type="number" class="form-control" name="interval" id="interval" value="{{ data['server_stats']['server_id']['path'] }}" placeholder="Interval" required>
<br>
<br>
<select id="interval_type" onchange="ifDays(this);" name="interval_type" class="form-control form-control-lg select-css">
<option value="days">Days</option>
<option value="hours">Hours</option>
<option value="minutes">Minutes</option>
</select>
</div>
<div id="ifDays" style="display: block;">
<div class="form-group">
<label for="time">Time <small class="text-muted ml-1"> - What time do you want your task to execute?</small> </label>
<input type="time" class="form-control" name="time" id="time" value="{{ data['server_stats']['server_id']['log_path'] }}" placeholder="Time" required>
</div>
</div>
</div>
<div id="ifYes" style="display: none;">
<div class="form-group">
<label for="command">Command <small class="text-muted ml-1"> - What command do you want us to execute? Do not include the '/'</small> </label>
<input type="input" class="form-control" name="command" id="command" value="" placeholder="Command" required>
</div>
</div>
<div id="ifAdvanced" style="display: none;">
<div class="form-group">
<label for="cron">Cron <small class="text-muted ml-1"> - Input your cron string</small> </label>
<input type="input" class="form-control" name="cron" id="cron" value="" placeholder="* * * * *">
</div>
</div>
<div class="form-check-flat">
<label for="enabled" class="form-check-label ml-4 mb-4">
<input type="checkbox" class="form-check-input" id="enabled" name="enabled" checked="" value="1">Enabled
</label>
</div>
<div class="form-check-flat">
<label for="one_time" class="form-check-label ml-4 mb-4">
<input type="checkbox" class="form-check-input" id="one_time" name="one_time" value="1">Delete After Execution
</label>
</div>
<button type="submit" class="btn btn-success mr-2"><i class="fas fa-save"></i> {{ translate('serverConfig', 'save', data['lang']) }}</button>
<button type="reset" class="btn btn-light"><i class="fas fa-times"></i> {{ translate('serverConfig', 'cancel', data['lang']) }}</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
{% end %}
{% block js %}
<script>
//used to get cookies from browser - this is part of tornados xsrf protection - it's for extra security
function getCookie(name) {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
$( document ).ready(function() {
console.log( "ready!" );
});
function yesnoCheck(that) {
if (that.value == "command") {
document.getElementById("ifYes").style.display = "block";
document.getElementById("command").required = true;
} else {
document.getElementById("ifYes").style.display = "none";
document.getElementById("command").required = false;
}
}
function basicAdvanced(that) {
if (that.value == "advanced") {
document.getElementById("ifAdvanced").style.display = "block";
document.getElementById("ifBasic").style.display = "none";
document.getElementById("interval").required = false;
document.getElementById("time").required = false;
} else {
document.getElementById("ifAdvanced").style.display = "none";
document.getElementById("ifBasic").style.display = "block";
document.getElementById("interval").required = true;
document.getElementById("time").required = true;
}
}
function ifDays(that) {
if (that.value == "days") {
document.getElementById("ifDays").style.display = "block";
document.getElementById("time").required = true;
} else {
document.getElementById("ifDays").style.display = "none";
document.getElementById("time").required = false;
}
}
$( ".del_button" ).click(function() {
var sch_id = $(this).data('sch');
var server_id = {{ data['server_stats']['server_id']['server_id'] }};
console.log(sch_id)
bootbox.confirm({
title: "Test",
message: "{{ translate('serverBackups', 'confirmDelete', data['lang']) }}",
buttons: {
cancel: {
label: '<i class="fas fa-times"></i> {{ translate("serverBackups", "cancel", data['lang']) }}'
},
confirm: {
label: '<i class="fas fa-check"></i> {{ translate("serverBackups", "confirm", data['lang']) }}'
}
},
callback: function (result) {
console.log(result);
if (result == true) {
del_task(sch_id, server_id);
}
}
});
});
function del_task(sch_id, id){
var token = getCookie("_xsrf")
$.ajax({
type: "DELETE",
headers: {'X-XSRFToken': token},
url: '/ajax/del_task?server_id='+id+'&schedule_id='+sch_id,
data: {
schedule_id: sch_id,
id: id
},
success: function(data) {
location.reload();
},
});
}
</script>
{% end %}

View File

@ -0,0 +1,16 @@
# Generated by database migrator
import peewee
def migrate(migrator, database, **kwargs):
migrator.add_columns('schedules', cron_string=peewee.CharField(default=""))
"""
Write your migrations here.
"""
def rollback(migrator, database, **kwargs):
migrator.drop_columns('schedules', ['cron_string'])
"""
Write your rollback migrations here.
"""