/
utils.py
3547 lines (2990 loc) · 119 KB
/
utils.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017-2021 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import glob
import itertools
import json
import os
import pyudev
import random
import re
import socket
import subprocess
import sys
import time
import uuid
import functools
from contextlib import contextmanager
from datetime import datetime
from charmhelpers.core import hookenv
from charmhelpers.core import templating
from charmhelpers.core.host import (
chownr,
cmp_pkgrevno,
lsb_release,
mkdir,
owner,
service_restart,
service_start,
service_stop,
CompareHostReleases,
write_file,
is_container,
)
from charmhelpers.core.hookenv import (
cached,
config,
log,
status_set,
DEBUG,
ERROR,
WARNING,
storage_get,
storage_list,
)
from charmhelpers.fetch import (
add_source,
apt_install,
apt_purge,
apt_update,
filter_missing_packages,
get_installed_version
)
from charmhelpers.contrib.storage.linux.ceph import (
get_mon_map,
monitor_key_set,
monitor_key_exists,
monitor_key_get,
)
from charmhelpers.contrib.storage.linux.utils import (
is_block_device,
is_device_mounted,
)
from charmhelpers.contrib.openstack.utils import (
get_os_codename_install_source,
)
from charmhelpers.contrib.storage.linux import lvm
from charmhelpers.core.unitdata import kv
CEPH_BASE_DIR = os.path.join(os.sep, 'var', 'lib', 'ceph')
OSD_BASE_DIR = os.path.join(CEPH_BASE_DIR, 'osd')
HDPARM_FILE = os.path.join(os.sep, 'etc', 'hdparm.conf')
LEADER = 'leader'
PEON = 'peon'
QUORUM = [LEADER, PEON]
PACKAGES = ['ceph', 'gdisk',
'radosgw', 'xfsprogs',
'lvm2', 'parted', 'smartmontools']
REMOVE_PACKAGES = []
CHRONY_PACKAGE = 'chrony'
CEPH_KEY_MANAGER = 'ceph'
VAULT_KEY_MANAGER = 'vault'
KEY_MANAGERS = [
CEPH_KEY_MANAGER,
VAULT_KEY_MANAGER,
]
LinkSpeed = {
"BASE_10": 10,
"BASE_100": 100,
"BASE_1000": 1000,
"GBASE_10": 10000,
"GBASE_40": 40000,
"GBASE_100": 100000,
"UNKNOWN": None
}
# Mapping of adapter speed to sysctl settings
NETWORK_ADAPTER_SYSCTLS = {
# 10Gb
LinkSpeed["GBASE_10"]: {
'net.core.rmem_default': 524287,
'net.core.wmem_default': 524287,
'net.core.rmem_max': 524287,
'net.core.wmem_max': 524287,
'net.core.optmem_max': 524287,
'net.core.netdev_max_backlog': 300000,
'net.ipv4.tcp_rmem': '10000000 10000000 10000000',
'net.ipv4.tcp_wmem': '10000000 10000000 10000000',
'net.ipv4.tcp_mem': '10000000 10000000 10000000'
},
# Mellanox 10/40Gb
LinkSpeed["GBASE_40"]: {
'net.ipv4.tcp_timestamps': 0,
'net.ipv4.tcp_sack': 1,
'net.core.netdev_max_backlog': 250000,
'net.core.rmem_max': 4194304,
'net.core.wmem_max': 4194304,
'net.core.rmem_default': 4194304,
'net.core.wmem_default': 4194304,
'net.core.optmem_max': 4194304,
'net.ipv4.tcp_rmem': '4096 87380 4194304',
'net.ipv4.tcp_wmem': '4096 65536 4194304',
'net.ipv4.tcp_low_latency': 1,
'net.ipv4.tcp_adv_win_scale': 1
}
}
class Partition(object):
def __init__(self, name, number, size, start, end, sectors, uuid):
"""A block device partition.
:param name: Name of block device
:param number: Partition number
:param size: Capacity of the device
:param start: Starting block
:param end: Ending block
:param sectors: Number of blocks
:param uuid: UUID of the partition
"""
self.name = name,
self.number = number
self.size = size
self.start = start
self.end = end
self.sectors = sectors
self.uuid = uuid
def __str__(self):
return "number: {} start: {} end: {} sectors: {} size: {} " \
"name: {} uuid: {}".format(self.number, self.start,
self.end,
self.sectors, self.size,
self.name, self.uuid)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other):
return not self.__eq__(other)
def unmounted_disks():
"""List of unmounted block devices on the current host."""
disks = []
context = pyudev.Context()
for device in context.list_devices(DEVTYPE='disk'):
if device['SUBSYSTEM'] == 'block':
if device.device_node is None:
continue
matched = False
for block_type in [u'dm-', u'loop', u'ram', u'nbd']:
if block_type in device.device_node:
matched = True
if matched:
continue
disks.append(device.device_node)
log("Found disks: {}".format(disks))
return [disk for disk in disks if not is_device_mounted(disk)]
def save_sysctls(sysctl_dict, save_location):
"""Persist the sysctls to the hard drive.
:param sysctl_dict: dict
:param save_location: path to save the settings to
:raises: IOError if anything goes wrong with writing.
"""
try:
# Persist the settings for reboots
with open(save_location, "w") as fd:
for key, value in sysctl_dict.items():
fd.write("{}={}\n".format(key, value))
except IOError as e:
log("Unable to persist sysctl settings to {}. Error {}".format(
save_location, e), level=ERROR)
raise
def tune_nic(network_interface):
"""This will set optimal sysctls for the particular network adapter.
:param network_interface: string The network adapter name.
"""
speed = get_link_speed(network_interface)
if speed in NETWORK_ADAPTER_SYSCTLS:
status_set('maintenance', 'Tuning device {}'.format(
network_interface))
sysctl_file = os.path.join(
os.sep,
'etc',
'sysctl.d',
'51-ceph-osd-charm-{}.conf'.format(network_interface))
try:
log("Saving sysctl_file: {} values: {}".format(
sysctl_file, NETWORK_ADAPTER_SYSCTLS[speed]),
level=DEBUG)
save_sysctls(sysctl_dict=NETWORK_ADAPTER_SYSCTLS[speed],
save_location=sysctl_file)
except IOError as e:
log("Write to /etc/sysctl.d/51-ceph-osd-charm-{} "
"failed. {}".format(network_interface, e),
level=ERROR)
try:
# Apply the settings
log("Applying sysctl settings", level=DEBUG)
subprocess.check_output(["sysctl", "-p", sysctl_file])
except subprocess.CalledProcessError as err:
log('sysctl -p {} failed with error {}'.format(sysctl_file,
err.output),
level=ERROR)
else:
log("No settings found for network adapter: {}".format(
network_interface), level=DEBUG)
def get_link_speed(network_interface):
"""This will find the link speed for a given network device. Returns None
if an error occurs.
:param network_interface: string The network adapter interface.
:returns: LinkSpeed
"""
speed_path = os.path.join(os.sep, 'sys', 'class', 'net',
network_interface, 'speed')
# I'm not sure where else we'd check if this doesn't exist
if not os.path.exists(speed_path):
return LinkSpeed["UNKNOWN"]
try:
with open(speed_path, 'r') as sysfs:
nic_speed = sysfs.readlines()
# Did we actually read anything?
if not nic_speed:
return LinkSpeed["UNKNOWN"]
# Try to find a sysctl match for this particular speed
for name, speed in LinkSpeed.items():
if speed == int(nic_speed[0].strip()):
return speed
# Default to UNKNOWN if we can't find a match
return LinkSpeed["UNKNOWN"]
except IOError as e:
log("Unable to open {path} because of error: {error}".format(
path=speed_path,
error=e), level='error')
return LinkSpeed["UNKNOWN"]
def persist_settings(settings_dict):
# Write all settings to /etc/hdparm.conf
"""This will persist the hard drive settings to the /etc/hdparm.conf file
The settings_dict should be in the form of {"uuid": {"key":"value"}}
:param settings_dict: dict of settings to save
"""
if not settings_dict:
return
try:
templating.render(source='hdparm.conf', target=HDPARM_FILE,
context=settings_dict)
except IOError as err:
log("Unable to open {path} because of error: {error}".format(
path=HDPARM_FILE, error=err), level=ERROR)
except Exception as e:
# The templating.render can raise a jinja2 exception if the
# template is not found. Rather than polluting the import
# space of this charm, simply catch Exception
log('Unable to render {path} due to error: {error}'.format(
path=HDPARM_FILE, error=e), level=ERROR)
def set_max_sectors_kb(dev_name, max_sectors_size):
"""This function sets the max_sectors_kb size of a given block device.
:param dev_name: Name of the block device to query
:param max_sectors_size: int of the max_sectors_size to save
"""
max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
'max_sectors_kb')
try:
with open(max_sectors_kb_path, 'w') as f:
f.write(max_sectors_size)
except IOError as e:
log('Failed to write max_sectors_kb to {}. Error: {}'.format(
max_sectors_kb_path, e), level=ERROR)
def get_max_sectors_kb(dev_name):
"""This function gets the max_sectors_kb size of a given block device.
:param dev_name: Name of the block device to query
:returns: int which is either the max_sectors_kb or 0 on error.
"""
max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
'max_sectors_kb')
# Read in what Linux has set by default
if os.path.exists(max_sectors_kb_path):
try:
with open(max_sectors_kb_path, 'r') as f:
max_sectors_kb = f.read().strip()
return int(max_sectors_kb)
except IOError as e:
log('Failed to read max_sectors_kb to {}. Error: {}'.format(
max_sectors_kb_path, e), level=ERROR)
# Bail.
return 0
return 0
def get_max_hw_sectors_kb(dev_name):
"""This function gets the max_hw_sectors_kb for a given block device.
:param dev_name: Name of the block device to query
:returns: int which is either the max_hw_sectors_kb or 0 on error.
"""
max_hw_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
'max_hw_sectors_kb')
# Read in what the hardware supports
if os.path.exists(max_hw_sectors_kb_path):
try:
with open(max_hw_sectors_kb_path, 'r') as f:
max_hw_sectors_kb = f.read().strip()
return int(max_hw_sectors_kb)
except IOError as e:
log('Failed to read max_hw_sectors_kb to {}. Error: {}'.format(
max_hw_sectors_kb_path, e), level=ERROR)
return 0
return 0
def set_hdd_read_ahead(dev_name, read_ahead_sectors=256):
"""This function sets the hard drive read ahead.
:param dev_name: Name of the block device to set read ahead on.
:param read_ahead_sectors: int How many sectors to read ahead.
"""
try:
# Set the read ahead sectors to 256
log('Setting read ahead to {} for device {}'.format(
read_ahead_sectors,
dev_name))
subprocess.check_output(['hdparm',
'-a{}'.format(read_ahead_sectors),
dev_name])
except subprocess.CalledProcessError as e:
log('hdparm failed with error: {}'.format(e.output),
level=ERROR)
def get_block_uuid(block_dev):
"""This queries blkid to get the uuid for a block device.
:param block_dev: Name of the block device to query.
:returns: The UUID of the device or None on Error.
"""
try:
block_info = str(subprocess
.check_output(['blkid', '-o', 'export', block_dev])
.decode('UTF-8'))
for tag in block_info.split('\n'):
parts = tag.split('=')
if parts[0] == 'UUID':
return parts[1]
return None
except subprocess.CalledProcessError as err:
log('get_block_uuid failed with error: {}'.format(err.output),
level=ERROR)
return None
def check_max_sectors(save_settings_dict,
block_dev,
uuid):
"""Tune the max_hw_sectors if needed.
make sure that /sys/.../max_sectors_kb matches max_hw_sectors_kb or at
least 1MB for spinning disks
If the box has a RAID card with cache this could go much bigger.
:param save_settings_dict: The dict used to persist settings
:param block_dev: A block device name: Example: /dev/sda
:param uuid: The uuid of the block device
"""
dev_name = None
path_parts = os.path.split(block_dev)
if len(path_parts) == 2:
dev_name = path_parts[1]
else:
log('Unable to determine the block device name from path: {}'.format(
block_dev))
# Play it safe and bail
return
max_sectors_kb = get_max_sectors_kb(dev_name=dev_name)
max_hw_sectors_kb = get_max_hw_sectors_kb(dev_name=dev_name)
if max_sectors_kb < max_hw_sectors_kb:
# OK we have a situation where the hardware supports more than Linux is
# currently requesting
config_max_sectors_kb = hookenv.config('max-sectors-kb')
if config_max_sectors_kb < max_hw_sectors_kb:
# Set the max_sectors_kb to the config.yaml value if it is less
# than the max_hw_sectors_kb
log('Setting max_sectors_kb for device {} to {}'.format(
dev_name, config_max_sectors_kb))
save_settings_dict[
"drive_settings"][uuid][
"read_ahead_sect"] = config_max_sectors_kb
set_max_sectors_kb(dev_name=dev_name,
max_sectors_size=config_max_sectors_kb)
else:
# Set to the max_hw_sectors_kb
log('Setting max_sectors_kb for device {} to {}'.format(
dev_name, max_hw_sectors_kb))
save_settings_dict[
"drive_settings"][uuid]['read_ahead_sect'] = max_hw_sectors_kb
set_max_sectors_kb(dev_name=dev_name,
max_sectors_size=max_hw_sectors_kb)
else:
log('max_sectors_kb match max_hw_sectors_kb. No change needed for '
'device: {}'.format(block_dev))
def tune_dev(block_dev):
"""Try to make some intelligent decisions with HDD tuning. Future work will
include optimizing SSDs.
This function will change the read ahead sectors and the max write
sectors for each block device.
:param block_dev: A block device name: Example: /dev/sda
"""
uuid = get_block_uuid(block_dev)
if uuid is None:
log('block device {} uuid is None. Unable to save to '
'hdparm.conf'.format(block_dev), level=DEBUG)
return
save_settings_dict = {}
log('Tuning device {}'.format(block_dev))
status_set('maintenance', 'Tuning device {}'.format(block_dev))
set_hdd_read_ahead(block_dev)
save_settings_dict["drive_settings"] = {}
save_settings_dict["drive_settings"][uuid] = {}
save_settings_dict["drive_settings"][uuid]['read_ahead_sect'] = 256
check_max_sectors(block_dev=block_dev,
save_settings_dict=save_settings_dict,
uuid=uuid)
persist_settings(settings_dict=save_settings_dict)
status_set('maintenance', 'Finished tuning device {}'.format(block_dev))
def ceph_user():
return 'ceph'
class CrushLocation(object):
def __init__(self, identifier, name, osd="", host="", chassis="",
rack="", row="", pdu="", pod="", room="",
datacenter="", zone="", region="", root=""):
self.identifier = identifier
self.name = name
self.osd = osd
self.host = host
self.chassis = chassis
self.rack = rack
self.row = row
self.pdu = pdu
self.pod = pod
self.room = room
self.datacenter = datacenter
self.zone = zone
self.region = region
self.root = root
def __str__(self):
return "name: {} id: {} osd: {} host: {} chassis: {} rack: {} " \
"row: {} pdu: {} pod: {} room: {} datacenter: {} zone: {} " \
"region: {} root: {}".format(self.name, self.identifier,
self.osd, self.host, self.chassis,
self.rack, self.row, self.pdu,
self.pod, self.room,
self.datacenter, self.zone,
self.region, self.root)
def __eq__(self, other):
return not self.name < other.name and not other.name < self.name
def __ne__(self, other):
return self.name < other.name or other.name < self.name
def __gt__(self, other):
return self.name > other.name
def __ge__(self, other):
return not self.name < other.name
def __le__(self, other):
return self.name < other.name
def get_osd_weight(osd_id):
"""Returns the weight of the specified OSD.
:returns: Float
:raises: ValueError if the monmap fails to parse.
:raises: CalledProcessError if our Ceph command fails.
"""
try:
tree = str(subprocess
.check_output(['ceph', 'osd', 'tree', '--format=json'])
.decode('UTF-8'))
try:
json_tree = json.loads(tree)
# Make sure children are present in the JSON
if not json_tree['nodes']:
return None
for device in json_tree['nodes']:
if device['type'] == 'osd' and device['name'] == osd_id:
return device['crush_weight']
except ValueError as v:
log("Unable to parse ceph tree json: {}. Error: {}".format(
tree, v))
raise
except subprocess.CalledProcessError as e:
log("ceph osd tree command failed with message: {}".format(
e))
raise
def _filter_nodes_and_set_attributes(node, node_lookup_map, lookup_type):
"""Get all nodes of the desired type, with all their attributes.
These attributes can be direct or inherited from ancestors.
"""
attribute_dict = {node['type']: node['name']}
if node['type'] == lookup_type:
attribute_dict['name'] = node['name']
attribute_dict['identifier'] = node['id']
return [attribute_dict]
elif not node.get('children'):
return [attribute_dict]
else:
descendant_attribute_dicts = [
_filter_nodes_and_set_attributes(node_lookup_map[node_id],
node_lookup_map, lookup_type)
for node_id in node.get('children', [])
]
return [dict(attribute_dict, **descendant_attribute_dict)
for descendant_attribute_dict
in itertools.chain.from_iterable(descendant_attribute_dicts)]
def _flatten_roots(nodes, lookup_type='host'):
"""Get a flattened list of nodes of the desired type.
:param nodes: list of nodes defined as a dictionary of attributes and
children
:type nodes: List[Dict[int, Any]]
:param lookup_type: type of searched node
:type lookup_type: str
:returns: flattened list of nodes
:rtype: List[Dict[str, Any]]
"""
lookup_map = {node['id']: node for node in nodes}
root_attributes_dicts = [_filter_nodes_and_set_attributes(node, lookup_map,
lookup_type)
for node in nodes if node['type'] == 'root']
# get a flattened list of roots.
return list(itertools.chain.from_iterable(root_attributes_dicts))
def get_osd_tree(service):
"""Returns the current OSD map in JSON.
:returns: List.
:rtype: List[CrushLocation]
:raises: ValueError if the monmap fails to parse.
Also raises CalledProcessError if our Ceph command fails
"""
try:
tree = str(subprocess
.check_output(['ceph', '--id', service,
'osd', 'tree', '--format=json'])
.decode('UTF-8'))
try:
json_tree = json.loads(tree)
roots = _flatten_roots(json_tree["nodes"])
return [CrushLocation(**host) for host in roots]
except ValueError as v:
log("Unable to parse ceph tree json: {}. Error: {}".format(
tree, v))
raise
except subprocess.CalledProcessError as e:
log("ceph osd tree command failed with message: {}".format(e))
raise
def _get_child_dirs(path):
"""Returns a list of directory names in the specified path.
:param path: a full path listing of the parent directory to return child
directory names
:returns: list. A list of child directories under the parent directory
:raises: ValueError if the specified path does not exist or is not a
directory,
OSError if an error occurs reading the directory listing
"""
if not os.path.exists(path):
raise ValueError('Specified path "%s" does not exist' % path)
if not os.path.isdir(path):
raise ValueError('Specified path "%s" is not a directory' % path)
files_in_dir = [os.path.join(path, f) for f in os.listdir(path)]
return list(filter(os.path.isdir, files_in_dir))
def _get_osd_num_from_dirname(dirname):
"""Parses the dirname and returns the OSD id.
Parses a string in the form of 'ceph-{osd#}' and returns the OSD number
from the directory name.
:param dirname: the directory name to return the OSD number from
:return int: the OSD number the directory name corresponds to
:raises ValueError: if the OSD number cannot be parsed from the provided
directory name.
"""
match = re.search(r'ceph-(?P<osd_id>\d+)', dirname)
if not match:
raise ValueError("dirname not in correct format: {}".format(dirname))
return match.group('osd_id')
def get_local_osd_ids():
"""This will list the /var/lib/ceph/osd/* directories and try
to split the ID off of the directory name and return it in
a list.
:returns: list. A list of OSD identifiers
:raises: OSError if something goes wrong with listing the directory.
"""
osd_ids = []
osd_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'osd')
if os.path.exists(osd_path):
try:
dirs = os.listdir(osd_path)
for osd_dir in dirs:
osd_id = osd_dir.split('-')[1]
if (_is_int(osd_id) and
filesystem_mounted(os.path.join(
os.sep, osd_path, osd_dir))):
osd_ids.append(osd_id)
except OSError:
raise
return osd_ids
def get_local_mon_ids():
"""This will list the /var/lib/ceph/mon/* directories and try
to split the ID off of the directory name and return it in
a list.
:returns: list. A list of monitor identifiers
:raises: OSError if something goes wrong with listing the directory.
"""
mon_ids = []
mon_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'mon')
if os.path.exists(mon_path):
try:
dirs = os.listdir(mon_path)
for mon_dir in dirs:
# Basically this takes everything after ceph- as the monitor ID
match = re.search('ceph-(?P<mon_id>.*)', mon_dir)
if match:
mon_ids.append(match.group('mon_id'))
except OSError:
raise
return mon_ids
def _is_int(v):
"""Return True if the object v can be turned into an integer."""
try:
int(v)
return True
except ValueError:
return False
def get_version():
"""Derive Ceph release from an installed package."""
import apt_pkg as apt
package = "ceph"
current_ver = get_installed_version(package)
if not current_ver:
# package is known, but no version is currently installed.
e = 'Could not determine version of uninstalled package: %s' % package
error_out(e)
vers = apt.upstream_version(current_ver.ver_str)
# x.y match only for 20XX.X
# and ignore patch level for other packages
match = re.match(r'^(\d+)\.(\d+)', vers)
if match:
vers = match.group(0)
return float(vers)
def error_out(msg):
log("FATAL ERROR: {}".format(msg),
level=ERROR)
sys.exit(1)
def is_quorum():
asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
cmd = [
"sudo",
"-u",
ceph_user(),
"ceph",
"--admin-daemon",
asok,
"mon_status"
]
if os.path.exists(asok):
try:
result = json.loads(str(subprocess
.check_output(cmd)
.decode('UTF-8')))
except subprocess.CalledProcessError:
return False
except ValueError:
# Non JSON response from mon_status
return False
if result['state'] in QUORUM:
return True
else:
return False
else:
return False
def is_leader():
asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
cmd = [
"sudo",
"-u",
ceph_user(),
"ceph",
"--admin-daemon",
asok,
"mon_status"
]
if os.path.exists(asok):
try:
result = json.loads(str(subprocess
.check_output(cmd)
.decode('UTF-8')))
except subprocess.CalledProcessError:
return False
except ValueError:
# Non JSON response from mon_status
return False
if result['state'] == LEADER:
return True
else:
return False
else:
return False
def manager_available():
# if manager daemon isn't on this release, just say it is Fine
if cmp_pkgrevno('ceph', '11.0.0') < 0:
return True
cmd = ["sudo", "-u", "ceph", "ceph", "mgr", "dump", "-f", "json"]
try:
result = json.loads(subprocess.check_output(cmd).decode('UTF-8'))
return result['available']
except subprocess.CalledProcessError as e:
log("'{}' failed: {}".format(" ".join(cmd), str(e)))
return False
except Exception:
return False
def wait_for_quorum():
while not is_quorum():
log("Waiting for quorum to be reached")
time.sleep(3)
def wait_for_manager():
while not manager_available():
log("Waiting for manager to be available")
time.sleep(5)
def add_bootstrap_hint(peer):
asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
cmd = [
"sudo",
"-u",
ceph_user(),
"ceph",
"--admin-daemon",
asok,
"add_bootstrap_peer_hint",
peer
]
if os.path.exists(asok):
# Ignore any errors for this call
subprocess.call(cmd)
DISK_FORMATS = [
'xfs',
'ext4',
'btrfs'
]
CEPH_PARTITIONS = [
'89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE', # Ceph encrypted disk in creation
'45B0969E-9B03-4F30-B4C6-5EC00CEFF106', # Ceph encrypted journal
'4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D', # Ceph encrypted OSD data
'4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D', # Ceph OSD data
'45B0969E-9B03-4F30-B4C6-B4B80CEFF106', # Ceph OSD journal
'89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE', # Ceph disk in creation
]
def get_partition_list(dev):
"""Lists the partitions of a block device.
:param dev: Path to a block device. ex: /dev/sda
:returns: Returns a list of Partition objects.
:raises: CalledProcessException if lsblk fails
"""
partitions_list = []
try:
partitions = get_partitions(dev)
# For each line of output
for partition in partitions:
parts = partition.split()
try:
partitions_list.append(
Partition(number=parts[0],
start=parts[1],
end=parts[2],
sectors=parts[3],
size=parts[4],
name=parts[5],
uuid=parts[6])
)
except IndexError:
partitions_list.append(
Partition(number=parts[0],
start=parts[1],
end=parts[2],
sectors=parts[3],
size=parts[4],
name="",
uuid=parts[5])
)
return partitions_list
except subprocess.CalledProcessError:
raise
def is_pristine_disk(dev):
"""
Read first 2048 bytes (LBA 0 - 3) of block device to determine whether it
is actually all zeros and safe for us to use.
Existing partitioning tools does not discern between a failure to read from
block device, failure to understand a partition table and the fact that a
block device has no partition table. Since we need to be positive about
which is which we need to read the device directly and confirm ourselves.
:param dev: Path to block device
:type dev: str
:returns: True all 2048 bytes == 0x0, False if not
:rtype: bool
"""
want_bytes = 2048
try:
f = open(dev, 'rb')
except OSError as e:
log(e)
return False
data = f.read(want_bytes)
read_bytes = len(data)
if read_bytes != want_bytes:
log('{}: short read, got {} bytes expected {}.'
.format(dev, read_bytes, want_bytes), level=WARNING)
return False
return all(byte == 0x0 for byte in data)
def is_osd_disk(dev):
db = kv()
osd_devices = db.get('osd-devices', [])
if dev in osd_devices:
log('Device {} already processed by charm,'
' skipping'.format(dev))
return True
partitions = get_partition_list(dev)
for partition in partitions:
try:
info = str(subprocess
.check_output(['sgdisk', '-i', partition.number, dev])
.decode('UTF-8'))
info = info.split("\n") # IGNORE:E1103
for line in info:
for ptype in CEPH_PARTITIONS:
sig = 'Partition GUID code: {}'.format(ptype)
if line.startswith(sig):
return True
except subprocess.CalledProcessError as e:
log("sgdisk inspection of partition {} on {} failed with "
"error: {}. Skipping".format(partition.minor, dev, e),
level=ERROR)
return False
def start_osds(devices):
# Scan for Ceph block devices
rescan_osd_devices()
if (cmp_pkgrevno('ceph', '0.56.6') >= 0 and
cmp_pkgrevno('ceph', '14.2.0') < 0):
# Use ceph-disk activate for directory based OSD's
for dev_or_path in devices:
if os.path.exists(dev_or_path) and os.path.isdir(dev_or_path):
subprocess.check_call(
['ceph-disk', 'activate', dev_or_path])
def udevadm_settle():
cmd = ['udevadm', 'settle']
subprocess.call(cmd)