// EnsureOpenShiftInfraNamespace is called as part of global policy initialization to ensure infra namespace exists
179901
func (c *completedConfig) EnsureOpenShiftInfraNamespace(context genericapiserver.PostStartHookContext) error {
	namespaceName := bootstrappolicy.DefaultOpenShiftInfraNamespace

	var coreClient coreclient.CoreInterface
	err := wait.Poll(1*time.Second, 30*time.Second, func() (bool, error) {
		var err error
		coreClient, err = coreclient.NewForConfig(c.ExtraConfig.KubeAPIServerClientConfig)
		if err != nil {
			utilruntime.HandleError(fmt.Errorf("unable to initialize client: %v", err))
			return false, nil
		}
		return true, nil
	})
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("error getting client: %v", err))
		return err
	}

	_, err = coreClient.Namespaces().Create(&kapi.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespaceName}})
	if err != nil && !kapierror.IsAlreadyExists(err) {
		utilruntime.HandleError(fmt.Errorf("error creating namespace %q: %v", namespaceName, err))
		return err
	}

	// Ensure we have the bootstrap SA for Nodes
	_, err = coreClient.ServiceAccounts(namespaceName).Create(&kapi.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: bootstrappolicy.InfraNodeBootstrapServiceAccountName}})
	if err != nil && !kapierror.IsAlreadyExists(err) {
		klog.Errorf("Error creating service account %s/%s: %v", namespaceName, bootstrappolicy.InfraNodeBootstrapServiceAccountName, err)
	}

	return nil
}
367856
func (st *State) SaveSpacesFromProvider(providerSpaces []network.SpaceInfo) error {
	stateSpaces, err := st.AllSpaces()
	if err != nil {
		return errors.Trace(err)
	}
	modelSpaceMap := make(map[network.Id]*Space)
	spaceNames := make(set.Strings)
	for _, space := range stateSpaces {
		modelSpaceMap[space.ProviderId()] = space
		spaceNames.Add(space.Name())
	}

	// TODO(mfoord): we need to delete spaces and subnets that no longer
	// exist, so long as they're not in use.
	for _, space := range providerSpaces {
		// Check if the space is already in state, in which case we know
		// its name.
		stateSpace, ok := modelSpaceMap[space.ProviderId]
		var spaceTag names.SpaceTag
		if ok {
			spaceName := stateSpace.Name()
			if !names.IsValidSpace(spaceName) {
				// Can only happen if an invalid name is stored
				// in state.
				logger.Errorf("space %q has an invalid name, ignoring", spaceName)
				continue

			}
			spaceTag = names.NewSpaceTag(spaceName)

		} else {
			// The space is new, we need to create a valid name for it
			// in state.
			spaceName := space.Name
			// Convert the name into a valid name that isn't already in
			// use.
			spaceName = network.ConvertSpaceName(spaceName, spaceNames)
			spaceNames.Add(spaceName)
			spaceTag = names.NewSpaceTag(spaceName)
			// We need to create the space.

			logger.Debugf("Adding space %s from provider %s", spaceTag.String(), string(space.ProviderId))
			_, err = st.AddSpace(spaceTag.Id(), space.ProviderId, []string{}, false)
			if err != nil {
				return errors.Trace(err)
			}
		}

		err = st.SaveSubnetsFromProvider(space.Subnets, spaceTag.Id())
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
455739
func validateMetricNamespace(ns core.Namespace) error {
	value := ""
	for _, i := range ns {
		// A dynamic element requires the name while a static element does not.
		if i.Name != "" && i.Value != "*" {
			return errorMetricStaticElementHasName(i.Value, i.Name, ns.String())
		}
		if i.Name == "" && i.Value == "*" {
			return errorMetricDynamicElementHasNoName(i.Value, ns.String())
		}
		if isTuple(i.Value) {
			return errorMetricElementHasTuple(i.Value, ns.String())
		}
		value += i.Value
	}
	// plugin should NOT advertise metrics ending with a wildcard
	if strings.HasSuffix(value, "*") {
		return errorMetricEndsWithAsterisk(ns.String())
	}
	return nil
}
720480
func (c *Client) GetNamespace(name string) (*services.Namespace, error) {
	if name == "" {
		return nil, trace.BadParameter("missing namespace name")
	}
	out, err := c.Get(c.Endpoint("namespaces", name), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.UnmarshalNamespace(out.Bytes(), services.SkipValidation())
}
305502
func (a *ACL) AllowNamespaceOperation(ns string, op string) bool {
	// Hot path management tokens
	if a.management {
		return true
	}

	// Check for a matching capability set
	capabilities, ok := a.matchingCapabilitySet(ns)
	if !ok {
		return false
	}

	// Check if the capability has been granted
	return capabilities.Check(op)
}
992530
func SetSupportsSpaceDiscovery(supports bool) bool {
	dummy.mu.Lock()
	defer dummy.mu.Unlock()
	current := dummy.supportsSpaceDiscovery
	dummy.supportsSpaceDiscovery = supports
	return current
}
1019374
func deploymentNamespaceFilter(namespace string) func(interface{}) bool {
	return func(raw interface{}) bool {
		d, ok := raw.(*structs.Deployment)
		if !ok {
			return true
		}

		return d.Namespace != namespace
	}
}
641606
func CheckName(name string) (string, error) {
	// Validate given name.
	if !names.IsValidSpace(name) {
		return "", errors.Errorf("%q is not a valid space name", name)
	}
	return name, nil
}
184826
func (c *NodeupModelContext) EnsureSystemdSuffix(name string) string {
	if !systemd.UnitFileExtensionValid(name) {
		name += ".service"
	}

	return name
}
1276695
func ValidateMetricNamespacePart(ns string) error {
	for _, chars := range notAllowedChars {
		for _, ch := range chars {
			if strings.ContainsAny(ns, ch) {
				return fmt.Errorf("Namespace contains not allowed chars, namespace part: %s, not allowed char: %s", ns, ch)
			}
		}
	}
	return nil
}
803045
func (s *LDAPGroupSyncer) makeOpenShiftGroup(ldapGroupUID string, usernames []string) (*userv1.Group, error) {
	hostIP, _, err := net.SplitHostPort(s.Host)
	if err != nil {
		return nil, err
	}
	groupName, err := s.GroupNameMapper.GroupNameFor(ldapGroupUID)
	if err != nil {
		return nil, err
	}

	group, err := s.GroupClient.Get(groupName, metav1.GetOptions{})
	if kapierrors.IsNotFound(err) {
		group = &userv1.Group{}
		group.Name = groupName
		group.Annotations = map[string]string{
			ldaputil.LDAPURLAnnotation: s.Host,
			ldaputil.LDAPUIDAnnotation: ldapGroupUID,
		}
		group.Labels = map[string]string{
			ldaputil.LDAPHostLabel: hostIP,
		}

	} else if err != nil {
		return nil, err
	}

	// make sure we aren't taking over an OpenShift group that is already related to a different LDAP group
	if host, exists := group.Labels[ldaputil.LDAPHostLabel]; !exists || (host != hostIP) {
		return nil, fmt.Errorf("group %q: %s label did not match sync host: wanted %s, got %s",
			group.Name, ldaputil.LDAPHostLabel, hostIP, host)
	}
	if url, exists := group.Annotations[ldaputil.LDAPURLAnnotation]; !exists || (url != s.Host) {
		return nil, fmt.Errorf("group %q: %s annotation did not match sync host: wanted %s, got %s",
			group.Name, ldaputil.LDAPURLAnnotation, s.Host, url)
	}
	if uid, exists := group.Annotations[ldaputil.LDAPUIDAnnotation]; !exists || (uid != ldapGroupUID) {
		return nil, fmt.Errorf("group %q: %s annotation did not match LDAP UID: wanted %s, got %s",
			group.Name, ldaputil.LDAPUIDAnnotation, ldapGroupUID, uid)
	}

	// overwrite Group Users data
	group.Users = usernames
	group.Annotations[ldaputil.LDAPSyncTimeAnnotation] = ISO8601(time.Now())

	return group, nil
}
209330
func WithHostNamespace(ns specs.LinuxNamespaceType) SpecOpts {
	return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
		setLinux(s)
		for i, n := range s.Linux.Namespaces {
			if n.Type == ns {
				s.Linux.Namespaces = append(s.Linux.Namespaces[:i], s.Linux.Namespaces[i+1:]...)
				return nil
			}
		}
		return nil
	}
}
630680
func ValidateNamespaceName(name string, prefix bool) (bool, string) {
	return NameIsDNSLabel(name, prefix)
}
245853
func ToNamespace(n core.Namespace) []*NamespaceElement {
	elements := make([]*NamespaceElement, 0, len(n))
	for _, value := range n {
		ne := &NamespaceElement{
			Value:       value.Value,
			Description: value.Description,
			Name:        value.Name,
		}
		elements = append(elements, ne)
	}
	return elements
}
33801
func CopyNamespace(src Namespace) Namespace {
	dst := make([]NamespaceElement, len(src))
	copy(dst, src)
	return dst
}
1213086
func NamespaceFrom(ctx context.Context) (string, bool) {
	namespace, ok := ctx.Value(namespaceKey).(string)
	return namespace, ok
}
1010578
func (agent *ActionAgent) InitTablet(port, gRPCPort int32) error {
	// it should be either we have all three of init_keyspace,
	// init_shard and init_tablet_type, or none.
	if *initKeyspace == "" && *initShard == "" && *initTabletType == "" {
		// not initializing the record
		return nil
	}
	if *initKeyspace == "" || *initShard == "" || *initTabletType == "" {
		return fmt.Errorf("either need all of init_keyspace, init_shard and init_tablet_type, or none")
	}

	// parse init_tablet_type
	tabletType, err := topoproto.ParseTabletType(*initTabletType)
	if err != nil {
		return vterrors.Wrapf(err, "invalid init_tablet_type %v", *initTabletType)
	}
	if tabletType == topodatapb.TabletType_MASTER {
		// We disallow MASTER, so we don't have to change
		// shard.MasterAlias, and deal with the corner cases.
		return fmt.Errorf("init_tablet_type cannot be master, use replica instead")
	}

	// parse and validate shard name
	shard, keyRange, err := topo.ValidateShardName(*initShard)
	if err != nil {
		return vterrors.Wrapf(err, "cannot validate shard name %v", *initShard)
	}

	// Create a context for this whole operation.  Note we will
	// retry some actions upon failure up to this context expires.
	ctx, cancel := context.WithTimeout(agent.batchCtx, *initTimeout)
	defer cancel()

	// Read the shard, create it if necessary.
	log.Infof("Reading/creating keyspace and shard records for %v/%v", *initKeyspace, shard)
	var si *topo.ShardInfo
	if err := agent.withRetry(ctx, "creating keyspace and shard", func() error {
		var err error
		si, err = agent.TopoServer.GetOrCreateShard(ctx, *initKeyspace, shard)
		return err
	}); err != nil {
		return vterrors.Wrap(err, "InitTablet cannot GetOrCreateShard shard")
	}
	if si.MasterAlias != nil && topoproto.TabletAliasEqual(si.MasterAlias, agent.TabletAlias) {
		// We're marked as master in the shard record, which could mean the master
		// tablet process was just restarted. However, we need to check if a new
		// master is in the process of taking over. In that case, it will let us
		// know by forcibly updating the old master's tablet record.
		oldTablet, err := agent.TopoServer.GetTablet(ctx, agent.TabletAlias)
		switch {
		case topo.IsErrType(err, topo.NoNode):
			// There's no existing tablet record, so we can assume
			// no one has left us a message to step down.
			tabletType = topodatapb.TabletType_MASTER
			// Update the TER timestamp (current value is 0) because we
			// assume that we are actually the MASTER and in case of a tiebreak,
			// vtgate should prefer us.
			agent.setExternallyReparentedTime(time.Now())
		case err == nil:
			if oldTablet.Type == topodatapb.TabletType_MASTER {
				// We're marked as master in the shard record,
				// and our existing tablet record agrees.
				tabletType = topodatapb.TabletType_MASTER
				// Same comment as above. Update tiebreaking timestamp to now.
				agent.setExternallyReparentedTime(time.Now())
			}
		default:
			return vterrors.Wrap(err, "InitTablet failed to read existing tablet record")
		}
	}

	// Rebuild keyspace graph if this the first tablet in this keyspace/cell
	_, err = agent.TopoServer.GetSrvKeyspace(ctx, agent.TabletAlias.Cell, *initKeyspace)
	switch {
	case err == nil:
		// NOOP
	case topo.IsErrType(err, topo.NoNode):
		// try to RebuildKeyspace here but ignore errors if it fails
		topotools.RebuildKeyspace(ctx, logutil.NewConsoleLogger(), agent.TopoServer, *initKeyspace, []string{agent.TabletAlias.Cell})
	default:
		return vterrors.Wrap(err, "InitTablet failed to read srvKeyspace")
	}

	log.Infof("Initializing the tablet for type %v", tabletType)

	// figure out the hostname
	hostname := *tabletHostname
	if hostname != "" {
		log.Infof("Using hostname: %v from -tablet_hostname flag.", hostname)
	} else {
		hostname, err := netutil.FullyQualifiedHostname()
		if err != nil {
			return err
		}
		log.Infof("Using detected machine hostname: %v To change this, fix your machine network configuration or override it with -tablet_hostname.", hostname)
	}

	// create and populate tablet record
	tablet := &topodatapb.Tablet{
		Alias:          agent.TabletAlias,
		Hostname:       hostname,
		PortMap:        make(map[string]int32),
		Keyspace:       *initKeyspace,
		Shard:          shard,
		KeyRange:       keyRange,
		Type:           tabletType,
		DbNameOverride: *initDbNameOverride,
		Tags:           initTags,
	}
	if port != 0 {
		tablet.PortMap["vt"] = port
	}
	if gRPCPort != 0 {
		tablet.PortMap["grpc"] = gRPCPort
	}

	// Now try to create the record (it will also fix up the
	// ShardReplication record if necessary).
	err = agent.TopoServer.CreateTablet(ctx, tablet)
	switch {
	case err == nil:
		// It worked, we're good.
	case topo.IsErrType(err, topo.NodeExists):
		// The node already exists, will just try to update
		// it. So we read it first.
		oldTablet, err := agent.TopoServer.GetTablet(ctx, tablet.Alias)
		if err != nil {
			return vterrors.Wrap(err, "InitTablet failed to read existing tablet record")
		}

		// Sanity check the keyspace and shard
		if oldTablet.Keyspace != tablet.Keyspace || oldTablet.Shard != tablet.Shard {
			return fmt.Errorf("InitTablet failed because existing tablet keyspace and shard %v/%v differ from the provided ones %v/%v", oldTablet.Keyspace, oldTablet.Shard, tablet.Keyspace, tablet.Shard)
		}

		// Update ShardReplication in any case, to be sure.  This is
		// meant to fix the case when a Tablet record was created, but
		// then the ShardReplication record was not (because for
		// instance of a startup timeout). Upon running this code
		// again, we want to fix ShardReplication.
		if updateErr := topo.UpdateTabletReplicationData(ctx, agent.TopoServer, tablet); updateErr != nil {
			return updateErr
		}

		// Then overwrite everything, ignoring version mismatch.
		if err := agent.TopoServer.UpdateTablet(ctx, topo.NewTabletInfo(tablet, nil)); err != nil {
			return vterrors.Wrap(err, "UpdateTablet failed")
		}
	default:
		return vterrors.Wrap(err, "CreateTablet failed")
	}

	// optionally populate metadata records
	if *initPopulateMetadata {
		agent.setTablet(tablet)
		localMetadata := agent.getLocalMetadataValues(tablet.Type)
		err := mysqlctl.PopulateMetadataTables(agent.MysqlDaemon, localMetadata, topoproto.TabletDbName(tablet))
		if err != nil {
			return vterrors.Wrap(err, "failed to -init_populate_metadata")
		}
	}

	return nil
}