summaryrefslogtreecommitdiff
path: root/src/op_mode/show_uptime.py
blob: 1b5e33fa9755dd3978d7b491e09cdb60127e4b8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python3
#
# Copyright (C) 2021 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

def get_uptime_seconds():
  from re import search
  from vyos.util import read_file

  data = read_file("/proc/uptime")
  seconds = search("([0-9\.]+)\s", data).group(1)

  return int(float(seconds))

def get_load_averages():
    from re import search
    from vyos.util import cmd

    data = cmd("uptime")
    matches = search(r"load average:\s*(?P<one>[0-9\.]+)\s*,\s*(?P<five>[0-9\.]+)\s*,\s*(?P<fifteen>[0-9\.]+)\s*", data)

    res = {}
    res[1]  = float(matches["one"])
    res[5]  = float(matches["five"])
    res[15] = float(matches["fifteen"])

    return res

def get_raw_data():
    from vyos.util import seconds_to_human

    res = {}
    res["uptime_seconds"] = get_uptime_seconds()
    res["uptime"] = seconds_to_human(get_uptime_seconds())
    res["load_average"] = get_load_averages()

    return res

def get_formatted_output():
    data = get_raw_data()

    out = "Uptime: {}\n\n".format(data["uptime"])
    avgs = data["load_average"]
    out += "Load averages:\n"
    out += "1  minute:   {:.02f}%\n".format(avgs[1]*100)
    out += "5  minutes:  {:.02f}%\n".format(avgs[5]*100)
    out += "15 minutes:  {:.02f}%\n".format(avgs[15]*100)

    return out

if __name__ == '__main__':
    print(get_formatted_output())