k3s/pkg/apiserver/operation_test.go

224 lines
6.0 KiB
Go
Raw Normal View History

2014-06-25 20:21:32 +00:00
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
2014-07-29 22:05:57 +00:00
"bytes"
"io/ioutil"
2014-07-29 22:05:57 +00:00
"net/http"
"net/http/httptest"
"sync/atomic"
2014-06-25 20:21:32 +00:00
"testing"
"time"
2014-07-29 22:05:57 +00:00
// TODO: remove dependency on api, apiserver should be generic
2014-07-29 22:05:57 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
_ "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta1"
2014-09-08 04:14:18 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
2014-06-25 20:21:32 +00:00
)
func TestOperation(t *testing.T) {
ops := NewOperations()
2014-09-08 04:14:18 +00:00
c := make(chan runtime.Object)
2014-09-26 00:20:28 +00:00
called := make(chan struct{})
op := ops.NewOperation(c, func(runtime.Object) { go close(called) })
// Allow context switch, so that op's ID can get added to the map and Get will work.
// This is just so we can test Get. Ordinary users have no need to call Get immediately
// after calling NewOperation, because it returns the operation directly.
time.Sleep(time.Millisecond)
2014-06-25 20:21:32 +00:00
go func() {
time.Sleep(500 * time.Millisecond)
c <- &Simple{TypeMeta: api.TypeMeta{ID: "All done"}}
2014-06-25 20:21:32 +00:00
}()
if op.expired(time.Now().Add(-time.Minute)) {
t.Errorf("Expired before finished: %#v", op)
}
ops.expire(time.Minute)
if tmp := ops.Get(op.ID); tmp == nil {
t.Errorf("expire incorrectly removed the operation %#v", ops)
}
op.WaitFor(10 * time.Millisecond)
if _, completed := op.StatusOrResult(); completed {
2014-06-25 20:21:32 +00:00
t.Errorf("Unexpectedly fast completion")
}
const waiters = 10
var waited int32
for i := 0; i < waiters; i++ {
go func() {
op.WaitFor(time.Hour)
atomic.AddInt32(&waited, 1)
}()
}
op.WaitFor(time.Minute)
if _, completed := op.StatusOrResult(); !completed {
2014-06-25 20:21:32 +00:00
t.Errorf("Unexpectedly slow completion")
}
2014-09-26 00:20:28 +00:00
_, open := <-called
if open {
t.Errorf("expected hook to be called!")
}
time.Sleep(100 * time.Millisecond)
2014-09-02 16:36:02 +00:00
finished := atomic.LoadInt32(&waited)
if finished != waiters {
t.Errorf("Multiple waiters doesn't work, only %v finished", finished)
}
2014-06-25 20:21:32 +00:00
if op.expired(time.Now().Add(-time.Second)) {
t.Errorf("Should not be expired: %#v", op)
}
if !op.expired(time.Now().Add(-80 * time.Millisecond)) {
2014-06-25 20:21:32 +00:00
t.Errorf("Should be expired: %#v", op)
}
ops.expire(80 * time.Millisecond)
2014-06-25 20:21:32 +00:00
if tmp := ops.Get(op.ID); tmp != nil {
t.Errorf("expire failed to remove the operation %#v", ops)
}
2014-09-08 04:14:18 +00:00
if op.result.(*Simple).ID != "All done" {
2014-06-25 20:21:32 +00:00
t.Errorf("Got unexpected result: %#v", op.result)
}
}
2014-07-29 22:05:57 +00:00
func TestOperationsList(t *testing.T) {
2014-08-27 05:00:26 +00:00
testOver := make(chan struct{})
defer close(testOver)
simpleStorage := &SimpleRESTStorage{
2014-09-08 04:14:18 +00:00
injectedFunction: func(obj runtime.Object) (runtime.Object, error) {
2014-08-27 05:00:26 +00:00
// Eliminate flakes by ensuring the create operation takes longer than this test.
<-testOver
return obj, nil
},
}
handler := Handle(map[string]RESTStorage{
"foo": simpleStorage,
2014-09-26 00:20:28 +00:00
}, codec, "/prefix/version", selfLinker)
handler.(*defaultAPIServer).group.handler.asyncOpWait = 0
server := httptest.NewServer(handler)
client := http.Client{}
2014-09-08 04:14:18 +00:00
simple := &Simple{
Name: "foo",
}
data, err := codec.Encode(simple)
2014-08-04 16:50:25 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 16:50:25 +00:00
}
response, err := client.Post(server.URL+"/prefix/version/foo", "application/json", bytes.NewBuffer(data))
2014-08-04 16:50:25 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 16:50:25 +00:00
}
if response.StatusCode != http.StatusAccepted {
t.Fatalf("Unexpected response %#v", response)
}
response, err = client.Get(server.URL + "/prefix/version/operations")
2014-08-04 16:50:25 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 16:50:25 +00:00
}
if response.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code %#v", response)
}
body, err := ioutil.ReadAll(response.Body)
2014-08-04 16:50:25 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 16:50:25 +00:00
}
obj, err := codec.Decode(body)
2014-08-04 16:50:25 +00:00
if err != nil {
t.Errorf("unexpected error: %v", err)
}
oplist, ok := obj.(*api.ServerOpList)
if !ok {
t.Fatalf("expected ServerOpList, got %#v", obj)
}
if len(oplist.Items) != 1 {
t.Errorf("expected 1 operation, got %#v", obj)
}
}
2014-07-29 22:05:57 +00:00
func TestOpGet(t *testing.T) {
testOver := make(chan struct{})
defer close(testOver)
simpleStorage := &SimpleRESTStorage{
2014-09-08 04:14:18 +00:00
injectedFunction: func(obj runtime.Object) (runtime.Object, error) {
// Eliminate flakes by ensuring the create operation takes longer than this test.
<-testOver
return obj, nil
},
}
handler := Handle(map[string]RESTStorage{
2014-07-29 22:05:57 +00:00
"foo": simpleStorage,
2014-09-26 00:20:28 +00:00
}, codec, "/prefix/version", selfLinker)
handler.(*defaultAPIServer).group.handler.asyncOpWait = 0
2014-07-29 22:05:57 +00:00
server := httptest.NewServer(handler)
client := http.Client{}
2014-09-08 04:14:18 +00:00
simple := &Simple{
2014-07-29 22:05:57 +00:00
Name: "foo",
}
data, err := codec.Encode(simple)
2014-07-29 22:05:57 +00:00
t.Log(string(data))
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
2014-07-29 22:05:57 +00:00
request, err := http.NewRequest("POST", server.URL+"/prefix/version/foo", bytes.NewBuffer(data))
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
2014-07-29 22:05:57 +00:00
response, err := client.Do(request)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
2014-07-29 22:05:57 +00:00
if response.StatusCode != http.StatusAccepted {
t.Fatalf("Unexpected response %#v", response)
2014-07-29 22:05:57 +00:00
}
var itemOut api.Status
body, err := extractBody(response, &itemOut)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
if itemOut.Status != api.StatusWorking || itemOut.Details == nil || itemOut.Details.ID == "" {
t.Fatalf("Unexpected status: %#v (%s)", itemOut, string(body))
2014-07-29 22:05:57 +00:00
}
Evolve the api.Status object with Reason/Details Contains breaking API change on api.Status#Details (type change) Turn Details from string -> StatusDetails - a general bucket for keyed error behavior. Define an open enumeration ReasonType exposed as Reason on the status object to provide machine readable subcategorization beyond HTTP Status Code. Define a human readable field Message which is common convention (previously this was joined into Details). Precedence order: HTTP Status Code, Reason, Details. apiserver would impose restraints on the ReasonTypes defined by the main apiobject, and ensure their use is consistent. There are four long term scenarios this change supports: 1. Allow a client access to a machine readable field that can be easily switched on for improving or translating the generic server Message. 2. Return a 404 when a composite operation on multiple resources fails with enough data so that a client can distinguish which item does not exist. E.g. resource Parent and resource Child, POST /parents/1/children to create a new Child, but /parents/1 is deleted. POST returns 404, ReasonTypeNotFound, and Details.ID = "1", Details.Kind = "parent" 3. Allow a client to receive validation data that is keyed by attribute for building user facing UIs around field submission. Validation is usually expressed as map[string][]string, but that type is less appropriate for many other uses. 4. Allow specific API errors to return more granular failure status for specific operations. An example might be a minion proxy, where the operation that failed may be both proxying OR the minion itself. In this case a reason may be defined "proxy_failed" corresponding to 502, where the Details field may be extended to contain a nested error object. At this time only ID and Kind are exposed
2014-07-31 18:12:26 +00:00
req2, err := http.NewRequest("GET", server.URL+"/prefix/version/operations/"+itemOut.Details.ID, nil)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
2014-07-29 22:05:57 +00:00
_, err = client.Do(req2)
2014-08-04 00:01:15 +00:00
if err != nil {
t.Fatalf("unexpected error: %v", err)
2014-08-04 00:01:15 +00:00
}
2014-07-29 22:05:57 +00:00
if response.StatusCode != http.StatusAccepted {
t.Errorf("Unexpected response %#v", response)
}
}