diff --git a/Policies/storage_space.policy.yml b/Policies/storage_space.policy.yml new file mode 100644 index 0000000..a608a13 --- /dev/null +++ b/Policies/storage_space.policy.yml @@ -0,0 +1,17 @@ +title: "Storage Space" +class: \Drutiny\algm\Audit\StorageSpace +name: algm:StorageSpace +tags: + - Space + - Storage +description: | + A policy to notify when disk usage goes below a certain percentage threshold +success: | + {{ status }} +failure: | + {{ status }} +warning: | + {{ warning_message }} +parameters: + threshold_percent: + default: 10 diff --git a/src/Audit/StorageSpace.php b/src/Audit/StorageSpace.php new file mode 100644 index 0000000..2e3baba --- /dev/null +++ b/src/Audit/StorageSpace.php @@ -0,0 +1,98 @@ +getTarget() instanceof DrushTarget; + } + + /** + * @inheritdoc + */ + public function audit(Sandbox $sandbox) { + + $threshold = (int) $sandbox->getParameter('threshold_percent'); + $status = $sandbox->drush(['format' => 'json'])->status(); + + if ($status === null) { + return AUDIT::ERROR; + } + + try { + $output = $sandbox->exec("df -H"); + } + catch (Exception $e) { + return Audit::ERROR; + } + + $disk = array_map(function($line) { + $elements = preg_split('/\s+/', $line); + return([ + 'filesystem' => isset($elements[0]) ? $elements[0] : '', + 'size' => isset($elements[1]) ? $elements[1] : '', + 'used' => isset($elements[2]) ? $elements[2] : '', + 'available' => isset($elements[3]) ? $elements[3] : '', + 'use%' => isset($elements[4]) ? $elements[4] : '', + 'mounted' => isset($elements[5]) ? $elements[5] : '', + ]); + }, explode("\n",$output)); + + array_shift($disk); + $storage_warnings = []; + foreach ($disk as $item) { + if (!empty($item['use%'])) { + $use = (int) str_replace('%', '', $item['use%']); + if ((100-$use) <= $threshold) { + $free_space = 100 - (int) str_replace('%', '', $item['use%']) . '%'; + $storage_warnings[] = "⚠️\t" .$item['filesystem'] . ' free space: ' . $free_space; + } + } //end if + } //end for + + if (count($storage_warnings)) { + $msg = "The following filesystems are bellow or euqal to the threshold ({$threshold}%)." . PHP_EOL; + foreach ($storage_warnings as $item) { + $msg .= $item . PHP_EOL; + } + $sandbox->setParameter('warning_message', $msg); + return Audit::WARNING; + } + + $sandbox->setParameter('status', "All filestystems have free space above threshhold ({$threshold}%)."); + return Audit::SUCCESS; + } +}