summaryrefslogtreecommitdiff
path: root/src/op_mode/cpu.py
blob: cb55ce4079f8ec9fa99b52406ba4f8cad7b1b8bf (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
#
# Copyright (C) 2016-2022 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 or later 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/>.

import json
import sys
import typing

import vyos.cpu
import vyos.opmode

from jinja2 import Template
from vyos.util import popen, DEVNULL

cpu_template = Template("""
{% for cpu in cpus %}
{% if 'physical id' in cpu %}CPU socket: {{cpu['physical id']}}{% endif %}
{% if 'vendor_id' in cpu %}CPU Vendor:       {{cpu['vendor_id']}}{% endif %}
{% if 'model name' in cpu %}Model:            {{cpu['model name']}}{% endif %}
{% if 'cpu cores' in cpu %}Cores:            {{cpu['cpu cores']}}{% endif %}
{% if 'cpu MHz' in cpu %}Current MHz:      {{cpu['cpu MHz']}}{% endif %}
{% endfor %}
""")

cpu_summary_template = Template("""
Physical CPU cores: {{count}}
CPU model(s): {{models | join(", ")}}
""")

def _get_raw_data():
    return vyos.cpu.get_cpus()

def _format_cpus(cpu_data):
    env = {'cpus': cpu_data}
    return cpu_template.render(env).strip()

def _get_summary_data():
    count = vyos.cpu.get_core_count()
    cpu_data = vyos.cpu.get_cpus()
    models = [c['model name'] for c in cpu_data]
    env = {'count': count, "models": models}

    return env

def _format_cpu_summary(summary_data):
    return cpu_summary_template.render(summary_data).strip()

def show(raw: bool):
    cpu_data = _get_raw_data()

    if raw:
        return cpu_data
    else:
        return _format_cpus(cpu_data)

def show_summary(raw: bool):
    cpu_summary_data = _get_summary_data()

    if raw:
        return cpu_summary_data
    else:
        return _format_cpu_summary(cpu_summary_data)


if __name__ == '__main__':
    try:
        res = vyos.opmode.run(sys.modules[__name__])
        if res:
            print(res)
    except ValueError as e:
        print(e)
        sys.exit(1)