NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 30 of 30 · Tools for the NASFinish a tool

TIniFile reads the limit, RunCommand calls grep and the program saves the list as report.txt.

Programming on the NAS › Pascal in 30 lessons

30-report.pas Download 30-report.pas

program Report;
{$mode objfpc}{$H+}
{ The state of volumes, disks and the log. The limit comes from config.ini. }
uses
  SysUtils, Classes, IniFiles, Process;
var
  Output: TStringList;
  Bad, Limit: Integer;

procedure Say(const Text: string; Wrong: Boolean);
begin
  if Wrong then
  begin
    Output.Add('  LOOK  ' + Text);
    Inc(Bad);
  end
  else
    Output.Add('  ok    ' + Text);
end;

procedure Each(const FileName: string; Fields: Integer; Volume: Boolean);
var
  F: TextFile;
  Line: string;
  Part: TStringArray;
  Raw: Integer;
begin
  AssignFile(F, FileName);
  Reset(F);
  ReadLn(F);
  while not Eof(F) do
  begin
    ReadLn(F, Line);
    Part := Trim(Line).Split([' '], TStringSplitOptions.ExcludeEmpty);
    if Length(Part) < Fields then
      Continue;
    if Volume then
    begin
      Raw := StrToIntDef(StringReplace(Part[4], '%', '', []), 0);
      Say(Format('%s %d percent used', [Part[5], Raw]), Raw >= Limit);
    end
    else
    begin
      Raw := StrToIntDef(Part[9], 0);
      case Part[1] of
        'Reallocated_Sector_Ct', 'Current_Pending_Sector':
          Say(Format('%s %d', [Part[1], Raw]), Raw > 0);
        'Temperature_Celsius':
          Say(Format('%s %d', [Part[1], Raw]), Raw >= 50);
      end;
    end;
  end;
  CloseFile(F);
end;

var
  Ini: TIniFile;
  Count: string;
begin
  Output := TStringList.Create;
  Ini := TIniFile.Create('config.ini');
  try
    Limit := Ini.ReadInteger('report', 'limit', 90);
    Output.Add(Ini.ReadString('report', 'title', 'Report'));
    Output.Add('Volumes');
    Each('df.txt', 6, True);
    Output.Add('Disks');
    Each('smartctl.txt', 10, False);
    Output.Add('Log');
    RunCommand('grep', ['-c', ' ERROR ', 'nas.log'], Count);
    Say(Trim(Count) + ' errors', Trim(Count) <> '0');
    Output.SaveToFile('report.txt');
    Write(Output.Text);
    WriteLn(Bad, ' lines need a look');
    if Bad > 0 then
      ExitCode := 1;
  finally
    Ini.Free;
    Output.Free;
  end;
end.

Terminal

$ ./30-report; echo "exit code $?"
Morning check
Volumes
  ok    /volume/data 75 percent used
  LOOK  /volume/media 93 percent used
  ok    /volume/fast 20 percent used
Disks
  LOOK  Reallocated_Sector_Ct 8
  ok    Temperature_Celsius 38
  ok    Current_Pending_Sector 0
Log
  LOOK  3 errors
3 lines need a look
exit code 1
$ head -n 2 report.txt
Morning check
Volumes

Exercise

Add the days a disk has been on.