diff --git a/Makefile b/Makefile index 88b6652..006744d 100644 --- a/Makefile +++ b/Makefile @@ -269,4 +269,49 @@ clean: $(CLEAN_TARGETS) ## Build the operator build: prebuild-check deps @echo "building $(BINARY_SERVER_BIN)..." + operator-sdk generate k8s go build -v -o $(BINARY_SERVER_BIN) cmd/manager/main.go + +# ------------------------------------------------------------------- +# deploy +# ------------------------------------------------------------------- + +APP_NAMESPACE ?= myproject +.PHONY: local +## Run Operator locally +local: deploy-rbac build deploy-crd + @-oc new-project $(APP_NAMESPACE) + operator-sdk up local --namespace=$(APP_NAMESPACE) + +.PHONY: deploy-rbac +## Setup service account and deploy RBAC +deploy-rbac: + @-oc login -u system:admin + @-oc create -f deploy/service_account.yaml + @-oc create -f deploy/role.yaml + @-oc create -f deploy/role_binding.yaml + +.PHONY: deploy-crd +## Deploy CRD +deploy-crd: + @-oc apply -f deploy/crds/devopsconsole_v1alpha1_component_crd.yaml + @-oc apply -f deploy/crds/devopsconsole_v1alpha1_envdeployment_crd.yaml + +.PHONY: deploy-operator +## Deploy Operator +deploy-operator: deploy-crd + oc create -f deploy/operator.yaml + +.PHONY: deploy-clean +## Deploy a CR as test +deploy-clean: + @-oc delete imagestream.image.openshift.io/myapp-runtime + @-oc delete imagestream.image.openshift.io/myapp-output + @-oc delete buildconfig.build.openshift.io/myapp-bc + @-oc delete deploymentconfig.apps.openshift.io/myapp + @-oc delete component.devopsconsole.openshift.io/myapp + +.PHONY: deploy-test +## Deploy a CR as test +deploy-test: + oc create -f examples/devopsconsole_v1alpha1_component_cr.yaml \ No newline at end of file diff --git a/README.md b/README.md index 4319bbb..281dab3 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,80 @@ -## Quick Start +# DevOpsConsole -Install the operator-sdk CLI: +This repository was initially bootstrapped using [CoreOS operator](https://github.com/operator-framework/operator-sdk). -```sh -$ mkdir -p $GOPATH/src/github.com/operator-framework -$ cd $GOPATH/src/github.com/operator-framework -$ git clone https://github.com/operator-framework/operator-sdk -$ cd operator-sdk -$ git checkout master -$ make dep -$ make install -``` +## Build -Add a new API for the custom resource AppService +### Pre-requisites +- [operator-sdk v0.5.0](https://github.com/operator-framework/operator-sdk#quick-start) +- [dep][dep_tool] version v0.5.0+. +- [git][git_tool] +- [go][go_tool] version v1.10+. +- [docker][docker_tool] version 17.03+. +- [kubectl][kubectl_tool] version v1.11.0+ or [oc] version 3.11 +- Access to a kubernetes v.1.11.0+ cluster or openshift cluster version 3.11 -```sh -$ operator-sdk add api --api-version=devopsconsole.openshift.io/v1alpha1 --kind=AppService +### Build ``` - -Add a new controller that watches for AppService - -```sh -$ operator-sdk add controller --api-version=devopsconsole.openshift.io/v1alpha1 --kind=AppService +make build ``` +## Deployment -Apply the app-operator CRD. - -```sh -$ kubectl apply -f deploy/crds/app_v1alpha1_appservice_crd.yaml +### Set up Minishift (one-off) +* create a new profile to test the operator +``` +minishift profile set devopsconsole +``` +* enable the admin-user add-on +``` +minishift addon enable admin-user +``` +* optionally, configure the VM +``` +minishift config set cpus 4 +minishift config set memory 8GB +minishift config set vm-driver virtualbox +``` +* start the instance +``` +minishift start ``` +> NOTE: this setup should be deprecated in favor of [OCP4 install](). -Set the OPERATOR_NAME variable +### Deploy the operator -```sh -$ export OPERATOR_NAME=app-operator +In dev mode, simply run your operator locally: +``` +make local ``` -Run the operator from outside the Minishift environment. - -```sh -$ operator-sdk up local --namespace myproject +### Deploy the CR for testing +* Make sure minishift is running and use myproject +``` +oc project myproject +``` +* Clean previously created resources +``` +make deploy-clean +``` +* Deploy CR ``` +make deploy-test +``` +* See the newly created resources +``` +oc get is,bc,svc,component.devopsconsole,build +NAME DOCKER REPO TAGS UPDATED +imagestream.image.openshift.io/myapp-output 172.30.1.1:5000/myproject/myapp-output +imagestream.image.openshift.io/myapp-runtime 172.30.1.1:5000/myproject/myapp-runtime latest 46 seconds ago -Your operator is now watching for the existence of an object that matches: GroupVersionKind(app.example.com/v1alpha1, Kind=App) +NAME TYPE FROM LATEST +buildconfig.build.openshift.io/myapp-bc Source Git@master 1 -Apply the provided CR.yaml to your cluster. This should trigger the default logic specified in the handler. +NAME AGE +component.devopsconsole.openshift.io/myapp 48s -```sh -$ kubectl create -f deploy/examples/app_v1alpha1_appservice_cr.yaml +NAME TYPE FROM STATUS STARTED DURATION +build.build.openshift.io/myapp-bc-1 Source Git@85ac14e Running 45 seconds ago ``` ## Directory layout @@ -63,3 +90,11 @@ Please consult [the documentation](https://github.com/operator-framework/operato | deploy | Contains various YAML manifests for registering CRDs, setting up [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/), and deploying the operator as a Deployment.| | Gopkg.toml Gopkg.lock | The [dep](https://github.com/golang/dep) manifests that describe the external dependencies of this operator.| | vendor | The golang [Vendor](https://golang.org/cmd/go/#hdr-Vendor_Directories) folder that contains the local copies of the external dependencies that satisfy the imports of this project. [dep](https://github.com/golang/dep) manages the vendor directly.| + + + +[dep_tool]:https://golang.github.io/dep/docs/installation.html +[git_tool]:https://git-scm.com/downloads +[go_tool]:https://golang.org/dl/ +[docker_tool]:https://docs.docker.com/install/ +[kubectl_tool]:https://kubernetes.io/docs/tasks/tools/install-kubectl/ \ No newline at end of file diff --git a/cmd/manager/main.go b/cmd/manager/main.go index f43d103..2b7ebc6 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -7,6 +7,9 @@ import ( "os" "runtime" + appsv1 "github.com/openshift/api/apps/v1" + buildv1 "github.com/openshift/api/build/v1" + imagev1 "github.com/openshift/api/image/v1" "github.com/operator-framework/operator-sdk/pkg/k8sutil" "github.com/operator-framework/operator-sdk/pkg/leader" "github.com/operator-framework/operator-sdk/pkg/ready" @@ -87,6 +90,18 @@ func main() { log.Error(err, "") os.Exit(1) } + if err := imagev1.AddToScheme(mgr.GetScheme()); err != nil { + log.Error(err, "") + os.Exit(1) + } + if err := buildv1.AddToScheme(mgr.GetScheme()); err != nil { + log.Error(err, "") + os.Exit(1) + } + if err := appsv1.AddToScheme(mgr.GetScheme()); err != nil { + log.Error(err, "") + os.Exit(1) + } // Setup all Controllers if err := controller.AddToManager(mgr); err != nil { diff --git a/deploy/crds/devopsconsole_v1alpha1_component_crd.yaml b/deploy/crds/devopsconsole_v1alpha1_component_crd.yaml new file mode 100644 index 0000000..65cea72 --- /dev/null +++ b/deploy/crds/devopsconsole_v1alpha1_component_crd.yaml @@ -0,0 +1,44 @@ +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition +metadata: + creationTimestamp: null + name: components.devopsconsole.openshift.io +spec: + group: devopsconsole.openshift.io + names: + kind: Component + listKind: ComponentList + plural: components + singular: component + scope: Namespaced + subresources: + status: {} + validation: + openAPIV3Schema: + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + properties: + buildType: + type: string + description: The type of the image that is required to build your component. + enum: + - nodejs + codebase: + type: string + required: + - buildType + - codebase + type: object + status: + type: object + version: v1alpha1 + versions: + - name: v1alpha1 + served: true + storage: true diff --git a/deploy/role.yaml b/deploy/role.yaml index a9431bd..2def1e7 100644 --- a/deploy/role.yaml +++ b/deploy/role.yaml @@ -36,5 +36,12 @@ rules: - devopsconsole.openshift.io resources: - '*' + - components + verbs: + - '*' +- apiGroups: + - components.devopsconsole.openshift.io + resources: + - '*' verbs: - '*' diff --git a/examples/devopsconsole_v1alpha1_component_cr.yaml b/examples/devopsconsole_v1alpha1_component_cr.yaml new file mode 100644 index 0000000..6249bc1 --- /dev/null +++ b/examples/devopsconsole_v1alpha1_component_cr.yaml @@ -0,0 +1,7 @@ +apiVersion: devopsconsole.openshift.io/v1alpha1 +kind: Component +metadata: + name: myapp +spec: + buildType: "nodejs" + codebase: "https://github.com/nodeshift-starters/nodejs-rest-http-crud" \ No newline at end of file diff --git a/pkg/apis/addtoscheme_components_v1alpha1.go b/pkg/apis/addtoscheme_components_v1alpha1.go new file mode 100644 index 0000000..44edce2 --- /dev/null +++ b/pkg/apis/addtoscheme_components_v1alpha1.go @@ -0,0 +1,10 @@ +package apis + +import ( + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1" +) + +func init() { + // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back + AddToSchemes = append(AddToSchemes, v1alpha1.SchemeBuilder.AddToScheme) +} diff --git a/pkg/apis/addtoscheme_devopsconsole_v1alpha1.go b/pkg/apis/addtoscheme_devopsconsole_v1alpha1.go index 5a5a987..44edce2 100644 --- a/pkg/apis/addtoscheme_devopsconsole_v1alpha1.go +++ b/pkg/apis/addtoscheme_devopsconsole_v1alpha1.go @@ -1,7 +1,7 @@ package apis import ( - "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1" + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1" ) func init() { diff --git a/pkg/apis/devopsconsole-operator/v1alpha1/zz_generated.openapi.go b/pkg/apis/devopsconsole-operator/v1alpha1/zz_generated.openapi.go index b03064f..b4a180d 100644 --- a/pkg/apis/devopsconsole-operator/v1alpha1/zz_generated.openapi.go +++ b/pkg/apis/devopsconsole-operator/v1alpha1/zz_generated.openapi.go @@ -13,16 +13,17 @@ import ( func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { return map[string]common.OpenAPIDefinition{ - "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvDeployment": schema_pkg_apis_devopsconsole_operator_v1alpha1_EnvDeployment(ref), - "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.Environment": schema_pkg_apis_devopsconsole_operator_v1alpha1_Environment(ref), + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSource": schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSource(ref), + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceSpec": schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSourceSpec(ref), + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceStatus": schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSourceStatus(ref), } } -func schema_pkg_apis_devopsconsole_operator_v1alpha1_EnvDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSource(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ - Description: "EnvDeployment is the Schema for the envdeployments API", + Description: "GitSource is the Schema for the gitsources API", Type: []string{"object"}, Properties: map[string]spec.Schema{ "kind": { @@ -46,62 +47,100 @@ func schema_pkg_apis_devopsconsole_operator_v1alpha1_EnvDeployment(ref common.Re }, "spec": { SchemaProps: spec.SchemaProps{ - Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvDeploymentSpec"), + Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ - Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvDeploymentStatus"), + Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceStatus"), }, }, }, }, }, Dependencies: []string{ - "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvDeploymentSpec", "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvDeploymentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceSpec", "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.GitSourceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, } } -func schema_pkg_apis_devopsconsole_operator_v1alpha1_Environment(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSourceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ - Description: "Environment is the Schema for the environments API", + Description: "GitSourceSpec defines the desired state of GitSource", Type: []string{"object"}, Properties: map[string]spec.Schema{ - "kind": { + "url": { SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds", + Description: "URL of the git repo", Type: []string{"string"}, Format: "", }, }, - "apiVersion": { + "ref": { SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources", + Description: "Ref is a git reference. Optional. \"master\" is used by default.", Type: []string{"string"}, Format: "", }, }, - "metadata": { + "contextDir": { SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + Description: "ContextDir is a path to subfolder in the repo. Optional.", + Type: []string{"string"}, + Format: "", }, }, - "spec": { + "httpProxy": { SchemaProps: spec.SchemaProps{ - Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvironmentSpec"), + Description: "HttpProxy is optional.", + Type: []string{"string"}, + Format: "", }, }, - "status": { + "httpsProxy": { + SchemaProps: spec.SchemaProps{ + Description: "HttpsProxy is optional.", + Type: []string{"string"}, + Format: "", + }, + }, + "noProxy": { + SchemaProps: spec.SchemaProps{ + Description: "NoProxy can be used to specify domains for which no proxying should be performed. Optional.", + Type: []string{"string"}, + Format: "", + }, + }, + "secretRef": { SchemaProps: spec.SchemaProps{ - Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvironmentStatus"), + Description: "SecretRef refers to the secret that contains credentials to access the git repo. Optional.", + Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.SecretRef"), + }, + }, + "flavor": { + SchemaProps: spec.SchemaProps{ + Description: "Flavor of the git provider like github, gitlab, bitbucket, generic, etc. Optional.", + Type: []string{"string"}, + Format: "", }, }, }, + Required: []string{"url"}, }, }, Dependencies: []string{ - "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvironmentSpec", "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.EnvironmentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole-operator/v1alpha1.SecretRef"}, + } +} + +func schema_pkg_apis_devopsconsole_operator_v1alpha1_GitSourceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "GitSourceStatus defines the observed state of GitSource", + Type: []string{"object"}, + }, + }, } } diff --git a/pkg/apis/devopsconsole/v1alpha1/component_types.go b/pkg/apis/devopsconsole/v1alpha1/component_types.go new file mode 100644 index 0000000..40ce571 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/component_types.go @@ -0,0 +1,45 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ComponentSpec defines the desired state of Component +// +k8s:openapi-gen=true +type ComponentSpec struct { + // Container image use to build (nodejs, golang etc..) + BuildType string `json:"buildType"` + // Codebase is the source code of your component. Atm only public remote URL are supported. + Codebase string `json:"codebase"` +} + +// ComponentStatus defines the observed state of Component +// +k8s:openapi-gen=true +type ComponentStatus struct { + RevNumber string +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Component is the Schema for the components API +// +k8s:openapi-gen=true +type Component struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ComponentSpec `json:"spec,omitempty"` + Status ComponentStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ComponentList contains a list of Component +type ComponentList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Component `json:"items"` +} + +func init() { + SchemeBuilder.Register(&Component{}, &ComponentList{}) +} diff --git a/pkg/apis/devopsconsole/v1alpha1/doc.go b/pkg/apis/devopsconsole/v1alpha1/doc.go new file mode 100644 index 0000000..1123016 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/doc.go @@ -0,0 +1,4 @@ +// Package v1alpha1 contains API Schema definitions for the devopsconsole v1alpha1 API group +// +k8s:deepcopy-gen=package,register +// +groupName=devopsconsole.openshift.io +package v1alpha1 diff --git a/pkg/apis/devopsconsole/v1alpha1/register.go b/pkg/apis/devopsconsole/v1alpha1/register.go new file mode 100644 index 0000000..27b8932 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/register.go @@ -0,0 +1,19 @@ +// NOTE: Boilerplate only. Ignore this file. + +// Package v1alpha1 contains API Schema definitions for the devopsconsole v1alpha1 API group +// +k8s:deepcopy-gen=package,register +// +groupName=devopsconsole.openshift.io +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" +) + +var ( + // SchemeGroupVersion is group version used to register these objects + SchemeGroupVersion = schema.GroupVersion{Group: "devopsconsole.openshift.io", Version: "v1alpha1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} +) diff --git a/pkg/apis/devopsconsole/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/devopsconsole/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 0000000..fda0e08 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,118 @@ +// +build !ignore_autogenerated + +/* +Copyright 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. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Component) DeepCopyInto(out *Component) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + out.Status = in.Status + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Component. +func (in *Component) DeepCopy() *Component { + if in == nil { + return nil + } + out := new(Component) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Component) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ComponentList) DeepCopyInto(out *ComponentList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Component, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentList. +func (in *ComponentList) DeepCopy() *ComponentList { + if in == nil { + return nil + } + out := new(ComponentList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ComponentList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ComponentSpec) DeepCopyInto(out *ComponentSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentSpec. +func (in *ComponentSpec) DeepCopy() *ComponentSpec { + if in == nil { + return nil + } + out := new(ComponentSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ComponentStatus) DeepCopyInto(out *ComponentStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentStatus. +func (in *ComponentStatus) DeepCopy() *ComponentStatus { + if in == nil { + return nil + } + out := new(ComponentStatus) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/apis/devopsconsole/v1alpha1/zz_generated.defaults.go b/pkg/apis/devopsconsole/v1alpha1/zz_generated.defaults.go new file mode 100644 index 0000000..dd621a3 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/zz_generated.defaults.go @@ -0,0 +1,32 @@ +// +build !ignore_autogenerated + +/* +Copyright 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. +*/ + +// Code generated by defaulter-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// RegisterDefaults adds defaulters functions to the given scheme. +// Public to allow building arbitrary schemes. +// All generated defaulters are covering - they call all nested defaulters. +func RegisterDefaults(scheme *runtime.Scheme) error { + return nil +} diff --git a/pkg/apis/devopsconsole/v1alpha1/zz_generated.openapi.go b/pkg/apis/devopsconsole/v1alpha1/zz_generated.openapi.go new file mode 100644 index 0000000..b3bb5c6 --- /dev/null +++ b/pkg/apis/devopsconsole/v1alpha1/zz_generated.openapi.go @@ -0,0 +1,111 @@ +// +build !ignore_autogenerated + +// Code generated by openapi-gen. DO NOT EDIT. + +// This file was autogenerated by openapi-gen. Do not edit it manually! + +package v1alpha1 + +import ( + spec "github.com/go-openapi/spec" + common "k8s.io/kube-openapi/pkg/common" +) + +func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { + return map[string]common.OpenAPIDefinition{ + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.Component": schema_pkg_apis_devopsconsole_v1alpha1_Component(ref), + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentSpec": schema_pkg_apis_devopsconsole_v1alpha1_ComponentSpec(ref), + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentStatus": schema_pkg_apis_devopsconsole_v1alpha1_ComponentStatus(ref), + } +} + +func schema_pkg_apis_devopsconsole_v1alpha1_Component(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Component is the Schema for the components API", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Ref: ref("github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentSpec", "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1.ComponentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_pkg_apis_devopsconsole_v1alpha1_ComponentSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ComponentSpec defines the desired state of Component", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "buildType": { + SchemaProps: spec.SchemaProps{ + Description: "Container image use to build (nodejs, golang etc..)", + Type: []string{"string"}, + Format: "", + }, + }, + "codebase": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"buildType", "codebase"}, + }, + }, + } +} + +func schema_pkg_apis_devopsconsole_v1alpha1_ComponentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ComponentStatus defines the observed state of Component", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "RevNumber": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"RevNumber"}, + }, + }, + } +} diff --git a/pkg/controller/add_component.go b/pkg/controller/add_component.go new file mode 100644 index 0000000..72d4676 --- /dev/null +++ b/pkg/controller/add_component.go @@ -0,0 +1,10 @@ +package controller + +import ( + "github.com/redhat-developer/devopsconsole-operator/pkg/controller/component" +) + +func init() { + // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. + AddToManagerFuncs = append(AddToManagerFuncs, component.Add) +} diff --git a/pkg/controller/component/component_controller.go b/pkg/controller/component/component_controller.go new file mode 100644 index 0000000..1c9a2ba --- /dev/null +++ b/pkg/controller/component/component_controller.go @@ -0,0 +1,248 @@ +package component + +import ( + "context" + "fmt" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "strconv" + + componentsv1alpha1 "github.com/redhat-developer/devopsconsole-operator/pkg/apis/devopsconsole/v1alpha1" + + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" + "sigs.k8s.io/controller-runtime/pkg/source" + + buildv1 "github.com/openshift/api/build/v1" + imagev1 "github.com/openshift/api/image/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var log = logf.Log.WithName("controller_component") + +/** +* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller +* business logic. Delete these comments after modifying this file.* + */ + +// Add creates a new Component Controller and adds it to the Manager. The Manager will set fields on the Controller +// and Start it when the Manager is Started. +func Add(mgr manager.Manager) error { + return add(mgr, newReconciler(mgr)) +} + +// newReconciler returns a new reconcile.Reconciler +func newReconciler(mgr manager.Manager) reconcile.Reconciler { + return &ReconcileComponent{client: mgr.GetClient(), scheme: mgr.GetScheme()} +} + +// add adds a new Controller to mgr with r as the reconcile.Reconciler +func add(mgr manager.Manager, r reconcile.Reconciler) error { + // Create a new controller + c, err := controller.New("component-controller", mgr, controller.Options{Reconciler: r}) + if err != nil { + return err + } + + // Watch for changes to primary resource Component + err = c.Watch(&source.Kind{Type: &componentsv1alpha1.Component{}}, &handler.EnqueueRequestForObject{}) + if err != nil { + return err + } + + return nil +} + +var _ reconcile.Reconciler = &ReconcileComponent{} +var buildTypeImages = map[string]string{"nodejs":"nodeshift/centos7-s2i-nodejs:10.x"} + +// ReconcileComponent reconciles a Component object +type ReconcileComponent struct { + // This client, initialized using mgr.Client() above, is a split client + // that reads objects from the cache and writes to the apiserver + client client.Client + scheme *runtime.Scheme +} + +// Reconcile reads that state of the cluster for a Component object and makes changes based on the state read +// and what is in the Component.Spec +// Note: +// The Controller will requeue the Request to be processed again if the returned error is non-nil or +// Result.Requeue is true, otherwise upon completion it will remove the work from the queue. +func (r *ReconcileComponent) Reconcile(request reconcile.Request) (reconcile.Result, error) { + reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) + reqLogger.Info("Reconciling Component") + + // Fetch the Component instance + instance := &componentsv1alpha1.Component{} + err := r.client.Get(context.TODO(), request.NamespacedName, instance) + if err != nil { + if errors.IsNotFound(err) { + // Request object not found, could have been deleted after reconcile request. + // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. + // Return and don't requeue + return reconcile.Result{}, nil + } + // Error reading the object - requeue the request. + return reconcile.Result{}, err + } + + log.Info("============================================================") + log.Info(fmt.Sprintf("***** Reconciling Component %s, namespace %s", request.Name, request.Namespace)) + log.Info(fmt.Sprintf("** Creation time : %s", instance.ObjectMeta.CreationTimestamp)) + log.Info(fmt.Sprintf("** Resource version : %s", instance.ObjectMeta.ResourceVersion)) + log.Info(fmt.Sprintf("** Generation version : %s", strconv.FormatInt(instance.ObjectMeta.Generation, 10))) + log.Info(fmt.Sprintf("** Deletion time : %s", instance.ObjectMeta.DeletionTimestamp)) + log.Info("============================================================") + + // Assign the generated ResourceVersion to the resource status + if instance.Status.RevNumber == "" { + instance.Status.RevNumber = instance.ObjectMeta.ResourceVersion + } + + if !instance.ObjectMeta.DeletionTimestamp.IsZero() { + log.Info( "** DELETION **") + return reconcile.Result{}, nil + } + + // We only call the pipeline when the component has been created + // and if the Status Revision Number is the same + if instance.Status.RevNumber == instance.ObjectMeta.ResourceVersion { + // Create an empty image name "nodejs-output" + newImageForOutput := newImageStream(instance.Namespace, instance.Name) + err = r.client.Create(context.TODO(), newImageForOutput) + if err != nil { + log.Error(err, "** Creating new OUTPUT image fails **") + return reconcile.Result{}, err + } + log.Info("** Image stream for OUTPUT created **") + if err := controllerutil.SetControllerReference(instance, newImageForOutput, r.scheme); err != nil { + log.Error(err, "** Setting owner reference fails **") + return reconcile.Result{}, err + } + + // Create an empty image name "nodejs-runtime" + // todo(corinne): check if we can reuse openshift's image stream + newImageForRuntime := newImageStreamFromDocker(instance.Namespace, instance.Name, instance.Spec.BuildType) + err = r.client.Create(context.TODO(), newImageForRuntime) + if err != nil { + log.Error(err, "** Creating new RUNTIME image fails **") + return reconcile.Result{}, err + } + if newImageForRuntime == nil { + log.Error(err, "** Creating new RUNTIME image fails **") + return reconcile.Result{}, errors.NewNotFound(schema.GroupResource{"", "ImageStream"}, "runtime image for build not found") + } + log.Info("** Image stream for RUNTIME created **") + if err := controllerutil.SetControllerReference(instance, newImageForRuntime, r.scheme); err != nil { + log.Error(err, "** Setting owner reference fails **") + return reconcile.Result{}, err + } + + // Create build config with s2i + bc := generateBuildConfig(instance.Namespace, instance.Name, instance.Spec.Codebase, "master") + err = r.client.Create(context.TODO(), &bc) + if err != nil { + log.Error(err, "** BuildConfig creation fails **") + return reconcile.Result{}, err + } + log.Info("** BuildConfig created **") + } + + return reconcile.Result{}, nil +} + + +func newImageStreamFromDocker(namespace string, name string, buildType string) *imagev1.ImageStream { + labels := map[string]string{ + "app": name, + } + if _, ok := buildTypeImages[buildType]; !ok { + return nil + } + return &imagev1.ImageStream{ObjectMeta:metav1.ObjectMeta{ + Name: name+"-runtime", + Namespace: namespace, + Labels: labels, + }, Spec: imagev1.ImageStreamSpec{ + LookupPolicy: imagev1.ImageLookupPolicy{ + Local:false, + }, + Tags:[]imagev1.TagReference{ + { + Name:"latest", + From:&corev1.ObjectReference{ + Kind: "DockerImage", + Name: buildTypeImages[buildType], + }, + }, + }, + }} +} +func newImageStream(namespace string, name string) *imagev1.ImageStream { + labels := map[string]string{ + "app": name, + } + return &imagev1.ImageStream{ObjectMeta:metav1.ObjectMeta{ + Name: name+"-output", + Namespace: namespace, + Labels: labels, + }} +} + +func getMetaObj(name string, imageNamespace string) metav1.ObjectMeta { + labels := map[string]string{ + "app": name, + } + return metav1.ObjectMeta{Name: name, Namespace:imageNamespace, Labels: labels} +} + +func generateBuildConfig(namespace string, name string, gitURL string, gitRef string) buildv1.BuildConfig { + buildSource := buildv1.BuildSource{ + Git: &buildv1.GitBuildSource{ + URI: gitURL, + Ref: gitRef, + }, + Type: buildv1.BuildSourceGit, + } + incremental := true + return buildv1.BuildConfig{ + ObjectMeta: getMetaObj(name + "-bc", namespace), + Spec: buildv1.BuildConfigSpec{ + CommonSpec: buildv1.CommonSpec{ + Output: buildv1.BuildOutput{ + To: &corev1.ObjectReference{ + Kind: "ImageStreamTag", + Name: name + "-output:latest", + }, + }, + Source: buildSource, + Strategy: buildv1.BuildStrategy{ + SourceStrategy: &buildv1.SourceBuildStrategy{ + From: corev1.ObjectReference{ + Kind: "ImageStreamTag", + Name: name + "-runtime:latest", + Namespace: namespace, + }, + Incremental: &incremental, + }, + }, + }, + Triggers:[]buildv1.BuildTriggerPolicy{ + { + Type: "ConfigChange", + }, { + Type: "ImageChange", + ImageChange: &buildv1.ImageChangeTrigger{}, + }, + }, + }, + } +} \ No newline at end of file