Passed
Push — master ( 269add...33a345 )
by Dave
01:22
created

backend.fcmservice.PoolService.add_pool()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
import os
2
from helpers.telegramhelper import sendalert, sendphoto
3
from domain.mining import Miner, Pool
4
from messaging.schema import MinerSchema, PoolSchema
5
6
class ServiceName:
7
    '''names of infrastructure services'''
8
    messagebus = 'rabbit'
9
    cache = 'redis'
10
    database = 'mysql'
11
    email = 'gmail'
12
    telegram = 'telegram'
13
14
class InfrastructureService:
15
    '''configuration for a dependency'''
16
    def __init__(self, name, connection, host, port, user, password):
17
        self.name = name
18
        self.connection = connection
19
        self.host = host
20
        self.port = port
21
        self.user = user
22
        self.password = password
23
24
class BaseService():
25
    def __init__(self):
26
        self.homedirectory = os.path.dirname(__file__)
27
28
    def getconfigfilename(self, configfilename):
29
        '''get the contents of a config file'''
30
        return os.path.join(self.homedirectory, configfilename)
31
    def serialize(self, entity):
32
        '''serialize any entity
33
        only need schema, message class not needed
34
        '''
35
        if isinstance(entity, Miner):
36
            schema = MinerSchema()
37
            return schema.dumps(entity).data
38
39
        if isinstance(entity, Pool):
40
            schema = PoolSchema()
41
            return schema.dumps(entity).data
42
        return None
43
44
45
class Configuration(object):
46
    def __init__(self, config):
47
        self.__config = config
48
49
    def get(self, key):
50
        if not key in self.__config:
51
            return None
52
        return self.__config[key]
53
54
    def is_enabled(self, key):
55
        lookupkey = '{0}.enabled'.format(key)
56
        if not lookupkey in self.__config:
57
            return False
58
        value = self.__config[lookupkey]
59
        if isinstance(value, str):
60
            return value == 'true' or value == 'True'
61
        return value
62
63
class PoolService(BaseService):
64
    def __init__(self, cache):
65
        super(PoolService, self).__init__()
66
        self.__cache = cache
67
68
    def get_all_pools(self):
69
        '''configured pools'''
70
        pools = PoolRepository().readpools(self.getconfigfilename('config/pools.conf'))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable PoolRepository does not seem to be defined.
Loading history...
71
        return pools
72
73
    def findpool(self, minerpool):
74
        '''find a pool in list'''
75
        if minerpool is None:
76
            return None
77
        for pool in self.get_all_pools():
78
            if minerpool.currentpool == pool.url and minerpool.currentworker.startswith(pool.user):
79
                return pool
80
        return None
81
82
    def knownpools(self):
83
        dknownpools = self.__cache.gethashset(CacheKeys.knownpools)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable CacheKeys does not seem to be defined.
Loading history...
84
        if dknownpools:
85
            return utils.deserializelist_withschema(AvailablePoolSchema(), list(dknownpools.values()))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable AvailablePoolSchema does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable utils does not seem to be defined.
Loading history...
86
        return None
87
88
    def getpool(self, miner: Miner):
89
        '''get pool from cache'''
90
        valu = self.__cache.trygetvaluefromcache(miner.name + '.pool')
91
        if valu is None:
92
            return None
93
        entity = MinerCurrentPool(miner, **utils.deserialize(MinerCurrentPoolSchema(), valu))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable MinerCurrentPoolSchema does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable utils does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable MinerCurrentPool does not seem to be defined.
Loading history...
94
        return entity
95
96
    def add_pool(self, minerpool: domain.minerpool.MinerPool):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable domain does not seem to be defined.
Loading history...
97
        '''see if pool is known or not, then add it'''
98
        knownpool = self.__cache.getfromhashset(CacheKeys.knownpools, minerpool.pool.key)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable CacheKeys does not seem to be defined.
Loading history...
99
        if not knownpool:
100
            val = utils.jsonserialize(AvailablePoolSchema(), minerpool.pool)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable AvailablePoolSchema does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable utils does not seem to be defined.
Loading history...
101
            self.__cache.putinhashset(CacheKeys.knownpools, minerpool.pool.key, val)
102
103
    def putpool(self, pool: Pool):
104
        '''put pool in cache'''
105
        if pool and pool.name:
106
            valu = self.serialize(pool)
107
            self.__cache.tryputcache('pool.{0}'.format(pool.name), valu)
108
109
    def update_pool(self, key, pool: AvailablePool):
110
        self.__cache.hdel(CacheKeys.knownpools, key)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable CacheKeys does not seem to be defined.
Loading history...
111
        knownpool = self.__cache.getfromhashset(CacheKeys.knownpools, pool.key)
112
        if not knownpool:
113
            val = utils.jsonserialize(AvailablePoolSchema(), pool)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable utils does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable AvailablePoolSchema does not seem to be defined.
Loading history...
114
            self.__cache.putinhashset(CacheKeys.knownpools, pool.key, val)
115
116
    def save_pool(self, pool: Pool):
117
        sch = PoolSchema()
118
        pools = PoolRepository()
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable PoolRepository does not seem to be defined.
Loading history...
119
        pools.add(pool, self.getconfigfilename('config/pools.conf'), sch)
120
121
        #update the known pools
122
        for known in self.knownpools():
123
            if pool.is_same_as(known):
124
                oldkey = known.key
125
                known.named_pool = pool
126
                #this changes the pool key!
127
                known.user = pool.user
128
                #update the known pool (with new key)
129
                self.update_pool(oldkey, known)
130
131
class Telegram(object):
132
    def __init__(self, config, service):
133
        self.configuration = config
134
        self.service = service
135
136
    def sendmessage(self, message):
137
        if self.configuration.is_enabled('telegram'):
138
            sendalert(message, self.service)
139
140
    def sendphoto(self, file_name):
141
        if os.path.isfile(file_name) and os.path.getsize(file_name) > 0:
142
            if self.configuration.is_enabled('telegram'):
143
                sendphoto(file_name, self.service)
144