First step of combination.

pull/6/head
Daniel Smith 2014-06-22 14:18:01 -07:00
parent e811e24b23
commit 61a494d303
11 changed files with 189 additions and 196 deletions

View File

@ -147,7 +147,7 @@ func executeAPIRequest(method string, auth *kube_client.AuthInfo) bool {
return false return false
} }
s := cloudcfg.New(*httpServer, auth) s := kube_client.New(*httpServer, auth)
r := s.Verb(verb). r := s.Verb(verb).
Path("api/v1beta1"). Path("api/v1beta1").
Path(parseStorage()). Path(parseStorage()).
@ -187,18 +187,16 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool {
return flag.Arg(1) return flag.Arg(1)
} }
c := kube_client.New(*httpServer, auth)
var err error var err error
switch method { switch method {
case "stop": case "stop":
err = cloudcfg.StopController(parseController(), kube_client.Client{Host: *httpServer, Auth: auth}) err = cloudcfg.StopController(parseController(), c)
case "rm": case "rm":
err = cloudcfg.DeleteController(parseController(), kube_client.Client{Host: *httpServer, Auth: auth}) err = cloudcfg.DeleteController(parseController(), c)
case "rollingupdate": case "rollingupdate":
client := &kube_client.Client{ err = cloudcfg.Update(parseController(), c, *updatePeriod)
Host: *httpServer,
Auth: auth,
}
err = cloudcfg.Update(parseController(), client, *updatePeriod)
case "run": case "run":
if len(flag.Args()) != 4 { if len(flag.Args()) != 4 {
log.Fatal("usage: cloudcfg [OPTIONS] run <image> <replicas> <controller>") log.Fatal("usage: cloudcfg [OPTIONS] run <image> <replicas> <controller>")
@ -209,7 +207,7 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool {
if err != nil { if err != nil {
log.Fatalf("Error parsing replicas: %#v", err) log.Fatalf("Error parsing replicas: %#v", err)
} }
err = cloudcfg.RunController(image, name, replicas, kube_client.Client{Host: *httpServer, Auth: auth}, *portSpec, *servicePort) err = cloudcfg.RunController(image, name, replicas, c, *portSpec, *servicePort)
case "resize": case "resize":
args := flag.Args() args := flag.Args()
if len(args) < 3 { if len(args) < 3 {
@ -220,7 +218,7 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool {
if err != nil { if err != nil {
log.Fatalf("Error parsing replicas: %#v", err) log.Fatalf("Error parsing replicas: %#v", err)
} }
err = cloudcfg.ResizeController(name, replicas, kube_client.Client{Host: *httpServer, Auth: auth}) err = cloudcfg.ResizeController(name, replicas, c)
default: default:
return false return false
} }

View File

@ -47,10 +47,9 @@ func main() {
// Set up logger for etcd client // Set up logger for etcd client
etcd.SetLogger(log.New(os.Stderr, "etcd ", log.LstdFlags)) etcd.SetLogger(log.New(os.Stderr, "etcd ", log.LstdFlags))
controllerManager := controller.MakeReplicationManager(etcd.NewClient([]string{*etcd_servers}), controllerManager := controller.MakeReplicationManager(
client.Client{ etcd.NewClient([]string{*etcd_servers}),
Host: "http://" + *master, client.New("http://"+*master, nil))
})
controllerManager.Run(10 * time.Second) controllerManager.Run(10 * time.Second)
select {} select {}

View File

@ -49,10 +49,7 @@ func main() {
}, "/api/v1beta1") }, "/api/v1beta1")
server := httptest.NewServer(apiserver) server := httptest.NewServer(apiserver)
controllerManager := controller.MakeReplicationManager(etcd.NewClient(servers), controllerManager := controller.MakeReplicationManager(etcd.NewClient(servers), client.New(server.URL, nil))
client.Client{
Host: server.URL,
})
controllerManager.Run(10 * time.Second) controllerManager.Run(10 * time.Second)
@ -61,9 +58,7 @@ func main() {
// Wait for the synchronization threads to come up. // Wait for the synchronization threads to come up.
time.Sleep(time.Second * 10) time.Sleep(time.Second * 10)
kubeClient := client.Client{ kubeClient := client.New(server.URL, nil)
Host: server.URL,
}
data, err := ioutil.ReadFile("api/examples/controller.json") data, err := ioutil.ReadFile("api/examples/controller.json")
if err != nil { if err != nil {
log.Fatalf("Unexpected error: %#v", err) log.Fatalf("Unexpected error: %#v", err)

View File

@ -86,10 +86,9 @@ func api_server() {
// Starts up a controller manager. Never returns. // Starts up a controller manager. Never returns.
func controller_manager() { func controller_manager() {
controllerManager := controller.MakeReplicationManager(etcd.NewClient([]string{*etcd_server}), controllerManager := controller.MakeReplicationManager(
client.Client{ etcd.NewClient([]string{*etcd_server}),
Host: fmt.Sprintf("http://%s:%d", *master_address, *master_port), client.New(fmt.Sprintf("http://%s:%d", *master_address, *master_port), nil))
})
controllerManager.Run(20 * time.Second) controllerManager.Run(20 * time.Second)
select {} select {}

View File

@ -59,47 +59,62 @@ type AuthInfo struct {
// Client is the actual implementation of a Kubernetes client. // Client is the actual implementation of a Kubernetes client.
// Host is the http://... base for the URL // Host is the http://... base for the URL
type Client struct { type Client struct {
Host string host string
Auth *AuthInfo auth *AuthInfo
httpClient *http.Client httpClient *http.Client
} }
// Underlying base implementation of performing a request. // Create a new client object.
// method is the HTTP method (e.g. "GET") func New(host string, auth *AuthInfo) *Client {
// path is the path on the host to hit return &Client{
// requestBody is the body of the request. Can be nil. auth: auth,
// target the interface to marshal the JSON response into. Can be nil. host: host,
func (client Client) rawRequest(method, path string, requestBody io.Reader, target interface{}) ([]byte, error) { httpClient: &http.Client{
request, err := http.NewRequest(method, client.makeURL(path), requestBody) Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
},
}
}
// Execute a request, adds authentication (if auth != nil), and HTTPS cert ignoring.
func (c *Client) doRequest(request *http.Request) ([]byte, error) {
if c.auth != nil {
request.SetBasicAuth(c.auth.User, c.auth.Password)
}
response, err := c.httpClient.Do(request)
if err != nil { if err != nil {
return []byte{}, err return []byte{}, err
} }
if client.Auth != nil {
request.SetBasicAuth(client.Auth.User, client.Auth.Password)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
var httpClient *http.Client
if client.httpClient != nil {
httpClient = client.httpClient
} else {
httpClient = &http.Client{Transport: tr}
}
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close() defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body) body, err := ioutil.ReadAll(response.Body)
if err != nil { if err != nil {
return body, err return body, err
} }
if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPartialContent { if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPartialContent {
return nil, fmt.Errorf("request [%s %s] failed (%d) %s: %s", method, client.makeURL(path), response.StatusCode, response.Status, string(body)) return nil, fmt.Errorf("request [%#v] failed (%d) %s: %s", request, response.StatusCode, response.Status, string(body))
}
return body, err
}
// Underlying base implementation of performing a request.
// method is the HTTP method (e.g. "GET")
// path is the path on the host to hit
// requestBody is the body of the request. Can be nil.
// target the interface to marshal the JSON response into. Can be nil.
func (c *Client) rawRequest(method, path string, requestBody io.Reader, target interface{}) ([]byte, error) {
request, err := http.NewRequest(method, c.makeURL(path), requestBody)
if err != nil {
return []byte{}, err
}
body, err := c.doRequest(request)
if err != nil {
return body, err
} }
if target != nil { if target != nil {
err = json.Unmarshal(body, target) err = api.DecodeInto(body, target)
} }
if err != nil { if err != nil {
log.Printf("Failed to parse: %s\n", string(body)) log.Printf("Failed to parse: %s\n", string(body))
@ -109,7 +124,7 @@ func (client Client) rawRequest(method, path string, requestBody io.Reader, targ
} }
func (client Client) makeURL(path string) string { func (client Client) makeURL(path string) string {
return client.Host + "/api/v1beta1/" + path return client.host + "/api/v1beta1/" + path
} }
// EncodeSelector transforms a selector expressed as a key/value map, into a // EncodeSelector transforms a selector expressed as a key/value map, into a

View File

@ -38,7 +38,7 @@ func makeUrl(suffix string) string {
func TestListEmptyPods(t *testing.T) { func TestListEmptyPods(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/pods"}, Request: testRequest{Method: "GET", Path: "/pods"},
Response: Response{StatusCode: 200, Body: api.PodList{}}, Response: Response{StatusCode: 200, Body: api.PodList{}},
} }
podList, err := c.Setup().ListPods(nil) podList, err := c.Setup().ListPods(nil)
@ -47,7 +47,7 @@ func TestListEmptyPods(t *testing.T) {
func TestListPods(t *testing.T) { func TestListPods(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/pods"}, Request: testRequest{Method: "GET", Path: "/pods"},
Response: Response{StatusCode: 200, Response: Response{StatusCode: 200,
Body: api.PodList{ Body: api.PodList{
Items: []api.Pod{ Items: []api.Pod{
@ -76,7 +76,7 @@ func validateLabels(a, b string) bool {
func TestListPodsLabels(t *testing.T) { func TestListPodsLabels(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/pods", Query: url.Values{"labels": []string{"foo=bar,name=baz"}}}, Request: testRequest{Method: "GET", Path: "/pods", Query: url.Values{"labels": []string{"foo=bar,name=baz"}}},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: api.PodList{ Body: api.PodList{
@ -103,7 +103,7 @@ func TestListPodsLabels(t *testing.T) {
func TestGetPod(t *testing.T) { func TestGetPod(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/pods/foo"}, Request: testRequest{Method: "GET", Path: "/pods/foo"},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: api.Pod{ Body: api.Pod{
@ -123,7 +123,7 @@ func TestGetPod(t *testing.T) {
func TestDeletePod(t *testing.T) { func TestDeletePod(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "DELETE", Path: "/pods/foo"}, Request: testRequest{Method: "DELETE", Path: "/pods/foo"},
Response: Response{StatusCode: 200}, Response: Response{StatusCode: 200},
} }
err := c.Setup().DeletePod("foo") err := c.Setup().DeletePod("foo")
@ -141,7 +141,7 @@ func TestCreatePod(t *testing.T) {
}, },
} }
c := &TestClient{ c := &TestClient{
Request: Request{Method: "POST", Path: "/pods", Body: requestPod}, Request: testRequest{Method: "POST", Path: "/pods", Body: requestPod},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: requestPod, Body: requestPod,
@ -163,7 +163,7 @@ func TestUpdatePod(t *testing.T) {
}, },
} }
c := &TestClient{ c := &TestClient{
Request: Request{Method: "PUT", Path: "/pods/foo"}, Request: testRequest{Method: "PUT", Path: "/pods/foo"},
Response: Response{StatusCode: 200, Body: requestPod}, Response: Response{StatusCode: 200, Body: requestPod},
} }
receivedPod, err := c.Setup().UpdatePod(requestPod) receivedPod, err := c.Setup().UpdatePod(requestPod)
@ -172,7 +172,7 @@ func TestUpdatePod(t *testing.T) {
func TestGetController(t *testing.T) { func TestGetController(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/replicationControllers/foo"}, Request: testRequest{Method: "GET", Path: "/replicationControllers/foo"},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: api.ReplicationController{ Body: api.ReplicationController{
@ -200,7 +200,7 @@ func TestUpdateController(t *testing.T) {
}, },
} }
c := &TestClient{ c := &TestClient{
Request: Request{Method: "PUT", Path: "/replicationControllers/foo"}, Request: testRequest{Method: "PUT", Path: "/replicationControllers/foo"},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: api.ReplicationController{ Body: api.ReplicationController{
@ -223,7 +223,7 @@ func TestUpdateController(t *testing.T) {
func TestDeleteController(t *testing.T) { func TestDeleteController(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "DELETE", Path: "/replicationControllers/foo"}, Request: testRequest{Method: "DELETE", Path: "/replicationControllers/foo"},
Response: Response{StatusCode: 200}, Response: Response{StatusCode: 200},
} }
err := c.Setup().DeleteReplicationController("foo") err := c.Setup().DeleteReplicationController("foo")
@ -237,7 +237,7 @@ func TestCreateController(t *testing.T) {
}, },
} }
c := &TestClient{ c := &TestClient{
Request: Request{Method: "POST", Path: "/replicationControllers", Body: requestController}, Request: testRequest{Method: "POST", Path: "/replicationControllers", Body: requestController},
Response: Response{ Response: Response{
StatusCode: 200, StatusCode: 200,
Body: api.ReplicationController{ Body: api.ReplicationController{
@ -267,7 +267,7 @@ func body(obj interface{}, raw *string) *string {
return raw return raw
} }
type Request struct { type testRequest struct {
Method string Method string
Path string Path string
Header string Header string
@ -284,7 +284,7 @@ type Response struct {
type TestClient struct { type TestClient struct {
*Client *Client
Request Request Request testRequest
Response Response Response Response
Error bool Error bool
server *httptest.Server server *httptest.Server
@ -306,9 +306,9 @@ func (c *TestClient) Setup() *TestClient {
} }
c.server = httptest.NewTLSServer(c.handler) c.server = httptest.NewTLSServer(c.handler)
if c.Client == nil { if c.Client == nil {
c.Client = &Client{} c.Client = New("", nil)
} }
c.Client.Host = c.server.URL c.Client.host = c.server.URL
c.QueryValidator = map[string]func(string, string) bool{} c.QueryValidator = map[string]func(string, string) bool{}
return c return c
} }
@ -355,7 +355,7 @@ func (c *TestClient) Validate(t *testing.T, received interface{}, err error) {
func TestGetService(t *testing.T) { func TestGetService(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "GET", Path: "/services/1"}, Request: testRequest{Method: "GET", Path: "/services/1"},
Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}},
} }
response, err := c.Setup().GetService("1") response, err := c.Setup().GetService("1")
@ -364,7 +364,7 @@ func TestGetService(t *testing.T) {
func TestCreateService(t *testing.T) { func TestCreateService(t *testing.T) {
c := (&TestClient{ c := (&TestClient{
Request: Request{Method: "POST", Path: "/services", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Request: testRequest{Method: "POST", Path: "/services", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}},
Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}},
}).Setup() }).Setup()
response, err := c.Setup().CreateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}}) response, err := c.Setup().CreateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}})
@ -373,7 +373,7 @@ func TestCreateService(t *testing.T) {
func TestUpdateService(t *testing.T) { func TestUpdateService(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "PUT", Path: "/services/service-1", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Request: testRequest{Method: "PUT", Path: "/services/service-1", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}},
Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}},
} }
response, err := c.Setup().UpdateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}}) response, err := c.Setup().UpdateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}})
@ -382,7 +382,7 @@ func TestUpdateService(t *testing.T) {
func TestDeleteService(t *testing.T) { func TestDeleteService(t *testing.T) {
c := &TestClient{ c := &TestClient{
Request: Request{Method: "DELETE", Path: "/services/1"}, Request: testRequest{Method: "DELETE", Path: "/services/1"},
Response: Response{StatusCode: 200}, Response: Response{StatusCode: 200},
} }
err := c.Setup().DeleteService("1") err := c.Setup().DeleteService("1")
@ -391,16 +391,40 @@ func TestDeleteService(t *testing.T) {
func TestMakeRequest(t *testing.T) { func TestMakeRequest(t *testing.T) {
testClients := []TestClient{ testClients := []TestClient{
{Request: Request{Method: "GET", Path: "/good"}, Response: Response{StatusCode: 200}}, {Request: testRequest{Method: "GET", Path: "/good"}, Response: Response{StatusCode: 200}},
{Request: Request{Method: "GET", Path: "/bad%ZZ"}, Error: true}, {Request: testRequest{Method: "GET", Path: "/bad%ZZ"}, Error: true},
{Client: &Client{Auth: &AuthInfo{"foo", "bar"}}, Request: Request{Method: "GET", Path: "/auth", Header: "Authorization"}, Response: Response{StatusCode: 200}}, {Client: New("", &AuthInfo{"foo", "bar"}), Request: testRequest{Method: "GET", Path: "/auth", Header: "Authorization"}, Response: Response{StatusCode: 200}},
{Client: &Client{httpClient: http.DefaultClient}, Request: Request{Method: "GET", Path: "/nocertificate"}, Error: true}, {Client: &Client{httpClient: http.DefaultClient}, Request: testRequest{Method: "GET", Path: "/nocertificate"}, Error: true},
{Request: Request{Method: "GET", Path: "/error"}, Response: Response{StatusCode: 500}, Error: true}, {Request: testRequest{Method: "GET", Path: "/error"}, Response: Response{StatusCode: 500}, Error: true},
{Request: Request{Method: "POST", Path: "/faildecode"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, {Request: testRequest{Method: "POST", Path: "/faildecode"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true},
{Request: Request{Method: "GET", Path: "/failread"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, {Request: testRequest{Method: "GET", Path: "/failread"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true},
} }
for _, c := range testClients { for _, c := range testClients {
response, err := c.Setup().rawRequest(c.Request.Method, c.Request.Path[1:], nil, c.Target) response, err := c.Setup().rawRequest(c.Request.Method, c.Request.Path[1:], nil, c.Target)
c.Validate(t, response, err) c.Validate(t, response, err)
} }
} }
func TestDoRequest(t *testing.T) {
expectedBody := `{ "items": []}`
fakeHandler := util.FakeHandler{
StatusCode: 200,
ResponseBody: expectedBody,
T: t,
}
testServer := httptest.NewTLSServer(&fakeHandler)
request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
auth := AuthInfo{User: "user", Password: "pass"}
c := New(testServer.URL, &auth)
body, err := c.doRequest(request)
if request.Header["Authorization"] == nil {
t.Errorf("Request is missing authorization header: %#v", *request)
}
if err != nil {
t.Error("Unexpected error")
}
if string(body) != expectedBody {
t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body)
}
fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}

View File

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package cloudcfg package client
import ( import (
"bytes" "bytes"
@ -26,46 +26,33 @@ import (
"time" "time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
) )
// Server contains info locating a kubernetes api server. // Server contains info locating a kubernetes api server.
// Example usage: // Example usage:
// auth, err := LoadAuth(filename) // auth, err := LoadAuth(filename)
// s := New(url, auth) // c := New(url, auth)
// resp, err := s.Verb("GET"). // resp, err := c.Verb("GET").
// Path("api/v1beta1"). // Path("api/v1beta1").
// Path("pods"). // Path("pods").
// Selector("area=staging"). // Selector("area=staging").
// Timeout(10*time.Second). // Timeout(10*time.Second).
// Do() // Do()
// list, ok := resp.(api.PodList) // list, ok := resp.(api.PodList)
type Server struct {
auth *client.AuthInfo
rawUrl string
}
// Create a new server object.
func New(serverUrl string, auth *client.AuthInfo) *Server {
return &Server{
auth: auth,
rawUrl: serverUrl,
}
}
// Begin a request with a verb (GET, POST, PUT, DELETE) // Begin a request with a verb (GET, POST, PUT, DELETE)
func (s *Server) Verb(verb string) *Request { func (c *Client) Verb(verb string) *Request {
return &Request{ return &Request{
verb: verb, verb: verb,
s: s, c: c,
path: "/", path: "/",
} }
} }
// Request allows for building up a request to a server in a chained fashion. // Request allows for building up a request to a server in a chained fashion.
type Request struct { type Request struct {
s *Server c *Client
err error err error
verb string verb string
path string path string
@ -118,7 +105,7 @@ func (r *Request) Do() (interface{}, error) {
if r.err != nil { if r.err != nil {
return nil, r.err return nil, r.err
} }
finalUrl := r.s.rawUrl + r.path finalUrl := r.c.host + r.path
query := url.Values{} query := url.Values{}
if r.selector != nil { if r.selector != nil {
query.Add("labels", r.selector.String()) query.Add("labels", r.selector.String())
@ -150,7 +137,7 @@ func (r *Request) Do() (interface{}, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
str, err := doRequest(req, r.s.auth) str, err := r.c.doRequest(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -14,16 +14,16 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
package cloudcfg package client
import ( import (
"io/ioutil"
"net/http/httptest" "net/http/httptest"
"reflect" "reflect"
"testing" "testing"
"time" "time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util" "github.com/GoogleCloudPlatform/kubernetes/pkg/util"
) )
@ -37,7 +37,7 @@ func TestDoRequestNewWay(t *testing.T) {
T: t, T: t,
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
auth := client.AuthInfo{User: "user", Password: "pass"} auth := AuthInfo{User: "user", Password: "pass"}
s := New(testServer.URL, &auth) s := New(testServer.URL, &auth)
obj, err := s.Verb("POST"). obj, err := s.Verb("POST").
Path("foo/bar"). Path("foo/bar").
@ -65,7 +65,7 @@ func TestDoRequestNewWay(t *testing.T) {
} }
func TestDoRequestNewWayObj(t *testing.T) { func TestDoRequestNewWayObj(t *testing.T) {
reqObj := &api.Pod{} reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
reqBodyExpected, _ := api.Encode(reqObj) reqBodyExpected, _ := api.Encode(reqObj)
expectedObj := &api.Service{Port: 12345} expectedObj := &api.Service{Port: 12345}
expectedBody, _ := api.Encode(expectedObj) expectedBody, _ := api.Encode(expectedObj)
@ -75,7 +75,7 @@ func TestDoRequestNewWayObj(t *testing.T) {
T: t, T: t,
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
auth := client.AuthInfo{User: "user", Password: "pass"} auth := AuthInfo{User: "user", Password: "pass"}
s := New(testServer.URL, &auth) s := New(testServer.URL, &auth)
obj, err := s.Verb("POST"). obj, err := s.Verb("POST").
Path("foo/bar"). Path("foo/bar").
@ -102,3 +102,48 @@ func TestDoRequestNewWayObj(t *testing.T) {
t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived) t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
} }
} }
func TestDoRequestNewWayFile(t *testing.T) {
reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
reqBodyExpected, err := api.Encode(reqObj)
expectNoError(t, err)
file, err := ioutil.TempFile("", "foo")
expectNoError(t, err)
_, err = file.Write(reqBodyExpected)
expectNoError(t, err)
expectedObj := &api.Service{Port: 12345}
expectedBody, _ := api.Encode(expectedObj)
fakeHandler := util.FakeHandler{
StatusCode: 200,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewTLSServer(&fakeHandler)
auth := AuthInfo{User: "user", Password: "pass"}
s := New(testServer.URL, &auth)
obj, err := s.Verb("POST").
Path("foo/bar").
Path("baz").
Selector("name=foo").
Timeout(time.Second).
Body(file.Name()).
Do()
if err != nil {
t.Errorf("Unexpected error: %v %#v", err, err)
return
}
if obj == nil {
t.Error("nil obj")
} else if !reflect.DeepEqual(obj, expectedObj) {
t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
}
tmpStr := string(reqBodyExpected)
fakeHandler.ValidateRequest(t, "/foo/bar/baz", "POST", &tmpStr)
if fakeHandler.RequestReceived.URL.RawQuery != "labels=name%3Dfoo&timeout=1s" {
t.Errorf("Unexpected query: %v", fakeHandler.RequestReceived.URL.RawQuery)
}
if fakeHandler.RequestReceived.Header["Authorization"] == nil {
t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
}
}

View File

@ -17,13 +17,10 @@ limitations under the License.
package cloudcfg package cloudcfg
import ( import (
"bytes"
"crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -90,7 +87,7 @@ func Update(name string, client client.ClientInterface, updatePeriod time.Durati
return nil return nil
} }
// RequestWithBody is a helper method that creates an HTTP request with the specified url, method /*// RequestWithBody is a helper method that creates an HTTP request with the specified url, method
// and a body read from 'configFile' // and a body read from 'configFile'
func requestWithBody(configFile, url, method string) (*http.Request, error) { func requestWithBody(configFile, url, method string) (*http.Request, error) {
if len(configFile) == 0 { if len(configFile) == 0 {
@ -127,7 +124,7 @@ func doRequest(request *http.Request, auth *client.AuthInfo) ([]byte, error) {
defer response.Body.Close() defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body) body, err := ioutil.ReadAll(response.Body)
return body, err return body, err
} }*/
// StopController stops a controller named 'name' by setting replicas to zero // StopController stops a controller named 'name' by setting replicas to zero
func StopController(name string, client client.ClientInterface) error { func StopController(name string, client client.ClientInterface) error {

View File

@ -19,14 +19,11 @@ package cloudcfg
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"net/http"
"net/http/httptest"
"os" "os"
"testing" "testing"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
) )
// TODO: This doesn't reduce typing enough to make it worth the less readable errors. Remove. // TODO: This doesn't reduce typing enough to make it worth the less readable errors. Remove.
@ -147,29 +144,6 @@ func TestUpdateNoPods(t *testing.T) {
validateAction(Action{action: "list-pods"}, client.actions[1], t) validateAction(Action{action: "list-pods"}, client.actions[1], t)
} }
func TestDoRequest(t *testing.T) {
expectedBody := `{ "items": []}`
fakeHandler := util.FakeHandler{
StatusCode: 200,
ResponseBody: expectedBody,
T: t,
}
testServer := httptest.NewTLSServer(&fakeHandler)
request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
auth := client.AuthInfo{User: "user", Password: "pass"}
body, err := doRequest(request, &auth)
if request.Header["Authorization"] == nil {
t.Errorf("Request is missing authorization header: %#v", *request)
}
if err != nil {
t.Error("Unexpected error")
}
if string(body) != expectedBody {
t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body)
}
fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}
func TestRunController(t *testing.T) { func TestRunController(t *testing.T) {
fakeClient := FakeKubeClient{} fakeClient := FakeKubeClient{}
name := "name" name := "name"
@ -283,6 +257,7 @@ func TestCloudCfgDeleteControllerWithReplicas(t *testing.T) {
} }
} }
/*
func TestRequestWithBodyNoSuchFile(t *testing.T) { func TestRequestWithBodyNoSuchFile(t *testing.T) {
request, err := requestWithBody("non/existent/file.json", "http://www.google.com", "GET") request, err := requestWithBody("non/existent/file.json", "http://www.google.com", "GET")
if request != nil { if request != nil {
@ -291,7 +266,7 @@ func TestRequestWithBodyNoSuchFile(t *testing.T) {
if err == nil { if err == nil {
t.Error("Unexpected non-error") t.Error("Unexpected non-error")
} }
} }*/
func TestLoadAuthInfo(t *testing.T) { func TestLoadAuthInfo(t *testing.T) {
testAuthInfo := &client.AuthInfo{ testAuthInfo := &client.AuthInfo{
@ -326,27 +301,6 @@ func TestLoadAuthInfo(t *testing.T) {
} }
} }
func TestRequestWithBody(t *testing.T) {
file, err := ioutil.TempFile("", "foo")
expectNoError(t, err)
data, err := json.Marshal(api.Pod{JSONBase: api.JSONBase{ID: "foo"}})
expectNoError(t, err)
_, err = file.Write(data)
expectNoError(t, err)
request, err := requestWithBody(file.Name(), "http://www.google.com", "GET")
if request == nil {
t.Error("Unexpected nil result")
}
if err != nil {
t.Errorf("Unexpected error: %#v")
}
dataOut, err := ioutil.ReadAll(request.Body)
expectNoError(t, err)
if string(data) != string(dataOut) {
t.Errorf("Mismatched data. Expected %s, got %s", data, dataOut)
}
}
func validatePort(t *testing.T, p api.Port, external int, internal int) { func validatePort(t *testing.T, p api.Port, external int, internal int) {
if p.HostPort != external || p.ContainerPort != internal { if p.HostPort != external || p.ContainerPort != internal {
t.Errorf("Unexpected port: %#v != (%d, %d)", p, external, internal) t.Errorf("Unexpected port: %#v != (%d, %d)", p, external, internal)

View File

@ -111,13 +111,11 @@ func TestSyncReplicationControllerDoesNothing(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
controllerSpec := makeReplicationController(2) controllerSpec := makeReplicationController(2)
@ -133,13 +131,11 @@ func TestSyncReplicationControllerDeletes(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
controllerSpec := makeReplicationController(1) controllerSpec := makeReplicationController(1)
@ -155,13 +151,11 @@ func TestSyncReplicationControllerCreates(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
controllerSpec := makeReplicationController(2) controllerSpec := makeReplicationController(2)
@ -177,9 +171,7 @@ func TestCreateReplica(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
podControl := RealPodControl{ podControl := RealPodControl{
kubeClient: client, kubeClient: client,
@ -222,13 +214,11 @@ func TestHandleWatchResponseNotSet(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
_, err := manager.handleWatchResponse(&etcd.Response{ _, err := manager.handleWatchResponse(&etcd.Response{
Action: "update", Action: "update",
@ -243,13 +233,11 @@ func TestHandleWatchResponseNoNode(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
_, err := manager.handleWatchResponse(&etcd.Response{ _, err := manager.handleWatchResponse(&etcd.Response{
Action: "set", Action: "set",
@ -266,13 +254,11 @@ func TestHandleWatchResponseBadData(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
_, err := manager.handleWatchResponse(&etcd.Response{ _, err := manager.handleWatchResponse(&etcd.Response{
Action: "set", Action: "set",
@ -292,13 +278,11 @@ func TestHandleWatchResponse(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
controller := makeReplicationController(2) controller := makeReplicationController(2)
@ -326,13 +310,11 @@ func TestHandleWatchResponseDelete(t *testing.T) {
ResponseBody: string(body), ResponseBody: string(body),
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager := MakeReplicationManager(nil, &client) manager := MakeReplicationManager(nil, client)
manager.podControl = &fakePodControl manager.podControl = &fakePodControl
controller := makeReplicationController(2) controller := makeReplicationController(2)
@ -417,9 +399,7 @@ func TestSyncronize(t *testing.T) {
T: t, T: t,
} }
testServer := httptest.NewTLSServer(&fakeHandler) testServer := httptest.NewTLSServer(&fakeHandler)
client := client.Client{ client := client.New(testServer.URL, nil)
Host: testServer.URL,
}
manager := MakeReplicationManager(fakeEtcd, client) manager := MakeReplicationManager(fakeEtcd, client)
fakePodControl := FakePodControl{} fakePodControl := FakePodControl{}
manager.podControl = &fakePodControl manager.podControl = &fakePodControl