Exemple #1
0
func GetContainerInfo(containerID string) (*info.ContainerInfo, error) {
	cinfo := new(info.ContainerInfo)
	cinfo.Stats = make([]*info.ContainerStats, 0)
	containerStats := &info.ContainerStats{
		Timestamp: time.Now(),
		Memory: &info.MemoryStats{
			Stats: make(map[string]uint64),
		},
	}
	if err := getMemoryStats(containerID, containerStats); err != nil {
		return nil, err
	}
	cinfo.Spec.HasMemory = true
	if err := getMemorySpec(containerID, cinfo); err != nil {
		return nil, err
	}
	cinfo.Spec.HasCpu = true
	if err := getCpusetSpec(containerID, cinfo); err != nil {
		return nil, err
	}
	cinfo.Stats = append(cinfo.Stats, containerStats)

	return cinfo, nil
}
func testHTTPContainerInfoGetter(
	req *info.ContainerInfoRequest,
	cinfo *info.ContainerInfo,
	podID string,
	containerID string,
	status int,
	t *testing.T,
) {
	expectedPath := "/stats"
	if len(podID) > 0 && len(containerID) > 0 {
		expectedPath = path.Join(expectedPath, podID, containerID)
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if status != 0 {
			w.WriteHeader(status)
		}
		if strings.TrimRight(r.URL.Path, "/") != strings.TrimRight(expectedPath, "/") {
			t.Fatalf("Received request to an invalid path. Should be %v. got %v",
				expectedPath, r.URL.Path)
		}

		var receivedReq info.ContainerInfoRequest
		err := json.NewDecoder(r.Body).Decode(&receivedReq)
		if err != nil {
			t.Fatal(err)
		}
		// Note: This will not make a deep copy of req.
		// So changing req after Get*Info would be a race.
		expectedReq := req
		// Fill any empty fields with default value
		if !reflect.DeepEqual(expectedReq, &receivedReq) {
			t.Errorf("received wrong request")
		}
		err = json.NewEncoder(w).Encode(cinfo)
		if err != nil {
			t.Fatal(err)
		}
	}))
	defer ts.Close()
	hostURL, err := url.Parse(ts.URL)
	if err != nil {
		t.Fatal(err)
	}
	parts := strings.Split(hostURL.Host, ":")

	port, err := strconv.Atoi(parts[1])
	if err != nil {
		t.Fatal(err)
	}

	containerInfoGetter := &HTTPContainerInfoGetter{
		Client: http.DefaultClient,
		Port:   port,
	}

	var receivedContainerInfo *info.ContainerInfo
	if len(podID) > 0 && len(containerID) > 0 {
		receivedContainerInfo, err = containerInfoGetter.GetContainerInfo(parts[0], podID, containerID, req)
	} else {
		receivedContainerInfo, err = containerInfoGetter.GetRootInfo(parts[0], req)
	}
	if status == 0 || status == http.StatusOK {
		if err != nil {
			t.Errorf("received unexpected error: %v", err)
		}

		if !receivedContainerInfo.Eq(cinfo) {
			t.Error("received unexpected container info")
		}
	} else {
		if err == nil {
			t.Error("did not receive expected error.")
		}
	}
}