Git Product home page Git Product logo

operator-utils's Introduction

operator-utils library

Go Report Card Build Status

This library layers on top of the Operator SDK, having set of utilities function as a library to easily create Kubernetes operators.

Kubernetes / OpenShift Version Support

In July of 2020, our team moved away from using the term master for our default branch. As a result, our branching scheme is as follows:

  • The main (default) branch currently supports OCP 4.6 (K8S 1.19), the latest GA release.
  • The next branch currently supports OCP 4.7 (K8S 1.20).
  • For versions of operator-utils targeting earlier releases of OCP (starting with 4.2), please refer to the tags section.
    • tag v1.X.Y indicates support for OCP vX.Y
  • With each General Availability release of OCP, the main branch will be given a tag matching the previously supported OCP version in main, then the next branch will be rebased onto main.

Contributing to the operator-utils Project

All bugs, tasks, fixes or enhancements should be tracked as GitHub Issues & Pull Requests.

  • To contribute features targeting OCP 4.6 only, use a local feature branch based off of & targeting origin/main with any PR's. Reference any JIRA/GitHub issues in PR's where applicable.
  • To contribute features targeting OCP 4.7 only, use a local feature branch based off of & targeting origin/next with any PR's, Reference any JIRA/GitHub issues in PR's where applicable.
  • To contribute features targeting both currently supported versions, first complete the commit/PR work targeting next. Once that PR is merged to next, create a new PR with cherry-pick of the commit targeting main.
  • Contributions targeting OCP versions older than what's currently supported by main will typically no longer be accepted. Please contact contributors for further discussion.

Declaring operator-utils dependency

Regardless of dependency framework, we suggest following the best practice of declaring any and all dependencies your project utilizes regardless of target branch, tag, or revision.

With regards to operator-utils, please carefully consider the given version support information above when declaring your dependency, as depending on or defaulting to main branch will likely result in future build complications as our project continues to evolve and cycle minor version support.

  • Go.mod example specifying REVISION:
github.com/RHsyseng/operator-utils v0.0.0-20200108204558-82090ef57586

Features

  1. managing CR and CRD validation
  2. pods deployment status
  3. resource comparison, adding, updating and deleting
  4. platform detection Kubernetes VS Openshift

Managing CR and CRD validation

Operator util library use package validation for validate the CRD and CR file, these function use as a unit test within operator

CRD validation Usage:

schema := getCompleteSchema(t)
 missingEntries := schema.GetMissingEntries(&sampleApp{})
 for _, missing := range missingEntries {
    if strings.HasPrefix(missing.Path, "/status") {
       //Not using subresources, so status is not expected to appear in CRD
    } else {
       assert.Fail(t, "Discrepancy between CRD and Struct", "Missing or incorrect schema validation at %v, expected type %v", missing.Path, missing.Type)
    }
 }

CR validation Usage:

schema, err := New([]byte(schemaYaml))
 assert.NoError(t, err)

 type myAppSpec struct {
    Number float64 `json:"number,omitempty"`
 }

 type myApp struct {
    Spec myAppSpec `json:"spec,omitempty"`
 }

 cr := myApp{
    Spec: myAppSpec{
       Number: float64(23),
    },
 }
 missingEntries := schema.GetMissingEntries(&cr)
 assert.Len(t, missingEntries, 0, "Expect no missing entries in CRD for this struct: %v", missingEntries)

A full example is provided here

Pods deployment status

showes the status of the deployment on OLM UI in the form of PI chart, as seen in below screenshot

alt text

Usage:

Below seen line required to add into types.go status structure

PodStatus olm.DeploymentStatus `json:"podStatus"`

Add these lines into CSV file inside statusDescriptors section:

statusDescriptors:
        - description: The current pods
          displayName: Pods Status
          path: podStatus
          x-descriptors:
            - "urn:alm:descriptor:com.tectonic.ui:podStatuses"

For DeploymentConfig deployment status:

var dcs []oappsv1.DeploymentConfig

deploymentStatus := olm.GetDeploymentConfigStatus(dcs)
 if !reflect.DeepEqual(instance.Status.Deployments, deploymentStatus) {
    r.reqLogger.Info("Deployment status will be updated")
    instance.Status.Deployments = deploymentStatus
    err = r.client.Status().Update(context.TODO(), instance)
    if err != nil {
       r.reqLogger.Error(err, "Failed to update deployment status")
       return err
    }
 }

For StatefulSet Deployment status:

var status olm.DeploymentStatus
 sfsFound := &appsv1.StatefulSet{}

 err := client.Get(context.TODO(), namespacedName, sfsFound)
 if err == nil {
    status = olm.GetSingleStatefulSetStatus(*sfsFound)
 } else {
    dsFound := &appsv1.DaemonSet{}
    err = client.Get(context.TODO(), namespacedName, dsFound)
    if err == nil {
       status = olm.GetSingleDaemonSetStatus(*dsFound)
    }
 }

Resource comparison (adding, updating and deleting)

Common function for listing, adding, updating, deleting kubernetes objects like seen below:

List of objects that are deployed

reader := read.New(client).WithNamespace(instance.Namespace).WithOwnerObject(instance)
  resourceMap, err := reader.ListAll(
     &corev1.PersistentVolumeClaimList{},
     &corev1.ServiceList{},
     &appsv1.StatefulSetList{},
     &routev1.RouteList{},
  )

Compare what's deployed with what should be deployed

requested := compare.NewMapBuilder().Add(requestedResources...).ResourceMap()
comparator := compare.NewMapComparator()
deltas := comparator.Compare(deployed, requested)

Adding the objects:

added, err := writer.AddResources(delta.Added)

Updating the objects:

updated, err := writer.UpdateResources(deployed[resourceType], delta.Updated)

Removing the objects:

removed, err := writer.RemoveResources(delta.Removed)

A full usage is provided here

Platform detection Kubernetes VS Openshift

To detect platform whether operator is running on kuberenete or openshift or what version of openshift is using

  info, err := pv.GetPlatformInfo(c.discoverer, c.config)

A full example is provided here

Who is using this Library

operator-utils is used by several Red Hat product & community operators, including the following:

operator-utils's People

Contributors

bmozaffa avatar jeremyary avatar tchughesiv avatar ruromero avatar myeung18 avatar ricardozanini avatar xieshenzh avatar akoserwal avatar philbrookes avatar redhathameed avatar willkutler avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.