Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvsapi.py
More file actions
4996 lines (4242 loc) · 169 KB
/
Copy pathvsapi.py
File metadata and controls
4996 lines (4242 loc) · 169 KB
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
# VizStack - A Framework to manage visualization resources
# Copyright (C) 2009-2010 Hewlett-Packard
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU 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.
"""
VizStack Job API
"""
import socket
import os
import subprocess
from copy import deepcopy
from xml.dom import minidom
import xml
from pprint import pprint
import re
import domutil
import slurmlauncher
import localscheduler
import sshscheduler
import string
import copy
import sys
masterConfigFile = '/etc/vizstack/master_config.xml'
nodeConfigFile = '/etc/vizstack/node_config.xml'
rgConfigFile = '/etc/vizstack/resource_group_config.xml'
systemTemplateDir = '/opt/vizstack/share/templates/'
overrideTemplateDir = '/etc/vizstack/templates/'
SSM_UNIX_SOCKET_ADDRESS = "/tmp/vs-ssm-socket"
NORMAL_SERVER = "normal"
VIRTUAL_SERVER = "virtual"
VALID_SERVER_TYPES = [NORMAL_SERVER, VIRTUAL_SERVER]
#
# On a multi-GPU system, I had observed that trying to start multiple
# X servers at the same time resulted in a crash. The node would almost
# lock up.
#
# So, vs-X now limits the rate at which X servers start. Right now, this
# is about 5 seconds (look up vs-X.cpp).
#
# Given that a job can run a single X server for every GPU (and more later),
# we need to accomodate for this delay in the job startup.
#
X_SERVER_DELAY = 5
MAX_GPUS_PER_SYSTEM = 8
X_WAIT_TIMEOUT = ((X_SERVER_DELAY+2)*2) * MAX_GPUS_PER_SYSTEM
X_WAIT_MAX = 600
def closeSocket(s):
"""
We need this to avoid TIME_WAIT states
"""
s.shutdown(socket.SHUT_RDWR)
s.close()
def encode_message_with_auth(authType, msg):
if authType!='Munge':
raise "Only Munge supported at this time"
# create a auth packet using munge with this content
d = subprocess.Popen('munge', stdout=subprocess.PIPE, stdin=subprocess.PIPE)
d.stdin.write(msg)
d.stdin.close()
payload = d.stdout.read()
d.stdout.close()
return payload
def decode_message_with_auth(authType, msg):
if authType!='Munge':
raise "Only Munge supported at this time"
# decode the metadata & payload into separate files
sp = subprocess.Popen('unmunge', stdout=subprocess.PIPE, stdin=subprocess.PIPE)
sp.stdin.write(msg)
sp.stdin.close()
decoded = sp.stdout.readlines()
errcode = sp.wait()
if errcode != 0:
return [errcode, None, None]
# decoding succeeded, so get the metadata
metadata = []
for ln in range(len(decoded)):
if len(decoded[ln])==1:
metadata = decoded[:ln-1]
message = string.join(decoded[ln+1:], "")
break
# We now have information about who connected to us
userInfo = parse_munge_metadata(metadata)
# Handle failure
if userInfo['statusCode']!=0:
errCode = userInfo.pop('statusCode')
message = userInfo.pop('status')
userInfo = None
else:
for key in userInfo.keys():
if key not in ['uid','gid']:
userInfo.pop(key)
return [errcode, userInfo, message]
# parse_munge_metadata
#
# Convert the munge metadata (obtained via message decoding) into
# a dictionary format that's easier to use in code.
#
def parse_munge_metadata(metadata):
# metadata is a list of strings
# each string is of the following format
# FIELD:<spaces>value
# The fields of interest to us are STATUS, UID & GID
ret = {}
for kvstr in metadata:
spindex = kvstr.find(':')
key = kvstr[:spindex]
value = string.strip(kvstr[spindex+1:])
# parse the key into components
if key=='UID':
parts = value.split(' ')
ret['user']=parts[0]
ret['uid']=int(parts[1][1:-1])
elif key=='GID':
parts = value.split(' ')
ret['gid']=int(parts[1][1:-1])
elif key=='STATUS':
parts = value.split(' ')
statusCode=int(parts[1][1:-1])
ret['status']=parts[0]
ret['statusCode']=statusCode
else:
ret[key]=value
return ret
class Schedulable:
rootNodeName = "Schedulable"
def __clearAll(self):
self.__launcher = None
self.locality = None
def __init__(self, launcher=None, locality=None):
self.__launcher = launcher
self.locality = locality
def run(self, args, inFile=None, outFile=None, errFile=None, launcherEnv=None):
proc = self.__launcher.run(args, self.locality, inFile, outFile, errFile, launcherEnv)
return proc
def serializeToXML(self):
ret = "<%s>"%(Schedulable.rootNodeName)
ret += "<locality>%s</locality>"%(self.locality)
ret += self.__launcher.serializeToXML()
ret += "</%s>"%(Schedulable.rootNodeName)
return ret
def deserializeFromXML(self, domNode):
self.__clearAll()
if domNode.nodeName != Schedulable.rootNodeName:
raise ValueError, "Failed to deserialize Schedulable. Programmatic Error"
childNodes = domutil.getAllChildNodes(domNode)
for node in childNodes:
if node.nodeName == "locality":
self.locality = domutil.getValue(node)
else:
for className in [localscheduler.LocalReservation, slurmlauncher.SLURMLauncher, sshscheduler.SSHReservation]:
if node.nodeName == className.rootNodeName:
# FIXME: ensure that there is only one of these!
newObject = className()
newObject.deserializeFromXML(node)
self.__launcher = newObject
break
# FIXME : what about bad sched input ?
if self.locality is None:
raise ValueError, "Bad Deserialized Object: No locality was specified"
class VizError(Exception):
INCORRECT_VALUE = 1
UNIMPLEMENTED = 2
RESOURCE_BUSY = 3
BAD_RESOURCE = 4
BAD_CONFIGURATION = 5
RESOURCE_UNSPECIFIED = 6
INTERNAL_ERROR = 7
USER_ERROR = 8
BAD_PROTOCOL = 9
NOT_CONNECTED = 10
RESOURCE_UNAVAILABLE = 11
SOCKET_ERROR = 12
BAD_OPERATION = 13
ACCESS_DENIED = 14
def __init__(self, errorCode, message):
self.errorCode = errorCode
self.message = message
def __str__(self):
return self.message
#
# The "resource" classes. Resource classes encapsulate the kind of resources that
# are managed by VizStack. These are the ones that the application deals with as
# well.
#
#
# resClass index resType
#
# GPU 2 "Quadro FX 5600"
# Keyboard 0 "DefaultKeyboard"
# Mouse 0 "DefaultMouse"
# Server 0 "normal"
# Server 1 "virtual"
# SLI 0 "discrete"
# SLI 0 "quadroplex"
class VizResource:
"""
Base class that represents visualization resources.
Note that the methods of this base class may be overridden in the derived classes.
"""
def __init__(self, resIndex=None, hostName=None, resClass=None, resType=None):
"""
Initialize with a class name, resouce index and hostname and type.
These are the three essential properties of every visualization resource.
Class is the kind of resource. E.g. gpu, X Server, keyboard, mouse, etc
Type is an important property from a user point of view. E.g., gpus of various
types are available(FX5800, etc). X Servers can be of multiple types too,
"regular" and "virtual". Keyboard and mouse may also come in various varieties.
VizResources, by default, are not shared. If you want a shared object
(typically GPU), you neet to set sharing to True.
"""
self.resClass = resClass
self.resIndex = resIndex
self.hostName = hostName
self.resType = resType
self.owners = []
self.shared = False
self.maxShareCount = 1
self.allocationBias = 0
def setShareLimit(self, count):
"""
Set the maximum number of times this object can be shared.
"""
if count<1:
raise VizError(BAD_OPERATION, "Invalid share count")
self.maxShareCount = count
def getShareLimit(self):
"""
Return the maximum number of times this object can be shared.
"""
return self.maxShareCount
def setShared(self, shared):
"""
Change the "shared" state of this object.
"shared" can be True/False
"""
if not isinstance(shared, bool):
raise TypeError, "Expected boolean, got %s"%(shared.__class__)
self.shared = shared
def __checkOwner(self, owner):
# Linux-only for now, so we check for UID
if owner is None:
raise TypeError, "Expecting User ID, got None"
if not isinstance(owner, int):
raise TypeError, "Expecting integer User ID, got %s"%(owner.__class__)
if owner<0:
raise TypeError, "User ID cannot be negative"
def addOwner(self, owner):
"""
Add the specific owner to the list of owners of this resource.
"""
self.__checkOwner(owner)
self.owners.append(owner)
def removeOwner(self, owner):
"""
Remove an owner from the ownership list. Note that an object
can be owned by a user multiple times, and this will remove only
one instance of ownership.
"""
self.__checkOwner(owner)
try:
self.owners.remove(owner)
except ValueError, e:
raise VizError(VizError.ACCESS_DENIED, "That user does not own this object")
def getOwners(self):
"""
Return a list of owners for this object.
"""
return self.owners
def isSharable(self):
"""
An resource is deemed sharable if its share count is >1.
A sharable resource can be allocated either shared or exclusive.
"""
return (self.maxShareCount > 1)
def isShared(self):
"""
Is this object allocated for shared use ?
"""
return self.shared
def isExclusive(self):
"""
Is this object allocated for exclusive access ?
Unshared => exclusive
"""
return not self.shared
def isFree(self):
"""
Is this object free (completely or partially) ?
An object that is allocated "shared" and still has room for allocating
out of it is considered "free"
"""
if self.isShared():
maxUsers = self.maxShareCount
else:
maxUsers = 1
if len(self.owners)==maxUsers:
return False
return True
def canAllocate(self, otherObject):
"""
Return true if "otherObject" can be allocated out of us.
This takes care of sharing cases
"""
if not self.typeSearchMatch(otherObject):
return False
if not self.isFree():
return False
if otherObject.isShared() and (not self.isSharable()):
return False
if self.isShared() and (not otherObject.isShared()):
return False
return True
def doAllocate(self, otherObject, userInfo):
"""
allocate otherObject out of this object.
Add userInfo as one of the owners.
"""
if not self.canAllocate(otherObject):
raise VizError(BAD_OPERATION, "Cant allocate")
self.addOwner(userInfo)
if otherObject.isShared():
if self.maxShareCount>1: # Sharable ?
self.shared = True
def deallocate(self, otherObject, userInfo):
"""
deallocate otherObject from this object.
Remove userInfo from the owner list.
"""
self.removeOwner(userInfo)
# reset to unshared. Note: there's no provision here to have
# shared-only objects
if len(self.owners)==0:
self.shared = False
def getType(self):
"""
Return the type of this resource
"""
return self.resType
def hashKey(self):
"""
Compute a hash key. This is used for easily searching this resource in
a hash table.
"""
return "%s-%d at host %s"%(self.resClass, self.resIndex, self.hostName)
def __str__(self):
return '<%s-%s at host %s>'%(self.resClass, self.resIndex, self.hostName)
def __repr__(self):
return self.__str__()
def isCompletelyResolvable(self):
"""
A resource is considered completely resolvalble if it has a hostname and index
that are valid.
"""
if (self.resIndex is not None) and (self.hostName is not None):
return True
return False
def getAllocationWeight(self):
"""
Returns a weight to be used by the allocation algorithm.
"""
wt = self.allocationBias
if self.resIndex is not None:
wt += self.resIndex
return wt
def getAllocationBias(self):
return self.allocationBias
def setAllocationBias(self, bias):
"""
Set a 'bias' value for allocation. This allows for fine tweaking of
resource allocation.
"""
if not isinstance(bias, int):
raise TypeError, "Expected integer weight, got %s"%(bias.__class__)
self.allocationBias = bias
def getAllocationDOF(self):
"""
Returns the "degrees of freedom" an allocator has while allocating this resource.
The degree of freedom is a non-negative integer value, and is
- 0 if both hostname and index are specified
- 1 if only the index is specified
- 2 if only the hostname is specified
- 3 if neither hostname nor index are specified.
The DOF value is used while allocating resources, primarily to decide the order to
allocate resources.
"""
ret = 0
if self.resIndex is not None:
ret += 2
if self.hostName is not None:
ret += 1
return (3-ret)
def typeSearchMatch(self, otherRes):
"""
Method used to match two resources in a search context.
if otherRes has specified search items that aren't in us, then we fail.
Else we pass
"""
if not isinstance(otherRes, VizResource):
raise ValueError, "%s : You're trying to compare apples(%s) to trees(%s), my friend!"%(self.resClass, self, otherRes)
if otherRes.resClass != self.resClass:
return False
if otherRes.resIndex is not None:
if self.resIndex is None:
return False
if self.resIndex != otherRes.resIndex:
return False
if otherRes.resType is not None:
if self.resType is None:
return False
if self.resType != otherRes.resType:
return False
if otherRes.hostName is not None:
if self.hostName is None:
return False
if self.hostName != otherRes.hostName:
return False
if (otherRes.isShared()) and (not self.isSharable()):
return False
return True
def refersToTheSame(self, otherRes, knownApplesToOranges=False):
"""
Does this resource refer to the same thing as the other resource ?
"""
if not isinstance(otherRes, VizResource):
raise ValueError, "%s : You're trying to compare apples(%s) to trees(%s), my friend!"%(self.resClass, self.resClass, otherRes)
if otherRes.resClass != self.resClass:
if knownApplesToOranges:
return False
raise ValueError, "%s : You're trying to compare apples(%s) and oranges(%s), my friend!"%(self.resClass, self.resClass, otherRes.resClass)
if ( otherRes.resIndex == self.resIndex ) and (otherRes.hostName == self.hostName):
return True
return False
def isSchedulable(self):
"""
Is this resource schedulable ?
"""
return False
def getSchedulable(self):
"""
Return the schedulable for this resource. None is returned if there is no scheduler associated.
"""
return None
def run(self, args, inFile=None, outFile=None, errFile=None, launcherEnv=None):
"""
Run a command on this resource.
You may optionally specify the standard input, output and error streams for the child process.
These are standard python file objects.
"""
raise NotImplementedError, "VizResource of type %s - can't run anything on this!"%(self.resClass)
def getHostName(self):
"""
Return the hostname where this resource is valid.
"""
return self.hostName
def setHostName(self, newName):
"""
Changes the host where this resource resides.
"""
self.hostName = newName
def getIndex(self):
"""
Return the index of this resource.
"""
return self.resIndex
def setIndex(self, newIndex):
"""
Set the index of this resource
"""
self.resIndex = newIndex
def serializeToXML(self, detailedConfig=True, addrOnly=False):
"""
Serialize this resource into an XML format. The base class implementation
serializes only some of the info.
"""
ret = ""
if not addrOnly:
for owner in self.owners:
ret = ret + "<owner>%d</owner>"%(owner)
ret = ret + "<maxShareCount>%d</maxShareCount>"%(self.maxShareCount)
ret = ret + "<shared>%d</shared>"%(self.shared)
if self.allocationBias is not None:
ret += "<allocationBias>%s</allocationBias>"%(self.allocationBias)
return ret
def deserializeFromXML(self, domNode):
"""
Restore the state of this resource from a DOM tree
"""
ownerNodes = domutil.getChildNodes(domNode, "owner")
self.owners = []
for ownerNode in ownerNodes:
self.addOwner(int(domutil.getValue(ownerNode)))
node = domutil.getChildNode(domNode, "maxShareCount")
if node is not None:
self.maxShareCount = int(domutil.getValue(node))
else:
self.maxShareCount = 1
if self.maxShareCount < 1:
raise ValueError, "Failed to deserialize. Invalid maxShareCount."
node = domutil.getChildNode(domNode, "shared")
if node is not None:
self.shared = bool(int(domutil.getValue(node)))
else:
self.shared = False
node = domutil.getChildNode(domNode, "allocationBias")
if node is not None:
self.allocationBias = int(domutil.getValue(node))
class Keyboard(VizResource):
"""
Keyboard resource class.
"""
rootNodeName = "keyboard"
def __clearAll(self):
self.resIndex = None
self.hostName = None
self.resType = None
self.physAddr = None
self.driver = None
self.options = []
def __init__(self, resIndex=None, hostName=None,keyboardType=None, physAddr=None):
VizResource.__init__(self)
self.resClass = "Keyboard"
self.__clearAll()
self.resIndex = resIndex
self.hostName = hostName
self.resType = keyboardType
self.physAddr = physAddr
def getPhysAddr(self):
return self.physAddr
def serializeToXML(self, detailedConfig = True, addrOnly=False):
ret = "<%s>"%(Keyboard.rootNodeName)
ret += VizResource.serializeToXML(self, detailedConfig, addrOnly)
if self.resIndex is not None: ret = ret + "<index>%d</index>"%(self.resIndex)
if self.hostName is not None: ret = ret + "<hostname>%s</hostname>"%(self.hostName)
if not addrOnly:
if self.resType is not None: ret = ret + "<type>%s</type>"%(self.resType)
if self.driver is not None: ret = ret + "<driver>%s</driver>"%(self.driver)
for opt in self.options:
ret = ret + "<option><name>%s</name><value>%s</value></option>"%(opt['name'],opt['value'])
if self.physAddr is not None: ret = ret + "<phys_addr>%s</phys_addr>"%(self.physAddr)
ret += "</%s>"%(Keyboard.rootNodeName)
return ret
def deserializeFromXML(self, domNode):
if domNode.nodeName != Keyboard.rootNodeName:
raise ValueError, "Failed to deserialize Keyboard. Incorrect deserialization attempt."
self.__clearAll()
# Deserialize the base class info
VizResource.deserializeFromXML(self, domNode)
hostNameNode = domutil.getChildNode(domNode, "hostname")
if hostNameNode is not None:
self.hostName = domutil.getValue(hostNameNode)
indexNode = domutil.getChildNode(domNode, "index")
if indexNode is not None:
self.resIndex = int(domutil.getValue(indexNode))
typeNode = domutil.getChildNode(domNode, "type")
if typeNode is not None:
self.resType = domutil.getValue(typeNode)
driverNode = domutil.getChildNode(domNode, "driver")
if driverNode is not None:
self.driver = domutil.getValue(driverNode)
optNodes = domutil.getChildNodes(domNode, "option")
for optNode in optNodes:
opt = {}
optName = domutil.getValue(domutil.getChildNode(optNode, "name"))
optVal = domutil.getValue(domutil.getChildNode(optNode, "value"))
opt['name']=optName
opt['value']=optVal
self.options.append(opt)
self.driver = domutil.getValue(driverNode)
physNode = domutil.getChildNode(domNode, "phys_addr")
if physNode is not None:
self.physAddr = domutil.getValue(physNode)
class Mouse(VizResource):
"""
Mouse resource class.
"""
rootNodeName = "mouse"
def __clearAll(self):
self.resIndex = None
self.hostName = None
self.resType = None
self.physAddr = None
self.driver = None
self.options = []
def __init__(self, resIndex=None, hostName=None,mouseType=None, physAddr=None):
VizResource.__init__(self)
self.resClass = "Mouse"
self.__clearAll()
self.resIndex = resIndex
self.hostName = hostName
self.resType = mouseType
self.physAddr = physAddr
def getPhysAddr(self):
return self.physAddr
def serializeToXML(self, detailedConfig = True, addrOnly=False):
ret = "<%s>"%(Mouse.rootNodeName)
ret += VizResource.serializeToXML(self, detailedConfig, addrOnly)
if self.resIndex is not None: ret = ret + "<index>%d</index>"%(self.resIndex)
if self.hostName is not None: ret = ret + "<hostname>%s</hostname>"%(self.hostName)
if not addrOnly:
if self.resType is not None: ret = ret + "<type>%s</type>"%(self.resType)
if self.driver is not None: ret = ret + "<driver>%s</driver>"%(self.driver)
for opt in self.options:
ret = ret + "<option><name>%s</name><value>%s</value></option>"%(opt['name'],opt['value'])
if self.physAddr is not None: ret = ret + "<phys_addr>%s</phys_addr>"%(self.physAddr)
ret += "</%s>"%(Mouse.rootNodeName)
return ret
def deserializeFromXML(self, domNode):
if domNode.nodeName != Mouse.rootNodeName:
raise ValueError, "Failed to deserialize Keyboard. Incorrect deserialization attempt."
self.__clearAll()
# Deserialize the base class info
VizResource.deserializeFromXML(self, domNode)
hostNameNode = domutil.getChildNode(domNode, "hostname")
if hostNameNode is not None:
self.hostName = domutil.getValue(hostNameNode)
indexNode = domutil.getChildNode(domNode, "index")
if indexNode is not None:
self.resIndex = int(domutil.getValue(indexNode))
typeNode = domutil.getChildNode(domNode, "type")
if typeNode is not None:
self.resType = domutil.getValue(typeNode)
driverNode = domutil.getChildNode(domNode, "driver")
if driverNode is not None:
self.driver = domutil.getValue(driverNode)
optNodes = domutil.getChildNodes(domNode, "option")
for optNode in optNodes:
opt = {}
optName = domutil.getValue(domutil.getChildNode(optNode, "name"))
optVal = domutil.getValue(domutil.getChildNode(optNode, "value"))
opt['name']=optName
opt['value']=optVal
self.options.append(opt)
self.driver = domutil.getValue(driverNode)
physNode = domutil.getChildNode(domNode, "phys_addr")
if physNode is not None:
self.physAddr = domutil.getValue(physNode)
# Resource Aggregates
# resClass index resType
#
# ResourceGroup ? "TiledDisplay"
# Node ? "Proliant DL160 G5"
class VizResourceAggregate(VizResource):
"""
Aggregate of Viz Resources. This has the same root properties - resClass, resIndex and resType
Additionally, it implements a getResources().
Calling some functions on the aggregates is considered an Error -
e.g., getAllocationDOF()
"""
def getResources(self):
"""
Get the list of resources that are included in this resource aggregate.
"""
raise UnimplementedError, "getResources() needs to be implemented in the derived class"
def setResources(self, resources):
"""
Sets the list of resources inside this aggregate to 'resources'
"""
raise UnimplementedError, "setResources() needs to be implemented in the derived class"
def getAllocationDOF(self):
"""
This inherited method from VizResource must not be called by anyone. This method
implementation exists to fail any such attempt.
"""
raise "getAllocationDOF must not be called for this class"
class DisplayDevice(VizResource):
rootNodeName = "display"
def __str__(self):
return self.__repr__()
def __repr__(self):
ret = "<Display Device '"
if self.resType is None:
ret = ret + "<undefined>"
else:
ret = ret + "%s"%(self.resType)
ret += "' at index "
if self.resIndex is None:
ret = ret + "<undefined>"
else:
ret = ret + "%d"%(self.resIndex)
ret = ret + " at host "
if self.hostName is None:
ret = ret + "<undefined>"
else:
ret = ret + "%s"%(self.hostName)
ret = ret + " >"
return ret
def __clearAll(self):
self.resIndex = None
self.resType = None
self.hostName = None
self.input = None
self.edid = None
self.edidBytes = None
self.edid_name = None
self.hsync_min = None
self.hsync_max = None
self.vrefresh_min = None
self.vrefresh_max = None
self.default_mode = None
self.modes = []
self.dimensions = None # Dimensions of the display. Two element [w,h]
self.bezel = None # Bezel - four elements [left, right, bottom, top]
def getDimensions(self):
"""
Get the physical dimensions of this display device (width, height)
in millimeters
"""
return self.dimensions
def setDimensions(self, dimensions):
"""
Set the physical dimensions of this display device (width, height)
in millimeters
"""
if dimensions is None:
self.dimensions = None
return
if not isinstance(dimensions, list):
raise TypeError, "Expect a list"
if len(dimensions)!=2:
raise ValueError, "Expect a two element list. Got %s"%(dimensions)
for dim in dimensions:
if isinstance(dim, int) or isinstance(dim, float) or isinstance(dim, long):
if dim<0:
raise ValueError, "Dimension(%s) cannot be negative"%(dim)
else:
raise TypeError, "Dimension(%s) has be a number"%(dim)
self.dimensions = dimensions
def getEDIDDisplayName(self):
"""
Return the name by which the display identifies itself in the EDID
Returns None of the display has no EDID.
"""
return self.edid_name
def getBezel(self):
return self.bezel
def setBezel(self, bezel):
if bezel is None:
self.bezel = None
return
if not isinstance(bezel, list):
raise TypeError, "Expect a list"
if len(bezel)!=4:
raise ValueError, "Expect a four element list. Got %s"%(bezel)
for val in bezel:
if isinstance(val, int) or isinstance(val, float) or isinstance(val, long):
if val<0:
raise ValueError, "Bezel dimension(%s) cannot be negative"%(val)
else:
raise TypeError, "Bezel dimension(%s) has be a number"%(val)
self.bezel = bezel
def getInput(self):
return self.input
def setEDIDDisplayName(self, name):
self.edid_name = name
def setEDIDBytes(self, value):
self.edidBytes = value
def getEDIDBytes(self):
return self.edidBytes
def setHSyncRange(self, value):
self.hsync_min = value[0]
self.hsync_max = value[1]
def setVRefreshRange(self, value):
self.vrefresh_min = value[0]
self.vrefresh_max = value[1]
def getHSyncRange(self):
return [self.hsync_min, self.hsync_max]
def getVRefreshRange(self):
return [self.vrefresh_min, self.vrefresh_max]
def getAllModes(self):
return deepcopy(self.modes)
def isValid(self):
if self.resType is None:
return False
if len(self.modes)==0:
return False
if self.default_mode is None:
return False
return True
def getModeByAlias(self, alias):
"""
Returns the mode that is supported by this Display Device,
and known by the specified alias.
"""
for thisMode in self.modes:
if alias == thisMode['alias']:
return thisMode
raise ValueError, "Did not find a mode matching '%s'"%(alias)
def getDefaultMode(self):
"""
Returns the "default" mode for this display device.
"""
if self.default_mode is None:
# If this _ever_ shows up, then we have a bug !
raise ValueError, "No default mode has been assigned for this device"
# Search for the default mode and return it.
for thisMode in self.modes:
if self.default_mode == thisMode['alias']:
return thisMode
raise ValueError, "Did not find a matching default mode. A default mode is assigned, but not defined for the display device."
def findBestMatchingMode(self, searchParams):
"""
Find the mode that best matches the search parameters.
searchParams may be a 2 or 3 item list. The following two inputs are supported:
[ width, height ] => search for a mode with this width or height
[ width, height, refresh_rate ] => search for a mode with specified width, height and refresh rate
This function goes through the list of modes supported by this device,
and chooses a single mode.
1. If the refresh rate is not specified in the input, then the
mode matching the width & height and having the maximum refresh
rate is chosen.
2. If the refresh rate is specified, then the mode which matches
all three parameters is returned.
You can’t perform that action at this time.
