/
hb_disk.py
356 lines (315 loc) · 11.6 KB
/
hb_disk.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
"""
Disk Heartbeat
"""
import sys
import os
import mmap
import stat
import errno
import contextlib
import json
import time
import osvcd_shared as shared
import rcExceptions as ex
from rcGlobalEnv import rcEnv
from hb import Hb
from rcUtilities import bdecode
class HbDisk(Hb):
"""
A class factorizing common methods and properties for the disk
heartbeat tx and rx child classes.
"""
# 4MB meta size allows 1024 nodes (with 4k pagesize)
METASIZE = 4 * 1024 * 1024
# A 100MB disk can hold 96 nodes
SLOTSIZE = 1024 * 1024
MAX_SLOTS = METASIZE // mmap.PAGESIZE
def status(self, **kwargs):
data = Hb.status(self, **kwargs)
data["stats"] = self.stats
data["config"] = {
"dev": self.dev,
"timeout": self.timeout,
}
for peer in data["peers"]:
data["peers"][peer].update(self.peer_config.get(peer, {}))
return data
def configure(self):
self.dev = None
self.reset_stats()
self._configure()
def reconfigure(self):
self._configure()
def _configure(self):
if self.name not in shared.NODE.cd:
# this thread will be stopped. don't reconfigure to avoid logging errors
return
self.get_hb_nodes()
self.peer_config = {}
if not hasattr(self, "meta_slot_buff"):
self.meta_slot_buff = mmap.mmap(-1, 2*mmap.PAGESIZE)
if not hasattr(self, "slot_buff"):
self.slot_buff = mmap.mmap(-1, self.SLOTSIZE)
self.timeout = shared.NODE.oget(self.name, "timeout")
try:
new_dev = shared.NODE.oget(self.name, "dev")
except ex.RequiredOptNotFound:
raise ex.excAbortAction("no %s.dev is not set in node.conf" % self.name)
if not os.path.exists(new_dev):
raise ex.excAbortAction("%s does not exist" % new_dev)
new_dev = os.path.realpath(new_dev)
new_flags = os.O_RDWR
statinfo = os.stat(new_dev)
if rcEnv.sysname == "Linux":
if stat.S_ISBLK(statinfo.st_mode):
self.log.info("using directio")
new_flags |= os.O_DIRECT | os.O_SYNC | os.O_DSYNC
else:
raise ex.excAbortAction("%s must be a block device" % new_dev)
else:
if not stat.S_ISCHR(statinfo.st_mode):
raise ex.excAbortAction("%s must be a char device" % new_dev)
if new_dev != self.dev:
self.dev = new_dev
self.flags = new_flags
self.peer_config = {}
self.log.info("set dev=%s", self.dev)
with self.hb_fo() as fo:
self.load_peer_config(fo=fo)
@contextlib.contextmanager
def hb_fo(self):
try:
fd = os.open(self.dev, self.flags)
fo = os.fdopen(fd, 'rb+')
except OSError as exc:
if exc.errno == errno.EINVAL:
raise ex.excAbortAction("%s directio is not supported" % self.dev)
else:
raise ex.excAbortAction("error opening %s: %s" % (self.dev, str(exc)))
except Exception as exc:
raise ex.excAbortAction("error opening %s: %s" % (self.dev, str(exc)))
try:
yield fo
except Exception as exc:
self.log.error("%s: %s", self.dev, exc)
finally:
# closing fo also closes fd
try:
os.fsync(fd)
except OSError as exc:
self.duplog("error", "%(exc)s", exc=str(exc), nodename="")
fo.close()
@staticmethod
def meta_slot_offset(slot):
return slot * mmap.PAGESIZE
def meta_read_slot(self, slot, fo=None):
offset = self.meta_slot_offset(slot)
fo.seek(offset, os.SEEK_SET)
fo.readinto(self.meta_slot_buff)
try:
return bdecode(self.meta_slot_buff[:mmap.PAGESIZE])
except Exception as exc:
return None
def meta_write_slot(self, slot, data, fo=None):
if len(data) > mmap.PAGESIZE:
self.log.error("attempt to write too long data in meta slot %d", slot)
raise ex.excAbortAction()
self.meta_slot_buff.seek(0)
self.meta_slot_buff.write(data)
offset = self.meta_slot_offset(slot)
fo.seek(offset, os.SEEK_SET)
fo.write(self.meta_slot_buff)
fo.flush()
def slot_offset(self, slot):
return self.METASIZE + slot * self.SLOTSIZE
def read_slot(self, slot, fo=None):
offset = self.slot_offset(slot)
fo.seek(offset, os.SEEK_SET)
fo.readinto(self.slot_buff)
data = bdecode(self.slot_buff[:])
end = data.index("\0")
return data[:end]
def write_slot(self, slot, data, fo=None):
if len(data) > self.SLOTSIZE:
self.log.error("attempt to write too long data in slot %d", slot)
raise ex.excAbortAction()
self.slot_buff.seek(0)
self.slot_buff.write(data)
offset = self.slot_offset(slot)
fo.seek(offset, os.SEEK_SET)
fo.write(self.slot_buff)
fo.flush()
def load_peer_config(self, fo=None, verbose=True):
for nodename in self.hb_nodes:
if nodename not in self.peer_config:
self.peer_config[nodename] = {
"slot": -1,
}
for slot in range(self.MAX_SLOTS):
buff = self.meta_read_slot(slot, fo=fo)
if buff is None or buff[0] == "\0":
return
try:
nodename = buff[:buff.index("\0")]
except IndexError:
continue
if nodename not in self.peer_config:
continue
if self.peer_config[nodename]["slot"] >= 0 and \
slot != self.peer_config[nodename]["slot"]:
if verbose:
self.log.warning("duplicate slot %d for node %s (first %d)",
slot, nodename,
self.peer_config[nodename]["slot"])
continue
if verbose:
self.log.info("detect slot %d for node %s", slot, nodename)
self.peer_config[nodename]["slot"] = slot
def allocate_slot(self):
for slot in range(self.MAX_SLOTS):
with self.hb_fo() as fo:
buff = self.meta_read_slot(slot, fo=fo)
if buff is None or buff[0] != "\0":
continue
self.peer_config[rcEnv.nodename]["slot"] = slot
try:
nodename = bytes(rcEnv.nodename, "utf-8")
except TypeError:
nodename = rcEnv.nodename
self.meta_write_slot(slot, nodename, fo=fo)
self.log.info("allocated slot %d", slot)
break
class HbDiskTx(HbDisk):
"""
The disk heartbeat tx class.
"""
def __init__(self, name):
HbDisk.__init__(self, name, role="tx")
def _configure(self):
HbDisk._configure(self)
if self.peer_config[rcEnv.nodename]["slot"] < 0:
self.allocate_slot()
def run(self):
self.set_tid()
try:
self.configure()
except ex.excAbortAction as exc:
self.log.error(exc)
self.stop()
sys.exit(1)
try:
while True:
self.do()
if self.stopped():
sys.exit(0)
with shared.HB_TX_TICKER:
shared.HB_TX_TICKER.wait(self.default_hb_period)
except Exception as exc:
self.log.exception(exc)
def do(self):
self.janitor_procs()
with self.hb_fo() as fo:
self._do(fo)
def _do(self, fo):
self.reload_config()
if rcEnv.nodename not in self.peer_config:
return
slot = self.peer_config[rcEnv.nodename]["slot"]
if slot < 0:
return
message, message_bytes = self.get_message()
if message is None:
return
data = (json.dumps({
"msg": message,
"updated": time.time(),
})+'\0').encode()
try:
self.write_slot(slot, data, fo=fo)
self.set_last()
self.push_stats(message_bytes)
#self.log.info("written to %s slot %s", self.dev, slot)
except Exception as exc:
self.push_stats()
if self.get_last().success:
self.log.error("write to %s slot %d error: %s", self.dev,
self.peer_config[rcEnv.nodename]["slot"], exc)
self.set_last(success=False)
finally:
self.set_beating()
class HbDiskRx(HbDisk):
"""
The disk heartbeat rx class.
"""
def __init__(self, name):
HbDisk.__init__(self, name, role="rx")
self.last_updated = {}
def run(self):
self.set_tid()
try:
self.configure()
except ex.excAbortAction as exc:
self.log.error(exc)
self.stop()
sys.exit(1)
loop = 0
while True:
loop += 1
if loop > 10:
loop = 0
missing = self.missing_peers()
if missing:
self.log.info("reload slots for missing peers: %s", ", ".join(missing))
with self.hb_fo() as fo:
self.load_peer_config(fo=fo)
self.do()
if self.stopped():
sys.exit(0)
with shared.HB_TX_TICKER:
shared.HB_TX_TICKER.wait(self.default_hb_period)
def missing_peers(self):
return [nodename for nodename, data in self.peer_config.items() if data.slot < 0]
def do(self):
self.janitor_procs()
with self.hb_fo() as fo:
self._do(fo)
def _do(self, fo):
self.reload_config()
for nodename, data in self.peer_config.items():
if nodename == rcEnv.nodename:
continue
if data["slot"] < 0:
continue
try:
slot_data = json.loads(self.read_slot(data["slot"], fo=fo))
_nodename, _data = self.decrypt(slot_data["msg"])
if _nodename is None:
# invalid crypt
#self.log.warning("can't decrypt data in node %s slot",
# nodename)
continue
if _nodename != nodename:
self.log.warning("node %s has written its data in node %s "
"reserved slot", _nodename, nodename)
nodename = _nodename
updated = slot_data["updated"]
last_updated = self.last_updated.get(nodename)
if last_updated is not None and last_updated == updated:
# remote tx has not rewritten its slot
#self.log.info("node %s has not updated its slot", nodename)
continue
if updated < time.time() - self.timeout:
# discard too old dataset
continue
self.last_updated[nodename] = updated
self.store_rx_data(_data, nodename)
self.push_stats(len(slot_data))
self.set_last(nodename)
except Exception as exc:
self.push_stats()
if self.get_last(nodename).success:
self.log.error("read from %s slot %d (%s) error: %s", self.dev,
data["slot"], nodename, str(exc))
self.set_last(nodename, success=False)
finally:
self.set_beating(nodename)