idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
233,700
def generate_password ( ) : if sys . version_info > ( 3 , 6 ) : import secrets # pylint: disable=import-error alphabet = string . ascii_letters + string . digits password = '' . join ( secrets . choice ( alphabet ) for i in range ( 20 ) ) special = '' . join ( secrets . choice ( string . punctuation ) for i in range ( 3 ) ) return password + special else : raise ImportError ( "Generating passwords require python 3.6 or higher" )
Returns a 23 character random string with 3 special characters at the end
111
13
233,701
def cli ( env ) : mgr = SoftLayer . EventLogManager ( env . client ) event_log_types = mgr . get_event_log_types ( ) table = formatting . Table ( COLUMNS ) for event_log_type in event_log_types : table . add_row ( [ event_log_type ] ) env . fout ( table )
Get Event Log Types
83
4
233,702
def _get_extra_price_id ( items , key_name , hourly , location ) : for item in items : if utils . lookup ( item , 'keyName' ) != key_name : continue for price in item [ 'prices' ] : if not _matches_billing ( price , hourly ) : continue if not _matches_location ( price , location ) : continue return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price for extra option, '%s'" % key_name )
Returns a price id attached to item with the given key_name .
119
14
233,703
def _get_default_price_id ( items , option , hourly , location ) : for item in items : if utils . lookup ( item , 'itemCategory' , 'categoryCode' ) != option : continue for price in item [ 'prices' ] : if all ( [ float ( price . get ( 'hourlyRecurringFee' , 0 ) ) == 0.0 , float ( price . get ( 'recurringFee' , 0 ) ) == 0.0 , _matches_billing ( price , hourly ) , _matches_location ( price , location ) ] ) : return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price for '%s' option" % option )
Returns a free price id given an option .
161
9
233,704
def _get_bandwidth_price_id ( items , hourly = True , no_public = False , location = None ) : # Prefer pay-for-use data transfer with hourly for item in items : capacity = float ( item . get ( 'capacity' , 0 ) ) # Hourly and private only do pay-as-you-go bandwidth if any ( [ utils . lookup ( item , 'itemCategory' , 'categoryCode' ) != 'bandwidth' , ( hourly or no_public ) and capacity != 0.0 , not ( hourly or no_public ) and capacity == 0.0 ] ) : continue for price in item [ 'prices' ] : if not _matches_billing ( price , hourly ) : continue if not _matches_location ( price , location ) : continue return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price for bandwidth option" )
Choose a valid price id for bandwidth .
200
8
233,705
def _get_os_price_id ( items , os , location ) : for item in items : if any ( [ utils . lookup ( item , 'itemCategory' , 'categoryCode' ) != 'os' , utils . lookup ( item , 'softwareDescription' , 'referenceCode' ) != os ] ) : continue for price in item [ 'prices' ] : if not _matches_location ( price , location ) : continue return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price for os: '%s'" % os )
Returns the price id matching .
127
6
233,706
def _get_port_speed_price_id ( items , port_speed , no_public , location ) : for item in items : if utils . lookup ( item , 'itemCategory' , 'categoryCode' ) != 'port_speed' : continue # Check for correct capacity and if the item matches private only if any ( [ int ( utils . lookup ( item , 'capacity' ) ) != port_speed , _is_private_port_speed_item ( item ) != no_public , not _is_bonded ( item ) ] ) : continue for price in item [ 'prices' ] : if not _matches_location ( price , location ) : continue return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price for port speed: '%s'" % port_speed )
Choose a valid price id for port speed .
182
9
233,707
def _matches_location ( price , location ) : # the price has no location restriction if not price . get ( 'locationGroupId' ) : return True # Check to see if any of the location groups match the location group # of this price object for group in location [ 'location' ] [ 'location' ] [ 'priceGroups' ] : if group [ 'id' ] == price [ 'locationGroupId' ] : return True return False
Return True if the price object matches the location .
96
10
233,708
def _get_location ( package , location ) : for region in package [ 'regions' ] : if region [ 'location' ] [ 'location' ] [ 'name' ] == location : return region raise SoftLayer . SoftLayerError ( "Could not find valid location for: '%s'" % location )
Get the longer key with a short location name .
67
10
233,709
def _get_preset_id ( package , size ) : for preset in package [ 'activePresets' ] + package [ 'accountRestrictedActivePresets' ] : if preset [ 'keyName' ] == size or preset [ 'id' ] == size : return preset [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid size for: '%s'" % size )
Get the preset id given the keyName of the preset .
88
12
233,710
def cancel_hardware ( self , hardware_id , reason = 'unneeded' , comment = '' , immediate = False ) : # Get cancel reason reasons = self . get_cancellation_reasons ( ) cancel_reason = reasons . get ( reason , reasons [ 'unneeded' ] ) ticket_mgr = SoftLayer . TicketManager ( self . client ) mask = 'mask[id, hourlyBillingFlag, billingItem[id], openCancellationTicket[id], activeTransaction]' hw_billing = self . get_hardware ( hardware_id , mask = mask ) if 'activeTransaction' in hw_billing : raise SoftLayer . SoftLayerError ( "Unable to cancel hardware with running transaction" ) if 'billingItem' not in hw_billing : raise SoftLayer . SoftLayerError ( "Ticket #%s already exists for this server" % hw_billing [ 'openCancellationTicket' ] [ 'id' ] ) billing_id = hw_billing [ 'billingItem' ] [ 'id' ] if immediate and not hw_billing [ 'hourlyBillingFlag' ] : LOGGER . warning ( "Immediate cancelation of montly servers is not guaranteed." "Please check the cancelation ticket for updates." ) result = self . client . call ( 'Billing_Item' , 'cancelItem' , False , False , cancel_reason , comment , id = billing_id ) hw_billing = self . get_hardware ( hardware_id , mask = mask ) ticket_number = hw_billing [ 'openCancellationTicket' ] [ 'id' ] cancel_message = "Please reclaim this server ASAP, it is no longer needed. Thankyou." ticket_mgr . update_ticket ( ticket_number , cancel_message ) LOGGER . info ( "Cancelation ticket #%s has been updated requesting immediate reclaim" , ticket_number ) else : result = self . client . call ( 'Billing_Item' , 'cancelItem' , immediate , False , cancel_reason , comment , id = billing_id ) hw_billing = self . get_hardware ( hardware_id , mask = mask ) ticket_number = hw_billing [ 'openCancellationTicket' ] [ 'id' ] LOGGER . info ( "Cancelation ticket #%s has been created" , ticket_number ) return result
Cancels the specified dedicated server .
542
8
233,711
def get_hardware ( self , hardware_id , * * kwargs ) : if 'mask' not in kwargs : kwargs [ 'mask' ] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'provisionDate,' 'hardwareStatus,' 'processorPhysicalCoreAmount,' 'memoryCapacity,' 'notes,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'primaryIpAddress,' 'networkManagementIpAddress,' 'userData,' 'datacenter,' '''networkComponents[id, status, speed, maxSpeed, name, ipmiMacAddress, ipmiIpAddress, macAddress, primaryIpAddress, port, primarySubnet[id, netmask, broadcastAddress, networkIdentifier, gateway]],''' 'hardwareChassis[id,name],' 'activeTransaction[id, transactionStatus[friendlyName,name]],' '''operatingSystem[ softwareLicense[softwareDescription[manufacturer, name, version, referenceCode]], passwords[username,password]],''' '''softwareComponents[ softwareLicense[softwareDescription[manufacturer, name, version, referenceCode]], passwords[username,password]],''' 'billingItem[' 'id,nextInvoiceTotalRecurringAmount,' 'children[nextInvoiceTotalRecurringAmount],' 'orderItem.order.userRecord[username]' '],' 'hourlyBillingFlag,' 'tagReferences[id,tag[name,id]],' 'networkVlans[id,vlanNumber,networkSpace],' 'remoteManagementAccounts[username,password]' ) return self . hardware . getObject ( id = hardware_id , * * kwargs )
Get details about a hardware device .
376
7
233,712
def reload ( self , hardware_id , post_uri = None , ssh_keys = None ) : config = { } if post_uri : config [ 'customProvisionScriptUri' ] = post_uri if ssh_keys : config [ 'sshKeyIds' ] = [ key_id for key_id in ssh_keys ] return self . hardware . reloadOperatingSystem ( 'FORCE' , config , id = hardware_id )
Perform an OS reload of a server with its current configuration .
97
13
233,713
def change_port_speed ( self , hardware_id , public , speed ) : if public : return self . client . call ( 'Hardware_Server' , 'setPublicNetworkInterfaceSpeed' , speed , id = hardware_id ) else : return self . client . call ( 'Hardware_Server' , 'setPrivateNetworkInterfaceSpeed' , speed , id = hardware_id )
Allows you to change the port speed of a server s NICs .
81
14
233,714
def place_order ( self , * * kwargs ) : create_options = self . _generate_create_dict ( * * kwargs ) return self . client [ 'Product_Order' ] . placeOrder ( create_options )
Places an order for a piece of hardware .
53
10
233,715
def verify_order ( self , * * kwargs ) : create_options = self . _generate_create_dict ( * * kwargs ) return self . client [ 'Product_Order' ] . verifyOrder ( create_options )
Verifies an order for a piece of hardware .
53
10
233,716
def get_create_options ( self ) : package = self . _get_package ( ) # Locations locations = [ ] for region in package [ 'regions' ] : locations . append ( { 'name' : region [ 'location' ] [ 'location' ] [ 'longName' ] , 'key' : region [ 'location' ] [ 'location' ] [ 'name' ] , } ) # Sizes sizes = [ ] for preset in package [ 'activePresets' ] + package [ 'accountRestrictedActivePresets' ] : sizes . append ( { 'name' : preset [ 'description' ] , 'key' : preset [ 'keyName' ] } ) # Operating systems operating_systems = [ ] for item in package [ 'items' ] : if item [ 'itemCategory' ] [ 'categoryCode' ] == 'os' : operating_systems . append ( { 'name' : item [ 'softwareDescription' ] [ 'longDescription' ] , 'key' : item [ 'softwareDescription' ] [ 'referenceCode' ] , } ) # Port speeds port_speeds = [ ] for item in package [ 'items' ] : if all ( [ item [ 'itemCategory' ] [ 'categoryCode' ] == 'port_speed' , # Hide private options not _is_private_port_speed_item ( item ) , # Hide unbonded options _is_bonded ( item ) ] ) : port_speeds . append ( { 'name' : item [ 'description' ] , 'key' : item [ 'capacity' ] , } ) # Extras extras = [ ] for item in package [ 'items' ] : if item [ 'itemCategory' ] [ 'categoryCode' ] in EXTRA_CATEGORIES : extras . append ( { 'name' : item [ 'description' ] , 'key' : item [ 'keyName' ] } ) return { 'locations' : locations , 'sizes' : sizes , 'operating_systems' : operating_systems , 'port_speeds' : port_speeds , 'extras' : extras , }
Returns valid options for ordering hardware .
463
7
233,717
def _get_package ( self ) : mask = ''' items[ keyName, capacity, description, attributes[id,attributeTypeKeyName], itemCategory[id,categoryCode], softwareDescription[id,referenceCode,longDescription], prices ], activePresets, accountRestrictedActivePresets, regions[location[location[priceGroups]]] ''' package_keyname = 'BARE_METAL_SERVER' package = self . ordering_manager . get_package_by_key ( package_keyname , mask = mask ) return package
Get the package related to simple hardware ordering .
120
9
233,718
def _generate_create_dict ( self , size = None , hostname = None , domain = None , location = None , os = None , port_speed = None , ssh_keys = None , post_uri = None , hourly = True , no_public = False , extras = None ) : extras = extras or [ ] package = self . _get_package ( ) location = _get_location ( package , location ) prices = [ ] for category in [ 'pri_ip_addresses' , 'vpn_management' , 'remote_management' ] : prices . append ( _get_default_price_id ( package [ 'items' ] , option = category , hourly = hourly , location = location ) ) prices . append ( _get_os_price_id ( package [ 'items' ] , os , location = location ) ) prices . append ( _get_bandwidth_price_id ( package [ 'items' ] , hourly = hourly , no_public = no_public , location = location ) ) prices . append ( _get_port_speed_price_id ( package [ 'items' ] , port_speed , no_public , location = location ) ) for extra in extras : prices . append ( _get_extra_price_id ( package [ 'items' ] , extra , hourly , location = location ) ) hardware = { 'hostname' : hostname , 'domain' : domain , } order = { 'hardware' : [ hardware ] , 'location' : location [ 'keyname' ] , 'prices' : [ { 'id' : price } for price in prices ] , 'packageId' : package [ 'id' ] , 'presetId' : _get_preset_id ( package , size ) , 'useHourlyPricing' : hourly , } if post_uri : order [ 'provisionScripts' ] = [ post_uri ] if ssh_keys : order [ 'sshKeys' ] = [ { 'sshKeyIds' : ssh_keys } ] return order
Translates arguments into a dictionary for creating a server .
444
12
233,719
def _get_ids_from_hostname ( self , hostname ) : results = self . list_hardware ( hostname = hostname , mask = "id" ) return [ result [ 'id' ] for result in results ]
Returns list of matching hardware IDs for a given hostname .
51
12
233,720
def _get_ids_from_ip ( self , ip ) : # pylint: disable=inconsistent-return-statements try : # Does it look like an ip address? socket . inet_aton ( ip ) except socket . error : return [ ] # Find the server via ip address. First try public ip, then private results = self . list_hardware ( public_ip = ip , mask = "id" ) if results : return [ result [ 'id' ] for result in results ] results = self . list_hardware ( private_ip = ip , mask = "id" ) if results : return [ result [ 'id' ] for result in results ]
Returns list of matching hardware IDs for a given ip address .
147
12
233,721
def edit ( self , hardware_id , userdata = None , hostname = None , domain = None , notes = None , tags = None ) : obj = { } if userdata : self . hardware . setUserMetadata ( [ userdata ] , id = hardware_id ) if tags is not None : self . hardware . setTags ( tags , id = hardware_id ) if hostname : obj [ 'hostname' ] = hostname if domain : obj [ 'domain' ] = domain if notes : obj [ 'notes' ] = notes if not obj : return True return self . hardware . editObject ( obj , id = hardware_id )
Edit hostname domain name notes user data of the hardware .
139
12
233,722
def update_firmware ( self , hardware_id , ipmi = True , raid_controller = True , bios = True , hard_drive = True ) : return self . hardware . createFirmwareUpdateTransaction ( bool ( ipmi ) , bool ( raid_controller ) , bool ( bios ) , bool ( hard_drive ) , id = hardware_id )
Update hardware firmware .
78
4
233,723
def reflash_firmware ( self , hardware_id , ipmi = True , raid_controller = True , bios = True ) : return self . hardware . createFirmwareReflashTransaction ( bool ( ipmi ) , bool ( raid_controller ) , bool ( bios ) , id = hardware_id )
Reflash hardware firmware .
67
5
233,724
def wait_for_ready ( self , instance_id , limit = 14400 , delay = 10 , pending = False ) : now = time . time ( ) until = now + limit mask = "mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]" instance = self . get_hardware ( instance_id , mask = mask ) while now <= until : if utils . is_ready ( instance , pending ) : return True transaction = utils . lookup ( instance , 'activeTransaction' , 'transactionStatus' , 'friendlyName' ) snooze = min ( delay , until - now ) LOGGER . info ( "%s - %d not ready. Auto retry in %ds" , transaction , instance_id , snooze ) time . sleep ( snooze ) instance = self . get_hardware ( instance_id , mask = mask ) now = time . time ( ) LOGGER . info ( "Waiting for %d expired." , instance_id ) return False
Determine if a Server is ready .
218
9
233,725
def cli ( env , identifier , immediate , comment , reason ) : mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) if not ( env . skip_confirmations or formatting . no_going_back ( hw_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) mgr . cancel_hardware ( hw_id , reason , comment , immediate )
Cancel a dedicated server .
111
6
233,726
def cli ( env , identifier , postinstall , key , image ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) keys = [ ] if key : for single_key in key : resolver = SoftLayer . SshKeyManager ( env . client ) . resolve_ids key_id = helpers . resolve_id ( resolver , single_key , 'SshKey' ) keys . append ( key_id ) if not ( env . skip_confirmations or formatting . no_going_back ( vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . reload_instance ( vs_id , post_uri = postinstall , ssh_keys = keys , image_id = image )
Reload operating system on a virtual server .
184
9
233,727
def cli ( env , identifier , columns ) : manager = CapacityManager ( env . client ) mask = """mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]], guest[modifyDate,id, primaryBackendIpAddress, primaryIpAddress,domain, hostname]]]""" result = manager . get_object ( identifier , mask ) try : flavor = result [ 'instances' ] [ 0 ] [ 'billingItem' ] [ 'description' ] except KeyError : flavor = "Pending Approval..." table = formatting . Table ( columns . columns , title = "%s - %s" % ( result . get ( 'name' ) , flavor ) ) # RCI = Reserved Capacity Instance for rci in result [ 'instances' ] : guest = rci . get ( 'guest' , None ) if guest is not None : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( guest ) ] ) else : table . add_row ( [ '-' for value in columns . columns ] ) env . fout ( table )
Reserved Capacity Group details . Will show which guests are assigned to a reservation .
254
16
233,728
def get_client_settings_args ( * * kwargs ) : timeout = kwargs . get ( 'timeout' ) if timeout is not None : timeout = float ( timeout ) return { 'endpoint_url' : kwargs . get ( 'endpoint_url' ) , 'timeout' : timeout , 'proxy' : kwargs . get ( 'proxy' ) , 'username' : kwargs . get ( 'username' ) , 'api_key' : kwargs . get ( 'api_key' ) , }
Retrieve client settings from user - supplied arguments .
119
10
233,729
def get_client_settings_env ( * * _ ) : return { 'proxy' : os . environ . get ( 'https_proxy' ) , 'username' : os . environ . get ( 'SL_USERNAME' ) , 'api_key' : os . environ . get ( 'SL_API_KEY' ) , }
Retrieve client settings from environment settings .
76
8
233,730
def get_client_settings_config_file ( * * kwargs ) : # pylint: disable=inconsistent-return-statements config_files = [ '/etc/softlayer.conf' , '~/.softlayer' ] if kwargs . get ( 'config_file' ) : config_files . append ( kwargs . get ( 'config_file' ) ) config_files = [ os . path . expanduser ( f ) for f in config_files ] config = utils . configparser . RawConfigParser ( { 'username' : '' , 'api_key' : '' , 'endpoint_url' : '' , 'timeout' : '0' , 'proxy' : '' , } ) config . read ( config_files ) if config . has_section ( 'softlayer' ) : return { 'endpoint_url' : config . get ( 'softlayer' , 'endpoint_url' ) , 'timeout' : config . getfloat ( 'softlayer' , 'timeout' ) , 'proxy' : config . get ( 'softlayer' , 'proxy' ) , 'username' : config . get ( 'softlayer' , 'username' ) , 'api_key' : config . get ( 'softlayer' , 'api_key' ) , }
Retrieve client settings from the possible config file locations .
285
11
233,731
def get_client_settings ( * * kwargs ) : all_settings = { } for setting_method in SETTING_RESOLVERS : settings = setting_method ( * * kwargs ) if settings : settings . update ( ( k , v ) for k , v in all_settings . items ( ) if v ) all_settings = settings return all_settings
Parse client settings .
80
5
233,732
def cli ( env , package_keyname , required ) : client = env . client manager = ordering . OrderingManager ( client ) table = formatting . Table ( COLUMNS ) categories = manager . list_categories ( package_keyname ) if required : categories = [ cat for cat in categories if cat [ 'isRequired' ] ] for cat in categories : table . add_row ( [ cat [ 'itemCategory' ] [ 'name' ] , cat [ 'itemCategory' ] [ 'categoryCode' ] , 'Y' if cat [ 'isRequired' ] else 'N' ] ) env . fout ( table )
List the categories of a package .
138
7
233,733
def list_certs ( self , method = 'all' ) : ssl = self . client [ 'Account' ] methods = { 'all' : 'getSecurityCertificates' , 'expired' : 'getExpiredSecurityCertificates' , 'valid' : 'getValidSecurityCertificates' } mask = "mask[id, commonName, validityDays, notes]" func = getattr ( ssl , methods [ method ] ) return func ( mask = mask )
List all certificates .
104
4
233,734
def cli ( env ) : manager = SoftLayer . DNSManager ( env . client ) zones = manager . list_zones ( ) table = formatting . Table ( [ 'id' , 'zone' , 'serial' , 'updated' ] ) table . align [ 'serial' ] = 'c' table . align [ 'updated' ] = 'c' for zone in zones : table . add_row ( [ zone [ 'id' ] , zone [ 'name' ] , zone [ 'serial' ] , zone [ 'updateDate' ] , ] ) env . fout ( table )
List all zones .
127
4
233,735
def list_file_volumes ( self , datacenter = None , username = None , storage_type = None , * * kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'username' , 'capacityGb' , 'bytesUsed' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'activeTransactionCount' , 'fileNetworkMountAddress' , 'replicationPartnerCount' ] kwargs [ 'mask' ] = ',' . join ( items ) _filter = utils . NestedDict ( kwargs . get ( 'filter' ) or { } ) _filter [ 'nasNetworkStorage' ] [ 'serviceResource' ] [ 'type' ] [ 'type' ] = ( utils . query_filter ( '!~ NAS' ) ) _filter [ 'nasNetworkStorage' ] [ 'storageType' ] [ 'keyName' ] = ( utils . query_filter ( '*FILE_STORAGE*' ) ) if storage_type : _filter [ 'nasNetworkStorage' ] [ 'storageType' ] [ 'keyName' ] = ( utils . query_filter ( '%s_FILE_STORAGE*' % storage_type . upper ( ) ) ) if datacenter : _filter [ 'nasNetworkStorage' ] [ 'serviceResource' ] [ 'datacenter' ] [ 'name' ] = ( utils . query_filter ( datacenter ) ) if username : _filter [ 'nasNetworkStorage' ] [ 'username' ] = ( utils . query_filter ( username ) ) kwargs [ 'filter' ] = _filter . to_dict ( ) return self . client . call ( 'Account' , 'getNasNetworkStorage' , * * kwargs )
Returns a list of file volumes .
402
7
233,736
def get_file_volume_details ( self , volume_id , * * kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'username' , 'password' , 'capacityGb' , 'bytesUsed' , 'snapshotCapacityGb' , 'parentVolume.snapshotSizeBytes' , 'storageType.keyName' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'fileNetworkMountAddress' , 'storageTierLevel' , 'provisionedIops' , 'lunId' , 'originalVolumeName' , 'originalSnapshotName' , 'originalVolumeSize' , 'activeTransactionCount' , 'activeTransactions.transactionStatus[friendlyName]' , 'replicationPartnerCount' , 'replicationStatus' , 'replicationPartners[id,username,' 'serviceResourceBackendIpAddress,' 'serviceResource[datacenter[name]],' 'replicationSchedule[type[keyname]]]' , ] kwargs [ 'mask' ] = ',' . join ( items ) return self . client . call ( 'Network_Storage' , 'getObject' , id = volume_id , * * kwargs )
Returns details about the specified volume .
274
7
233,737
def order_replicant_volume ( self , volume_id , snapshot_schedule , location , tier = None ) : file_mask = 'billingItem[activeChildren,hourlyFlag],' 'storageTierLevel,osType,staasVersion,' 'hasEncryptionAtRest,snapshotCapacityGb,schedules,' 'intervalSchedule,hourlySchedule,dailySchedule,' 'weeklySchedule,storageType[keyName],provisionedIops' file_volume = self . get_file_volume_details ( volume_id , mask = file_mask ) order = storage_utils . prepare_replicant_order_object ( self , snapshot_schedule , location , tier , file_volume , 'file' ) return self . client . call ( 'Product_Order' , 'placeOrder' , order )
Places an order for a replicant file volume .
184
12
233,738
def order_duplicate_volume ( self , origin_volume_id , origin_snapshot_id = None , duplicate_size = None , duplicate_iops = None , duplicate_tier_level = None , duplicate_snapshot_size = None , hourly_billing_flag = False ) : file_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,' 'storageType[keyName],capacityGb,originalVolumeSize,' 'provisionedIops,storageTierLevel,' 'staasVersion,hasEncryptionAtRest' origin_volume = self . get_file_volume_details ( origin_volume_id , mask = file_mask ) order = storage_utils . prepare_duplicate_order_object ( self , origin_volume , duplicate_iops , duplicate_tier_level , duplicate_size , duplicate_snapshot_size , 'file' , hourly_billing_flag ) if origin_snapshot_id is not None : order [ 'duplicateOriginSnapshotId' ] = origin_snapshot_id return self . client . call ( 'Product_Order' , 'placeOrder' , order )
Places an order for a duplicate file volume .
256
10
233,739
def order_modified_volume ( self , volume_id , new_size = None , new_iops = None , new_tier_level = None ) : mask_items = [ 'id' , 'billingItem' , 'storageType[keyName]' , 'capacityGb' , 'provisionedIops' , 'storageTierLevel' , 'staasVersion' , 'hasEncryptionAtRest' , ] file_mask = ',' . join ( mask_items ) volume = self . get_file_volume_details ( volume_id , mask = file_mask ) order = storage_utils . prepare_modify_order_object ( self , volume , new_iops , new_tier_level , new_size ) return self . client . call ( 'Product_Order' , 'placeOrder' , order )
Places an order for modifying an existing file volume .
181
11
233,740
def order_snapshot_space ( self , volume_id , capacity , tier , upgrade , * * kwargs ) : file_mask = 'id,billingItem[location,hourlyFlag],' 'storageType[keyName],storageTierLevel,provisionedIops,' 'staasVersion,hasEncryptionAtRest' file_volume = self . get_file_volume_details ( volume_id , mask = file_mask , * * kwargs ) order = storage_utils . prepare_snapshot_order_object ( self , file_volume , capacity , tier , upgrade ) return self . client . call ( 'Product_Order' , 'placeOrder' , order )
Orders snapshot space for the given file volume .
150
10
233,741
def cli ( env , zone ) : manager = SoftLayer . DNSManager ( env . client ) zone_id = helpers . resolve_id ( manager . resolve_ids , zone , name = 'zone' ) env . fout ( manager . dump_zone ( zone_id ) )
Print zone in BIND format .
61
7
233,742
def rescue ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( "This action will reboot this VSI. Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . rescue ( vs_id )
Reboot into a rescue image .
95
7
233,743
def reboot ( env , identifier , hard ) : virtual_guest = env . client [ 'Virtual_Guest' ] mgr = SoftLayer . HardwareManager ( env . client ) vs_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will reboot the VS with id %s. ' 'Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if hard is True : virtual_guest . rebootHard ( id = vs_id ) elif hard is False : virtual_guest . rebootSoft ( id = vs_id ) else : virtual_guest . rebootDefault ( id = vs_id )
Reboot an active virtual server .
166
7
233,744
def power_off ( env , identifier , hard ) : virtual_guest = env . client [ 'Virtual_Guest' ] vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will power off the VS with id %s. ' 'Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if hard : virtual_guest . powerOff ( id = vs_id ) else : virtual_guest . powerOffSoft ( id = vs_id )
Power off an active virtual server .
148
7
233,745
def power_on ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) env . client [ 'Virtual_Guest' ] . powerOn ( id = vs_id )
Power on a virtual server .
66
6
233,746
def pause ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will pause the VS with id %s. Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) env . client [ 'Virtual_Guest' ] . pause ( id = vs_id )
Pauses an active virtual server .
111
7
233,747
def resume ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) env . client [ 'Virtual_Guest' ] . resume ( id = vs_id )
Resumes a paused virtual server .
63
7
233,748
def cli ( env ) : manager = AccountManager ( env . client ) summary = manager . get_summary ( ) env . fout ( get_snapshot_table ( summary ) )
Prints some various bits of information about an account
40
10
233,749
def get_snapshot_table ( account ) : table = formatting . KeyValueTable ( [ "Name" , "Value" ] , title = "Account Snapshot" ) table . align [ 'Name' ] = 'r' table . align [ 'Value' ] = 'l' table . add_row ( [ 'Company Name' , account . get ( 'companyName' , '-' ) ] ) table . add_row ( [ 'Balance' , utils . lookup ( account , 'pendingInvoice' , 'startingBalance' ) ] ) table . add_row ( [ 'Upcoming Invoice' , utils . lookup ( account , 'pendingInvoice' , 'invoiceTotalAmount' ) ] ) table . add_row ( [ 'Image Templates' , account . get ( 'blockDeviceTemplateGroupCount' , '-' ) ] ) table . add_row ( [ 'Dedicated Hosts' , account . get ( 'dedicatedHostCount' , '-' ) ] ) table . add_row ( [ 'Hardware' , account . get ( 'hardwareCount' , '-' ) ] ) table . add_row ( [ 'Virtual Guests' , account . get ( 'virtualGuestCount' , '-' ) ] ) table . add_row ( [ 'Domains' , account . get ( 'domainCount' , '-' ) ] ) table . add_row ( [ 'Network Storage Volumes' , account . get ( 'networkStorageCount' , '-' ) ] ) table . add_row ( [ 'Open Tickets' , account . get ( 'openTicketCount' , '-' ) ] ) table . add_row ( [ 'Network Vlans' , account . get ( 'networkVlanCount' , '-' ) ] ) table . add_row ( [ 'Subnets' , account . get ( 'subnetCount' , '-' ) ] ) table . add_row ( [ 'Users' , account . get ( 'userCount' , '-' ) ] ) return table
Generates a table for printing account summary data
437
9
233,750
def cli ( env , prop ) : try : if prop == 'network' : env . fout ( get_network ( ) ) return meta_prop = META_MAPPING . get ( prop ) or prop env . fout ( SoftLayer . MetadataManager ( ) . get ( meta_prop ) ) except SoftLayer . TransportError : raise exceptions . CLIAbort ( 'Cannot connect to the backend service address. Make sure ' 'this command is being ran from a device on the backend ' 'network.' )
Find details about this machine .
113
6
233,751
def get_network ( ) : meta = SoftLayer . MetadataManager ( ) network_tables = [ ] for network_func in [ meta . public_network , meta . private_network ] : network = network_func ( ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'mac addresses' , formatting . listing ( network [ 'mac_addresses' ] , separator = ',' ) ] ) table . add_row ( [ 'router' , network [ 'router' ] ] ) table . add_row ( [ 'vlans' , formatting . listing ( network [ 'vlans' ] , separator = ',' ) ] ) table . add_row ( [ 'vlan ids' , formatting . listing ( network [ 'vlan_ids' ] , separator = ',' ) ] ) network_tables . append ( table ) return network_tables
Returns a list of tables with public and private network details .
229
12
233,752
def get_formatter ( columns ) : column_map = dict ( ( column . name , column ) for column in columns ) def validate ( ctx , param , value ) : """Click validation function.""" if value == '' : raise click . BadParameter ( 'At least one column is required.' ) formatter = ColumnFormatter ( ) for column in [ col . strip ( ) for col in value . split ( ',' ) ] : if column in column_map : formatter . add_column ( column_map [ column ] ) else : formatter . add_column ( Column ( column , column . split ( '.' ) ) ) return formatter return validate
This function returns a callback to use with click options .
141
11
233,753
def add_column ( self , column ) : self . columns . append ( column . name ) self . column_funcs . append ( column . path ) if column . mask is not None : self . mask_parts . add ( column . mask )
Add a new column along with a formatting function .
53
10
233,754
def row ( self , data ) : for column in self . column_funcs : if callable ( column ) : yield column ( data ) else : yield utils . lookup ( data , * column )
Return a formatted row for the given data .
43
9
233,755
def cli ( env , account_id , origin_id ) : manager = SoftLayer . CDNManager ( env . client ) manager . remove_origin ( account_id , origin_id )
Remove an origin pull mapping .
42
6
233,756
def cli ( env , sortby ) : manager = SoftLayer . CDNManager ( env . client ) accounts = manager . list_accounts ( ) table = formatting . Table ( [ 'id' , 'account_name' , 'type' , 'created' , 'notes' ] ) for account in accounts : table . add_row ( [ account [ 'id' ] , account [ 'cdnAccountName' ] , account [ 'cdnSolutionName' ] , account [ 'createDate' ] , account . get ( 'cdnAccountNote' , formatting . blank ( ) ) ] ) table . sortby = sortby env . fout ( table )
List all CDN accounts .
140
6
233,757
def cli ( env , volume_id , sortby , columns ) : file_manager = SoftLayer . FileStorageManager ( env . client ) snapshots = file_manager . get_file_volume_snapshot_list ( volume_id , mask = columns . mask ( ) ) table = formatting . Table ( columns . columns ) table . sortby = sortby for snapshot in snapshots : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( snapshot ) ] ) env . fout ( table )
List file storage snapshots .
114
5
233,758
def list_instances ( self , hourly = True , monthly = True , tags = None , cpus = None , memory = None , hostname = None , domain = None , local_disk = None , datacenter = None , nic_speed = None , public_ip = None , private_ip = None , * * kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'globalIdentifier' , 'hostname' , 'domain' , 'fullyQualifiedDomainName' , 'primaryBackendIpAddress' , 'primaryIpAddress' , 'lastKnownPowerState.name' , 'powerState' , 'maxCpu' , 'maxMemory' , 'datacenter' , 'activeTransaction.transactionStatus[friendlyName,name]' , 'status' , ] kwargs [ 'mask' ] = "mask[%s]" % ',' . join ( items ) call = 'getVirtualGuests' if not all ( [ hourly , monthly ] ) : if hourly : call = 'getHourlyVirtualGuests' elif monthly : call = 'getMonthlyVirtualGuests' _filter = utils . NestedDict ( kwargs . get ( 'filter' ) or { } ) if tags : _filter [ 'virtualGuests' ] [ 'tagReferences' ] [ 'tag' ] [ 'name' ] = { 'operation' : 'in' , 'options' : [ { 'name' : 'data' , 'value' : tags } ] , } if cpus : _filter [ 'virtualGuests' ] [ 'maxCpu' ] = utils . query_filter ( cpus ) if memory : _filter [ 'virtualGuests' ] [ 'maxMemory' ] = utils . query_filter ( memory ) if hostname : _filter [ 'virtualGuests' ] [ 'hostname' ] = utils . query_filter ( hostname ) if domain : _filter [ 'virtualGuests' ] [ 'domain' ] = utils . query_filter ( domain ) if local_disk is not None : _filter [ 'virtualGuests' ] [ 'localDiskFlag' ] = ( utils . query_filter ( bool ( local_disk ) ) ) if datacenter : _filter [ 'virtualGuests' ] [ 'datacenter' ] [ 'name' ] = ( utils . query_filter ( datacenter ) ) if nic_speed : _filter [ 'virtualGuests' ] [ 'networkComponents' ] [ 'maxSpeed' ] = ( utils . query_filter ( nic_speed ) ) if public_ip : _filter [ 'virtualGuests' ] [ 'primaryIpAddress' ] = ( utils . query_filter ( public_ip ) ) if private_ip : _filter [ 'virtualGuests' ] [ 'primaryBackendIpAddress' ] = ( utils . query_filter ( private_ip ) ) kwargs [ 'filter' ] = _filter . to_dict ( ) kwargs [ 'iter' ] = True return self . client . call ( 'Account' , call , * * kwargs )
Retrieve a list of all virtual servers on the account .
694
12
233,759
def get_instance ( self , instance_id , * * kwargs ) : if 'mask' not in kwargs : kwargs [ 'mask' ] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'createDate,' 'modifyDate,' 'provisionDate,' 'notes,' 'dedicatedAccountHostOnlyFlag,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'primaryIpAddress,' '''networkComponents[id, status, speed, maxSpeed, name, macAddress, primaryIpAddress, port, primarySubnet[addressSpace], securityGroupBindings[ securityGroup[id, name]]],''' 'lastKnownPowerState.name,' 'powerState,' 'status,' 'maxCpu,' 'maxMemory,' 'datacenter,' 'activeTransaction[id, transactionStatus[friendlyName,name]],' 'lastTransaction[transactionStatus],' 'lastOperatingSystemReload.id,' 'blockDevices,' 'blockDeviceTemplateGroup[id, name, globalIdentifier],' 'postInstallScriptUri,' '''operatingSystem[passwords[username,password], softwareLicense.softwareDescription[ manufacturer,name,version, referenceCode]],''' '''softwareComponents[ passwords[username,password,notes], softwareLicense[softwareDescription[ manufacturer,name,version, referenceCode]]],''' 'hourlyBillingFlag,' 'userData,' '''billingItem[id,nextInvoiceTotalRecurringAmount, package[id,keyName], children[categoryCode,nextInvoiceTotalRecurringAmount], orderItem[id, order.userRecord[username], preset.keyName]],''' 'tagReferences[id,tag[name,id]],' 'networkVlans[id,vlanNumber,networkSpace],' 'dedicatedHost.id,' 'placementGroupId' ) return self . guest . getObject ( id = instance_id , * * kwargs )
Get details about a virtual server instance .
435
8
233,760
def reload_instance ( self , instance_id , post_uri = None , ssh_keys = None , image_id = None ) : config = { } if post_uri : config [ 'customProvisionScriptUri' ] = post_uri if ssh_keys : config [ 'sshKeyIds' ] = [ key_id for key_id in ssh_keys ] if image_id : config [ 'imageTemplateId' ] = image_id return self . client . call ( 'Virtual_Guest' , 'reloadOperatingSystem' , 'FORCE' , config , id = instance_id )
Perform an OS reload of an instance .
133
9
233,761
def wait_for_transaction ( self , instance_id , limit , delay = 10 ) : return self . wait_for_ready ( instance_id , limit , delay = delay , pending = True )
Waits on a VS transaction for the specified amount of time .
44
13
233,762
def verify_create_instance ( self , * * kwargs ) : kwargs . pop ( 'tags' , None ) create_options = self . _generate_create_dict ( * * kwargs ) return self . guest . generateOrderTemplate ( create_options )
Verifies an instance creation command .
61
7
233,763
def create_instance ( self , * * kwargs ) : tags = kwargs . pop ( 'tags' , None ) inst = self . guest . createObject ( self . _generate_create_dict ( * * kwargs ) ) if tags is not None : self . set_tags ( tags , guest_id = inst [ 'id' ] ) return inst
Creates a new virtual server instance .
81
8
233,764
def set_tags ( self , tags , guest_id ) : self . guest . setTags ( tags , id = guest_id )
Sets tags on a guest with a retry decorator
29
12
233,765
def create_instances ( self , config_list ) : tags = [ conf . pop ( 'tags' , None ) for conf in config_list ] resp = self . guest . createObjects ( [ self . _generate_create_dict ( * * kwargs ) for kwargs in config_list ] ) for instance , tag in zip ( resp , tags ) : if tag is not None : self . set_tags ( tag , guest_id = instance [ 'id' ] ) return resp
Creates multiple virtual server instances .
109
7
233,766
def change_port_speed ( self , instance_id , public , speed ) : if public : return self . client . call ( 'Virtual_Guest' , 'setPublicNetworkInterfaceSpeed' , speed , id = instance_id ) else : return self . client . call ( 'Virtual_Guest' , 'setPrivateNetworkInterfaceSpeed' , speed , id = instance_id )
Allows you to change the port speed of a virtual server s NICs .
81
15
233,767
def _get_ids_from_hostname ( self , hostname ) : results = self . list_instances ( hostname = hostname , mask = "id" ) return [ result [ 'id' ] for result in results ]
List VS ids which match the given hostname .
51
11
233,768
def _get_ids_from_ip ( self , ip_address ) : # pylint: disable=inconsistent-return-statements try : # Does it look like an ip address? socket . inet_aton ( ip_address ) except socket . error : return [ ] # Find the VS via ip address. First try public ip, then private results = self . list_instances ( public_ip = ip_address , mask = "id" ) if results : return [ result [ 'id' ] for result in results ] results = self . list_instances ( private_ip = ip_address , mask = "id" ) if results : return [ result [ 'id' ] for result in results ]
List VS ids which match the given ip address .
155
11
233,769
def upgrade ( self , instance_id , cpus = None , memory = None , nic_speed = None , public = True , preset = None ) : upgrade_prices = self . _get_upgrade_prices ( instance_id ) prices = [ ] data = { 'nic_speed' : nic_speed } if cpus is not None and preset is not None : raise ValueError ( "Do not use cpu, private and memory if you are using flavors" ) data [ 'cpus' ] = cpus if memory is not None and preset is not None : raise ValueError ( "Do not use memory, private or cpu if you are using flavors" ) data [ 'memory' ] = memory maintenance_window = datetime . datetime . now ( utils . UTC ( ) ) order = { 'complexType' : 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade' , 'properties' : [ { 'name' : 'MAINTENANCE_WINDOW' , 'value' : maintenance_window . strftime ( "%Y-%m-%d %H:%M:%S%z" ) } ] , 'virtualGuests' : [ { 'id' : int ( instance_id ) } ] , } for option , value in data . items ( ) : if not value : continue price_id = self . _get_price_id_for_upgrade_option ( upgrade_prices , option , value , public ) if not price_id : # Every option provided is expected to have a price raise exceptions . SoftLayerError ( "Unable to find %s option with value %s" % ( option , value ) ) prices . append ( { 'id' : price_id } ) order [ 'prices' ] = prices if preset is not None : vs_object = self . get_instance ( instance_id ) [ 'billingItem' ] [ 'package' ] order [ 'presetId' ] = self . ordering_manager . get_preset_by_key ( vs_object [ 'keyName' ] , preset ) [ 'id' ] if prices or preset : self . client [ 'Product_Order' ] . placeOrder ( order ) return True return False
Upgrades a VS instance .
482
6
233,770
def _get_package_items ( self ) : warnings . warn ( "use _get_upgrade_prices() instead" , DeprecationWarning ) mask = [ 'description' , 'capacity' , 'units' , 'prices[id,locationGroupId,categories[name,id,categoryCode]]' ] mask = "mask[%s]" % ',' . join ( mask ) package_keyname = "CLOUD_SERVER" package = self . ordering_manager . get_package_by_key ( package_keyname ) package_service = self . client [ 'Product_Package' ] return package_service . getItems ( id = package [ 'id' ] , mask = mask )
Following Method gets all the item ids related to VS .
158
12
233,771
def _get_upgrade_prices ( self , instance_id , include_downgrade_options = True ) : mask = [ 'id' , 'locationGroupId' , 'categories[name,id,categoryCode]' , 'item[description,capacity,units]' ] mask = "mask[%s]" % ',' . join ( mask ) return self . guest . getUpgradeItemPrices ( include_downgrade_options , id = instance_id , mask = mask )
Following Method gets all the price ids related to upgrading a VS .
105
14
233,772
def _get_price_id_for_upgrade_option ( self , upgrade_prices , option , value , public = True ) : option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category . get ( option ) for price in upgrade_prices : if price . get ( 'categories' ) is None or price . get ( 'item' ) is None : continue product = price . get ( 'item' ) is_private = ( product . get ( 'units' ) == 'PRIVATE_CORE' or product . get ( 'units' ) == 'DEDICATED_CORE' ) for category in price . get ( 'categories' ) : if not ( category . get ( 'categoryCode' ) == category_code and str ( product . get ( 'capacity' ) ) == str ( value ) ) : continue if option == 'cpus' : # Public upgrade and public guest_core price if public and not is_private : return price . get ( 'id' ) # Private upgrade and private guest_core price elif not public and is_private : return price . get ( 'id' ) elif option == 'nic_speed' : if 'Public' in product . get ( 'description' ) : return price . get ( 'id' ) else : return price . get ( 'id' )
Find the price id for the option and value to upgrade . This
319
13
233,773
def _get_price_id_for_upgrade ( self , package_items , option , value , public = True ) : warnings . warn ( "use _get_price_id_for_upgrade_option() instead" , DeprecationWarning ) option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category [ option ] for item in package_items : is_private = ( item . get ( 'units' ) == 'PRIVATE_CORE' ) for price in item [ 'prices' ] : if 'locationGroupId' in price and price [ 'locationGroupId' ] : # Skip location based prices continue if 'categories' not in price : continue categories = price [ 'categories' ] for category in categories : if not ( category [ 'categoryCode' ] == category_code and str ( item [ 'capacity' ] ) == str ( value ) ) : continue if option == 'cpus' : if public and not is_private : return price [ 'id' ] elif not public and is_private : return price [ 'id' ] elif option == 'nic_speed' : if 'Public' in item [ 'description' ] : return price [ 'id' ] else : return price [ 'id' ]
Find the price id for the option and value to upgrade .
301
12
233,774
def interface_list ( env , securitygroup_id , sortby ) : mgr = SoftLayer . NetworkManager ( env . client ) table = formatting . Table ( COLUMNS ) table . sortby = sortby mask = ( '''networkComponentBindings[ networkComponentId, networkComponent[ id, port, guest[ id, hostname, primaryBackendIpAddress, primaryIpAddress ] ] ]''' ) secgroup = mgr . get_securitygroup ( securitygroup_id , mask = mask ) for binding in secgroup . get ( 'networkComponentBindings' , [ ] ) : interface_id = binding [ 'networkComponentId' ] try : interface = binding [ 'networkComponent' ] vsi = interface [ 'guest' ] vsi_id = vsi [ 'id' ] hostname = vsi [ 'hostname' ] priv_pub = 'PRIVATE' if interface [ 'port' ] == 0 else 'PUBLIC' ip_address = ( vsi [ 'primaryBackendIpAddress' ] if interface [ 'port' ] == 0 else vsi [ 'primaryIpAddress' ] ) except KeyError : vsi_id = "N/A" hostname = "Not enough permission to view" priv_pub = "N/A" ip_address = "N/A" table . add_row ( [ interface_id , vsi_id , hostname , priv_pub , ip_address ] ) env . fout ( table )
List interfaces associated with security groups .
324
7
233,775
def add ( env , securitygroup_id , network_component , server , interface ) : _validate_args ( network_component , server , interface ) mgr = SoftLayer . NetworkManager ( env . client ) component_id = _get_component_id ( env , network_component , server , interface ) ret = mgr . attach_securitygroup_component ( securitygroup_id , component_id ) if not ret : raise exceptions . CLIAbort ( "Could not attach network component" ) table = formatting . Table ( REQUEST_COLUMNS ) table . add_row ( [ ret [ 'requestId' ] ] ) env . fout ( table )
Attach an interface to a security group .
144
8
233,776
def default_select ( identifier , all_entry_points ) : # pylint: disable=inconsistent-return-statements if len ( all_entry_points ) == 0 : raise PluginMissingError ( identifier ) elif len ( all_entry_points ) == 1 : return all_entry_points [ 0 ] elif len ( all_entry_points ) > 1 : raise AmbiguousPluginError ( all_entry_points )
Raise an exception when we have ambiguous entry points .
95
11
233,777
def _load_class_entry_point ( cls , entry_point ) : class_ = entry_point . load ( ) setattr ( class_ , 'plugin_name' , entry_point . name ) return class_
Load entry_point and set the entry_point . name as the attribute plugin_name on the loaded object
49
22
233,778
def load_class ( cls , identifier , default = None , select = None ) : identifier = identifier . lower ( ) key = ( cls . entry_point , identifier ) if key not in PLUGIN_CACHE : if select is None : select = default_select all_entry_points = list ( pkg_resources . iter_entry_points ( cls . entry_point , name = identifier ) ) for extra_identifier , extra_entry_point in cls . extra_entry_points : if identifier == extra_identifier : all_entry_points . append ( extra_entry_point ) try : selected_entry_point = select ( identifier , all_entry_points ) except PluginMissingError : if default is not None : return default raise PLUGIN_CACHE [ key ] = cls . _load_class_entry_point ( selected_entry_point ) return PLUGIN_CACHE [ key ]
Load a single class specified by identifier .
206
8
233,779
def load_classes ( cls , fail_silently = True ) : all_classes = itertools . chain ( pkg_resources . iter_entry_points ( cls . entry_point ) , ( entry_point for identifier , entry_point in cls . extra_entry_points ) , ) for class_ in all_classes : try : yield ( class_ . name , cls . _load_class_entry_point ( class_ ) ) except Exception : # pylint: disable=broad-except if fail_silently : log . warning ( 'Unable to load %s %r' , cls . __name__ , class_ . name , exc_info = True ) else : raise
Load all the classes for a plugin .
155
8
233,780
def register_temp_plugin ( cls , class_ , identifier = None , dist = 'xblock' ) : from mock import Mock if identifier is None : identifier = class_ . __name__ . lower ( ) entry_point = Mock ( dist = Mock ( key = dist ) , load = Mock ( return_value = class_ ) , ) entry_point . name = identifier def _decorator ( func ) : # pylint: disable=C0111 @ functools . wraps ( func ) def _inner ( * args , * * kwargs ) : # pylint: disable=C0111 global PLUGIN_CACHE # pylint: disable=global-statement old = list ( cls . extra_entry_points ) old_cache = PLUGIN_CACHE cls . extra_entry_points . append ( ( identifier , entry_point ) ) PLUGIN_CACHE = { } try : return func ( * args , * * kwargs ) finally : cls . extra_entry_points = old PLUGIN_CACHE = old_cache return _inner return _decorator
Decorate a function to run with a temporary plugin available .
249
12
233,781
def webob_to_django_response ( webob_response ) : from django . http import HttpResponse django_response = HttpResponse ( webob_response . app_iter , content_type = webob_response . content_type , status = webob_response . status_code , ) for name , value in webob_response . headerlist : django_response [ name ] = value return django_response
Returns a django response to the webob_response
96
11
233,782
def querydict_to_multidict ( query_dict , wrap = None ) : wrap = wrap or ( lambda val : val ) return MultiDict ( chain . from_iterable ( six . moves . zip ( repeat ( key ) , ( wrap ( v ) for v in vals ) ) for key , vals in six . iterlists ( query_dict ) ) )
Returns a new webob . MultiDict from a django . http . QueryDict .
81
20
233,783
def _meta_name ( self , name ) : name = name . upper ( ) . replace ( '-' , '_' ) if name not in self . UNPREFIXED_HEADERS : name = 'HTTP_' + name return name
Translate HTTP header names to the format used by Django request objects .
53
14
233,784
def _un_meta_name ( self , name ) : if name . startswith ( 'HTTP_' ) : name = name [ 5 : ] return name . replace ( '_' , '-' ) . title ( )
Reverse of _meta_name
49
8
233,785
def environ ( self ) : environ = dict ( self . _request . META ) environ [ 'PATH_INFO' ] = self . _request . path_info return environ
Add path_info to the request s META dictionary .
41
12
233,786
def _getfield ( self , block , name ) : # First, get the field from the class, if defined block_field = getattr ( block . __class__ , name , None ) if block_field is not None and isinstance ( block_field , Field ) : return block_field # Not in the class, so name # really doesn't name a field raise KeyError ( name )
Return the field with the given name from block . If no field with name exists in any namespace raises a KeyError .
84
24
233,787
def get ( self , block , name ) : return self . _kvs . get ( self . _key ( block , name ) )
Retrieve the value for the field named name .
29
10
233,788
def set ( self , block , name , value ) : self . _kvs . set ( self . _key ( block , name ) , value )
Set the value of the field named name
32
8
233,789
def delete ( self , block , name ) : self . _kvs . delete ( self . _key ( block , name ) )
Reset the value of the field named name to the default
28
12
233,790
def has ( self , block , name ) : try : return self . _kvs . has ( self . _key ( block , name ) ) except KeyError : return False
Return whether or not the field named name has a non - default value
37
14
233,791
def set_many ( self , block , update_dict ) : updated_dict = { } # Generate a new dict with the correct mappings. for ( key , value ) in six . iteritems ( update_dict ) : updated_dict [ self . _key ( block , key ) ] = value self . _kvs . set_many ( updated_dict )
Update the underlying model with the correct values .
79
9
233,792
def create_aside ( self , definition_id , usage_id , aside_type ) : return ( self . ASIDE_DEFINITION_ID ( definition_id , aside_type ) , self . ASIDE_USAGE_ID ( usage_id , aside_type ) , )
Create the aside .
63
4
233,793
def create_usage ( self , def_id ) : usage_id = self . _next_id ( "u" ) self . _usages [ usage_id ] = def_id return usage_id
Make a usage storing its definition id .
45
8
233,794
def get_definition_id ( self , usage_id ) : try : return self . _usages [ usage_id ] except KeyError : raise NoSuchUsage ( repr ( usage_id ) )
Get a definition_id by its usage id .
43
10
233,795
def create_definition ( self , block_type , slug = None ) : prefix = "d" if slug : prefix += "_" + slug def_id = self . _next_id ( prefix ) self . _definitions [ def_id ] = block_type return def_id
Make a definition storing its block type .
61
8
233,796
def get_block_type ( self , def_id ) : try : return self . _definitions [ def_id ] except KeyError : try : return def_id . aside_type except AttributeError : raise NoSuchDefinition ( repr ( def_id ) )
Get a block_type by its definition id .
58
10
233,797
def field_data ( self , field_data ) : warnings . warn ( "Runtime.field_data is deprecated" , FieldDataDeprecationWarning , stacklevel = 2 ) self . _deprecated_per_instance_field_data = field_data
Set field_data .
55
5
233,798
def construct_xblock_from_class ( self , cls , scope_ids , field_data = None , * args , * * kwargs ) : return self . mixologist . mix ( cls ) ( runtime = self , field_data = field_data , scope_ids = scope_ids , * args , * * kwargs )
Construct a new xblock of type cls mixing in the mixins defined for this application .
76
19
233,799
def get_block ( self , usage_id , for_parent = None ) : def_id = self . id_reader . get_definition_id ( usage_id ) try : block_type = self . id_reader . get_block_type ( def_id ) except NoSuchDefinition : raise NoSuchUsage ( repr ( usage_id ) ) keys = ScopeIds ( self . user_id , block_type , def_id , usage_id ) block = self . construct_xblock ( block_type , keys , for_parent = for_parent ) return block
Create an XBlock instance in this runtime .
126
9