comparison ServerMonitor/Objects/Checks/DiskSpaceCheck.cs @ 2:453ecc1ed9ea

Disk space check
author Brad Greco <brad@bgreco.net>
date Sun, 06 Jan 2019 20:49:08 -0500
parents
children 96f0b028176d
comparison
equal deleted inserted replaced
1:9e92780ebc0f 2:453ecc1ed9ea
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Linq;
5 using System.Text;
6 using System.Threading.Tasks;
7
8 namespace ServerMonitorApp
9 {
10 [DisplayName("Disk space check"), Description("Check the remaining free disk space"), DisplayWeight(11)]
11 public class DiskSpaceCheck : SshCheck
12 {
13 public string Device { get; set; }
14
15 public double MinFreeSpace { get; set; }
16
17 public FreeSpaceUnits FreeSpaceUnits { get; set; }
18
19 public DiskSpaceCheck()
20 {
21 Command = "df -P -k {0} | awk 'NR>1' | tr -s ' ' | cut -d ' ' -f 4,5";
22 CheckExitCode = true;
23 ExitCode = 0;
24 }
25
26 protected override string GetCommand()
27 {
28 return string.Format(base.GetCommand(), Device);
29 }
30
31 protected override List<CheckResult> ProcessCommandResult(string output, int exitCode)
32 {
33 List<CheckResult> results = base.ProcessCommandResult(output, exitCode);
34 if (output.Split('\n').Length > 1)
35 {
36 results.Add(Fail("df output was more than one line: " + output));
37 }
38 else
39 {
40
41 string[] tokens = output.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
42 if (FreeSpaceUnits == FreeSpaceUnits.percent)
43 {
44 if (int.TryParse(tokens[1].Replace("%", ""), out int percent))
45 {
46 percent = 100 - percent;
47 string message = string.Format("Free disk space is {0}%", percent);
48 if (percent < MinFreeSpace)
49 results.Add(Fail(message));
50 else
51 results.Add(Pass(message));
52 }
53 else
54 {
55 results.Add(Fail("Unable to parse df output as integer: " + tokens[1].Replace("%", "")));
56 }
57 }
58 else
59 {
60 if (int.TryParse(tokens[0], out int freeSpace))
61 {
62 freeSpace /= 1024;
63 if (FreeSpaceUnits == FreeSpaceUnits.GB)
64 freeSpace /= 1024;
65 string message = string.Format("Free disk space is {0} {1}", freeSpace, FreeSpaceUnits);
66 if (freeSpace < MinFreeSpace)
67 results.Add(Fail(message));
68 else
69 results.Add(Pass(message));
70 }
71 else
72 {
73 results.Add(Fail("Unable to parse df output as integer: " + tokens[0]));
74 }
75 }
76 }
77 return results;
78 }
79
80 public override string Validate(bool saving = true)
81 {
82 string message = base.Validate();
83 if (Device.IsNullOrEmpty())
84 message += "Device is required." + Environment.NewLine;
85 if (MinFreeSpace <= 0)
86 message += "Free space must be greater than 0." + Environment.NewLine;
87 else if (FreeSpaceUnits == FreeSpaceUnits.percent && MinFreeSpace > 100)
88 message += "Free space percent must be between 0 and 100." + Environment.NewLine;
89 return message;
90 }
91 }
92
93 public enum FreeSpaceUnits { MB = 0, GB = 1, percent = 2 }
94 }