Using CRD instead of TPR
- Use CRD for clusters and pools - For k8s before 1.7.0, TPR will be used - Also use the watcher libraries in client-go
This commit is contained in:
1 parent
c1cbda3e21
commit
709b7ddafe
46 files changed
+1111
-1461
No files matched your search
+1
-1
@@ -59,7 +59,7 @@ func startAPI(cmd *cobra.Command, args []string) error {
|
||||
|
||||
setLogLevel()
|
||||
|
||||
_, clientset, err := getClientset()
|
||||
clientset, _, err := getClientset()
|
||||
if err != nil {
|
||||
fmt.Printf("failed to init k8s client. %+v\n", err)
|
||||
os.Exit(1)
|
||||
|
||||
+19
-12
@@ -21,9 +21,9 @@ import (
|
||||
|
||||
"github.com/rook/rook/pkg/operator"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"github.com/rook/rook/pkg/util/flags"
|
||||
"github.com/spf13/cobra"
|
||||
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/rest"
|
||||
)
|
||||
@@ -45,7 +45,7 @@ func startOperator(cmd *cobra.Command, args []string) error {
|
||||
|
||||
setLogLevel()
|
||||
|
||||
host, clientset, err := getClientset()
|
||||
clientset, apiExtClientset, err := getClientset()
|
||||
if err != nil {
|
||||
fmt.Printf("failed to get k8s client. %+v", err)
|
||||
os.Exit(1)
|
||||
@@ -54,14 +54,14 @@ func startOperator(cmd *cobra.Command, args []string) error {
|
||||
logger.Infof("starting operator")
|
||||
context := createContext()
|
||||
context.ConfigDir = k8sutil.DataDir
|
||||
context.KubeContext = kit.KubeContext{
|
||||
MasterHost: host,
|
||||
Clientset: clientset,
|
||||
RetryDelay: 6,
|
||||
MaxRetries: 15,
|
||||
}
|
||||
context.Clientset = clientset
|
||||
context.APIExtensionClientset = apiExtClientset
|
||||
|
||||
op := operator.New(context)
|
||||
if op == nil {
|
||||
fmt.Printf("failed to create operator.")
|
||||
os.Exit(1)
|
||||
}
|
||||
err = op.Run()
|
||||
if err != nil {
|
||||
fmt.Printf("failed to run operator. %+v\n", err)
|
||||
@@ -71,13 +71,20 @@ func startOperator(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getClientset() (string, *kubernetes.Clientset, error) {
|
||||
func getClientset() (kubernetes.Interface, apiextensionsclient.Interface, error) {
|
||||
// create the k8s client
|
||||
config, err := rest.InClusterConfig()
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to get k8s config. %+v", err)
|
||||
return nil, nil, fmt.Errorf("failed to get k8s config. %+v", err)
|
||||
}
|
||||
|
||||
c, err := kubernetes.NewForConfig(config)
|
||||
return config.Host, c, err
|
||||
clientset, err := kubernetes.NewForConfig(config)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create k8s clientset. %+v", err)
|
||||
}
|
||||
apiExtClientset, err := apiextensionsclient.NewForConfig(config)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create k8s API extension clientset. %+v", err)
|
||||
}
|
||||
return clientset, apiExtClientset, nil
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: rook
|
||||
---
|
||||
apiVersion: rook.io/v1alpha1
|
||||
kind: Cluster
|
||||
metadata:
|
||||
|
||||
@@ -37,6 +37,16 @@ rules:
|
||||
- watch
|
||||
- create
|
||||
- delete
|
||||
- apiGroups:
|
||||
- apiextensions.k8s.io
|
||||
resources:
|
||||
- customresourcedefinitions
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- create
|
||||
- delete
|
||||
- apiGroups:
|
||||
- rbac.authorization.k8s.io
|
||||
resources:
|
||||
|
||||
Generated
+8
-3
@@ -1,8 +1,8 @@
|
||||
hash: fe1ad353107dd7cafbb209b1a47dbc8f133c33e903c624dbb0ca6b8e5dd96b90
|
||||
updated: 2017-07-21T14:07:40.218420356-07:00
|
||||
hash: 217958937f963168826d53f68b03fd51d9c88167624b8cf97c15f0455f46e2b7
|
||||
updated: 2017-07-17T16:52:36.136812758-07:00
|
||||
imports:
|
||||
- name: github.com/aws/aws-sdk-go
|
||||
version: afd601335e2a72d43caa3af6bd2abe512fcc3bfd
|
||||
version: 6d7fc1a00fcae6bbb53550f4a0b98324fd7aa250
|
||||
subpackages:
|
||||
- aws
|
||||
- aws/awserr
|
||||
@@ -313,6 +313,11 @@ imports:
|
||||
- settings/v1alpha1
|
||||
- storage/v1
|
||||
- storage/v1beta1
|
||||
- name: k8s.io/apiextensions-apiserver
|
||||
version: 3eb4c5fefbe7ad866747f78c7e4994cb555170c6
|
||||
subpackages:
|
||||
- pkg/apis/apiextensions
|
||||
- pkg/apis/apiextensions/v1beta1
|
||||
- name: k8s.io/apimachinery
|
||||
version: 728b986edb9bd4bb8a022a8cc13573a97ecc2239
|
||||
subpackages:
|
||||
|
||||
@@ -31,6 +31,8 @@ import:
|
||||
version: 728b986edb9bd4bb8a022a8cc13573a97ecc2239
|
||||
- package: k8s.io/api
|
||||
version: e24ed681f56165befbea50a24f7e9f1c079ac366
|
||||
- package: k8s.io/apiextensions-apiserver
|
||||
version: 3eb4c5fefbe7ad866747f78c7e4994cb555170c6
|
||||
- package: github.com/prometheus/client_golang
|
||||
version: v0.8.0
|
||||
subpackages:
|
||||
|
||||
@@ -19,10 +19,11 @@ import (
|
||||
etcd "github.com/coreos/etcd/client"
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/pkg/clusterd/inventory"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"github.com/rook/rook/pkg/util"
|
||||
"github.com/rook/rook/pkg/util/exec"
|
||||
"github.com/rook/rook/pkg/util/proc"
|
||||
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -63,8 +64,11 @@ type Context struct {
|
||||
// The context for the Standalone orchestrator
|
||||
DirectContext
|
||||
|
||||
// The context for the Kubernetes orchestrator
|
||||
kit.KubeContext
|
||||
// Clientset is a connection to the core kubernetes API
|
||||
Clientset kubernetes.Interface
|
||||
|
||||
// APIExtensionClientset is a connection to the API Extension kubernetes API
|
||||
APIExtensionClientset apiextensionsclient.Interface
|
||||
|
||||
// The implementation of executing a console command
|
||||
Executor exec.Executor
|
||||
|
||||
+41
-14
@@ -19,25 +19,29 @@ package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
opmon "github.com/rook/rook/pkg/operator/mon"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
"k8s.io/api/core/v1"
|
||||
extensions "k8s.io/api/extensions/v1beta1"
|
||||
"k8s.io/api/rbac/v1beta1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/intstr"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
)
|
||||
|
||||
var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-api")
|
||||
|
||||
const (
|
||||
// DeploymentName is the service name
|
||||
DeploymentName = "rook-api"
|
||||
deploymentName = "rook-api"
|
||||
clientTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
var clusterAccessRules = []v1beta1.PolicyRule{
|
||||
@@ -51,6 +55,11 @@ var clusterAccessRules = []v1beta1.PolicyRule{
|
||||
Resources: []string{"thirdpartyresources", "deployments", "daemonsets", "replicasets"},
|
||||
Verbs: []string{"get", "list", "create"},
|
||||
},
|
||||
{
|
||||
APIGroups: []string{"apiextensions.k8s.io"},
|
||||
Resources: []string{"customresourcedefinitions"},
|
||||
Verbs: []string{"get", "list", "create"},
|
||||
},
|
||||
{
|
||||
APIGroups: []string{"storage.k8s.io"},
|
||||
Resources: []string{"storageclasses"},
|
||||
@@ -112,7 +121,7 @@ func (c *Cluster) Start() error {
|
||||
// make a cluster role
|
||||
func (c *Cluster) makeClusterRole() error {
|
||||
account := &v1.ServiceAccount{}
|
||||
account.Name = DeploymentName
|
||||
account.Name = deploymentName
|
||||
account.Namespace = c.Namespace
|
||||
_, err := c.context.Clientset.CoreV1().ServiceAccounts(c.Namespace).Create(account)
|
||||
if err != nil && !errors.IsAlreadyExists(err) {
|
||||
@@ -123,7 +132,7 @@ func (c *Cluster) makeClusterRole() error {
|
||||
// If the role already exists we have to update it. Otherwise if the permissions change during an upgrade,
|
||||
// the create will fail with an error that we're changing the permissions.
|
||||
role := &v1beta1.ClusterRole{Rules: clusterAccessRules}
|
||||
role.Name = DeploymentName
|
||||
role.Name = deploymentName
|
||||
_, err = c.context.Clientset.RbacV1beta1().ClusterRoles().Get(role.Name, metav1.GetOptions{})
|
||||
if errors.IsNotFound(err) {
|
||||
logger.Infof("creating cluster role rook-api")
|
||||
@@ -137,9 +146,9 @@ func (c *Cluster) makeClusterRole() error {
|
||||
}
|
||||
|
||||
binding := &v1beta1.ClusterRoleBinding{}
|
||||
binding.Name = DeploymentName
|
||||
binding.RoleRef = v1beta1.RoleRef{Name: DeploymentName, Kind: "ClusterRole", APIGroup: "rbac.authorization.k8s.io"}
|
||||
binding.Subjects = []v1beta1.Subject{{Kind: "ServiceAccount", Name: DeploymentName, Namespace: c.Namespace}}
|
||||
binding.Name = deploymentName
|
||||
binding.RoleRef = v1beta1.RoleRef{Name: deploymentName, Kind: "ClusterRole", APIGroup: "rbac.authorization.k8s.io"}
|
||||
binding.Subjects = []v1beta1.Subject{{Kind: "ServiceAccount", Name: deploymentName, Namespace: c.Namespace}}
|
||||
_, err = c.context.Clientset.RbacV1beta1().ClusterRoleBindings().Create(binding)
|
||||
if err != nil && !errors.IsAlreadyExists(err) {
|
||||
return fmt.Errorf("failed to create api cluster role binding. %+v", err)
|
||||
@@ -149,11 +158,11 @@ func (c *Cluster) makeClusterRole() error {
|
||||
|
||||
func (c *Cluster) makeDeployment() *extensions.Deployment {
|
||||
deployment := &extensions.Deployment{}
|
||||
deployment.Name = DeploymentName
|
||||
deployment.Name = deploymentName
|
||||
deployment.Namespace = c.Namespace
|
||||
|
||||
podSpec := v1.PodSpec{
|
||||
ServiceAccountName: DeploymentName,
|
||||
ServiceAccountName: deploymentName,
|
||||
Containers: []v1.Container{c.apiContainer()},
|
||||
RestartPolicy: v1.RestartPolicyAlways,
|
||||
Volumes: []v1.Volume{
|
||||
@@ -164,7 +173,7 @@ func (c *Cluster) makeDeployment() *extensions.Deployment {
|
||||
|
||||
podTemplateSpec := v1.PodTemplateSpec{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: DeploymentName,
|
||||
Name: deploymentName,
|
||||
Labels: c.getLabels(),
|
||||
Annotations: map[string]string{},
|
||||
},
|
||||
@@ -184,7 +193,7 @@ func (c *Cluster) apiContainer() v1.Container {
|
||||
fmt.Sprintf("--config-dir=%s", k8sutil.DataDir),
|
||||
fmt.Sprintf("--port=%d", model.Port),
|
||||
},
|
||||
Name: DeploymentName,
|
||||
Name: deploymentName,
|
||||
Image: k8sutil.MakeRookImage(c.Version),
|
||||
VolumeMounts: []v1.VolumeMount{
|
||||
{Name: k8sutil.DataDirVolume, MountPath: k8sutil.DataDir},
|
||||
@@ -205,14 +214,14 @@ func (c *Cluster) startService() error {
|
||||
labels := c.getLabels()
|
||||
s := &v1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: DeploymentName,
|
||||
Name: deploymentName,
|
||||
Namespace: c.Namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: v1.ServiceSpec{
|
||||
Ports: []v1.ServicePort{
|
||||
{
|
||||
Name: DeploymentName,
|
||||
Name: deploymentName,
|
||||
Port: model.Port,
|
||||
TargetPort: intstr.FromInt(int(model.Port)),
|
||||
Protocol: v1.ProtocolTCP,
|
||||
@@ -237,7 +246,25 @@ func (c *Cluster) startService() error {
|
||||
|
||||
func (c *Cluster) getLabels() map[string]string {
|
||||
return map[string]string{
|
||||
k8sutil.AppAttr: DeploymentName,
|
||||
k8sutil.AppAttr: deploymentName,
|
||||
k8sutil.ClusterAttr: c.Namespace,
|
||||
}
|
||||
}
|
||||
|
||||
// GetRookClient gets a reference of the rook client connected to the Rook-API on the given namespace
|
||||
func GetRookClient(namespace string, client kubernetes.Interface) (rookclient.RookRestClient, error) {
|
||||
|
||||
// Look up the api service for the given namespace
|
||||
logger.Infof("retrieving rook api endpoint for namespace %s", namespace)
|
||||
svc, err := client.CoreV1().Services(namespace).Get(deploymentName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to find the api service. %+v", err)
|
||||
}
|
||||
|
||||
httpClient := http.DefaultClient
|
||||
httpClient.Timeout = clientTimeout
|
||||
endpoint := fmt.Sprintf("%s:%d", svc.Spec.ClusterIP, svc.Spec.Ports[0].Port)
|
||||
rclient := rookclient.NewRookNetworkRestClient(rookclient.GetRestURL(endpoint), httpClient)
|
||||
logger.Infof("rook api endpoint %s for namespace %s", endpoint, namespace)
|
||||
return rclient, nil
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -32,7 +31,7 @@ import (
|
||||
|
||||
func TestStartAPI(t *testing.T) {
|
||||
clientset := testop.New(3)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", k8sutil.Placement{})
|
||||
|
||||
// start a basic cluster
|
||||
err := c.Start()
|
||||
@@ -49,28 +48,28 @@ func TestStartAPI(t *testing.T) {
|
||||
|
||||
func validateStart(t *testing.T, c *Cluster) {
|
||||
|
||||
r, err := c.context.Clientset.ExtensionsV1beta1().Deployments(c.Namespace).Get(DeploymentName, metav1.GetOptions{})
|
||||
r, err := c.context.Clientset.ExtensionsV1beta1().Deployments(c.Namespace).Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, DeploymentName, r.Name)
|
||||
assert.Equal(t, deploymentName, r.Name)
|
||||
|
||||
s, err := c.context.Clientset.CoreV1().Services(c.Namespace).Get(DeploymentName, metav1.GetOptions{})
|
||||
s, err := c.context.Clientset.CoreV1().Services(c.Namespace).Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, DeploymentName, s.Name)
|
||||
assert.Equal(t, deploymentName, s.Name)
|
||||
}
|
||||
|
||||
func TestPodSpecs(t *testing.T) {
|
||||
clientset := testop.New(1)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", k8sutil.Placement{})
|
||||
|
||||
d := c.makeDeployment()
|
||||
assert.NotNil(t, d)
|
||||
assert.Equal(t, DeploymentName, d.Name)
|
||||
assert.Equal(t, deploymentName, d.Name)
|
||||
assert.Equal(t, v1.RestartPolicyAlways, d.Spec.Template.Spec.RestartPolicy)
|
||||
assert.Equal(t, 1, len(d.Spec.Template.Spec.Volumes))
|
||||
assert.Equal(t, "rook-data", d.Spec.Template.Spec.Volumes[0].Name)
|
||||
|
||||
assert.Equal(t, DeploymentName, d.ObjectMeta.Name)
|
||||
assert.Equal(t, DeploymentName, d.Spec.Template.ObjectMeta.Labels["app"])
|
||||
assert.Equal(t, deploymentName, d.ObjectMeta.Name)
|
||||
assert.Equal(t, deploymentName, d.Spec.Template.ObjectMeta.Labels["app"])
|
||||
assert.Equal(t, c.Namespace, d.Spec.Template.ObjectMeta.Labels["rook_cluster"])
|
||||
assert.Equal(t, 0, len(d.ObjectMeta.Annotations))
|
||||
|
||||
@@ -89,24 +88,24 @@ func TestPodSpecs(t *testing.T) {
|
||||
|
||||
func TestClusterRole(t *testing.T) {
|
||||
clientset := testop.New(1)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", k8sutil.Placement{})
|
||||
|
||||
// the role is create
|
||||
err := c.makeClusterRole()
|
||||
assert.Nil(t, err)
|
||||
role, err := c.context.Clientset.RbacV1beta1().ClusterRoles().Get(DeploymentName, metav1.GetOptions{})
|
||||
role, err := c.context.Clientset.RbacV1beta1().ClusterRoles().Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, DeploymentName, role.Name)
|
||||
assert.Equal(t, 3, len(role.Rules))
|
||||
account, err := c.context.Clientset.CoreV1().ServiceAccounts(c.Namespace).Get(DeploymentName, metav1.GetOptions{})
|
||||
assert.Equal(t, deploymentName, role.Name)
|
||||
assert.Equal(t, 4, len(role.Rules))
|
||||
account, err := c.context.Clientset.CoreV1().ServiceAccounts(c.Namespace).Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, c.Namespace, account.Namespace)
|
||||
binding, err := c.context.Clientset.RbacV1beta1().ClusterRoleBindings().Get(DeploymentName, metav1.GetOptions{})
|
||||
binding, err := c.context.Clientset.RbacV1beta1().ClusterRoleBindings().Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, DeploymentName, binding.RoleRef.Name)
|
||||
assert.Equal(t, deploymentName, binding.RoleRef.Name)
|
||||
assert.Equal(t, "ClusterRole", binding.RoleRef.Kind)
|
||||
assert.Equal(t, "rbac.authorization.k8s.io", binding.RoleRef.APIGroup)
|
||||
assert.Equal(t, DeploymentName, binding.Subjects[0].Name)
|
||||
assert.Equal(t, deploymentName, binding.Subjects[0].Name)
|
||||
assert.Equal(t, "ServiceAccount", binding.Subjects[0].Kind)
|
||||
|
||||
// update the rules
|
||||
@@ -119,7 +118,7 @@ func TestClusterRole(t *testing.T) {
|
||||
}
|
||||
err = c.makeClusterRole()
|
||||
assert.Nil(t, err)
|
||||
role, err = c.context.Clientset.RbacV1beta1().ClusterRoles().Get(DeploymentName, metav1.GetOptions{})
|
||||
role, err = c.context.Clientset.RbacV1beta1().ClusterRoles().Get(deploymentName, metav1.GetOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 1, len(role.Rules))
|
||||
assert.Equal(t, "", role.Rules[0].APIGroups[0])
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package operator to manage Kubernetes storage.
|
||||
package operator
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"sync"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/cluster"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
kwatch "k8s.io/apimachinery/pkg/watch"
|
||||
)
|
||||
|
||||
type clusterManager struct {
|
||||
context *clusterd.Context
|
||||
devicesInUse bool
|
||||
clusters map[string]*cluster.Cluster
|
||||
tracker *tprTracker
|
||||
sync.RWMutex
|
||||
// The initiators that create TPRs specific to specific Rook clusters.
|
||||
// For example, pools, object services, and file services, only make sense in the context of a Rook cluster
|
||||
inclusterInitiators []inclusterInitiator
|
||||
inclusterMgrs []resourceManager
|
||||
}
|
||||
|
||||
type clusterEvent struct {
|
||||
Type kwatch.EventType
|
||||
Object *cluster.Cluster
|
||||
}
|
||||
|
||||
func newClusterManager(context *clusterd.Context, inclusterInitiators []inclusterInitiator) *clusterManager {
|
||||
return &clusterManager{
|
||||
context: context,
|
||||
clusters: make(map[string]*cluster.Cluster),
|
||||
tracker: newTPRTracker(),
|
||||
inclusterInitiators: inclusterInitiators,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *clusterManager) Manage() {
|
||||
for {
|
||||
logger.Infof("Managing clusters")
|
||||
watchVersion, err := m.Load()
|
||||
if err != nil {
|
||||
logger.Errorf("failed to load cluster. %+v", err)
|
||||
} else {
|
||||
if err := m.watchClusters(watchVersion); err != nil {
|
||||
logger.Errorf("failed to watch clusters. %+v", err)
|
||||
}
|
||||
}
|
||||
|
||||
<-time.After(time.Second * time.Duration(m.context.RetryDelay))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *clusterManager) Load() (string, error) {
|
||||
|
||||
// Check if there is an existing cluster to recover
|
||||
logger.Info("finding existing clusters...")
|
||||
clusterList, err := m.getClusterList()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
logger.Infof("found %d clusters", len(clusterList.Items))
|
||||
for i := range clusterList.Items {
|
||||
c := clusterList.Items[i]
|
||||
logger.Infof("checking if cluster %s is running in namespace %s", c.Name, c.Namespace)
|
||||
m.startCluster(&c)
|
||||
}
|
||||
|
||||
return clusterList.Metadata.ResourceVersion, nil
|
||||
}
|
||||
|
||||
func (m *clusterManager) startTrack(c *cluster.Cluster) error {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
existing, ok := m.clusters[c.Namespace]
|
||||
if ok {
|
||||
if c.Name != existing.Name {
|
||||
return fmt.Errorf("cluster %s is already running in namespace %s. Multiple clusters per namespace not supported", existing.Name, existing.Namespace)
|
||||
}
|
||||
} else {
|
||||
// only start the cluster if we're not already tracking it from a previous iteration
|
||||
m.clusters[c.Namespace] = c
|
||||
}
|
||||
|
||||
// refresh the version of the cluster we're tracking
|
||||
m.tracker.add(c.Namespace, c.ResourceVersion)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *clusterManager) stopTrack(c *cluster.Cluster) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
m.tracker.remove(c.Namespace)
|
||||
delete(m.clusters, c.Namespace)
|
||||
}
|
||||
|
||||
func (m *clusterManager) startCluster(c *cluster.Cluster) {
|
||||
c.Init(m.context)
|
||||
if err := m.startTrack(c); err != nil {
|
||||
logger.Errorf("failed to start cluster %s in namespace %s. %+v", c.Name, c.Namespace, err)
|
||||
return
|
||||
}
|
||||
|
||||
if m.devicesInUse && c.Spec.Storage.AnyUseAllDevices() {
|
||||
logger.Warningf("using all devices in more than one namespace not supported. ignoring devices in namespace %s", c.Namespace)
|
||||
c.Spec.Storage.ClearUseAllDevices()
|
||||
}
|
||||
|
||||
if c.Spec.Storage.AnyUseAllDevices() {
|
||||
m.devicesInUse = true
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer m.stopTrack(c)
|
||||
logger.Infof("starting cluster %s in namespace %s", c.Name, c.Namespace)
|
||||
|
||||
// Start the Rook cluster components. Retry several times in case of failure.
|
||||
err := kit.Retry(m.context.KubeContext, func() (bool, error) {
|
||||
err := c.CreateInstance()
|
||||
if err != nil {
|
||||
logger.Errorf("failed to create cluster %s in namespace %s. %+v", c.Name, c.Namespace, err)
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf("giving up to create cluster %s in namespace %s", c.Name, c.Namespace)
|
||||
return
|
||||
}
|
||||
|
||||
// Start all the TPRs for this cluster
|
||||
for _, initiator := range m.inclusterInitiators {
|
||||
kit.Retry(m.context.KubeContext, func() (bool, error) {
|
||||
tprMgr, err := initiator.Create(m, c.Namespace)
|
||||
if err != nil {
|
||||
logger.Warningf("cannot create in-cluster tpr %s. %+v. retrying...", initiator.Resource().Name, err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Start the tpr-manager asynchronously
|
||||
go tprMgr.Manage()
|
||||
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
m.inclusterMgrs = append(m.inclusterMgrs, tprMgr)
|
||||
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
c.Monitor(m.tracker.stopChMap[c.Namespace])
|
||||
}()
|
||||
}
|
||||
|
||||
func (m *clusterManager) isClustersCacheStale(currentClusters []cluster.Cluster) bool {
|
||||
if len(m.tracker.clusterRVs) != len(currentClusters) {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, cc := range currentClusters {
|
||||
rv, ok := m.tracker.clusterRVs[cc.Name]
|
||||
if !ok || rv != cc.ResourceVersion {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *clusterManager) getClusterList() (*cluster.ClusterList, error) {
|
||||
b, err := kit.GetRawList(m.context.Clientset, cluster.ClusterResource)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
clusters := &cluster.ClusterList{}
|
||||
if err := json.Unmarshal(b, clusters); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return clusters, nil
|
||||
}
|
||||
|
||||
func (m *clusterManager) watchClusters(watchVersion string) error {
|
||||
defer m.tracker.stop()
|
||||
|
||||
w := kit.NewWatcher(
|
||||
m.context.KubeContext,
|
||||
cluster.ClusterResource,
|
||||
"",
|
||||
watchVersion,
|
||||
m.handleClusterEvent,
|
||||
m.checkStaleCache)
|
||||
return w.Watch()
|
||||
}
|
||||
|
||||
func (m *clusterManager) handleClusterEvent(e *kit.RawEvent) error {
|
||||
|
||||
event, err := unmarshalEvent(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch event.Type {
|
||||
case kwatch.Added:
|
||||
logger.Infof("starting new cluster in namespace %s", event.Object.Namespace)
|
||||
m.startCluster(event.Object)
|
||||
|
||||
case kwatch.Modified:
|
||||
logger.Infof("modifying a cluster not implemented")
|
||||
|
||||
case kwatch.Deleted:
|
||||
logger.Infof("deleting a cluster not implemented")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *clusterManager) checkStaleCache() (string, error) {
|
||||
clusterList, err := m.getClusterList()
|
||||
if err == nil && !m.isClustersCacheStale(clusterList.Items) {
|
||||
return clusterList.Metadata.ResourceVersion, nil
|
||||
}
|
||||
|
||||
return "", err
|
||||
}
|
||||
|
||||
func (m *clusterManager) getRookClient(namespace string) (rookclient.RookRestClient, error) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if c, ok := m.clusters[namespace]; ok {
|
||||
return c.GetRookClient()
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("namespace %s not found", namespace)
|
||||
}
|
||||
|
||||
func (m *clusterManager) getCluster(namespace string) (*cluster.Cluster, error) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if c, ok := m.clusters[namespace]; ok {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("cluster namespace %s not found", namespace)
|
||||
}
|
||||
|
||||
func unmarshalEvent(event *kit.RawEvent) (*clusterEvent, error) {
|
||||
|
||||
e := &clusterEvent{
|
||||
Type: event.Type,
|
||||
Object: &cluster.Cluster{},
|
||||
}
|
||||
err := json.Unmarshal(event.Object, e.Object)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to unmarshal Cluster object: %v", err)
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package cluster to manage a rook cluster.
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// ClusterList is a list of rook clusters.
|
||||
type ClusterList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
// Standard list metadata
|
||||
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
|
||||
Metadata metav1.ListMeta `json:"metadata,omitempty"`
|
||||
// Items is a list of third party objects
|
||||
Items []Cluster `json:"items"`
|
||||
}
|
||||
|
||||
// There is known issue with TPR in client-go:
|
||||
// https://github.com/kubernetes/client-go/issues/8
|
||||
// Workarounds:
|
||||
// - We include `Metadata` field in object explicitly.
|
||||
// - we have the code below to work around a known problem with third-party resources and ugorji.
|
||||
|
||||
// ClusterListCopy is for deserialization
|
||||
type ClusterListCopy ClusterList
|
||||
|
||||
// ClusterCopy is for deserializaion
|
||||
type ClusterCopy Cluster
|
||||
|
||||
// UnmarshalJSON unmarshals the raw cluster
|
||||
func (c *Cluster) UnmarshalJSON(data []byte) error {
|
||||
tmp := ClusterCopy{}
|
||||
err := json.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp2 := Cluster(tmp)
|
||||
*c = tmp2
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON unmarshals the raw cluster list
|
||||
func (cl *ClusterList) UnmarshalJSON(data []byte) error {
|
||||
tmp := ClusterListCopy{}
|
||||
err := json.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp2 := ClusterList(tmp)
|
||||
*cl = tmp2
|
||||
return nil
|
||||
}
|
||||
@@ -22,11 +22,8 @@ package cluster
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/pkg/ceph/client"
|
||||
cephmon "github.com/rook/rook/pkg/ceph/mon"
|
||||
@@ -37,59 +34,124 @@ import (
|
||||
"github.com/rook/rook/pkg/operator/mgr"
|
||||
"github.com/rook/rook/pkg/operator/mon"
|
||||
"github.com/rook/rook/pkg/operator/osd"
|
||||
"github.com/rook/rook/pkg/operator/rgw"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
"github.com/rook/rook/pkg/operator/pool"
|
||||
"k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
const (
|
||||
crushConfigMapName = "crush-config"
|
||||
crushmapCreatedKey = "initialCrushMapCreated"
|
||||
customResourceName = "cluster"
|
||||
customResourceNamePlural = "clusters"
|
||||
crushConfigMapName = "crush-config"
|
||||
crushmapCreatedKey = "initialCrushMapCreated"
|
||||
clusterCreateInterval = 6 * time.Second
|
||||
clusterCreateTimeout = 5 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
healthCheckInterval = 10 * time.Second
|
||||
clientTimeout = 15 * time.Second
|
||||
logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-cluster")
|
||||
// ClusterResource is the definition of the cluster CRD
|
||||
ClusterResource = kit.CustomResource{
|
||||
Name: "cluster",
|
||||
Group: k8sutil.CustomResourceGroup,
|
||||
Version: kit.V1Alpha1,
|
||||
Description: "Managed Rook clusters",
|
||||
}
|
||||
)
|
||||
|
||||
// Cluster controls an instance of a Rook cluster
|
||||
type Cluster struct {
|
||||
context *clusterd.Context
|
||||
v1.ObjectMeta `json:"metadata,omitempty"`
|
||||
Spec `json:"spec"`
|
||||
mons *mon.Cluster
|
||||
mgrs *mgr.Cluster
|
||||
osds *osd.Cluster
|
||||
apis *api.Cluster
|
||||
rgws *rgw.Cluster
|
||||
rclient rookclient.RookRestClient
|
||||
// ClusterController controls an instance of a Rook cluster
|
||||
type ClusterController struct {
|
||||
context *clusterd.Context
|
||||
scheme *runtime.Scheme
|
||||
devicesInUse bool
|
||||
}
|
||||
|
||||
// Init assigns the cluster context
|
||||
func (c *Cluster) Init(context *clusterd.Context) {
|
||||
// NewClusterController create controller for watching cluster custom resources created
|
||||
func NewClusterController(context *clusterd.Context) (*ClusterController, error) {
|
||||
return &ClusterController{
|
||||
context: context,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// Watch watches instances of cluster resources
|
||||
func (c *ClusterController) StartWatch(namespace string, stopCh chan struct{}) error {
|
||||
|
||||
customResourceClient, scheme, err := kit.NewHTTPClient(k8sutil.CustomResourceGroup, k8sutil.V1Alpha1, schemeBuilder)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get a k8s client for watching cluster resources: %v", err)
|
||||
}
|
||||
c.scheme = scheme
|
||||
|
||||
resourceHandlerFuncs := cache.ResourceEventHandlerFuncs{
|
||||
AddFunc: c.onAdd,
|
||||
UpdateFunc: c.onUpdate,
|
||||
DeleteFunc: c.onDelete,
|
||||
}
|
||||
|
||||
watcher := kit.NewWatcher(ClusterResource, namespace, resourceHandlerFuncs, customResourceClient)
|
||||
go watcher.Watch(&Cluster{}, stopCh)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ClusterController) onAdd(obj interface{}) {
|
||||
clusterOrig := obj.(*Cluster)
|
||||
|
||||
// NEVER modify objects from the store. It's a read-only, local cache.
|
||||
// Use scheme.Copy() to make a deep copy of original object.
|
||||
copyObj, err := c.scheme.Copy(clusterOrig)
|
||||
if err != nil {
|
||||
logger.Errorf("creating a deep copy of cluster object: %v\n", err)
|
||||
return
|
||||
}
|
||||
cluster := copyObj.(*Cluster)
|
||||
|
||||
cluster.init(c.context)
|
||||
if c.devicesInUse && cluster.Spec.Storage.AnyUseAllDevices() {
|
||||
logger.Warningf("using all devices in more than one namespace not supported. ignoring devices in namespace %s", cluster.Namespace)
|
||||
cluster.Spec.Storage.ClearUseAllDevices()
|
||||
}
|
||||
|
||||
if cluster.Spec.Storage.AnyUseAllDevices() {
|
||||
c.devicesInUse = true
|
||||
}
|
||||
|
||||
logger.Infof("starting cluster %s in namespace %s", cluster.Name, cluster.Namespace)
|
||||
// Start the Rook cluster components. Retry several times in case of failure.
|
||||
err = wait.Poll(clusterCreateInterval, clusterCreateTimeout, func() (bool, error) {
|
||||
err = cluster.createInstance()
|
||||
if err != nil {
|
||||
logger.Errorf("failed to create cluster %s in namespace %s. %+v", cluster.Name, cluster.Namespace, err)
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf("giving up to create cluster %s in namespace %s after %s", cluster.Name, cluster.Namespace, clusterCreateTimeout)
|
||||
return
|
||||
}
|
||||
|
||||
// Start pool CRD watcher
|
||||
poolController, err := pool.NewPoolController(c.context.Clientset)
|
||||
poolController.StartWatch(cluster.Namespace, cluster.stopCh)
|
||||
|
||||
// Start mon health checker
|
||||
healthChecker := mon.NewHealthChecker(cluster.mons)
|
||||
go healthChecker.Check(cluster.stopCh)
|
||||
}
|
||||
|
||||
func (c *ClusterController) onUpdate(oldObj, newObj interface{}) {
|
||||
logger.Infof("modifying a cluster not implemented")
|
||||
}
|
||||
|
||||
func (c *ClusterController) onDelete(obj interface{}) {
|
||||
logger.Infof("deleting a cluster not implemented")
|
||||
}
|
||||
|
||||
func (c *Cluster) init(context *clusterd.Context) {
|
||||
c.context = context
|
||||
}
|
||||
|
||||
// CreateInstance creates a new Rook cluster instance
|
||||
func (c *Cluster) CreateInstance() error {
|
||||
|
||||
// Create the namespace if not already created
|
||||
ns := &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: c.Namespace}}
|
||||
_, err := c.context.Clientset.CoreV1().Namespaces().Create(ns)
|
||||
if err != nil {
|
||||
if !errors.IsAlreadyExists(err) {
|
||||
return fmt.Errorf("failed to create namespace %s. %+v", c.Namespace, err)
|
||||
}
|
||||
}
|
||||
func (c *Cluster) createInstance() error {
|
||||
|
||||
// Create a configmap for overriding ceph config settings
|
||||
// These settings should only be modified by a user after they are initialized
|
||||
@@ -98,7 +160,7 @@ func (c *Cluster) CreateInstance() error {
|
||||
}
|
||||
cm := &v1.ConfigMap{Data: placeholderConfig}
|
||||
cm.Name = k8sutil.ConfigOverrideName
|
||||
_, err = c.context.Clientset.CoreV1().ConfigMaps(c.Namespace).Create(cm)
|
||||
_, err := c.context.Clientset.CoreV1().ConfigMaps(c.Namespace).Create(cm)
|
||||
if err != nil && !errors.IsAlreadyExists(err) {
|
||||
return fmt.Errorf("failed to create override configmap %s. %+v", c.Namespace, err)
|
||||
}
|
||||
@@ -139,28 +201,15 @@ func (c *Cluster) CreateInstance() error {
|
||||
return fmt.Errorf("failed to create client access. %+v", err)
|
||||
}
|
||||
|
||||
c.rookClient, err = api.GetRookClient(c.Namespace, c.context.Clientset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to get rook client: %v", err)
|
||||
}
|
||||
|
||||
logger.Infof("Done creating rook instance in namespace %s", c.Namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Monitor watches a cluster for failures and restarts failed components
|
||||
func (c *Cluster) Monitor(stopCh <-chan struct{}) {
|
||||
for {
|
||||
select {
|
||||
case <-stopCh:
|
||||
logger.Infof("Stopping monitoring of cluster in namespace %s", c.Namespace)
|
||||
return
|
||||
|
||||
case <-time.After(healthCheckInterval):
|
||||
logger.Debugf("checking health of mons")
|
||||
err := c.mons.CheckHealth()
|
||||
if err != nil {
|
||||
logger.Infof("failed to check mon health. %+v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) createInitialCrushMap() error {
|
||||
configMapExists := false
|
||||
createCrushMap := false
|
||||
@@ -258,24 +307,3 @@ func (c *Cluster) createClientAccess(clusterInfo *cephmon.ClusterInfo) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRookClient gets the REST api client
|
||||
func (c *Cluster) GetRookClient() (rookclient.RookRestClient, error) {
|
||||
if c.rclient != nil {
|
||||
return c.rclient, nil
|
||||
}
|
||||
|
||||
// Look up the api service for the given namespace
|
||||
logger.Infof("retrieving rook api endpoint for namespace %s", c.Namespace)
|
||||
svc, err := c.context.Clientset.CoreV1().Services(c.Namespace).Get(api.DeploymentName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to find the api service. %+v", err)
|
||||
}
|
||||
|
||||
httpClient := http.DefaultClient
|
||||
httpClient.Timeout = clientTimeout
|
||||
endpoint := fmt.Sprintf("%s:%d", svc.Spec.ClusterIP, svc.Spec.Ports[0].Port)
|
||||
c.rclient = rookclient.NewRookNetworkRestClient(rookclient.GetRestURL(endpoint), httpClient)
|
||||
logger.Infof("rook api endpoint %s for namespace %s", endpoint, c.Namespace)
|
||||
return c.rclient, nil
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import (
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
exectest "github.com/rook/rook/pkg/util/exec/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -41,14 +40,13 @@ func TestCreateSecrets(t *testing.T) {
|
||||
return "{\"key\":\"mysecurekey\"}", nil
|
||||
},
|
||||
}
|
||||
c := &Cluster{Spec: Spec{VersionTag: "myversion"}}
|
||||
c := &Cluster{Spec: ClusterSpec{VersionTag: "myversion"}}
|
||||
c.Name = "myrook"
|
||||
c.Namespace = "myns"
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
c.Init(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}, ConfigDir: configDir, Executor: executor})
|
||||
c.init(&clusterd.Context{Clientset: clientset, ConfigDir: configDir, Executor: executor})
|
||||
defer os.RemoveAll(c.context.ConfigDir)
|
||||
|
||||
err := c.createClientAccess(info)
|
||||
assert.Nil(t, err)
|
||||
|
||||
@@ -64,7 +62,7 @@ func TestCreateInitialCrushMap(t *testing.T) {
|
||||
executor := &exectest.MockExecutor{}
|
||||
c := &Cluster{}
|
||||
c.Namespace = "rook294"
|
||||
c.Init(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}, Executor: executor})
|
||||
c.init(&clusterd.Context{Clientset: clientset, Executor: executor})
|
||||
|
||||
// create the initial crush map and verify that a configmap value was created that says the crush map was created
|
||||
err := c.createInitialCrushMap()
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package cluster to manage a rook cluster.
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// PoolList is a list of rook pools from the TPR.
|
||||
type PoolList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
// Standard list metadata
|
||||
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
|
||||
Metadata metav1.ListMeta `json:"metadata,omitempty"`
|
||||
// Items is a list of third party objects
|
||||
Items []Pool `json:"items"`
|
||||
}
|
||||
|
||||
// There is known issue with TPR in client-go:
|
||||
// https://github.com/kubernetes/client-go/issues/8
|
||||
// Workarounds:
|
||||
// - We include `Metadata` field in object explicitly.
|
||||
// - we have the code below to work around a known problem with third-party resources and ugorji.
|
||||
|
||||
// PoolListCopy is for deserialization
|
||||
type PoolListCopy PoolList
|
||||
|
||||
// PoolCopy is for deserialization
|
||||
type PoolCopy Pool
|
||||
|
||||
// UnmarshalJSON deserializes the pool
|
||||
func (p *Pool) UnmarshalJSON(data []byte) error {
|
||||
tmp := PoolCopy{}
|
||||
err := json.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp2 := Pool(tmp)
|
||||
*p = tmp2
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON deserializes the pool list
|
||||
func (pl *PoolList) UnmarshalJSON(data []byte) error {
|
||||
tmp := PoolListCopy{}
|
||||
err := json.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp2 := PoolList(tmp)
|
||||
*pl = tmp2
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Copyright 2017 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
|
||||
addToScheme = schemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
var ClusterResource = kit.CustomResource{
|
||||
Name: customResourceName,
|
||||
Plural: customResourceNamePlural,
|
||||
Group: k8sutil.CustomResourceGroup,
|
||||
Version: k8sutil.V1Alpha1,
|
||||
Scope: apiextensionsv1beta1.NamespaceScoped,
|
||||
Kind: reflect.TypeOf(Cluster{}).Name(),
|
||||
}
|
||||
|
||||
// Kind takes an unqualified kind and returns back a Group qualified GroupKind
|
||||
func Kind(kind string) schema.GroupKind {
|
||||
return schemeGroupVersion.WithKind(kind).GroupKind()
|
||||
}
|
||||
|
||||
// Resource takes an unqualified resource and returns back a Group qualified GroupResource
|
||||
func Resource(resource string) schema.GroupResource {
|
||||
return schemeGroupVersion.WithResource(resource).GroupResource()
|
||||
}
|
||||
|
||||
// Adds the list of known types to api.Scheme.
|
||||
func addKnownTypes(scheme *runtime.Scheme) error {
|
||||
scheme.AddKnownTypes(schemeGroupVersion,
|
||||
&Cluster{},
|
||||
&ClusterList{},
|
||||
)
|
||||
metav1.AddToGroupVersion(scheme, schemeGroupVersion)
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2016 The Rook Authors. All rights reserved.
|
||||
Copyright 2017 The Rook 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.
|
||||
@@ -21,12 +21,45 @@ which also has the apache 2.0 license.
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/api"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/mgr"
|
||||
"github.com/rook/rook/pkg/operator/mon"
|
||||
"github.com/rook/rook/pkg/operator/osd"
|
||||
"github.com/rook/rook/pkg/operator/rgw"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
// Spec for the cluster
|
||||
type Spec struct {
|
||||
// schemeGroupVersion is group version used to register these objects
|
||||
var schemeGroupVersion = schema.GroupVersion{Group: k8sutil.CustomResourceGroup, Version: k8sutil.V1Alpha1}
|
||||
|
||||
// Cluster represents an object of a Rook cluster
|
||||
type Cluster struct {
|
||||
context *clusterd.Context
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ObjectMeta `json:"metadata"`
|
||||
Spec ClusterSpec `json:"spec"`
|
||||
mons *mon.Cluster
|
||||
mgrs *mgr.Cluster
|
||||
osds *osd.Cluster
|
||||
apis *api.Cluster
|
||||
rgws *rgw.Cluster
|
||||
rookClient rookclient.RookRestClient
|
||||
stopCh chan struct{}
|
||||
}
|
||||
|
||||
// ClusterList represents an object of a Rook cluster list
|
||||
type ClusterList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ListMeta `json:"metadata"`
|
||||
Items []Cluster `json:"items"`
|
||||
}
|
||||
|
||||
// ClusterSpec represents an object of a Rook cluster spec
|
||||
type ClusterSpec struct {
|
||||
// VersionTag is the expected version of the rook container to run in the cluster.
|
||||
// The operator will eventually make the rook cluster version
|
||||
// equal to the expected version.
|
||||
@@ -45,30 +78,6 @@ type Spec struct {
|
||||
Storage osd.StorageSpec `json:"storage"`
|
||||
}
|
||||
|
||||
// PoolSpec is the specific spec for the redundancy
|
||||
type PoolSpec struct {
|
||||
// The replication settings
|
||||
Replication ReplicationSpec `json:"replication"`
|
||||
|
||||
// The erasure code setteings
|
||||
ErasureCoding ErasureCodeSpec `json:"erasureCode"`
|
||||
}
|
||||
|
||||
// ReplicationSpec specifies the number of replicas
|
||||
type ReplicationSpec struct {
|
||||
// Number of copies per object in a replicated storage pool, including the object itself (required for replicated pool type)
|
||||
Size uint `json:"size"`
|
||||
}
|
||||
|
||||
// ErasureCodeSpec specifies the erasure coding params
|
||||
type ErasureCodeSpec struct {
|
||||
// Number of coding chunks per object in an erasure coded storage pool (required for erasure-coded pool type)
|
||||
CodingChunks uint `json:"codingChunks"`
|
||||
|
||||
// Number of data chunks per object in an erasure coded storage pool (required for erasure-coded pool type)
|
||||
DataChunks uint `json:"dataChunks"`
|
||||
}
|
||||
|
||||
// PlacementSpec is a set of Placement configurations for the rook cluster.
|
||||
type PlacementSpec struct {
|
||||
All k8sutil.Placement `json:"all,omitempty"`
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
package operator
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/cluster"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestTrackCluster(t *testing.T) {
|
||||
context := &clusterd.Context{}
|
||||
mgr := newClusterManager(context, []inclusterInitiator{})
|
||||
|
||||
c1 := &cluster.Cluster{}
|
||||
c1.Name = "myname"
|
||||
c1.Namespace = "myns"
|
||||
c1.ResourceVersion = "23"
|
||||
|
||||
// not tracked yet
|
||||
checkClusterTracked(t, mgr, c1, false, false)
|
||||
|
||||
// track the cluster
|
||||
err := mgr.startTrack(c1)
|
||||
assert.Nil(t, err)
|
||||
checkClusterTracked(t, mgr, c1, true, true)
|
||||
|
||||
// do not support muliple clusters in the same namespace
|
||||
c2 := &cluster.Cluster{}
|
||||
c2.Name = "myothername"
|
||||
c2.Namespace = "myns"
|
||||
c2.ResourceVersion = "24"
|
||||
err = mgr.startTrack(c2)
|
||||
assert.NotNil(t, err)
|
||||
checkClusterTracked(t, mgr, c2, false, true)
|
||||
|
||||
// stop tracking the cluster
|
||||
mgr.stopTrack(c1)
|
||||
checkClusterTracked(t, mgr, c1, false, false)
|
||||
}
|
||||
|
||||
func checkClusterTracked(t *testing.T, mgr *clusterManager, c *cluster.Cluster, nameTracked, namespaceTracked bool) {
|
||||
trackedCluster, clusterOK := mgr.clusters[c.Namespace]
|
||||
version, trackerOK := mgr.tracker.clusterRVs[c.Namespace]
|
||||
assert.Equal(t, namespaceTracked, clusterOK)
|
||||
assert.Equal(t, namespaceTracked, trackerOK)
|
||||
if nameTracked {
|
||||
assert.Equal(t, c.Name, trackedCluster.Name)
|
||||
assert.Equal(t, c.ResourceVersion, version)
|
||||
}
|
||||
if namespaceTracked && !nameTracked {
|
||||
assert.NotEqual(t, c.Name, trackedCluster.Name)
|
||||
assert.NotEqual(t, c.ResourceVersion, version)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,17 @@ import "github.com/coreos/pkg/capnslog"
|
||||
|
||||
var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-k8sutil")
|
||||
|
||||
const (
|
||||
// V1Alpha1 version for kubernetes resources
|
||||
V1Alpha1 = "v1alpha1"
|
||||
|
||||
// V1Beta1 version for kubernetes resources
|
||||
V1Beta1 = "v1beta1"
|
||||
|
||||
// V1 version for kubernetes resources
|
||||
V1 = "v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// Namespace for rook
|
||||
Namespace = "rook"
|
||||
|
||||
+19
-11
@@ -24,27 +24,35 @@ import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
"k8s.io/client-go/kubernetes/scheme"
|
||||
"k8s.io/client-go/rest"
|
||||
)
|
||||
|
||||
// NewHTTPClient creates a new http client for the operator to manage the Kubernetes cluster
|
||||
func NewHTTPClient(group string) (*rest.RESTClient, error) {
|
||||
const (
|
||||
serverVersionV170 = "v1.7.0"
|
||||
)
|
||||
|
||||
// NewHTTPClient creates a Kubernetes client to interact with API extensions for Custom Resources
|
||||
func NewHTTPClient(group, version string, schemeBuilder runtime.SchemeBuilder) (*rest.RESTClient, *runtime.Scheme, error) {
|
||||
scheme := runtime.NewScheme()
|
||||
if err := schemeBuilder.AddToScheme(scheme); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
config, err := rest.InClusterConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
config.GroupVersion = &schema.GroupVersion{
|
||||
Group: group,
|
||||
}
|
||||
config.GroupVersion = &schema.GroupVersion{Group: group, Version: version}
|
||||
|
||||
config.APIPath = "/apis"
|
||||
config.ContentType = runtime.ContentTypeJSON
|
||||
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
|
||||
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(scheme)}
|
||||
|
||||
restcli, err := rest.RESTClientFor(config)
|
||||
client, err := rest.RESTClientFor(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
return restcli, nil
|
||||
|
||||
return client, scheme, nil
|
||||
}
|
||||
+139
-86
@@ -22,140 +22,193 @@ package kit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"k8s.io/api/extensions/v1beta1"
|
||||
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
||||
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
errorsUtil "k8s.io/apimachinery/pkg/util/errors"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/kubernetes/pkg/util/version"
|
||||
)
|
||||
|
||||
const (
|
||||
// V1Alpha1 version for kubernetes resources
|
||||
V1Alpha1 = "v1alpha1"
|
||||
|
||||
// V1Beta1 version for kubernetes resources
|
||||
V1Beta1 = "v1beta1"
|
||||
|
||||
// V1 version for kubernetes resources
|
||||
V1 = "v1"
|
||||
)
|
||||
|
||||
// KubeContext provides the context for connecting to Kubernetes APIs
|
||||
type KubeContext struct {
|
||||
// Clientset is a connection to the core kubernetes API
|
||||
Clientset kubernetes.Interface
|
||||
|
||||
// RetryDelay is the number of seconds to delay between retrying of kubernetes API calls.
|
||||
// Only used by the Retry function.
|
||||
RetryDelay int
|
||||
|
||||
// MaxRetries is the number of times that an operation will be attempted by the Retry function.
|
||||
MaxRetries int
|
||||
|
||||
// The host where the Kubernetes master is found.
|
||||
MasterHost string
|
||||
|
||||
// An http connection to the Kubernetes API
|
||||
KubeHTTPCli *http.Client
|
||||
}
|
||||
|
||||
// CustomResource is for creating a Kubernetes TPR/CRD
|
||||
type CustomResource struct {
|
||||
// Name of the custom resource
|
||||
Name string
|
||||
|
||||
// Plural of the custom resource in plural
|
||||
Plural string
|
||||
|
||||
// Group the custom resource belongs to
|
||||
Group string
|
||||
|
||||
// Version which should be defined in a const above
|
||||
Version string
|
||||
|
||||
// Description that is human readable
|
||||
Description string
|
||||
// Scope of the CRD. Namespaced or cluster
|
||||
Scope apiextensionsv1beta1.ResourceScope
|
||||
|
||||
// Kind is the serialized interface of the resource.
|
||||
Kind string
|
||||
}
|
||||
|
||||
// Context hold the clientsets used for creating and watching custom resources
|
||||
type Context struct {
|
||||
Clientset kubernetes.Interface
|
||||
APIExtensionClientset apiextensionsclient.Interface
|
||||
Interval time.Duration
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// CreateCustomResources creates the given custom resources and waits for them to initialize
|
||||
func CreateCustomResources(context KubeContext, resources []CustomResource) error {
|
||||
for _, resource := range resources {
|
||||
if err := CreateCustomResource(context, resource); err != nil {
|
||||
return fmt.Errorf("failed to init resource %s. %+v", resource.Name, err)
|
||||
// The resource is of kind CRD if the Kubernetes server is 1.7.0.
|
||||
// The resource is of kind TPR if the Kubernetes server is before 1.7.0.
|
||||
func CreateCustomResources(context Context, resources []CustomResource) error {
|
||||
|
||||
// CRD is available on v1.7.0. TPR became deprecated on v1.7.0
|
||||
serverVersion, err := context.Clientset.Discovery().ServerVersion()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting server version: %v", err)
|
||||
}
|
||||
kubeVersion := version.MustParseSemantic(serverVersion.GitVersion)
|
||||
|
||||
if kubeVersion.AtLeast(version.MustParseSemantic(serverVersionV170)) {
|
||||
for _, resource := range resources {
|
||||
err = createCRD(context, resource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create resource %s. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, resource := range resources {
|
||||
if err := waitForCRDInit(context, resource); err != nil {
|
||||
return fmt.Errorf("failed to complete init %s. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Create and wait for TPR resources
|
||||
for _, resource := range resources {
|
||||
err = createTPR(context, resource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create resource %s. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, resource := range resources {
|
||||
if err := waitForTPRInit(context, resource); err != nil {
|
||||
return fmt.Errorf("failed to complete init %s. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, resource := range resources {
|
||||
if err := waitForCustomResourceInit(context, resource); err != nil {
|
||||
return fmt.Errorf("failed to complete init %s. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateCustomResource creates a single custom resource, but does not wait for it to initialize
|
||||
func CreateCustomResource(context KubeContext, resource CustomResource) error {
|
||||
logger.Infof("creating %s resource", resource.Name)
|
||||
r := &v1beta1.ThirdPartyResource{
|
||||
func createCRD(context Context, resource CustomResource) error {
|
||||
logger.Infof("creating %s CRD", resource.Name)
|
||||
crdName := fmt.Sprintf("%s.%s", resource.Plural, resource.Group)
|
||||
crd := &apiextensionsv1beta1.CustomResourceDefinition{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: fmt.Sprintf("%s.%s", resource.Name, resource.Group),
|
||||
Name: crdName,
|
||||
},
|
||||
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
|
||||
Group: resource.Group,
|
||||
Version: resource.Version,
|
||||
Scope: resource.Scope,
|
||||
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
|
||||
Singular: resource.Name,
|
||||
Plural: resource.Plural,
|
||||
Kind: resource.Kind,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := context.APIExtensionClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd)
|
||||
if err != nil {
|
||||
if !errors.IsAlreadyExists(err) {
|
||||
return fmt.Errorf("failed to create %s CRD. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitForCRDInit(context Context, resource CustomResource) error {
|
||||
crdName := fmt.Sprintf("%s.%s", resource.Plural, resource.Group)
|
||||
err := wait.Poll(context.Interval, context.Timeout, func() (bool, error) {
|
||||
crd, err := context.APIExtensionClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(crdName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, cond := range crd.Status.Conditions {
|
||||
switch cond.Type {
|
||||
case apiextensionsv1beta1.Established:
|
||||
if cond.Status == apiextensionsv1beta1.ConditionTrue {
|
||||
return true, err
|
||||
}
|
||||
case apiextensionsv1beta1.NamesAccepted:
|
||||
if cond.Status == apiextensionsv1beta1.ConditionFalse {
|
||||
fmt.Printf("Name conflict: %v\n", cond.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, err
|
||||
})
|
||||
if err != nil {
|
||||
deleteErr := context.APIExtensionClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(crdName, nil)
|
||||
if deleteErr != nil {
|
||||
return errorsUtil.NewAggregate([]error{err, deleteErr})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createTPR(context Context, resource CustomResource) error {
|
||||
logger.Infof("creating %s TPR", resource.Name)
|
||||
tprName := fmt.Sprintf("%s.%s", resource.Name, resource.Group)
|
||||
tpr := &v1beta1.ThirdPartyResource{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tprName,
|
||||
},
|
||||
Versions: []v1beta1.APIVersion{
|
||||
{Name: resource.Version},
|
||||
},
|
||||
Description: resource.Description,
|
||||
Description: fmt.Sprintf("ThirdPartyResource for Rook %s", resource.Name),
|
||||
}
|
||||
_, err := context.Clientset.ExtensionsV1beta1().ThirdPartyResources().Create(r)
|
||||
_, err := context.Clientset.ExtensionsV1beta1().ThirdPartyResources().Create(tpr)
|
||||
if err != nil {
|
||||
if !errors.IsAlreadyExists(err) {
|
||||
return fmt.Errorf("failed to create %s resource. %+v", resource.Name, err)
|
||||
return fmt.Errorf("failed to create %s TPR. %+v", resource.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitForCustomResourceInit(context KubeContext, resource CustomResource) error {
|
||||
func waitForTPRInit(context Context, resource CustomResource) error {
|
||||
// wait for TPR being established
|
||||
restcli := context.Clientset.CoreV1().RESTClient()
|
||||
uri := resourceURI(resource, "")
|
||||
return Retry(context, func() (bool, error) {
|
||||
uri := fmt.Sprintf("apis/%s/%s/%s", resource.Group, resource.Version, resource.Plural)
|
||||
tprName := fmt.Sprintf("%s.%s", resource.Name, resource.Group)
|
||||
|
||||
err := wait.Poll(context.Interval, context.Timeout, func() (bool, error) {
|
||||
_, err := restcli.Get().RequestURI(uri).DoRaw()
|
||||
if err != nil {
|
||||
logger.Infof("did not yet find resource %s at %s. %+v", resource.Name, uri, err)
|
||||
if errors.IsNotFound(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func watchResource(context KubeContext, resource CustomResource, namespace, resourceVersion string) (*http.Response, error) {
|
||||
uri := fmt.Sprintf("%s/%s?watch=true&resourceVersion=%s", context.MasterHost, resourceURI(resource, namespace), resourceVersion)
|
||||
logger.Debugf("watching resource: %s", uri)
|
||||
return context.KubeHTTPCli.Get(uri)
|
||||
}
|
||||
|
||||
func resourceURI(resource CustomResource, namespace string) string {
|
||||
if namespace == "" {
|
||||
// creates a uri that is for retrieving or watching a resource in all namespaces. For example:
|
||||
// /apis/rook.io/v1alpha1/clusters
|
||||
return fmt.Sprintf("apis/%s/%s/%ss", resource.Group, resource.Version, resource.Name)
|
||||
if err != nil {
|
||||
deleteErr := context.Clientset.ExtensionsV1beta1().ThirdPartyResources().Delete(tprName, nil)
|
||||
if deleteErr != nil {
|
||||
return errorsUtil.NewAggregate([]error{err, deleteErr})
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// create a uri that is for a specific namespace
|
||||
// /apis/rook.io/v1alpha1/namespaces/rook/pools
|
||||
return fmt.Sprintf("apis/%s/%s/namespaces/%s/%ss", resource.Group, resource.Version, namespace, resource.Name)
|
||||
}
|
||||
|
||||
// GetRawListNamespaced retrieves a list custom resources of the given type in a specific namespace
|
||||
func GetRawListNamespaced(clientset kubernetes.Interface, resource CustomResource, namespace string) ([]byte, error) {
|
||||
restcli := clientset.CoreV1().RESTClient()
|
||||
uri := resourceURI(resource, namespace)
|
||||
return restcli.Get().RequestURI(uri).DoRaw()
|
||||
}
|
||||
|
||||
// GetRawList retrieves a list of custom resources of the given type across all namespaces
|
||||
func GetRawList(clientset kubernetes.Interface, resource CustomResource) ([]byte, error) {
|
||||
return GetRawListNamespaced(clientset, resource, "")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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 kit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rook/rook/pkg/operator/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
||||
apiextensionsclientfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
var exampleResource = CustomResource{
|
||||
Name: "example",
|
||||
Plural: "examples",
|
||||
Group: "example.com",
|
||||
Version: "v1alpha",
|
||||
Scope: apiextensionsv1beta1.NamespaceScoped,
|
||||
}
|
||||
|
||||
func TestCreateCRDCustomResource(t *testing.T) {
|
||||
ctx := Context{
|
||||
APIExtensionClientset: apiextensionsclientfake.NewSimpleClientset(),
|
||||
Interval: 100 * time.Millisecond,
|
||||
Timeout: 1 * time.Second,
|
||||
}
|
||||
|
||||
err := createCRD(ctx, exampleResource)
|
||||
assert.NoError(t, err)
|
||||
|
||||
crdName := fmt.Sprintf("%s.%s", exampleResource.Plural, exampleResource.Group)
|
||||
crd, err := ctx.APIExtensionClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(crdName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("CustomResource.Create: %+v", err))
|
||||
}
|
||||
|
||||
assert.Equal(t, crdName, crd.ObjectMeta.Name)
|
||||
assert.Equal(t, "examples", crd.Spec.Names.Plural)
|
||||
assert.Equal(t, "example", crd.Spec.Names.Singular)
|
||||
assert.Equal(t, "example.com", crd.Spec.Group)
|
||||
assert.Equal(t, "v1alpha", crd.Spec.Version)
|
||||
assert.Equal(t, apiextensionsv1beta1.NamespaceScoped, crd.Spec.Scope)
|
||||
}
|
||||
|
||||
func TestCreateTPRCustomResource(t *testing.T) {
|
||||
ctx := Context{
|
||||
Clientset: test.New(3),
|
||||
Interval: 100 * time.Millisecond,
|
||||
Timeout: 1 * time.Second,
|
||||
}
|
||||
|
||||
err := createTPR(ctx, exampleResource)
|
||||
assert.NoError(t, err)
|
||||
|
||||
tprName := fmt.Sprintf("%s.%s", exampleResource.Name, exampleResource.Group)
|
||||
tpr, err := ctx.Clientset.ExtensionsV1beta1().ThirdPartyResources().Get(tprName, metav1.GetOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tprName, tpr.ObjectMeta.Name)
|
||||
assert.Equal(t, "v1alpha", tpr.Versions[0].Name)
|
||||
assert.Equal(t, "ThirdPartyResource for Rook example", tpr.Description)
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package kit for Kubernetes operators
|
||||
package kit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConditionFunc returns true if a retry condition has been satisfied.
|
||||
// If the condition returns false, the retry will try again.
|
||||
type ConditionFunc func() (bool, error)
|
||||
|
||||
// Retry retries f every interval until after maxRetries.
|
||||
// The interval won't be affected by how long f takes.
|
||||
// For example, if interval is 3s, f takes 1s, another f will be called 2s later.
|
||||
// However, if f takes longer than interval, it will be delayed.
|
||||
func Retry(context KubeContext, f ConditionFunc) error {
|
||||
interval := time.Duration(context.RetryDelay) * time.Second
|
||||
tick := time.NewTicker(interval)
|
||||
defer tick.Stop()
|
||||
|
||||
for i := 0; i < context.MaxRetries; i++ {
|
||||
ok, err := f()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed on retry %d. %+v", i, err)
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
if i < context.MaxRetries-1 {
|
||||
<-tick.C
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("failed after max retries %d", context.MaxRetries)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package kit for Kubernetes operators
|
||||
package kit
|
||||
|
||||
import "time"
|
||||
|
||||
// panicTimer panics when it reaches the given duration.
|
||||
type panicTimer struct {
|
||||
duration time.Duration
|
||||
message string
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
func (t *panicTimer) Start() {
|
||||
t.timer = time.AfterFunc(t.duration, func() {
|
||||
panic(t.message)
|
||||
})
|
||||
}
|
||||
|
||||
// stop stops the timer and resets the elapsed duration.
|
||||
func (t *panicTimer) Stop() {
|
||||
if t.timer != nil {
|
||||
t.timer.Stop()
|
||||
t.timer = nil
|
||||
}
|
||||
}
|
||||
+39
-186
@@ -21,16 +21,13 @@ which also has the apache 2.0 license.
|
||||
package kit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
kwatch "k8s.io/apimachinery/pkg/watch"
|
||||
"k8s.io/apimachinery/pkg/fields"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/client-go/rest"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -40,198 +37,54 @@ var (
|
||||
|
||||
// ResourceWatcher watches a custom resource for desired state
|
||||
type ResourceWatcher struct {
|
||||
context KubeContext
|
||||
resource CustomResource
|
||||
namespace string
|
||||
watchVersion string
|
||||
callback func(event *RawEvent) error
|
||||
checkStaleCache func() (string, error)
|
||||
}
|
||||
|
||||
// RawEvent is the raw json message retrieved from the TPR/CRD update
|
||||
type RawEvent struct {
|
||||
Type kwatch.EventType
|
||||
Object json.RawMessage
|
||||
resource CustomResource
|
||||
namespace string
|
||||
resourceEventHandlers cache.ResourceEventHandlerFuncs
|
||||
client *rest.RESTClient
|
||||
scheme *runtime.Scheme
|
||||
}
|
||||
|
||||
// NewWatcher creates an instance of a custom resource watcher for the given resource
|
||||
func NewWatcher(context KubeContext, resource CustomResource, namespace, watchVersion string,
|
||||
callback func(event *RawEvent) error,
|
||||
checkStaleCache func() (string, error)) *ResourceWatcher {
|
||||
|
||||
// Assign a default func for resources that don't have a cache
|
||||
if checkStaleCache == nil {
|
||||
checkStaleCache = func() (string, error) {
|
||||
// there is no cache for the resource so we indicate to always reset the watch on error
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
func NewWatcher(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client *rest.RESTClient) *ResourceWatcher {
|
||||
return &ResourceWatcher{
|
||||
context: context,
|
||||
resource: resource,
|
||||
namespace: namespace,
|
||||
watchVersion: watchVersion,
|
||||
callback: callback,
|
||||
checkStaleCache: checkStaleCache,
|
||||
resource: resource,
|
||||
namespace: namespace,
|
||||
resourceEventHandlers: handlers,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// Watch begins watching the custom resource (TPR/CRD). The call will block until an error is raised during the watch.
|
||||
// When the watch has detected a create, update, or delete event, the raw event will be passed to the caller
|
||||
// in the callback. After the callback returns, the watch loop will continue for the next event.
|
||||
// If the callback returns an error, the error will be logged but will not abort the event loop.
|
||||
func (w *ResourceWatcher) Watch() error {
|
||||
if w.namespace == "" {
|
||||
logger.Infof("start watching %s resource in all namespaces at %s", w.resource.Name, w.watchVersion)
|
||||
// Watch begins watching the custom resource (TPR/CRD). The call will block until a Done signal is raised during in the context.
|
||||
// When the watch has detected a create, update, or delete event, it will handled by the functions in the resourceEventHandlers. After the callback returns, the watch loop will continue for the next event.
|
||||
// If the callback returns an error, the error will be logged.
|
||||
func (w *ResourceWatcher) Watch(objType runtime.Object, done chan struct{}) error {
|
||||
if w.namespace == v1.NamespaceAll {
|
||||
logger.Infof("start watching %s resource in all namespaces at %s", w.resource.Name, w.resource.Version)
|
||||
} else {
|
||||
logger.Infof("start watching %s resource in namespace %s at %s", w.resource.Name, w.namespace, w.watchVersion)
|
||||
logger.Infof("start watching %s resource in namespace %s at %s", w.resource.Name, w.namespace, w.resource.Version)
|
||||
}
|
||||
|
||||
eventCh, errCh := w.watch()
|
||||
source := cache.NewListWatchFromClient(
|
||||
w.client,
|
||||
w.resource.Plural,
|
||||
w.namespace,
|
||||
fields.Everything())
|
||||
|
||||
go func() {
|
||||
_, controller := cache.NewInformer(
|
||||
source,
|
||||
|
||||
timer := &panicTimer{
|
||||
duration: time.Minute,
|
||||
message: fmt.Sprintf("unexpected long blocking (> 1 Minute) when handling %s event", w.resource.Name),
|
||||
}
|
||||
// The object type.
|
||||
objType,
|
||||
|
||||
for event := range eventCh {
|
||||
timer.Start()
|
||||
// resyncPeriod
|
||||
// Every resyncPeriod, all resources in the cache will retrigger events.
|
||||
// Set to 0 to disable the resync.
|
||||
0,
|
||||
|
||||
err := w.callback(event)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to handle event %s on %s. %+v", event.Type, w.resource.Name, err)
|
||||
}
|
||||
// Your custom resource event handlers.
|
||||
w.resourceEventHandlers)
|
||||
|
||||
timer.Stop()
|
||||
}
|
||||
}()
|
||||
return <-errCh
|
||||
}
|
||||
|
||||
// watch creates a go routine, and watches the custom resource at <name>.<group> starting at
|
||||
// the given watch version. It emits events on the resources through the returned
|
||||
// event chan. Errors will be reported through the returned error chan. The go routine
|
||||
// exits on any error.
|
||||
func (w *ResourceWatcher) watch() (<-chan *RawEvent, <-chan error) {
|
||||
eventCh := make(chan *RawEvent)
|
||||
// On unexpected error case, the operator should exit
|
||||
errCh := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
defer close(eventCh)
|
||||
|
||||
for {
|
||||
err := w.watchOuterResource(eventCh, errCh)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("failed to watch %s resource. %+v", w.resource.Name, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return eventCh, errCh
|
||||
}
|
||||
|
||||
func (w *ResourceWatcher) watchOuterResource(eventCh chan *RawEvent, errCh chan error) error {
|
||||
resp, err := watchResource(w.context, w.resource, w.namespace, w.watchVersion)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("invalid status code: %s", resp.Status)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(resp.Body)
|
||||
for {
|
||||
ev, st, err := pollEvent(decoder)
|
||||
done, err := w.handlePollEventResult(st, err, errCh)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
logger.Debugf("rook pool event: %+v", ev)
|
||||
|
||||
// Extract the resource version from the raw json
|
||||
meta := &v1.ObjectMeta{}
|
||||
err = json.Unmarshal(ev.Object, meta)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fail to unmarshal metadata from body %s: %v", resp.Body, err)
|
||||
}
|
||||
w.watchVersion = meta.ResourceVersion
|
||||
eventCh <- ev
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ResourceWatcher) handlePollEventResult(status *metav1.Status, errIn error, errCh chan error) (done bool, err error) {
|
||||
if errIn != nil {
|
||||
if errIn == io.EOF { // apiserver will close stream periodically
|
||||
logger.Debug("apiserver closed stream")
|
||||
done = true
|
||||
return
|
||||
}
|
||||
|
||||
err = errIn
|
||||
errCh <- fmt.Errorf("received invalid event from API server: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if status != nil {
|
||||
|
||||
if status.Code == http.StatusGone {
|
||||
// event history is outdated.
|
||||
// if nothing has changed, we can go back to watch again.
|
||||
var resourceVersion string
|
||||
resourceVersion, err = w.checkStaleCache()
|
||||
if err == nil && resourceVersion != "" {
|
||||
// we were able to recover from the cache, so we update the watch version to the latest
|
||||
// resource version from the cache
|
||||
logger.Infof("continuing watch based on resource version %s", resourceVersion)
|
||||
w.watchVersion = resourceVersion
|
||||
done = true
|
||||
return
|
||||
}
|
||||
|
||||
// if anything has changed (or error on relist), we have to rebuild the state.
|
||||
// go to recovery path
|
||||
logger.Infof("watch is outdated, must start a watch based on a new resource version")
|
||||
err = ErrVersionOutdated
|
||||
errCh <- ErrVersionOutdated
|
||||
return
|
||||
}
|
||||
|
||||
logger.Errorf("unexpected status response from API server: %v", status.Message)
|
||||
done = true
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func pollEvent(decoder *json.Decoder) (*RawEvent, *metav1.Status, error) {
|
||||
re := &RawEvent{}
|
||||
err := decoder.Decode(re)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, nil, fmt.Errorf("fail to decode raw event from apiserver (%v)", err)
|
||||
}
|
||||
|
||||
if re.Type == kwatch.Error {
|
||||
status := &metav1.Status{}
|
||||
err = json.Unmarshal(re.Object, status)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("fail to decode (%s) into metav1.Status (%v)", re.Object, err)
|
||||
}
|
||||
logger.Infof("returning pollEvent status %+v", status)
|
||||
return nil, status, nil
|
||||
}
|
||||
|
||||
return re, nil, nil
|
||||
go controller.Run(done)
|
||||
<-done
|
||||
return nil
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
exectest "github.com/rook/rook/pkg/util/exec/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -40,9 +39,9 @@ func TestStartMDS(t *testing.T) {
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
context := &clusterd.Context{
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
KubeContext: kit.KubeContext{Clientset: testop.New(3)}}
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
Clientset: testop.New(3)}
|
||||
c := New(context, "ns", "myversion", k8sutil.Placement{})
|
||||
defer os.RemoveAll(c.dataDir)
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
exectest "github.com/rook/rook/pkg/util/exec/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -40,9 +39,9 @@ func TestStartMGR(t *testing.T) {
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
context := &clusterd.Context{
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
KubeContext: kit.KubeContext{Clientset: testop.New(3)}}
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
Clientset: testop.New(3)}
|
||||
c := New(context, "ns", "myversion")
|
||||
defer os.RemoveAll(c.dataDir)
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ package mon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rook/rook/pkg/ceph/client"
|
||||
"github.com/rook/rook/pkg/ceph/mon"
|
||||
@@ -26,8 +27,41 @@ import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// CheckHealth for the monitors
|
||||
func (c *Cluster) CheckHealth() error {
|
||||
var (
|
||||
healthCheckInterval = 10 * time.Second
|
||||
)
|
||||
|
||||
// HealthChecker check health for the monitors
|
||||
type HealthChecker struct {
|
||||
monCluster *Cluster
|
||||
}
|
||||
|
||||
// NewHealthChecker creates a new HealthChecker object
|
||||
func NewHealthChecker(monCluster *Cluster) *HealthChecker {
|
||||
return &HealthChecker{
|
||||
monCluster: monCluster,
|
||||
}
|
||||
}
|
||||
|
||||
// Check periodically the health of the monitors
|
||||
func (hc *HealthChecker) Check(stopCh chan struct{}) {
|
||||
for {
|
||||
select {
|
||||
case <-stopCh:
|
||||
logger.Infof("Stopping monitoring of cluster in namespace %s", hc.monCluster.Namespace)
|
||||
return
|
||||
|
||||
case <-time.After(healthCheckInterval):
|
||||
logger.Debugf("checking health of mons")
|
||||
err := hc.monCluster.checkHealth()
|
||||
if err != nil {
|
||||
logger.Infof("failed to check mon health. %+v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cluster) checkHealth() error {
|
||||
logger.Debugf("Checking health for mons. %+v", c.clusterInfo)
|
||||
|
||||
// connect to the mons
|
||||
|
||||
+41
-39
@@ -33,6 +33,7 @@ import (
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
helper "k8s.io/kubernetes/pkg/api/v1/helper"
|
||||
"k8s.io/kubernetes/pkg/kubelet/apis"
|
||||
)
|
||||
@@ -55,19 +56,21 @@ const (
|
||||
|
||||
// Cluster is for the cluster of monitors
|
||||
type Cluster struct {
|
||||
context *clusterd.Context
|
||||
Namespace string
|
||||
Keyring string
|
||||
Version string
|
||||
MasterHost string
|
||||
Size int
|
||||
Paused bool
|
||||
Port int32
|
||||
clusterInfo *mon.ClusterInfo
|
||||
placement k8sutil.Placement
|
||||
maxMonID int
|
||||
waitForStart bool
|
||||
dataDirHostPath string
|
||||
context *clusterd.Context
|
||||
Namespace string
|
||||
Keyring string
|
||||
Version string
|
||||
MasterHost string
|
||||
Size int
|
||||
Paused bool
|
||||
Port int32
|
||||
clusterInfo *mon.ClusterInfo
|
||||
placement k8sutil.Placement
|
||||
maxMonID int
|
||||
waitForStart bool
|
||||
dataDirHostPath string
|
||||
monPodRetryInterval time.Duration
|
||||
monPodTimeout time.Duration
|
||||
}
|
||||
|
||||
// monConfig for a single monitor
|
||||
@@ -79,14 +82,16 @@ type monConfig struct {
|
||||
// New creates an instance of a mon cluster
|
||||
func New(context *clusterd.Context, namespace, dataDirHostPath, version string, placement k8sutil.Placement) *Cluster {
|
||||
return &Cluster{
|
||||
context: context,
|
||||
placement: placement,
|
||||
dataDirHostPath: dataDirHostPath,
|
||||
Namespace: namespace,
|
||||
Version: version,
|
||||
Size: 3,
|
||||
maxMonID: -1,
|
||||
waitForStart: true,
|
||||
context: context,
|
||||
placement: placement,
|
||||
dataDirHostPath: dataDirHostPath,
|
||||
Namespace: namespace,
|
||||
Version: version,
|
||||
Size: 3,
|
||||
maxMonID: -1,
|
||||
waitForStart: true,
|
||||
monPodRetryInterval: 6 * time.Second,
|
||||
monPodTimeout: 5 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +113,7 @@ func (c *Cluster) Start() (*mon.ClusterInfo, error) {
|
||||
}
|
||||
} else {
|
||||
// Check the health of a previously started cluster
|
||||
err = c.CheckHealth()
|
||||
err = c.checkHealth()
|
||||
if err != nil {
|
||||
logger.Warningf("failed to check mon health %+v. %+v", c.clusterInfo.Monitors, err)
|
||||
}
|
||||
@@ -304,37 +309,34 @@ func (c *Cluster) waitForPodToStart(name string) (string, error) {
|
||||
}
|
||||
|
||||
// Poll the status of the pods to see if they are ready
|
||||
status := ""
|
||||
retryFactor := 3
|
||||
for i := 0; i < c.context.MaxRetries*retryFactor; i++ {
|
||||
// wait and try again
|
||||
if i%retryFactor == 0 {
|
||||
logger.Infof("waiting for mon %s to start. status=%s", name, status)
|
||||
}
|
||||
<-time.After(time.Duration(c.context.RetryDelay/retryFactor) * time.Second)
|
||||
|
||||
options := metav1.ListOptions{LabelSelector: fmt.Sprintf("mon=%s", name)}
|
||||
options := metav1.ListOptions{LabelSelector: fmt.Sprintf("mon=%s", name)}
|
||||
status := string(v1.PodUnknown)
|
||||
var pod v1.Pod
|
||||
err := wait.Poll(c.monPodRetryInterval, c.monPodTimeout, func() (bool, error) {
|
||||
logger.Infof("waiting for mon %s to start. status=%s", name, status)
|
||||
pods, err := c.context.Clientset.CoreV1().Pods(c.Namespace).List(options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get mon %s pod. %+v", name, err)
|
||||
return false, fmt.Errorf("failed to get mon %s pod. %+v", name, err)
|
||||
}
|
||||
if len(pods.Items) == 0 {
|
||||
logger.Infof("%s pod not yet created", name)
|
||||
continue
|
||||
return false, nil
|
||||
}
|
||||
if len(pods.Items) > 1 {
|
||||
logger.Warningf("more than one mon pod found for %s", name)
|
||||
}
|
||||
|
||||
pod := pods.Items[0]
|
||||
pod = pods.Items[0]
|
||||
if pod.Status.Phase == v1.PodRunning {
|
||||
logger.Infof("pod %s started", pod.Name)
|
||||
return pod.Status.PodIP, nil
|
||||
return true, nil
|
||||
}
|
||||
status = string(pod.Status.Phase)
|
||||
return false, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("timed out waiting for pod %s to start", name)
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("timed out waiting for pod %s to start", name)
|
||||
return pod.Status.PodIP, nil
|
||||
}
|
||||
|
||||
func (c *Cluster) saveMonConfig() error {
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"os"
|
||||
|
||||
@@ -29,7 +30,6 @@ import (
|
||||
cephtest "github.com/rook/rook/pkg/ceph/test"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"github.com/rook/rook/pkg/operator/test"
|
||||
exectest "github.com/rook/rook/pkg/util/exec/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -51,11 +51,20 @@ func TestStartMonPods(t *testing.T) {
|
||||
},
|
||||
}
|
||||
context := &clusterd.Context{
|
||||
KubeContext: kit.KubeContext{Clientset: clientset, MaxRetries: 1},
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
Clientset: clientset,
|
||||
Executor: executor,
|
||||
ConfigDir: configDir,
|
||||
}
|
||||
c := &Cluster{
|
||||
context: context,
|
||||
Namespace: namespace,
|
||||
Version: "myversion",
|
||||
Size: 3,
|
||||
maxMonID: -1,
|
||||
waitForStart: true,
|
||||
monPodRetryInterval: 10 * time.Millisecond,
|
||||
monPodTimeout: 1 * time.Second,
|
||||
}
|
||||
c := New(context, namespace, "", "myversion", k8sutil.Placement{})
|
||||
|
||||
// start a basic cluster
|
||||
// an error is expected since mocking always creates pods that are not running
|
||||
@@ -91,7 +100,7 @@ func TestSaveMonEndpoints(t *testing.T) {
|
||||
clientset := test.New(1)
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}, ConfigDir: configDir}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset, ConfigDir: configDir}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(1)
|
||||
|
||||
// create the initial config map
|
||||
@@ -122,16 +131,16 @@ func TestCheckHealth(t *testing.T) {
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
context := &clusterd.Context{
|
||||
KubeContext: kit.KubeContext{Clientset: clientset, RetryDelay: 1, MaxRetries: 1},
|
||||
ConfigDir: configDir,
|
||||
Executor: executor,
|
||||
Clientset: clientset,
|
||||
ConfigDir: configDir,
|
||||
Executor: executor,
|
||||
}
|
||||
c := New(context, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(1)
|
||||
c.waitForStart = false
|
||||
defer os.RemoveAll(c.context.ConfigDir)
|
||||
|
||||
err := c.CheckHealth()
|
||||
err := c.checkHealth()
|
||||
assert.Nil(t, err)
|
||||
|
||||
c.maxMonID = 10
|
||||
@@ -183,7 +192,7 @@ func TestMonID(t *testing.T) {
|
||||
|
||||
func TestAvailableMonNodes(t *testing.T) {
|
||||
clientset := test.New(1)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(0)
|
||||
nodes, err := c.getAvailableMonNodes()
|
||||
assert.Nil(t, err)
|
||||
@@ -200,7 +209,7 @@ func TestAvailableMonNodes(t *testing.T) {
|
||||
|
||||
func TestAvailableNodesInUse(t *testing.T) {
|
||||
clientset := test.New(3)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(0)
|
||||
|
||||
// all three nodes are available by default
|
||||
@@ -231,7 +240,7 @@ func TestAvailableNodesInUse(t *testing.T) {
|
||||
|
||||
func TestTaintedNodes(t *testing.T) {
|
||||
clientset := test.New(3)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(0)
|
||||
|
||||
nodes, err := c.getAvailableMonNodes()
|
||||
@@ -264,7 +273,7 @@ func TestTaintedNodes(t *testing.T) {
|
||||
|
||||
func TestNodeAffinity(t *testing.T) {
|
||||
clientset := test.New(3)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "", "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = test.CreateClusterInfo(0)
|
||||
|
||||
nodes, err := c.getAvailableMonNodes()
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -35,7 +34,7 @@ func TestPodSpecs(t *testing.T) {
|
||||
|
||||
func testPodSpec(t *testing.T, dataDir string) {
|
||||
clientset := testop.New(1)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", dataDir, "myversion", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", dataDir, "myversion", k8sutil.Placement{})
|
||||
c.clusterInfo = testop.CreateClusterInfo(0)
|
||||
config := &monConfig{Name: "mon0", Port: 6790}
|
||||
|
||||
|
||||
+40
-31
@@ -22,15 +22,19 @@ package operator
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/kubernetes-incubator/external-storage/lib/controller"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/cluster"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"github.com/rook/rook/pkg/operator/pool"
|
||||
"github.com/rook/rook/pkg/operator/provisioner"
|
||||
"k8s.io/api/core/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -50,31 +54,23 @@ type Operator struct {
|
||||
resources []kit.CustomResource
|
||||
// The custom resource that is global to the kubernetes cluster.
|
||||
// The cluster is global because you create multiple clusers in k8s
|
||||
clusterMgr *clusterManager
|
||||
clusterController *cluster.ClusterController
|
||||
volumeProvisioner controller.Provisioner
|
||||
}
|
||||
|
||||
type inclusterInitiator interface {
|
||||
Create(clusterMgr *clusterManager, namespace string) (resourceManager, error)
|
||||
Resource() kit.CustomResource
|
||||
}
|
||||
|
||||
type resourceManager interface {
|
||||
Load() (string, error)
|
||||
Manage()
|
||||
}
|
||||
|
||||
// New creates an operator instance
|
||||
func New(context *clusterd.Context) *Operator {
|
||||
clusterController, err := cluster.NewClusterController(context)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to create Operator. %+v.", err)
|
||||
return nil
|
||||
}
|
||||
volumeProvisioner := provisioner.New(context.Clientset)
|
||||
|
||||
poolInitiator := newPoolInitiator(context)
|
||||
clusterMgr := newClusterManager(context, []inclusterInitiator{poolInitiator})
|
||||
volumeProvisioner := newRookVolumeProvisioner(clusterMgr)
|
||||
|
||||
schemes := []kit.CustomResource{cluster.ClusterResource, cluster.PoolResource}
|
||||
schemes := []kit.CustomResource{cluster.ClusterResource, pool.PoolResource}
|
||||
return &Operator{
|
||||
context: context,
|
||||
clusterMgr: clusterMgr,
|
||||
clusterController: clusterController,
|
||||
resources: schemes,
|
||||
volumeProvisioner: volumeProvisioner,
|
||||
}
|
||||
@@ -92,6 +88,10 @@ func (o *Operator) Run() error {
|
||||
<-time.After(initRetryDelay)
|
||||
}
|
||||
|
||||
signalChan := make(chan os.Signal, 1)
|
||||
stopChan := make(chan struct{})
|
||||
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
// Run volume provisioner
|
||||
// The controller needs to know what the server version is because out-of-tree
|
||||
// provisioners aren't officially supported until 1.5
|
||||
@@ -105,24 +105,33 @@ func (o *Operator) Run() error {
|
||||
o.volumeProvisioner,
|
||||
serverVersion.GitVersion,
|
||||
)
|
||||
go pc.Run(wait.NeverStop)
|
||||
go pc.Run(stopChan)
|
||||
|
||||
// watch for changes to the rook clusters
|
||||
o.clusterMgr.Manage()
|
||||
return nil
|
||||
o.clusterController.StartWatch(v1.NamespaceAll, stopChan)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-signalChan:
|
||||
logger.Infof("shutdown signal received, exiting...")
|
||||
close(stopChan)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Operator) initResources() error {
|
||||
httpCli, err := kit.NewHTTPClient(k8sutil.CustomResourceGroup)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tpr client. %+v", err)
|
||||
}
|
||||
o.context.KubeHTTPCli = httpCli.Client
|
||||
|
||||
err = kit.CreateCustomResources(o.context.KubeContext, o.resources)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create TPR. %+v", err)
|
||||
kitCtx := kit.Context{
|
||||
Clientset: o.context.Clientset,
|
||||
APIExtensionClientset: o.context.APIExtensionClientset,
|
||||
Interval: 500 * time.Millisecond,
|
||||
Timeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Create and wait for CRD resources
|
||||
err := kit.CreateCustomResources(kitCtx, o.resources)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create custom resource. %+v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,35 +16,30 @@ limitations under the License.
|
||||
package operator
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"github.com/rook/rook/pkg/operator/cluster"
|
||||
"github.com/rook/rook/pkg/operator/pool"
|
||||
"github.com/rook/rook/pkg/operator/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func TestCreateCluster(t *testing.T) {
|
||||
func TestOperator(t *testing.T) {
|
||||
clientset := test.New(3)
|
||||
context := &clusterd.Context{KubeContext: kit.KubeContext{MasterHost: "foo", Clientset: clientset}}
|
||||
context := &clusterd.Context{Clientset: clientset}
|
||||
o := New(context)
|
||||
o.context.RetryDelay = 1
|
||||
|
||||
// fail to init k8s client since we're not actually inside k8s
|
||||
err := o.initResources()
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// create the tpr
|
||||
scheme := kit.CustomResource{Name: "test", Version: "alpha", Group: k8sutil.CustomResourceGroup, Description: "test description"}
|
||||
err = kit.CreateCustomResource(o.context.KubeContext, scheme)
|
||||
assert.Nil(t, err)
|
||||
tpr, err := clientset.ExtensionsV1beta1().ThirdPartyResources().List(v1.ListOptions{})
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 1, len(tpr.Items))
|
||||
assert.Equal(t, "test.rook.io", tpr.Items[0].Name)
|
||||
assert.Equal(t, scheme.Description, tpr.Items[0].Description)
|
||||
|
||||
// TODO: Watch for a new Rook cluster and create it. Need a mocked http client to be working
|
||||
assert.NotNil(t, o)
|
||||
assert.NotNil(t, o.clusterController)
|
||||
assert.NotNil(t, o.resources)
|
||||
assert.NotNil(t, o.volumeProvisioner)
|
||||
assert.Equal(t, context, o.context)
|
||||
assert.Equal(t, len(o.resources), 2)
|
||||
for _, r := range o.resources {
|
||||
if r.Name != cluster.ClusterResource.Name && r.Name != pool.PoolResource.Name {
|
||||
assert.Fail(t, fmt.Sprintf("Resource is %s not valid", r.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
cephosd "github.com/rook/rook/pkg/ceph/osd"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"k8s.io/api/core/v1"
|
||||
"k8s.io/client-go/kubernetes/fake"
|
||||
@@ -31,7 +30,7 @@ import (
|
||||
|
||||
func TestStartDaemonset(t *testing.T) {
|
||||
clientset := fake.NewSimpleClientset()
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", StorageSpec{}, "", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", StorageSpec{}, "", k8sutil.Placement{})
|
||||
|
||||
// Start the first time
|
||||
err := c.Start()
|
||||
@@ -67,7 +66,7 @@ func testPodDevices(t *testing.T, dataDir, deviceFilter string, allDevices bool)
|
||||
}
|
||||
|
||||
clientset := fake.NewSimpleClientset()
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", storageSpec, dataDir, k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", storageSpec, dataDir, k8sutil.Placement{})
|
||||
|
||||
n := c.Storage.resolveNode(storageSpec.Nodes[0].Name)
|
||||
replicaSet := c.makeReplicaSet(n.Name, n.Devices, n.Directories, n.Selection, n.Config)
|
||||
@@ -140,7 +139,7 @@ func TestStorageSpecDevicesAndDirectories(t *testing.T) {
|
||||
}
|
||||
|
||||
clientset := fake.NewSimpleClientset()
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", storageSpec, "", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", storageSpec, "", k8sutil.Placement{})
|
||||
|
||||
n := c.Storage.resolveNode(storageSpec.Nodes[0].Name)
|
||||
replicaSet := c.makeReplicaSet(n.Name, n.Devices, n.Directories, n.Selection, n.Config)
|
||||
@@ -182,7 +181,7 @@ func TestStorageSpecConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
clientset := fake.NewSimpleClientset()
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}}, "ns", "myversion", storageSpec, "", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset}, "ns", "myversion", storageSpec, "", k8sutil.Placement{})
|
||||
|
||||
n := c.Storage.resolveNode(storageSpec.Nodes[0].Name)
|
||||
replicaSet := c.makeReplicaSet(n.Name, n.Devices, n.Directories, n.Selection, n.Config)
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package operator to manage Kubernetes storage.
|
||||
package operator
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/cluster"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
kwatch "k8s.io/apimachinery/pkg/watch"
|
||||
)
|
||||
|
||||
type poolInitiator struct {
|
||||
context *clusterd.Context
|
||||
}
|
||||
|
||||
type poolManager struct {
|
||||
namespace string
|
||||
watchVersion string
|
||||
context *clusterd.Context
|
||||
rclient rookclient.RookRestClient
|
||||
}
|
||||
|
||||
type poolEvent struct {
|
||||
Type kwatch.EventType
|
||||
Object *cluster.Pool
|
||||
}
|
||||
|
||||
func newPoolInitiator(context *clusterd.Context) *poolInitiator {
|
||||
return &poolInitiator{context: context}
|
||||
}
|
||||
|
||||
func (p *poolInitiator) Create(clusterMgr *clusterManager, namespace string) (resourceManager, error) {
|
||||
rclient, err := clusterMgr.getRookClient(namespace)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get api client for pool tpr for cluster in namespace %s. %+v", namespace, err)
|
||||
}
|
||||
return &poolManager{context: p.context, namespace: namespace, rclient: rclient}, nil
|
||||
}
|
||||
|
||||
func (p *poolInitiator) Resource() kit.CustomResource {
|
||||
return cluster.PoolResource
|
||||
}
|
||||
|
||||
// Run the tpr manager until the caller signals with an EndWatch()
|
||||
func (p *poolManager) Manage() {
|
||||
for {
|
||||
|
||||
// load and initialize the pools
|
||||
watchVersion, err := p.Load()
|
||||
if err != nil {
|
||||
logger.Errorf("cannot load %s pool tpr. %+v. retrying...", p.namespace, err)
|
||||
} else {
|
||||
// watch for added/updated/deleted pools
|
||||
watcher := kit.NewWatcher(p.context.KubeContext, cluster.PoolResource, p.namespace, watchVersion, p.handlePoolEvent, nil)
|
||||
if err := watcher.Watch(); err != nil {
|
||||
logger.Errorf("failed to watch %s pool tpr. %+v. retrying...", p.namespace, err)
|
||||
}
|
||||
}
|
||||
|
||||
<-time.After(time.Second * time.Duration(p.context.RetryDelay))
|
||||
}
|
||||
}
|
||||
|
||||
func (p *poolManager) handlePoolEvent(event *kit.RawEvent) error {
|
||||
pool := &poolEvent{
|
||||
Type: event.Type,
|
||||
Object: &cluster.Pool{},
|
||||
}
|
||||
err := json.Unmarshal(event.Object, pool.Object)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fail to unmarshal Pool from data (%s): %v", pool.Object, err)
|
||||
}
|
||||
|
||||
switch event.Type {
|
||||
case kwatch.Added:
|
||||
if err := pool.Object.Create(p.rclient); err != nil {
|
||||
logger.Errorf("failed to create pool %s. %+v", pool.Object.Name, err)
|
||||
break
|
||||
}
|
||||
|
||||
case kwatch.Modified:
|
||||
// if the pool is modified, allow the pool to be created if it wasn't already
|
||||
if err := pool.Object.Create(p.rclient); err != nil {
|
||||
logger.Errorf("failed to create (modify) pool %s. %+v", pool.Object.Name, err)
|
||||
break
|
||||
}
|
||||
|
||||
case kwatch.Deleted:
|
||||
err := pool.Object.Delete(p.rclient)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to delete pool %s. %+v", pool.Object.Name, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *poolManager) Load() (string, error) {
|
||||
// Check if pools have all been created
|
||||
logger.Info("finding existing pools...")
|
||||
poolList, err := p.getPoolList()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
logger.Infof("found %d pools. ensuring they exist.", len(poolList.Items))
|
||||
for i := range poolList.Items {
|
||||
// ensure the pool exists
|
||||
item := poolList.Items[i]
|
||||
logger.Infof("checking pool %s in namespace %s", item.Name, item.Namespace)
|
||||
if err := item.Create(p.rclient); err != nil {
|
||||
logger.Warningf("failed to check that pool %s exists in namespace %s. %+v", item.Name, item.Namespace, err)
|
||||
}
|
||||
}
|
||||
|
||||
return poolList.Metadata.ResourceVersion, nil
|
||||
}
|
||||
|
||||
func (p *poolManager) getPoolList() (*cluster.PoolList, error) {
|
||||
b, err := kit.GetRawListNamespaced(p.context.Clientset, cluster.PoolResource, p.namespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pools := &cluster.PoolList{}
|
||||
if err := json.Unmarshal(b, pools); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pools, nil
|
||||
}
|
||||
@@ -17,46 +17,110 @@ Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package cluster to manage a rook cluster.
|
||||
package cluster
|
||||
// Package pool to manage a rook pool.
|
||||
package pool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"github.com/rook/rook/pkg/operator/api"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
"k8s.io/api/core/v1"
|
||||
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
const (
|
||||
replicatedType = "replicated"
|
||||
erasureCodeType = "erasure-coded"
|
||||
customResourceName = "pool"
|
||||
customResourceNamePlural = "pools"
|
||||
replicatedType = "replicated"
|
||||
erasureCodeType = "erasure-coded"
|
||||
)
|
||||
|
||||
// PoolResource is the definition of the pool CRD
|
||||
var PoolResource = kit.CustomResource{
|
||||
Name: "pool",
|
||||
Group: k8sutil.CustomResourceGroup,
|
||||
Version: kit.V1Alpha1,
|
||||
Description: "Managed Rook pools",
|
||||
var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-pool")
|
||||
|
||||
// PoolController represents a controller object for pool custom resources
|
||||
type PoolController struct {
|
||||
clientset kubernetes.Interface
|
||||
rookClient rookclient.RookRestClient
|
||||
scheme *runtime.Scheme
|
||||
}
|
||||
|
||||
// Pool is the spec for the CRD
|
||||
type Pool struct {
|
||||
v1.ObjectMeta `json:"metadata,omitempty"`
|
||||
PoolSpec `json:"spec"`
|
||||
// NewPoolController create controller for watching pool custom resources created
|
||||
func NewPoolController(clientset kubernetes.Interface) (*PoolController, error) {
|
||||
return &PoolController{
|
||||
clientset: clientset,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// NewPool creates a new pool
|
||||
func NewPool(spec PoolSpec) *Pool {
|
||||
return &Pool{PoolSpec: spec}
|
||||
// Watch watches for instances of Pool custom resources and acts on them
|
||||
func (c *PoolController) StartWatch(namespace string, stopCh chan struct{}) error {
|
||||
client, scheme, err := kit.NewHTTPClient(k8sutil.CustomResourceGroup, k8sutil.V1Alpha1, schemeBuilder)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get a k8s client for watching pool resources: %v", err)
|
||||
}
|
||||
c.scheme = scheme
|
||||
|
||||
rclient, err := api.GetRookClient(namespace, c.clientset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to get rook client: %v", err)
|
||||
}
|
||||
c.rookClient = rclient
|
||||
|
||||
resourceHandlerFuncs := cache.ResourceEventHandlerFuncs{
|
||||
AddFunc: c.onAdd,
|
||||
UpdateFunc: c.onUpdate,
|
||||
DeleteFunc: c.onDelete,
|
||||
}
|
||||
watcher := kit.NewWatcher(PoolResource, namespace, resourceHandlerFuncs, client)
|
||||
go watcher.Watch(&Pool{}, stopCh)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create a pool
|
||||
func (p *Pool) Create(rclient rookclient.RookRestClient) error {
|
||||
func (c *PoolController) onAdd(obj interface{}) {
|
||||
pool := obj.(*Pool)
|
||||
|
||||
// NEVER modify objects from the store. It's a read-only, local cache.
|
||||
// Use scheme.Copy() to make a deep copy of original object.
|
||||
copyObj, err := c.scheme.Copy(pool)
|
||||
if err != nil {
|
||||
fmt.Printf("ERROR creating a deep copy of pool object: %v\n", err)
|
||||
return
|
||||
}
|
||||
poolCopy := copyObj.(*Pool)
|
||||
|
||||
err = poolCopy.create(c.rookClient)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to create pool %s. %+v", pool.ObjectMeta.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *PoolController) onUpdate(oldObj, newObj interface{}) {
|
||||
//oldPool := oldObj.(*Pool)
|
||||
newPool := newObj.(*Pool)
|
||||
|
||||
// if the pool is modified, allow the pool to be created if it wasn't already
|
||||
err := newPool.create(c.rookClient)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to create (modify) pool %s. %+v", newPool.ObjectMeta.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *PoolController) onDelete(obj interface{}) {
|
||||
pool := obj.(*Pool)
|
||||
err := pool.delete(c.rookClient)
|
||||
if err != nil {
|
||||
logger.Errorf("failed to delete pool %s. %+v", pool.ObjectMeta.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create the pool
|
||||
func (p *Pool) create(rclient rookclient.RookRestClient) error {
|
||||
// validate the pool settings
|
||||
if err := p.validate(); err != nil {
|
||||
return fmt.Errorf("invalid pool %s arguments. %+v", p.Name, err)
|
||||
@@ -95,7 +159,7 @@ func (p *Pool) Create(rclient rookclient.RookRestClient) error {
|
||||
}
|
||||
|
||||
// Delete the pool
|
||||
func (p *Pool) Delete(rclient rookclient.RookRestClient) error {
|
||||
func (p *Pool) delete(rclient rookclient.RookRestClient) error {
|
||||
// check if the pool exists
|
||||
exists, err := p.exists(rclient)
|
||||
if err == nil && !exists {
|
||||
@@ -139,14 +203,14 @@ func (p *Pool) validate() error {
|
||||
}
|
||||
|
||||
func (p *Pool) replication() *ReplicationSpec {
|
||||
if p.PoolSpec.Replication.Size > 0 {
|
||||
return &p.PoolSpec.Replication
|
||||
if p.Spec.Replication.Size > 0 {
|
||||
return &p.Spec.Replication
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pool) erasureCode() *ErasureCodeSpec {
|
||||
ec := &p.PoolSpec.ErasureCoding
|
||||
ec := &p.Spec.ErasureCoding
|
||||
if ec.CodingChunks > 0 || ec.DataChunks > 0 {
|
||||
return ec
|
||||
}
|
||||
@@ -16,75 +16,74 @@ limitations under the License.
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
package cluster
|
||||
package pool
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"github.com/rook/rook/pkg/rook/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func TestValidatePool(t *testing.T) {
|
||||
// must specify some replication or EC settings
|
||||
p := Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p := Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
err := p.validate()
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// must specify name
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Namespace: "myns"}}
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Namespace: "myns"}}
|
||||
err = p.validate()
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// must specify namespace
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool"}}
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool"}}
|
||||
err = p.validate()
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// must not specify both replication and EC settings
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Replication.Size = 1
|
||||
p.ErasureCoding.CodingChunks = 2
|
||||
p.ErasureCoding.DataChunks = 3
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Spec.Replication.Size = 1
|
||||
p.Spec.ErasureCoding.CodingChunks = 2
|
||||
p.Spec.ErasureCoding.DataChunks = 3
|
||||
err = p.validate()
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// succeed with replication settings
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Replication.Size = 1
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Spec.Replication.Size = 1
|
||||
err = p.validate()
|
||||
assert.Nil(t, err)
|
||||
|
||||
// succeed with ec settings
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.ErasureCoding.CodingChunks = 1
|
||||
p.ErasureCoding.DataChunks = 2
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Spec.ErasureCoding.CodingChunks = 1
|
||||
p.Spec.ErasureCoding.DataChunks = 2
|
||||
err = p.validate()
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
|
||||
func TestCreatePool(t *testing.T) {
|
||||
rclient := &test.MockRookRestClient{}
|
||||
p := Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Replication.Size = 1
|
||||
p := Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p.Spec.Replication.Size = 1
|
||||
|
||||
exists, err := p.exists(rclient)
|
||||
assert.False(t, exists)
|
||||
err = p.Create(rclient)
|
||||
err = p.create(rclient)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// fail if both replication and EC are specified
|
||||
p.ErasureCoding.CodingChunks = 2
|
||||
p.ErasureCoding.DataChunks = 2
|
||||
err = p.Create(rclient)
|
||||
p.Spec.ErasureCoding.CodingChunks = 2
|
||||
p.Spec.ErasureCoding.DataChunks = 2
|
||||
err = p.create(rclient)
|
||||
assert.NotNil(t, err)
|
||||
|
||||
// succeed with EC
|
||||
p.Replication.Size = 0
|
||||
err = p.Create(rclient)
|
||||
p.Spec.Replication.Size = 0
|
||||
err = p.create(rclient)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -99,18 +98,18 @@ func TestDeletePool(t *testing.T) {
|
||||
}
|
||||
|
||||
// delete a pool that exists
|
||||
p := Pool{ObjectMeta: v1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
p := Pool{ObjectMeta: metav1.ObjectMeta{Name: "mypool", Namespace: "myns"}}
|
||||
exists, err := p.exists(rclient)
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, exists)
|
||||
err = p.Delete(rclient)
|
||||
err = p.delete(rclient)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// succeed even if the pool doesn't exist
|
||||
p = Pool{ObjectMeta: v1.ObjectMeta{Name: "otherpool", Namespace: "myns"}}
|
||||
p = Pool{ObjectMeta: metav1.ObjectMeta{Name: "otherpool", Namespace: "myns"}}
|
||||
exists, err = p.exists(rclient)
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, exists)
|
||||
err = p.Delete(rclient)
|
||||
err = p.delete(rclient)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
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 pool to manage a rook pool.
|
||||
package pool
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
|
||||
addToScheme = schemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
// PoolResource represents the Pool custom resource object
|
||||
var PoolResource = kit.CustomResource{
|
||||
Name: customResourceName,
|
||||
Plural: customResourceNamePlural,
|
||||
Group: k8sutil.CustomResourceGroup,
|
||||
Version: k8sutil.V1Alpha1,
|
||||
Scope: apiextensionsv1beta1.NamespaceScoped,
|
||||
Kind: reflect.TypeOf(Pool{}).Name(),
|
||||
}
|
||||
|
||||
// Kind takes an unqualified kind and returns back a Group qualified GroupKind
|
||||
func Kind(kind string) schema.GroupKind {
|
||||
return schemeGroupVersion.WithKind(kind).GroupKind()
|
||||
}
|
||||
|
||||
// Resource takes an unqualified resource and returns back a Group qualified GroupResource
|
||||
func Resource(resource string) schema.GroupResource {
|
||||
return schemeGroupVersion.WithResource(resource).GroupResource()
|
||||
}
|
||||
|
||||
// Adds the list of known types to api.Scheme.
|
||||
func addKnownTypes(scheme *runtime.Scheme) error {
|
||||
scheme.AddKnownTypes(schemeGroupVersion,
|
||||
&Pool{},
|
||||
&PoolList{},
|
||||
)
|
||||
metav1.AddToGroupVersion(scheme, schemeGroupVersion)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Copyright 2017 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package pool to manage a rook pool.
|
||||
package pool
|
||||
|
||||
import (
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
// schemeGroupVersion is group version used to register these objects
|
||||
var schemeGroupVersion = schema.GroupVersion{Group: k8sutil.CustomResourceGroup, Version: k8sutil.V1Alpha1}
|
||||
|
||||
// Pool is the definition of the pool custom resource
|
||||
type Pool struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ObjectMeta `json:"metadata"`
|
||||
Spec PoolSpec `json:"spec"`
|
||||
}
|
||||
|
||||
// PoolList is the definition of a list of pools
|
||||
type PoolList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ListMeta `json:"metadata"`
|
||||
Items []Pool `json:"items"`
|
||||
}
|
||||
|
||||
// PoolSpec represent the spec of a pool
|
||||
type PoolSpec struct {
|
||||
// The replication settings
|
||||
Replication ReplicationSpec `json:"replication"`
|
||||
|
||||
// The erasure code setteings
|
||||
ErasureCoding ErasureCodeSpec `json:"erasureCode"`
|
||||
}
|
||||
|
||||
// ReplicationSpec represents the spec for replication in a pool
|
||||
type ReplicationSpec struct {
|
||||
// Number of copies per object in a replicated storage pool, including the object itself (required for replicated pool type)
|
||||
Size uint `json:"size"`
|
||||
}
|
||||
|
||||
// ErasureCodeSpec represents the spec for erasure code in a pool
|
||||
type ErasureCodeSpec struct {
|
||||
// Number of coding chunks per object in an erasure coded storage pool (required for erasure-coded pool type)
|
||||
CodingChunks uint `json:"codingChunks"`
|
||||
|
||||
// Number of data chunks per object in an erasure coded storage pool (required for erasure-coded pool type)
|
||||
DataChunks uint `json:"dataChunks"`
|
||||
}
|
||||
@@ -14,20 +14,23 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package operator to manage Kubernetes storage.
|
||||
package operator
|
||||
// Package provisioner to provision Rook volumes on Kubernetes.
|
||||
package provisioner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/kubernetes-incubator/external-storage/lib/controller"
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"github.com/rook/rook/pkg/operator/api"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
rookclient "github.com/rook/rook/pkg/rook/client"
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/uuid"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -36,8 +39,11 @@ const (
|
||||
rbdIDPrefix = "rbd_id."
|
||||
)
|
||||
|
||||
type rookVolumeProvisioner struct {
|
||||
clusterManager *clusterManager
|
||||
var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-provisioner")
|
||||
|
||||
// RookVolumeProvisioner is used to provision Rook volumes on Kubernetes
|
||||
type RookVolumeProvisioner struct {
|
||||
client kubernetes.Interface
|
||||
|
||||
// Configuration of rook volume provisioner
|
||||
provConfig provisionerConfig
|
||||
@@ -54,14 +60,15 @@ type provisionerConfig struct {
|
||||
clusterName string
|
||||
}
|
||||
|
||||
func newRookVolumeProvisioner(clusterManager *clusterManager) controller.Provisioner {
|
||||
return &rookVolumeProvisioner{
|
||||
clusterManager: clusterManager,
|
||||
// New creates RookVolumeProvisioner
|
||||
func New(client kubernetes.Interface) controller.Provisioner {
|
||||
return &RookVolumeProvisioner{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// Provision creates a storage asset and returns a PV object representing it.
|
||||
func (p *rookVolumeProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
|
||||
func (p *RookVolumeProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
|
||||
|
||||
var err error
|
||||
if options.PVC.Spec.Selector != nil {
|
||||
@@ -83,7 +90,7 @@ func (p *rookVolumeProvisioner) Provision(options controller.VolumeOptions) (*v1
|
||||
|
||||
imageName := createImageName(options.PVName)
|
||||
|
||||
rookClient, err := p.clusterManager.getRookClient(p.provConfig.clusterNamespace)
|
||||
rookClient, err := api.GetRookClient(p.provConfig.clusterNamespace, p.client)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to get rook client: %v", err)
|
||||
}
|
||||
@@ -148,8 +155,8 @@ func createVolume(image, pool string, size int64, client rookclient.RookRestClie
|
||||
|
||||
// Delete removes the storage asset that was created by Provision represented
|
||||
// by the given PV.
|
||||
func (p *rookVolumeProvisioner) Delete(volume *v1.PersistentVolume) error {
|
||||
rookClient, err := p.clusterManager.getRookClient(p.provConfig.clusterNamespace)
|
||||
func (p *RookVolumeProvisioner) Delete(volume *v1.PersistentVolume) error {
|
||||
rookClient, err := api.GetRookClient(p.provConfig.clusterNamespace, p.client)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to get rook client: %v", err)
|
||||
}
|
||||
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
*/
|
||||
package operator
|
||||
package provisioner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
cephrgw "github.com/rook/rook/pkg/ceph/rgw"
|
||||
"github.com/rook/rook/pkg/clusterd"
|
||||
"github.com/rook/rook/pkg/operator/k8sutil"
|
||||
"github.com/rook/rook/pkg/operator/kit"
|
||||
testop "github.com/rook/rook/pkg/operator/test"
|
||||
exectest "github.com/rook/rook/pkg/util/exec/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -43,7 +42,7 @@ func TestStartRGW(t *testing.T) {
|
||||
|
||||
configDir, _ := ioutil.TempDir("", "")
|
||||
defer os.RemoveAll(configDir)
|
||||
c := New(&clusterd.Context{KubeContext: kit.KubeContext{Clientset: clientset}, Executor: executor, ConfigDir: configDir}, "ns", "version", k8sutil.Placement{})
|
||||
c := New(&clusterd.Context{Clientset: clientset, Executor: executor, ConfigDir: configDir}, "ns", "version", k8sutil.Placement{})
|
||||
|
||||
// start a basic cluster
|
||||
err := c.Start()
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 The Rook 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.
|
||||
|
||||
Some of the code below came from https://github.com/coreos/etcd-operator
|
||||
which also has the apache 2.0 license.
|
||||
*/
|
||||
|
||||
// Package operator to manage Kubernetes storage.
|
||||
package operator
|
||||
|
||||
import "sync"
|
||||
|
||||
type tprTracker struct {
|
||||
stopChMap map[string]chan struct{}
|
||||
clusterRVs map[string]string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func newTPRTracker() *tprTracker {
|
||||
return &tprTracker{
|
||||
clusterRVs: make(map[string]string),
|
||||
stopChMap: map[string]chan struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tprTracker) add(name, version string) {
|
||||
t.clusterRVs[name] = version
|
||||
if _, ok := t.stopChMap[name]; !ok {
|
||||
t.stopChMap[name] = make(chan struct{})
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tprTracker) remove(name string) {
|
||||
delete(t.clusterRVs, name)
|
||||
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
if stopCh, ok := t.stopChMap[name]; ok {
|
||||
close(stopCh)
|
||||
}
|
||||
delete(t.stopChMap, name)
|
||||
}
|
||||
|
||||
func (t *tprTracker) stop() {
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
for _, stop := range t.stopChMap {
|
||||
close(stop)
|
||||
}
|
||||
t.stopChMap = map[string]chan struct{}{}
|
||||
}
|
||||
@@ -89,6 +89,16 @@ rules:
|
||||
- watch
|
||||
- create
|
||||
- delete
|
||||
- apiGroups:
|
||||
- apiextensions.k8s.io
|
||||
resources:
|
||||
- customresourcedefinitions
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- create
|
||||
- delete
|
||||
- apiGroups:
|
||||
- rbac.authorization.k8s.io
|
||||
resources:
|
||||
@@ -161,7 +171,12 @@ spec:
|
||||
}
|
||||
|
||||
func (i *InstallData) getRookCluster() string {
|
||||
return `apiVersion: rook.io/v1alpha1
|
||||
return `apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: rook
|
||||
---
|
||||
apiVersion: rook.io/v1alpha1
|
||||
kind: Cluster
|
||||
metadata:
|
||||
name: rook
|
||||
|
||||
@@ -27,10 +27,12 @@ import (
|
||||
"github.com/coreos/pkg/capnslog"
|
||||
"github.com/rook/rook/tests/framework/objects"
|
||||
"github.com/rook/rook/tests/framework/utils"
|
||||
utilversion "k8s.io/kubernetes/pkg/util/version"
|
||||
)
|
||||
|
||||
const (
|
||||
rookOperatorCreatedTpr = "cluster.rook.io"
|
||||
rookOperatorCreatedCrd = "clusters.rook.io"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -57,10 +59,18 @@ func (h *InstallHelper) createK8sRookOperator(k8sHelper *utils.K8sHelper, k8sver
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create rook-operator pod : %v ", err)
|
||||
}
|
||||
kubeVersion := utilversion.MustParseSemantic(k8sversion)
|
||||
|
||||
if !k8sHelper.IsThirdPartyResourcePresent(rookOperatorCreatedTpr) {
|
||||
return fmt.Errorf("Failed to start Rook Operator; k8s thirdpartyresource did not appear")
|
||||
if kubeVersion.AtLeast(utilversion.MustParseSemantic("v1.7.0")) {
|
||||
if !k8sHelper.IsCRDPresent(rookOperatorCreatedCrd) {
|
||||
return fmt.Errorf("Failed to start Rook Operator; k8s CustomResourceDefinition did not appear")
|
||||
}
|
||||
} else {
|
||||
if !k8sHelper.IsThirdPartyResourcePresent(rookOperatorCreatedTpr) {
|
||||
return fmt.Errorf("Failed to start Rook Operator; k8s thirdpartyresource did not appear")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof("Rook Operator started")
|
||||
|
||||
return nil
|
||||
@@ -155,14 +165,19 @@ func (h *InstallHelper) UninstallRookFromK8s() {
|
||||
if skipRookInstall {
|
||||
return
|
||||
}
|
||||
k8sversion := h.k8shelper.GetK8sServerVersion()
|
||||
k8sVersion := h.k8shelper.GetK8sServerVersion()
|
||||
serverVersion, err := h.k8shelper.Clientset.Discovery().ServerVersion()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
kubeVersion := utilversion.MustParseSemantic(serverVersion.GitVersion)
|
||||
|
||||
logger.Infof("Uninstalling Rook")
|
||||
k8sHelp, err := utils.CreatK8sHelper()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
rookOperator := h.installData.getRookOperator(k8sversion)
|
||||
rookOperator := h.installData.getRookOperator(k8sVersion)
|
||||
|
||||
_, err = h.k8shelper.KubectlWithStdin(rookOperator, deleteArgs...)
|
||||
if err != nil {
|
||||
@@ -176,7 +191,7 @@ func (h *InstallHelper) UninstallRookFromK8s() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if !strings.EqualFold(h.Env.K8sVersion, "v1.5") {
|
||||
if kubeVersion.AtLeast(utilversion.MustParseSemantic("v1.6.0")) {
|
||||
_, err = k8sHelp.DeleteResource([]string{"clusterrole", "rook-api"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -186,9 +201,17 @@ func (h *InstallHelper) UninstallRookFromK8s() {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
_, err = k8sHelp.DeleteResource([]string{"thirdpartyresources", "cluster.rook.io", "pool.rook.io"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
if kubeVersion.AtLeast(utilversion.MustParseSemantic("v1.7.0")) {
|
||||
_, err = k8sHelp.DeleteResource([]string{"crd", "clusters.rook.io", "pools.rook.io"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
_, err = k8sHelp.DeleteResource([]string{"thirdpartyresources", "cluster.rook.io", "pool.rook.io"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
_, err = k8sHelp.DeleteResource([]string{"secret", "rook-rook-user"})
|
||||
if err != nil {
|
||||
|
||||
@@ -409,7 +409,7 @@ func (k8sh *K8sHelper) GetService(servicename string) (string, error) {
|
||||
func (k8sh *K8sHelper) IsThirdPartyResourcePresent(tprname string) bool {
|
||||
args := []string{"get", "thirdpartyresources", tprname}
|
||||
inc := 0
|
||||
for inc < 20 {
|
||||
for inc < RetryLoop {
|
||||
_, err := k8sh.Kubectl(args...)
|
||||
if err == nil {
|
||||
k8slogger.Infof("Found the thirdparty resource: " + tprname)
|
||||
@@ -422,6 +422,24 @@ func (k8sh *K8sHelper) IsThirdPartyResourcePresent(tprname string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
//IsCRDPresent returns true if custom resource definition is present
|
||||
func (k8sh *K8sHelper) IsCRDPresent(crdName string) bool {
|
||||
|
||||
cmdArgs := []string{"get", "crd", crdName}
|
||||
inc := 0
|
||||
for inc < RetryLoop {
|
||||
_, err := k8sh.Kubectl(cmdArgs...)
|
||||
if err == nil {
|
||||
k8slogger.Infof("Found the CRD resource: " + crdName)
|
||||
return true
|
||||
}
|
||||
time.Sleep(RetryInterval * time.Second)
|
||||
inc++
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
//GetPodDetails returns details about a pod
|
||||
func (k8sh *K8sHelper) GetPodDetails(podNamePattern string, namespace string) (string, error) {
|
||||
args := []string{"get", "pods", "-l", "app=" + podNamePattern, "-o", "wide", "--no-headers=true", "-o", "name"}
|
||||
|
||||
@@ -20,10 +20,11 @@ import (
|
||||
"errors"
|
||||
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rook/rook/pkg/model"
|
||||
"github.com/rook/rook/tests/framework/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
Reference in new issue
Block a user