finish script checks

This commit is contained in:
wh1te909 2020-02-06 06:32:30 +00:00
parent 37eef466a1
commit 400f5d2efc
13 changed files with 356 additions and 65 deletions

View File

@ -0,0 +1,22 @@
# Generated by Django 3.0.3 on 2020-02-06 05:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agents', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='agent',
name='ping_check_interval',
),
migrations.AddField(
model_name='agent',
name='check_interval',
field=models.PositiveIntegerField(default=120),
),
]

View File

@ -45,7 +45,7 @@ class Agent(models.Model):
overdue_time = models.PositiveIntegerField(default=30)
uninstall_pending = models.BooleanField(default=False)
uninstall_inprogress = models.BooleanField(default=False)
ping_check_interval = models.PositiveIntegerField(default=300)
check_interval = models.PositiveIntegerField(default=120)
needs_reboot = models.BooleanField(default=False)
managed_by_wsus = models.BooleanField(default=False)
is_updating = models.BooleanField(default=False)
@ -67,7 +67,6 @@ class Agent(models.Model):
else:
return "online"
@property
def has_patches_pending(self):
from winupdate.models import WinUpdate
@ -80,7 +79,7 @@ class Agent(models.Model):
@property
def salt_id(self):
return f"{self.hostname}-{self.pk}"
@staticmethod
def salt_api_cmd(**kwargs):
try:
@ -177,4 +176,3 @@ class Agent(models.Model):
}, timeout=100)
return resp """

View File

@ -44,7 +44,7 @@ class AgentSerializer(serializers.ModelSerializer):
"status",
"uninstall_pending",
"uninstall_inprogress",
"ping_check_interval",
"check_interval",
"needs_reboot",
"managed_by_wsus",
"is_updating",
@ -64,4 +64,3 @@ class AgentHostnameSerializer(serializers.ModelSerializer):
"client",
"site",
)

View File

@ -35,7 +35,7 @@ class TestAgentViews(BaseTestCase):
"montype": "workstation",
"desc": "asjdk234andasd",
"overduetime": 300,
"pinginterval": 60,
"checkinterval": 60,
"emailalert": True,
"textalert": False,
"critical": "approve",

View File

@ -102,7 +102,7 @@ def edit_agent(request):
agent.monitoring_type = request.data["montype"]
agent.description = request.data["desc"]
agent.overdue_time = request.data["overduetime"]
agent.ping_check_interval = request.data["pinginterval"]
agent.check_interval = request.data["checkinterval"]
agent.overdue_email_alert = request.data["emailalert"]
agent.overdue_text_alert = request.data["textalert"]
@ -126,7 +126,7 @@ def edit_agent(request):
"site",
"monitoring_type",
"description",
"ping_check_interval",
"check_interval",
"overdue_time",
"overdue_email_alert",
"overdue_text_alert",
@ -199,9 +199,7 @@ def get_processes(request, pk):
agent = get_object_or_404(Agent, pk=pk)
try:
resp = agent.salt_api_cmd(
hostname=agent.salt_id,
timeout=70,
func="process_manager.get_procs"
hostname=agent.salt_id, timeout=70, func="process_manager.get_procs"
)
data = resp.json()
except Exception:
@ -211,14 +209,12 @@ def get_processes(request, pk):
return Response(data["return"][0][agent.salt_id])
@api_view()
def kill_proc(request, pk, pid):
agent = get_object_or_404(Agent, pk=pk)
resp = agent.salt_api_cmd(
hostname=agent.salt_id,
timeout=60,
func="ps.kill_pid",
arg=int(pid)
hostname=agent.salt_id, timeout=60, func="ps.kill_pid", arg=int(pid)
)
data = resp.json()

View File

@ -100,7 +100,7 @@ class CheckSerializer(serializers.ModelSerializer):
"hostname",
"pk",
"disks",
"ping_check_interval",
"check_interval",
"diskchecks",
"cpuloadchecks",
"memchecks",

View File

@ -12,4 +12,5 @@ urlpatterns = [
path("checkalert/", views.check_alert),
path("updatepingcheck/", views.update_ping_check),
path("updatescriptcheck/", views.update_script_check),
path("getscripts/", views.get_scripts),
]

View File

@ -23,6 +23,7 @@ from .models import (
CpuLoadCheck,
MemCheck,
WinServiceCheck,
Script,
ScriptCheck,
ScriptCheckEmail,
validate_threshold,
@ -36,11 +37,18 @@ from .serializers import (
MemCheckSerializer,
WinServiceCheckSerializer,
ScriptCheckSerializer,
ScriptSerializer,
)
from .tasks import handle_check_email_alert_task
@api_view()
def get_scripts(request):
scripts = Script.objects.all()
return Response(ScriptSerializer(scripts, many=True, read_only=True).data)
@api_view(["PATCH"])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
@ -62,12 +70,12 @@ def update_ping_check(request):
if new_count >= check.failures:
alert = True
if alert:
if check.email_alert:
handle_check_email_alert_task.delay("ping", check.pk)
if alert and check.email_alert:
handle_check_email_alert_task.delay("ping", check.pk)
return Response("ok")
@api_view(["PATCH"])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
@ -75,26 +83,12 @@ def update_script_check(request):
check = get_object_or_404(ScriptCheck, pk=request.data["id"])
try:
retcode = request.data["output"]["local"]["retcode"]
output = request.data["output"]
status = request.data["status"]
except Exception:
retcode = 1
if retcode == 0:
status = "passing"
else:
output = "something went wrong"
status = "failing"
try:
stdout = request.data["output"]["local"]["stdout"]
stderr = request.data["output"]["local"]["stderr"]
except Exception:
output = "error running script"
else:
if stdout:
output = stdout
else:
output = stderr
check.status = status
check.more_info = output
check.save(update_fields=["status", "more_info", "last_run"])
@ -111,9 +105,8 @@ def update_script_check(request):
if new_count >= check.failures:
alert = True
if alert:
if check.email_alert:
handle_check_email_alert_task.delay("script", check.pk)
if alert and check.email_alert:
handle_check_email_alert_task.delay("script", check.pk)
return Response("ok")
@ -218,6 +211,28 @@ def add_standard_check(request):
).save()
return Response("ok")
elif request.data["check_type"] == "script":
script_pk = request.data["scriptPk"]
timeout = request.data["timeout"]
failures = request.data["failures"]
script = Script.objects.get(pk=script_pk)
if ScriptCheck.objects.filter(agent=agent).filter(script=script).exists():
return Response(
f"{script.name} already exists on {agent.hostname}",
status=status.HTTP_400_BAD_REQUEST,
)
ScriptCheck(
agent=agent, timeout=timeout, failures=failures, script=script
).save()
return Response(f"{script.name} was added on {agent.hostname}!")
else:
return Response("something went wrong", status=status.HTTP_400_BAD_REQUEST)
@api_view(["PATCH"])
def edit_standard_check(request):
@ -269,6 +284,13 @@ def edit_standard_check(request):
)
return Response("ok")
elif request.data["check_type"] == "script":
check = get_object_or_404(ScriptCheck, pk=request.data["pk"])
check.failures = request.data["failures"]
check.timeout = request.data["timeout"]
check.save(update_fields=["failures", "timeout"])
return Response(f"{check.script.name} was edited on {check.agent.hostname}")
@api_view()
def get_standard_check(request, checktype, pk):
@ -287,6 +309,9 @@ def get_standard_check(request, checktype, pk):
elif checktype == "winsvc":
check = WinServiceCheck.objects.get(pk=pk)
return Response(WinServiceCheckSerializer(check).data)
elif checktype == "script":
check = ScriptCheck.objects.get(pk=pk)
return Response(ScriptCheckSerializer(check).data)
@api_view(["DELETE"])
@ -302,6 +327,8 @@ def delete_standard_check(request):
check = MemCheck.objects.get(pk=pk)
elif request.data["checktype"] == "winsvc":
check = WinServiceCheck.objects.get(pk=pk)
elif request.data["checktype"] == "script":
check = ScriptCheck.objects.get(pk=pk)
check.delete()
return Response("ok")
@ -323,6 +350,8 @@ def check_alert(request):
check = PingCheck.objects.get(pk=checkid)
elif category == "winsvc":
check = WinServiceCheck.objects.get(pk=checkid)
elif category == "script":
check = ScriptCheck.objects.get(pk=checkid)
else:
return Response(
{"error": "Something went wrong"}, status=status.HTTP_400_BAD_REQUEST

View File

@ -20,6 +20,9 @@
<q-item clickable v-close-popup @click="showAddWinSvcCheck = true">
<q-item-section>Windows Service Check</q-item-section>
</q-item>
<q-item clickable v-close-popup @click="showAddScriptCheck = true">
<q-item-section>Script Check</q-item-section>
</q-item>
</q-list>
</q-menu>
</q-btn>
@ -38,9 +41,8 @@
<th width="33%" class="text-left">More Info</th>
<th width="34%" class="text-left">Date / Time</th>
</thead>
<tbody>
<q-tr
v-for="check in allChecks"
:key="check.id + check.check_type"
@ -49,11 +51,15 @@
<q-menu context-menu>
<q-list dense style="min-width: 200px">
<q-item clickable v-close-popup @click="editCheck(check.check_type)">
<q-item-section side><q-icon name="edit" /></q-item-section>
<q-item-section side>
<q-icon name="edit" />
</q-item-section>
<q-item-section>Edit</q-item-section>
</q-item>
<q-item clickable v-close-popup @click="deleteCheck(check.id, check.check_type)">
<q-item-section side><q-icon name="delete" /></q-item-section>
<q-item-section side>
<q-icon name="delete" />
</q-item-section>
<q-item-section>Delete</q-item-section>
</q-item>
<q-separator></q-separator>
@ -87,11 +93,14 @@
v-if="check.check_type === 'diskspace'"
>Disk Space Drive {{ check.disk }} > {{check.threshold }}%</td>
<td v-else-if="check.check_type === 'cpuload'">Avg CPU Load > {{ check.cpuload }}%</td>
<td v-else-if="check.check_type === 'script'">Script check: {{ check.script.name }}</td>
<td v-else-if="check.check_type === 'ping'">Ping {{ check.name }} ({{ check.ip }})</td>
<td
v-else-if="check.check_type === 'memory'"
>Avg memory usage > {{ check.threshold }}%</td>
<td v-else-if="check.check_type === 'winsvc'">Service Check - {{ check.svc_display_name }}</td>
<td
v-else-if="check.check_type === 'winsvc'"
>Service Check - {{ check.svc_display_name }}</td>
<td v-if="check.status === 'pending'">Awaiting First Synchronization</td>
<td v-else-if="check.status === 'passing'">
<q-badge color="positive">Passing</q-badge>
@ -100,19 +109,21 @@
<q-badge color="negative">Failing</q-badge>
</td>
<td v-if="check.check_type === 'ping'">
<span
<span
style="cursor:pointer;color:blue;text-decoration:underline"
@click="pingMoreInfo(check.more_info)"
>
output
</span>
@click="moreInfo('Ping', check.more_info)"
>output</span>
</td>
<td v-else-if="check.check_type === 'script'">
<span
style="cursor:pointer;color:blue;text-decoration:underline"
@click="moreInfo('Script Check', check.more_info)"
>output</span>
</td>
<td v-else>{{ check.more_info }}</td>
<td>{{ check.last_run }}</td>
</q-tr>
</tbody>
</q-markup-table>
</template>
</div>
@ -169,6 +180,17 @@
:agentpk="checks.pk"
/>
</q-dialog>
<!-- script check -->
<q-dialog v-model="showAddScriptCheck">
<AddScriptCheck @close="showAddScriptCheck = false" :agentpk="checks.pk" />
</q-dialog>
<q-dialog v-model="showEditScriptCheck">
<EditScriptCheck
@close="showEditScriptCheck = false"
:editCheckPK="editCheckPK"
:agentpk="checks.pk"
/>
</q-dialog>
</div>
</template>
@ -186,6 +208,8 @@ import AddMemCheck from "@/components/modals/checks/AddMemCheck";
import EditMemCheck from "@/components/modals/checks/EditMemCheck";
import AddWinSvcCheck from "@/components/modals/checks/AddWinSvcCheck";
import EditWinSvcCheck from "@/components/modals/checks/EditWinSvcCheck";
import AddScriptCheck from "@/components/modals/checks/AddScriptCheck";
import EditScriptCheck from "@/components/modals/checks/EditScriptCheck";
export default {
name: "ChecksTab",
@ -199,7 +223,9 @@ export default {
AddMemCheck,
EditMemCheck,
AddWinSvcCheck,
EditWinSvcCheck
EditWinSvcCheck,
AddScriptCheck,
EditScriptCheck
},
mixins: [mixins],
data() {
@ -214,6 +240,8 @@ export default {
showEditMemCheck: false,
showAddWinSvcCheck: false,
showEditWinSvcCheck: false,
showAddScriptCheck: false,
showEditScriptCheck: false,
editCheckPK: null
};
},
@ -238,10 +266,10 @@ export default {
onRefresh(id) {
this.$store.dispatch("loadChecks", id);
},
pingMoreInfo(output) {
moreInfo(name, output) {
this.$q.dialog({
title: "Ping output",
style: "width: 600px; max-width: 90vw",
title: `${name} output`,
style: "width: 80vw; max-width: 90vw",
message: `<pre>${output}</pre>`,
html: true,
dark: true
@ -264,6 +292,9 @@ export default {
case "winsvc":
this.showEditWinSvcCheck = true;
break;
case "script":
this.showEditScriptCheck = true;
break;
default:
return false;
}
@ -294,11 +325,12 @@ export default {
}),
allChecks() {
return [
...this.checks.pingchecks,
...this.checks.diskchecks,
...this.checks.cpuloadchecks,
...this.checks.memchecks,
...this.checks.winservicechecks
...this.checks.scriptchecks,
...this.checks.winservicechecks,
...this.checks.pingchecks
];
}
}

View File

@ -52,8 +52,8 @@
<q-input
dense
outlined
v-model.number="pingInterval"
label="Interval for ping checks (seconds)"
v-model.number="checkInterval"
label="Interval for checks (seconds)"
:rules="[
val => !!val || '*Required',
val => val >= 60 || 'Minimum is 60 seconds',
@ -246,7 +246,7 @@ export default {
monTypes: ["server", "workstation"],
desc: "",
overdueTime: null,
pingInterval: null,
checkInterval: null,
emailAlert: null,
textAlert: null,
tree: {},
@ -282,7 +282,7 @@ export default {
this.monType = r.data.monitoring_type;
this.desc = r.data.description;
this.overdueTime = r.data.overdue_time;
this.pingInterval = r.data.ping_check_interval;
this.checkInterval = r.data.check_interval;
this.emailAlert = r.data.overdue_email_alert;
this.textAlert = r.data.overdue_text_alert;
this.updatePolicy = r.data.winupdatepolicy;
@ -312,7 +312,7 @@ export default {
montype: this.monType,
desc: this.desc,
overduetime: this.overdueTime,
pinginterval: this.pingInterval,
checkinterval: this.checkInterval,
emailalert: this.emailAlert,
textalert: this.textAlert,
critical: this.critical,

View File

@ -0,0 +1,113 @@
<template>
<q-card v-if="scripts.length === 0" style="min-width: 400px">
<q-card-section class="row items-center">
<div class="text-h6">Add Script Check</div>
<q-space />
<q-btn icon="close" flat round dense v-close-popup />
</q-card-section>
<q-card-section>
<p>You need to upload a script first</p>
<p>Settings -> Script Manager</p>
</q-card-section>
</q-card>
<q-card v-else style="min-width: 400px">
<q-card-section class="row items-center">
<div class="text-h6">Add Script Check</div>
<q-space />
<q-btn icon="close" flat round dense v-close-popup />
</q-card-section>
<q-form @submit.prevent="addScriptCheck">
<q-card-section>
<q-select
:rules="[val => !!val || '*Required']"
dense
outlined
v-model="scriptName"
:options="scriptOptions"
label="Select script"
/>
</q-card-section>
<q-card-section>
<q-input
outlined
dense
v-model.number="timeout"
label="Timeout (seconds)"
:rules="[
val => !!val || '*Required',
val => val >= 10 || 'Minimum is 10 seconds',
val => val <= 86400 || 'Maximum is 86400 seconds'
]"
/>
</q-card-section>
<q-card-section>
<q-select
outlined
dense
v-model="failure"
:options="failures"
label="Number of consecutive failures before alert"
/>
</q-card-section>
<q-card-actions align="right">
<q-btn label="Add" color="primary" type="submit" />
<q-btn label="Cancel" v-close-popup />
</q-card-actions>
</q-form>
</q-card>
</template>
<script>
import axios from "axios";
import { mapState } from "vuex";
import { mapGetters } from "vuex";
import mixins from "@/mixins/mixins";
export default {
name: "AddScriptCheck",
props: ["agentpk"],
mixins: [mixins],
data() {
return {
scriptName: null,
failure: 1,
failures: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
timeout: 120
};
},
methods: {
getScripts() {
this.$store.dispatch("getScripts");
},
addScriptCheck() {
const data = {
pk: this.agentpk,
check_type: "script",
scriptPk: this.scriptPk,
timeout: this.timeout,
failures: this.failure
};
axios
.post("/checks/addstandardcheck/", data)
.then(r => {
this.$emit("close");
this.$store.dispatch("loadChecks", this.agentpk);
this.notifySuccess(r.data);
})
.catch(e => this.notifyError(e.response.data));
}
},
computed: {
...mapGetters(["scripts"]),
scriptOptions() {
return this.scripts.map(k => k.name).sort();
},
scriptPk(name) {
return this.scripts.filter(k => k.name === this.scriptName)[0].id;
}
},
created() {
this.getScripts();
}
};
</script>

View File

@ -0,0 +1,89 @@
<template>
<q-card style="min-width: 400px">
<q-card-section class="row items-center">
<div class="text-h6">Edit Script Check</div>
<q-space />
<q-btn icon="close" flat round dense v-close-popup />
</q-card-section>
<q-form @submit.prevent="editScriptCheck">
<q-card-section>
<q-select dense outlined v-model="scriptName" disable label="Select script" />
</q-card-section>
<q-card-section>
<q-input
outlined
dense
v-model.number="timeout"
label="Timeout (seconds)"
:rules="[
val => !!val || '*Required',
val => val >= 10 || 'Minimum is 10 seconds',
val => val <= 86400 || 'Maximum is 86400 seconds'
]"
/>
</q-card-section>
<q-card-section>
<q-select
outlined
dense
v-model="failure"
:options="failures"
label="Number of consecutive failures before alert"
/>
</q-card-section>
<q-card-actions align="right">
<q-btn label="Edit" color="primary" type="submit" />
<q-btn label="Cancel" v-close-popup />
</q-card-actions>
</q-form>
</q-card>
</template>
<script>
import axios from "axios";
import mixins from "@/mixins/mixins";
export default {
name: "EditScriptCheck",
props: ["agentpk", "editCheckPK"],
mixins: [mixins],
data() {
return {
scriptName: null,
failure: null,
failures: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
timeout: null
};
},
methods: {
getScriptCheck() {
axios
.get(`/checks/getstandardcheck/script/${this.editCheckPK}/`)
.then(r => {
this.failure = r.data.failures;
this.timeout = r.data.timeout;
this.scriptName = r.data.script.name;
});
},
editScriptCheck() {
const data = {
pk: this.editCheckPK,
check_type: "script",
failures: this.failure,
timeout: this.timeout
};
axios
.patch("/checks/editstandardcheck/", data)
.then(r => {
this.$emit("close");
this.$store.dispatch("loadChecks", this.agentpk);
this.notifySuccess(r.data);
})
.catch(e => this.notifyError(e.response.data.error));
}
},
created() {
this.getScriptCheck();
}
};
</script>

View File

@ -23,7 +23,8 @@ export const store = new Vuex.Store({
agentChecks: {},
agentTableLoading: false,
treeLoading: false,
installedSoftware: []
installedSoftware: [],
scripts: [],
},
getters: {
loggedIn(state) {
@ -50,6 +51,9 @@ export const store = new Vuex.Store({
},
agentHostname(state) {
return state.agentSummary.hostname;
},
scripts(state) {
return state.scripts;
}
},
mutations: {
@ -92,9 +96,17 @@ export const store = new Vuex.Store({
(state.winUpdates = {});
(state.installedSoftware = []);
state.selectedRow = "";
},
SET_SCRIPTS(state, scripts) {
state.scripts = scripts;
}
},
actions: {
getScripts(context) {
axios.get("/checks/getscripts/").then(r => {
context.commit("SET_SCRIPTS", r.data);
})
},
loadInstalledSoftware(context, pk) {
axios.get(`/software/installed/${pk}`).then(r => {
context.commit("SET_INSTALLED_SOFTWARE", r.data.software);