示例#1
0
文件: cache.go 项目: cjnygard/origin
// syncRequest takes a reviewRequest and determines if it should update the caches supplied, it is not thread-safe
func (ac *AuthorizationCache) syncRequest(request *reviewRequest, userSubjectRecordStore cache.Store, groupSubjectRecordStore cache.Store, reviewRecordStore cache.Store) error {

	lastKnownValue, err := lastKnown(reviewRecordStore, request.namespace)
	if err != nil {
		return err
	}

	if skipReview(request, lastKnownValue) {
		return nil
	}

	namespace := request.namespace
	review, err := ac.reviewer.Review(namespace)
	if err != nil {
		return err
	}

	usersToRemove := util.NewStringSet()
	groupsToRemove := util.NewStringSet()
	if lastKnownValue != nil {
		usersToRemove.Insert(lastKnownValue.users...)
		usersToRemove.Delete(review.Users()...)
		groupsToRemove.Insert(lastKnownValue.groups...)
		groupsToRemove.Delete(review.Groups()...)
	}

	deleteNamespaceFromSubjects(userSubjectRecordStore, usersToRemove.List(), namespace)
	deleteNamespaceFromSubjects(groupSubjectRecordStore, groupsToRemove.List(), namespace)
	addSubjectsToNamespace(userSubjectRecordStore, review.Users(), namespace)
	addSubjectsToNamespace(groupSubjectRecordStore, review.Groups(), namespace)
	cacheReviewRecord(request, lastKnownValue, review, reviewRecordStore)
	return nil
}
示例#2
0
func TestAdd(t *testing.T) {
	testCases := []struct {
		sel         Selector
		key         string
		operator    Operator
		values      []string
		refSelector Selector
	}{
		{
			LabelSelector{},
			"key",
			InOperator,
			[]string{"value"},
			LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
		},
		{
			LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
			"key2",
			EqualsOperator,
			[]string{"value2"},
			LabelSelector{
				Requirement{"key", InOperator, util.NewStringSet("value")},
				Requirement{"key2", EqualsOperator, util.NewStringSet("value2")},
			},
		},
	}
	for _, ts := range testCases {
		ts.sel = ts.sel.Add(ts.key, ts.operator, ts.values)
		if !reflect.DeepEqual(ts.sel, ts.refSelector) {
			t.Errorf("Expected %t found %t", ts.refSelector, ts.sel)
		}
	}
}
示例#3
0
func TestEscalating(t *testing.T) {
	escalatingResources := ExpandResources(util.NewStringSet(GroupsToResources[EscalatingResourcesGroupName]...))
	nonEscalatingResources := ExpandResources(util.NewStringSet(GroupsToResources[NonEscalatingResourcesGroupName]...))
	if len(nonEscalatingResources) <= len(escalatingResources) {
		t.Errorf("groups look bad: escalating=%v nonescalating=%v", escalatingResources.List(), nonEscalatingResources.List())
	}
}
func newInvalidExtensionPolicies() []authorizationapi.Policy {
	return []authorizationapi.Policy{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      authorizationapi.PolicyName,
				Namespace: "mallet",
			},
			Roles: map[string]*authorizationapi.Role{
				"badExtension": {
					ObjectMeta: kapi.ObjectMeta{
						Name:      "failure",
						Namespace: "mallet",
					},
					Rules: []authorizationapi.PolicyRule{
						{
							Verbs:                 util.NewStringSet("watch", "list", "get"),
							Resources:             util.NewStringSet("buildConfigs"),
							AttributeRestrictions: runtime.EmbeddedObject{&authorizationapi.Role{}},
						},
						{
							Verbs:     util.NewStringSet("update"),
							Resources: util.NewStringSet("buildConfigs"),
						},
					},
				},
			},
		}}
}
示例#5
0
func (s *serviceAccount) limitSecretReferences(serviceAccount *api.ServiceAccount, pod *api.Pod) error {
	// Ensure all secrets the pod references are allowed by the service account
	mountableSecrets := util.NewStringSet()
	for _, s := range serviceAccount.Secrets {
		mountableSecrets.Insert(s.Name)
	}
	for _, volume := range pod.Spec.Volumes {
		source := volume.VolumeSource
		if source.Secret == nil {
			continue
		}
		secretName := source.Secret.SecretName
		if !mountableSecrets.Has(secretName) {
			return fmt.Errorf("Volume with secret.secretName=\"%s\" is not allowed because service account %s does not reference that secret", secretName, serviceAccount.Name)
		}
	}

	// limit pull secret references as well
	pullSecrets := util.NewStringSet()
	for _, s := range serviceAccount.ImagePullSecrets {
		pullSecrets.Insert(s.Name)
	}
	for i, pullSecretRef := range pod.Spec.ImagePullSecrets {
		if !pullSecrets.Has(pullSecretRef.Name) {
			return fmt.Errorf(`imagePullSecrets[%d].name="%s" is not allowed because service account %s does not reference that imagePullSecret`, i, pullSecretRef.Name, serviceAccount.Name)
		}
	}
	return nil
}
示例#6
0
func newDefaultClusterPolicyBindings() []authorizationapi.ClusterPolicyBinding {
	policyBinding := authorizationapi.ClusterPolicyBinding{
		ObjectMeta: kapi.ObjectMeta{
			Name: authorizationapi.ClusterPolicyBindingName,
		},
		RoleBindings: map[string]*authorizationapi.ClusterRoleBinding{
			"extra-cluster-admins": {
				ObjectMeta: kapi.ObjectMeta{
					Name: "cluster-admins",
				},
				RoleRef: kapi.ObjectReference{
					Name: "cluster-admin",
				},
				Users:  util.NewStringSet("ClusterAdmin"),
				Groups: util.NewStringSet("RootUsers"),
			},
			"user-only": {
				ObjectMeta: kapi.ObjectMeta{
					Name: "user-only",
				},
				RoleRef: kapi.ObjectReference{
					Name: "basic-user",
				},
				Users: util.NewStringSet("just-a-user"),
			},
		},
	}
	for key, value := range GetBootstrapPolicyBinding().RoleBindings {
		policyBinding.RoleBindings[key] = value
	}
	return []authorizationapi.ClusterPolicyBinding{policyBinding}
}
// Test public interface
func doTestIndex(t *testing.T, indexer Indexer) {
	mkObj := func(id string, val string) testStoreObject {
		return testStoreObject{id: id, val: val}
	}

	// Test Index
	expected := map[string]util.StringSet{}
	expected["b"] = util.NewStringSet("a", "c")
	expected["f"] = util.NewStringSet("e")
	expected["h"] = util.NewStringSet("g")
	indexer.Add(mkObj("a", "b"))
	indexer.Add(mkObj("c", "b"))
	indexer.Add(mkObj("e", "f"))
	indexer.Add(mkObj("g", "h"))
	{
		for k, v := range expected {
			found := util.StringSet{}
			indexResults, err := indexer.Index("by_val", mkObj("", k))
			if err != nil {
				t.Errorf("Unexpected error %v", err)
			}
			for _, item := range indexResults {
				found.Insert(item.(testStoreObject).id)
			}
			items := v.List()
			if !found.HasAll(items...) {
				t.Errorf("missing items, index %s, expected %v but found %v", k, items, found.List())
			}
		}
	}
}
func GetBootstrapServiceAccountProjectRoleBindings(namespace string) []authorizationapi.RoleBinding {
	return []authorizationapi.RoleBinding{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      ImagePullerRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: ImagePullerRoleName,
			},
			Groups: util.NewStringSet(serviceaccount.MakeNamespaceGroupName(namespace)),
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      ImageBuilderRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: ImageBuilderRoleName,
			},
			Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, BuilderServiceAccountName)),
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      DeployerRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: DeployerRoleName,
			},
			Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, DeployerServiceAccountName)),
		},
	}
}
示例#9
0
func TestNodeConfigTLS(t *testing.T) {
	signerCert, signerKey, signerSerial := makeSignerCert(t)
	defer os.Remove(signerCert)
	defer os.Remove(signerKey)
	defer os.Remove(signerSerial)

	configDirName := executeNodeConfig([]string{"--node=my-node", "--hostnames=example.org", "--listen=https://0.0.0.0", "--certificate-authority=" + signerCert, "--node-client-certificate-authority=" + signerCert, "--signer-cert=" + signerCert, "--signer-key=" + signerKey, "--signer-serial=" + signerSerial})
	defer os.Remove(configDirName)

	configDir, err := os.Open(configDirName)
	if err != nil {
		t.Fatalf("unable to read %v", configDirName)
	}

	fileNameSlice, err := configDir.Readdirnames(0)
	if err != nil {
		t.Fatalf("unable to read %v", configDirName)
	}
	filenames := util.NewStringSet(fileNameSlice...)

	expectedNames := util.NewStringSet("master-client.crt", "master-client.key", "server.crt", "server.key", "node-client-ca.crt", "node.kubeconfig", "node-config.yaml", "node-registration.json", "ca.crt")
	if !filenames.HasAll(expectedNames.List()...) || !expectedNames.HasAll(filenames.List()...) {
		t.Errorf("expected %v, got %v", expectedNames.List(), filenames.List())
	}
}
示例#10
0
func init() {
	// set the non-escalating groups
	GroupsToResources[OpenshiftNonEscalatingViewableGroupName] = ExpandResources(util.NewStringSet(GroupsToResources[OpenshiftAllGroupName]...)).
		Difference(ExpandResources(util.NewStringSet(GroupsToResources[OpenshiftEscalatingViewableGroupName]...))).List()

	GroupsToResources[KubeNonEscalatingViewableGroupName] = ExpandResources(util.NewStringSet(GroupsToResources[KubeAllGroupName]...)).
		Difference(ExpandResources(util.NewStringSet(GroupsToResources[KubeEscalatingViewableGroupName]...))).List()
}
示例#11
0
func convert_v1_ClusterRoleBinding_To_api_ClusterRoleBinding(in *ClusterRoleBinding, out *newer.ClusterRoleBinding, s conversion.Scope) error {
	if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields|conversion.AllowDifferentFieldTypeNames); err != nil {
		return err
	}

	out.Users = util.NewStringSet(in.UserNames...)
	out.Groups = util.NewStringSet(in.GroupNames...)

	return nil
}
示例#12
0
func convert_v1_ResourceAccessReviewResponse_To_api_ResourceAccessReviewResponse(in *ResourceAccessReviewResponse, out *newer.ResourceAccessReviewResponse, s conversion.Scope) error {
	if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields); err != nil {
		return err
	}

	out.Users = util.NewStringSet(in.UsersSlice...)
	out.Groups = util.NewStringSet(in.GroupsSlice...)

	return nil
}
示例#13
0
func TestSetSelectorParser(t *testing.T) {
	setSelectorParserTests := []struct {
		In    string
		Out   SetBasedSelector
		Match bool
		Valid bool
	}{
		{"", &LabelSelector{Requirements: nil}, true, true},
		{"x", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", Exists, nil, t),
		}}, true, true},
		{"foo in (abc)", &LabelSelector{Requirements: []Requirement{
			getRequirement("foo", In, util.NewStringSet("abc"), t),
		}}, true, true},
		{"x not in (abc)", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", NotIn, util.NewStringSet("abc"), t),
		}}, true, true},
		{"x not in (abc,def)", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", NotIn, util.NewStringSet("abc", "def"), t),
		}}, true, true},
		{"x in (abc,def)", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", In, util.NewStringSet("abc", "def"), t),
		}}, true, true},
		{"x in (abc,)", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", In, util.NewStringSet("abc", ""), t),
		}}, true, true},
		{"x in ()", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", In, util.NewStringSet(""), t),
		}}, true, true},
		{"x not in (abc,,def),bar,z in (),w", &LabelSelector{Requirements: []Requirement{
			getRequirement("x", NotIn, util.NewStringSet("abc", "", "def"), t),
			getRequirement("bar", Exists, nil, t),
			getRequirement("z", In, util.NewStringSet(""), t),
			getRequirement("w", Exists, nil, t),
		}}, true, true},
		{"x,y in (a)", &LabelSelector{Requirements: []Requirement{
			getRequirement("y", In, util.NewStringSet("a"), t),
			getRequirement("x", Exists, nil, t),
		}}, false, true},
		{"x,,y", nil, true, false},
		{",x,y", nil, true, false},
		{"x, y", nil, true, false},
		{"x nott in (y)", nil, true, false},
		{"x not in ( )", nil, true, false},
		{"x not in (, a)", nil, true, false},
		{"a in (xyz),", nil, true, false},
		{"a in (xyz)b not in ()", nil, true, false},
		{"a ", nil, true, false},
		{"a not in(", nil, true, false},
	}
	for _, ssp := range setSelectorParserTests {
		if sel, err := Parse(ssp.In); err != nil && ssp.Valid {
			t.Errorf("Parse(%s) => %v expected no error", ssp.In, err)
		} else if err == nil && !ssp.Valid {
			t.Errorf("Parse(%s) => %+v expected error", ssp.In, sel)
		} else if ssp.Match && !reflect.DeepEqual(sel, ssp.Out) {
			t.Errorf("parse output %+v doesn't match %+v, expected match", sel, ssp.Out)
		}
	}
}
示例#14
0
func TestToString(t *testing.T) {
	var req Requirement
	toStringTests := []struct {
		In    *LabelSelector
		Out   string
		Valid bool
	}{
		{&LabelSelector{Requirements: []Requirement{
			getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
			getRequirement("y", NotInOperator, util.NewStringSet("jkl"), t),
			getRequirement("z", ExistsOperator, nil, t),
		}}, "x in (abc,def),y notin (jkl),z", true},
		{&LabelSelector{Requirements: []Requirement{
			getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
			req,
		}}, "x in (abc,def),", false},
		{&LabelSelector{Requirements: []Requirement{
			getRequirement("x", NotInOperator, util.NewStringSet("abc"), t),
			getRequirement("y", InOperator, util.NewStringSet("jkl", "mno"), t),
			getRequirement("z", NotInOperator, util.NewStringSet(""), t),
		}}, "x notin (abc),y in (jkl,mno),z notin ()", true},
		{&LabelSelector{Requirements: []Requirement{
			getRequirement("x", EqualsOperator, util.NewStringSet("abc"), t),
			getRequirement("y", DoubleEqualsOperator, util.NewStringSet("jkl"), t),
			getRequirement("z", NotEqualsOperator, util.NewStringSet("a"), t),
		}}, "x=abc,y==jkl,z!=a", true},
	}
	for _, ts := range toStringTests {
		if out := ts.In.String(); out == "" && ts.Valid {
			t.Errorf("%+v.String() => '%v' expected no error", ts.In)
		} else if out != ts.Out {
			t.Errorf("%+v.String() => '%v' want '%v'", ts.In, out, ts.Out)
		}
	}
}
示例#15
0
func TestRequirementMatches(t *testing.T) {
	s := Set{"x": "foo", "y": "baz"}
	a := Requirement{key: "x", operator: IN, strValues: util.NewStringSet("foo")}
	b := Requirement{key: "x", operator: NOT_IN, strValues: util.NewStringSet("beta")}
	c := Requirement{key: "y", operator: IN, strValues: nil}
	d := Requirement{key: "y", strValues: util.NewStringSet("foo")}
	expectMatchRequirement(t, a, s)
	expectMatchRequirement(t, b, s)
	expectNoMatchRequirement(t, c, s)
	expectNoMatchRequirement(t, d, s)
}
示例#16
0
func (o *RemoveFromProjectOptions) Run() error {
	bindingList, err := o.Client.PolicyBindings(o.BindingNamespace).List(labels.Everything(), fields.Everything())
	if err != nil {
		return err
	}
	sort.Sort(authorizationapi.PolicyBindingSorter(bindingList.Items))

	usersRemoved := util.StringSet{}
	groupsRemoved := util.StringSet{}

	for _, currPolicyBinding := range bindingList.Items {
		for _, currBinding := range authorizationapi.SortRoleBindings(currPolicyBinding.RoleBindings, true) {
			bindingHasGroups := len(o.Groups) > 0 && currBinding.Groups.HasAny(o.Groups...)
			bindingHasUsers := len(o.Users) > 0 && currBinding.Users.HasAny(o.Users...)
			if !bindingHasGroups && !bindingHasUsers {
				continue
			}

			existingGroups := util.NewStringSet(currBinding.Groups.List()...)
			existingUsers := util.NewStringSet(currBinding.Users.List()...)

			currBinding.Groups.Delete(o.Groups...)
			currBinding.Users.Delete(o.Users...)

			_, err = o.Client.RoleBindings(o.BindingNamespace).Update(currBinding)
			if err != nil {
				return err
			}

			roleDisplayName := fmt.Sprintf("%s/%s", currBinding.RoleRef.Namespace, currBinding.RoleRef.Name)
			if len(currBinding.RoleRef.Namespace) == 0 {
				roleDisplayName = currBinding.RoleRef.Name
			}
			if diff := existingGroups.Difference(currBinding.Groups); len(diff) != 0 {
				fmt.Fprintf(o.Out, "Removing %s from groups %v in project %s.\n", roleDisplayName, diff.List(), o.BindingNamespace)
				groupsRemoved.Insert(diff.List()...)
			}
			if diff := existingUsers.Difference(currBinding.Users); len(diff) != 0 {
				fmt.Fprintf(o.Out, "Removing %s from users %v in project %s.\n", roleDisplayName, diff.List(), o.BindingNamespace)
				usersRemoved.Insert(diff.List()...)
			}
		}
	}

	if diff := util.NewStringSet(o.Groups...).Difference(groupsRemoved); len(diff) != 0 {
		fmt.Fprintf(o.Out, "Groups %v were not bound to roles in project %s.\n", diff.List(), o.BindingNamespace)
	}
	if diff := util.NewStringSet(o.Users...).Difference(usersRemoved); len(diff) != 0 {
		fmt.Fprintf(o.Out, "Users %v were not bound to roles in project %s.\n", diff.List(), o.BindingNamespace)
	}

	return nil
}
func TestResourceStarCoveringStar(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("*")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("*")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
func TestResourceNameEmptyCoveringMultiple(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("pods"), ResourceNames: util.NewStringSet()},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("pods"), ResourceNames: util.NewStringSet("foo", "bar")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
func TestResourceGroupCoveringEnumerated(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("create", "delete", "update"), Resources: util.NewStringSet("resourcegroup:builds")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("builds", "buildconfigs")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
func TestEnumeratedCoveringResourceGroup(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("builds", "buildconfigs", "buildlogs", "buildconfigs/instantiate", "builds/log", "builds/clone", "buildconfigs/webhooks")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("resourcegroup:builds")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
func TestVerbStarCoveringMultiple(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("watch", "list"), Resources: util.NewStringSet("roles")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
func TestSyncNamespaceThatIsTerminating(t *testing.T) {
	mockKubeClient := &ktestclient.Fake{}
	mockOriginClient := &testclient.Fake{}
	nm := NamespaceController{
		KubeClient: mockKubeClient,
		Client:     mockOriginClient,
	}
	now := util.Now()
	testNamespace := &kapi.Namespace{
		ObjectMeta: kapi.ObjectMeta{
			Name:              "test",
			ResourceVersion:   "1",
			DeletionTimestamp: &now,
		},
		Spec: kapi.NamespaceSpec{
			Finalizers: []kapi.FinalizerName{kapi.FinalizerKubernetes, api.FinalizerOrigin},
		},
		Status: kapi.NamespaceStatus{
			Phase: kapi.NamespaceTerminating,
		},
	}
	err := nm.Handle(testNamespace)
	if err != nil {
		t.Errorf("Unexpected error when handling namespace %v", err)
	}

	// TODO: we will expect a finalize namespace call after rebase
	expectedActionSet := util.NewStringSet(
		"list-buildconfig",
		"list-policies",
		"list-imagestreams",
		"list-policyBindings",
		"list-roleBinding",
		"list-role",
		"list-routes",
		"list-templates",
		"list-builds",
		"finalize-namespace",
		"list-deploymentconfig",
	)
	actionSet := util.NewStringSet()
	for i := range mockKubeClient.Actions {
		actionSet.Insert(mockKubeClient.Actions[i].Action)
	}
	for i := range mockOriginClient.Actions {
		actionSet.Insert(mockOriginClient.Actions[i].Action)
	}
	if !(actionSet.HasAll(expectedActionSet.List()...) && (len(actionSet) == len(expectedActionSet))) {
		t.Errorf("Expected actions: %v, but got: %v", expectedActionSet, actionSet)
	}
}
示例#23
0
func TestNoErrors(t *testing.T) {
	test := &resourceAccessTest{
		authorizer: &testAuthorizer{
			users:  util.NewStringSet("one", "two"),
			groups: util.NewStringSet("three", "four"),
		},
		reviewRequest: &authorizationapi.ResourceAccessReview{
			Verb:     "delete",
			Resource: "deploymentConfig",
		},
	}

	test.runTest(t)
}
func (im *realImageManager) detectImages(detected time.Time) error {
	images, err := im.dockerClient.ListImages(docker.ListImagesOptions{})
	if err != nil {
		return err
	}
	containers, err := im.dockerClient.ListContainers(docker.ListContainersOptions{
		All: true,
	})
	if err != nil {
		return err
	}

	// Make a set of images in use by containers.
	imagesInUse := util.NewStringSet()
	for _, container := range containers {
		imagesInUse.Insert(container.Image)
	}

	// Add new images and record those being used.
	now := time.Now()
	currentImages := util.NewStringSet()
	im.imageRecordsLock.Lock()
	defer im.imageRecordsLock.Unlock()
	for _, image := range images {
		currentImages.Insert(image.ID)

		// New image, set it as detected now.
		if _, ok := im.imageRecords[image.ID]; !ok {
			im.imageRecords[image.ID] = &imageRecord{
				detected: detected,
			}
		}

		// Set last used time to now if the image is being used.
		if isImageUsed(&image, imagesInUse) {
			im.imageRecords[image.ID].lastUsed = now
		}

		im.imageRecords[image.ID].size = image.VirtualSize
	}

	// Remove old images from our records.
	for image := range im.imageRecords {
		if !currentImages.Has(image) {
			delete(im.imageRecords, image)
		}
	}

	return nil
}
func TestEnumerationNotCoveringVerbStar(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get", "list", "watch", "create", "update", "delete", "exec"), Resources: util.NewStringSet("roles")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},

		expectedCovered: false,
		expectedUncoveredRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},
	}.test(t)
}
示例#26
0
func TestEtcdWatch(t *testing.T) {
	table := map[string]generic.Matcher{
		"single": setMatcher{util.NewStringSet("foo")},
		"multi":  setMatcher{util.NewStringSet("foo", "bar")},
	}

	for name, m := range table {
		podA := &api.Pod{
			ObjectMeta: api.ObjectMeta{
				Name:            "foo",
				Namespace:       api.NamespaceDefault,
				ResourceVersion: "1",
			},
			Spec: api.PodSpec{Host: "machine"},
		}
		respWithPodA := &etcd.Response{
			Node: &etcd.Node{
				Key:           "/registry/pods/default/foo",
				Value:         runtime.EncodeOrDie(testapi.Codec(), podA),
				ModifiedIndex: 1,
				CreatedIndex:  1,
			},
			Action: "create",
		}

		fakeClient, registry := NewTestGenericEtcdRegistry(t)
		wi, err := registry.WatchPredicate(api.NewContext(), m, "1")
		if err != nil {
			t.Errorf("%v: unexpected error: %v", name, err)
			continue
		}
		fakeClient.WaitForWatchCompletion()

		go func() {
			fakeClient.WatchResponse <- respWithPodA
		}()

		got, open := <-wi.ResultChan()
		if !open {
			t.Errorf("%v: unexpected channel close", name)
			continue
		}

		if e, a := podA, got.Object; !api.Semantic.DeepDerivative(e, a) {
			t.Errorf("%v: difference: %s", name, util.ObjectDiff(e, a))
		}
	}
}
示例#27
0
// BuildSerializeableKubeMasterConfig creates a fully specified kubernetes master startup configuration based on MasterArgs
func (args MasterArgs) BuildSerializeableKubeMasterConfig() (*configapi.KubernetesMasterConfig, error) {
	servicesSubnet := net.IPNet(args.PortalNet)

	masterAddr, err := args.GetMasterAddress()
	if err != nil {
		return nil, err
	}
	masterHost, _, err := net.SplitHostPort(masterAddr.Host)
	if err != nil {
		masterHost = masterAddr.Host
	}
	masterIP := ""
	if ip := net.ParseIP(masterHost); ip != nil {
		masterIP = ip.String()
	}

	staticNodeList := util.NewStringSet(args.NodeList...)
	staticNodeList.Delete("")

	config := &configapi.KubernetesMasterConfig{
		MasterIP:            masterIP,
		ServicesSubnet:      servicesSubnet.String(),
		StaticNodeNames:     staticNodeList.List(),
		SchedulerConfigFile: args.SchedulerConfigFile,
	}

	return config, nil
}
示例#28
0
func describeService(service *api.Service, endpoints *api.Endpoints, events *api.EventList) (string, error) {
	if endpoints == nil {
		endpoints = &api.Endpoints{}
	}
	return tabbedString(func(out io.Writer) error {
		fmt.Fprintf(out, "Name:\t%s\n", service.Name)
		fmt.Fprintf(out, "Labels:\t%s\n", formatLabels(service.Labels))
		fmt.Fprintf(out, "Selector:\t%s\n", formatLabels(service.Spec.Selector))
		fmt.Fprintf(out, "Type:\t%s\n", service.Spec.Type)
		fmt.Fprintf(out, "IP:\t%s\n", service.Spec.ClusterIP)
		if len(service.Status.LoadBalancer.Ingress) > 0 {
			list := buildIngressString(service.Status.LoadBalancer.Ingress)
			fmt.Fprintf(out, "LoadBalancer Ingress:\t%s\n", list)
		}
		for i := range service.Spec.Ports {
			sp := &service.Spec.Ports[i]

			name := sp.Name
			if name == "" {
				name = "<unnamed>"
			}
			fmt.Fprintf(out, "Port:\t%s\t%d/%s\n", name, sp.Port, sp.Protocol)
			if sp.NodePort != 0 {
				fmt.Fprintf(out, "NodePort:\t%s\t%d/%s\n", name, sp.NodePort, sp.Protocol)
			}
			fmt.Fprintf(out, "Endpoints:\t%s\n", formatEndpoints(endpoints, util.NewStringSet(sp.Name)))
		}
		fmt.Fprintf(out, "Session Affinity:\t%s\n", service.Spec.SessionAffinity)
		if events != nil {
			DescribeEvents(events, out)
		}
		return nil
	})
}
func TestSyncNamespaceThatIsActive(t *testing.T) {
	mockClient := &testclient.Fake{}
	testNamespace := api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:            "test",
			ResourceVersion: "1",
		},
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"kubernetes"},
		},
		Status: api.NamespaceStatus{
			Phase: api.NamespaceActive,
		},
	}
	err := syncNamespace(mockClient, testNamespace)
	if err != nil {
		t.Errorf("Unexpected error when synching namespace %v", err)
	}
	actionSet := util.NewStringSet()
	for i := range mockClient.Actions {
		actionSet.Insert(mockClient.Actions[i].Action)
	}
	if len(actionSet) != 0 {
		t.Errorf("Expected no action from controller, but got: %v", actionSet)
	}
}
func TestMergeResolver(t *testing.T) {
	resolverA := &mockResolver{
		items: []*kapi.ReplicationController{
			mockDeployment("a", "b", nil),
		},
	}
	resolverB := &mockResolver{
		items: []*kapi.ReplicationController{
			mockDeployment("c", "d", nil),
		},
	}
	resolver := &mergeResolver{resolvers: []Resolver{resolverA, resolverB}}
	results, err := resolver.Resolve()
	if err != nil {
		t.Errorf("Unexpected error %v", err)
	}
	if len(results) != 2 {
		t.Errorf("Unexpected results %v", results)
	}
	expectedNames := util.NewStringSet("b", "d")
	for _, item := range results {
		if !expectedNames.Has(item.Name) {
			t.Errorf("Unexpected name %v", item.Name)
		}
	}
}