forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutil.py
executable file
·2132 lines (1754 loc) · 65.3 KB
/
util.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 (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Miscellaneous utility functions
#
import os
import re
import sys
import subprocess
import shutil
import tempfile
import signal
import time
import datetime
import errno
import socket
import xml.dom.minidom
import scsiutil
import stat
import xs_errors
import XenAPI # pylint: disable=import-error
import xmlrpc.client
import base64
import syslog
import resource
import traceback
import glob
import copy
import tempfile
from functools import reduce
NO_LOGGING_STAMPFILE = '/etc/xensource/no_sm_log'
IORETRY_MAX = 20 # retries
IORETRY_PERIOD = 1.0 # seconds
LOGGING = not (os.path.exists(NO_LOGGING_STAMPFILE))
_SM_SYSLOG_FACILITY = syslog.LOG_LOCAL2
LOG_EMERG = syslog.LOG_EMERG
LOG_ALERT = syslog.LOG_ALERT
LOG_CRIT = syslog.LOG_CRIT
LOG_ERR = syslog.LOG_ERR
LOG_WARNING = syslog.LOG_WARNING
LOG_NOTICE = syslog.LOG_NOTICE
LOG_INFO = syslog.LOG_INFO
LOG_DEBUG = syslog.LOG_DEBUG
ISCSI_REFDIR = '/var/run/sr-ref'
CMD_DD = "/bin/dd"
FIST_PAUSE_PERIOD = 30 # seconds
class SMException(Exception):
"""Base class for all SM exceptions for easier catching & wrapping in
XenError"""
class CommandException(SMException):
def error_message(self, code):
if code > 0:
return os.strerror(code)
elif code < 0:
return "Signalled %s" % (abs(code))
return "Success"
def __init__(self, code, cmd="", reason='exec failed'):
self.code = code
self.cmd = cmd
self.reason = reason
Exception.__init__(self, self.error_message(code))
class SRBusyException(SMException):
"""The SR could not be locked"""
pass
def logException(tag):
info = sys.exc_info()
if info[0] == SystemExit:
# this should not be happening when catching "Exception", but it is
sys.exit(0)
tb = reduce(lambda a, b: "%s%s" % (a, b), traceback.format_tb(info[2]))
str = "***** %s: EXCEPTION %s, %s\n%s" % (tag, info[0], info[1], tb)
SMlog(str)
def roundup(divisor, value):
"""Retruns the rounded up value so it is divisible by divisor."""
if value == 0:
value = 1
if value % divisor != 0:
return ((int(value) // divisor) + 1) * divisor
return value
def to_plain_string(obj):
if obj is None:
return None
if type(obj) == str:
return obj
return str(obj)
def shellquote(arg):
return '"%s"' % arg.replace('"', '\\"')
def make_WWN(name):
hex_prefix = name.find("0x")
if (hex_prefix >= 0):
name = name[name.find("0x") + 2:len(name)]
# inject dashes for each nibble
if (len(name) == 16): # sanity check
name = name[0:2] + "-" + name[2:4] + "-" + name[4:6] + "-" + \
name[6:8] + "-" + name[8:10] + "-" + name[10:12] + "-" + \
name[12:14] + "-" + name[14:16]
return name
def _logToSyslog(ident, facility, priority, message):
syslog.openlog(ident, 0, facility)
syslog.syslog(priority, "[%d] %s" % (os.getpid(), message))
syslog.closelog()
def SMlog(message, ident="SM", priority=LOG_INFO):
if LOGGING:
for message_line in str(message).split('\n'):
_logToSyslog(ident, _SM_SYSLOG_FACILITY, priority, message_line)
def _getDateString():
d = datetime.datetime.now()
t = d.timetuple()
return "%s-%s-%s:%s:%s:%s" % \
(t[0], t[1], t[2], t[3], t[4], t[5])
def doexec(args, inputtext=None, new_env=None, text=True):
"""Execute a subprocess, then return its return code, stdout and stderr"""
env = None
if new_env:
env = dict(os.environ)
env.update(new_env)
proc = subprocess.Popen(args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True, env=env,
universal_newlines=text)
if not text and inputtext is not None:
inputtext = inputtext.encode()
(stdout, stderr) = proc.communicate(inputtext)
rc = proc.returncode
return rc, stdout, stderr
def is_string(value):
return isinstance(value, str)
# These are partially tested functions that replicate the behaviour of
# the original pread,pread2 and pread3 functions. Potentially these can
# replace the original ones at some later date.
#
# cmdlist is a list of either single strings or pairs of strings. For
# each pair, the first component is passed to exec while the second is
# written to the logs.
def pread(cmdlist, close_stdin=False, scramble=None, expect_rc=0,
quiet=False, new_env=None, text=True):
cmdlist_for_exec = []
cmdlist_for_log = []
for item in cmdlist:
if is_string(item):
cmdlist_for_exec.append(item)
if scramble:
if item.find(scramble) != -1:
cmdlist_for_log.append("<filtered out>")
else:
cmdlist_for_log.append(item)
else:
cmdlist_for_log.append(item)
else:
cmdlist_for_exec.append(item[0])
cmdlist_for_log.append(item[1])
if not quiet:
SMlog(cmdlist_for_log)
(rc, stdout, stderr) = doexec(cmdlist_for_exec, new_env=new_env, text=text)
if rc != expect_rc:
SMlog("FAILED in util.pread: (rc %d) stdout: '%s', stderr: '%s'" % \
(rc, stdout, stderr))
if quiet:
SMlog("Command was: %s" % cmdlist_for_log)
if '' == stderr:
stderr = stdout
raise CommandException(rc, str(cmdlist), stderr.strip())
if not quiet:
SMlog(" pread SUCCESS")
return stdout
# POSIX guaranteed atomic within the same file system.
# Supply directory to ensure tempfile is created
# in the same directory.
def atomicFileWrite(targetFile, directory, text):
file = None
try:
# Create file only current pid can write/read to
# our responsibility to clean it up.
_, tempPath = tempfile.mkstemp(dir=directory)
file = open(tempPath, 'w')
file.write(text)
# Ensure flushed to disk.
file.flush()
os.fsync(file.fileno())
file.close()
os.rename(tempPath, targetFile)
except OSError:
SMlog("FAILED to atomic write to %s" % (targetFile))
finally:
if (file is not None) and (not file.closed):
file.close()
if os.path.isfile(tempPath):
os.remove(tempPath)
#Read STDOUT from cmdlist and discard STDERR output
def pread2(cmdlist, quiet=False, text=True):
return pread(cmdlist, quiet=quiet, text=text)
#Read STDOUT from cmdlist, feeding 'text' to STDIN
def pread3(cmdlist, text):
SMlog(cmdlist)
(rc, stdout, stderr) = doexec(cmdlist, text)
if rc:
SMlog("FAILED in util.pread3: (errno %d) stdout: '%s', stderr: '%s'" % \
(rc, stdout, stderr))
if '' == stderr:
stderr = stdout
raise CommandException(rc, str(cmdlist), stderr.strip())
SMlog(" pread3 SUCCESS")
return stdout
def listdir(path, quiet=False):
cmd = ["ls", path, "-1", "--color=never"]
try:
text = pread2(cmd, quiet=quiet)[:-1]
if len(text) == 0:
return []
return text.split('\n')
except CommandException as inst:
if inst.code == errno.ENOENT:
raise CommandException(errno.EIO, inst.cmd, inst.reason)
else:
raise CommandException(inst.code, inst.cmd, inst.reason)
def gen_uuid():
cmd = ["uuidgen", "-r"]
return pread(cmd)[:-1]
def match_uuid(s):
regex = re.compile("^[0-9a-f]{8}-(([0-9a-f]{4})-){3}[0-9a-f]{12}")
return regex.search(s, 0)
def findall_uuid(s):
regex = re.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
return regex.findall(s, 0)
def exactmatch_uuid(s):
regex = re.compile("^[0-9a-f]{8}-(([0-9a-f]{4})-){3}[0-9a-f]{12}$")
return regex.search(s, 0)
def start_log_entry(srpath, path, args):
logstring = str(datetime.datetime.now())
logstring += " log: "
logstring += srpath
logstring += " " + path
for element in args:
logstring += " " + element
try:
file = open(srpath + "/filelog.txt", "a")
file.write(logstring)
file.write("\n")
file.close()
except:
pass
# failed to write log ...
def end_log_entry(srpath, path, args):
# for teminating, use "error" or "done"
logstring = str(datetime.datetime.now())
logstring += " end: "
logstring += srpath
logstring += " " + path
for element in args:
logstring += " " + element
try:
file = open(srpath + "/filelog.txt", "a")
file.write(logstring)
file.write("\n")
file.close()
except:
pass
# failed to write log ...
# for now print
# print "%s" % logstring
def ioretry(f, errlist=[errno.EIO], maxretry=IORETRY_MAX, period=IORETRY_PERIOD, **ignored):
retries = 0
while True:
try:
return f()
except OSError as ose:
err = int(ose.errno)
if not err in errlist:
raise CommandException(err, str(f), "OSError")
except CommandException as ce:
if not int(ce.code) in errlist:
raise
retries += 1
if retries >= maxretry:
break
time.sleep(period)
raise CommandException(errno.ETIMEDOUT, str(f), "Timeout")
def ioretry_stat(path, maxretry=IORETRY_MAX):
# this ioretry is similar to the previous method, but
# stat does not raise an error -- so check its return
retries = 0
while retries < maxretry:
stat = os.statvfs(path)
if stat.f_blocks != -1:
return stat
time.sleep(1)
retries += 1
raise CommandException(errno.EIO, "os.statvfs")
def sr_get_capability(sr_uuid):
result = []
session = get_localAPI_session()
try:
sr_ref = session.xenapi.SR.get_by_uuid(sr_uuid)
sm_type = session.xenapi.SR.get_record(sr_ref)['type']
sm_rec = session.xenapi.SM.get_all_records_where(
"field \"type\" = \"%s\"" % sm_type)
# SM expects at least one entry of any SR type
if len(sm_rec) > 0:
result = list(sm_rec.values())[0]['capabilities']
return result
finally:
session.xenapi.session.logout()
def sr_get_driver_info(driver_info):
results = {}
# first add in the vanilla stuff
for key in ['name', 'description', 'vendor', 'copyright', \
'driver_version', 'required_api_version']:
results[key] = driver_info[key]
# add the capabilities (xmlrpc array)
# enforcing activate/deactivate for blktap2
caps = driver_info['capabilities']
if "ATOMIC_PAUSE" in caps:
for cap in ("VDI_ACTIVATE", "VDI_DEACTIVATE"):
if not cap in caps:
caps.append(cap)
elif "VDI_ACTIVATE" in caps or "VDI_DEACTIVATE" in caps:
SMlog("Warning: vdi_[de]activate present for %s" % driver_info["name"])
results['capabilities'] = caps
# add in the configuration options
options = []
for option in driver_info['configuration']:
options.append({'key': option[0], 'description': option[1]})
results['configuration'] = options
return xmlrpc.client.dumps((results, ), "", True)
def return_nil():
return xmlrpc.client.dumps((None, ), "", True, allow_none=True)
def SRtoXML(SRlist):
dom = xml.dom.minidom.Document()
driver = dom.createElement("SRlist")
dom.appendChild(driver)
for key in SRlist.keys():
dict = SRlist[key]
entry = dom.createElement("SR")
driver.appendChild(entry)
e = dom.createElement("UUID")
entry.appendChild(e)
textnode = dom.createTextNode(key)
e.appendChild(textnode)
if 'size' in dict:
e = dom.createElement("Size")
entry.appendChild(e)
textnode = dom.createTextNode(str(dict['size']))
e.appendChild(textnode)
if 'storagepool' in dict:
e = dom.createElement("StoragePool")
entry.appendChild(e)
textnode = dom.createTextNode(str(dict['storagepool']))
e.appendChild(textnode)
if 'aggregate' in dict:
e = dom.createElement("Aggregate")
entry.appendChild(e)
textnode = dom.createTextNode(str(dict['aggregate']))
e.appendChild(textnode)
return dom.toprettyxml()
def pathexists(path):
try:
os.lstat(path)
return True
except OSError as inst:
if inst.errno == errno.EIO:
time.sleep(1)
try:
listdir(os.path.realpath(os.path.dirname(path)))
os.lstat(path)
return True
except:
pass
raise CommandException(errno.EIO, "os.lstat(%s)" % path, "failed")
return False
def force_unlink(path):
try:
os.unlink(path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def create_secret(session, secret):
ref = session.xenapi.secret.create({'value': secret})
return session.xenapi.secret.get_uuid(ref)
def get_secret(session, uuid):
try:
ref = session.xenapi.secret.get_by_uuid(uuid)
return session.xenapi.secret.get_value(ref)
except:
raise xs_errors.XenError('InvalidSecret', opterr='Unable to look up secret [%s]' % uuid)
def get_real_path(path):
"Follow symlinks to the actual file"
absPath = path
directory = ''
while os.path.islink(absPath):
directory = os.path.dirname(absPath)
absPath = os.readlink(absPath)
absPath = os.path.join(directory, absPath)
return absPath
def wait_for_path(path, timeout):
for i in range(0, timeout):
if len(glob.glob(path)):
return True
time.sleep(1)
return False
def wait_for_nopath(path, timeout):
for i in range(0, timeout):
if not os.path.exists(path):
return True
time.sleep(1)
return False
def wait_for_path_multi(path, timeout):
for i in range(0, timeout):
paths = glob.glob(path)
SMlog("_wait_for_paths_multi: paths = %s" % paths)
if len(paths):
SMlog("_wait_for_paths_multi: return first path: %s" % paths[0])
return paths[0]
time.sleep(1)
return ""
def isdir(path):
try:
st = os.stat(path)
return stat.S_ISDIR(st.st_mode)
except OSError as inst:
if inst.errno == errno.EIO:
raise CommandException(errno.EIO, "os.stat(%s)" % path, "failed")
return False
def get_single_entry(path):
f = open(path, 'r')
line = f.readline()
f.close()
return line.rstrip()
def get_fs_size(path):
st = ioretry_stat(path)
return st.f_blocks * st.f_frsize
def get_fs_utilisation(path):
st = ioretry_stat(path)
return (st.f_blocks - st.f_bfree) * \
st.f_frsize
def ismount(path):
"""Test whether a path is a mount point"""
try:
s1 = os.stat(path)
s2 = os.stat(os.path.join(path, '..'))
except OSError as inst:
raise CommandException(inst.errno, "os.stat")
dev1 = s1.st_dev
dev2 = s2.st_dev
if dev1 != dev2:
return True # path/.. on a different device as path
ino1 = s1.st_ino
ino2 = s2.st_ino
if ino1 == ino2:
return True # path/.. is the same i-node as path
return False
def makedirs(name, mode=0o777):
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not pathexists(head):
makedirs(head, mode)
if tail == os.curdir:
return
try:
os.mkdir(name, mode)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(name):
if mode:
os.chmod(name, mode)
pass
else:
raise
def zeroOut(path, fromByte, bytes):
"""write 'bytes' zeros to 'path' starting from fromByte (inclusive)"""
blockSize = 4096
fromBlock = fromByte // blockSize
if fromByte % blockSize:
fromBlock += 1
bytesBefore = fromBlock * blockSize - fromByte
if bytesBefore > bytes:
bytesBefore = bytes
bytes -= bytesBefore
cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=1",
"seek=%s" % fromByte, "count=%s" % bytesBefore]
try:
pread2(cmd)
except CommandException:
return False
blocks = bytes // blockSize
bytes -= blocks * blockSize
fromByte = (fromBlock + blocks) * blockSize
if blocks:
cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=%s" % blockSize,
"seek=%s" % fromBlock, "count=%s" % blocks]
try:
pread2(cmd)
except CommandException:
return False
if bytes:
cmd = [CMD_DD, "if=/dev/zero", "of=%s" % path, "bs=1",
"seek=%s" % fromByte, "count=%s" % bytes]
try:
pread2(cmd)
except CommandException:
return False
return True
def wipefs(blockdev):
"Wipe filesystem signatures from `blockdev`"
pread2(["/usr/sbin/wipefs", "-a", blockdev])
def match_rootdev(s):
regex = re.compile("^PRIMARY_DISK")
return regex.search(s, 0)
def getrootdev():
filename = '/etc/xensource-inventory'
try:
f = open(filename, 'r')
except:
raise xs_errors.XenError('EIO', \
opterr="Unable to open inventory file [%s]" % filename)
rootdev = ''
for line in filter(match_rootdev, f.readlines()):
rootdev = line.split("'")[1]
if not rootdev:
raise xs_errors.XenError('NoRootDev')
return rootdev
def getrootdevID():
rootdev = getrootdev()
try:
rootdevID = scsiutil.getSCSIid(rootdev)
except:
SMlog("util.getrootdevID: Unable to verify serial or SCSIid of device: %s" \
% rootdev)
return ''
if not len(rootdevID):
SMlog("util.getrootdevID: Unable to identify scsi device [%s] via scsiID" \
% rootdev)
return rootdevID
def get_localAPI_session():
# First acquire a valid session
session = XenAPI.xapi_local()
try:
session.xenapi.login_with_password('root', '', '', 'SM')
except:
raise xs_errors.XenError('APISession')
return session
def get_this_host():
uuid = None
f = open("/etc/xensource-inventory", 'r')
for line in f.readlines():
if line.startswith("INSTALLATION_UUID"):
uuid = line.split("'")[1]
f.close()
return uuid
def get_master_ref(session):
pools = session.xenapi.pool.get_all()
return session.xenapi.pool.get_master(pools[0])
def is_master(session):
return get_this_host_ref(session) == get_master_ref(session)
def get_localhost_ref(session):
filename = '/etc/xensource-inventory'
try:
f = open(filename, 'r')
except:
raise xs_errors.XenError('EIO', \
opterr="Unable to open inventory file [%s]" % filename)
domid = ''
for line in filter(match_domain_id, f.readlines()):
domid = line.split("'")[1]
if not domid:
raise xs_errors.XenError('APILocalhost')
vms = session.xenapi.VM.get_all_records_where('field "uuid" = "%s"' % domid)
for vm in vms:
record = vms[vm]
if record["uuid"] == domid:
hostid = record["resident_on"]
return hostid
raise xs_errors.XenError('APILocalhost')
def match_domain_id(s):
regex = re.compile("^CONTROL_DOMAIN_UUID")
return regex.search(s, 0)
def get_hosts_attached_on(session, vdi_uuids):
host_refs = {}
for vdi_uuid in vdi_uuids:
try:
vdi_ref = session.xenapi.VDI.get_by_uuid(vdi_uuid)
except XenAPI.Failure:
SMlog("VDI %s not in db, ignoring" % vdi_uuid)
continue
sm_config = session.xenapi.VDI.get_sm_config(vdi_ref)
for key in [x for x in sm_config.keys() if x.startswith('host_')]:
host_refs[key[len('host_'):]] = True
return host_refs.keys()
def get_this_host_address(session):
host_uuid = get_this_host()
host_ref = session.xenapi.host.get_by_uuid(host_uuid)
return session.xenapi.host.get_record(host_ref)['address']
def get_host_addresses(session):
addresses = []
hosts = session.xenapi.host.get_all_records()
for record in hosts.values():
addresses.append(record['address'])
return addresses
def get_this_host_ref(session):
host_uuid = get_this_host()
host_ref = session.xenapi.host.get_by_uuid(host_uuid)
return host_ref
def get_slaves_attached_on(session, vdi_uuids):
"assume this host is the SR master"
host_refs = get_hosts_attached_on(session, vdi_uuids)
master_ref = get_this_host_ref(session)
return [x for x in host_refs if x != master_ref]
def get_enabled_hosts(session):
"""
Returns a list of host refs that are enabled in the pool.
"""
enabled_hosts = []
hosts = session.xenapi.host.get_all_records()
for host_ref, host_rec in hosts.items():
if host_rec.get("enabled", True):
enabled_hosts.append(host_ref)
return enabled_hosts
def get_online_hosts(session):
online_hosts = []
hosts = session.xenapi.host.get_all_records()
for host_ref, host_rec in hosts.items():
metricsRef = host_rec["metrics"]
metrics = session.xenapi.host_metrics.get_record(metricsRef)
if metrics["live"]:
online_hosts.append(host_ref)
return online_hosts
def get_all_slaves(session):
"assume this host is the SR master"
host_refs = get_online_hosts(session)
master_ref = get_this_host_ref(session)
return [x for x in host_refs if x != master_ref]
def is_attached_rw(sm_config):
for key, val in sm_config.items():
if key.startswith("host_") and val == "RW":
return True
return False
def attached_as(sm_config):
for key, val in sm_config.items():
if key.startswith("host_") and (val == "RW" or val == "RO"):
return val
def find_my_pbd_record(session, host_ref, sr_ref):
try:
pbds = session.xenapi.PBD.get_all_records()
for pbd_ref in pbds.keys():
if pbds[pbd_ref]['host'] == host_ref and pbds[pbd_ref]['SR'] == sr_ref:
return [pbd_ref, pbds[pbd_ref]]
return None
except Exception as e:
SMlog("Caught exception while looking up PBD for host %s SR %s: %s" % (str(host_ref), str(sr_ref), str(e)))
return None
def find_my_pbd(session, host_ref, sr_ref):
ret = find_my_pbd_record(session, host_ref, sr_ref)
if ret is not None:
return ret[0]
else:
return None
def test_hostPBD_devs(session, sr_uuid, devs):
host = get_localhost_ref(session)
sr = session.xenapi.SR.get_by_uuid(sr_uuid)
try:
pbds = session.xenapi.PBD.get_all_records()
except:
raise xs_errors.XenError('APIPBDQuery')
for dev in devs.split(','):
for pbd in pbds:
record = pbds[pbd]
# it's ok if it's *our* PBD
if record["SR"] == sr:
break
if record["host"] == host:
devconfig = record["device_config"]
if 'device' in devconfig:
for device in devconfig['device'].split(','):
if os.path.realpath(device) == os.path.realpath(dev):
return True
return False
def test_hostPBD_lun(session, targetIQN, LUNid):
host = get_localhost_ref(session)
try:
pbds = session.xenapi.PBD.get_all_records()
except:
raise xs_errors.XenError('APIPBDQuery')
for pbd in pbds:
record = pbds[pbd]
if record["host"] == host:
devconfig = record["device_config"]
if 'targetIQN' in devconfig and 'LUNid' in devconfig:
if devconfig['targetIQN'] == targetIQN and \
devconfig['LUNid'] == LUNid:
return True
return False
def test_SCSIid(session, sr_uuid, SCSIid):
if sr_uuid is not None:
sr = session.xenapi.SR.get_by_uuid(sr_uuid)
try:
pbds = session.xenapi.PBD.get_all_records()
except:
raise xs_errors.XenError('APIPBDQuery')
for pbd in pbds:
record = pbds[pbd]
# it's ok if it's *our* PBD
# During FC SR creation, devscan.py passes sr_uuid as None
if sr_uuid is not None:
if record["SR"] == sr:
break
devconfig = record["device_config"]
sm_config = session.xenapi.SR.get_sm_config(record["SR"])
if 'SCSIid' in devconfig and devconfig['SCSIid'] == SCSIid:
return True
elif 'SCSIid' in sm_config and sm_config['SCSIid'] == SCSIid:
return True
elif 'scsi-' + SCSIid in sm_config:
return True
return False
class TimeoutException(SMException):
pass
def timeout_call(timeoutseconds, function, *arguments):
def handler(signum, frame):
raise TimeoutException()
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeoutseconds)
try:
return function(*arguments)
finally:
signal.alarm(0)
def _incr_iscsiSR_refcount(targetIQN, uuid):
if not os.path.exists(ISCSI_REFDIR):
os.mkdir(ISCSI_REFDIR)
filename = os.path.join(ISCSI_REFDIR, targetIQN)
try:
f = open(filename, 'a+')
except:
raise xs_errors.XenError('LVMRefCount', \
opterr='file %s' % filename)
f.seek(0)
found = False
refcount = 0
for line in filter(match_uuid, f.readlines()):
refcount += 1
if line.find(uuid) != -1:
found = True
if not found:
f.write("%s\n" % uuid)
refcount += 1
f.close()
return refcount
def _decr_iscsiSR_refcount(targetIQN, uuid):
filename = os.path.join(ISCSI_REFDIR, targetIQN)
if not os.path.exists(filename):
return 0
try:
f = open(filename, 'a+')
except:
raise xs_errors.XenError('LVMRefCount', \
opterr='file %s' % filename)
f.seek(0)
output = []
refcount = 0
for line in filter(match_uuid, f.readlines()):
if line.find(uuid) == -1:
output.append(line.rstrip())
refcount += 1
if not refcount:
os.unlink(filename)
return refcount
# Re-open file and truncate
f.close()
f = open(filename, 'w')
for i in range(0, refcount):
f.write("%s\n" % output[i])
f.close()
return refcount
# The agent enforces 1 PBD per SR per host, so we
# check for active SR entries not attached to this host
def test_activePoolPBDs(session, host, uuid):
try:
pbds = session.xenapi.PBD.get_all_records()
except:
raise xs_errors.XenError('APIPBDQuery')
for pbd in pbds:
record = pbds[pbd]
if record["host"] != host and record["SR"] == uuid \
and record["currently_attached"]:
return True
return False
def remove_mpathcount_field(session, host_ref, sr_ref, SCSIid):
try:
pbdref = find_my_pbd(session, host_ref, sr_ref)
if pbdref is not None:
key = "mpath-" + SCSIid
session.xenapi.PBD.remove_from_other_config(pbdref, key)
except:
pass
def _testHost(hostname, port, errstring):
SMlog("_testHost: Testing host/port: %s,%d" % (hostname, port))
try:
sockinfo = socket.getaddrinfo(hostname, int(port))[0]
except: