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.
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 % │ └─────────────────────────────────────┘ └─────────────────────────────────────┘
Download it on the NAS
curl -fsSLO https://kb.nasutils.net/projects/pascal/stats.passtats.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
TSystemkeeps 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, becausevarpasses the record itself, not a copy.with vols[High(vols)] dowrites three fields of the newest array element without repeating its name.- Two
TStringListcolumns, each filled byPanel, 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–49
Runreturns the lines a command prints. A file of/procreports a size of 0, so the program reads it throughcat. - 55–61
Sizedivides by 1024 until the number is below 1024 and takes the unit from the array. - 62–69
Meterdrawscellsblocks; 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
getsysinfothe answer is empty and the field is "0". - 83–87One loop over
/proc/cpuinfofinds 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–134
Panelwrites the title into the top edge, pads each line to the inside width and clearslinesfor 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 && ./statsThe 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
- A menu bar with drop-down boxes in Free PascalA Free Pascal program draws a desktop with a menu bar, drop-down boxes and dialog boxes with shadows, and fills the dialogs with the NAS's memory, load, processor, volumes and RAID groups. You learn to draw boxes with escape codes, read keys with crt and run commands with POpen.
- A greeting screen with large letters in Free PascalA Free Pascal program prints the word NAS in large block letters, greets you by the hour and lists the model, kernel, uptime, load and memory in a framed table. You learn records and dynamic arrays, reading the date with dateutils and drawing a table with box characters.
- A NAS summary in two columns in Free PascalA Free Pascal program reads the CPU, temperatures, load, memory, data volumes and network ports into records and prints them as framed panels in two columns. You learn records, dynamic arrays of records, var parameters and a layout built from lists of lines.
- Cable run: a moving game in Free PascalA Free Pascal game where you steer a network cable round a frame with the arrow keys; it grows with every data packet it picks up, and the wall or its own body ends the run. You learn a game loop with KeyPressed and Delay, records for coordinates and drawing only the cells that change.
- A temperature chart of the NAS in Free PascalA Free Pascal program asks QNAP's getsysinfo for the system, CPU and disk temperatures and draws them as a vertical bar chart with a scale, coloured green, amber or red by level. You learn to build a chart line by line from the top and to treat an empty disk bay as a value of its own.
- A log viewer with colours and search in Free PascalA Free Pascal program shows a log file a screen at a time, colours warnings amber and errors red, scrolls with the arrow and page keys and jumps to the next error with /. You learn to load a file into a TStringList, keep a window of lines on the screen and search with UpperCase and Pos.