/
issuecommands.py
394 lines (311 loc) · 14.1 KB
/
issuecommands.py
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import json
import os
import threading
import subprocess
import functools
from dataclasses import dataclass
from ast import literal_eval
import githubutil as U
import logsupport
import historybuffer
import time
from logsupport import ConsoleWarning, ConsoleError, ConsoleInfo
from controlevents import PostEvent, ConsoleEvent, CEvent
import config
from collections import OrderedDict
from typing import Callable, Union
from enum import Enum
from stores import valuestore
from utils import hw
from utils.exitutils import MAINTEXIT, Exit_Screen_Message, MAINTRESTART, MAINTPISHUT, MAINTPIREBOOT, Exit, \
REMOTERESTART, \
REMOTEEXIT, REMOTEPISHUT, REMOTEPIREBOOT
fetcher = None # type: Union[None, threading.Thread]
ReportStatus = None # type: Union[Callable, None]
Nodes = OrderedDict()
def DeleteNode(nd):
logsupport.Logs.Log('Deleting history of node {}'.format(nd))
del Nodes[nd]
lastseenlogmessage = ''
# filled in by consolestatus to avoid dependency loop
def TempCheckSanity(Key, params):
if Key is None and params is None:
logsupport.Logs.Log('Internal Error: Both Command sources are None', severity=ConsoleError, tb=True, hb=True)
def FetchInProgress():
global fetcher
return fetcher is not None and fetcher.is_alive()
# todo further compress below to unify messagint
# noinspection PyUnusedLocal
def RestartConsole(params=None, Key=None, AutoVer=False):
TempCheckSanity(Key, params)
if not FetchInProgress():
_SystemTermination('console restart', 'Console Restart', (MAINTRESTART, REMOTERESTART), Key, params)
else:
CommandResp(Key, 'nak', params, None)
def ShutConsole(params=None, Key=None):
TempCheckSanity(Key, params)
if not FetchInProgress():
_SystemTermination('console shutdown', 'Console Shutdown', (MAINTEXIT, REMOTEEXIT), Key, params)
else:
CommandResp(Key, 'nak', params, None)
def ShutdownPi(params=None, Key=None):
TempCheckSanity(Key, params)
if not FetchInProgress():
_SystemTermination('pi shutdown', "Pi Shutdown", (MAINTPISHUT, REMOTEPISHUT), Key, params)
else:
CommandResp(Key, 'nak', params, None)
def RebootPi(params=None, Key=None):
TempCheckSanity(Key, params)
if not FetchInProgress():
_SystemTermination('pi reboot', "Pi Reboot", (MAINTPIREBOOT, REMOTEPIREBOOT), Key, params)
else:
CommandResp(Key, 'nak', params, None)
def _SystemTermination(statmsg, exitmsg, exitcode, Key, params):
ReportStatus(statmsg)
CommandResp(Key, 'ok', params, None)
Exit_Screen_Message(exitmsg + ' Requested', ('Remote' if Key is None else 'Maintenance') + ' Request', exitmsg)
config.terminationreason = ('remote' if Key is None else 'manual') + statmsg
Exit(exitcode[1] if Key is None else exitcode[0])
def DoDelayedAction(evnt): # only for autover
PostEvent(ConsoleEvent(CEvent.RunProc, name='DelayedRestart', proc=evnt.action))
def CommandResp(Key, success, params, value):
if Key is not None:
if success == 'ok':
Key.ScheduleBlinkKey(5)
else:
Key.FlashNo(5)
else:
config.MQTTBroker.CommandResponse(success, params[0], params[1], params[2], value)
def Get(nm, target, params, Key):
global fetcher
TempCheckSanity(Key, params)
if not FetchInProgress():
fetcher = threading.Thread(name=nm, target=target, daemon=True)
fetcher.start()
CommandResp(Key, 'ok', params, None)
else:
CommandResp(Key, 'busy', params, None)
def GetStable(params=None, Key=None):
Get('FetchStableRemote', fetch_stable, params, Key)
def GetBeta(params=None, Key=None):
Get('FetchBetRemote', fetch_beta, params, Key)
def GetDev(params=None, Key=None):
Get('FetchDevRemote', fetch_dev, params, Key)
def UseStable(params=None, Key=None):
TempCheckSanity(Key, params)
subprocess.Popen('echo stable > /home/pi/versionselector', shell=True)
CommandResp(Key, 'ok', params, None)
def UseBeta(params=None, Key=None):
TempCheckSanity(Key, params)
subprocess.Popen('echo beta > /home/pi/versionselector', shell=True)
CommandResp(Key, 'ok', params, None)
def UseDev(params=None, Key=None):
TempCheckSanity(Key, params)
subprocess.Popen('echo dev > /home/pi/versionselector', shell=True)
CommandResp(Key, 'ok', params, None)
def FreezeConfig(params=None, Key=None):
TempCheckSanity(Key, params)
subprocess.Popen('echo FROZEN > /home/pi/.freezeconfig', shell=True)
CommandResp(Key, 'ok', params, None)
def UnfreezeConfig(params=None, Key=None):
TempCheckSanity(Key, params)
subprocess.Popen('rm /home/pi/.freezeconfig', shell=True)
CommandResp(Key, 'ok', params, None)
def DumpHB(params=None, Key=None):
TempCheckSanity(Key, params)
entrytime = time.strftime('%m-%d-%y %H:%M:%S')
historybuffer.DumpAll('Command Dump', entrytime)
CommandResp(Key, 'ok', params, None)
def EchoStat(params=None, Key=None):
TempCheckSanity(Key, params)
ReportStatus('running stat')
CommandResp(Key, 'ok', params, None)
def LogItem(sev, params=None, Key=None):
TempCheckSanity(Key, params)
logsupport.Logs.Log('Remotely forced test message ({})'.format(sev), severity=sev, tb=False, hb=False)
CommandResp(Key, 'ok', params, None)
def GetErrors(params=None): # remote only
errs = logsupport.Logs.ReturnRecent(logsupport.ConsoleWarning, 10)
CommandResp(None, 'ok', params, errs)
def GetLog(params=None): # remote only
log = logsupport.Logs.ReturnRecent(-1, 0)
CommandResp(None, 'ok', params, log)
def ClearIndicator(params=None, Key=None):
TempCheckSanity(Key, params)
config.sysStore.ErrorNotice = -1 # clear indicator
ReportStatus('cleared indicator')
CommandResp(Key, 'ok', params, None)
def GetVar(params=None, Key=None):
print(params, Key)
if len(params) < 4:
logsupport.Logs.Log('No request to remote GetVar command {}'.format(params), severity=ConsoleWarning)
return
try:
p = json.loads(params[3])
assert (type(p) == dict)
except Exception as E:
logsupport.Logs.Log(f'Non-dict paramater to remote GetVar command: {params} ({E}', severity=ConsoleWarning)
return
resp = {}
for v, val in p.items():
try:
val = valuestore.GetVal(v)
logsupport.Logs.Log('Remote get of {} to {}'.format(v, val))
resp[v] = val
except Exception as E:
logsupport.Logs.Log(f'Bad store attempt in remote SetVar command: {v}={val} ({E}',
severity=ConsoleWarning)
CommandResp(Key, 'ok', params, resp)
def SetVar(params=None):
print(params)
if len(params) < 4:
logsupport.Logs.Log('No request to remote SetVar command {}'.format(params), severity=ConsoleWarning)
return
try:
p = json.loads(params[3])
assert (type(p) == dict)
except Exception as E:
logsupport.Logs.Log(f'Non-dict paramater to remote SetVar command: {params} ({E})', severity=ConsoleWarning)
raise
for v, val in p.items():
try:
valuestore.SetVal(v, val)
logsupport.Logs.Log('Remote set of {} to {}'.format(v, val))
except Exception as E:
logsupport.Logs.Log(f'Bad store attempt in remote SetVar command: {v}={val} ({E})',
severity=ConsoleWarning)
def SendErrMatch(params=None, Key=None):
TempCheckSanity(Key, params)
try:
lev, msg = literal_eval(params[3])
except (SyntaxError, ValueError, TypeError, MemoryError):
logsupport.Logs.Log('Bad last error received in clear match cmd: {}'.format(params))
CommandResp(Key, 'nomatch', params, None)
return
if logsupport.Logs.MatchLastErr(lev, msg, logsupport.ConsoleWarning):
config.sysStore.ErrorNotice = -1 # clear indicator
ReportStatus('cleared indicator')
CommandResp(Key, 'ok', params, None)
else:
CommandResp(Key, 'nomatch', params, None)
def IncludeErrToMatch():
return lastseenlogmessage
def DelHistory(params=None, Key=None):
logsupport.Logs.Log('Got request from {} to delete history for {}'.format(params[2], params[3]))
DeleteNode(params[3])
CommandResp(Key, 'ok', params, None)
Where = Enum('Where',
'LocalMenuExits LocalMenuVersions LocalMenuVersionsAdv RemoteMenu RemoteMenuAdv MQTTCmds RemoteMenuDead')
MaintVers = (Where.LocalMenuVersions, Where.RemoteMenu, Where.MQTTCmds)
MaintVersAdv = (Where.LocalMenuVersionsAdv, Where.RemoteMenuAdv, Where.MQTTCmds)
MaintExits = (Where.LocalMenuExits, Where.RemoteMenu, Where.MQTTCmds)
RemoteOnly = (Where.RemoteMenu, Where.MQTTCmds)
RemoteOnlyAdv = (Where.RemoteMenuAdv, Where.MQTTCmds)
RemoteOnlyDead = (Where.RemoteMenuDead,)
MQTTOnly = (Where.MQTTCmds,)
'''
CommandRecord = NamedTuple('CommandRecord',
[('Proc', Callable), ('simple', bool), ('DisplayName', str), ('Verify', str),
('where', tuple), ('notgroup', bool), ('cmdparam', Callable)])
CommandRecord.__new__.__defaults__ = (None)
'''
# Better Python 3.7 syntax
@dataclass
class CommandRecord:
Proc: callable # called locally or at remote site
simple: bool # simple or None - handle remote response simply or call a special proc (name mapping in consolestatus
DisplayName: str # button label when on a screen
Verify: str # whether to do verify when on a screen
where: tuple # which places to use this record
notgroup: bool # true if only works for targeted node
suppresstoself: bool # true if suppress "all" on sending node
cmdparam: Union[Callable, None] = None # - optional proc that provides a parameter to send with the command
cmdcalls = OrderedDict({
'restart': CommandRecord(RestartConsole, True, "Restart Console", 'True', MaintExits, False, True),
'shut': CommandRecord(ShutConsole, True, "Shutdown Console", 'True', MaintExits, False, True),
'reboot': CommandRecord(RebootPi, True, "Reboot Pi", 'True', MaintExits, False, True),
'shutpi': CommandRecord(ShutdownPi, True, "Shutdown Pi", 'True', MaintExits, False, True),
'usestable': CommandRecord(UseStable, True, "Use Stable Release", 'False', MaintVers, False, True),
'usebeta': CommandRecord(UseBeta, True, "Use Beta Release", 'False', MaintVers, False, True),
'usedev': CommandRecord(UseDev, True, "Use Development Release", 'False', MaintVersAdv, False, True),
'freezeconfig': CommandRecord(FreezeConfig, True, 'Freeze Configuration', 'False', MaintVersAdv, False, True),
'unfreezeconfig': CommandRecord(UnfreezeConfig, True, 'Unfreeze Configuration', 'False', MaintVersAdv, False, True),
'getstable': CommandRecord(GetStable, True, "Download Release", 'False', MaintVers, False, True),
'getbeta': CommandRecord(GetBeta, True, "Download Beta", 'False', MaintVers, False, True),
'getdev': CommandRecord(GetDev, True, "Download Development", 'False', MaintVersAdv, False, True),
'hbdump': CommandRecord(DumpHB, True, "Dump HB", 'False', RemoteOnlyAdv, False, False),
# 'status': CommandRecord(EchoStat, True, "Echo Status", 'False', RemoteOnly),
'getlog': CommandRecord(GetLog, False, "Get Remote Log", "False", RemoteOnly, True, True),
'geterrors': CommandRecord(GetErrors, False, "Get Recent Errors", 'False', RemoteOnly, True, True),
'clearerrindicator': CommandRecord(ClearIndicator, True, "Clear Error Indicator", 'False', RemoteOnly, False,
False),
'clearerrindicatormatch': CommandRecord(SendErrMatch, True, 'Clear Matching Error', 'False', RemoteOnly, False,
False,
IncludeErrToMatch),
'issueerror': CommandRecord(functools.partial(LogItem, ConsoleError), True, "Issue Error", 'False',
RemoteOnlyAdv, False, True),
'issuewarning': CommandRecord(functools.partial(LogItem, ConsoleWarning), True, "Issue Warning", 'False',
RemoteOnlyAdv, False, True),
'issueinfo': CommandRecord(functools.partial(LogItem, ConsoleInfo), True, "Issue Info", 'False',
RemoteOnlyAdv, False, True),
'deletehistory': CommandRecord(DelHistory, True, 'Clear History', 'True', RemoteOnlyDead, True, True),
'setvar': CommandRecord(SetVar, True, "Set Variable Value", 'False', MQTTOnly, False, True),
'getvar': CommandRecord(GetVar, False, "Get Variable Value", 'False', MQTTOnly, True, True)})
def IssueCommand(source, cmd, seq, fromnd, param=None):
if cmd.lower() in cmdcalls:
if fromnd == hw.hostname and cmdcalls[cmd.lower()].suppresstoself:
logsupport.Logs.Log(
'Ignore remote command {} to ALL from self'.format(cmd))
return
try:
PostEvent(
ConsoleEvent(CEvent.RunProc, name=cmd, proc=cmdcalls[cmd.lower()].Proc,
params=(cmd, seq, fromnd, param)))
except Exception as E:
logsupport.Logs.Log('Exc: {}'.format(repr(E)))
else:
logsupport.Logs.Log('{}: Unknown remote command request: {}'.format(source, cmd),
severity=ConsoleWarning)
def fetch_stable():
basedir = os.path.dirname(config.sysStore.ExecDir)
ReportStatus("updt stable", hold=1)
# noinspection PyBroadException
try:
if os.path.exists(basedir + '/homesystem'):
# personal system
logsupport.Logs.Log("New version fetch(homerelease)")
logsupport.DevPrint("New Version Fetch Requested (homesystem)")
U.StageVersion(basedir + '/consolestable', 'homerelease', 'Maint Dnld', logger=logsupport.Logs)
else:
logsupport.Logs.Log("New version fetch(currentrelease)")
logsupport.DevPrint("New Version Fetch Requested (currentrelease)")
U.StageVersion(basedir + '/consolestable', 'currentrelease', 'Maint Dnld', logger=logsupport.Logs)
U.InstallStagedVersion(basedir + '/consolestable', logger=logsupport.Logs)
logsupport.Logs.Log("Staged version installed in consolestable")
except Exception as E:
logsupport.Logs.Log(f'Failed release download ({E})', severity=ConsoleWarning)
ReportStatus("done stable", hold=2)
def fetch_beta():
basedir = os.path.dirname(config.sysStore.ExecDir)
ReportStatus("updt beta", hold=1)
logsupport.Logs.Log("New version fetch(currentbeta)")
# noinspection PyBroadException
try:
U.StageVersion(basedir + '/consolebeta', 'currentbeta', 'Maint Dnld', logger=logsupport.Logs)
U.InstallStagedVersion(basedir + '/consolebeta', logger=logsupport.Logs)
logsupport.Logs.Log("Staged version installed in consolebeta")
except Exception as E:
logsupport.Logs.Log(f'Failed beta download ({E})', severity=ConsoleWarning)
ReportStatus("done beta", hold=2)
def fetch_dev():
basedir = os.path.dirname(config.sysStore.ExecDir)
ReportStatus("updt dev", hold=1)
logsupport.Logs.Log("New version fetch(currentdev)")
# noinspection PyBroadException
try:
U.StageVersion(basedir + '/consoledev', '*live*', 'Maint Dnld', logger=logsupport.Logs)
U.InstallStagedVersion(basedir + '/consoledev', logger=logsupport.Logs)
logsupport.Logs.Log("Staged version installed in consoledev")
except Exception as E:
logsupport.Logs.Log(f'Failed dev download ({E})', severity=ConsoleWarning)
ReportStatus("done dev", hold=2)