forked from hyperledger/indy-plenum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_manager.py
257 lines (219 loc) · 10.2 KB
/
stack_manager.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
from abc import ABCMeta
from collections import OrderedDict
from plenum.common.keygen_utils import initRemoteKeys
from plenum.common.txn_util import get_payload_data, get_type, get_from
from stp_core.types import HA
from stp_core.network.exceptions import RemoteNotFound
from stp_core.common.log import getlogger
from plenum.common.constants import DATA, ALIAS, TARGET_NYM, NODE_IP, CLIENT_IP, \
CLIENT_PORT, NODE_PORT, VERKEY, NODE, SERVICES, VALIDATOR, CLIENT_STACK_SUFFIX
from plenum.common.util import cryptonymToHex, updateNestedDict
logger = getlogger()
class TxnStackManager(metaclass=ABCMeta):
def __init__(self, name, keys_dir, isNode=True):
self.name = name
self.keys_dir = keys_dir
self.isNode = isNode
@staticmethod
def parseLedgerForHaAndKeys(ledger, returnActive=True, ledger_size=None):
"""
Returns validator ip, ports and keys
:param ledger:
:param returnActive: If returnActive is True, return only those
validators which are not out of service
:return:
"""
nodeReg = OrderedDict()
cliNodeReg = OrderedDict()
nodeKeys = {}
activeValidators = set()
try:
TxnStackManager._parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=ledger_size)
except ValueError:
errMsg = 'Pool transaction file corrupted. Rebuild pool transactions.'
logger.exception(errMsg)
exit(errMsg)
if returnActive:
allNodes = tuple(nodeReg.keys())
for nodeName in allNodes:
if nodeName not in activeValidators:
nodeReg.pop(nodeName, None)
cliNodeReg.pop(nodeName + CLIENT_STACK_SUFFIX, None)
nodeKeys.pop(nodeName, None)
return nodeReg, cliNodeReg, nodeKeys
else:
return nodeReg, cliNodeReg, nodeKeys, activeValidators
@staticmethod
def _parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=None):
"""
helper function for parseLedgerForHaAndKeys
"""
for _, txn in ledger.getAllTxn(to=ledger_size):
if get_type(txn) == NODE:
txn_data = get_payload_data(txn)
nodeName = txn_data[DATA][ALIAS]
clientStackName = nodeName + CLIENT_STACK_SUFFIX
nHa = (txn_data[DATA][NODE_IP], txn_data[DATA][NODE_PORT]) \
if (NODE_IP in txn_data[DATA] and NODE_PORT in txn_data[DATA]) \
else None
cHa = (txn_data[DATA][CLIENT_IP], txn_data[DATA][CLIENT_PORT]) \
if (CLIENT_IP in txn_data[DATA] and CLIENT_PORT in txn_data[DATA]) \
else None
if nHa:
nodeReg[nodeName] = HA(*nHa)
if cHa:
cliNodeReg[clientStackName] = HA(*cHa)
try:
# TODO: Need to handle abbreviated verkey
key_type = 'verkey'
verkey = cryptonymToHex(str(txn_data[TARGET_NYM]))
key_type = 'identifier'
cryptonymToHex(get_from(txn))
except ValueError:
logger.exception(
'Invalid {}. Rebuild pool transactions.'.format(key_type))
exit('Invalid {}. Rebuild pool transactions.'.format(key_type))
nodeKeys[nodeName] = verkey
services = txn_data[DATA].get(SERVICES)
if isinstance(services, list):
if VALIDATOR in services:
activeValidators.add(nodeName)
else:
activeValidators.discard(nodeName)
def connectNewRemote(self, txn_data, remoteName, nodeOrClientObj,
addRemote=True):
# TODO: Need to handle abbreviated verkey
verkey = cryptonymToHex(txn_data[TARGET_NYM])
nodeHa = (txn_data[DATA][NODE_IP], txn_data[DATA][NODE_PORT])
cliHa = (txn_data[DATA][CLIENT_IP], txn_data[DATA][CLIENT_PORT])
if addRemote:
try:
# Override any keys found, reason being the scenario where
# before this node comes to know about the other node, the other
# node tries to connect to it.
initRemoteKeys(self.name, remoteName, self.keys_dir, verkey, override=True)
except Exception as ex:
logger.error("Exception while initializing keep for remote {}".
format(ex))
if self.isNode:
nodeOrClientObj.nodeReg[remoteName] = HA(*nodeHa)
nodeOrClientObj.cliNodeReg[remoteName +
CLIENT_STACK_SUFFIX] = HA(*cliHa)
logger.display("{} adding new node {} with HA {}".format(self.name, remoteName, nodeHa))
else:
nodeOrClientObj.nodeReg[remoteName] = HA(*cliHa)
logger.display("{} adding new node {} with HA {}".format(self.name, remoteName, cliHa))
nodeOrClientObj.nodestack.maintainConnections(force=True)
def stackHaChanged(self, txn_data, remoteName, nodeOrClientObj):
nodeHa = None
cliHa = None
if self.isNode:
node_ha_changed = False
(ip, port) = nodeOrClientObj.nodeReg[remoteName]
if NODE_IP in txn_data[DATA] and ip != txn_data[DATA][NODE_IP]:
ip = txn_data[DATA][NODE_IP]
node_ha_changed = True
if NODE_PORT in txn_data[DATA] and port != txn_data[DATA][NODE_PORT]:
port = txn_data[DATA][NODE_PORT]
node_ha_changed = True
if node_ha_changed:
nodeHa = (ip, port)
cli_ha_changed = False
(ip, port) = nodeOrClientObj.cliNodeReg[remoteName + CLIENT_STACK_SUFFIX] \
if self.isNode \
else nodeOrClientObj.nodeReg[remoteName]
if CLIENT_IP in txn_data[DATA] and ip != txn_data[DATA][CLIENT_IP]:
ip = txn_data[DATA][CLIENT_IP]
cli_ha_changed = True
if CLIENT_PORT in txn_data[DATA] and port != txn_data[DATA][CLIENT_PORT]:
port = txn_data[DATA][CLIENT_PORT]
cli_ha_changed = True
if cli_ha_changed:
cliHa = (ip, port)
rid = self.removeRemote(nodeOrClientObj.nodestack, remoteName)
if self.isNode:
if nodeHa:
nodeOrClientObj.nodeReg[remoteName] = HA(*nodeHa)
if cliHa:
nodeOrClientObj.cliNodeReg[remoteName +
CLIENT_STACK_SUFFIX] = HA(*cliHa)
elif cliHa:
nodeOrClientObj.nodeReg[remoteName] = HA(*cliHa)
# Attempt connection at the new HA
nodeOrClientObj.nodestack.maintainConnections(force=True)
return rid
def stackKeysChanged(self, txn_data, remoteName, nodeOrClientObj):
logger.debug("{} clearing remote role data in keep of {}".
format(nodeOrClientObj.nodestack.name, remoteName))
logger.display("{} removing remote {}".format(nodeOrClientObj, remoteName))
# Removing remote so that the nodestack will attempt to connect
rid = self.removeRemote(nodeOrClientObj.nodestack, remoteName)
if txn_data[VERKEY][0] == '~': # abbreviated
verkey = cryptonymToHex(
txn_data[TARGET_NYM]) + cryptonymToHex(txn_data[VERKEY][1:])
else:
verkey = cryptonymToHex(txn_data[VERKEY])
# Override any keys found
initRemoteKeys(self.name, remoteName, self.keys_dir, verkey, override=True)
# Attempt connection with the new keys
nodeOrClientObj.nodestack.maintainConnections(force=True)
return rid
@staticmethod
def removeRemote(stack, remoteName):
try:
stack.disconnectByName(remoteName)
rid = stack.removeRemoteByName(remoteName)
logger.display("{} removed remote {}".format(stack, remoteName))
except RemoteNotFound as ex:
logger.debug(str(ex))
rid = None
return rid
def addRemoteKeysFromLedger(self, keys):
for remoteName, key in keys.items():
# If its a client then remoteName should be suffixed with
# CLIENT_STACK_SUFFIX
if not self.isNode:
remoteName += CLIENT_STACK_SUFFIX
try:
# Override any keys found, reason being the scenario where
# before this node comes to know about the other node, the other
# node tries to connect to it.
# Do it only for Nodes, not for Clients!
# if self.isNode:
initRemoteKeys(self.name, remoteName, self.keys_dir, key,
override=True)
except Exception as ex:
logger.error("Exception while initializing keep for remote {}".
format(ex))
def getNodeRegistry(self, ledger_size=None):
nodeReg, _, _ = self.parseLedgerForHaAndKeys(
self.ledger, ledger_size=ledger_size)
return nodeReg
def nodeExistsInLedger(self, nym):
# Since PoolLedger is going to be small so using
# `getAllTxn` is fine
for _, txn in self.ledger.getAllTxn():
if get_type(txn) == NODE and \
get_payload_data(txn)[TARGET_NYM] == nym:
return True
return False
# TODO: Consider removing `nodeIds` and using `node_ids_in_order`
@property
def nodeIds(self) -> set:
return {get_payload_data(txn)[TARGET_NYM] for _, txn in self.ledger.getAllTxn()}
def getNodesServices(self):
# Returns services for each node
srvs = dict()
for _, txn in self.ledger.getAllTxn():
txn_data = get_payload_data(txn)
if get_type(txn) == NODE and \
txn_data.get(DATA, {}).get(SERVICES) is not None:
srvs.update({txn_data[TARGET_NYM]: txn_data[DATA][SERVICES]})
return srvs
@staticmethod
def updateNodeTxns(oldTxn, newTxn):
updateNestedDict(oldTxn, newTxn, nestedKeysToUpdate=[DATA, ])