本文整理汇总了Golang中k8s/io/kubernetes/pkg/util/sets.String类的典型用法代码示例。如果您正苦于以下问题:Golang String类的具体用法?Golang String怎么用?Golang String使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了String类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewSharedContextEvaluator
// NewSharedContextEvaluator creates an evaluator object that allows to share context while computing usage of
// single namespace. Context is represented by an object returned by usageComputerFactory and is destroyed
// when the namespace is processed.
func NewSharedContextEvaluator(
name string,
groupKind unversioned.GroupKind,
operationResources map[admission.Operation][]kapi.ResourceName,
matchedResourceNames []kapi.ResourceName,
matchesScopeFunc generic.MatchesScopeFunc,
getFuncByNamespace generic.GetFuncByNamespace,
listFuncByNamespace generic.ListFuncByNamespace,
constraintsFunc generic.ConstraintsFunc,
usageComputerFactory UsageComputerFactory,
) quota.Evaluator {
rnSet := sets.String{}
for _, resourceNames := range operationResources {
rnSet.Insert(quota.ToSet(resourceNames).List()...)
}
return &SharedContextEvaluator{
GenericEvaluator: &generic.GenericEvaluator{
Name: name,
InternalGroupKind: groupKind,
InternalOperationResources: operationResources,
MatchedResourceNames: matchedResourceNames,
MatchesScopeFunc: matchesScopeFunc,
GetFuncByNamespace: getFuncByNamespace,
ListFuncByNamespace: listFuncByNamespace,
ConstraintsFunc: constraintsFunc,
UsageFunc: func(object runtime.Object) kapi.ResourceList {
comp := usageComputerFactory()
return comp.Usage(object)
},
},
UsageComputerFactory: usageComputerFactory,
}
}
示例2: String
// Print formats and prints the give PodDiff.
func (p PodDiff) String(ignorePhases sets.String) string {
ret := ""
for name, info := range p {
if ignorePhases.Has(info.phase) {
continue
}
if info.phase == nonExist {
ret += fmt.Sprintf("Pod %v was deleted, had phase %v and host %v\n", name, info.oldPhase, info.oldHostname)
continue
}
phaseChange, hostChange := false, false
msg := fmt.Sprintf("Pod %v ", name)
if info.oldPhase != info.phase {
phaseChange = true
if info.oldPhase == nonExist {
msg += fmt.Sprintf("in phase %v ", info.phase)
} else {
msg += fmt.Sprintf("went from phase: %v -> %v ", info.oldPhase, info.phase)
}
}
if info.oldHostname != info.hostname {
hostChange = true
if info.oldHostname == nonExist || info.oldHostname == "" {
msg += fmt.Sprintf("assigned host %v ", info.hostname)
} else {
msg += fmt.Sprintf("went from host: %v -> %v ", info.oldHostname, info.hostname)
}
}
if phaseChange || hostChange {
ret += msg + "\n"
}
}
return ret
}
示例3: filterInvalidPods
func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventRecorder) (filtered []*api.Pod) {
names := sets.String{}
for i, pod := range pods {
var errlist field.ErrorList
if errs := validation.ValidatePod(pod); len(errs) != 0 {
errlist = append(errlist, errs...)
// If validation fails, don't trust it any further -
// even Name could be bad.
} else {
name := kubecontainer.GetPodFullName(pod)
if names.Has(name) {
// TODO: when validation becomes versioned, this gets a bit
// more complicated.
errlist = append(errlist, field.Duplicate(field.NewPath("metadata", "name"), pod.Name))
} else {
names.Insert(name)
}
}
if len(errlist) > 0 {
name := bestPodIdentString(pod)
err := errlist.ToAggregate()
glog.Warningf("Pod[%d] (%s) from %s failed validation, ignoring: %v", i+1, name, source, err)
recorder.Eventf(pod, api.EventTypeWarning, kubecontainer.FailedValidation, "Error validating pod %s from %s, ignoring: %v", name, source, err)
continue
}
filtered = append(filtered, pod)
}
return
}
示例4: getPullSecretNames
func getPullSecretNames(serviceaccount *kapi.ServiceAccount) sets.String {
names := sets.String{}
for _, secret := range serviceaccount.ImagePullSecrets {
names.Insert(secret.Name)
}
return names
}
示例5: Index
// Index returns a list of items that match on the index function
// Index is thread-safe so long as you treat all items as immutable
func (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error) {
c.lock.RLock()
defer c.lock.RUnlock()
indexFunc := c.indexers[indexName]
if indexFunc == nil {
return nil, fmt.Errorf("Index with name %s does not exist", indexName)
}
indexKeys, err := indexFunc(obj)
if err != nil {
return nil, err
}
index := c.indices[indexName]
// need to de-dupe the return list. Since multiple keys are allowed, this can happen.
returnKeySet := sets.String{}
for _, indexKey := range indexKeys {
set := index[indexKey]
for _, key := range set.List() {
returnKeySet.Insert(key)
}
}
list := make([]interface{}, 0, returnKeySet.Len())
for absoluteKey := range returnKeySet {
list = append(list, c.items[absoluteKey])
}
return list, nil
}
示例6: filterInvalidPods
func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventRecorder) (filtered []*api.Pod) {
names := sets.String{}
for i, pod := range pods {
var errlist []error
if errs := validation.ValidatePod(pod); len(errs) != 0 {
errlist = append(errlist, errs...)
// If validation fails, don't trust it any further -
// even Name could be bad.
} else {
name := kubecontainer.GetPodFullName(pod)
if names.Has(name) {
errlist = append(errlist, fielderrors.NewFieldDuplicate("name", pod.Name))
} else {
names.Insert(name)
}
}
if len(errlist) > 0 {
name := bestPodIdentString(pod)
err := utilerrors.NewAggregate(errlist)
glog.Warningf("Pod[%d] (%s) from %s failed validation, ignoring: %v", i+1, name, source, err)
recorder.Eventf(pod, "FailedValidation", "Error validating pod %s from %s, ignoring: %v", name, source, err)
continue
}
filtered = append(filtered, pod)
}
return
}
示例7: nextClassID
func (t *tcShaper) nextClassID() (int, error) {
data, err := t.e.Command("tc", "class", "show", "dev", t.iface).CombinedOutput()
if err != nil {
return -1, err
}
scanner := bufio.NewScanner(bytes.NewBuffer(data))
classes := sets.String{}
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// skip empty lines
if len(line) == 0 {
continue
}
parts := strings.Split(line, " ")
// expected tc line:
// class htb 1:1 root prio 0 rate 1000Kbit ceil 1000Kbit burst 1600b cburst 1600b
if len(parts) != 14 {
return -1, fmt.Errorf("unexpected output from tc: %s (%v)", scanner.Text(), parts)
}
classes.Insert(parts[2])
}
// Make sure it doesn't go forever
for nextClass := 1; nextClass < 10000; nextClass++ {
if !classes.Has(fmt.Sprintf("1:%d", nextClass)) {
return nextClass, nil
}
}
// This should really never happen
return -1, fmt.Errorf("exhausted class space, please try again")
}
示例8: Expand
// Expand takes aliases and expands them into owner lists.
func (a *Aliases) Expand(toExpand sets.String) sets.String {
expanded := sets.String{}
for _, owner := range toExpand.List() {
expanded.Insert(a.resolve(owner)...)
}
return expanded
}
示例9: nameMatches
// nameMatches checks to see if the resourceName of the action is in a the specified whitelist. An empty whitelist indicates that any name is allowed.
// An empty string in the whitelist should only match the action's resourceName if the resourceName itself is empty string. This behavior allows for the
// combination of a whitelist for gets in the same rule as a list that won't have a resourceName. I don't recommend writing such a rule, but we do
// handle it like you'd expect: white list is respected for gets while not preventing the list you explicitly asked for.
func (a DefaultAuthorizationAttributes) nameMatches(allowedResourceNames sets.String) bool {
if len(allowedResourceNames) == 0 {
return true
}
return allowedResourceNames.Has(a.GetResourceName())
}
示例10: UsersWithCommit
func (config *GithubConfig) UsersWithCommit() ([]string, error) {
userSet := sets.String{}
teams, err := config.fetchAllTeams()
if err != nil {
glog.Errorf("%v", err)
return nil, err
}
teamIDs := []int{}
for _, team := range teams {
repo, _, err := config.client.Organizations.IsTeamRepo(*team.ID, config.Org, config.Project)
if repo == nil || err != nil {
continue
}
perms := *repo.Permissions
if perms["push"] {
teamIDs = append(teamIDs, *team.ID)
}
}
for _, team := range teamIDs {
users, err := config.fetchAllUsers(team)
if err != nil {
glog.Errorf("%v", err)
continue
}
for _, user := range users {
userSet.Insert(*user.Login)
}
}
return userSet.List(), nil
}
示例11: dialFromNode
// dialFromNode executes a tcp or udp request based on protocol via kubectl exec
// in a test container running with host networking.
// - minTries is the minimum number of curl attempts required before declaring
// success. Set to 0 if you'd like to return as soon as all endpoints respond
// at least once.
// - maxTries is the maximum number of curl attempts. If this many attempts pass
// and we don't see all expected endpoints, the test fails.
// maxTries == minTries will confirm that we see the expected endpoints and no
// more for maxTries. Use this if you want to eg: fail a readiness check on a
// pod and confirm it doesn't show up as an endpoint.
func (config *NetworkingTestConfig) dialFromNode(protocol, targetIP string, targetPort, maxTries, minTries int, expectedEps sets.String) {
var cmd string
if protocol == "udp" {
cmd = fmt.Sprintf("echo 'hostName' | timeout -t 3 nc -w 1 -u %s %d", targetIP, targetPort)
} else {
cmd = fmt.Sprintf("curl -q -s --connect-timeout 1 http://%s:%d/hostName", targetIP, targetPort)
}
// TODO: This simply tells us that we can reach the endpoints. Check that
// the probability of hitting a specific endpoint is roughly the same as
// hitting any other.
eps := sets.NewString()
filterCmd := fmt.Sprintf("%s | grep -v '^\\s*$'", cmd)
for i := 0; i < maxTries; i++ {
stdout, err := framework.RunHostCmd(config.ns, config.hostTestContainerPod.Name, filterCmd)
if err != nil {
// A failure to kubectl exec counts as a try, not a hard fail.
// Also note that we will keep failing for maxTries in tests where
// we confirm unreachability.
framework.Logf("Failed to execute %v: %v", filterCmd, err)
} else {
eps.Insert(strings.TrimSpace(stdout))
}
framework.Logf("Waiting for %+v endpoints, got endpoints %+v", expectedEps.Difference(eps), eps)
// Check against i+1 so we exit if minTries == maxTries.
if (eps.Equal(expectedEps) || eps.Len() == 0 && expectedEps.Len() == 0) && i+1 >= minTries {
return
}
}
config.diagnoseMissingEndpoints(eps)
framework.Failf("Failed to find expected endpoints:\nTries %d\nCommand %v\nretrieved %v\nexpected %v\n", minTries, cmd, eps, expectedEps)
}
示例12: parseMetrics
func parseMetrics(data string, knownMetrics map[string][]string, output *Metrics, unknownMetrics sets.String) error {
dec := expfmt.NewDecoder(strings.NewReader(data), expfmt.FmtText)
decoder := expfmt.SampleDecoder{
Dec: dec,
Opts: &expfmt.DecodeOptions{},
}
for {
var v model.Vector
if err := decoder.Decode(&v); err != nil {
if err == io.EOF {
// Expected loop termination condition.
return nil
}
glog.Warningf("Invalid Decode. Skipping.")
continue
}
for _, metric := range v {
name := string(metric.Metric[model.MetricNameLabel])
_, isCommonMetric := CommonMetrics[name]
_, isKnownMetric := knownMetrics[name]
if isKnownMetric || isCommonMetric {
(*output)[name] = append((*output)[name], metric)
} else {
if unknownMetrics != nil {
unknownMetrics.Insert(name)
}
}
}
}
}
示例13: formatEndpoints
// Pass ports=nil for all ports.
func formatEndpoints(endpoints *api.Endpoints, ports sets.String) string {
if len(endpoints.Subsets) == 0 {
return "<none>"
}
list := []string{}
max := 3
more := false
count := 0
for i := range endpoints.Subsets {
ss := &endpoints.Subsets[i]
for i := range ss.Ports {
port := &ss.Ports[i]
if ports == nil || ports.Has(port.Name) {
for i := range ss.Addresses {
if len(list) == max {
more = true
}
addr := &ss.Addresses[i]
if !more {
list = append(list, fmt.Sprintf("%s:%d", addr.IP, port.Port))
}
count++
}
}
}
}
ret := strings.Join(list, ",")
if more {
return fmt.Sprintf("%s + %d more...", ret, count-max)
}
return ret
}
示例14: ScopesToVisibleNamespaces
// ScopesToVisibleNamespaces returns a list of namespaces that the provided scopes have "get" access to.
// This exists only to support efficiently list/watch of projects (ACLed namespaces)
func ScopesToVisibleNamespaces(scopes []string, clusterPolicyGetter client.ClusterPolicyLister) (sets.String, error) {
if len(scopes) == 0 {
return sets.NewString("*"), nil
}
visibleNamespaces := sets.String{}
errors := []error{}
for _, scope := range scopes {
found := false
for _, evaluator := range ScopeEvaluators {
if evaluator.Handles(scope) {
found = true
allowedNamespaces, err := evaluator.ResolveGettableNamespaces(scope, clusterPolicyGetter)
if err != nil {
errors = append(errors, err)
continue
}
visibleNamespaces.Insert(allowedNamespaces...)
break
}
}
if !found {
errors = append(errors, fmt.Errorf("no scope evaluator found for %q", scope))
}
}
return visibleNamespaces, kutilerrors.NewAggregate(errors)
}
示例15: List
// List returns the set of namespace names the user has access to view
func (ac *AuthorizationCache) List(userInfo user.Info) (*kapi.NamespaceList, error) {
keys := sets.String{}
user := userInfo.GetName()
groups := userInfo.GetGroups()
obj, exists, _ := ac.userSubjectRecordStore.GetByKey(user)
if exists {
subjectRecord := obj.(*subjectRecord)
keys.Insert(subjectRecord.namespaces.List()...)
}
for _, group := range groups {
obj, exists, _ := ac.groupSubjectRecordStore.GetByKey(group)
if exists {
subjectRecord := obj.(*subjectRecord)
keys.Insert(subjectRecord.namespaces.List()...)
}
}
namespaceList := &kapi.NamespaceList{}
for key := range keys {
namespace, exists, err := ac.namespaceStore.GetByKey(key)
if err != nil {
return nil, err
}
if exists {
namespaceList.Items = append(namespaceList.Items, *namespace.(*kapi.Namespace))
}
}
return namespaceList, nil
}