示例#1
0
func makeRawConfigFromV1Config(imageJSON []byte, rootfs *image.RootFS, history []image.History) (map[string]*json.RawMessage, error) {
	var dver struct {
		DockerVersion string `json:"docker_version"`
	}

	if err := json.Unmarshal(imageJSON, &dver); err != nil {
		return nil, err
	}

	useFallback := versionPkg.Version(dver.DockerVersion).LessThan("1.8.3")

	if useFallback {
		var v1Image image.V1Image
		err := json.Unmarshal(imageJSON, &v1Image)
		if err != nil {
			return nil, err
		}
		imageJSON, err = json.Marshal(v1Image)
		if err != nil {
			return nil, err
		}
	}

	var c map[string]*json.RawMessage
	if err := json.Unmarshal(imageJSON, &c); err != nil {
		return nil, err
	}

	c["rootfs"] = rawJSON(rootfs)
	c["history"] = rawJSON(history)

	return c, nil
}
示例#2
0
// What we're trying to do here is compare the JSON encoded values, but we can't
// to a simple encode + string compare since JSON encoding is not ordered. So
// what we do is JSON encode, then JSON decode into untyped maps, and then
// finally do a recursive comparison.
func compareObjects(t *testing.T, expected interface{}, actual interface{}) {
	expectedBytes, err := json.Marshal(expected)
	if err != nil {
		t.Fatal(err)
		return
	}
	actualBytes, err := json.Marshal(actual)
	if err != nil {
		t.Fatal(err)
		return
	}
	var expectedUntyped, actualUntyped map[string]interface{}
	err = json.Unmarshal(expectedBytes, &expectedUntyped)
	if err != nil {
		t.Fatal(err)
		return
	}
	err = json.Unmarshal(actualBytes, &actualUntyped)
	if err != nil {
		t.Fatal(err)
		return
	}
	if !reflect.DeepEqual(expectedUntyped, actualUntyped) {
		t.Fatalf("Expected %s, got %s", string(expectedBytes), string(actualBytes))
	}
}
func UtilCreateNetworkMode(c *check.C, networkMode string) {
	config := map[string]interface{}{
		"Image":      "busybox",
		"HostConfig": map[string]interface{}{"NetworkMode": networkMode},
	}

	status, body, err := sockRequest("POST", "/containers/create", config)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusCreated)

	var container types.ContainerCreateResponse
	if err := json.Unmarshal(body, &container); err != nil {
		c.Fatal(err)
	}

	status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	var containerJSON types.ContainerJSON
	if err := json.Unmarshal(body, &containerJSON); err != nil {
		c.Fatal(err)
	}

	if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
		c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
	}
}
示例#4
0
文件: auth_user.go 项目: kjplatz/vic
func (u *httpAuthUserAPI) modUser(ctx context.Context, req *authUserAPIAction) (*User, error) {
	resp, body, err := u.client.Do(ctx, req)
	if err != nil {
		return nil, err
	}
	if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
		var sec authError
		err = json.Unmarshal(body, &sec)
		if err != nil {
			return nil, err
		}
		return nil, sec
	}
	var user User
	if err = json.Unmarshal(body, &user); err != nil {
		var userR UserRoles
		if urerr := json.Unmarshal(body, &userR); urerr != nil {
			return nil, err
		}
		user.User = userR.User
		for _, r := range userR.Roles {
			user.Roles = append(user.Roles, r.Role)
		}
	}
	return &user, nil
}
示例#5
0
// ManifestMatchesImage returns true if the provided manifest matches the name of the image.
func ManifestMatchesImage(image *Image, newManifest []byte) (bool, error) {
	dgst, err := digest.ParseDigest(image.Name)
	if err != nil {
		return false, err
	}
	v, err := digest.NewDigestVerifier(dgst)
	if err != nil {
		return false, err
	}
	var canonical []byte

	switch image.DockerImageManifestMediaType {
	case schema2.MediaTypeManifest:
		var m schema2.DeserializedManifest
		if err := json.Unmarshal(newManifest, &m); err != nil {
			return false, err
		}
		_, canonical, err = m.Payload()
		if err != nil {
			return false, err
		}
	case schema1.MediaTypeManifest, "":
		var m schema1.SignedManifest
		if err := json.Unmarshal(newManifest, &m); err != nil {
			return false, err
		}
		canonical = m.Canonical
	default:
		return false, fmt.Errorf("unsupported manifest mediatype: %s", image.DockerImageManifestMediaType)
	}
	if _, err := v.Write(canonical); err != nil {
		return false, err
	}
	return v.Verified(), nil
}
示例#6
0
func (t *Tags) UnmarshalJSON(data []byte) error {
	var tags []Tag

	switch data[0] {
	case '[':
		// Unmarshal into []Tag
		if err := json.Unmarshal(data, &tags); err != nil {
			return err
		}
	case '{':
		// Unmarshal into map[string]string
		tagMap := make(map[string]string)
		if err := json.Unmarshal(data, &tagMap); err != nil {
			return err
		}

		// Convert to []Tag
		for k, v := range tagMap {
			tags = append(tags, Tag{k, v})
		}
	default:
		return ErrUnableToUnmarshalJSON
	}

	*t = tags
	return nil
}
//Tests #1109, where design doc contains multiple views
func TestViewQueryMultipleViews(t *testing.T) {
	var rt restTester
	//Define three views
	response := rt.sendAdminRequest("PUT", "/db/_design/foo", `{"views": {"by_fname": {"map": "function (doc, meta) { emit(doc.fname, null); }"},"by_lname": {"map": "function (doc, meta) { emit(doc.lname, null); }"},"by_age": {"map": "function (doc, meta) { emit(doc.age, null); }"}}}`)
	assertStatus(t, response, 201)
	response = rt.sendRequest("PUT", "/db/doc1", `{"fname": "Alice", "lname":"Ten", "age":10}`)
	assertStatus(t, response, 201)
	response = rt.sendRequest("PUT", "/db/doc2", `{"fname": "Bob", "lname":"Seven", "age":7}`)
	assertStatus(t, response, 201)

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_age", ``)
	assertStatus(t, response, 200)
	var result sgbucket.ViewResult
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 2)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: interface{}(nil)})
	assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: interface{}(nil)})

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_fname", ``)
	assertStatus(t, response, 200)
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 2)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc1", Key: "Alice", Value: interface{}(nil)})
	assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc2", Key: "Bob", Value: interface{}(nil)})

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_lname", ``)
	assertStatus(t, response, 200)
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 2)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: "Seven", Value: interface{}(nil)})
	assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc1", Key: "Ten", Value: interface{}(nil)})
}
示例#8
0
func (plugin *execNetworkPlugin) Status(namespace string, name string, id kubeletTypes.DockerID) (*network.PodNetworkStatus, error) {
	out, err := utilexec.New().Command(plugin.getExecutable(), statusCmd, namespace, name, string(id)).CombinedOutput()
	glog.V(5).Infof("Status 'exec' network plugin output: %s, %v", string(out), err)
	if err != nil {
		return nil, err
	}
	if string(out) == "" {
		return nil, nil
	}
	findVersion := struct {
		api.TypeMeta `json:",inline"`
	}{}
	err = json.Unmarshal(out, &findVersion)
	if err != nil {
		return nil, err
	}

	// check kind and version
	if findVersion.Kind != "" && findVersion.Kind != "PodNetworkStatus" {
		errStr := fmt.Sprintf("Invalid 'kind' returned in network status for pod '%s'. Valid value is 'PodNetworkStatus', got '%s'.", name, findVersion.Kind)
		return nil, errors.New(errStr)
	}
	switch findVersion.APIVersion {
	case "":
		fallthrough
	case "v1beta1":
		networkStatus := &network.PodNetworkStatus{}
		err = json.Unmarshal(out, networkStatus)
		return networkStatus, err
	}
	errStr := fmt.Sprintf("Unknown version '%s' in network status for pod '%s'.", findVersion.APIVersion, name)
	return nil, errors.New(errStr)
}
示例#9
0
func RetrieveStatelessApplication(name string) (*StatelessSerializable, error) {
	stateless, err := GetStorage().LoadStatelessApplication(name)
	if err != nil {
		log.Error("Load stateless application error %s", err)
		return nil, err
	}

	replicationControllerJsonMap := make(map[string]interface{})
	err = json.Unmarshal(stateless.replicationControllerJson, &replicationControllerJsonMap)
	if err != nil {
		log.Error("Unmarshal replication controller json for stateless application error %s", err)
		return nil, err
	}
	serviceJsonMap := make(map[string]interface{})
	err = json.Unmarshal(stateless.serviceJson, &serviceJsonMap)
	if err != nil {
		log.Error("Unmarshal service json for stateless application error %s", err)
		return nil, err
	}

	statelessSerializable := &StatelessSerializable{
		stateless.Name,
		stateless.Description,
		replicationControllerJsonMap,
		serviceJsonMap,
		stateless.Environment,
	}

	return statelessSerializable, nil
}
示例#10
0
// CanEmulateNetworkConditions - Tells whether emulation of network conditions is supported.
// Returns -  result - True if emulation of network conditions is supported.
func (c *Network) CanEmulateNetworkConditions() (bool, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.canEmulateNetworkConditions"})
	if err != nil {
		return false, err
	}

	var chromeData struct {
		Result struct {
			Result bool
		}
	}

	if resp == nil {
		return false, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return false, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return false, err
	}

	return chromeData.Result.Result, nil
}
示例#11
0
// GetCertificateDetails - Returns details for the given certificate.
// certificateId - ID of the certificate to get details for.
// Returns -  result - Certificate details.
func (c *Network) GetCertificateDetails(certificateId int) (*NetworkCertificateDetails, error) {
	paramRequest := make(map[string]interface{}, 1)
	paramRequest["certificateId"] = certificateId
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getCertificateDetails", Params: paramRequest})
	if err != nil {
		return nil, err
	}

	var chromeData struct {
		Result struct {
			Result *NetworkCertificateDetails
		}
	}

	if resp == nil {
		return nil, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return nil, err
	}

	return chromeData.Result.Result, nil
}
示例#12
0
// GetCookies - Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the <code>cookies</code> field.
// Returns -  cookies - Array of cookie objects.
func (c *Network) GetCookies() ([]*NetworkCookie, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getCookies"})
	if err != nil {
		return nil, err
	}

	var chromeData struct {
		Result struct {
			Cookies []*NetworkCookie
		}
	}

	if resp == nil {
		return nil, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return nil, err
	}

	return chromeData.Result.Cookies, nil
}
示例#13
0
// GetResponseBody - Returns content served for the given request.
// requestId - Identifier of the network request to get content for.
// Returns -  body - Response body. base64Encoded - True, if content was sent as base64.
func (c *Network) GetResponseBody(requestId string) (string, bool, error) {
	paramRequest := make(map[string]interface{}, 1)
	paramRequest["requestId"] = requestId
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getResponseBody", Params: paramRequest})
	if err != nil {
		return "", false, err
	}

	var chromeData struct {
		Result struct {
			Body          string
			Base64Encoded bool
		}
	}

	if resp == nil {
		return "", false, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return "", false, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return "", false, err
	}

	return chromeData.Result.Body, chromeData.Result.Base64Encoded, nil
}
示例#14
0
// associate a profile to a blade
func (s *UCSService) AssociateUcsProfileToBlade(p *AssociateUcsProfileToBladeParams) (*AssociateUcsProfileToBladeResponse, error) {
	resp, err := s.cs.newRequest("associateUcsProfileToBlade", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r AssociateUcsProfileToBladeResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			return nil, err
		}
		// If 'warn' has a value it means the job is running longer than the configured
		// timeout, the resonse will contain the jobid of the running async job
		if warn != nil {
			return &r, warn
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}
示例#15
0
func (testSuite *BoolTest) TestBool(c *C) {
	inputBuf := `{"B": true, "C": false, "D": {"Ref": "foo"}, "E": "true"}`

	v := struct {
		A *BoolExpr `json:",omitempty"`
		B *BoolExpr `json:",omitempty"`
		C *BoolExpr `json:",omitempty"`
		D *BoolExpr `json:",omitempty"`
		E *BoolExpr `json:",omitempty"`
	}{}

	err := json.Unmarshal([]byte(inputBuf), &v)
	c.Assert(err, IsNil)

	c.Assert(v.A, IsNil)
	c.Assert(v.B, DeepEquals, Bool(true))
	c.Assert(v.C, DeepEquals, Bool(false))
	c.Assert(v.D, DeepEquals, Ref("foo").Bool())
	c.Assert(v.E, DeepEquals, Bool(true))

	buf, err := json.Marshal(v)
	c.Assert(err, IsNil)
	c.Assert(string(buf), Equals,
		`{"B":true,"C":false,"D":{"Ref":"foo"},"E":true}`)

	inputBuf = `{"A": "invalid"}`
	err = json.Unmarshal([]byte(inputBuf), &v)
	c.Assert(err, ErrorMatches, "json: cannot unmarshal string into Go value of type bool")

	inputBuf = `{"A": {"Fn::Missing": "invalid"}}`
	err = json.Unmarshal([]byte(inputBuf), &v)
	c.Assert(err, ErrorMatches, "unknown function Fn::Missing")
}
示例#16
0
func (q *SearchQuery) Get() ([]SearchResult, error) {
	querystring, err := q.buildQuery()
	if err != nil {
		return nil, err
	}
	resp, err := http.Get(querystring)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	result := make([]SearchResult, 0)
	err = json.Unmarshal(body, &result)
	if err != nil {
		err_obj := new(searchResultError)
		err := json.Unmarshal(body, err_obj)
		if err != nil {
			return nil, err
		} else {
			return nil, errors.New(err_obj.error)
		}
	}
	if len(result) == 0 {
		return nil, errors.New("Nothing found; sorry :/")
	}
	return result, nil
}
示例#17
0
// adds a baremetal dhcp server
func (s *BaremetalService) AddBaremetalDhcp(p *AddBaremetalDhcpParams) (*AddBaremetalDhcpResponse, error) {
	resp, err := s.cs.newRequest("addBaremetalDhcp", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r AddBaremetalDhcpResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}
示例#18
0
// Analyzed creates a new analyzed spec document
func Analyzed(data json.RawMessage, version string) (*Document, error) {
	if version == "" {
		version = "2.0"
	}
	if version != "2.0" {
		return nil, fmt.Errorf("spec version %q is not supported", version)
	}

	swspec := new(spec.Swagger)
	if err := json.Unmarshal(data, swspec); err != nil {
		return nil, err
	}

	origsqspec := new(spec.Swagger)
	if err := json.Unmarshal(data, origsqspec); err != nil {
		return nil, err
	}

	d := &Document{
		Analyzer: analysis.New(swspec),
		schema:   swag20Schema,
		spec:     swspec,
		raw:      data,
		origSpec: origsqspec,
	}
	return d, nil
}
示例#19
0
func TestViewQuery(t *testing.T) {
	var rt restTester
	response := rt.sendAdminRequest("PUT", "/db/_design/foo", `{"views":{"bar": {"map": "function(doc) {emit(doc.key, doc.value);}"}}}`)
	assertStatus(t, response, 201)
	response = rt.sendRequest("PUT", "/db/doc1", `{"key":10, "value":"ten"}`)
	assertStatus(t, response, 201)
	response = rt.sendRequest("PUT", "/db/doc2", `{"key":7, "value":"seven"}`)
	assertStatus(t, response, 201)

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/bar", ``)
	assertStatus(t, response, 200)
	var result sgbucket.ViewResult
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 2)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"})
	assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: "ten"})

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/bar?limit=1", ``)
	assertStatus(t, response, 200)
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 1)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"})

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/bar?endkey=9", ``)
	assertStatus(t, response, 200)
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 1)
	assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"})

	response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/bar?endkey=9&include_docs=true", ``)
	assertStatus(t, response, 200)
	json.Unmarshal(response.Body.Bytes(), &result)
	assert.Equals(t, len(result.Rows), 1)
	assert.DeepEquals(t, *result.Rows[0].Doc, map[string]interface{}{"key": 7.0, "value": "seven"})
}
示例#20
0
func TestCertificateRequest(t *testing.T) {

	// Good
	var goodCR CertificateRequest
	err := json.Unmarshal(testCertificateRequestGood, &goodCR)
	if err != nil {
		t.Errorf("Error unmarshaling good certificate request: %v", err)
	}
	if err = goodCR.CSR.CheckSignature(); err != nil {
		t.Errorf("Valid CSR in CertificateRequest failed to verify: %v", err)
	}

	// Bad CSR
	var badCR CertificateRequest
	err = json.Unmarshal(testCertificateRequestBadCSR, &badCR)
	if err == nil {
		t.Errorf("Unexpectedly accepted certificate request with bad CSR")
	}

	// Marshal
	jsonCR, err := json.Marshal(goodCR)
	if err != nil {
		t.Errorf("Failed to marshal good certificate request: %v", err)
	}
	err = json.Unmarshal(jsonCR, &goodCR)
	if err != nil {
		t.Errorf("Marshalled certificate request failed to unmarshal: %v", err)
	}
}
示例#21
0
文件: auth_user.go 项目: kjplatz/vic
func (u *httpAuthUserAPI) ListUsers(ctx context.Context) ([]string, error) {
	resp, body, err := u.client.Do(ctx, &authUserAPIList{})
	if err != nil {
		return nil, err
	}
	if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
		var sec authError
		err = json.Unmarshal(body, &sec)
		if err != nil {
			return nil, err
		}
		return nil, sec
	}

	var userList struct {
		Users []User `json:"users"`
	}

	if err = json.Unmarshal(body, &userList); err != nil {
		return nil, err
	}

	ret := make([]string, 0, len(userList.Users))
	for _, u := range userList.Users {
		ret = append(ret, u.User)
	}
	return ret, nil
}
//  delete a Cisco Nexus VSM device
func (s *ExternalDeviceService) DeleteCiscoNexusVSM(p *DeleteCiscoNexusVSMParams) (*DeleteCiscoNexusVSMResponse, error) {
	resp, err := s.cs.newRequest("deleteCiscoNexusVSM", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteCiscoNexusVSMResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			return nil, err
		}
		// If 'warn' has a value it means the job is running longer than the configured
		// timeout, the resonse will contain the jobid of the running async job
		if warn != nil {
			return &r, warn
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}
示例#23
0
// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string
func (s *StringOrArray) UnmarshalJSON(data []byte) error {
	if len(data) < 3 {
		return nil
	}

	if data[0] == '[' {
		var parsed []string
		if err := json.Unmarshal(data, &parsed); err != nil {
			return err
		}
		*s = StringOrArray(parsed)
		return nil
	}

	var single interface{}
	if err := json.Unmarshal(data, &single); err != nil {
		return err
	}
	if single == nil {
		return nil
	}
	switch single.(type) {
	case string:
		*s = StringOrArray([]string{single.(string)})
		return nil
	default:
		return fmt.Errorf("only string or array is allowed, not %T", single)
	}
}
示例#24
0
func (m *httpMembersAPI) Add(ctx context.Context, peerURL string) (*Member, error) {
	urls, err := types.NewURLs([]string{peerURL})
	if err != nil {
		return nil, err
	}

	req := &membersAPIActionAdd{peerURLs: urls}
	resp, body, err := m.client.Do(ctx, req)
	if err != nil {
		return nil, err
	}

	if err := assertStatusCode(resp.StatusCode, http.StatusCreated, http.StatusConflict); err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusCreated {
		var merr membersError
		if err := json.Unmarshal(body, &merr); err != nil {
			return nil, err
		}
		return nil, merr
	}

	var memb Member
	if err := json.Unmarshal(body, &memb); err != nil {
		return nil, err
	}

	return &memb, nil
}
示例#25
0
// New creates a new App with the provided environment.
func New(env map[string]string) (*App, error) {
	var app App
	appVar := env["VCAP_APPLICATION"]
	if err := json.Unmarshal([]byte(appVar), &app); err != nil {
		return nil, err
	}
	app.Home = env["HOME"]
	app.MemoryLimit = env["MEMORY_LIMIT"]
	app.WorkingDir = env["PWD"]
	app.TempDir = env["TMPDIR"]
	app.User = env["USER"]
	var rawServices map[string]interface{}
	servicesVar := env["VCAP_SERVICES"]
	if err := json.Unmarshal([]byte(servicesVar), &rawServices); err != nil {
		return nil, err
	}

	services := make(map[string][]Service)
	for k, v := range rawServices {
		var serviceInstances []Service
		if err := mapstructure.WeakDecode(v, &serviceInstances); err != nil {
			return nil, err
		}
		services[k] = serviceInstances
	}
	app.Services = services
	return &app, nil
}
示例#26
0
// MakeDockerKeyring inspects the passedSecrets to see if they contain any DockerConfig secrets.  If they do,
// then a DockerKeyring is built based on every hit and unioned with the defaultKeyring.
// If they do not, then the default keyring is returned
func MakeDockerKeyring(passedSecrets []api.Secret, defaultKeyring DockerKeyring) (DockerKeyring, error) {
	passedCredentials := []DockerConfig{}
	for _, passedSecret := range passedSecrets {
		if dockerConfigJsonBytes, dockerConfigJsonExists := passedSecret.Data[api.DockerConfigJsonKey]; (passedSecret.Type == api.SecretTypeDockerConfigJson) && dockerConfigJsonExists && (len(dockerConfigJsonBytes) > 0) {
			dockerConfigJson := DockerConfigJson{}
			if err := json.Unmarshal(dockerConfigJsonBytes, &dockerConfigJson); err != nil {
				return nil, err
			}

			passedCredentials = append(passedCredentials, dockerConfigJson.Auths)
		} else if dockercfgBytes, dockercfgExists := passedSecret.Data[api.DockerConfigKey]; (passedSecret.Type == api.SecretTypeDockercfg) && dockercfgExists && (len(dockercfgBytes) > 0) {
			dockercfg := DockerConfig{}
			if err := json.Unmarshal(dockercfgBytes, &dockercfg); err != nil {
				return nil, err
			}

			passedCredentials = append(passedCredentials, dockercfg)
		}
	}

	if len(passedCredentials) > 0 {
		basicKeyring := &BasicDockerKeyring{}
		for _, currCredentials := range passedCredentials {
			basicKeyring.Add(currCredentials)
		}
		return &unionDockerKeyring{[]DockerKeyring{basicKeyring, defaultKeyring}}, nil
	}

	return defaultKeyring, nil
}
func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
	testRequires(c, DaemonIsLinux)
	domainName := "test-domain"
	config := map[string]interface{}{
		"Image":      "busybox",
		"Domainname": domainName,
	}

	status, body, err := sockRequest("POST", "/containers/create", config)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusCreated)

	var container types.ContainerCreateResponse
	if err := json.Unmarshal(body, &container); err != nil {
		c.Fatal(err)
	}

	status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	var containerJSON types.ContainerJSON
	if err := json.Unmarshal(body, &containerJSON); err != nil {
		c.Fatal(err)
	}

	if containerJSON.Config.Domainname != domainName {
		c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname)
	}
}
//  delete a Cisco Nexus VSM device
func (s *ExternalDeviceService) DeleteCiscoNexusVSM(p *DeleteCiscoNexusVSMParams) (*DeleteCiscoNexusVSMResponse, error) {
	resp, err := s.cs.newRequest("deleteCiscoNexusVSM", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteCiscoNexusVSMResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}
	return &r, nil
}
func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
	testRequires(c, DaemonIsLinux)
	config := map[string]interface{}{
		"Image":      "busybox",
		"CpuShares":  512,
		"CpusetCpus": "0,1",
	}

	status, body, err := sockRequest("POST", "/containers/create", config)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusCreated)

	var container types.ContainerCreateResponse
	if err := json.Unmarshal(body, &container); err != nil {
		c.Fatal(err)
	}

	status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	var containerJSON types.ContainerJSON

	c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)

	out, err := inspectField(containerJSON.ID, "HostConfig.CpuShares")
	c.Assert(err, check.IsNil)
	c.Assert(out, check.Equals, "512")

	outCpuset, errCpuset := inspectField(containerJSON.ID, "HostConfig.CpusetCpus")
	c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset))
	c.Assert(outCpuset, check.Equals, "0,1")
}
示例#30
0
// CheckResponse checks the API response for error, and returns it
// if present. A response is considered an error if it has non StatusOK
// code.
func CheckResponse(r *http.Response) error {
	if r.StatusCode == http.StatusOK {
		return nil
	}
	data, readErr := ioutil.ReadAll(r.Body)
	if readErr != nil {
		return readErr
	}

	// Forbidden: see http://instagram.com/developer/restrict-api-requests/
	if r.StatusCode == http.StatusForbidden {
		err := &Error{}
		json.Unmarshal(data, &err)
		return err
	}

	// RateLimit: see http://instagram.com/developer/limits/
	if r.StatusCode == 429 {
		err := &Error{}
		json.Unmarshal(data, &err)
		return err
	}

	// Sometimes Instagram returns 500 with plain message
	// "Oops, an error occurred.".
	if r.StatusCode == http.StatusInternalServerError {
		err := &Error{
			ErrorType:    "Internal Server Error",
			Code:         http.StatusInternalServerError,
			ErrorMessage: "Oops, an error occurred.",
		}
		return err
	}

	if data != nil {
		// Unlike for successful (2XX) requests, unsuccessful
		// requests SOMETIMES have the {Meta: Error{}} format but
		// SOMETIMES they are just Error{}. From what I can tell, there is not
		// an obvious rationale behind what gets constructed in which way, so
		// we need to try both:
		err := &Error{}
		json.Unmarshal(data, err)
		if *err == *new(Error) {
			// Unmarshaling did nothing for us, so the format was not Error{}.
			// We will assume the format was {Meta: Error{}}:
			temp := make(map[string]Error)
			json.Unmarshal(data, &temp)

			meta := temp["meta"]

			delete(temp, "meta") // Probably uselesss
			return &meta
		}

		// Unmarshaling did something
		return err
	}

	return nil
}