-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment
executable file
·257 lines (209 loc) · 8.01 KB
/
environment
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python3
#
# This file is part of the Robotic Observatory Control Kit (rockit)
#
# rockit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# rockit 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 rockit. If not, see <http://www.gnu.org/licenses/>.
"""Commandline client for communicating with environmentd"""
# pylint: disable=bare-except
import datetime
import glob
import json
import os
import sys
import Pyro4
from rockit.common import print
from rockit.environment import Config
SCRIPT_NAME = os.path.basename(sys.argv[0])
sys.excepthook = Pyro4.util.excepthook
SET_LABELS = {
'BoolPowerOnOff': {
False: '[b]POWER OFF[/b]',
True: '[b]POWER ON[/b]'
},
'BoolClosedOpen': {
False: 'OPEN',
True: 'CLOSED'
},
'BoolSafeTripped': {
False: '[red]TRIPPED[/red]',
True: '[green]SAFE[/green]'
},
'BoolHealthyUnhealthy': {
False: '[red]UNHEALTY[/red]',
True: '[green]HEALTHY[/green]'
},
'UPSStatus': {
1: '[red]UNKNOWN[/red]',
2: '[green]ONLINE[/green]',
3: '[yellow]ON BATTERY[/yellow]',
4: '[red]SMART BOOST[/red]',
5: '[red]TIMED SLEEPING[/red]',
6: '[red]SOFTWARE BYPASS[/red]',
7: '[red]OFF[/red]',
8: '[red]REBOOTING[/red]',
9: '[red]SWITCHED BYPASS[/red]',
10: '[red]HARDWARE FAILURE BYPASS[/red]',
11: '[red]SLEEPING UNTIL POWER RETURNS[/red]',
12: '[red]ON SMART TRIM[/red]'
}
}
def print_status(daemon):
"""Prints the latest environment data in human-readable form"""
try:
with daemon.connect() as environment:
data = environment.status()
except Pyro4.errors.CommunicationError:
print('error: unable to communicate with the environment daemon')
return 1
if data is None:
print('No data available')
else:
# Find the longest label to set the parameter indent
max_label_length = 0
for watcher_data in data.values():
for parameter_data in watcher_data['parameters'].values():
max_label_length = max(max_label_length, len(parameter_data['label']))
for watcher_data in data.values():
print(watcher_data['label'] + ' data from ' + format_date(watcher_data['parameters']))
for parameter_data in watcher_data['parameters'].values():
label = parameter_data['label']
label_padding = max_label_length - len(label)
suffix = ''
if 'unit' in parameter_data:
suffix = ' ' + parameter_data['unit']
output = ' ' * label_padding + label + ': '
if 'values' in parameter_data:
output += format_set(parameter_data)
else:
output += format_measurement(parameter_data, suffix)
print(output)
print()
return 0
def print_json(daemon):
"""Prints the latest environment data in machine-readable form"""
try:
with daemon.connect() as environment:
status = environment.status()
except Pyro4.errors.CommunicationError:
print('error: unable to communicate with the environment daemon')
return 1
print(json.dumps(status))
return 0
def format_date(data):
"""Builds a formatted date string for the named data group"""
start = None
end = None
current = False
for param in data.values():
try:
param_start = datetime.datetime.strptime(param['date_start'],
'%Y-%m-%dT%H:%M:%SZ')
param_end = datetime.datetime.strptime(param['date_end'], '%Y-%m-%dT%H:%M:%SZ')
start = param_start if not start else min(start, param_start)
end = param_end if not end else min(end, param_end)
current = current or param['current']
except:
pass
if start and end:
color = 'default' if current else 'red'
return f'[b]{start.strftime("%H:%M:%S")} \u2014 [{color}]{end.strftime("%H:%M:%S")}[/{color}]:[/b]'
else:
return '[b][red]NO DATA[red][/b]'
def format_value(value, data, fmt='.1f'):
"""Builds a formatted string colored based on the specified limits"""
limits = data.get('limits', None)
warn_limits = data.get('warn_limits', None)
color = 'default'
if limits or warn_limits:
if limits and (value < limits[0] or value > limits[1]):
color = 'red'
elif warn_limits and (value < warn_limits[0] or value > warn_limits[1]):
color = 'yellow'
else:
color = 'green'
display = data.get('display', None)
if display == 'DiskBytes':
value = str(round(value / 2**30, 1))
fmt = ''
elif display in SET_LABELS:
value = SET_LABELS[display].get(value, value)
fmt = ''
return f'[b][{color}]' + ('{0' + fmt + '}').format(value) + f'[/{color}][/b]'
def format_measurement(data, suffix='', fmt='.1f'):
"""Builds a formatted string with a value range"""
if fmt != '':
fmt = ':' + fmt
ret = ''
if 'min' in data:
ret += format_value(data['min'], data, fmt) + ' \u2264 '
if data['current']:
ret += format_value(data['latest'], data, fmt)
else:
ret += '[b][red]NO DATA[/red][/b]'
if 'max' in data:
ret += ' \u2264 ' + format_value(data['max'], data, fmt)
if data['current'] or 'max' in data:
ret += suffix
if data['unsafe']:
ret += ' [b][red](UNSAFE)[/red][/b]'
elif data['warning']:
ret += ' [b][yellow](WARNING)[/yellow][/b]'
return ret
def format_set(data):
"""Builds a formatted string with specified values"""
labels = []
if 'display' in data:
labels = SET_LABELS.get(data['display'], [])
if data['current']:
ret = f'[b]{labels.get(data["latest"], data["latest"])}[/b]'
else:
ret = '[b][red]NO DATA[/red][/b]'
if 'values' in data and (len(data['values']) > 1 or not data['current']):
if ret:
ret += ' '
display_values = [labels.get(v, v) for v in data['values']]
ret += '[' + ', '.join(display_values) + ']'
if data['unsafe']:
ret += ' [b][red](UNSAFE)[/red][/b]'
elif data['warning']:
ret += ' [b][yellow](WARNING)[/yellow][/b]'
return ret
def print_usage(name):
"""Prints the utility help"""
print(f'Usage: {name} <command>')
print()
print(' status print a human-readable summary of the aggregated environment status')
print(' json print a machine-readable summary of the aggregated environment status')
print()
return 1
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit(print_usage(SCRIPT_NAME))
if 'ENVIRONMENTD_CONFIG_PATH' in os.environ:
config = Config(os.environ['ENVIRONMENTD_CONFIG_PATH'])
else:
# Load the config file defined in the ENVIRONMENTD_CONFIG_PATH environment variable or from the
# default system location (/etc/environmentd/). Exit with an error if zero or multiple are found.
files = glob.glob("/etc/environmentd/*.json")
if len(files) != 1:
print('error: failed to guess the default config file. ' +
'Run as ENVIRONMENTD_CONFIG_PATH=/path/to/config.json environment <command>')
sys.exit(1)
config = Config(files[0])
if sys.argv[1] == 'status':
sys.exit(print_status(config.daemon))
elif sys.argv[1] == 'json':
sys.exit(print_json(config.daemon))
# Command not found
sys.exit(print_usage(SCRIPT_NAME))