def testEq(self): config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) config_file_2 = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path_2) config_file3 = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) self.assertNotEqual(config_file, config_file_2) self.assertEqual(config_file, config_file3)
def testSetMatchingItemWithPersist(self): # copy config to a temp directory config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) temp_config_path = self.Touch(self.temp_path, name='temp_config.yaml', contents=config_file.yaml) new_config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=temp_config_path) # mutate copied config and confirm temp file is changed on disk new_config_file.SetMatchingItemData( file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'testcluster-2', file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'updated_cluster') self.AssertFileContains('updated_cluster', temp_config_path)
def testEqLoadFromContents(self): # Read from file 1. config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) # Read from file 2. config_file_2 = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path_2) # Load from pre-read contents of file 1. config_file3 = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_contents=self.config_contents) self.assertNotEqual(config_file3, config_file_2) self.assertEqual(config_file3, config_file)
def testFileContentsProperty(self): # Read from file 1. config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_contents=self.config_contents, file_path=self.config_path) self.assertEqual(self.config_contents, config_file.file_contents)
def testFindMatchingItem(self): config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) found_config = config_file.FindMatchingItem( file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'testcluster-2')[0] self.assertEqual(found_config.GetPreferredAuth(), 'ldap2')
def GetPreferredAuthForCluster(cluster, config_file, force_update=False): """Get preferredAuthentication value for cluster.""" configs = file_parsers.YamlConfigFile(config_file, file_parsers.LoginConfigObject) cluster_config = _GetClusterConfig(configs, cluster) try: auth_method = cluster_config.GetPreferredAuth() except KeyError: auth_method = None except file_parsers.YamlConfigObjectFieldError: # gracefully quit for config versions older than v2alpha1 that # do not support 'preferredAuthentication' field. return None if not auth_method or force_update: prompt_message = ('Please select your preferred authentication option for ' 'cluster [{}]'.format(cluster)) override_warning = ('. Note: This will overwrite current preferred auth ' 'method [{}] in config file.') if auth_method and force_update: prompt_message = prompt_message + override_warning.format(auth_method) # do the prompting providers = cluster_config.GetAuthProviders() index = console_io.PromptChoice(providers, message=prompt_message, cancel_option=True) auth_method = providers[index] log.status.Print( 'Setting Preferred Authentication option to [{}]'.format(auth_method)) cluster_config.SetPreferredAuth(auth_method) configs.WriteToDisk() return auth_method
def testFindMatchingItemData(self): config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) found_clusters = config_file.FindMatchingItemData( file_parsers.LoginConfigObject.CLUSTER_NAME_KEY) self.assertCountEqual(found_clusters, ['testcluster-1', 'testcluster-2', 'testcluster-3'])
def testSetMatchingItem(self): config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) config_file.SetMatchingItemData( file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'testcluster-2', file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'updated_cluster', persist=False) self.assertIsNotNone(config_file.FindMatchingItem( file_parsers.LoginConfigObject.CLUSTER_NAME_KEY, 'updated_cluster'))
def GenerateMessageMappingFromFile(input_file): """Build apitools to krm mapping from a YAML/JSON File.""" config_file = file_parsers.YamlConfigFile(ApitoolsToKrmConfigObject, file_path=input_file) config_data = config_file.data[0] ValidateMessageMappingFile(config_data.content) request_type = config_data.apitools_request mapping = collections.OrderedDict() for msg_field, value in six.iteritems(config_data): mapping[msg_field] = ApitoolsToKrmFieldDescriptor.FromYamlData(msg_field, value) return request_type, mapping
def Run(self, args): # Get Hub memberships (cluster registered with Hub) from GCP Project. project = args.project or properties.VALUES.core.project.GetOrFail() memberships = base.ListMemberships(project) if not memberships: raise exceptions.Error('No Memberships available in Hub.') # Acquire membership. global membership # Prompt user for an existing hub membership if none is provided. if not args.membership: index = 0 if len(memberships) > 1: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to apply {}:\n'. format(args.config)) membership = memberships[index] sys.stderr.write('Selecting membership [{}].\n'.format(membership)) else: membership = args.membership if membership not in memberships: raise exceptions.Error( 'Membership {} is not in Hub.'.format(membership)) # Load config YAML file. loaded_config = file_parsers.YamlConfigFile( file_path=args.config, item_type=file_parsers.LoginConfigObject) # Create new identity service feature spec. client = core_apis.GetClientInstance('gkehub', 'v1alpha1') msg = client.MESSAGES_MODULE member_config = _parse_config(loaded_config, msg) # UpdateFeature uses the patch method to update member_configs map, hence # there's no need to get the existing feature spec. applied_config = msg.IdentityServiceFeatureSpec.MemberConfigsValue.AdditionalProperty( key=membership, value=member_config) m_configs = msg.IdentityServiceFeatureSpec.MemberConfigsValue( additionalProperties=[applied_config]) # Execute update to apply new identity service feature spec to membership. self.RunCommand( 'identityservice_feature_spec.member_configs', identityserviceFeatureSpec=msg.IdentityServiceFeatureSpec( memberConfigs=m_configs))
def Run(self, args): # Get fleet memberships (cluster registered with fleet) from GCP Project. memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') # Acquire membership. membership = None # Prompt user for an existing fleet membership if none is provided. if not args.membership: index = 0 if len(memberships) > 1: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to apply {}:\n'.format( args.config)) membership = memberships[index] sys.stderr.write('Selecting membership [{}].\n'.format(membership)) else: membership = args.membership if membership not in memberships: raise exceptions.Error( 'Membership {} is not in the fleet.'.format(membership)) # Load config YAML file. loaded_config = file_parsers.YamlConfigFile( file_path=args.config, item_type=file_parsers.LoginConfigObject) # Create new identity service feature spec. member_config = _parse_config(loaded_config, self.messages) # UpdateFeature uses the patch method to update member_configs map, hence # there's no need to get the existing feature spec. full_name = self.MembershipResourceName(membership) specs = { full_name: self.messages.MembershipFeatureSpec(identityservice=member_config) } feature = self.messages.Feature( membershipSpecs=self.hubclient.ToMembershipSpecs(specs)) # Execute update to apply new identity service feature spec to membership. self.Update(['membership_specs'], feature)
def testNoContentsNorFileProvided(self): with self.assertRaises(file_parsers.YamlConfigFileError): file_parsers.YamlConfigFile(item_type=file_parsers.LoginConfigObject)
def GetPreferredAuthForCluster( cluster, login_config, config_contents=None, force_update=False, is_url=False): """Get preferredAuthentication value for cluster.""" if not (cluster and login_config): return None, None, None configs = None # If URL, then pass contents directly. if is_url: if not config_contents: raise AnthosAuthException( 'Config contents were not passed with URL [{}]' .format(login_config)) configs = file_parsers.YamlConfigFile( file_contents=config_contents, item_type=file_parsers.LoginConfigObject) # If file, pass contents and location for updating. else: configs = file_parsers.YamlConfigFile( file_contents=config_contents, file_path=login_config, item_type=file_parsers.LoginConfigObject) cluster_config = _GetClusterConfig(configs, cluster) try: auth_method = cluster_config.GetPreferredAuth() except KeyError: auth_method = None except file_parsers.YamlConfigObjectFieldError: # gracefully quit for config versions older than v2alpha1 that # do not support 'preferredAuthentication' field. return None, None, None if not auth_method or force_update: providers = cluster_config.GetAuthProviders() if not providers: raise AnthosAuthException( 'No Authentication Providers found in [{}]'.format(login_config)) if len(providers) == 1: auth_method = providers.pop() else: # do the prompting prompt_message = ('Please select your preferred authentication option ' 'for cluster [{}]'.format(cluster)) override_warning = ('. Note: This will overwrite current preferred auth ' 'method [{}] in config file.') # Only print override warning in certain cases. if auth_method and force_update and not is_url: prompt_message = prompt_message + override_warning.format(auth_method) index = console_io.PromptChoice(providers, message=prompt_message, cancel_option=True) auth_method = providers[index] log.status.Print( 'Setting Preferred Authentication option to [{}]'.format(auth_method)) cluster_config.SetPreferredAuth(auth_method) # Only save to disk if file is specified. Don't want URL failure. if login_config and not is_url: configs.WriteToDisk() ldap_user, ldap_pass = _GetLdapUserAndPass(cluster_config, auth_method, cluster) return auth_method, ldap_user, ldap_pass
def testPathNotFound(self): # No file_contents provided. with self.assertRaises(file_parsers.YamlConfigFileError): file_parsers.YamlConfigFile(item_type=file_parsers.YamlConfigObject, file_path='NOT_FOUND')
def testItemType(self): config_file = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_path=self.config_path) self.assertEqual(config_file.item_type, file_parsers.LoginConfigObject)
def testWriteToDiskNoFilePath(self): with self.assertRaises(file_parsers.YamlConfigFileError): login_config = file_parsers.YamlConfigFile( item_type=file_parsers.LoginConfigObject, file_contents=self.config_contents) login_config.WriteToDisk()
def testURLWithNoContents(self): with self.assertRaises(file_parsers.YamlConfigFileError): file_parsers.YamlConfigFile(item_type=file_parsers.LoginConfigObject, file_path='http://www.example.com')