def Run(self, args): if not args.config_membership: memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') index = console_io.PromptChoice( options=memberships, message='Please specify a config membership:\n') config_membership = memberships[index] else: # Strip to the final path component to allow short and long names. # Assumes long names are for the same project and global location. # TODO(b/192580393): Use the resource args instead of this hack. config_membership = os.path.basename(args.config_membership) config_membership = self.MembershipResourceName(config_membership) # MCI requires MCSD. Enablement of the fleet feature for MCSD is taken care # of by CLH but we need to enable the OP API before that happens. If not, # CLH will return an error asking for the API to be enabled. mcsd_api = info.Get('multiclusterservicediscovery').api enable_api.EnableServiceIfDisabled(self.Project(), mcsd_api) f = self.messages.Feature( spec=self.messages.CommonFeatureSpec( multiclusteringress=self.messages.MultiClusterIngressFeatureSpec( configMembership=config_membership))) result = self.Enable(f) # We only want to poll for usability if everything above succeeded. if result is not None: self.PollForUsability()
def Run(self, args): log.warning( 'Are you sure you want to update your config membership? Any ' 'differences in your MCI and MCS resources between the old and ' 'new config membership can trigger load balancer updates which ' 'could cause traffic interruption.') console_io.PromptContinue(default=True, cancel_on_no=True) config_membership = args.config_membership if not config_membership: memberships = base.ListMemberships() if not memberships: raise exceptions.Error( 'No Memberships available in the fleet.') index = console_io.PromptChoice( options=memberships, message='Please specify a config membership:\n') config_membership = memberships[index] else: # Strip to the final path component to allow short and long names. # Assumes long names are for the same project and global location. # TODO(b/192580393): Use the resource args instead of this hack. config_membership = os.path.basename(args.config_membership) config_membership = self.MembershipResourceName(config_membership) f = self.messages.Feature(spec=self.messages.CommonFeatureSpec( multiclusteringress=self.messages.MultiClusterIngressFeatureSpec( configMembership=config_membership))) self.Update(['spec.multiclusteringress.config_membership'], f)
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 delete Identity Service {}:\n' ) 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)) # Setup a patch to set the MembershipSpec to the empty proto ("delete"). membership_key = self.MembershipResourceName(membership) specs = {membership_key: self.messages.MembershipFeatureSpec()} patch = self.messages.Feature( membershipSpecs=self.hubclient.ToMembershipSpecs(specs)) self.Update(['membership_specs'], patch)
def select_memberships(args): """Returns a list of memberships to which to apply the command, given the arguments. Args: args: object containing arguments passed as flags with the command Returns: memberships: A list of membership name strings """ memberships = [] all_memberships = base.ListMemberships() if args.all_memberships: memberships = all_memberships elif args.memberships: memberships = args.memberships.split(',') for membership in memberships: if membership not in all_memberships: raise exceptions.Error('Membership {} not found'.format(membership)) else: index = console_io.PromptChoice( options=all_memberships, message='Please specify a membership:\n') memberships = [all_memberships[index]] if not memberships: raise exceptions.Error('A membership is required for this command.') return memberships
def Run(self, args): memberships = feature_base.ListMemberships() f = self.GetFeature() if not memberships: return None acm_status = [] acm_errors = [] feature_spec_memberships = { util.MembershipShortname(m): s for m, s in self.hubclient.ToPyDict(f.membershipSpecs).items() if s is not None and s.configmanagement is not None } feature_state_memberships = { util.MembershipShortname(m): s for m, s in self.hubclient.ToPyDict(f.membershipStates).items() } for name in memberships: cluster = ConfigmanagementFeatureState(name) if name not in feature_state_memberships: if name in feature_spec_memberships: # (b/187846229) Show PENDING if feature spec is aware of # this membership name but feature state is not cluster.update_pending_state( feature_spec_memberships[name], None) acm_status.append(cluster) continue md = feature_state_memberships[name] fs = md.configmanagement # (b/153587485) Show FeatureState.code if it's not OK # as it indicates an unreachable cluster or a dated syncState.code if md.state is None or md.state.code is None: cluster.config_sync = 'CODE_UNSPECIFIED' elif md.state.code.name != 'OK': cluster.config_sync = md.state.code.name else: # operator errors could occur regardless of the deployment_state if has_operator_error(fs): append_error(name, fs.operatorState.errors, acm_errors) # (b/154174276, b/156293028) # check operator_state to see if ACM/nomos has been installed if not has_operator_state(fs): cluster.config_sync = 'OPERATOR_STATE_UNSPECIFIED' else: cluster.config_sync = fs.operatorState.deploymentState.name if cluster.config_sync == 'INSTALLED': cluster.update_sync_state(fs) if has_config_sync_error(fs): append_error(name, fs.configSyncState.syncState.errors, acm_errors) cluster.update_policy_controller_state(fs) cluster.update_hierarchy_controller_state(fs) if name in feature_spec_memberships: cluster.update_pending_state( feature_spec_memberships[name]. configmanagement, fs.membershipSpec) acm_status.append(cluster) return {'acm_errors': acm_errors, 'acm_status': acm_status}
def Run(self, args): # Get fleet memberships (cluster registered with fleet) from GCP Project. memberships = base.ListMemberships() response = self.GetFeature() if not memberships: log.status.Print('No Memberships available in the fleet.') return {} return {'Identity Service Feature': response}
def Run(self, args): # check static yaml fields before query membership try: loaded_cm = yaml.load_path(args.config) except yaml.Error as e: raise exceptions.Error( 'Invalid config yaml file {}'.format(args.config), e) _validate_meta(loaded_cm) # make sure a valid membership is selected memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') # User should choose an existing membership if not provide one membership = None if not args.membership: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to apply {}:\n'.format( args.config)) membership = memberships[index] else: membership = args.membership if membership not in memberships: raise exceptions.Error( 'Membership {} is not in the fleet.'.format(membership)) config_sync = _parse_config_sync(loaded_cm, self.messages) policy_controller = _parse_policy_controller(loaded_cm, self.messages) hierarchy_controller_config = _parse_hierarchy_controller_config( loaded_cm, self.messages) version = self._get_backfill_version( membership) if not args.version else args.version spec = self.messages.MembershipFeatureSpec( configmanagement=self.messages.ConfigManagementMembershipSpec( version=version, configSync=config_sync, policyController=policy_controller, hierarchyController=hierarchy_controller_config)) spec_map = {self.MembershipResourceName(membership): spec} # UpdateFeature uses patch method to update membership_configs map, # there's no need to get the existing feature spec patch = self.messages.Feature( membershipSpecs=self.hubclient.ToMembershipSpecs(spec_map)) self.Update(['membership_specs'], patch)
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 ParseMemberships(args): """Returns a list of memberships to which to apply the command, given the arguments. Args: args: object containing arguments passed as flags with the command Returns: memberships: A list of membership name strings """ memberships = [] all_memberships = base.ListMemberships() if not all_memberships: raise exceptions.Error('No Memberships available in the fleet.') if hasattr(args, 'membership') and args.membership: memberships.append(args.membership) elif args.memberships: memberships = args.memberships.split(',') else: if console_io.CanPrompt(): index = console_io.PromptChoice( options=all_memberships, message='Please specify a Membership:\n', cancel_option=True) memberships.append(all_memberships[index]) else: raise calliope_exceptions.RequiredArgumentException( '--membership', ('Cannot prompt a console for membership. Membership is required. ' 'Please specify `--memberships` to select at least one membership.')) if not memberships: raise exceptions.Error( 'At least one membership is required for this command.') for membership in memberships: if membership not in all_memberships: raise exceptions.Error( 'Membership {} does not exist in the fleet.'.format(membership)) return memberships
def Run(self, args): memberships = feature_base.ListMemberships() f = self.GetFeature() acm_status = [] feature_state_memberships = feature_state_memberships = { util.MembershipShortname(m): s for m, s in self.hubclient.ToPyDict(f.membershipStates).items() } for name in memberships: cluster = ConfigmanagementFeatureState(name) if name not in feature_state_memberships: acm_status.append(cluster) continue md = feature_state_memberships[name] fs = md.configmanagement if fs and fs.membershipSpec and fs.membershipSpec.version: cluster.version = fs.membershipSpec.version acm_status.append(cluster) return acm_status
def Run(self, args): # Get Hub memberships (cluster registered with fleet) from GCP Project. memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') # User should choose an existing membership if not provide one membership = None if args.membership is None: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to fetch the config:\n') membership = memberships[index] else: membership = args.membership if membership not in memberships: raise exceptions.Error( 'Membership {} is not in the fleet.'.format(membership)) f = self.GetFeature() version = utils.get_backfill_version_from_feature(f, membership) membership_spec = None for full_name, spec in self.hubclient.ToPyDict( f.membershipSpecs).items(): if util.MembershipShortname( full_name) == membership and spec is not None: membership_spec = spec.configmanagement if membership_spec is None: log.status.Print( 'Membership {} not initialized'.format(membership)) # load the config template and merge with config has been applied to the # feature spec template = yaml.load(utils.APPLY_SPEC_VERSION_1) full_config = template['spec'] merge_config_sync(membership_spec, full_config, version) merge_non_cs_components(membership_spec, full_config) return template
def _get_or_prompt_membership(membership): """Retrieve the membership name from args or user prompt choice. Args: membership: The default membership, if any. Returns: membership: A final membership name Raises: Error, if specified membership could not be found """ memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') # User should choose an existing membership if this arg wasn't provided if not membership: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to upgrade:\n') membership = memberships[index] elif membership not in memberships: raise exceptions.Error( 'Membership {} is not in the fleet.'.format(membership)) return membership
def Run(self, args): memberships = base.ListMemberships() if not memberships: raise exceptions.Error('No Memberships available in the fleet.') # User should choose an existing membership if not provide one if not args.membership: index = console_io.PromptChoice( options=memberships, message='Please specify a membership to ' 'unmanage in configmanagement:\n') membership = memberships[index] else: membership = args.membership if membership not in memberships: raise exceptions.Error( 'Membership {} is not in the fleet.'.format(membership)) # Setup a patch to set the MembershipSpec to the empty proto ("delete"). membership_key = self.MembershipResourceName(membership) specs = {membership_key: self.messages.MembershipFeatureSpec()} patch = self.messages.Feature( membershipSpecs=self.hubclient.ToMembershipSpecs(specs)) self.Update(['membership_specs'], patch)
def Run(self, args): """Runs the command. Args: args: argparse.Namespace, An object that contains the values for the arguments specified in the .Args() method. """ specified_args = args.GetSpecifiedArgsDict() if 'membership' not in specified_args: raise exceptions.Error( 'Please specify the membership to be changed') if len(specified_args) <= 1: raise exceptions.Error( """Please specify at least one config to be changed: --enable-stackdriver-on-applications --disable-stackdriver-on-applications --enable-optimized-metrics --disable-optimized-metrics""") membership = args.membership all_memberships = base.ListMemberships() if not all_memberships: raise exceptions.Error('No Memberships available in the fleet.') if membership not in all_memberships: raise exceptions.Error( 'Membership {} not found. Valid choices are {}.'.format( membership, all_memberships)) resource_name = self.MembershipResourceName(membership) old_feature = self.GetFeature(v1alpha1=True) ao_feature_spec = old_feature.anthosobservabilityFeatureSpec membership_spec = self.v1alpha1_messages.AnthosObservabilityMembershipSpec( ) if ao_feature_spec is not None: membership_map = self.hubclient.ToPyDict( ao_feature_spec.membershipSpecs) membership_spec = membership_map.get( resource_name, membership_spec) or membership_spec if 'enable_optimized_metrics' in specified_args: membership_spec.doNotOptimizeMetrics = False elif 'disable_optimized_metrics' in specified_args: membership_spec.doNotOptimizeMetrics = True if 'enable_stackdriver_on_applications' in specified_args: membership_spec.enableStackdriverOnApplications = True if 'disable_stackdriver_on_applications' in specified_args: membership_spec.enableStackdriverOnApplications = False spec_map = {resource_name: membership_spec} value = client.HubClient.ToProtoMap( self.v1alpha1_messages.AnthosObservabilityFeatureSpec. MembershipSpecsValue, spec_map) f = self.v1alpha1_messages.Feature( anthosobservabilityFeatureSpec=self.v1alpha1_messages. AnthosObservabilityFeatureSpec(membershipSpecs=value)) self.Update(['anthosobservability_feature_spec.membership_specs'], f, v1alpha1=True)
def Run(self, args): if args.enable and args.disable: raise exceptions.Error( '--enable and --disable cannot both be set.') # If neither flag is set, disable workload certificate management for the # memberships. enable = args.enable all_memberships = base.ListMemberships() if not all_memberships: raise exceptions.Error('No memberships available in the fleet.') memberships = [] if args.all_memberships: memberships = all_memberships elif args.memberships: memberships = args.memberships.split(',') if not memberships: # The user didn't provide --memberships. if console_io.CanPrompt(): index = console_io.PromptChoice( options=all_memberships, message='Please specify a membership:\n', cancel_option=True) memberships.append(all_memberships[index]) else: raise calliope_exceptions.RequiredArgumentException( '--memberships', ('Cannot prompt a console for membership. Membership is required. ' 'Please specify `--memberships` to select at least one membership.' )) for membership in memberships: if membership not in all_memberships: raise exceptions.Error( 'Membership {} does not exist in the fleet.'.format( membership)) # All memberships in memberships are valid. f = self.GetFeature() membership_specs = {} for membership_str in memberships: membership = self.MembershipResourceName(membership_str) patch = self.messages.MembershipFeatureSpec() # Use current spec if it exists. for name, spec in self.hubclient.ToPyDict( f.membershipSpecs).items(): if name == membership and spec: patch = spec break if not patch.workloadcertificate: patch.workloadcertificate = self.messages.MembershipSpec() if enable: patch.workloadcertificate.certificateManagement = self.messages.MembershipSpec.CertificateManagementValueValuesEnum.ENABLED else: patch.workloadcertificate.certificateManagement = self.messages.MembershipSpec.CertificateManagementValueValuesEnum.DISABLED membership_specs[membership] = patch f = self.messages.Feature( membershipSpecs=self.hubclient.ToMembershipSpecs(membership_specs)) self.Update(['membershipSpecs'], f)