kraken
81 строка · 2.2 Кб
1// Copyright (c) 2016-2019 Uber Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package agentclient
15
16import (
17"errors"
18"fmt"
19"io"
20"io/ioutil"
21"net/url"
22
23"github.com/uber/kraken/core"
24"github.com/uber/kraken/utils/httputil"
25)
26
27// Client errors.
28var (
29ErrTagNotFound = errors.New("tag not found")
30)
31
32// Client defines a client for accessing the agent server.
33type Client interface {
34GetTag(tag string) (core.Digest, error)
35Download(namespace string, d core.Digest) (io.ReadCloser, error)
36}
37
38// HTTPClient provides a wrapper for HTTP operations on an agent.
39type HTTPClient struct {
40addr string
41}
42
43// New creates a new client for an agent at addr.
44func New(addr string) *HTTPClient {
45return &HTTPClient{addr}
46}
47
48// GetTag resolves tag into a digest. Returns ErrTagNotFound if the tag does
49// not exist.
50func (c *HTTPClient) GetTag(tag string) (core.Digest, error) {
51resp, err := httputil.Get(fmt.Sprintf("http://%s/tags/%s", c.addr, url.PathEscape(tag)))
52if err != nil {
53if httputil.IsNotFound(err) {
54return core.Digest{}, ErrTagNotFound
55}
56return core.Digest{}, err
57}
58defer resp.Body.Close()
59b, err := ioutil.ReadAll(resp.Body)
60if err != nil {
61return core.Digest{}, fmt.Errorf("read body: %s", err)
62}
63d, err := core.ParseSHA256Digest(string(b))
64if err != nil {
65return core.Digest{}, fmt.Errorf("parse digest: %s", err)
66}
67return d, nil
68}
69
70// Download returns the blob of d. Callers should close the returned ReadCloser
71// when done reading the blob.
72func (c *HTTPClient) Download(namespace string, d core.Digest) (io.ReadCloser, error) {
73resp, err := httputil.Get(
74fmt.Sprintf(
75"http://%s/namespace/%s/blobs/%s",
76c.addr, url.PathEscape(namespace), d))
77if err != nil {
78return nil, err
79}
80return resp.Body, nil
81}
82