• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang util.NewIntOrStringFromString函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/util.NewIntOrStringFromString函数的典型用法代码示例。如果您正苦于以下问题:Golang NewIntOrStringFromString函数的具体用法?Golang NewIntOrStringFromString怎么用?Golang NewIntOrStringFromString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewIntOrStringFromString函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestGetInteger

func TestGetInteger(t *testing.T) {
	tests := []struct {
		res      api.ResourceList
		name     api.ResourceName
		expected int
		def      int
		test     string
	}{
		{
			res:      api.ResourceList{},
			name:     CPU,
			expected: 1,
			def:      1,
			test:     "nothing present",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromInt(2),
			},
			name:     CPU,
			expected: 2,
			def:      1,
			test:     "present",
		},
		{
			res: api.ResourceList{
				Memory: util.NewIntOrStringFromInt(2),
			},
			name:     CPU,
			expected: 1,
			def:      1,
			test:     "not-present",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromString("2"),
			},
			name:     CPU,
			expected: 2,
			def:      1,
			test:     "present-string",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromString("foo"),
			},
			name:     CPU,
			expected: 1,
			def:      1,
			test:     "present-invalid",
		},
	}

	for _, test := range tests {
		val := GetIntegerResource(test.res, test.name, test.def)
		if val != test.expected {
			t.Errorf("expected: %d found %d", test.expected, val)
		}
	}
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:60,代码来源:resources_test.go


示例2: Instances

// Instances returns an implementation of Instances for OpenStack.
func (os *OpenStack) Instances() (cloudprovider.Instances, bool) {
	servers, err := gophercloud.ServersApi(os.access, gophercloud.ApiCriteria{
		Type:      "compute",
		UrlChoice: gophercloud.PublicURL,
		Region:    os.region,
	})

	if err != nil {
		return nil, false
	}

	flavors, err := servers.ListFlavors()
	if err != nil {
		return nil, false
	}
	flavor_to_resource := make(map[string]*api.NodeResources, len(flavors))
	for _, flavor := range flavors {
		rsrc := api.NodeResources{
			Capacity: api.ResourceList{
				"cpu":                      util.NewIntOrStringFromInt(flavor.VCpus),
				"memory":                   util.NewIntOrStringFromString(fmt.Sprintf("%dMiB", flavor.Ram)),
				"openstack.org/disk":       util.NewIntOrStringFromString(fmt.Sprintf("%dGB", flavor.Disk)),
				"openstack.org/rxTxFactor": util.NewIntOrStringFromInt(int(flavor.RxTxFactor * 1000)),
				"openstack.org/swap":       util.NewIntOrStringFromString(fmt.Sprintf("%dMiB", flavor.Swap)),
			},
		}
		flavor_to_resource[flavor.Id] = &rsrc
	}

	return &Instances{servers, flavor_to_resource}, true
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:32,代码来源:openstack.go


示例3: TestGetURLParts

func TestGetURLParts(t *testing.T) {
	testCases := []struct {
		probe *api.HTTPGetAction
		ok    bool
		host  string
		port  int
		path  string
	}{
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromInt(-1), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromString(""), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromString("-1"), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromString("not-found"), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromString("found"), Path: ""}, true, "127.0.0.1", 93, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromInt(76), Path: ""}, true, "127.0.0.1", 76, ""},
		{&api.HTTPGetAction{Host: "", Port: util.NewIntOrStringFromString("118"), Path: ""}, true, "127.0.0.1", 118, ""},
		{&api.HTTPGetAction{Host: "hostname", Port: util.NewIntOrStringFromInt(76), Path: "path"}, true, "hostname", 76, "path"},
	}

	for _, test := range testCases {
		state := api.PodStatus{PodIP: "127.0.0.1"}
		container := api.Container{
			Ports: []api.ContainerPort{{Name: "found", HostPort: 93}},
			LivenessProbe: &api.Probe{
				Handler: api.Handler{
					HTTPGet: test.probe,
				},
			},
		}

		scheme := test.probe.Scheme
		if scheme == "" {
			scheme = api.URISchemeHTTP
		}
		host := test.probe.Host
		if host == "" {
			host = state.PodIP
		}
		port, err := extractPort(test.probe.Port, container)
		if test.ok && err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		path := test.probe.Path

		if !test.ok && err == nil {
			t.Errorf("Expected error for %+v, got %s%s:%d/%s", test, scheme, host, port, path)
		}
		if test.ok {
			if host != test.host || port != test.port || path != test.path {
				t.Errorf("Expected %s:%d/%s, got %s:%d/%s",
					test.host, test.port, test.path, host, port, path)
			}
		}
	}
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:54,代码来源:prober_test.go


示例4: TestGetFloat

func TestGetFloat(t *testing.T) {
	tests := []struct {
		res      api.ResourceList
		name     api.ResourceName
		expected float64
		def      float64
		test     string
	}{
		{
			res:      api.ResourceList{},
			name:     CPU,
			expected: 1.5,
			def:      1.5,
			test:     "nothing present",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromInt(2),
			},
			name:     CPU,
			expected: 2.0,
			def:      1.5,
			test:     "present",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromString("2.5"),
			},
			name:     CPU,
			expected: 2.5,
			def:      1,
			test:     "present-string",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromString("foo"),
			},
			name:     CPU,
			expected: 1,
			def:      1,
			test:     "present-invalid",
		},
	}

	for _, test := range tests {
		val := GetFloatResource(test.res, test.name, test.def)
		if val != test.expected {
			t.Errorf("expected: %d found %d", test.expected, val)
		}
	}
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:51,代码来源:resources_test.go


示例5: TestGetString

func TestGetString(t *testing.T) {
	tests := []struct {
		res      api.ResourceList
		name     api.ResourceName
		expected string
		def      string
		test     string
	}{
		{
			res:      api.ResourceList{},
			name:     CPU,
			expected: "foo",
			def:      "foo",
			test:     "nothing present",
		},
		{
			res: api.ResourceList{
				CPU: util.NewIntOrStringFromString("bar"),
			},
			name:     CPU,
			expected: "bar",
			def:      "foo",
			test:     "present",
		},
	}

	for _, test := range tests {
		val := GetStringResource(test.res, test.name, test.def)
		if val != test.expected {
			t.Errorf("expected: %d found %d", test.expected, val)
		}
	}
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:33,代码来源:resources_test.go


示例6: TestSetDefaultServicePort

func TestSetDefaultServicePort(t *testing.T) {
	// Unchanged if set.
	in := &versioned.Service{Spec: versioned.ServiceSpec{
		Ports: []versioned.ServicePort{
			{Protocol: "UDP", Port: 9376, TargetPort: util.NewIntOrStringFromString("p")},
			{Protocol: "UDP", Port: 8675, TargetPort: util.NewIntOrStringFromInt(309)},
		},
	}}
	out := roundTrip(t, runtime.Object(in)).(*versioned.Service)
	if out.Spec.Ports[0].Protocol != versioned.ProtocolUDP {
		t.Errorf("Expected protocol %s, got %s", versioned.ProtocolUDP, out.Spec.Ports[0].Protocol)
	}
	if out.Spec.Ports[0].TargetPort != util.NewIntOrStringFromString("p") {
		t.Errorf("Expected port %d, got %s", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort)
	}
	if out.Spec.Ports[1].Protocol != versioned.ProtocolUDP {
		t.Errorf("Expected protocol %s, got %s", versioned.ProtocolUDP, out.Spec.Ports[1].Protocol)
	}
	if out.Spec.Ports[1].TargetPort != util.NewIntOrStringFromInt(309) {
		t.Errorf("Expected port %d, got %s", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort)
	}

	// Defaulted.
	in = &versioned.Service{Spec: versioned.ServiceSpec{
		Ports: []versioned.ServicePort{
			{Protocol: "", Port: 9376, TargetPort: util.NewIntOrStringFromString("")},
			{Protocol: "", Port: 8675, TargetPort: util.NewIntOrStringFromInt(0)},
		},
	}}
	out = roundTrip(t, runtime.Object(in)).(*versioned.Service)
	if out.Spec.Ports[0].Protocol != versioned.ProtocolTCP {
		t.Errorf("Expected protocol %s, got %s", versioned.ProtocolTCP, out.Spec.Ports[0].Protocol)
	}
	if out.Spec.Ports[0].TargetPort != util.NewIntOrStringFromInt(in.Spec.Ports[0].Port) {
		t.Errorf("Expected port %d, got %d", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort)
	}
	if out.Spec.Ports[1].Protocol != versioned.ProtocolTCP {
		t.Errorf("Expected protocol %s, got %s", versioned.ProtocolTCP, out.Spec.Ports[1].Protocol)
	}
	if out.Spec.Ports[1].TargetPort != util.NewIntOrStringFromInt(in.Spec.Ports[1].Port) {
		t.Errorf("Expected port %d, got %d", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort)
	}
}
开发者ID:eghobo,项目名称:kubedash,代码行数:43,代码来源:defaults_test.go


示例7: TestGetURLParts

func TestGetURLParts(t *testing.T) {
	testCases := []struct {
		probe *api.HTTPGetProbe
		ok    bool
		host  string
		port  int
		path  string
	}{
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromInt(-1), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromString(""), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromString("-1"), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromString("not-found"), Path: ""}, false, "", -1, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromString("found"), Path: ""}, true, "127.0.0.1", 93, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromInt(76), Path: ""}, true, "127.0.0.1", 76, ""},
		{&api.HTTPGetProbe{Host: "", Port: util.NewIntOrStringFromString("118"), Path: ""}, true, "127.0.0.1", 118, ""},
		{&api.HTTPGetProbe{Host: "hostname", Port: util.NewIntOrStringFromInt(76), Path: "path"}, true, "hostname", 76, "path"},
	}

	for _, test := range testCases {
		state := api.PodState{PodIP: "127.0.0.1"}
		container := api.Container{
			Ports: []api.Port{{Name: "found", HostPort: 93}},
			LivenessProbe: &api.LivenessProbe{
				HTTPGet: test.probe,
				Type:    "http",
			},
		}
		host, port, path, err := getURLParts(state, container)
		if !test.ok && err == nil {
			t.Errorf("Expected error for %+v, got %s:%d/%s", test, host, port, path)
		}
		if test.ok && err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if test.ok {
			if host != test.host || port != test.port || path != test.path {
				t.Errorf("Expected %s:%d/%s, got %s:%d/%s",
					test.host, test.port, test.path, host, port, path)
			}
		}
	}
}
开发者ID:hvdb,项目名称:kubernetes,代码行数:42,代码来源:http_test.go


示例8: TestGetTCPAddrParts

func TestGetTCPAddrParts(t *testing.T) {
	testCases := []struct {
		probe *api.TCPSocketAction
		ok    bool
		host  string
		port  int
	}{
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromInt(-1)}, false, "", -1},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromString("")}, false, "", -1},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromString("-1")}, false, "", -1},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromString("not-found")}, false, "", -1},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromString("found")}, true, "1.2.3.4", 93},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromInt(76)}, true, "1.2.3.4", 76},
		{&api.TCPSocketAction{Port: util.NewIntOrStringFromString("118")}, true, "1.2.3.4", 118},
	}

	for _, test := range testCases {
		host := "1.2.3.4"
		container := api.Container{
			Ports: []api.ContainerPort{{Name: "found", HostPort: 93}},
			LivenessProbe: &api.Probe{
				Handler: api.Handler{
					TCPSocket: test.probe,
				},
			},
		}
		port, err := extractPort(test.probe.Port, container)
		if !test.ok && err == nil {
			t.Errorf("Expected error for %+v, got %s:%d", test, host, port)
		}
		if test.ok && err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if test.ok {
			if host != test.host || port != test.port {
				t.Errorf("Expected %s:%d, got %s:%d", test.host, test.port, host, port)
			}
		}
	}
}
开发者ID:vrosnet,项目名称:kubernetes,代码行数:40,代码来源:probe_test.go


示例9: TestHTTPHealthChecker

func TestHTTPHealthChecker(t *testing.T) {
	testCases := []struct {
		probe  *api.HTTPGetAction
		status int
		health Status
	}{
		// The probe will be filled in below.  This is primarily testing that an HTTP GET happens.
		{&api.HTTPGetAction{}, http.StatusOK, Healthy},
		{&api.HTTPGetAction{}, -1, Unhealthy},
		{nil, -1, Unknown},
	}
	hc := &HTTPHealthChecker{
		client: &http.Client{},
	}
	for _, test := range testCases {
		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(test.status)
		}))
		u, err := url.Parse(ts.URL)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		host, port, err := net.SplitHostPort(u.Host)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		container := api.Container{
			LivenessProbe: &api.LivenessProbe{
				HTTPGet: test.probe,
				Type:    "http",
			},
		}
		params := container.LivenessProbe.HTTPGet
		if params != nil {
			params.Port = util.NewIntOrStringFromString(port)
			params.Host = host
		}
		health, err := hc.HealthCheck("test", api.PodState{PodIP: host}, container)
		if test.health == Unknown && err == nil {
			t.Errorf("Expected error")
		}
		if test.health != Unknown && err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if health != test.health {
			t.Errorf("Expected %v, got %v", test.health, health)
		}
	}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:49,代码来源:http_test.go


示例10: TestHealthChecker

func TestHealthChecker(t *testing.T) {
	AddHealthChecker(&HTTPHealthChecker{client: &http.Client{}})
	var healthCheckerTests = []struct {
		status int
		health Status
	}{
		{http.StatusOK, Healthy},
		{statusServerEarlyShutdown, Unknown},
		{http.StatusBadRequest, Unhealthy},
		{http.StatusBadGateway, Unhealthy},
		{http.StatusInternalServerError, Unhealthy},
	}
	for _, healthCheckerTest := range healthCheckerTests {
		tt := healthCheckerTest
		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(tt.status)
		}))
		defer ts.Close()
		u, err := url.Parse(ts.URL)
		if err != nil {
			t.Fatalf("Unexpected error: %v", err)
		}
		host, port, err := net.SplitHostPort(u.Host)
		if err != nil {
			t.Fatalf("Unexpected error: %v", err)
		}
		if tt.status == statusServerEarlyShutdown {
			ts.Close()
		}
		container := api.Container{
			LivenessProbe: &api.LivenessProbe{
				HTTPGet: &api.HTTPGetAction{
					Port: util.NewIntOrStringFromString(port),
					Path: "/foo/bar",
					Host: host,
				},
			},
		}
		hc := NewHealthChecker()
		health, err := hc.HealthCheck("test", "", api.PodState{}, container)
		if err != nil && tt.health != Unknown {
			t.Errorf("Unexpected error: %v", err)
		}
		if health != tt.health {
			t.Errorf("Expected %v, got %v", tt.health, health)
		}
	}
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:48,代码来源:health_test.go


示例11: TestTcpHealthChecker

func TestTcpHealthChecker(t *testing.T) {
	tests := []struct {
		probe          *api.TCPSocketProbe
		expectedStatus Status
		expectError    bool
	}{
		// The probe will be filled in below.  This is primarily testing that a connection is made.
		{&api.TCPSocketProbe{}, Healthy, false},
		{&api.TCPSocketProbe{}, Unhealthy, false},
		{nil, Unknown, true},
	}

	checker := &TCPHealthChecker{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	u, err := url.Parse(server.URL)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	host, port, err := net.SplitHostPort(u.Host)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	for _, test := range tests {
		container := api.Container{
			LivenessProbe: &api.LivenessProbe{
				TCPSocket: test.probe,
				Type:      "tcp",
			},
		}
		params := container.LivenessProbe.TCPSocket
		if params != nil && test.expectedStatus == Healthy {
			params.Port = util.NewIntOrStringFromString(port)
		}
		status, err := checker.HealthCheck("test", api.PodState{PodIP: host}, container)
		if status != test.expectedStatus {
			t.Errorf("expected: %v, got: %v", test.expectedStatus, status)
		}
		if err != nil && !test.expectError {
			t.Errorf("unexpected error: %#v", err)
		}
		if err == nil && test.expectError {
			t.Errorf("unexpected non-error.")
		}
	}
}
开发者ID:hvdb,项目名称:kubernetes,代码行数:47,代码来源:tcp_test.go


示例12: Generate

func (ServiceGenerator) Generate(params map[string]string) (runtime.Object, error) {
	selectorString, found := params["selector"]
	if !found || len(selectorString) == 0 {
		return nil, fmt.Errorf("'selector' is a required parameter.")
	}
	selector := ParseLabels(selectorString)
	name, found := params["name"]
	if !found {
		return nil, fmt.Errorf("'name' is a required parameter.")
	}
	portString, found := params["port"]
	if !found {
		return nil, fmt.Errorf("'port' is a required parameter.")
	}
	port, err := strconv.Atoi(portString)
	if err != nil {
		return nil, err
	}
	service := api.Service{
		ObjectMeta: api.ObjectMeta{
			Name: name,
		},
		Spec: api.ServiceSpec{
			Port:     port,
			Protocol: api.Protocol(params["protocol"]),
			Selector: selector,
		},
	}
	containerPort, found := params["container-port"]
	if found && len(containerPort) > 0 {
		if cPort, err := strconv.Atoi(containerPort); err != nil {
			service.Spec.ContainerPort = util.NewIntOrStringFromString(containerPort)
		} else {
			service.Spec.ContainerPort = util.NewIntOrStringFromInt(cPort)
		}
	} else {
		service.Spec.ContainerPort = util.NewIntOrStringFromInt(port)
	}
	if params["create-external-load-balancer"] == "true" {
		service.Spec.CreateExternalLoadBalancer = true
	}
	if len(params["public-ip"]) != 0 {
		service.Spec.PublicIPs = []string{params["public-ip"]}
	}
	return &service, nil
}
开发者ID:vrosnet,项目名称:kubernetes,代码行数:46,代码来源:service.go


示例13: TestMuxHealthChecker

func TestMuxHealthChecker(t *testing.T) {
	muxHealthCheckerTests := []struct {
		health    Status
		probeType string
	}{
		{Healthy, "http"},
		{Unknown, "ftp"},
	}
	mc := &muxHealthChecker{
		checkers: make(map[string]HealthChecker),
	}
	hc := &HTTPHealthChecker{
		client: &http.Client{},
	}
	mc.checkers["http"] = hc
	for _, muxHealthCheckerTest := range muxHealthCheckerTests {
		tt := muxHealthCheckerTest
		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
		}))
		u, err := url.Parse(ts.URL)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		host, port, err := net.SplitHostPort(u.Host)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		container := api.Container{
			LivenessProbe: &api.LivenessProbe{
				HTTPGet: &api.HTTPGetProbe{},
			},
		}
		container.LivenessProbe.Type = tt.probeType
		container.LivenessProbe.HTTPGet.Port = util.NewIntOrStringFromString(port)
		container.LivenessProbe.HTTPGet.Host = host
		health, err := mc.HealthCheck("test", api.PodState{}, container)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if health != tt.health {
			t.Errorf("Expected %v, got %v", tt.health, health)
		}
	}
}
开发者ID:hvdb,项目名称:kubernetes,代码行数:45,代码来源:health_test.go


示例14: TestMuxHealthChecker

func TestMuxHealthChecker(t *testing.T) {
	muxHealthCheckerTests := []struct {
		health Status
	}{
		// TODO: This test should run through a few different checker types.
		{Healthy},
	}
	mc := &muxHealthChecker{
		checkers: []HealthChecker{
			&HTTPHealthChecker{client: &http.Client{}},
		},
	}
	for _, muxHealthCheckerTest := range muxHealthCheckerTests {
		tt := muxHealthCheckerTest
		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
		}))
		defer ts.Close()
		u, err := url.Parse(ts.URL)
		if err != nil {
			t.Fatalf("Unexpected error: %v", err)
		}
		host, port, err := net.SplitHostPort(u.Host)
		if err != nil {
			t.Fatalf("Unexpected error: %v", err)
		}
		container := api.Container{
			LivenessProbe: &api.LivenessProbe{
				HTTPGet: &api.HTTPGetAction{},
			},
		}
		container.LivenessProbe.HTTPGet.Port = util.NewIntOrStringFromString(port)
		container.LivenessProbe.HTTPGet.Host = host
		health, err := mc.HealthCheck("test", "", api.PodState{}, container)
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if health != tt.health {
			t.Errorf("Expected %v, got %v", tt.health, health)
		}
	}
}
开发者ID:ericcapricorn,项目名称:kubernetes,代码行数:42,代码来源:health_test.go


示例15: TestGetEndpoints

func TestGetEndpoints(t *testing.T) {
	// 2 pods each of which have 3 targetPorts exposed via a single service
	endpointAddresses := []api.EndpointAddress{
		{IP: "1.2.3.4"},
		{IP: "6.7.8.9"},
	}
	ports := []int{80, 443, 3306}
	endpointPorts := []api.EndpointPort{
		{Port: ports[0], Protocol: "TCP"},
		{Port: ports[1], Protocol: "TCP"},
		{Port: ports[2], Protocol: "TCP", Name: "mysql"},
	}
	servicePorts := []api.ServicePort{
		{Port: 10, TargetPort: util.NewIntOrStringFromInt(ports[0])},
		{Port: 20, TargetPort: util.NewIntOrStringFromInt(ports[1])},
		{Port: 30, TargetPort: util.NewIntOrStringFromString("mysql")},
	}

	svc := getService(servicePorts)
	endpoints := []*api.Endpoints{getEndpoints(svc, endpointAddresses, endpointPorts)}
	flb := newFakeLoadBalancerController(endpoints, []*api.Service{svc})

	for i := range ports {
		eps := flb.getEndpoints(svc, &svc.Spec.Ports[i])
		expectedEps := util.NewStringSet()
		for _, address := range endpointAddresses {
			expectedEps.Insert(fmt.Sprintf("%v:%v", address.IP, ports[i]))
		}

		receivedEps := util.NewStringSet()
		for _, ep := range eps {
			receivedEps.Insert(ep)
		}
		if len(receivedEps) != len(expectedEps) || !expectedEps.IsSuperset(receivedEps) {
			t.Fatalf("Unexpected endpoints, received %+v, expected %+v", receivedEps, expectedEps)
		}
		glog.Infof("Got endpoints %+v", receivedEps)
	}
}
开发者ID:Bazooki,项目名称:kubernetes,代码行数:39,代码来源:service_loadbalancer_test.go


示例16: init


//.........这里部分代码省略.........
			out.Source.Host = in.Host
			out.Timestamp = in.Timestamp
			return s.Convert(&in.InvolvedObject, &out.InvolvedObject, 0)
		},

		// This is triggered for the Memory field of Container.
		func(in *int64, out *resource.Quantity, s conversion.Scope) error {
			out.Set(*in)
			out.Format = resource.BinarySI
			return nil
		},
		func(in *resource.Quantity, out *int64, s conversion.Scope) error {
			*out = in.Value()
			return nil
		},

		// This is triggered by the CPU field of Container.
		// Note that if we add other int/Quantity conversions my
		// simple hack (int64=Value(), int=MilliValue()) here won't work.
		func(in *int, out *resource.Quantity, s conversion.Scope) error {
			out.SetMilli(int64(*in))
			out.Format = resource.DecimalSI
			return nil
		},
		func(in *resource.Quantity, out *int, s conversion.Scope) error {
			*out = int(in.MilliValue())
			return nil
		},

		// Convert resource lists.
		func(in *ResourceList, out *newer.ResourceList, s conversion.Scope) error {
			*out = newer.ResourceList{}
			for k, v := range *in {
				fv, err := strconv.ParseFloat(v.String(), 64)
				if err != nil {
					return &newer.ConversionError{
						In: in, Out: out,
						Message: fmt.Sprintf("value '%v' of '%v': %v", v, k, err),
					}
				}
				if k == ResourceCPU {
					(*out)[newer.ResourceCPU] = *resource.NewMilliQuantity(int64(fv*1000), resource.DecimalSI)
				} else {
					(*out)[newer.ResourceName(k)] = *resource.NewQuantity(int64(fv), resource.BinarySI)
				}
			}
			return nil
		},
		func(in *newer.ResourceList, out *ResourceList, s conversion.Scope) error {
			*out = ResourceList{}
			for k, v := range *in {
				if k == newer.ResourceCPU {
					(*out)[ResourceCPU] = util.NewIntOrStringFromString(fmt.Sprintf("%v", float64(v.MilliValue())/1000))
				} else {
					(*out)[ResourceName(k)] = util.NewIntOrStringFromInt(int(v.Value()))
				}
			}
			return nil
		},

		// VolumeSource's HostDir is deprecated in favor of HostPath.
		// TODO: It would be great if I could just map field names to
		// convert or else maybe say "convert all members of this
		// struct" and then fix up only the stuff that changed.
		func(in *newer.VolumeSource, out *VolumeSource, s conversion.Scope) error {
			if err := s.Convert(&in.EmptyDir, &out.EmptyDir, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.GitRepo, &out.GitRepo, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.GCEPersistentDisk, &out.GCEPersistentDisk, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.HostPath, &out.HostDir, 0); err != nil {
				return err
			}
			return nil
		},
		func(in *VolumeSource, out *newer.VolumeSource, s conversion.Scope) error {
			if err := s.Convert(&in.EmptyDir, &out.EmptyDir, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.GitRepo, &out.GitRepo, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.GCEPersistentDisk, &out.GCEPersistentDisk, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.HostDir, &out.HostPath, 0); err != nil {
				return err
			}
			return nil
		},
	)
	if err != nil {
		// If one of the conversion functions is malformed, detect it immediately.
		panic(err)
	}
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:101,代码来源:conversion.go


示例17: addConversionFuncs


//.........这里部分代码省略.........
		func(in *int, out *resource.Quantity, s conversion.Scope) error {
			out.SetMilli(int64(*in))
			out.Format = resource.DecimalSI
			return nil
		},
		func(in *resource.Quantity, out *int, s conversion.Scope) error {
			*out = int(in.MilliValue())
			return nil
		},

		// Convert resource lists.
		func(in *ResourceList, out *api.ResourceList, s conversion.Scope) error {
			*out = api.ResourceList{}
			for k, v := range *in {
				fv, err := strconv.ParseFloat(v.String(), 64)
				if err != nil {
					return &api.ConversionError{
						In: in, Out: out,
						Message: fmt.Sprintf("value '%v' of '%v': %v", v, k, err),
					}
				}
				if k == ResourceCPU {
					(*out)[api.ResourceCPU] = *resource.NewMilliQuantity(int64(fv*1000), resource.DecimalSI)
				} else {
					(*out)[api.ResourceName(k)] = *resource.NewQuantity(int64(fv), resource.BinarySI)
				}
			}
			return nil
		},
		func(in *api.ResourceList, out *ResourceList, s conversion.Scope) error {
			*out = ResourceList{}
			for k, v := range *in {
				if k == api.ResourceCPU {
					(*out)[ResourceCPU] = util.NewIntOrStringFromString(fmt.Sprintf("%v", float64(v.MilliValue())/1000))
				} else {
					(*out)[ResourceName(k)] = util.NewIntOrStringFromInt(int(v.Value()))
				}
			}
			return nil
		},

		func(in *api.Volume, out *Volume, s conversion.Scope) error {
			if err := s.Convert(&in.VolumeSource, &out.Source, 0); err != nil {
				return err
			}
			out.Name = in.Name
			return nil
		},
		func(in *Volume, out *api.Volume, s conversion.Scope) error {
			if err := s.Convert(&in.Source, &out.VolumeSource, 0); err != nil {
				return err
			}
			out.Name = in.Name
			return nil
		},

		func(in *api.VolumeSource, out *VolumeSource, s conversion.Scope) error {
			if err := s.Convert(&in.EmptyDir, &out.EmptyDir, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.GitRepo, &out.GitRepo, 0); err != nil {
				return err
			}
			if err := s.Convert(&in.ISCSI, &out.ISCSI, 0); err != nil {
				return err
			}
开发者ID:spinolacastro,项目名称:docker-influxdb,代码行数:67,代码来源:conversion.go


示例18: proxyContext

func proxyContext(version string) {
	f := NewFramework("proxy")
	prefix := "/api/" + version

	It("should proxy logs on node with explicit kubelet port", func() {
		node, err := pickNode(f.Client)
		Expect(err).NotTo(HaveOccurred())
		// AbsPath preserves the trailing '/'.
		body, err := f.Client.Get().AbsPath(prefix + "/proxy/nodes/" + node + ":10250/logs/").Do().Raw()
		if len(body) > 0 {
			if len(body) > 100 {
				body = body[:100]
				body = append(body, '.', '.', '.')
			}
			Logf("Got: %s", body)
		}
		Expect(err).NotTo(HaveOccurred())
	})

	It("should proxy logs on node", func() {
		node, err := pickNode(f.Client)
		Expect(err).NotTo(HaveOccurred())
		body, err := f.Client.Get().AbsPath(prefix + "/proxy/nodes/" + node + "/logs/").Do().Raw()
		if len(body) > 0 {
			if len(body) > 100 {
				body = body[:100]
				body = append(body, '.', '.', '.')
			}
			Logf("Got: %s", body)
		}
		Expect(err).NotTo(HaveOccurred())
	})

	It("should proxy to cadvisor", func() {
		node, err := pickNode(f.Client)
		Expect(err).NotTo(HaveOccurred())
		body, err := f.Client.Get().AbsPath(prefix + "/proxy/nodes/" + node + ":4194/containers/").Do().Raw()
		if len(body) > 0 {
			if len(body) > 100 {
				body = body[:100]
				body = append(body, '.', '.', '.')
			}
			Logf("Got: %s", body)
		}
		Expect(err).NotTo(HaveOccurred())
	})

	It("should proxy through a service and a pod", func() {
		labels := map[string]string{"proxy-service-target": "true"}
		service, err := f.Client.Services(f.Namespace.Name).Create(&api.Service{
			ObjectMeta: api.ObjectMeta{
				GenerateName: "proxy-service-",
			},
			Spec: api.ServiceSpec{
				Selector: labels,
				Ports: []api.ServicePort{
					{
						Name:       "portname1",
						Port:       80,
						TargetPort: util.NewIntOrStringFromString("dest1"),
					},
					{
						Name:       "portname2",
						Port:       81,
						TargetPort: util.NewIntOrStringFromInt(162),
					},
				},
			},
		})
		Expect(err).NotTo(HaveOccurred())
		defer func(name string) {
			err := f.Client.Services(f.Namespace.Name).Delete(name)
			if err != nil {
				Logf("Failed deleting service %v: %v", name, err)
			}
		}(service.Name)

		// Make an RC with a single pod.
		pods := []*api.Pod{}
		cfg := RCConfig{
			Client:       f.Client,
			Image:        "gcr.io/google_containers/porter:91d46193649807d1340b46797774d8b2",
			Name:         service.Name,
			Namespace:    f.Namespace.Name,
			Replicas:     1,
			PollInterval: time.Second,
			Env: map[string]string{
				"SERVE_PORT_80":  "not accessible via service",
				"SERVE_PORT_160": "foo",
				"SERVE_PORT_162": "bar",
			},
			Ports: map[string]int{
				"dest1": 160,
				"dest2": 162,
			},
			Labels:      labels,
			CreatedPods: &pods,
		}
		Expect(RunRC(cfg)).NotTo(HaveOccurred())
		defer DeleteRC(f.Client, f.Namespace.Name, cfg.Name)
//.........这里部分代码省略.........
开发者ID:mbforbes,项目名称:kubernetes,代码行数:101,代码来源:proxy.go


示例19: init

func init() {
	api.Scheme.AddDefaultingFuncs(
		func(obj *ReplicationController) {
			if len(obj.DesiredState.ReplicaSelector) == 0 {
				obj.DesiredState.ReplicaSelector = obj.DesiredState.PodTemplate.Labels
			}
			if len(obj.Labels) == 0 {
				obj.Labels = obj.DesiredState.PodTemplate.Labels
			}
		},
		func(obj *Volume) {
			if util.AllPtrFieldsNil(&obj.Source) {
				glog.Errorf("Defaulting volume source for %v", obj)
				obj.Source = VolumeSource{
					EmptyDir: &EmptyDirVolumeSource{},
				}
			}
		},
		func(obj *ContainerPort) {
			if obj.Protocol == "" {
				obj.Protocol = ProtocolTCP
			}
		},
		func(obj *Container) {
			if obj.ImagePullPolicy == "" {
				// TODO(dchen1107): Move ParseImageName code to pkg/util
				parts := strings.Split(obj.Image, ":")
				// Check image tag
				if parts[len(parts)-1] == "latest" {
					obj.ImagePullPolicy = PullAlways
				} else {
					obj.ImagePullPolicy = PullIfNotPresent
				}
			}
			if obj.TerminationMessagePath == "" {
				obj.TerminationMessagePath = TerminationMessagePathDefault
			}
		},
		func(obj *RestartPolicy) {
			if util.AllPtrFieldsNil(obj) {
				obj.Always = &RestartPolicyAlways{}
			}
		},
		func(obj *Service) {
			if obj.Protocol == "" {
				obj.Protocol = ProtocolTCP
			}
			if obj.SessionAffinity == "" {
				obj.SessionAffinity = AffinityTypeNone
			}
			for i := range obj.Ports {
				sp := &obj.Ports[i]
				if sp.Protocol == "" {
					sp.Protocol = ProtocolTCP
				}
				if sp.ContainerPort == util.NewIntOrStringFromInt(0) || sp.ContainerPort == util.NewIntOrStringFromString("") {
					sp.ContainerPort = util.NewIntOrStringFromInt(sp.Port)
				}
			}
		},
		func(obj *PodSpec) {
			if obj.DNSPolicy == "" {
				obj.DNSPolicy = DNSClusterFirst
			}
			if obj.HostNetwork {
				defaultHostNetworkPorts(&obj.Containers)
			}
		},
		func(obj *ContainerManifest) {
			if obj.DNSPolicy == "" {
				obj.DNSPolicy = DNSClusterFirst
			}
			if obj.HostNetwork {
				defaultHostNetworkPorts(&obj.Containers)
			}
		},
		func(obj *LivenessProbe) {
			if obj.TimeoutSeconds == 0 {
				obj.TimeoutSeconds = 1
			}
		},
		func(obj *Secret) {
			if obj.Type == "" {
				obj.Type = SecretTypeOpaque
			}
		},
		func(obj *Endpoints) {
			if obj.Protocol == "" {
				obj.Protocol = ProtocolTCP
			}
			if len(obj.Subsets) == 0 && len(obj.Endpoints) > 0 {
				// Must be a legacy-style object - populate
				// Subsets from the older fields.  Do this the
				// simplest way, which is dumb (but valid).
				for i := range obj.Endpoints {
					host, portStr, err := net.SplitHostPort(obj.Endpoints[i])
					if err != nil {
						glog.Errorf("failed to SplitHostPort(%q)", obj.Endpoints[i])
					}
					var tgtRef *ObjectReference
//.........这里部分代码省略.........
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:101,代码来源:defaults.go


示例20: Generate

func (ServiceGenerator) Generate(params map[string]string) (runtime.Object, error) {
	selectorString, found := params["selector"]
	if !found || len(selectorString) == 0 {
		return nil, fmt.Errorf("'selector' is a required parameter.")
	}
	selector, err := ParseLabels(selectorString)
	if err != nil {
		return nil, err
	}

	labelsString, found := params["labels"]
	var labels map[string]string
	if found && len(labelsString) > 0 {
		labels, err = ParseLabels(labelsString)
		if err != nil {
			return nil, err
		}
	}

	name, found := params["name"]
	if !found {
		return nil, fmt.Errorf("'name' is a required parameter.")
	}
	portString, found := params["port"]
	if !found {
		return nil, fmt.Errorf("'port' is a required parameter.")
	}
	port, err := strconv.Atoi(portString)
	if err != nil {
		return nil, err
	}
	service := api.Service{
		ObjectMeta: api.ObjectMeta{
			Name:   name,
			Labels: labels,
		},
		Spec: api.ServiceSpec{
			Selector: selector,
			Ports: []api.ServicePort{
				{
					Name:     "default",
					Port:     port,
					Protocol: api.Protocol(params["protocol"]),
				},
			},
		},
	}
	targetPort, found := params["target-port"]
	if !found {
		targetPort, found = params["container-port"]
	}
	if found && len(targetPort) > 0 {
		if portNum, err := strconv.Atoi(targetPort); err != nil {
			service.Spec.Ports[0].TargetPort = util.NewIntOrStringFromString(targetPort)
		} else {
			service.Spec.Ports[0].TargetPort = util.NewIntOrStringFromInt(portNum)
		}
	} else {
		service.Spec.Ports[0].TargetPort = util.NewIntOrStringFromInt(port)
	}
	if params["create-external-load-balancer"] == "true" {
		service.Spec.CreateExternalLoadBalancer = true
	}
	if len(params["public-ip"]) != 0 {
		service.Spec.PublicIPs = []string{params["public-ip"]}
	}
	return &service, nil
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:68,代码来源:service.go



注:本文中的github.com/GoogleCloudPlatform/kubernetes/pkg/util.NewIntOrStringFromString函数示例整理自Github/MSDocs等


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang util.NewLogger函数代码示例发布时间:2022-05-23
下一篇:
Golang util.NewIntOrStringFromInt函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap