Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding test for apiserver example #20513

Merged
merged 2 commits into from
Feb 4, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion cmd/integration/integration.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ func startComponents(firstManifestURL, secondManifestURL string) (string, string
masterConfig.CacheTimeout = 2 * time.Second

// Create a master and install handlers into mux.
m := master.New(masterConfig)
m, err := master.New(masterConfig)
if err != nil {
glog.Fatalf("Error in bringing up the master: %v", err)
}
handler.delegate = m.Handler

// Scheduler
Expand Down
5 changes: 4 additions & 1 deletion cmd/kube-apiserver/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,10 @@ func Run(s *options.APIServer) error {

Tunneler: tunneler,
}
m := master.New(config)
m, err := master.New(config)
if err != nil {
return err
}
m.Run(s.ServerRunOptions)
return nil
}
Expand Down
6 changes: 6 additions & 0 deletions examples/apiserver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ API objects. Some relevant issues:

This code here is to examplify what it takes to write your own API server.

To start this example api server, run:

```
$ go run examples/apiserver/server/main.go
```


<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/apiserver/README.md?pixel)]()
Expand Down
23 changes: 16 additions & 7 deletions examples/apiserver/server.go → examples/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package main
package apiserver

import (
"github.com/golang/glog"
"fmt"

"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup/v1"
testgroupetcd "k8s.io/kubernetes/examples/apiserver/rest"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/apimachinery"
"k8s.io/kubernetes/pkg/apimachinery/registered"
Expand All @@ -44,23 +46,27 @@ func newStorageDestinations(groupName string, groupMeta *apimachinery.GroupMeta)
return &storageDestinations, nil
}

func main() {
func Run() error {
config := genericapiserver.Config{
EnableIndex: true,
APIPrefix: "/api",
APIGroupPrefix: "/apis",
Serializer: api.Codecs,
}
s, err := genericapiserver.New(&config)
if err != nil {
return fmt.Errorf("Error in bringing up the server: %v", err)
}
s := genericapiserver.New(&config)

groupVersion := v1.SchemeGroupVersion
groupName := groupVersion.Group
groupMeta, err := registered.Group(groupName)
if err != nil {
glog.Fatalf("%v", err)
return fmt.Errorf("%v", err)
}
storageDestinations, err := newStorageDestinations(groupName, groupMeta)
if err != nil {
glog.Fatalf("Unable to init etcd: %v", err)
return fmt.Errorf("Unable to init etcd: %v", err)
}
restStorageMap := map[string]rest.Storage{
"testtypes": testgroupetcd.NewREST(storageDestinations.Get(groupName, "testtype"), s.StorageDecorator()),
Expand All @@ -70,9 +76,12 @@ func main() {
VersionedResourcesStorageMap: map[string]map[string]rest.Storage{
groupVersion.Version: restStorageMap,
},
Scheme: api.Scheme,
NegotiatedSerializer: api.Codecs,
}
if err := s.InstallAPIGroups([]genericapiserver.APIGroupInfo{apiGroupInfo}); err != nil {
glog.Fatalf("Error in installing API: %v", err)
return fmt.Errorf("Error in installing API: %v", err)
}
s.Run(genericapiserver.NewServerRunOptions())
return nil
}
108 changes: 108 additions & 0 deletions examples/apiserver/apiserver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
Copyright 2016 The Kubernetes Authors 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 (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"testing"
"time"

"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup/v1"

"github.com/stretchr/testify/assert"
"k8s.io/kubernetes/pkg/api/unversioned"
)

var serverIP = "http://localhost:8080"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to use another port? If I have a local cluster running via hack/local-cluster-up.sh, it would conflict with this test.

The log actually says I0204 13:52:20.157799 9217 genericapiserver.go:607] Serving securely on 0.0.0.0:6443, I don't have time to dig into the code but it seems the generic apiserver randoms picks a port if 8080 is not available. If that's the case, we probably should improve this test to be more robust.

Sorry I didn't catch these yesterday.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixing in #22898


var groupVersion = v1.SchemeGroupVersion

func TestRun(t *testing.T) {
go func() {
if err := Run(); err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}
}()
if err := waitForApiserverUp(); err != nil {
t.Fatalf("%v", err)
}
testAPIGroup(t)
testAPIResourceList(t)
}

func waitForApiserverUp() error {
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
_, err := http.Get(serverIP)
if err == nil {
return nil
}
}
return fmt.Errorf("waiting for apiserver timed out")
}

func readResponse(serverURL string) ([]byte, error) {
response, err := http.Get(serverURL)
if err != nil {
return nil, fmt.Errorf("Error in fetching %s: %v", serverURL, err)
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("Error reading response from %s: %v", serverURL, err)
}
return contents, nil
}

func testAPIGroup(t *testing.T) {
serverURL := serverIP + "/apis/testgroup"
contents, err := readResponse(serverURL)
if err != nil {
t.Fatalf("%v", err)
}
var apiGroup unversioned.APIGroup
err = json.Unmarshal(contents, &apiGroup)
if err != nil {
t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
}
assert.Equal(t, apiGroup.APIVersion, groupVersion.Version)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nikhiljindal, I think the expected value and actual value should be swapped here.

assert.Equal(t, apiGroup.Name, groupVersion.Group)
assert.Equal(t, 1, len(apiGroup.Versions))
assert.Equal(t, apiGroup.Versions[0].GroupVersion, groupVersion.String())
assert.Equal(t, apiGroup.Versions[0].Version, groupVersion.Version)
assert.Equal(t, apiGroup.Versions[0], apiGroup.PreferredVersion)
}

func testAPIResourceList(t *testing.T) {
serverURL := serverIP + "/apis/testgroup/v1"
contents, err := readResponse(serverURL)
if err != nil {
t.Fatalf("%v", err)
}
var apiResourceList unversioned.APIResourceList
err = json.Unmarshal(contents, &apiResourceList)
if err != nil {
t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
}
assert.Equal(t, apiResourceList.APIVersion, groupVersion.Version)
assert.Equal(t, apiResourceList.GroupVersion, groupVersion.String())
assert.Equal(t, 1, len(apiResourceList.APIResources))
assert.Equal(t, apiResourceList.APIResources[0].Name, "testtypes")
assert.True(t, apiResourceList.APIResources[0].Namespaced)
}
29 changes: 29 additions & 0 deletions examples/apiserver/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2016 The Kubernetes Authors 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 main

import (
"k8s.io/kubernetes/examples/apiserver"

"github.com/golang/glog"
)

func main() {
if err := apiserver.Run(); err != nil {
glog.Fatalf("Error in bringing up the server: %v", err)
}
}
7 changes: 5 additions & 2 deletions pkg/genericapiserver/genericapiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,10 @@ func setDefaults(c *Config) {
// If the caller wants to add additional endpoints not using the GenericAPIServer's
// auth, then the caller should create a handler for those endpoints, which delegates the
// any unhandled paths to "Handler".
func New(c *Config) *GenericAPIServer {
func New(c *Config) (*GenericAPIServer, error) {
if c.Serializer == nil {
return nil, fmt.Errorf("Genericapiserver.New() called with config.Serializer == nil")
}
setDefaults(c)

s := &GenericAPIServer{
Expand Down Expand Up @@ -432,7 +435,7 @@ func New(c *Config) *GenericAPIServer {

s.init(c)

return s
return s, nil
}

func (s *GenericAPIServer) NewRequestInfoResolver() *apiserver.RequestInfoResolver {
Expand Down
12 changes: 10 additions & 2 deletions pkg/genericapiserver/genericapiserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,12 @@ func TestNew(t *testing.T) {

config.ProxyDialer = func(network, addr string) (net.Conn, error) { return nil, nil }
config.ProxyTLSClientConfig = &tls.Config{}
config.Serializer = api.Codecs

s := New(&config)
s, err := New(&config)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}

// Verify many of the variables match their config counterparts
assert.Equal(s.enableLogsSupport, config.EnableLogsSupport)
Expand Down Expand Up @@ -96,7 +100,11 @@ func TestInstallAPIGroups(t *testing.T) {
config.APIGroupPrefix = "/apiGroupPrefix"
config.Serializer = api.Codecs

s := New(&config)
s, err := New(&config)
if err != nil {
t.Fatalf("Error in bringing up the server: %v", err)
}

apiGroupMeta := registered.GroupOrDie(api.GroupName)
extensionsGroupMeta := registered.GroupOrDie(extensions.GroupName)
apiGroupsInfo := []APIGroupInfo{
Expand Down
11 changes: 7 additions & 4 deletions pkg/master/master.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,15 @@ type thirdPartyEntry struct {
// Certain config fields will be set to a default value if unset.
// Certain config fields must be specified, including:
// KubeletClient
func New(c *Config) *Master {
func New(c *Config) (*Master, error) {
if c.KubeletClient == nil {
glog.Fatalf("Master.New() called with config.KubeletClient == nil")
return nil, fmt.Errorf("Master.New() called with config.KubeletClient == nil")
}

s := genericapiserver.New(c.Config)
s, err := genericapiserver.New(c.Config)
if err != nil {
return nil, err
}

m := &Master{
GenericAPIServer: s,
Expand All @@ -155,7 +158,7 @@ func New(c *Config) *Master {
m.NewBootstrapController().Start()
}

return m
return m, nil
}

func (m *Master) InstallAPIs(c *Config) {
Expand Down
6 changes: 5 additions & 1 deletion pkg/master/master_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ func newMaster(t *testing.T) (*Master, *etcdtesting.EtcdTestServer, Config, *ass
config.ProxyDialer = func(network, addr string) (net.Conn, error) { return nil, nil }
config.ProxyTLSClientConfig = &tls.Config{}

master := New(&config)
master, err := New(&config)
if err != nil {
t.Fatalf("Error in bringing up the master: %v", err)
}

return master, etcdserver, config, assert
}

Expand Down
5 changes: 4 additions & 1 deletion test/component/scheduler/perf/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ func mustSetupScheduler() (schedulerConfigFactory *factory.ConfigFactory, destro

var m *master.Master
masterConfig := framework.NewIntegrationTestMasterConfig()
m = master.New(masterConfig)
m, err := master.New(masterConfig)
if err != nil {
panic("error in brining up the master: " + err.Error())
}
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
m.Handler.ServeHTTP(w, req)
}))
Expand Down