fix autotasks

This commit is contained in:
wh1te909 2020-05-30 08:29:44 +00:00
parent 14cb693be9
commit 04cdb51320
9 changed files with 108 additions and 119 deletions

View File

@ -0,0 +1,20 @@
# Generated by Django 3.0.6 on 2020-05-30 07:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('checks', '0004_check_svc_policy_mode'),
('autotasks', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='automatedtask',
name='assigned_check',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assignedtask', to='checks.Check'),
),
]

View File

@ -50,7 +50,7 @@ class AutomatedTask(models.Model):
"checks.Check",
null=True,
blank=True,
related_name="assignedcheck",
related_name="assignedtask",
on_delete=models.SET_NULL,
)
name = models.CharField(max_length=255)

View File

@ -4,17 +4,17 @@ from .models import AutomatedTask
from agents.models import Agent
from scripts.serializers import ScriptSerializer
from checks.serializers import CheckSerializer
class TaskSerializer(serializers.ModelSerializer):
assigned_check = serializers.ReadOnlyField()
assigned_check = CheckSerializer(read_only=True)
schedule = serializers.ReadOnlyField()
class Meta:
model = AutomatedTask
fields = "__all__"
depth = 1
class AgentTaskSerializer(serializers.ModelSerializer):

View File

@ -12,11 +12,12 @@ from rest_framework.decorators import api_view
from .models import AutomatedTask
from agents.models import Agent
from checks.models import Check
from scripts.models import Script
from automation.models import Policy
from .serializers import AutoTaskSerializer, AgentTaskSerializer
from .serializers import TaskSerializer, AutoTaskSerializer, AgentTaskSerializer
from scripts.serializers import ScriptSerializer
from .tasks import (
@ -29,78 +30,35 @@ from .tasks import (
class AddAutoTask(APIView):
def post(self, request):
daily, checkfailure, manual = False, False, False
data = request.data
script = get_object_or_404(Script, pk=data["autotask"]["script"])
# Determine if adding check to Policy or Agent
if "policy" in data:
policy = get_object_or_404(Policy, id=data["policy"])
# Object used for filter and save
parent = {"policy": policy}
else:
agent = get_object_or_404(Agent, pk=data["agent"])
# Object used for filter and save
parent = {"agent": agent}
script = Script.objects.only("pk").get(pk=data["script"])
if data["trigger"] == "daily":
daily = True
days = data["days"]
time = data["time"]
elif data["trigger"] == "checkfailure":
checkfailure = True
check = data["check"]
elif data["trigger"] == "manual":
manual = True
check = None
if data["autotask"]["assigned_check"]:
check = get_object_or_404(Check, pk=data["autotask"]["assigned_check"])
rand_name = AutomatedTask.generate_task_name()
serializer = TaskSerializer(data=data["autotask"], partial=True, context=parent)
serializer.is_valid(raise_exception=True)
obj = serializer.save(
**parent,
script=script,
win_task_name=AutomatedTask.generate_task_name(),
assigned_check=check,
)
try:
timeout = data["timeout"]
except KeyError:
timeout = 130
create_win_task_schedule.delay(pk=obj.pk)
if daily:
task = AutomatedTask(
**parent,
name=data["name"],
script=script,
timeout=timeout,
task_type="scheduled",
win_task_name=rand_name,
run_time_days=data["days"],
run_time_minute=data["time"],
)
task.save()
elif checkfailure:
task = AutomatedTask(
**parent,
name=data["name"],
script=script,
timeout=timeout,
win_task_name=rand_name,
task_type="checkfailure",
)
task.save()
related_check = AutomatedTask.get_related_check(check)
related_check.task_on_failure = task
related_check.save(update_fields=["task_on_failure"])
elif manual:
task = AutomatedTask(
**parent,
name=data["name"],
timeout=timeout,
win_task_name=rand_name,
script=script,
task_type="manual",
)
task.save()
create_win_task_schedule.delay(pk=task.pk)
return Response("ok")
return Response("Task will be created shortly!")
class AutoTask(APIView):

View File

@ -130,9 +130,9 @@ class Check(models.Model):
def __str__(self):
if self.agent:
return f"{self.agent.hostname} - {self.check_type}"
return f"{self.agent.hostname} - {self.readable_desc}"
else:
return f"{self.policy.name} - {self.check_type}"
return f"{self.policy.name} - {self.readable_desc}"
@property
def readable_desc(self):

View File

@ -3,13 +3,26 @@ import validators as _v
from rest_framework import serializers
from .models import Check
from autotasks.models import AutomatedTask
from scripts.serializers import ScriptSerializer
class AssignedTaskField(serializers.ModelSerializer):
class Meta:
model = AutomatedTask
fields = "__all__"
class CheckSerializer(serializers.ModelSerializer):
readable_desc = serializers.ReadOnlyField()
script = ScriptSerializer(read_only=True)
assigned_task = serializers.SerializerMethodField()
def get_assigned_task(self, obj):
if obj.assignedtask.exists():
task = obj.assignedtask.get()
return AssignedTaskField(task).data
class Meta:
model = Check

View File

@ -81,7 +81,8 @@
<q-td v-if="props.row.last_run">{{ props.row.last_run }}</q-td>
<q-td v-else>Has not run yet</q-td>
<q-td>{{ props.row.schedule }}</q-td>
<q-td>{{ props.row.assigned_check }}</q-td>
<q-td v-if="props.row.assigned_check">{{ props.row.assigned_check.readable_desc }}</q-td>
<q-td v-else></q-td>
</q-tr>
</template>
</q-table>

View File

@ -161,7 +161,8 @@
</q-td>
<q-td v-else>{{ props.row.more_info }}</q-td>
<q-td>{{ props.row.last_run }}</q-td>
<q-td>{{ props.row.assigned_task }}</q-td>
<q-td v-if="props.row.assigned_task">{{ props.row.assigned_task.name }}</q-td>
<q-td v-else></q-td>
</q-tr>
</template>
</q-table>

View File

@ -6,7 +6,7 @@
<q-btn icon="close" flat round dense v-close-popup />
</q-card-section>
<q-card-section>
<p>You need to upload a script/task first</p>
<p>You need to upload a script first</p>
<p>Settings -> Script Manager</p>
</q-card-section>
</q-card>
@ -23,7 +23,7 @@
:rules="[val => !!val || '*Required']"
dense
outlined
v-model="scriptPk"
v-model="autotask.script"
:options="scriptOptions"
label="Select task"
map-options
@ -35,7 +35,7 @@
:rules="[val => !!val || '*Required']"
outlined
dense
v-model="taskName"
v-model="autotask.name"
label="Descriptive name of task"
/>
</q-card-section>
@ -44,7 +44,7 @@
:rules="[val => !!val || '*Required']"
outlined
dense
v-model.number="timeout"
v-model.number="autotask.timeout"
type="number"
label="Maximum permitted execution time (seconds)"
/>
@ -52,28 +52,38 @@
</q-step>
<q-step :name="2" title="Choose Schedule" :done="step2Done" :error="!step2Done">
<q-radio v-model="trigger" val="daily" label="Scheduled" />
<q-radio v-model="trigger" val="checkfailure" label="On check failure" />
<q-radio v-model="trigger" val="manual" label="Manual" />
<div v-if="trigger === 'daily'" class="row q-pa-lg">
<q-radio v-model="autotask.task_type" val="scheduled" label="Scheduled" @input="clear" />
<q-radio
v-model="autotask.task_type"
val="checkfailure"
label="On check failure"
@input="clear"
/>
<q-radio v-model="autotask.task_type" val="manual" label="Manual" @input="clear" />
<div v-if="autotask.task_type === 'scheduled'" class="row q-pa-lg">
<div class="col-3">
Run on Days:
<q-option-group :options="dayOptions" label="Days" type="checkbox" v-model="days" />
<q-option-group
:options="dayOptions"
label="Days"
type="checkbox"
v-model="autotask.run_time_days"
/>
</div>
<div class="col-2"></div>
<div class="col-6">
At time:
<q-time v-model="time" />
<q-time v-model="autotask.run_time_minute" />
</div>
<div class="col-1"></div>
</div>
<div v-else-if="trigger === 'checkfailure'" class="q-pa-lg">
<div v-else-if="autotask.task_type === 'checkfailure'" class="q-pa-lg">
When Check Fails:
<q-select
:rules="[val => !!val || '*Required']"
dense
outlined
v-model="assignedCheck"
v-model="autotask.assigned_check"
:options="checksOptions"
label="Select Check"
map-options
@ -120,13 +130,15 @@ export default {
data() {
return {
step: 1,
trigger: "daily",
time: null,
taskName: null,
scriptPk: null,
assignedCheck: null,
timeout: 120,
days: [],
autotask: {
script: null,
assigned_check: null,
name: null,
run_time_days: [],
run_time_minute: null,
task_type: "scheduled",
timeout: 120
},
dayOptions: [
{ label: "Monday", value: 0 },
{ label: "Tuesday", value: 1 },
@ -139,6 +151,11 @@ export default {
};
},
methods: {
clear() {
this.autotask.assigned_check = null;
this.autotask.run_time_days = [];
this.autotask.run_time_minute = null;
},
addTask() {
if (!this.step1Done || !this.step2Done) {
this.notifyError("Some steps incomplete");
@ -147,16 +164,9 @@ export default {
const data = {
...pk,
name: this.taskName,
script: this.scriptPk,
trigger: this.trigger,
check: this.assignedCheck,
time: this.time,
days: this.days,
timeout: this.timeout
autotask: this.autotask
};
console.log(data);
axios
.post("tasks/automatedtasks/", data)
.then(r => {
@ -180,48 +190,34 @@ export default {
},
computed: {
...mapGetters(["selectedAgentPk", "scripts"]),
/* ...mapState({
checks: state => (this.policypk ? state.automation.checks : state.agentChecks)
}), */
// I have no idea why this works and the above doesn't
checks() {
return this.policypk ? this.$store.state.automation.checks : this.$store.state.agentChecks;
},
allChecks() {
return [
...this.checks.diskchecks,
...this.checks.cpuloadchecks,
...this.checks.memchecks,
...this.checks.scriptchecks,
...this.checks.winservicechecks,
...this.checks.pingchecks,
...this.checks.eventlogchecks
];
},
checksOptions() {
const r = [];
this.allChecks.forEach(k => {
// some checks may have the same primary key so add the check type to make them unique
r.push({ label: k.readable_desc, value: `${k.id}|${k.check_type}` });
this.checks.forEach(i => {
r.push({ label: i.readable_desc, value: i.id });
});
return r;
},
scriptOptions() {
const r = [];
this.scripts.forEach(k => {
r.push({ label: k.name, value: k.id });
this.scripts.forEach(i => {
r.push({ label: i.name, value: i.id });
});
return r;
},
step1Done() {
return this.step > 1 && this.scriptPk !== null && this.taskName !== null ? true : false;
return this.step > 1 && this.autotask.script !== null && this.autotask.name && this.autotask.timeout
? true
: false;
},
step2Done() {
if (this.trigger === "daily") {
return this.days !== null && this.days.length !== 0 && this.time !== null ? true : false;
} else if (this.trigger === "checkfailure") {
return this.assignedCheck !== null && this.assignedCheck.length !== 0 ? true : false;
} else if (this.trigger === "manual") {
if (this.autotask.task_type === "scheduled") {
return this.autotask.run_time_days.length !== 0 && this.autotask.run_time_minute !== null ? true : false;
} else if (this.autotask.task_type === "checkfailure") {
return this.autotask.assigned_check !== null ? true : false;
} else if (this.autotask.task_type === "manual") {
return true;
} else {
return false;