idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
43,600
def dedicate ( rh ) : rh . printSysLog ( "Enter changeVM.dedicate" ) parms = [ "-T" , rh . userid , "-v" , rh . parms [ 'vaddr' ] , "-r" , rh . parms [ 'raddr' ] , "-R" , rh . parms [ 'mode' ] ] hideList = [ ] results = invokeSMCLI ( rh , "Image_Device_Dedicate_DM" , parms , hideInLog = hideList ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 : results = isLoggedOn ( rh , rh . userid ) if ( results [ 'overallRC' ] == 0 and results [ 'rs' ] == 0 ) : parms = [ "-T" , rh . userid , "-v" , rh . parms [ 'vaddr' ] , "-r" , rh . parms [ 'raddr' ] , "-R" , rh . parms [ 'mode' ] ] results = invokeSMCLI ( rh , "Image_Device_Dedicate" , parms ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , "Dedicated device " + rh . parms [ 'vaddr' ] + " to the active configuration." ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit changeVM.dedicate, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Dedicate device .
43,601
def addAEMOD ( rh ) : rh . printSysLog ( "Enter changeVM.addAEMOD" ) invokeScript = "invokeScript.sh" trunkFile = "aemod.doscript" fileClass = "X" tempDir = tempfile . mkdtemp ( ) if os . path . isfile ( rh . parms [ 'aeScript' ] ) : if rh . parms [ 'aeScript' ] . startswith ( "/" ) : s = rh . parms [ 'aeScript' ] tmpAEScript = s [ s . rindex ( "/" ) + 1 : ] else : tmpAEScript = rh . parms [ 'aeScript' ] shutil . copyfile ( rh . parms [ 'aeScript' ] , tempDir + "/" + tmpAEScript ) conf = "#!/bin/bash \n" baseName = os . path . basename ( rh . parms [ 'aeScript' ] ) parm = "/bin/bash %s %s \n" % ( baseName , rh . parms [ 'invParms' ] ) fh = open ( tempDir + "/" + invokeScript , "w" ) fh . write ( conf ) fh . write ( parm ) fh . close ( ) tar = tarfile . open ( tempDir + "/" + trunkFile , "w" ) for file in os . listdir ( tempDir ) : tar . add ( tempDir + "/" + file , arcname = file ) tar . close ( ) punch2reader ( rh , rh . userid , tempDir + "/" + trunkFile , fileClass ) shutil . rmtree ( tempDir ) else : shutil . rmtree ( tempDir ) msg = msgs . msg [ '0400' ] [ 1 ] % ( modId , rh . parms [ 'aeScript' ] ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0400' ] [ 0 ] ) rh . printSysLog ( "Exit changeVM.addAEMOD, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Send an Activation Modification Script to the virtual machine .
43,602
def addLOADDEV ( rh ) : rh . printSysLog ( "Enter changeVM.addLOADDEV" ) if ( 'scpData' in rh . parms and 'scpDataType' not in rh . parms ) : msg = msgs . msg [ '0014' ] [ 1 ] % ( modId , "scpData" , "scpDataType" ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0014' ] [ 0 ] ) return if ( 'scpDataType' in rh . parms and 'scpData' not in rh . parms ) : if rh . parms [ 'scpDataType' ] . lower ( ) == "delete" : scpDataType = 1 else : msg = msgs . msg [ '0014' ] [ 1 ] % ( modId , "scpDataType" , "scpData" ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0014' ] [ 0 ] ) return scpData = "" if 'scpDataType' in rh . parms : if rh . parms [ 'scpDataType' ] . lower ( ) == "hex" : scpData = rh . parms [ 'scpData' ] scpDataType = 3 elif rh . parms [ 'scpDataType' ] . lower ( ) == "ebcdic" : scpData = rh . parms [ 'scpData' ] scpDataType = 2 elif rh . parms [ 'scpDataType' ] . lower ( ) != "delete" : msg = msgs . msg [ '0016' ] [ 1 ] % ( modId , rh . parms [ 'scpDataType' ] ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0016' ] [ 0 ] ) return else : scpDataType = 0 scpData = "" if 'boot' not in rh . parms : boot = "" else : boot = rh . parms [ 'boot' ] if 'addr' not in rh . parms : block = "" else : block = rh . parms [ 'addr' ] if 'lun' not in rh . parms : lun = "" else : lun = rh . parms [ 'lun' ] lun . replace ( "0x" , "" ) if 'wwpn' not in rh . parms : wwpn = "" else : wwpn = rh . parms [ 'wwpn' ] wwpn . replace ( "0x" , "" ) parms = [ "-T" , rh . userid , "-b" , boot , "-k" , block , "-l" , lun , "-p" , wwpn , "-s" , str ( scpDataType ) ] if scpData != "" : parms . extend ( [ "-d" , scpData ] ) results = invokeSMCLI ( rh , "Image_SCSI_Characteristics_Define_DM" , parms ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit changeVM.addLOADDEV, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Sets the LOADDEV statement in the virtual machine s directory entry .
43,603
def purgeRDR ( rh ) : rh . printSysLog ( "Enter changeVM.purgeRDR" ) results = purgeReader ( rh ) rh . updateResults ( results ) rh . printSysLog ( "Exit changeVM.purgeRDR, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Purge the reader belonging to the virtual machine .
43,604
def removeDisk ( rh ) : rh . printSysLog ( "Enter changeVM.removeDisk" ) results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 } loggedOn = False results = isLoggedOn ( rh , rh . userid ) if results [ 'overallRC' ] == 0 : if results [ 'rs' ] == 0 : loggedOn = True results = disableEnableDisk ( rh , rh . userid , rh . parms [ 'vaddr' ] , '-d' ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 and loggedOn : strCmd = "/sbin/vmcp detach " + rh . parms [ 'vaddr' ] results = execCmdThruIUCV ( rh , rh . userid , strCmd ) if results [ 'overallRC' ] != 0 : if re . search ( '(^HCP\w\w\w040E)' , results [ 'response' ] ) : results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , 'response' : '' } else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 : parms = [ "-T" , rh . userid , "-v" , rh . parms [ 'vaddr' ] , "-e" , "0" ] results = invokeSMCLI ( rh , "Image_Disk_Delete_DM" , parms ) if results [ 'overallRC' ] != 0 : if ( results [ 'overallRC' ] == 8 and results [ 'rc' ] == 208 and results [ 'rs' ] == 36 ) : results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , 'response' : '' } else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) else : rh . updateResults ( results ) rh . printSysLog ( "Exit changeVM.removeDisk, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Remove a disk from a virtual machine .
43,605
def send_request ( self , api_name , * api_args , ** api_kwargs ) : return self . conn . request ( api_name , * api_args , ** api_kwargs )
Refer to SDK API documentation .
43,606
def getDiskPoolNames ( rh ) : rh . printSysLog ( "Enter getHost.getDiskPoolNames" ) parms = [ "-q" , "1" , "-e" , "3" , "-T" , "dummy" ] results = invokeSMCLI ( rh , "Image_Volume_Space_Query_DM" , parms ) if results [ 'overallRC' ] == 0 : for line in results [ 'response' ] . splitlines ( ) : poolName = line . partition ( ' ' ) [ 0 ] rh . printLn ( "N" , poolName ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit getHost.getDiskPoolNames, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Obtain the list of disk pools known to the directory manager .
43,607
def getDiskPoolSpace ( rh ) : rh . printSysLog ( "Enter getHost.getDiskPoolSpace" ) results = { 'overallRC' : 0 } if 'poolName' not in rh . parms : poolNames = [ "*" ] else : if isinstance ( rh . parms [ 'poolName' ] , list ) : poolNames = rh . parms [ 'poolName' ] else : poolNames = [ rh . parms [ 'poolName' ] ] if results [ 'overallRC' ] == 0 : totals = { } for qType in [ "2" , "3" ] : parms = [ "-q" , qType , "-e" , "3" , "-T" , "DUMMY" , "-n" , " " . join ( poolNames ) ] results = invokeSMCLI ( rh , "Image_Volume_Space_Query_DM" , parms ) if results [ 'overallRC' ] == 0 : for line in results [ 'response' ] . splitlines ( ) : parts = line . split ( ) if len ( parts ) == 9 : poolName = parts [ 7 ] else : poolName = parts [ 4 ] if poolName not in totals : totals [ poolName ] = { "2" : 0. , "3" : 0. } if parts [ 1 ] [ : 4 ] == "3390" : totals [ poolName ] [ qType ] += int ( parts [ 3 ] ) * 737280 elif parts [ 1 ] [ : 4 ] == "9336" : totals [ poolName ] [ qType ] += int ( parts [ 3 ] ) * 512 else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) break if results [ 'overallRC' ] == 0 : if len ( totals ) == 0 : msg = msgs . msg [ '0402' ] [ 1 ] % ( modId , " " . join ( poolNames ) ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0402' ] [ 0 ] ) else : for poolName in sorted ( totals ) : total = totals [ poolName ] [ "2" ] + totals [ poolName ] [ "3" ] rh . printLn ( "N" , poolName + " Total: " + generalUtils . cvtToMag ( rh , total ) ) rh . printLn ( "N" , poolName + " Used: " + generalUtils . cvtToMag ( rh , totals [ poolName ] [ "3" ] ) ) rh . printLn ( "N" , poolName + " Free: " + generalUtils . cvtToMag ( rh , totals [ poolName ] [ "2" ] ) ) rh . printSysLog ( "Exit getHost.getDiskPoolSpace, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Obtain disk pool space information for all or a specific disk pool .
43,608
def getFcpDevices ( rh ) : rh . printSysLog ( "Enter getHost.getFcpDevices" ) parms = [ "-T" , "dummy" ] results = invokeSMCLI ( rh , "System_WWPN_Query" , parms ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , results [ 'response' ] ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit getHost.getFcpDevices, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Lists the FCP device channels that are active free or offline .
43,609
def deleteMachine ( rh ) : rh . printSysLog ( "Enter deleteVM.deleteMachine" ) results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 } state = 'on' results = isLoggedOn ( rh , rh . userid ) if results [ 'overallRC' ] != 0 : pass elif results [ 'rs' ] == 0 : pass else : state = 'off' results [ 'overallRC' ] = 0 results [ 'rc' ] = 0 results [ 'rs' ] = 0 if state == 'on' : parms = [ "-T" , rh . userid , "-f IMMED" ] results = invokeSMCLI ( rh , "Image_Deactivate" , parms ) if results [ 'overallRC' ] == 0 : pass elif ( results [ 'overallRC' ] == 8 and results [ 'rc' ] == 200 and ( results [ 'rs' ] == 12 or results [ 'rs' ] == 16 ) ) : rh . updateResults ( { } , reset = 1 ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 : result = purgeReader ( rh ) if result [ 'overallRC' ] != 0 : rh . updateResults ( { } , reset = 1 ) if results [ 'overallRC' ] == 0 : parms = [ "-T" , rh . userid , "-e" , "0" ] results = invokeSMCLI ( rh , "Image_Delete_DM" , parms ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) rh . printSysLog ( "Exit deleteVM.deleteMachine, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Delete a virtual machine from the user directory .
43,610
def activate ( rh ) : rh . printSysLog ( "Enter powerVM.activate, userid: " + rh . userid ) parms = [ "-T" , rh . userid ] smcliResults = invokeSMCLI ( rh , "Image_Activate" , parms ) if smcliResults [ 'overallRC' ] == 0 : pass elif ( smcliResults [ 'overallRC' ] == 8 and smcliResults [ 'rc' ] == 200 and smcliResults [ 'rs' ] == 8 ) : pass else : rh . printLn ( "ES" , smcliResults [ 'response' ] ) rh . updateResults ( smcliResults ) if rh . results [ 'overallRC' ] == 0 and 'maxQueries' in rh . parms : if rh . parms [ 'desiredState' ] == 'up' : results = waitForOSState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) else : results = waitForVMState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , "%s: %s" % ( rh . userid , rh . parms [ 'desiredState' ] ) ) else : rh . updateResults ( results ) rh . printSysLog ( "Exit powerVM.activate, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Activate a virtual machine .
43,611
def checkIsReachable ( rh ) : rh . printSysLog ( "Enter powerVM.checkIsReachable, userid: " + rh . userid ) strCmd = "echo 'ping'" results = execCmdThruIUCV ( rh , rh . userid , strCmd ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , rh . userid + ": reachable" ) reachable = 1 else : rh . printLn ( "N" , rh . userid + ": unreachable" ) reachable = 0 rh . updateResults ( { "rs" : reachable } ) rh . printSysLog ( "Exit powerVM.checkIsReachable, rc: 0" ) return 0
Check if a virtual machine is reachable .
43,612
def deactivate ( rh ) : rh . printSysLog ( "Enter powerVM.deactivate, userid: " + rh . userid ) parms = [ "-T" , rh . userid , "-f" , "IMMED" ] results = invokeSMCLI ( rh , "Image_Deactivate" , parms ) if results [ 'overallRC' ] == 0 : pass elif ( results [ 'overallRC' ] == 8 and results [ 'rc' ] == 200 and ( results [ 'rs' ] == 12 or results [ 'rs' ] == 16 ) ) : rh . printLn ( "N" , rh . userid + ": off" ) rh . updateResults ( { } , reset = 1 ) else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 and 'maxQueries' in rh . parms : results = waitForVMState ( rh , rh . userid , 'off' , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , rh . userid + ": off" ) else : rh . updateResults ( results ) rh . printSysLog ( "Exit powerVM.deactivate, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Deactivate a virtual machine .
43,613
def reset ( rh ) : rh . printSysLog ( "Enter powerVM.reset, userid: " + rh . userid ) parms = [ "-T" , rh . userid ] results = invokeSMCLI ( rh , "Image_Deactivate" , parms ) if results [ 'overallRC' ] != 0 : if results [ 'rc' ] == 200 and results [ 'rs' ] == 12 : results [ 'overallRC' ] = 0 results [ 'rc' ] = 0 results [ 'rs' ] = 0 else : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 : results = waitForVMState ( rh , rh . userid , "off" , maxQueries = 30 , sleepSecs = 10 ) if results [ 'overallRC' ] == 0 : parms = [ "-T" , rh . userid ] results = invokeSMCLI ( rh , "Image_Activate" , parms ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'overallRC' ] == 0 and 'maxQueries' in rh . parms : if rh . parms [ 'desiredState' ] == 'up' : results = waitForOSState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) else : results = waitForVMState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , rh . userid + ": " + rh . parms [ 'desiredState' ] ) else : rh . updateResults ( results ) rh . printSysLog ( "Exit powerVM.reset, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Reset a virtual machine .
43,614
def softDeactivate ( rh ) : rh . printSysLog ( "Enter powerVM.softDeactivate, userid: " + rh . userid ) strCmd = "echo 'ping'" iucvResults = execCmdThruIUCV ( rh , rh . userid , strCmd ) if iucvResults [ 'overallRC' ] == 0 : strCmd = "shutdown -h now" iucvResults = execCmdThruIUCV ( rh , rh . userid , strCmd ) if iucvResults [ 'overallRC' ] == 0 : time . sleep ( 15 ) else : rh . printSysLog ( "powerVM.softDeactivate " + rh . userid + " is unreachable. Treating it as already shutdown." ) else : rh . printSysLog ( "powerVM.softDeactivate " + rh . userid + " is unreachable. Treating it as already shutdown." ) parms = [ "-T" , rh . userid ] smcliResults = invokeSMCLI ( rh , "Image_Deactivate" , parms ) if smcliResults [ 'overallRC' ] == 0 : pass elif ( smcliResults [ 'overallRC' ] == 8 and smcliResults [ 'rc' ] == 200 and ( smcliResults [ 'rs' ] == 12 or + smcliResults [ 'rs' ] == 16 ) ) : rh . printLn ( "N" , rh . userid + " is already logged off." ) else : rh . printLn ( "ES" , smcliResults [ 'response' ] ) rh . updateResults ( smcliResults ) if rh . results [ 'overallRC' ] == 0 and 'maxQueries' in rh . parms : waitResults = waitForVMState ( rh , rh . userid , 'off' , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) if waitResults [ 'overallRC' ] == 0 : rh . printLn ( "N" , "Userid '" + rh . userid + " is in the desired state: off" ) else : rh . updateResults ( waitResults ) rh . printSysLog ( "Exit powerVM.softDeactivate, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Deactivate a virtual machine by first shutting down Linux and then log it off .
43,615
def wait ( rh ) : rh . printSysLog ( "Enter powerVM.wait, userid: " + rh . userid ) if ( rh . parms [ 'desiredState' ] == 'off' or rh . parms [ 'desiredState' ] == 'on' ) : results = waitForVMState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) else : results = waitForOSState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] ) if results [ 'overallRC' ] == 0 : rh . printLn ( "N" , rh . userid + ": " + rh . parms [ 'desiredState' ] ) else : rh . updateResults ( results ) rh . printSysLog ( "Exit powerVM.wait, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Wait for the virtual machine to go into the specified state .
43,616
def call ( self , func , * api_args , ** api_kwargs ) : if not isinstance ( func , str ) or ( func == '' ) : msg = ( 'Invalid input for API name, should be a' 'string, type: %s specified.' ) % type ( func ) return self . _construct_api_name_error ( msg ) try : cs = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) except socket . error as err : return self . _construct_socket_error ( 1 , error = six . text_type ( err ) ) try : cs . settimeout ( self . timeout ) try : cs . connect ( ( self . addr , self . port ) ) except socket . error as err : return self . _construct_socket_error ( 2 , addr = self . addr , port = self . port , error = six . text_type ( err ) ) api_data = json . dumps ( ( func , api_args , api_kwargs ) ) api_data = api_data . encode ( ) sent = 0 total_len = len ( api_data ) got_error = False try : while ( sent < total_len ) : this_sent = cs . send ( api_data [ sent : ] ) if this_sent == 0 : got_error = True break sent += this_sent except socket . error as err : return self . _construct_socket_error ( 5 , error = six . text_type ( err ) ) if got_error or sent != total_len : return self . _construct_socket_error ( 3 , sent = sent , api = api_data ) return_blocks = [ ] try : while True : block = cs . recv ( 4096 ) if not block : break block = bytes . decode ( block ) return_blocks . append ( block ) except socket . error as err : return self . _construct_socket_error ( 6 , error = six . text_type ( err ) ) finally : cs . close ( ) if return_blocks : results = json . loads ( '' . join ( return_blocks ) ) else : results = self . _construct_socket_error ( 4 ) return results
Send API call to SDK server and return results
43,617
def dispatch ( environ , start_response , mapper ) : result = mapper . match ( environ = environ ) if result is None : info = environ . get ( 'PATH_INFO' , '' ) LOG . debug ( 'The route for %s can not be found' , info ) raise webob . exc . HTTPNotFound ( json_formatter = util . json_error_formatter ) handler = result . pop ( 'action' ) environ [ 'wsgiorg.routing_args' ] = ( ( ) , result ) return handler ( environ , start_response )
Find a matching route for the current request .
43,618
def handle_not_allowed ( environ , start_response ) : _methods = util . wsgi_path_item ( environ , '_methods' ) headers = { } if _methods : headers [ 'allow' ] = str ( _methods ) raise webob . exc . HTTPMethodNotAllowed ( ( 'The method specified is not allowed for this resource.' ) , headers = headers , json_formatter = util . json_error_formatter )
Return a 405 response when method is not allowed .
43,619
def make_map ( declarations ) : mapper = routes . Mapper ( ) for route , methods in ROUTE_LIST : allowed_methods = [ ] for method , func in methods . items ( ) : mapper . connect ( route , action = func , conditions = dict ( method = [ method ] ) ) allowed_methods . append ( method ) allowed_methods = ', ' . join ( allowed_methods ) mapper . connect ( route , action = handle_not_allowed , _methods = allowed_methods ) return mapper
Process route declarations to create a Route Mapper .
43,620
def _offline_fcp_device ( self , fcp , target_wwpn , target_lun , multipath ) : offline_dev = 'chccwdev -d %s' % fcp delete_records = self . _delete_zfcp_config_records ( fcp , target_wwpn , target_lun ) return '\n' . join ( ( offline_dev , delete_records ) )
rhel offline zfcp . sampe to all rhel distro .
43,621
def _set_sysfs ( self , fcp , target_wwpn , target_lun ) : device = '0.0.%s' % fcp port_add = "echo '%s' > " % target_wwpn port_add += "/sys/bus/ccw/drivers/zfcp/%s/port_add" % device unit_add = "echo '%s' > " % target_lun unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n" % { 'device' : device , 'wwpn' : target_wwpn } return '\n' . join ( ( port_add , unit_add ) )
rhel6 set WWPN and LUN in sysfs
43,622
def _set_zfcp_config_files ( self , fcp , target_wwpn , target_lun ) : device = '0.0.%s' % fcp set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf' % { 'device' : device , 'wwpn' : target_wwpn , 'lun' : target_lun } trigger_uevent = 'echo "add" >> /sys/bus/ccw/devices/%s/uevent\n' % device return '\n' . join ( ( set_zfcp_conf , trigger_uevent ) )
rhel6 set WWPN and LUN in configuration files
43,623
def _set_sysfs ( self , fcp , target_wwpn , target_lun ) : device = '0.0.%s' % fcp unit_add = "echo '%s' > " % target_lun unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n" % { 'device' : device , 'wwpn' : target_wwpn } return unit_add
rhel7 set WWPN and LUN in sysfs
43,624
def _get_udev_rules ( self , channel_read , channel_write , channel_data ) : sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { 'read' : channel_read , 'read' : channel_read , 'write' : channel_write , 'data' : channel_data } rules_str = '# Configure qeth device at' rules_str += ' %(read)s/%(write)s/%(data)s\n' % { 'read' : channel_read , 'write' : channel_write , 'data' : channel_data } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==' '\"qeth\", IMPORT{program}=\"collect %s\"\n' ) % sub_str rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(read)s\", IMPORT{program}="collect %(channel)s\"\n' ) % { 'read' : channel_read , 'channel' : sub_str } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(write)s\", IMPORT{program}=\"collect %(channel)s\"\n' ) % { 'write' : channel_write , 'channel' : sub_str } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(data)s\", IMPORT{program}=\"collect %(channel)s\"\n' ) % { 'data' : channel_data , 'channel' : sub_str } rules_str += ( 'ACTION==\"remove\", SUBSYSTEM==\"drivers\", KERNEL==\"' 'qeth\", IMPORT{program}=\"collect --remove %s\"\n' ) % sub_str rules_str += ( 'ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(read)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n' ) % { 'read' : channel_read , 'channel' : sub_str } rules_str += ( 'ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(write)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n' ) % { 'write' : channel_write , 'channel' : sub_str } rules_str += ( 'ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"' '%(data)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n' ) % { 'data' : channel_data , 'channel' : sub_str } rules_str += ( 'TEST==\"[ccwgroup/%(read)s]\", GOTO=\"qeth-%(read)s' '-end\"\n' ) % { 'read' : channel_read , 'read' : channel_read } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccw\", ENV{COLLECT_' '%(read)s}==\"0\", ATTR{[drivers/ccwgroup:qeth]group}=\"' '%(read)s,%(write)s,%(data)s\"\n' ) % { 'read' : channel_read , 'read' : channel_read , 'write' : channel_write , 'data' : channel_data } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==\"qeth' '\", ENV{COLLECT_%(read)s}==\"0\", ATTR{[drivers/' 'ccwgroup:qeth]group}=\"%(read)s,%(write)s,%(data)s\"\n' 'LABEL=\"qeth-%(read)s-end\"\n' ) % { 'read' : channel_read , 'read' : channel_read , 'write' : channel_write , 'data' : channel_data , 'read' : channel_read } rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL==' '\"%s\", ATTR{layer2}=\"1\"\n' ) % channel_read rules_str += ( 'ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL==' '\"%s\", ATTR{online}=\"1\"\n' ) % channel_read return rules_str
construct udev rules info .
43,625
def _delete_vdev_info ( self , vdev ) : vdev = vdev . lower ( ) rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev cmd = 'rm -f %s\n' % rules_file_name address = '0.0.%s' % str ( vdev ) . zfill ( 4 ) udev_file_name = '/etc/udev/rules.d/70-persistent-net.rules' cmd += "sed -i '/%s/d' %s\n" % ( address , udev_file_name ) cmd += "sed -i '/%s/d' %s\n" % ( address , '/boot/zipl/active_devices.txt' ) return cmd
handle udev rules file .
43,626
def _set_zfcp_config_files ( self , fcp , target_wwpn , target_lun ) : device = '0.0.%s' % fcp host_config = '/sbin/zfcp_host_configure %s 1' % device disk_config = '/sbin/zfcp_disk_configure ' + '%(device)s %(wwpn)s %(lun)s 1' % { 'device' : device , 'wwpn' : target_wwpn , 'lun' : target_lun } create_config = 'touch /etc/udev/rules.d/51-zfcp-%s.rules' % device check_channel = ( 'out=`cat "/etc/udev/rules.d/51-zfcp-%s.rules" ' '| egrep -i "ccw/%s]online"`\n' % ( device , device ) ) check_channel += 'if [[ ! $out ]]; then\n' check_channel += ( ' echo "ACTION==\\"add\\", SUBSYSTEM==\\"ccw\\", ' 'KERNEL==\\"%(device)s\\", IMPORT{program}=\\"' 'collect %(device)s %%k %(device)s zfcp\\""' '| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules' '\n' % { 'device' : device } ) check_channel += ( ' echo "ACTION==\\"add\\", SUBSYSTEM==\\"drivers\\"' ', KERNEL==\\"zfcp\\", IMPORT{program}=\\"' 'collect %(device)s %%k %(device)s zfcp\\""' '| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules' '\n' % { 'device' : device } ) check_channel += ( ' echo "ACTION==\\"add\\", ' 'ENV{COLLECT_%(device)s}==\\"0\\", ' 'ATTR{[ccw/%(device)s]online}=\\"1\\""' '| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules' '\n' % { 'device' : device } ) check_channel += 'fi\n' check_channel += ( 'echo "ACTION==\\"add\\", KERNEL==\\"rport-*\\", ' 'ATTR{port_name}==\\"%(wwpn)s\\", ' 'SUBSYSTEMS==\\"ccw\\", KERNELS==\\"%(device)s\\",' 'ATTR{[ccw/%(device)s]%(wwpn)s/unit_add}=' '\\"%(lun)s\\""' '| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules' '\n' % { 'device' : device , 'wwpn' : target_wwpn , 'lun' : target_lun } ) return '\n' . join ( ( host_config , 'sleep 2' , disk_config , 'sleep 2' , create_config , check_channel ) )
sles set WWPN and LUN in configuration files
43,627
def _offline_fcp_device ( self , fcp , target_wwpn , target_lun , multipath ) : device = '0.0.%s' % fcp disk_config = '/sbin/zfcp_disk_configure ' + '%(device)s %(wwpn)s %(lun)s 0' % { 'device' : device , 'wwpn' : target_wwpn , 'lun' : target_lun } host_config = '/sbin/zfcp_host_configure %s 0' % device return '\n' . join ( ( disk_config , host_config ) )
sles offline zfcp . sampe to all rhel distro .
43,628
def _delete_vdev_info ( self , vdev ) : vdev = vdev . lower ( ) network_config_file_name = self . _get_network_file ( ) device = self . _get_device_name ( vdev ) cmd = '\n' . join ( ( "num=$(sed -n '/auto %s/=' %s)" % ( device , network_config_file_name ) , "dns=$(awk 'NR==(\"\'$num\'\"+6)&&" "/dns-nameservers/' %s)" % network_config_file_name , "if [[ -n $dns ]]; then" , " sed -i '/auto %s/,+6d' %s" % ( device , network_config_file_name ) , "else" , " sed -i '/auto %s/,+5d' %s" % ( device , network_config_file_name ) , "fi" ) ) return cmd
handle vdev related info .
43,629
def _set_zfcp_config_files ( self , fcp , target_wwpn , target_lun ) : host_config = '/sbin/chzdev zfcp-host %s -e' % fcp device = '0.0.%s' % fcp target = '%s:%s:%s' % ( device , target_wwpn , target_lun ) disk_config = '/sbin/chzdev zfcp-lun %s -e\n' % target return '\n' . join ( ( host_config , disk_config ) )
ubuntu zfcp configuration
43,630
def _offline_fcp_device ( self , fcp , target_wwpn , target_lun , multipath ) : device = '0.0.%s' % fcp target = '%s:%s:%s' % ( device , target_wwpn , target_lun ) disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target host_offline = '/sbin/chzdev zfcp-host %s -d' % fcp offline_dev = 'chccwdev -d %s' % fcp return '\n' . join ( ( disk_offline , host_offline , offline_dev ) )
ubuntu offline zfcp .
43,631
def parse_dist ( self , os_version ) : supported = { 'rhel' : [ 'rhel' , 'redhat' , 'red hat' ] , 'sles' : [ 'suse' , 'sles' ] , 'ubuntu' : [ 'ubuntu' ] } os_version = os_version . lower ( ) for distro , patterns in supported . items ( ) : for i in patterns : if os_version . startswith ( i ) : remain = os_version . split ( i , 2 ) [ 1 ] release = self . _parse_release ( os_version , distro , remain ) return distro , release msg = 'Can not handle os: %s' % os_version raise exception . ZVMException ( msg = msg )
Separate os and version from os_version .
43,632
def getStatus ( rh ) : rh . printSysLog ( "Enter migrateVM.getStatus" ) parms = [ "-T" , rh . userid ] if 'all' in rh . parms : parms . extend ( [ "-k" , "status_target=ALL" ] ) elif 'incoming' in rh . parms : parms . extend ( [ "-k" , "status_target=INCOMING" ] ) elif 'outgoing' in rh . parms : parms . extend ( [ "-k" , "status_target=OUTGOING" ] ) else : parms . extend ( [ "-k" , "status_target=USER " + rh . userid + "" ] ) results = invokeSMCLI ( rh , "VMRELOCATE_Status" , parms ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . updateResults ( results ) if results [ 'rc' ] == 4 and results [ 'rs' ] == 3001 : msg = msgs . msg [ '0419' ] [ 1 ] % ( modId , rh . userid ) rh . printLn ( "ES" , msg ) rh . updateResults ( msgs . msg [ '0419' ] [ 0 ] ) else : rh . printLn ( "N" , results [ 'response' ] ) rh . printSysLog ( "Exit migrateVM.getStatus, rc: " + str ( rh . results [ 'overallRC' ] ) ) return rh . results [ 'overallRC' ]
Get status of a VMRelocate request .
43,633
def parseCmdline ( self , requestData ) : self . printSysLog ( "Enter ReqHandle.parseCmdline" ) if isinstance ( requestData , list ) : self . requestString = ' ' . join ( requestData ) self . request = requestData elif isinstance ( requestData , string_types ) : self . requestString = requestData self . request = shlex . split ( requestData ) else : msg = msgs . msg [ '0012' ] [ 1 ] % ( modId , type ( requestData ) ) self . printLn ( "ES" , msg ) self . updateResults ( msgs . msg [ '0012' ] [ 0 ] ) return self . results self . totalParms = len ( self . request ) if self . totalParms == 0 : msg = msgs . msg [ '0009' ] [ 1 ] % modId self . printLn ( "ES" , msg ) self . updateResults ( msgs . msg [ '0009' ] [ 0 ] ) elif self . totalParms == 1 : self . function = self . request [ 0 ] . upper ( ) if self . function == 'HELP' or self . function == 'VERSION' : pass else : msg = msgs . msg [ '0008' ] [ 1 ] % ( modId , self . function ) self . printLn ( "ES" , msg ) self . updateResults ( msgs . msg [ '0008' ] [ 0 ] ) else : self . function = self . request [ 0 ] . upper ( ) if self . request [ 0 ] == 'HELP' or self . request [ 0 ] == 'VERSION' : pass else : if self . function in ReqHandle . funcHandler : self . funcHandler [ self . function ] [ 2 ] ( self ) else : msg = msgs . msg [ '0007' ] [ 1 ] % ( modId , self . function ) self . printLn ( "ES" , msg ) self . updateResults ( msgs . msg [ '0007' ] [ 0 ] ) self . printSysLog ( "Exit ReqHandle.parseCmdline, rc: " + str ( self . results [ 'overallRC' ] ) ) return self . results
Parse the request command string .
43,634
def printLn ( self , respType , respString ) : if 'E' in respType : respString = '(Error) ' + respString if 'W' in respType : respString = '(Warning) ' + respString if 'S' in respType : self . printSysLog ( respString ) self . results [ 'response' ] = ( self . results [ 'response' ] + respString . splitlines ( ) ) return
Add one or lines of output to the response list .
43,635
def printSysLog ( self , logString ) : if zvmsdklog . LOGGER . getloglevel ( ) <= logging . DEBUG : if self . daemon == '' : self . logger . debug ( self . requestId + ": " + logString ) else : self . daemon . logger . debug ( self . requestId + ": " + logString ) if self . captureLogs is True : self . results [ 'logEntries' ] . append ( self . requestId + ": " + logString ) return
Log one or more lines . Optionally add them to logEntries list .
43,636
def filters ( self ) : params = { } for _filter in self . _filters : params . update ( _filter ) return params
Returns a merged dictionary of filters .
43,637
def json_error_formatter ( body , status , title , environ ) : body = webob . exc . strip_tags ( body ) status_code = int ( status . split ( None , 1 ) [ 0 ] ) error_dict = { 'status' : status_code , 'title' : title , 'detail' : body } return { 'errors' : [ error_dict ] }
A json_formatter for webob exceptions .
43,638
def call_func ( self , req , * args , ** kwargs ) : try : return super ( SdkWsgify , self ) . call_func ( req , * args , ** kwargs ) except webob . exc . HTTPException as exc : msg = ( 'encounter %(error)s error' ) % { 'error' : exc } LOG . debug ( msg ) exc . json_formatter = json_error_formatter code = exc . status_int explanation = six . text_type ( exc ) fault_data = { 'overallRC' : 400 , 'rc' : 400 , 'rs' : code , 'modID' : SDKWSGI_MODID , 'output' : '' , 'errmsg' : explanation } exc . text = six . text_type ( json . dumps ( fault_data ) ) raise exc
Add json_error_formatter to any webob HTTPExceptions .
43,639
def _load_GeoTransform ( self ) : def load_lon ( ) : return arange ( ds . RasterXSize ) * b [ 1 ] + b [ 0 ] def load_lat ( ) : return arange ( ds . RasterYSize ) * b [ 5 ] + b [ 3 ] ds = self . ds b = self . ds . GetGeoTransform ( ) if with_dask : lat = Array ( { ( 'lat' , 0 ) : ( load_lat , ) } , 'lat' , ( self . ds . RasterYSize , ) , shape = ( self . ds . RasterYSize , ) , dtype = float ) lon = Array ( { ( 'lon' , 0 ) : ( load_lon , ) } , 'lon' , ( self . ds . RasterXSize , ) , shape = ( self . ds . RasterXSize , ) , dtype = float ) else : lat = load_lat ( ) lon = load_lon ( ) return Variable ( ( 'lat' , ) , lat ) , Variable ( ( 'lon' , ) , lon )
Calculate latitude and longitude variable calculated from the gdal . Open . GetGeoTransform method
43,640
def psyplot_fname ( env_key = 'PSYPLOTRC' , fname = 'psyplotrc.yml' , if_exists = True ) : cwd = getcwd ( ) full_fname = os . path . join ( cwd , fname ) if os . path . exists ( full_fname ) : return full_fname if env_key in os . environ : path = os . environ [ env_key ] if os . path . exists ( path ) : if os . path . isdir ( path ) : full_fname = os . path . join ( path , fname ) if os . path . exists ( full_fname ) : return full_fname else : return path configdir = get_configdir ( ) if configdir is not None : full_fname = os . path . join ( configdir , fname ) if os . path . exists ( full_fname ) or not if_exists : return full_fname return None
Get the location of the config file .
43,641
def validate_path_exists ( s ) : if s is None : return None if os . path . exists ( s ) : return s else : raise ValueError ( '"%s" should be a path but it does not exist' % s )
If s is a path return s else False
43,642
def validate_dict ( d ) : try : return dict ( d ) except TypeError : d = validate_path_exists ( d ) try : with open ( d ) as f : return dict ( yaml . load ( f ) ) except Exception : raise ValueError ( "Could not convert {} to dictionary!" . format ( d ) )
Validate a dictionary
43,643
def validate_str ( s ) : if not isinstance ( s , six . string_types ) : raise ValueError ( "Did not found string!" ) return six . text_type ( s )
Validate a string
43,644
def validate_stringlist ( s ) : if isinstance ( s , six . string_types ) : return [ six . text_type ( v . strip ( ) ) for v in s . split ( ',' ) if v . strip ( ) ] else : try : return list ( map ( validate_str , s ) ) except TypeError as e : raise ValueError ( e . message )
Validate a list of strings
43,645
def add_base_str ( self , base_str , pattern = '.+' , pattern_base = None , append = True ) : base_str = safe_list ( base_str ) pattern_base = safe_list ( pattern_base or [ ] ) for i , s in enumerate ( base_str ) : if '%(key)s' not in s : base_str [ i ] += '%(key)s' if pattern_base : for i , s in enumerate ( pattern_base ) : if '%(key)s' not in s : pattern_base [ i ] += '%(key)s' else : pattern_base = base_str self . base_str = base_str + self . base_str self . patterns = list ( map ( lambda s : re . compile ( s . replace ( '%(key)s' , '(?P<key>%s)' % pattern ) ) , pattern_base ) ) + self . patterns
Add further base string to this instance
43,646
def iterkeys ( self ) : patterns = self . patterns replace = self . replace seen = set ( ) for key in six . iterkeys ( self . base ) : for pattern in patterns : m = pattern . match ( key ) if m : ret = m . group ( 'key' ) if replace else m . group ( ) if ret not in seen : seen . add ( ret ) yield ret break for key in DictMethods . iterkeys ( self ) : if key not in seen : yield key
Unsorted iterator over keys
43,647
def validate ( self ) : depr = self . _all_deprecated return dict ( ( key , val [ 1 ] ) for key , val in six . iteritems ( self . defaultParams ) if key not in depr )
Dictionary with validation methods as values
43,648
def descriptions ( self ) : return { key : val [ 2 ] for key , val in six . iteritems ( self . defaultParams ) if len ( val ) >= 3 }
The description of each keyword in the rcParams dictionary
43,649
def connect ( self , key , func ) : key = self . _get_depreceated ( key ) [ 0 ] if key is not None : self . _connections [ key ] . append ( func )
Connect a function to the given formatoption
43,650
def disconnect ( self , key = None , func = None ) : if key is None : for key , connections in self . _connections . items ( ) : for conn in connections [ : ] : if func is None or conn is func : connections . remove ( conn ) else : connections = self . _connections [ key ] for conn in connections [ : ] : if func is None or conn is func : connections . remove ( conn )
Disconnect the connections to the an rcParams key
43,651
def keys ( self ) : k = list ( dict . keys ( self ) ) k . sort ( ) return k
Return sorted list of keys .
43,652
def load_from_file ( self , fname = None ) : fname = fname or psyplot_fname ( ) if fname and os . path . exists ( fname ) : with open ( fname ) as f : d = yaml . load ( f ) self . update ( d ) if ( d . get ( 'project.plotters.user' ) and 'project.plotters' in self ) : self [ 'project.plotters' ] . update ( d [ 'project.plotters.user' ] )
Update rcParams from user - defined settings
43,653
def dump ( self , fname = None , overwrite = True , include_keys = None , exclude_keys = [ 'project.plotters' ] , include_descriptions = True , ** kwargs ) : if fname is not None and not overwrite and os . path . exists ( fname ) : raise IOError ( '%s already exists! Set overwrite=True to overwrite it!' % ( fname ) ) if six . PY2 : kwargs . setdefault ( 'encoding' , 'utf-8' ) d = { key : val for key , val in six . iteritems ( self ) if ( include_keys is None or key in include_keys ) and key not in exclude_keys } kwargs [ 'default_flow_style' ] = False if include_descriptions : s = yaml . dump ( d , ** kwargs ) desc = self . descriptions i = 2 header = self . HEADER . splitlines ( ) + [ '' , 'Created with python' , '' ] + sys . version . splitlines ( ) + [ '' , '' ] lines = [ '# ' + l for l in header ] + s . splitlines ( ) for l in lines [ 2 : ] : key = l . split ( ':' ) [ 0 ] if key in desc : lines . insert ( i , '# ' + '\n# ' . join ( desc [ key ] . splitlines ( ) ) ) i += 1 i += 1 s = '\n' . join ( lines ) if fname is None : return s else : with open ( fname , 'w' ) as f : f . write ( s ) else : if fname is None : return yaml . dump ( d , ** kwargs ) with open ( fname , 'w' ) as f : yaml . dump ( d , f , ** kwargs ) return None
Dump this instance to a yaml file
43,654
def _load_plugin_entrypoints ( self ) : from pkg_resources import iter_entry_points def load_plugin ( ep ) : if plugins_env == [ 'no' ] : return False elif ep . module_name in exclude_plugins : return False elif include_plugins and ep . module_name not in include_plugins : return False return True self . _plugins = self . _plugins or [ ] plugins_env = os . getenv ( 'PSYPLOT_PLUGINS' , '' ) . split ( '::' ) include_plugins = [ s [ 4 : ] for s in plugins_env if s . startswith ( 'yes:' ) ] exclude_plugins = [ s [ 3 : ] for s in plugins_env if s . startswith ( 'no:' ) ] logger = logging . getLogger ( __name__ ) for ep in iter_entry_points ( group = 'psyplot' , name = 'plugin' ) : if not load_plugin ( ep ) : logger . debug ( 'Skipping entrypoint %s' , ep ) continue self . _plugins . append ( str ( ep ) ) logger . debug ( 'Loading entrypoint %s' , ep ) yield ep
Load the modules for the psyplot plugins
43,655
def deploy ( project_name ) : request_log = requestlog . RequestLog header_addon = HeaderControl fault_wrapper = FaultWrapper application = handler . SdkHandler ( ) for middleware in ( header_addon , fault_wrapper , request_log , ) : if middleware : application = middleware ( application ) return application
Assemble the middleware pipeline
43,656
def guest_reboot ( self , userid ) : LOG . info ( "Begin to reboot vm %s" , userid ) self . _smtclient . guest_reboot ( userid ) LOG . info ( "Complete reboot vm %s" , userid )
Reboot a guest vm .
43,657
def execute_cmd ( self , userid , cmdStr ) : LOG . debug ( "executing cmd: %s" , cmdStr ) return self . _smtclient . execute_cmd ( userid , cmdStr )
Execute commands on the guest vm .
43,658
def set_hostname ( self , userid , hostname , os_version ) : tmp_path = self . _pathutils . get_guest_temp_path ( userid ) if not os . path . exists ( tmp_path ) : os . makedirs ( tmp_path ) tmp_file = tmp_path + '/hostname.sh' lnxdist = self . _dist_manager . get_linux_dist ( os_version ) ( ) lines = lnxdist . generate_set_hostname_script ( hostname ) with open ( tmp_file , 'w' ) as f : f . writelines ( lines ) requestData = "ChangeVM " + userid + " punchfile " + tmp_file + " --class x" LOG . debug ( "Punch script to guest %s to set hostname" % userid ) try : self . _smtclient . _request ( requestData ) except exception . SDKSMTRequestFailed as err : msg = ( "Failed to punch set_hostname script to userid '%s'. SMT " "error: %s" % ( userid , err . format_message ( ) ) ) LOG . error ( msg ) raise exception . SDKSMTRequestFailed ( err . results , msg ) finally : self . _pathutils . clean_temp_folder ( tmp_path )
Punch a script that used to set the hostname of the guest .
43,659
def cvtToBlocks ( rh , diskSize ) : rh . printSysLog ( "Enter generalUtils.cvtToBlocks" ) blocks = 0 results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , 'errno' : 0 } blocks = diskSize . strip ( ) . upper ( ) lastChar = blocks [ - 1 ] if lastChar == 'G' or lastChar == 'M' : byteSize = blocks [ : - 1 ] if byteSize == '' : msg = msgs . msg [ '0200' ] [ 1 ] % ( modId , blocks ) rh . printLn ( "ES" , msg ) results = msgs . msg [ '0200' ] [ 0 ] else : try : if lastChar == 'M' : blocks = ( float ( byteSize ) * 1024 * 1024 ) / 512 elif lastChar == 'G' : blocks = ( float ( byteSize ) * 1024 * 1024 * 1024 ) / 512 blocks = str ( int ( math . ceil ( blocks ) ) ) except Exception : msg = msgs . msg [ '0201' ] [ 1 ] % ( modId , byteSize ) rh . printLn ( "ES" , msg ) results = msgs . msg [ '0201' ] [ 0 ] elif blocks . strip ( '1234567890' ) : msg = msgs . msg [ '0202' ] [ 1 ] % ( modId , blocks ) rh . printLn ( "ES" , msg ) results = msgs . msg [ '0202' ] [ 0 ] rh . printSysLog ( "Exit generalUtils.cvtToBlocks, rc: " + str ( results [ 'overallRC' ] ) ) return results , blocks
Convert a disk storage value to a number of blocks .
43,660
def cvtToMag ( rh , size ) : rh . printSysLog ( "Enter generalUtils.cvtToMag" ) mSize = '' size = size / ( 1024 * 1024 ) if size > ( 1024 * 5 ) : size = size / 1024 mSize = "%.1fG" % size else : mSize = "%.1fM" % size rh . printSysLog ( "Exit generalUtils.cvtToMag, magSize: " + mSize ) return mSize
Convert a size value to a number with a magnitude appended .
43,661
def getSizeFromPage ( rh , page ) : rh . printSysLog ( "Enter generalUtils.getSizeFromPage" ) bSize = float ( page ) * 4096 mSize = cvtToMag ( rh , bSize ) rh . printSysLog ( "Exit generalUtils.getSizeFromPage, magSize: " + mSize ) return mSize
Convert a size value from page to a number with a magnitude appended .
43,662
def validate ( self ) : if not self . api_token or not self . api_token_secret : raise ImproperlyConfigured ( "'api_token' and 'api_token_secret' are required for authentication." ) if self . response_type not in [ "json" , "pson" , "xml" , "debug" , None ] : raise ImproperlyConfigured ( "'%s' is an invalid response_type" % self . response_type )
Perform validation check on properties .
43,663
def R ( X , destination , a1 , a2 , b ) : a = ( X [ a1 ] + X [ a2 ] ) & 0xffffffff X [ destination ] ^= ( ( a << b ) | ( a >> ( 32 - b ) ) )
A single Salsa20 row operation
43,664
def fileChunkIter ( file_object , file_chunk_size = 65536 ) : while True : chunk = file_object . read ( file_chunk_size ) if chunk : yield chunk else : break
Return an iterator to a file - like object that yields fixed size chunks
43,665
def read_objfile ( fname ) : verts = defaultdict ( list ) obj_props = [ ] with open ( fname ) as f : lines = f . read ( ) . splitlines ( ) for line in lines : if line : split_line = line . strip ( ) . split ( ' ' , 1 ) if len ( split_line ) < 2 : continue prefix , value = split_line [ 0 ] , split_line [ 1 ] if prefix == 'o' : obj_props . append ( { } ) obj = obj_props [ - 1 ] obj [ 'f' ] = [ ] obj [ prefix ] = value elif prefix == 'v' and len ( obj_props ) < 1 : obj_props . append ( { } ) obj = obj_props [ - 1 ] obj [ 'f' ] = [ ] obj [ 'o' ] = fname if obj_props : if prefix [ 0 ] == 'v' : verts [ prefix ] . append ( [ float ( val ) for val in value . split ( ' ' ) ] ) elif prefix == 'f' : obj [ prefix ] . append ( parse_mixed_delim_str ( value ) ) else : obj [ prefix ] = value verts = { key : np . array ( value ) for key , value in iteritems ( verts ) } for obj in obj_props : obj [ 'f' ] = tuple ( np . array ( verts ) if verts [ 0 ] else tuple ( ) for verts in zip ( * obj [ 'f' ] ) ) for idx , vertname in enumerate ( [ 'v' , 'vt' , 'vn' ] ) : if vertname in verts : obj [ vertname ] = verts [ vertname ] [ obj [ 'f' ] [ idx ] . flatten ( ) - 1 , : ] else : obj [ vertname ] = tuple ( ) del obj [ 'f' ] geoms = { obj [ 'o' ] : obj for obj in obj_props } return geoms
Takes . obj filename and returns dict of object properties for each object in file .
43,666
def disableEnableDisk ( rh , userid , vaddr , option ) : rh . printSysLog ( "Enter vmUtils.disableEnableDisk, userid: " + userid + " addr: " + vaddr + " option: " + option ) results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , 'response' : '' } for secs in [ 0.1 , 0.4 , 1 , 1.5 , 3 , 7 , 15 , 32 , 30 , 30 , 60 , 60 , 60 , 60 , 60 ] : strCmd = "sudo /sbin/chccwdev " + option + " " + vaddr + " 2>&1" results = execCmdThruIUCV ( rh , userid , strCmd ) if results [ 'overallRC' ] == 0 : break elif ( results [ 'overallRC' ] == 2 and results [ 'rc' ] == 8 and results [ 'rs' ] == 1 and option == '-d' ) : results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , 'response' : '' } break time . sleep ( secs ) rh . printSysLog ( "Exit vmUtils.disableEnableDisk, rc: " + str ( results [ 'overallRC' ] ) ) return results
Disable or enable a disk .
43,667
def getPerfInfo ( rh , useridlist ) : rh . printSysLog ( "Enter vmUtils.getPerfInfo, userid: " + useridlist ) parms = [ "-T" , rh . userid , "-c" , "1" ] results = invokeSMCLI ( rh , "Image_Performance_Query" , parms ) if results [ 'overallRC' ] != 0 : rh . printLn ( "ES" , results [ 'response' ] ) rh . printSysLog ( "Exit vmUtils.getPerfInfo, rc: " + str ( results [ 'overallRC' ] ) ) return results lines = results [ 'response' ] . split ( "\n" ) usedTime = 0 totalCpu = 0 totalMem = 0 usedMem = 0 try : for line in lines : if "Used CPU time:" in line : usedTime = line . split ( ) [ 3 ] . strip ( '"' ) usedTime = int ( usedTime ) / 1000000 if "Guest CPUs:" in line : totalCpu = line . split ( ) [ 2 ] . strip ( '"' ) if "Max memory:" in line : totalMem = line . split ( ) [ 2 ] . strip ( '"' ) totalMem = int ( totalMem ) / 1024 if "Used memory:" in line : usedMem = line . split ( ) [ 2 ] . strip ( '"' ) usedMem = int ( usedMem ) / 1024 except Exception as e : msg = msgs . msg [ '0412' ] [ 1 ] % ( modId , type ( e ) . __name__ , str ( e ) , results [ 'response' ] ) rh . printLn ( "ES" , msg ) results [ 'overallRC' ] = 4 results [ 'rc' ] = 4 results [ 'rs' ] = 412 if results [ 'overallRC' ] == 0 : memstr = "Total Memory: %iM\n" % totalMem usedmemstr = "Used Memory: %iM\n" % usedMem procstr = "Processors: %s\n" % totalCpu timestr = "CPU Used Time: %i sec\n" % usedTime results [ 'response' ] = memstr + usedmemstr + procstr + timestr rh . printSysLog ( "Exit vmUtils.getPerfInfo, rc: " + str ( results [ 'rc' ] ) ) return results
Get the performance information for a userid
43,668
def isLoggedOn ( rh , userid ) : rh . printSysLog ( "Enter vmUtils.isLoggedOn, userid: " + userid ) results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , } cmd = [ "sudo" , "/sbin/vmcp" , "query" , "user" , userid ] strCmd = ' ' . join ( cmd ) rh . printSysLog ( "Invoking: " + strCmd ) try : subprocess . check_output ( cmd , close_fds = True , stderr = subprocess . STDOUT ) except CalledProcessError as e : search_pattern = '(^HCP\w\w\w045E|^HCP\w\w\w361E)' . encode ( ) match = re . search ( search_pattern , e . output ) if match : results [ 'rs' ] = 1 else : rh . printLn ( "ES" , msgs . msg [ '0415' ] [ 1 ] % ( modId , strCmd , e . returncode , e . output ) ) results = msgs . msg [ '0415' ] [ 0 ] results [ 'rs' ] = e . returncode except Exception as e : results = msgs . msg [ '0421' ] [ 0 ] rh . printLn ( "ES" , msgs . msg [ '0421' ] [ 1 ] % ( modId , strCmd , type ( e ) . __name__ , str ( e ) ) ) rh . printSysLog ( "Exit vmUtils.isLoggedOn, overallRC: " + str ( results [ 'overallRC' ] ) + " rc: " + str ( results [ 'rc' ] ) + " rs: " + str ( results [ 'rs' ] ) ) return results
Determine whether a virtual machine is logged on .
43,669
def waitForOSState ( rh , userid , desiredState , maxQueries = 90 , sleepSecs = 5 ) : rh . printSysLog ( "Enter vmUtils.waitForOSState, userid: " + userid + " state: " + desiredState + " maxWait: " + str ( maxQueries ) + " sleepSecs: " + str ( sleepSecs ) ) results = { } strCmd = "echo 'ping'" stateFnd = False for i in range ( 1 , maxQueries + 1 ) : results = execCmdThruIUCV ( rh , rh . userid , strCmd ) if results [ 'overallRC' ] == 0 : if desiredState == 'up' : stateFnd = True break else : if desiredState == 'down' : stateFnd = True break if i < maxQueries : time . sleep ( sleepSecs ) if stateFnd is True : results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , } else : maxWait = maxQueries * sleepSecs rh . printLn ( "ES" , msgs . msg [ '0413' ] [ 1 ] % ( modId , userid , desiredState , maxWait ) ) results = msgs . msg [ '0413' ] [ 0 ] rh . printSysLog ( "Exit vmUtils.waitForOSState, rc: " + str ( results [ 'overallRC' ] ) ) return results
Wait for the virtual OS to go into the indicated state .
43,670
def waitForVMState ( rh , userid , desiredState , maxQueries = 90 , sleepSecs = 5 ) : rh . printSysLog ( "Enter vmUtils.waitForVMState, userid: " + userid + " state: " + desiredState + " maxWait: " + str ( maxQueries ) + " sleepSecs: " + str ( sleepSecs ) ) results = { } cmd = [ "sudo" , "/sbin/vmcp" , "query" , "user" , userid ] strCmd = " " . join ( cmd ) stateFnd = False for i in range ( 1 , maxQueries + 1 ) : rh . printSysLog ( "Invoking: " + strCmd ) try : out = subprocess . check_output ( cmd , close_fds = True , stderr = subprocess . STDOUT ) if isinstance ( out , bytes ) : out = bytes . decode ( out ) if desiredState == 'on' : stateFnd = True break except CalledProcessError as e : match = re . search ( '(^HCP\w\w\w045E|^HCP\w\w\w361E)' , e . output ) if match : if desiredState == 'off' : stateFnd = True break else : out = e . output rh . printLn ( "ES" , msgs . msg [ '0415' ] [ 1 ] % ( modId , strCmd , e . returncode , out ) ) results = msgs . msg [ '0415' ] [ 0 ] results [ 'rs' ] = e . returncode break except Exception as e : rh . printLn ( "ES" , msgs . msg [ '0421' ] [ 1 ] % ( modId , strCmd , type ( e ) . __name__ , str ( e ) ) ) results = msgs . msg [ '0421' ] [ 0 ] if i < maxQueries : time . sleep ( sleepSecs ) if stateFnd is True : results = { 'overallRC' : 0 , 'rc' : 0 , 'rs' : 0 , } else : maxWait = maxQueries * sleepSecs rh . printLn ( "ES" , msgs . msg [ '0414' ] [ 1 ] % ( modId , userid , desiredState , maxWait ) ) results = msgs . msg [ '0414' ] [ 0 ] rh . printSysLog ( "Exit vmUtils.waitForVMState, rc: " + str ( results [ 'overallRC' ] ) ) return results
Wait for the virtual machine to go into the indicated state .
43,671
def stream ( input , encoding = None , errors = 'strict' ) : input = ( i for i in input if i ) if encoding : input = iterencode ( input , encoding , errors = errors ) return input
Safely iterate a template generator ignoring None values and optionally stream encoding . Used internally by cinje . flatten this allows for easy use of a template generator as a WSGI body .
43,672
def prepare ( self ) : self . scope = 0 self . mapping = deque ( [ 0 ] ) self . _handler = [ i ( ) for i in sorted ( self . handlers , key = lambda handler : handler . priority ) ]
Prepare the ordered list of transformers and reset context state to initial .
43,673
def classify ( self , line ) : for handler in self . _handler : if handler . match ( self , line ) : return handler
Identify the correct handler for a given line of input .
43,674
def red ( numbers ) : line = 0 deltas = [ ] for value in numbers : deltas . append ( value - line ) line = value return b64encode ( compress ( b'' . join ( chr ( i ) . encode ( 'latin1' ) for i in deltas ) ) ) . decode ( 'latin1' )
Encode the deltas to reduce entropy .
43,675
def match ( self , context , line ) : return line . kind == 'code' and line . partitioned [ 0 ] in self . _both
Match code lines prefixed with a variety of keywords .
43,676
def get_direct_fields_from_model ( model_class ) : direct_fields = [ ] all_fields_names = _get_all_field_names ( model_class ) for field_name in all_fields_names : field , model , direct , m2m = _get_field_by_name ( model_class , field_name ) if direct and not m2m and not _get_remote_field ( field ) : direct_fields += [ field ] return direct_fields
Direct not m2m not FK
43,677
def get_fields ( model_class , field_name = '' , path = '' ) : fields = get_direct_fields_from_model ( model_class ) app_label = model_class . _meta . app_label if field_name != '' : field , model , direct , m2m = _get_field_by_name ( model_class , field_name ) path += field_name path += '__' if direct : try : new_model = _get_remote_field ( field ) . parent_model except AttributeError : new_model = _get_remote_field ( field ) . model else : new_model = field . related_model fields = get_direct_fields_from_model ( new_model ) app_label = new_model . _meta . app_label return { 'fields' : fields , 'path' : path , 'app_label' : app_label , }
Get fields and meta data from a model
43,678
def get_related_fields ( model_class , field_name , path = "" ) : if field_name : field , model , direct , m2m = _get_field_by_name ( model_class , field_name ) if direct : try : new_model = _get_remote_field ( field ) . parent_model ( ) except AttributeError : new_model = _get_remote_field ( field ) . model else : if hasattr ( field , 'related_model' ) : new_model = field . related_model else : new_model = field . model ( ) path += field_name path += '__' else : new_model = model_class new_fields = get_relation_fields_from_model ( new_model ) model_ct = ContentType . objects . get_for_model ( new_model ) return ( new_fields , model_ct , path )
Get fields for a given model
43,679
def flush_template ( context , declaration = None , reconstruct = True ) : if declaration is None : declaration = Line ( 0 , '' ) if { 'text' , 'dirty' } . issubset ( context . flag ) : yield declaration . clone ( line = 'yield "".join(_buffer)' ) context . flag . remove ( 'text' ) context . flag . remove ( 'dirty' ) if reconstruct : for i in ensure_buffer ( context ) : yield i if declaration . stripped == 'yield' : yield declaration
Emit the code needed to flush the buffer . Will only emit the yield and clear if the buffer is known to be dirty .
43,680
def _can_change_or_view ( model , user ) : model_name = model . _meta . model_name app_label = model . _meta . app_label can_change = user . has_perm ( app_label + '.change_' + model_name ) can_view = user . has_perm ( app_label + '.view_' + model_name ) return can_change or can_view
Return True iff user has either change or view permission for model .
43,681
def report_to_list ( queryset , display_fields , user ) : model_class = queryset . model objects = queryset message = "" if not _can_change_or_view ( model_class , user ) : return [ ] , 'Permission Denied' new_display_fields = [ ] for display_field in display_fields : field_list = display_field . split ( '__' ) field = field_list [ - 1 ] path = '__' . join ( field_list [ : - 1 ] ) if path : path += '__' df = DisplayField ( path , field ) new_display_fields . append ( df ) display_fields = new_display_fields display_field_paths = [ ] for i , display_field in enumerate ( display_fields ) : model = get_model_from_path_string ( model_class , display_field . path ) if not model or _can_change_or_view ( model , user ) : display_field_key = display_field . path + display_field . field display_field_paths . append ( display_field_key ) else : message += 'Error: Permission denied on access to {0}.' . format ( display_field . name ) values_list = objects . values_list ( * display_field_paths ) values_and_properties_list = [ list ( row ) for row in values_list ] return values_and_properties_list , message
Create list from a report with all data filtering .
43,682
def list_to_workbook ( data , title = 'report' , header = None , widths = None ) : wb = Workbook ( ) title = re . sub ( r'\W+' , '' , title ) [ : 30 ] if isinstance ( data , dict ) : i = 0 for sheet_name , sheet_data in data . items ( ) : if i > 0 : wb . create_sheet ( ) ws = wb . worksheets [ i ] build_sheet ( sheet_data , ws , sheet_name = sheet_name , header = header ) i += 1 else : ws = wb . worksheets [ 0 ] build_sheet ( data , ws , header = header , widths = widths ) return wb
Create just a openpxl workbook from a list of data
43,683
def build_xlsx_response ( wb , title = "report" ) : title = generate_filename ( title , '.xlsx' ) myfile = BytesIO ( ) myfile . write ( save_virtual_workbook ( wb ) ) response = HttpResponse ( myfile . getvalue ( ) , content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response [ 'Content-Disposition' ] = 'attachment; filename=%s' % title response [ 'Content-Length' ] = myfile . tell ( ) return response
Take a workbook and return a xlsx file response
43,684
def list_to_csv_response ( data , title = 'report' , header = None , widths = None ) : response = HttpResponse ( content_type = "text/csv; charset=UTF-8" ) cw = csv . writer ( response ) for row in chain ( [ header ] if header else [ ] , data ) : cw . writerow ( [ force_text ( s ) . encode ( response . charset ) for s in row ] ) return response
Make 2D list into a csv response for download data .
43,685
def gather ( input ) : try : line = input . next ( ) except StopIteration : return lead = True buffer = [ ] while line . kind == 'text' : value = line . line . rstrip ( ) . rstrip ( '\\' ) + ( '' if line . continued else '\n' ) if lead and line . stripped : yield Line ( line . number , value ) lead = False elif not lead : if line . stripped : for buf in buffer : yield buf buffer = [ ] yield Line ( line . number , value ) else : buffer . append ( Line ( line . number , value ) ) try : line = input . next ( ) except StopIteration : line = None break if line : input . push ( line )
Collect contiguous lines of text preserving line numbers .
43,686
def process ( self , context , lines ) : handler = None for line in lines : for chunk in chunk_ ( line ) : if 'strip' in context . flag : chunk . line = chunk . stripped if not chunk . line : continue if not handler or handler [ 0 ] != chunk . kind : if handler : try : result = next ( handler [ 1 ] ) except StopIteration : result = None if result : yield result handler = getattr ( self , 'process_' + chunk . kind , self . process_generic ) ( chunk . kind , context ) handler = ( chunk . kind , handler ) try : next ( handler [ 1 ] ) except StopIteration : return result = handler [ 1 ] . send ( chunk ) if result : yield result if __debug__ : handler = ( None , handler [ 1 ] ) if handler : try : result = next ( handler [ 1 ] ) except StopIteration : return if result : yield result
Chop up individual lines into static and dynamic parts . Applies light optimizations such as empty chunk removal and calls out to other methods to process different chunk types . The processor protocol here requires the method to accept values by yielding resulting lines while accepting sent chunks . Deferral of multiple chunks is possible by yielding None . The processor will be sent None to be given a chance to yield a final line and perform any clean - up .
43,687
def process_text ( self , kind , context ) : result = None while True : chunk = yield None if chunk is None : if result : yield result . clone ( line = repr ( result . line ) ) return if not result : result = chunk continue result . line += chunk . line
Combine multiple lines of bare text and emit as a Python string literal .
43,688
def process_generic ( self , kind , context ) : result = None while True : chunk = yield result if chunk is None : return result = chunk . clone ( line = '_' + kind + '(' + chunk . line + ')' )
Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name .
43,689
def process_format ( self , kind , context ) : result = None while True : chunk = yield result if chunk is None : return split = - 1 line = chunk . line try : ast . parse ( line ) except SyntaxError as e : split = line . rfind ( ' ' , 0 , e . offset ) result = chunk . clone ( line = '_bless(' + line [ : split ] . rstrip ( ) + ').format(' + line [ split : ] . lstrip ( ) + ')' )
Handle transforming format string + arguments into Python code .
43,690
def copy ( self , * args , ** kwargs ) : self . make_body_seekable ( ) env = self . environ . copy ( ) new_req = self . __class__ ( env , * args , ** kwargs ) new_req . copy_body ( ) new_req . identity = self . identity return new_req
Copy the request and environment object .
43,691
def add_source ( self , source ) : geocode_service = self . _get_service_by_name ( source [ 0 ] ) self . _sources . append ( geocode_service ( ** source [ 1 ] ) )
Add a geocoding service to this instance .
43,692
def remove_source ( self , source ) : geocode_service = self . _get_service_by_name ( source [ 0 ] ) self . _sources . remove ( geocode_service ( ** source [ 1 ] ) )
Remove a geocoding service from this instance .
43,693
def set_sources ( self , sources ) : if len ( sources ) == 0 : raise Exception ( 'Must declare at least one source for a geocoder' ) self . _sources = [ ] for source in sources : self . add_source ( source )
Creates GeocodeServiceConfigs from each str source
43,694
def _apply_param_actions ( self , params , schema_params ) : for key , val in schema_params . items ( ) : if key not in params : continue if isinstance ( val , dict ) : self . _apply_param_actions ( params [ key ] , schema_params [ key ] ) elif isinstance ( val , ResourceId ) : resource_id = val params [ key ] = str ( params [ key ] ) resource_id . action ( params , schema_params , key , resource_id , self . state , self . options ) else : logger . error ( "Invalid value in schema params: %r. schema_params: %r and params: %r" , val , schema_params , params )
Traverse a schema and perform the updates it describes to params .
43,695
def snpeff ( self ) : tstart = datetime . now ( ) se = snpeff . Snpeff ( self . vcf_file ) std = se . run ( ) tend = datetime . now ( ) execution_time = tend - tstart
Annotation with snpEff
43,696
def cli ( ctx , settings , app ) : if app is None and settings is None : print ( 'Either --app or --settings must be supplied' ) ctx . ensure_object ( dict ) ctx . obj [ 'app' ] = app ctx . obj [ 'settings' ] = settings
Manage Morp application services
43,697
def _settings_checker ( self , required_settings = None , accept_none = True ) : if required_settings is not None : for keyname in required_settings : if keyname not in self . _settings : return keyname if accept_none is False and self . _settings [ keyname ] is None : return keyname return True
Take a list of required _settings dictionary keys and make sure they are set . This can be added to a custom constructor in a subclass and tested to see if it returns True .
43,698
def _get_response ( self , endpoint , query , is_post = False ) : timeout_secs = self . _settings . get ( 'timeout' , 10 ) headers = self . _settings . get ( 'request_headers' , { } ) try : if is_post : response = requests . post ( endpoint , data = query , headers = headers , timeout = timeout_secs ) else : response = requests . get ( endpoint , params = query , headers = headers , timeout = timeout_secs ) except requests . exceptions . Timeout as e : raise Exception ( 'API request timed out after %s seconds.' % timeout_secs ) except Exception as e : raise e if response . status_code != 200 : raise Exception ( 'Received status code %s from %s. Content is:\n%s' % ( response . status_code , self . get_service_name ( ) , response . text ) ) return response
Returns response or False in event of failure
43,699
def _get_json_obj ( self , endpoint , query , is_post = False ) : response = self . _get_response ( endpoint , query , is_post = is_post ) content = response . text try : return loads ( content ) except ValueError : raise Exception ( 'Could not decode content to JSON:\n%s' % self . __class__ . __name__ , content )
Return False if connection could not be made . Otherwise return a response object from JSON .