NASutils Knowledge BaseUnofficialPolski

Pascal · projectA NAS summary in two columns in Free Pascal

This program shows the state of the NAS on one screen in two columns. On the left: the cores and logical processors, the CPU and system temperatures, the load and the memory. On the right: each data volume and the bytes each network port has received and sent. It prints once and ends.

Programming on the NAS › Pascal in 30 lessons

 TBS-h574TX   12th Gen Intel(R) Core(TM) i5-1235U                              
┌─ System ────────────────────────────┐ ┌─ Volumes ───────────────────────────┐
│ Cores               10              │ │ CACHEDEV1_DATA  281.8 GiB of 1.3 TiB │
│ Logical processors  12              │ │         ████░░░░░░░░░░░░░░░░  21 %  │
│                                     │ │ CACHEDEV2_DATA  177.1 GiB of 1.2 TiB │
│ CPU                 53 °C           │ │         ███░░░░░░░░░░░░░░░░░  14 %  │
│ System              34 °C           │ └─────────────────────────────────────┘
│                                     │ ┌─ Network ───────────────────────────┐
│ Load    1.17  0.90  0.88            │ │ eth0    received  51.4 GiB          │
│         ██░░░░░░░░░░░░░░░░░░  10 %  │ │         sent      10.2 GiB          │
│                                     │ │ eth1    received  567.3 KiB         │
│ Memory  5.6 GiB of 15.4 GiB         │ │         sent      11.4 MiB          │
│         ███████░░░░░░░░░░░░░  36 %  │ └─────────────────────────────────────┘
└─────────────────────────────────────┘
The summary of the sample NAS: 10 cores and 12 logical processors, CPU 53 °C in amber, a load bar at 10 %, 5.6 of 15.4 GiB of memory in use, two data volumes, and the traffic of eth0 and eth1.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/pascal/stats.pas

stats.pas Download stats.pas

{ NAS summary in two columns: the system on the left, volumes and network ports on the right.
  Build and run: fpc stats.pas && ./stats   (prints once and ends)
  Each part of the NAS is a record; each panel is a list of lines that a procedure frames. }
program stats;
{$mode objfpc}{$H+}
uses sysutils, classes, unix;

type
  TSystem = record
    Model, Cpu, Load: string; Cores, Logical, CpuTemp, SysTemp: integer; MemTotal, MemAvail: double;
  end;
  TVolume = record Name: string; Size, Used: double; end;
  TPort = record Name: string; Received, Sent: double; end;

var
  sys: TSystem;
  vols: array of TVolume;
  ports: array of TPort;
  left, right, lines: TStringList;
  v: TVolume; p: TPort; i: integer;

function Esc(const code: string): string; begin Result := #27'[' + code + 'm'; end;
function Rep(const s: string; n: integer): string; var i: integer; begin Result := ''; for i := 1 to n do Result := Result + s; end;

{ Columns on the screen: UTF-8 continuation bytes ($80-$BF) and colour codes do not count }
function Width(const s: string): integer;
var i: integer; skip: boolean = false;
begin
  Result := 0;
  for i := 1 to Length(s) do begin
    if s[i] = #27 then skip := true;
    if not skip and not (s[i] in [#$80..#$BF]) then Inc(Result);
    if skip and (s[i] = 'm') then skip := false;
  end;
end;

function Pad(const s: string; n: integer): string; begin Result := s + Rep(' ', n - Width(s)); end;
function Field(const s: string; n: integer): string;
begin Result := s.Split([' ', #9], TStringSplitOptions.ExcludeEmpty)[n]; end;

{ The lines a command prints; /proc files are read through cat, because their size reads as 0 }
function Run(const cmd: string): TStringList;
var f: Text; s: string;
begin
  Result := TStringList.Create;
  if POpen(f, cmd + ' 2>/dev/null', 'R') <> 0 then Exit;
  while not Eof(f) do begin ReadLn(f, s); Result.Add(s); end;
  PClose(f);
end;
function Proc(const name: string): TStringList;
begin
  if GetEnvironmentVariable('PROC') = '' then Result := Run('cat /proc/' + name)
  else Result := Run('cat ' + GetEnvironmentVariable('PROC') + '/' + name);
end;
function Size(kb: double): string;
const units: array[0..3] of string = ('KiB', 'MiB', 'GiB', 'TiB');
var u: integer = 0;
begin
  while (kb >= 1024) and (u < 3) do begin kb := kb / 1024; Inc(u); end;
  Result := FormatFloat('0.0', kb) + ' ' + units[u];
end;
function Meter(part: double; cells: integer): string;
var c: string;
begin
  if part > 1 then part := 1;
  if part > 0.9 then c := '31' else if part > 0.7 then c := '33' else c := '32';
  Result := Esc(c) + Rep('█', Round(part * cells)) + Esc('90') + Rep('░', cells - Round(part * cells))
    + Esc('0') + Format('%4.0f %%', [part * 100]);
end;
function Temp(c: integer): string;
begin
  if c >= 55 then Result := Esc('31') else if c >= 45 then Result := Esc('33') else Result := Esc('32');
  if c = 0 then Result := '--' else Result := Result + IntToStr(c) + ' °C' + Esc('0');
end;

procedure ReadSystem(var s: TSystem);
var t, seen: TStringList; line, chip: string;
begin
  t := Run('getsysinfo model'); if t.Count > 0 then s.Model := t[0] else s.Model := 'NAS'; t.Free;
  s.CpuTemp := StrToIntDef(Field(Run('getsysinfo cputmp').Text + ' 0', 0), 0);
  s.SysTemp := StrToIntDef(Field(Run('getsysinfo systmp').Text + ' 0', 0), 0);
  t := Proc('cpuinfo'); seen := TStringList.Create; chip := '';
  for line in t do
    if line.StartsWith('model name') then s.Cpu := Trim(line.Substring(line.IndexOf(':') + 1))
    else if line.StartsWith('processor') then Inc(s.Logical)
    else if line.StartsWith('physical id') then chip := Field(line, 3)
    else if line.StartsWith('core id') and (seen.IndexOf(chip + '/' + Field(line, 3)) < 0) then seen.Add(chip + '/' + Field(line, 3));
  s.Cores := seen.Count; seen.Free; t.Free;
  t := Proc('loadavg'); s.Load := Field(t[0], 0) + '  ' + Field(t[0], 1) + '  ' + Field(t[0], 2); t.Free;
  t := Proc('meminfo');
  for line in t do
    if line.StartsWith('MemTotal:') then s.MemTotal := StrToFloat(Field(line, 1))
    else if line.StartsWith('MemAvailable:') then s.MemAvail := StrToFloat(Field(line, 1));
  t.Free;
end;

procedure ReadVolumes;
var t: TStringList; line: string;
begin
  if GetEnvironmentVariable('DF') = '' then t := Run('df -kP') else t := Run('cat ' + GetEnvironmentVariable('DF'));
  for line in t do
    if (Length(line.Split([' '], TStringSplitOptions.ExcludeEmpty)) = 6) and Field(line, 5).StartsWith('/share/CACHEDEV') then
    begin
      SetLength(vols, Length(vols) + 1);
      with vols[High(vols)] do begin Name := Field(line, 5).Substring(7); Size := StrToFloat(Field(line, 1)); Used := StrToFloat(Field(line, 2)); end;
    end;
  t.Free;
end;

procedure ReadPorts;
var t: TStringList; line: string;
begin
  t := Proc('net/dev');
  for line in t do
    if Trim(line).StartsWith('eth') then
    begin
      SetLength(ports, Length(ports) + 1);
      with ports[High(ports)] do begin
        Name := Trim(line.Substring(0, line.IndexOf(':')));
        Received := StrToFloat(Field(line.Substring(line.IndexOf(':') + 1), 0)); Sent := StrToFloat(Field(line.Substring(line.IndexOf(':') + 1), 8));
      end;
    end;
  t.Free;
end;

{ Adds the lines of a panel of width w, framed and with a title, to the column col }
procedure Panel(col: TStringList; const title: string; lines: TStringList; w: integer);
var s: string;
begin
  col.Add(Esc('33') + '┌─ ' + Esc('1') + title + Esc('0;33') + ' ' + Rep('─', w - Width(title) - 5) + '┐' + Esc('0'));
  for s in lines do col.Add(Esc('33') + '│ ' + Esc('0') + Pad(s, w - 4) + Esc('33') + ' │' + Esc('0'));
  col.Add(Esc('33') + '└' + Rep('─', w - 2) + '┘' + Esc('0'));
  lines.Clear;
end;

begin
  ReadSystem(sys); ReadVolumes; ReadPorts;
  left := TStringList.Create; right := TStringList.Create; lines := TStringList.Create;
  lines.AddStrings([Pad('Cores', 20) + IntToStr(sys.Cores), Pad('Logical processors', 20) + IntToStr(sys.Logical), '',
    Pad('CPU', 20) + Temp(sys.CpuTemp), Pad('System', 20) + Temp(sys.SysTemp), '',
    Pad('Load', 8) + sys.Load, Pad('', 8) + Meter(StrToFloat(Field(sys.Load, 0)) / sys.Logical, 20), '',
    Pad('Memory', 8) + Size(sys.MemTotal - sys.MemAvail) + ' of ' + Size(sys.MemTotal),
    Pad('', 8) + Meter((sys.MemTotal - sys.MemAvail) / sys.MemTotal, 20)]);
  Panel(left, 'System', lines, 39);
  for v in vols do begin
    lines.Add(Pad(v.Name, 16) + Size(v.Used) + ' of ' + Size(v.Size));
    lines.Add(Pad('', 8) + Meter(v.Used / v.Size, 20));
  end;
  Panel(right, 'Volumes', lines, 39);
  for p in ports do begin
    lines.Add(Pad(p.Name, 8) + Pad('received', 10) + Esc('32') + Size(p.Received / 1024) + Esc('0'));
    lines.Add(Pad('', 8) + Pad('sent', 10) + Esc('32') + Size(p.Sent / 1024) + Esc('0'));
  end;
  Panel(right, 'Network', lines, 39);
  WriteLn(Esc('30;43'), Pad(' ' + sys.Model + '   ' + sys.Cpu, 79), Esc('0'));
  while right.Count < left.Count do right.Add('');
  while left.Count < right.Count do left.Add(Rep(' ', 39));
  for i := 0 to left.Count - 1 do WriteLn(left[i], ' ', right[i]);
  left.Free; right.Free; lines.Free;
end.

What you learn

  • A record such as TSystem keeps all facts of one part of the NAS under one name: sys.Cores, sys.Load.
  • procedure ReadSystem(var s: TSystem) fills the record of the caller, because var passes the record itself, not a copy.
  • with vols[High(vols)] do writes three fields of the newest array element without repeating its name.
  • Two TStringList columns, each filled by Panel, print side by side in one loop.

How it works

The program reads first and draws after. ReadSystem asks getsysinfo for the model and both temperatures and reads /proc/cpuinfo, /proc/loadavg and /proc/meminfo. It counts the processor lines as logical processors, and the distinct pairs of physical id and core id as cores: 10 cores and 12 logical processors on the i5-1235U, because only some of its cores run two threads. ReadVolumes keeps the /share/CACHEDEV mounts of df -kP, and ReadPorts keeps the lines of /proc/net/dev whose name starts with eth.

Panel turns a list of lines into a framed panel 39 columns wide and adds it to a column. The left column gets the System panel, the right one Volumes and Network. Then the program prints a title bar with the model and the CPU, fills the shorter column with empty lines and prints both columns line by line, one space apart.

Bars turn amber above 70 % and red above 90 %. Temperatures are green below 45 °C, amber below 55 °C and red from 55 °C.

Notes to the lines

  • 8–13Three record types: the system, one volume, one network port.
  • 17–18Dynamic arrays of records: they grow by one for each volume and port found.
  • 41–49Run returns the lines a command prints. A file of /proc reports a size of 0, so the program reads it through cat.
  • 55–61Size divides by 1024 until the number is below 1024 and takes the unit from the array.
  • 62–69Meter draws cells blocks; a part above 1 (load higher than the processors) stops at 100 %.
  • 80–81"53 C/127 F" plus " 0" gives "53" as the first field; without getsysinfo the answer is empty and the field is "0".
  • 83–87One loop over /proc/cpuinfo finds the CPU name, counts the logical processors and collects the core pairs.
  • 105The mount point minus /share/ is the name of the volume, field 2 its size and field 3 its used space, in KiB.
  • 119–120The name of a port ends at the colon; after it, field 0 is the bytes received and field 8 the bytes sent.
  • 127–134Panel writes the title into the top edge, pads each line to the inside width and clears lines for the next panel.
  • 141The load bar is the 1-minute load divided by the logical processors.
  • 156–158The shorter column gets empty lines, so both columns end on the same line.

Run it

fpc stats.pas && ./stats

The program prints the summary and ends.

Try it yourself

Add a field Swap to TSystem, fill it with SwapTotal minus SwapFree in ReadSystem and add a line for it to the System panel. Change the 20 in the two Meter calls of the System panel to 12 and see shorter bars.

More projects in Pascal