idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
45,700 | def cli ( env , identifier , out_file ) : mgr = SoftLayer . SshKeyManager ( env . client ) key_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'SshKey' ) key = mgr . get_key ( key_id ) if out_file : with open ( path . expanduser ( out_file ) , 'w' ) as pub_file : pub_file . write ( key [ 'key' ] ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . add_row ( [ 'id' , key [ 'id' ] ] ) table . add_row ( [ 'label' , key . get ( 'label' ) ] ) table . add_row ( [ 'notes' , key . get ( 'notes' , '-' ) ] ) env . fout ( table ) | Prints out an SSH key to the screen . |
45,701 | def list_endpoints ( self ) : _filter = { 'hubNetworkStorage' : { 'vendorName' : { 'operation' : 'Swift' } } , } endpoints = [ ] network_storage = self . client . call ( 'Account' , 'getHubNetworkStorage' , mask = ENDPOINT_MASK , limit = 1 , filter = _filter ) if network_storage : for node in network_storage [ 'storageNodes' ] : endpoints . append ( { 'datacenter' : node [ 'datacenter' ] , 'public' : node [ 'frontendIpAddress' ] , 'private' : node [ 'backendIpAddress' ] , } ) return endpoints | Lists the known object storage endpoints . |
45,702 | def delete_credential ( self , identifier , credential_id = None ) : credential = { 'id' : credential_id } return self . client . call ( 'SoftLayer_Network_Storage_Hub_Cleversafe_Account' , 'credentialDelete' , credential , id = identifier ) | Delete the object storage credential . |
45,703 | def cli ( env , sortby , cpu , domain , datacenter , hostname , memory , network , tag , columns , limit ) : manager = SoftLayer . HardwareManager ( env . client ) servers = manager . list_hardware ( hostname = hostname , domain = domain , cpus = cpu , memory = memory , datacenter = datacenter , nic_speed = network , tags = tag , mask = "mask(SoftLayer_Hardware_Server)[%s]" % columns . mask ( ) , limit = limit ) table = formatting . Table ( columns . columns ) table . sortby = sortby for server in servers : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( server ) ] ) env . fout ( table ) | List hardware servers . |
45,704 | def cli ( env , user , template ) : mgr = SoftLayer . UserManager ( env . client ) user_id = helpers . resolve_id ( mgr . resolve_ids , user , 'username' ) user_template = { } if template is not None : try : template_object = json . loads ( template ) for key in template_object : user_template [ key ] = template_object [ key ] except ValueError as ex : raise exceptions . ArgumentError ( "Unable to parse --template. %s" % ex ) result = mgr . edit_user ( user_id , user_template ) if result : click . secho ( "%s updated successfully" % ( user ) , fg = 'green' ) else : click . secho ( "Failed to update %s" % ( user ) , fg = 'red' ) | Edit a Users details |
45,705 | def cli ( env , ip_address ) : mgr = SoftLayer . NetworkManager ( env . client ) addr_info = mgr . ip_lookup ( ip_address ) if not addr_info : raise exceptions . CLIAbort ( 'Not found' ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , addr_info [ 'id' ] ] ) table . add_row ( [ 'ip' , addr_info [ 'ipAddress' ] ] ) subnet_table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) subnet_table . align [ 'name' ] = 'r' subnet_table . align [ 'value' ] = 'l' subnet_table . add_row ( [ 'id' , addr_info [ 'subnet' ] [ 'id' ] ] ) subnet_table . add_row ( [ 'identifier' , '%s/%s' % ( addr_info [ 'subnet' ] [ 'networkIdentifier' ] , str ( addr_info [ 'subnet' ] [ 'cidr' ] ) ) ] ) subnet_table . add_row ( [ 'netmask' , addr_info [ 'subnet' ] [ 'netmask' ] ] ) if addr_info [ 'subnet' ] . get ( 'gateway' ) : subnet_table . add_row ( [ 'gateway' , addr_info [ 'subnet' ] [ 'gateway' ] ] ) subnet_table . add_row ( [ 'type' , addr_info [ 'subnet' ] . get ( 'subnetType' ) ] ) table . add_row ( [ 'subnet' , subnet_table ] ) if addr_info . get ( 'virtualGuest' ) or addr_info . get ( 'hardware' ) : device_table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) device_table . align [ 'name' ] = 'r' device_table . align [ 'value' ] = 'l' if addr_info . get ( 'virtualGuest' ) : device = addr_info [ 'virtualGuest' ] device_type = 'vs' else : device = addr_info [ 'hardware' ] device_type = 'server' device_table . add_row ( [ 'id' , device [ 'id' ] ] ) device_table . add_row ( [ 'name' , device [ 'fullyQualifiedDomainName' ] ] ) device_table . add_row ( [ 'type' , device_type ] ) table . add_row ( [ 'device' , device_table ] ) env . fout ( table ) | Find an IP address and display its subnet and device info . |
45,706 | def cli ( env , name , note , os_code , uri , ibm_api_key , root_key_crn , wrapped_dek , cloud_init , byol , is_encrypted ) : image_mgr = SoftLayer . ImageManager ( env . client ) result = image_mgr . import_image_from_uri ( name = name , note = note , os_code = os_code , uri = uri , ibm_api_key = ibm_api_key , root_key_crn = root_key_crn , wrapped_dek = wrapped_dek , cloud_init = cloud_init , byol = byol , is_encrypted = is_encrypted ) if not result : raise exceptions . CLIAbort ( "Failed to import Image" ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'name' , result [ 'name' ] ] ) table . add_row ( [ 'id' , result [ 'id' ] ] ) table . add_row ( [ 'created' , result [ 'createDate' ] ] ) table . add_row ( [ 'guid' , result [ 'globalIdentifier' ] ] ) env . fout ( table ) | Import an image . |
45,707 | def cli ( env , context_id , friendly_name , remote_peer , preshared_key , phase1_auth , phase1_crypto , phase1_dh , phase1_key_ttl , phase2_auth , phase2_crypto , phase2_dh , phase2_forward_secrecy , phase2_key_ttl ) : manager = SoftLayer . IPSECManager ( env . client ) succeeded = manager . update_tunnel_context ( context_id , friendly_name = friendly_name , remote_peer = remote_peer , preshared_key = preshared_key , phase1_auth = phase1_auth , phase1_crypto = phase1_crypto , phase1_dh = phase1_dh , phase1_key_ttl = phase1_key_ttl , phase2_auth = phase2_auth , phase2_crypto = phase2_crypto , phase2_dh = phase2_dh , phase2_forward_secrecy = phase2_forward_secrecy , phase2_key_ttl = phase2_key_ttl ) if succeeded : env . out ( 'Updated context #{}' . format ( context_id ) ) else : raise CLIHalt ( 'Failed to update context #{}' . format ( context_id ) ) | Update tunnel context properties . |
45,708 | def add_internal_subnet ( self , context_id , subnet_id ) : return self . context . addPrivateSubnetToNetworkTunnel ( subnet_id , id = context_id ) | Add an internal subnet to a tunnel context . |
45,709 | def add_remote_subnet ( self , context_id , subnet_id ) : return self . context . addCustomerSubnetToNetworkTunnel ( subnet_id , id = context_id ) | Adds a remote subnet to a tunnel context . |
45,710 | def add_service_subnet ( self , context_id , subnet_id ) : return self . context . addServiceSubnetToNetworkTunnel ( subnet_id , id = context_id ) | Adds a service subnet to a tunnel context . |
45,711 | def create_remote_subnet ( self , account_id , identifier , cidr ) : return self . remote_subnet . createObject ( { 'accountId' : account_id , 'cidr' : cidr , 'networkIdentifier' : identifier } ) | Creates a remote subnet on the given account . |
45,712 | def get_tunnel_context ( self , context_id , ** kwargs ) : _filter = utils . NestedDict ( kwargs . get ( 'filter' ) or { } ) _filter [ 'networkTunnelContexts' ] [ 'id' ] = utils . query_filter ( context_id ) kwargs [ 'filter' ] = _filter . to_dict ( ) contexts = self . account . getNetworkTunnelContexts ( ** kwargs ) if len ( contexts ) == 0 : raise SoftLayerAPIError ( 'SoftLayer_Exception_ObjectNotFound' , 'Unable to find object with id of \'{}\'' . format ( context_id ) ) return contexts [ 0 ] | Retrieves the network tunnel context instance . |
45,713 | def get_translation ( self , context_id , translation_id ) : translation = next ( ( x for x in self . get_translations ( context_id ) if x [ 'id' ] == translation_id ) , None ) if translation is None : raise SoftLayerAPIError ( 'SoftLayer_Exception_ObjectNotFound' , 'Unable to find object with id of \'{}\'' . format ( translation_id ) ) return translation | Retrieves a translation entry for the given id values . |
45,714 | def get_translations ( self , context_id ) : _mask = ( '[mask[addressTranslations[customerIpAddressRecord,' 'internalIpAddressRecord]]]' ) context = self . get_tunnel_context ( context_id , mask = _mask ) for translation in context . get ( 'addressTranslations' , [ ] ) : remote_ip = translation . get ( 'customerIpAddressRecord' , { } ) internal_ip = translation . get ( 'internalIpAddressRecord' , { } ) translation [ 'customerIpAddress' ] = remote_ip . get ( 'ipAddress' , '' ) translation [ 'internalIpAddress' ] = internal_ip . get ( 'ipAddress' , '' ) translation . pop ( 'customerIpAddressRecord' , None ) translation . pop ( 'internalIpAddressRecord' , None ) return context [ 'addressTranslations' ] | Retrieves all translation entries for a tunnel context . |
45,715 | def remove_internal_subnet ( self , context_id , subnet_id ) : return self . context . removePrivateSubnetFromNetworkTunnel ( subnet_id , id = context_id ) | Remove an internal subnet from a tunnel context . |
45,716 | def remove_remote_subnet ( self , context_id , subnet_id ) : return self . context . removeCustomerSubnetFromNetworkTunnel ( subnet_id , id = context_id ) | Removes a remote subnet from a tunnel context . |
45,717 | def remove_service_subnet ( self , context_id , subnet_id ) : return self . context . removeServiceSubnetFromNetworkTunnel ( subnet_id , id = context_id ) | Removes a service subnet from a tunnel context . |
45,718 | def remove_translation ( self , context_id , translation_id ) : return self . context . deleteAddressTranslation ( translation_id , id = context_id ) | Removes a translation entry from a tunnel context . |
45,719 | def update_translation ( self , context_id , translation_id , static_ip = None , remote_ip = None , notes = None ) : translation = self . get_translation ( context_id , translation_id ) if static_ip is not None : translation [ 'internalIpAddress' ] = static_ip translation . pop ( 'internalIpAddressId' , None ) if remote_ip is not None : translation [ 'customerIpAddress' ] = remote_ip translation . pop ( 'customerIpAddressId' , None ) if notes is not None : translation [ 'notes' ] = notes self . context . editAddressTranslation ( translation , id = context_id ) return True | Updates an address translation entry using the given values . |
45,720 | def update_tunnel_context ( self , context_id , friendly_name = None , remote_peer = None , preshared_key = None , phase1_auth = None , phase1_crypto = None , phase1_dh = None , phase1_key_ttl = None , phase2_auth = None , phase2_crypto = None , phase2_dh = None , phase2_forward_secrecy = None , phase2_key_ttl = None ) : context = self . get_tunnel_context ( context_id ) if friendly_name is not None : context [ 'friendlyName' ] = friendly_name if remote_peer is not None : context [ 'customerPeerIpAddress' ] = remote_peer if preshared_key is not None : context [ 'presharedKey' ] = preshared_key if phase1_auth is not None : context [ 'phaseOneAuthentication' ] = phase1_auth if phase1_crypto is not None : context [ 'phaseOneEncryption' ] = phase1_crypto if phase1_dh is not None : context [ 'phaseOneDiffieHellmanGroup' ] = phase1_dh if phase1_key_ttl is not None : context [ 'phaseOneKeylife' ] = phase1_key_ttl if phase2_auth is not None : context [ 'phaseTwoAuthentication' ] = phase2_auth if phase2_crypto is not None : context [ 'phaseTwoEncryption' ] = phase2_crypto if phase2_dh is not None : context [ 'phaseTwoDiffieHellmanGroup' ] = phase2_dh if phase2_forward_secrecy is not None : context [ 'phaseTwoPerfectForwardSecrecy' ] = phase2_forward_secrecy if phase2_key_ttl is not None : context [ 'phaseTwoKeylife' ] = phase2_key_ttl return self . context . editObject ( context , id = context_id ) | Updates a tunnel context using the given values . |
45,721 | def cli ( env , identifier ) : mgr = SoftLayer . ObjectStorageManager ( env . client ) credential = mgr . create_credential ( identifier ) table = formatting . Table ( [ 'id' , 'password' , 'username' , 'type_name' ] ) table . sortby = 'id' table . add_row ( [ credential [ 'id' ] , credential [ 'password' ] , credential [ 'username' ] , credential [ 'type' ] [ 'name' ] ] ) env . fout ( table ) | Create credentials for an IBM Cloud Object Storage Account |
45,722 | def cli ( env , name , public ) : image_mgr = SoftLayer . ImageManager ( env . client ) images = [ ] if public in [ False , None ] : for image in image_mgr . list_private_images ( name = name , mask = image_mod . MASK ) : images . append ( image ) if public in [ True , None ] : for image in image_mgr . list_public_images ( name = name , mask = image_mod . MASK ) : images . append ( image ) table = formatting . Table ( [ 'id' , 'name' , 'type' , 'visibility' , 'account' ] ) images = [ image for image in images if image [ 'parentId' ] == '' ] for image in images : visibility = ( image_mod . PUBLIC_TYPE if image [ 'publicFlag' ] else image_mod . PRIVATE_TYPE ) table . add_row ( [ image . get ( 'id' , formatting . blank ( ) ) , formatting . FormattedItem ( image [ 'name' ] , click . wrap_text ( image [ 'name' ] , width = 50 ) ) , formatting . FormattedItem ( utils . lookup ( image , 'imageType' , 'keyName' ) , utils . lookup ( image , 'imageType' , 'name' ) ) , visibility , image . get ( 'accountId' , formatting . blank ( ) ) , ] ) env . fout ( table ) | List images . |
45,723 | def cli ( env , context_id , subnet_id , subnet_type , network_identifier ) : create_remote = False if subnet_id is None : if network_identifier is None : raise ArgumentError ( 'Either a network identifier or subnet id ' 'must be provided.' ) if subnet_type != 'remote' : raise ArgumentError ( 'Unable to create {} subnets' . format ( subnet_type ) ) create_remote = True manager = SoftLayer . IPSECManager ( env . client ) context = manager . get_tunnel_context ( context_id ) if create_remote : subnet = manager . create_remote_subnet ( context [ 'accountId' ] , identifier = network_identifier [ 0 ] , cidr = network_identifier [ 1 ] ) subnet_id = subnet [ 'id' ] env . out ( 'Created subnet {}/{} #{}' . format ( network_identifier [ 0 ] , network_identifier [ 1 ] , subnet_id ) ) succeeded = False if subnet_type == 'internal' : succeeded = manager . add_internal_subnet ( context_id , subnet_id ) elif subnet_type == 'remote' : succeeded = manager . add_remote_subnet ( context_id , subnet_id ) elif subnet_type == 'service' : succeeded = manager . add_service_subnet ( context_id , subnet_id ) if succeeded : env . out ( 'Added {} subnet #{}' . format ( subnet_type , subnet_id ) ) else : raise CLIHalt ( 'Failed to add {} subnet #{}' . format ( subnet_type , subnet_id ) ) | Add a subnet to an IPSEC tunnel context . |
45,724 | def cli ( env ) : manager = PlacementManager ( env . client ) result = manager . list ( ) table = formatting . Table ( [ "Id" , "Name" , "Backend Router" , "Rule" , "Guests" , "Created" ] , title = "Placement Groups" ) for group in result : table . add_row ( [ group [ 'id' ] , group [ 'name' ] , group [ 'backendRouter' ] [ 'hostname' ] , group [ 'rule' ] [ 'name' ] , group [ 'guestCount' ] , group [ 'createDate' ] ] ) env . fout ( table ) | List placement groups . |
45,725 | def cli ( env , ack_all ) : manager = AccountManager ( env . client ) events = manager . get_upcoming_events ( ) if ack_all : for event in events : result = manager . ack_event ( event [ 'id' ] ) event [ 'acknowledgedFlag' ] = result env . fout ( event_table ( events ) ) | Summary and acknowledgement of upcoming and ongoing maintenance events |
45,726 | def event_table ( events ) : table = formatting . Table ( [ "Id" , "Start Date" , "End Date" , "Subject" , "Status" , "Acknowledged" , "Updates" , "Impacted Resources" ] , title = "Upcoming Events" ) table . align [ 'Subject' ] = 'l' table . align [ 'Impacted Resources' ] = 'l' for event in events : table . add_row ( [ event . get ( 'id' ) , utils . clean_time ( event . get ( 'startDate' ) ) , utils . clean_time ( event . get ( 'endDate' ) ) , utils . clean_splitlines ( event . get ( 'subject' ) ) , utils . lookup ( event , 'statusCode' , 'name' ) , event . get ( 'acknowledgedFlag' ) , event . get ( 'updateCount' ) , event . get ( 'impactedResourceCount' ) ] ) return table | Formats a table for events |
45,727 | def cli ( env , access_id , password ) : block_manager = SoftLayer . BlockStorageManager ( env . client ) result = block_manager . set_credential_password ( access_id = access_id , password = password ) if result : click . echo ( 'Password updated for %s' % access_id ) else : click . echo ( 'FAILED updating password for %s' % access_id ) | Changes a password for a volume s access . |
45,728 | def cli ( env , account_id ) : manager = SoftLayer . CDNManager ( env . client ) account = manager . get_account ( account_id ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , account [ 'id' ] ] ) table . add_row ( [ 'account_name' , account [ 'cdnAccountName' ] ] ) table . add_row ( [ 'type' , account [ 'cdnSolutionName' ] ] ) table . add_row ( [ 'status' , account [ 'status' ] [ 'name' ] ] ) table . add_row ( [ 'created' , account [ 'createDate' ] ] ) table . add_row ( [ 'notes' , account . get ( 'cdnAccountNote' , formatting . blank ( ) ) ] ) env . fout ( table ) | Detail a CDN Account . |
45,729 | def lookup ( dic , key , * keys ) : if keys : return lookup ( dic . get ( key , { } ) , keys [ 0 ] , * keys [ 1 : ] ) return dic . get ( key ) | A generic dictionary access helper . |
45,730 | def query_filter ( query ) : try : return { 'operation' : int ( query ) } except ValueError : pass if isinstance ( query , string_types ) : query = query . strip ( ) for operation in KNOWN_OPERATIONS : if query . startswith ( operation ) : query = "%s %s" % ( operation , query [ len ( operation ) : ] . strip ( ) ) return { 'operation' : query } if query . startswith ( '*' ) and query . endswith ( '*' ) : query = "*= %s" % query . strip ( '*' ) elif query . startswith ( '*' ) : query = "$= %s" % query . strip ( '*' ) elif query . endswith ( '*' ) : query = "^= %s" % query . strip ( '*' ) else : query = "_= %s" % query return { 'operation' : query } | Translate a query - style string to a filter . |
45,731 | def query_filter_date ( start , end ) : sdate = datetime . datetime . strptime ( start , "%Y-%m-%d" ) edate = datetime . datetime . strptime ( end , "%Y-%m-%d" ) startdate = "%s/%s/%s" % ( sdate . month , sdate . day , sdate . year ) enddate = "%s/%s/%s" % ( edate . month , edate . day , edate . year ) return { 'operation' : 'betweenDate' , 'options' : [ { 'name' : 'startDate' , 'value' : [ startdate + ' 0:0:0' ] } , { 'name' : 'endDate' , 'value' : [ enddate + ' 0:0:0' ] } ] } | Query filters given start and end date . |
45,732 | def format_event_log_date ( date_string , utc ) : user_date_format = "%m/%d/%Y" user_date = datetime . datetime . strptime ( date_string , user_date_format ) dirty_time = user_date . isoformat ( ) if utc is None : utc = "+0000" iso_time_zone = utc [ : 3 ] + ':' + utc [ 3 : ] cleaned_time = "{}.000000{}" . format ( dirty_time , iso_time_zone ) return cleaned_time | Gets a date in the format that the SoftLayer_EventLog object likes . |
45,733 | def event_log_filter_between_date ( start , end , utc ) : return { 'operation' : 'betweenDate' , 'options' : [ { 'name' : 'startDate' , 'value' : [ format_event_log_date ( start , utc ) ] } , { 'name' : 'endDate' , 'value' : [ format_event_log_date ( end , utc ) ] } ] } | betweenDate Query filter that SoftLayer_EventLog likes |
45,734 | def resolve_ids ( identifier , resolvers ) : try : return [ int ( identifier ) ] except ValueError : pass if len ( identifier ) == 36 and UUID_RE . match ( identifier ) : return [ identifier ] for resolver in resolvers : ids = resolver ( identifier ) if ids : return ids return [ ] | Resolves IDs given a list of functions . |
45,735 | def is_ready ( instance , pending = False ) : last_reload = lookup ( instance , 'lastOperatingSystemReload' , 'id' ) active_transaction = lookup ( instance , 'activeTransaction' , 'id' ) reloading = all ( ( active_transaction , last_reload , last_reload == active_transaction , ) ) outstanding = False if pending : outstanding = active_transaction if instance . get ( 'provisionDate' ) and not reloading and not outstanding : return True return False | Returns True if instance is ready to be used |
45,736 | def clean_time ( sltime , in_format = '%Y-%m-%dT%H:%M:%S%z' , out_format = '%Y-%m-%d %H:%M' ) : try : clean = datetime . datetime . strptime ( sltime , in_format ) return clean . strftime ( out_format ) except ValueError : return sltime | Easy way to format time strings |
45,737 | def to_dict ( self ) : return { key : val . to_dict ( ) if isinstance ( val , NestedDict ) else val for key , val in self . items ( ) } | Converts a NestedDict instance into a real dictionary . |
45,738 | def cli ( env , identifier ) : mgr = SoftLayer . FirewallManager ( env . client ) firewall_type , firewall_id = firewall . parse_id ( identifier ) if not ( env . skip_confirmations or formatting . confirm ( "This action will cancel a firewall from your " "account. Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if firewall_type in [ 'vs' , 'server' ] : mgr . cancel_firewall ( firewall_id , dedicated = False ) elif firewall_type == 'vlan' : mgr . cancel_firewall ( firewall_id , dedicated = True ) else : raise exceptions . CLIAbort ( 'Unknown firewall type: %s' % firewall_type ) env . fout ( 'Firewall with id %s is being cancelled!' % identifier ) | Cancels a firewall . |
45,739 | def cli ( env , label , in_file , key , note ) : if in_file is None and key is None : raise exceptions . ArgumentError ( 'Either [-f | --in-file] or [-k | --key] arguments are required to add a key' ) if in_file and key : raise exceptions . ArgumentError ( '[-f | --in-file] is not allowed with [-k | --key]' ) if key : key_text = key else : key_file = open ( path . expanduser ( in_file ) , 'rU' ) key_text = key_file . read ( ) . strip ( ) key_file . close ( ) mgr = SoftLayer . SshKeyManager ( env . client ) result = mgr . add_key ( key_text , label , note ) env . fout ( "SSH key added: %s" % result . get ( 'fingerprint' ) ) | Add a new SSH key . |
45,740 | def cli ( env ) : mgr = SoftLayer . NetworkManager ( env . client ) result = mgr . get_rwhois ( ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'Name' , result [ 'firstName' ] + ' ' + result [ 'lastName' ] ] ) table . add_row ( [ 'Company' , result [ 'companyName' ] ] ) table . add_row ( [ 'Abuse Email' , result [ 'abuseEmail' ] ] ) table . add_row ( [ 'Address 1' , result [ 'address1' ] ] ) if result . get ( 'address2' ) : table . add_row ( [ 'Address 2' , result [ 'address2' ] ] ) table . add_row ( [ 'City' , result [ 'city' ] ] ) table . add_row ( [ 'State' , result . get ( 'state' , '-' ) ] ) table . add_row ( [ 'Postal Code' , result . get ( 'postalCode' , '-' ) ] ) table . add_row ( [ 'Country' , result [ 'country' ] ] ) table . add_row ( [ 'Private Residence' , result [ 'privateResidenceFlag' ] ] ) env . fout ( table ) | Display the RWhois information for your account . |
45,741 | def cli ( env , context_id , static_ip , remote_ip , note ) : manager = SoftLayer . IPSECManager ( env . client ) manager . get_tunnel_context ( context_id ) translation = manager . create_translation ( context_id , static_ip = static_ip , remote_ip = remote_ip , notes = note ) env . out ( 'Created translation from {} to {} #{}' . format ( static_ip , remote_ip , translation [ 'id' ] ) ) | Add an address translation to an IPSEC tunnel context . |
45,742 | def cli ( env , status , sortby ) : manager = SoftLayer . SSLManager ( env . client ) certificates = manager . list_certs ( status ) table = formatting . Table ( [ 'id' , 'common_name' , 'days_until_expire' , 'notes' ] ) for certificate in certificates : table . add_row ( [ certificate [ 'id' ] , certificate [ 'commonName' ] , certificate [ 'validityDays' ] , certificate . get ( 'notes' , formatting . blank ( ) ) ] ) table . sortby = sortby env . fout ( table ) | List SSL certificates . |
45,743 | def cli ( env ) : mgr = SoftLayer . LoadBalancerManager ( env . client ) hc_types = mgr . get_hc_types ( ) table = formatting . KeyValueTable ( [ 'ID' , 'Name' ] ) table . align [ 'ID' ] = 'l' table . align [ 'Name' ] = 'l' table . sortby = 'ID' for hc_type in hc_types : table . add_row ( [ hc_type [ 'id' ] , hc_type [ 'name' ] ] ) env . fout ( table ) | List health check types . |
45,744 | def cli ( env , identifier ) : mgr = SoftLayer . ObjectStorageManager ( env . client ) credential_limit = mgr . limit_credential ( identifier ) table = formatting . Table ( [ 'limit' ] ) table . add_row ( [ credential_limit , ] ) env . fout ( table ) | Credential limits for this IBM Cloud Object Storage account . |
45,745 | def cli ( env , context_id , include ) : mask = _get_tunnel_context_mask ( ( 'at' in include ) , ( 'is' in include ) , ( 'rs' in include ) , ( 'sr' in include ) , ( 'ss' in include ) ) manager = SoftLayer . IPSECManager ( env . client ) context = manager . get_tunnel_context ( context_id , mask = mask ) env . out ( 'Context Details:' ) env . fout ( _get_context_table ( context ) ) for relation in include : if relation == 'at' : env . out ( 'Address Translations:' ) env . fout ( _get_address_translations_table ( context . get ( 'addressTranslations' , [ ] ) ) ) elif relation == 'is' : env . out ( 'Internal Subnets:' ) env . fout ( _get_subnets_table ( context . get ( 'internalSubnets' , [ ] ) ) ) elif relation == 'rs' : env . out ( 'Remote Subnets:' ) env . fout ( _get_subnets_table ( context . get ( 'customerSubnets' , [ ] ) ) ) elif relation == 'sr' : env . out ( 'Static Subnets:' ) env . fout ( _get_subnets_table ( context . get ( 'staticRouteSubnets' , [ ] ) ) ) elif relation == 'ss' : env . out ( 'Service Subnets:' ) env . fout ( _get_subnets_table ( context . get ( 'serviceSubnets' , [ ] ) ) ) | List IPSEC VPN tunnel context details . |
45,746 | def _get_address_translations_table ( address_translations ) : table = formatting . Table ( [ 'id' , 'static IP address' , 'static IP address id' , 'remote IP address' , 'remote IP address id' , 'note' ] ) for address_translation in address_translations : table . add_row ( [ address_translation . get ( 'id' , '' ) , address_translation . get ( 'internalIpAddressRecord' , { } ) . get ( 'ipAddress' , '' ) , address_translation . get ( 'internalIpAddressId' , '' ) , address_translation . get ( 'customerIpAddressRecord' , { } ) . get ( 'ipAddress' , '' ) , address_translation . get ( 'customerIpAddressId' , '' ) , address_translation . get ( 'notes' , '' ) ] ) return table | Yields a formatted table to print address translations . |
45,747 | def _get_subnets_table ( subnets ) : table = formatting . Table ( [ 'id' , 'network identifier' , 'cidr' , 'note' ] ) for subnet in subnets : table . add_row ( [ subnet . get ( 'id' , '' ) , subnet . get ( 'networkIdentifier' , '' ) , subnet . get ( 'cidr' , '' ) , subnet . get ( 'note' , '' ) ] ) return table | Yields a formatted table to print subnet details . |
45,748 | def _get_tunnel_context_mask ( address_translations = False , internal_subnets = False , remote_subnets = False , static_subnets = False , service_subnets = False ) : entries = [ 'id' , 'accountId' , 'advancedConfigurationFlag' , 'createDate' , 'customerPeerIpAddress' , 'modifyDate' , 'name' , 'friendlyName' , 'internalPeerIpAddress' , 'phaseOneAuthentication' , 'phaseOneDiffieHellmanGroup' , 'phaseOneEncryption' , 'phaseOneKeylife' , 'phaseTwoAuthentication' , 'phaseTwoDiffieHellmanGroup' , 'phaseTwoEncryption' , 'phaseTwoKeylife' , 'phaseTwoPerfectForwardSecrecy' , 'presharedKey' ] if address_translations : entries . append ( 'addressTranslations[internalIpAddressRecord[ipAddress],' 'customerIpAddressRecord[ipAddress]]' ) if internal_subnets : entries . append ( 'internalSubnets' ) if remote_subnets : entries . append ( 'customerSubnets' ) if static_subnets : entries . append ( 'staticRouteSubnets' ) if service_subnets : entries . append ( 'serviceSubnets' ) return '[mask[{}]]' . format ( ',' . join ( entries ) ) | Yields a mask object for a tunnel context . |
45,749 | def _get_context_table ( context ) : table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , context . get ( 'id' , '' ) ] ) table . add_row ( [ 'name' , context . get ( 'name' , '' ) ] ) table . add_row ( [ 'friendly name' , context . get ( 'friendlyName' , '' ) ] ) table . add_row ( [ 'internal peer IP address' , context . get ( 'internalPeerIpAddress' , '' ) ] ) table . add_row ( [ 'remote peer IP address' , context . get ( 'customerPeerIpAddress' , '' ) ] ) table . add_row ( [ 'advanced configuration flag' , context . get ( 'advancedConfigurationFlag' , '' ) ] ) table . add_row ( [ 'preshared key' , context . get ( 'presharedKey' , '' ) ] ) table . add_row ( [ 'phase 1 authentication' , context . get ( 'phaseOneAuthentication' , '' ) ] ) table . add_row ( [ 'phase 1 diffie hellman group' , context . get ( 'phaseOneDiffieHellmanGroup' , '' ) ] ) table . add_row ( [ 'phase 1 encryption' , context . get ( 'phaseOneEncryption' , '' ) ] ) table . add_row ( [ 'phase 1 key life' , context . get ( 'phaseOneKeylife' , '' ) ] ) table . add_row ( [ 'phase 2 authentication' , context . get ( 'phaseTwoAuthentication' , '' ) ] ) table . add_row ( [ 'phase 2 diffie hellman group' , context . get ( 'phaseTwoDiffieHellmanGroup' , '' ) ] ) table . add_row ( [ 'phase 2 encryption' , context . get ( 'phaseTwoEncryption' , '' ) ] ) table . add_row ( [ 'phase 2 key life' , context . get ( 'phaseTwoKeylife' , '' ) ] ) table . add_row ( [ 'phase 2 perfect forward secrecy' , context . get ( 'phaseTwoPerfectForwardSecrecy' , '' ) ] ) table . add_row ( [ 'created' , context . get ( 'createDate' ) ] ) table . add_row ( [ 'modified' , context . get ( 'modifyDate' ) ] ) return table | Yields a formatted table to print context details . |
45,750 | def cli ( env , volume_id , replicant_id , immediate ) : file_storage_manager = SoftLayer . FileStorageManager ( env . client ) success = file_storage_manager . failover_to_replicant ( volume_id , replicant_id , immediate ) if success : click . echo ( "Failover to replicant is now in progress." ) else : click . echo ( "Failover operation could not be initiated." ) | Failover a file volume to the given replicant volume . |
45,751 | def cli ( env , sortby , datacenter ) : file_manager = SoftLayer . FileStorageManager ( env . client ) mask = "mask[serviceResource[datacenter[name]]," "replicationPartners[serviceResource[datacenter[name]]]]" file_volumes = file_manager . list_file_volumes ( datacenter = datacenter , mask = mask ) datacenters = dict ( ) for volume in file_volumes : service_resource = volume [ 'serviceResource' ] if 'datacenter' in service_resource : datacenter_name = service_resource [ 'datacenter' ] [ 'name' ] if datacenter_name not in datacenters . keys ( ) : datacenters [ datacenter_name ] = 1 else : datacenters [ datacenter_name ] += 1 table = formatting . KeyValueTable ( DEFAULT_COLUMNS ) table . sortby = sortby for datacenter_name in datacenters : table . add_row ( [ datacenter_name , datacenters [ datacenter_name ] ] ) env . fout ( table ) | List number of file storage volumes per datacenter . |
45,752 | def cli ( env ) : hardware_manager = hardware . HardwareManager ( env . client ) options = hardware_manager . get_create_options ( ) tables = [ ] dc_table = formatting . Table ( [ 'datacenter' , 'value' ] ) dc_table . sortby = 'value' for location in options [ 'locations' ] : dc_table . add_row ( [ location [ 'name' ] , location [ 'key' ] ] ) tables . append ( dc_table ) preset_table = formatting . Table ( [ 'size' , 'value' ] ) preset_table . sortby = 'value' for size in options [ 'sizes' ] : preset_table . add_row ( [ size [ 'name' ] , size [ 'key' ] ] ) tables . append ( preset_table ) os_table = formatting . Table ( [ 'operating_system' , 'value' ] ) os_table . sortby = 'value' for operating_system in options [ 'operating_systems' ] : os_table . add_row ( [ operating_system [ 'name' ] , operating_system [ 'key' ] ] ) tables . append ( os_table ) port_speed_table = formatting . Table ( [ 'port_speed' , 'value' ] ) port_speed_table . sortby = 'value' for speed in options [ 'port_speeds' ] : port_speed_table . add_row ( [ speed [ 'name' ] , speed [ 'key' ] ] ) tables . append ( port_speed_table ) extras_table = formatting . Table ( [ 'extras' , 'value' ] ) extras_table . sortby = 'value' for extra in options [ 'extras' ] : extras_table . add_row ( [ extra [ 'name' ] , extra [ 'key' ] ] ) tables . append ( extras_table ) env . fout ( formatting . listing ( tables , separator = '\n' ) ) | Server order options for a given chassis . |
45,753 | def parse_id ( input_id ) : key_value = input_id . split ( ':' ) if len ( key_value ) != 2 : raise exceptions . CLIAbort ( 'Invalid ID %s: ID should be of the form xxx:yyy' % input_id ) return key_value [ 0 ] , int ( key_value [ 1 ] ) | Helper package to retrieve the actual IDs . |
45,754 | def _build_filters ( _filters ) : root = utils . NestedDict ( { } ) for _filter in _filters : operation = None for operation , token in SPLIT_TOKENS : top_parts = _filter . split ( token , 1 ) if len ( top_parts ) == 2 : break else : raise exceptions . CLIAbort ( 'Failed to find valid operation for: %s' % _filter ) key , value = top_parts current = root parts = [ part . strip ( ) for part in key . split ( '.' ) ] for part in parts [ : - 1 ] : current = current [ part ] if operation == 'eq' : current [ parts [ - 1 ] ] = utils . query_filter ( value . strip ( ) ) elif operation == 'in' : current [ parts [ - 1 ] ] = { 'operation' : 'in' , 'options' : [ { 'name' : 'data' , 'value' : [ p . strip ( ) for p in value . split ( ',' ) ] , } ] , } return root . to_dict ( ) | Builds filters using the filter options passed into the CLI . |
45,755 | def cli ( env , service , method , parameters , _id , _filters , mask , limit , offset , output_python = False ) : args = [ service , method ] + list ( parameters ) kwargs = { 'id' : _id , 'filter' : _build_filters ( _filters ) , 'mask' : mask , 'limit' : limit , 'offset' : offset , } if output_python : env . out ( _build_python_example ( args , kwargs ) ) else : result = env . client . call ( * args , ** kwargs ) env . fout ( formatting . iter_to_table ( result ) ) | Call arbitrary API endpoints with the given SERVICE and METHOD . |
45,756 | def cli ( env , volume_id , sortby , columns ) : block_manager = SoftLayer . BlockStorageManager ( env . client ) snapshots = block_manager . get_block_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 block storage snapshots . |
45,757 | def cli ( env , package_keyname , location , preset , verify , billing , complex_type , quantity , extras , order_items ) : manager = ordering . OrderingManager ( env . client ) if extras : try : extras = json . loads ( extras ) except ValueError as err : raise exceptions . CLIAbort ( "There was an error when parsing the --extras value: {}" . format ( err ) ) args = ( package_keyname , location , order_items ) kwargs = { 'preset_keyname' : preset , 'extras' : extras , 'quantity' : quantity , 'complex_type' : complex_type , 'hourly' : bool ( billing == 'hourly' ) } if verify : table = formatting . Table ( COLUMNS ) order_to_place = manager . verify_order ( * args , ** kwargs ) for price in order_to_place [ 'orderContainers' ] [ 0 ] [ 'prices' ] : cost_key = 'hourlyRecurringFee' if billing == 'hourly' else 'recurringFee' table . add_row ( [ price [ 'item' ] [ 'keyName' ] , price [ 'item' ] [ 'description' ] , price [ cost_key ] if cost_key in price else formatting . blank ( ) ] ) else : if not ( env . skip_confirmations or formatting . confirm ( "This action will incur charges on your account. Continue?" ) ) : raise exceptions . CLIAbort ( "Aborting order." ) order = manager . place_order ( * args , ** kwargs ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , order [ 'orderId' ] ] ) table . add_row ( [ 'created' , order [ 'orderDate' ] ] ) table . add_row ( [ 'status' , order [ 'placedOrder' ] [ 'status' ] ] ) env . fout ( table ) | Place or verify an order . |
45,758 | def cli ( env , identifier , label , note ) : mgr = SoftLayer . SshKeyManager ( env . client ) key_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'SshKey' ) if not mgr . edit_key ( key_id , label = label , notes = note ) : raise exceptions . CLIAbort ( 'Failed to edit SSH key' ) | Edits an SSH key . |
45,759 | def cli ( env , securitygroup_id ) : mgr = SoftLayer . NetworkManager ( env . client ) if not mgr . delete_securitygroup ( securitygroup_id ) : raise exceptions . CLIAbort ( "Failed to delete security group" ) | Deletes the given security group |
45,760 | def cli ( env , ipv6 , test ) : mgr = SoftLayer . NetworkManager ( env . client ) version = 4 if ipv6 : version = 6 if not ( test or env . skip_confirmations ) : if not formatting . confirm ( "This action will incur charges on your " "account. Continue?" ) : raise exceptions . CLIAbort ( 'Cancelling order.' ) result = mgr . add_global_ip ( version = version , test_order = test ) table = formatting . Table ( [ 'item' , 'cost' ] ) table . align [ 'Item' ] = 'r' table . align [ 'cost' ] = 'r' total = 0.0 for price in result [ 'orderDetails' ] [ 'prices' ] : total += float ( price . get ( 'recurringFee' , 0.0 ) ) rate = "%.2f" % float ( price [ 'recurringFee' ] ) table . add_row ( [ price [ 'item' ] [ 'description' ] , rate ] ) table . add_row ( [ 'Total monthly cost' , "%.2f" % total ] ) env . fout ( table ) | Creates a global IP . |
45,761 | def cli ( env , context_id , translation_id ) : manager = SoftLayer . IPSECManager ( env . client ) manager . get_translation ( context_id , translation_id ) succeeded = manager . remove_translation ( context_id , translation_id ) if succeeded : env . out ( 'Removed translation #{}' . format ( translation_id ) ) else : raise CLIHalt ( 'Failed to remove translation #{}' . format ( translation_id ) ) | Remove a translation entry from an IPSEC tunnel context . |
45,762 | def cli ( env , sortby , cpu , domain , datacenter , hostname , memory , network , hourly , monthly , tag , columns , limit ) : vsi = SoftLayer . VSManager ( env . client ) guests = vsi . list_instances ( hourly = hourly , monthly = monthly , hostname = hostname , domain = domain , cpus = cpu , memory = memory , datacenter = datacenter , nic_speed = network , tags = tag , mask = columns . mask ( ) , limit = limit ) table = formatting . Table ( columns . columns ) table . sortby = sortby for guest in guests : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( guest ) ] ) env . fout ( table ) | List virtual servers . |
45,763 | def cli ( env , identifier ) : mgr = SoftLayer . SshKeyManager ( env . client ) key_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'SshKey' ) if not ( env . skip_confirmations or formatting . no_going_back ( key_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) mgr . delete_key ( key_id ) | Permanently removes an SSH key . |
45,764 | def format_output ( data , fmt = 'table' ) : if isinstance ( data , utils . string_types ) : if fmt in ( 'json' , 'jsonraw' ) : return json . dumps ( data ) return data if hasattr ( data , 'prettytable' ) : if fmt == 'table' : return str ( format_prettytable ( data ) ) elif fmt == 'raw' : return str ( format_no_tty ( data ) ) if hasattr ( data , 'to_python' ) : if fmt == 'json' : return json . dumps ( format_output ( data , fmt = 'python' ) , indent = 4 , cls = CLIJSONEncoder ) elif fmt == 'jsonraw' : return json . dumps ( format_output ( data , fmt = 'python' ) , cls = CLIJSONEncoder ) elif fmt == 'python' : return data . to_python ( ) if hasattr ( data , 'formatted' ) : if fmt == 'table' : return data . formatted if hasattr ( data , 'separator' ) : output = [ format_output ( d , fmt = fmt ) for d in data if d ] return str ( SequentialOutput ( data . separator , output ) ) if isinstance ( data , list ) or isinstance ( data , tuple ) : output = [ format_output ( d , fmt = fmt ) for d in data ] if fmt == 'python' : return output return format_output ( listing ( output , separator = os . linesep ) ) return data | Given some data will format it for console output . |
45,765 | def transaction_status ( transaction ) : if not transaction or not transaction . get ( 'transactionStatus' ) : return blank ( ) return FormattedItem ( transaction [ 'transactionStatus' ] . get ( 'name' ) , transaction [ 'transactionStatus' ] . get ( 'friendlyName' ) ) | Returns a FormattedItem describing the given transaction . |
45,766 | def tags ( tag_references ) : if not tag_references : return blank ( ) tag_row = [ ] for tag_detail in tag_references : tag = utils . lookup ( tag_detail , 'tag' , 'name' ) if tag is not None : tag_row . append ( tag ) return listing ( tag_row , separator = ', ' ) | Returns a formatted list of tags . |
45,767 | def confirm ( prompt_str , default = False ) : if default : default_str = 'y' prompt = '%s [Y/n]' % prompt_str else : default_str = 'n' prompt = '%s [y/N]' % prompt_str ans = click . prompt ( prompt , default = default_str , show_default = False ) if ans . lower ( ) in ( 'y' , 'yes' , 'yeah' , 'yup' , 'yolo' ) : return True return False | Show a confirmation prompt to a command - line user . |
45,768 | def no_going_back ( confirmation ) : if not confirmation : confirmation = 'yes' prompt = ( 'This action cannot be undone! Type "%s" or press Enter ' 'to abort' % confirmation ) ans = click . prompt ( prompt , default = '' , show_default = False ) if ans . lower ( ) == str ( confirmation ) : return True return False | Show a confirmation to a user . |
45,769 | def iter_to_table ( value ) : if isinstance ( value , list ) : return _format_list ( value ) if isinstance ( value , dict ) : return _format_dict ( value ) return value | Convert raw API responses to response tables . |
45,770 | def _format_dict ( result ) : table = KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' for key , value in result . items ( ) : value = iter_to_table ( value ) table . add_row ( [ key , value ] ) return table | Format dictionary responses into key - value table . |
45,771 | def _format_list ( result ) : if not result : return result if isinstance ( result [ 0 ] , dict ) : return _format_list_objects ( result ) table = Table ( [ 'value' ] ) for item in result : table . add_row ( [ iter_to_table ( item ) ] ) return table | Format list responses into a table . |
45,772 | def _format_list_objects ( result ) : all_keys = set ( ) for item in result : all_keys = all_keys . union ( item . keys ( ) ) all_keys = sorted ( all_keys ) table = Table ( all_keys ) for item in result : values = [ ] for key in all_keys : value = iter_to_table ( item . get ( key ) ) values . append ( value ) table . add_row ( values ) return table | Format list of objects into a table . |
45,773 | def to_python ( self ) : items = [ ] for row in self . rows : formatted_row = [ _format_python_value ( v ) for v in row ] items . append ( dict ( zip ( self . columns , formatted_row ) ) ) return items | Decode this Table object to standard Python types . |
45,774 | def prettytable ( self ) : table = prettytable . PrettyTable ( self . columns ) if self . sortby : if self . sortby in self . columns : table . sortby = self . sortby else : msg = "Column (%s) doesn't exist to sort by" % self . sortby raise exceptions . CLIAbort ( msg ) for a_col , alignment in self . align . items ( ) : table . align [ a_col ] = alignment if self . title : table . title = self . title for row in self . rows : table . add_row ( row ) return table | Returns a new prettytable instance . |
45,775 | def to_python ( self ) : mapping = { } for row in self . rows : mapping [ row [ 0 ] ] = _format_python_value ( row [ 1 ] ) return mapping | Decode this KeyValueTable object to standard Python types . |
45,776 | def cli ( env , username , email , password , from_user , template , api_key ) : mgr = SoftLayer . UserManager ( env . client ) user_mask = ( "mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, " "state, userStatusId, timezoneId]" ) from_user_id = None if from_user is None : user_template = mgr . get_current_user ( objectmask = user_mask ) from_user_id = user_template [ 'id' ] else : from_user_id = helpers . resolve_id ( mgr . resolve_ids , from_user , 'username' ) user_template = mgr . get_user ( from_user_id , objectmask = user_mask ) del user_template [ 'id' ] if template is not None : try : template_object = json . loads ( template ) for key in template_object : user_template [ key ] = template_object [ key ] except ValueError as ex : raise exceptions . ArgumentError ( "Unable to parse --template. %s" % ex ) user_template [ 'username' ] = username if password == 'generate' : password = generate_password ( ) user_template [ 'email' ] = email if not env . skip_confirmations : table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) for key in user_template : table . add_row ( [ key , user_template [ key ] ] ) table . add_row ( [ 'password' , password ] ) click . secho ( "You are about to create the following user..." , fg = 'green' ) env . fout ( table ) if not formatting . confirm ( "Do you wish to continue?" ) : raise exceptions . CLIAbort ( "Canceling creation!" ) result = mgr . create_user ( user_template , password ) new_api_key = None if api_key : click . secho ( "Adding API key..." , fg = 'green' ) new_api_key = mgr . add_api_authentication_key ( result [ 'id' ] ) table = formatting . Table ( [ 'Username' , 'Email' , 'Password' , 'API Key' ] ) table . add_row ( [ result [ 'username' ] , result [ 'email' ] , password , new_api_key ] ) env . fout ( table ) | Creates a user Users . |
45,777 | def generate_password ( ) : if sys . version_info > ( 3 , 6 ) : import secrets 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 |
45,778 | 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 |
45,779 | 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 . |
45,780 | 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 . |
45,781 | def _get_bandwidth_price_id ( items , hourly = True , no_public = False , location = None ) : for item in items : capacity = float ( item . get ( 'capacity' , 0 ) ) 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 . |
45,782 | 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 . |
45,783 | 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 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 . |
45,784 | def _matches_location ( price , location ) : if not price . get ( 'locationGroupId' ) : return True 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 . |
45,785 | 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 . |
45,786 | 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 . |
45,787 | def cancel_hardware ( self , hardware_id , reason = 'unneeded' , comment = '' , immediate = False ) : 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 . |
45,788 | 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,' 'hardwareChassis[id,name],' 'activeTransaction[id, transactionStatus[friendlyName,name]],' '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 . |
45,789 | 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 . |
45,790 | 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 . |
45,791 | 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 . |
45,792 | 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 . |
45,793 | def get_create_options ( self ) : package = self . _get_package ( ) locations = [ ] for region in package [ 'regions' ] : locations . append ( { 'name' : region [ 'location' ] [ 'location' ] [ 'longName' ] , 'key' : region [ 'location' ] [ 'location' ] [ 'name' ] , } ) sizes = [ ] for preset in package [ 'activePresets' ] + package [ 'accountRestrictedActivePresets' ] : sizes . append ( { 'name' : preset [ 'description' ] , 'key' : preset [ 'keyName' ] } ) 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 = [ ] for item in package [ 'items' ] : if all ( [ item [ 'itemCategory' ] [ 'categoryCode' ] == 'port_speed' , not _is_private_port_speed_item ( item ) , _is_bonded ( item ) ] ) : port_speeds . append ( { 'name' : item [ 'description' ] , 'key' : item [ 'capacity' ] , } ) 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 . |
45,794 | def _get_package ( self ) : mask = 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 . |
45,795 | 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 . |
45,796 | 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 . |
45,797 | def _get_ids_from_ip ( self , ip ) : try : socket . inet_aton ( ip ) except socket . error : return [ ] 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 . |
45,798 | 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 . |
45,799 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.