backend.runcommand.doit()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 28
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 23
nop 1
dl 0
loc 28
rs 7.9279
c 0
b 0
f 0
1
'''#raises event that will run the command
2
# a command listener must be running to listen for the command!
3
# publish to durable queue?
4
# TODO: allow pass in minername
5
6
#Examples:
7
#   runcommand.py switch S9102 3
8
'''
9
import sys
10
from helpers.queuehelper import QueueName
11
#from messaging.messages import *
12
from domain.mining import Miner, MinerCommand
13
from domain.rep import MinerRepository
14
from backend.fcmapp import ApplicationService
15
16
APP = ApplicationService()
17
18
def findminerbyname(minertofind):
19
    miners = MinerRepository()
20
    miner = miners.getminerbyname(minertofind, APP.getconfigfilename('config/miners.conf'))
21
    if miner is None:
22
        miner = APP.getknownminerbyname(minertofind)
23
    if miner is None:
24
        miner = APP.getminer(Miner(name=minertofind))
25
    if miner is None:
26
        print('Miner {0} does not exist'.format(minertofind))
27
        sys.exit(1)
28
    return miner
29
30
def doit(args):
31
    if len(args) < 2:
32
        print('usage: python runcommand.py nameofcommand [nameofminer] [commandparameter]')
33
        APP.shutdown(1)
34
35
    cmd = args[1]
36
    if len(args) == 2:
37
        #single command, no miner specified
38
        if cmd == 'alert':
39
            APP.trybroadcast(cmd, '{0}: runcommand called on {1}'.format(APP.now(), cmd))
40
        else:
41
            APP.trypublish(cmd, '{0}: runcommand called on {1}'.format(APP.now(), cmd))
42
        print('sent command {0}'.format(cmd))
43
    else:
44
        minertofind = args[2]
45
        miner = findminerbyname(minertofind)
46
        cmdparam = ''
47
        if len(args) > 3:
48
            cmdparam = args[3]
49
        if not QueueName.has_value(cmd):
50
            print('Queue {0} is not valid'.format(cmd))
51
            sys.exit(1)
52
53
        if cmd:
54
            qmess = MinerCommand(cmd, cmdparam)
55
            msg = APP.createmessagecommand(miner, qmess)
56
            APP.bus.publish(queue_name=cmd, msg=msg)
57
            print('sent command {0} for miner {1}'.format(cmd, miner.name))
58
59
def main():
60
    if len(sys.argv) < 2:
61
        doit([sys.argv[0], 'provision', '192.168.1.117'])
62
    else:
63
        args = sys.argv[0:len(sys.argv)]
64
        doit(args)
65
    APP.shutdown()
66
67
if __name__ == "__main__":
68
    main()
69