{"id":22885027,"url":"https://github.com/mark8s/helloworld-operator","last_synced_at":"2025-03-31T17:55:20.430Z","repository":{"id":112107736,"uuid":"452575622","full_name":"mark8s/helloworld-operator","owner":"mark8s","description":"a k8s operator 、operator-sdk ","archived":false,"fork":false,"pushed_at":"2022-05-10T07:00:57.000Z","size":857,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-06T22:42:24.426Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mark8s.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-27T07:04:23.000Z","updated_at":"2022-01-27T07:06:58.000Z","dependencies_parsed_at":null,"dependency_job_id":"d5777540-57b2-4e44-9e34-8d455e17122d","html_url":"https://github.com/mark8s/helloworld-operator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mark8s%2Fhelloworld-operator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mark8s%2Fhelloworld-operator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mark8s%2Fhelloworld-operator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mark8s%2Fhelloworld-operator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mark8s","download_url":"https://codeload.github.com/mark8s/helloworld-operator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246514236,"owners_count":20790016,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-13T19:31:02.238Z","updated_at":"2025-03-31T17:55:20.406Z","avatar_url":"https://github.com/mark8s.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# helloworld-operator\na k8s operator 、operator-sdk \n\n## Operator\n参考 \n\n\u003e https://jicki.cn/kubernetes-operator/\n\u003e https://learnku.com/articles/60683\n\u003e https://opensource.actionsky.com/20210706-kubernetes-operator/\n\n### 安装\n\n（1）安装operator-sdk、go环境\n\n（2）创建helloworld-operator目录,执行以下命令\n\n```bash\noperator-sdk init --domain mark8s.io --owner \"mark\" --repo github.com/example/helloworld-operator\n```\n\n执行后，查看当前目录结构：\n\n```bash\n[root@infra helloworld-operator]# operator-sdk init --domain mark8s.io --owner \"mark\" --repo github.com/example/helloworld-operator\nWriting kustomize manifests for you to edit...\nWriting scaffold for you to edit...\nGet controller runtime:\n$ go get sigs.k8s.io/controller-runtime@v0.10.0\nUpdate dependencies:\n$ go mod tidy\nNext: define a resource with:\n$ operator-sdk create api\n[root@infra helloworld-operator]# ls\nconfig  Dockerfile  go.mod  go.sum  hack  main.go  Makefile  PROJECT\n[root@infra helloworld-operator]# tree\n.\n├── config\n│   ├── default\n│   │   ├── kustomization.yaml\n│   │   ├── manager_auth_proxy_patch.yaml\n│   │   └── manager_config_patch.yaml\n│   ├── manager\n│   │   ├── controller_manager_config.yaml\n│   │   ├── kustomization.yaml\n│   │   └── manager.yaml\n│   ├── manifests\n│   │   └── kustomization.yaml\n│   ├── prometheus\n│   │   ├── kustomization.yaml\n│   │   └── monitor.yaml\n│   ├── rbac\n│   │   ├── auth_proxy_client_clusterrole.yaml\n│   │   ├── auth_proxy_role_binding.yaml\n│   │   ├── auth_proxy_role.yaml\n│   │   ├── auth_proxy_service.yaml\n│   │   ├── kustomization.yaml\n│   │   ├── leader_election_role_binding.yaml\n│   │   ├── leader_election_role.yaml\n│   │   ├── role_binding.yaml\n│   │   └── service_account.yaml\n│   └── scorecard\n│       ├── bases\n│       │   └── config.yaml\n│       ├── kustomization.yaml\n│       └── patches\n│           ├── basic.config.yaml\n│           └── olm.config.yaml\n├── Dockerfile\n├── go.mod\n├── go.sum\n├── hack\n│   └── boilerplate.go.txt\n├── main.go\n├── Makefile\n└── PROJECT\n\n10 directories, 29 files\n[root@infra helloworld-operator]#\n```\n\n创建crd\n\n```\noperator-sdk create api \\\n    --group=hello \\\n    --version=v1alpha1 \\\n    --kind=Mark \\\n    --resource \\\n    --controller\n```\n\n执行后，发现报错\n\n```bash\n[root@infra helloworld-operator]# operator-sdk create api \\\n\u003e     --group=hello \\\n\u003e     --version=v1alpha1 \\\n\u003e     --kind=Mark \\\n\u003e     --resource \\\n\u003e     --controller\nWriting kustomize manifests for you to edit...\nWriting scaffold for you to edit...\napi/v1alpha1/mark_types.go\ncontrollers/mark_controller.go\nUpdate dependencies:\n$ go mod tidy\nRunning make:\n$ make generate\ngo: creating new go.mod: module tmp\nDownloading sigs.k8s.io/controller-tools/cmd/controller-gen@v0.7.0\ngo get: added sigs.k8s.io/controller-tools v0.7.0\n/root/mark/operator/helloworld-operator/bin/controller-gen object:headerFile=\"hack/boilerplate.go.txt\" paths=\"./...\"\n/usr/local/go/src/net/cgo_linux.go:12:8: no such package located\nError: not all generators ran successfully\nrun `controller-gen object:headerFile=hack/boilerplate.go.txt paths=./... -w` to see all available markers, or `controller-gen object:headerFile=hack/boilerplate.go.txt paths=./... -h` for usage\nmake: *** [generate] Error 1\nError: failed to create API: unable to run post-scaffold tasks of \"base.go.kubebuilder.io/v3\": exit status 2\nUsage:\n  operator-sdk create api [flags]\n\nExamples:\n  # Create a frigates API with Group: ship, Version: v1beta1 and Kind: Frigate\n  operator-sdk create api --group ship --version v1beta1 --kind Frigate\n\n  # Edit the API Scheme\n  nano api/v1beta1/frigate_types.go\n\n  # Edit the Controller\n  nano controllers/frigate/frigate_controller.go\n\n  # Edit the Controller Test\n  nano controllers/frigate/frigate_controller_test.go\n\n  # Generate the manifests\n  make manifests\n\n  # Install CRDs into the Kubernetes cluster using kubectl apply\n  make install\n\n  # Regenerate code and run against the Kubernetes cluster configured by ~/.kube/config\n  make run\n\n\nFlags:\n      --controller           if set, generate the controller without prompting the user (default true)\n      --force                attempt to create resource even if it already exists\n      --group string         resource Group\n  -h, --help                 help for api\n      --kind string          resource Kind\n      --make make generate   if true, run make generate after generating files (default true)\n      --namespaced           resource is namespaced (default true)\n      --plural string        resource irregular plural form\n      --resource             if set, generate the resource without prompting the user (default true)\n      --version string       resource Version\n\nGlobal Flags:\n      --plugins strings   plugin keys to be used for this subcommand execution\n      --verbose           Enable verbose logging\n\nFATA[0011] failed to create API: unable to run post-scaffold tasks of \"base.go.kubebuilder.io/v3\": exit status 2 \n[root@infra helloworld-operator]#\n```\n\n错误为：\n\n\u003e FATA[0011] failed to create API: unable to run post-scaffold tasks of \"base.go.kubebuilder.io/v3\": exit status 2\n\n具体查了发现有个网址有这个的说明：\n\n```\nhttps://github.com/operator-framework/operator-sdk/issues/5284\n```\n\n意思是虚拟机上面还得装gcc\n\n![install-gcc](./image/install-gcc.png)\n\n我查了下我本地的虚拟机环境，果然没装，于是安装了下：\n\n```bash\n[root@infra helloworld-operator]# gcc\n-bash: gcc: command not found\n[root@infra helloworld-operator]# yum install gcc -y\nLoaded plugins: fastestmirror\n...\n[root@infra helloworld-operator]# gcc -v\nUsing built-in specs.\nCOLLECT_GCC=gcc\n...\ngcc version 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) \n[root@infra helloworld-operator]# \n```\n\n我们清干净 helloworld-operator 目录下面的所有文件，重新执行\n\n```\noperator-sdk init --domain mark8s.io --owner \"mark\" --repo github.com/example/helloworld-operator\n```\n\n然后继续执行create api\n\n```bash\n[root@infra helloworld-operator]# operator-sdk init --domain mark8s.io --owner \"mark\" --repo github.com/example/helloworld-operator\nWriting kustomize manifests for you to edit...\nWriting scaffold for you to edit...\nGet controller runtime:\n$ go get sigs.k8s.io/controller-runtime@v0.10.0\nUpdate dependencies:\n$ go mod tidy\nNext: define a resource with:\n$ operator-sdk create api\n[root@infra helloworld-operator]# operator-sdk create api     --group=hello     --version=v1alpha1     --kind=Mark     --resource     --controller\nWriting kustomize manifests for you to edit...\nWriting scaffold for you to edit...\napi/v1alpha1/mark_types.go\ncontrollers/mark_controller.go\nUpdate dependencies:\n$ go mod tidy\nRunning make:\n$ make generate\ngo: creating new go.mod: module tmp\nDownloading sigs.k8s.io/controller-tools/cmd/controller-gen@v0.7.0\ngo get: added sigs.k8s.io/controller-tools v0.7.0\n/root/mark/operator/helloworld-operator/bin/controller-gen object:headerFile=\"hack/boilerplate.go.txt\" paths=\"./...\"\nNext: implement your new API and generate the manifests (e.g. CRDs,CRs) with:\n$ make manifests\n[root@infra helloworld-operator]#\n```\n\n很好！没有报错了！\n\n```bash\n[root@infra helloworld-operator]# tree\n.\n├── api\n│   └── v1alpha1\n│       ├── groupversion_info.go\n│       ├── mark_types.go\n│       └── zz_generated.deepcopy.go\n├── bin\n│   └── controller-gen\n├── config\n│   ├── crd\n│   │   ├── kustomization.yaml\n│   │   ├── kustomizeconfig.yaml\n│   │   └── patches\n│   │       ├── cainjection_in_marks.yaml\n│   │       └── webhook_in_marks.yaml\n│   ├── default\n│   │   ├── kustomization.yaml\n│   │   ├── manager_auth_proxy_patch.yaml\n│   │   └── manager_config_patch.yaml\n│   ├── manager\n│   │   ├── controller_manager_config.yaml\n│   │   ├── kustomization.yaml\n│   │   └── manager.yaml\n│   ├── manifests\n│   │   └── kustomization.yaml\n│   ├── prometheus\n│   │   ├── kustomization.yaml\n│   │   └── monitor.yaml\n│   ├── rbac\n│   │   ├── auth_proxy_client_clusterrole.yaml\n│   │   ├── auth_proxy_role_binding.yaml\n│   │   ├── auth_proxy_role.yaml\n│   │   ├── auth_proxy_service.yaml\n│   │   ├── kustomization.yaml\n│   │   ├── leader_election_role_binding.yaml\n│   │   ├── leader_election_role.yaml\n│   │   ├── mark_editor_role.yaml\n│   │   ├── mark_viewer_role.yaml\n│   │   ├── role_binding.yaml\n│   │   └── service_account.yaml\n│   ├── samples\n│   │   ├── hello_v1alpha1_mark.yaml\n│   │   └── kustomization.yaml\n│   └── scorecard\n│       ├── bases\n│       │   └── config.yaml\n│       ├── kustomization.yaml\n│       └── patches\n│           ├── basic.config.yaml\n│           └── olm.config.yaml\n├── controllers\n│   ├── mark_controller.go\n│   └── suite_test.go\n├── Dockerfile\n├── go.mod\n├── go.sum\n├── hack\n│   └── boilerplate.go.txt\n├── main.go\n├── Makefile\n└── PROJECT\n\n17 directories, 43 files\n```\n\n执行下面的命令生成 CR 资源相关代码，每次修改 CR 的定义都需执行该命令。\n\n```makefile\nmake generate\n```\n\n执行下面的命令会生成 CRD 定义文件 helloworld-operator/config/crd/bases/hello.mark8s.io_marks.yaml\n\n```makefile\nmake manifests\n```\n\n### 编写逻辑\n\n现在就需要修改CRD类型定义代码 api/v1alpha1/mark_types.go\n\n```go\npackage v1alpha1\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n)\n\n// EDIT THIS FILE!  THIS IS SCAFFOLDING FOR YOU TO OWN!\n// NOTE: json tags are required.  Any new fields you add must have json tags for the fields to be serialized.\n\n// MarkSpec defines the desired state of Mark\ntype MarkSpec struct {\n\t// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster\n\t// Important: Run \"make\" to regenerate code after modifying this file\n\n\t// Count is an example field of Mark. Edit mark_types.go to remove/update\n\tCount int32 `json:\"count,omitempty\"`\n}\n\n// MarkStatus defines the observed state of Mark\ntype MarkStatus struct {\n\t// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster\n\t// Important: Run \"make\" to regenerate code after modifying this file\n\tInstances []string `json:\"instances\"`\n}\n\n//+kubebuilder:object:root=true\n//+kubebuilder:subresource:status\n\n// Mark is the Schema for the marks API\ntype Mark struct {\n\tmetav1.TypeMeta   `json:\",inline\"`\n\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec   MarkSpec   `json:\"spec,omitempty\"`\n\tStatus MarkStatus `json:\"status,omitempty\"`\n}\n\n//+kubebuilder:object:root=true\n\n// MarkList contains a list of Mark\ntype MarkList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ListMeta `json:\"metadata,omitempty\"`\n\tItems           []Mark `json:\"items\"`\n}\n\nfunc init() {\n\tSchemeBuilder.Register(\u0026Mark{}, \u0026MarkList{})\n}\n\n```\n\n在 MarkSpec 中定义了一个 Count ，MarkStatus 定义了一个 Instances。\n\n然后需要执行\n\n```makefile\nmake generate\nmake manifests\n```\n\n执行完上述后，我们可以查看生成的crd，路径为 config/crd/bases/hello.mark8s.io_marks.yaml\n\n![project](./image/project-str1.png)\n\n\n内容如下\n\n```yaml\n---\napiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\nmetadata:\n  annotations:\n    controller-gen.kubebuilder.io/version: v0.7.0\n  creationTimestamp: null\n  name: marks.hello.mark8s.io\nspec:\n  group: hello.mark8s.io\n  names:\n    kind: Mark\n    listKind: MarkList\n    plural: marks\n    singular: mark\n  scope: Namespaced\n  versions:\n  - name: v1alpha1\n    schema:\n      openAPIV3Schema:\n        description: Mark is the Schema for the marks API\n        properties:\n          apiVersion:\n            description: 'APIVersion defines the versioned schema of this representation\n              of an object. Servers should convert recognized schemas to the latest\n              internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'\n            type: string\n          kind:\n            description: 'Kind is a string value representing the REST resource this\n              object represents. Servers may infer this from the endpoint the client\n              submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'\n            type: string\n          metadata:\n            type: object\n          spec:\n            description: MarkSpec defines the desired state of Mark\n            properties:\n              count:\n                description: Count is an example field of Mark. Edit mark_types.go\n                  to remove/update\n                format: int32\n                type: integer\n            type: object\n          status:\n            description: MarkStatus defines the observed state of Mark\n            properties:\n              instances:\n                description: 'INSERT ADDITIONAL STATUS FIELD - define observed state\n                  of cluster Important: Run \"make\" to regenerate code after modifying\n                  this file'\n                items:\n                  type: string\n                type: array\n            required:\n            - instances\n            type: object\n        type: object\n    served: true\n    storage: true\n    subresources:\n      status: {}\nstatus:\n  acceptedNames:\n    kind: \"\"\n    plural: \"\"\n  conditions: []\n  storedVersions: []\n\n```\n\n现在我们去写controller的逻辑，路径为 controllers/mark_controller.go\n\n```go\n/*\nCopyright 2022 mark.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage controllers\n\nimport (\n\t\"context\"\n\tv1 \"k8s.io/api/apps/v1\"\n\tv12 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n\t\"reflect\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log\"\n\n\thellov1alpha1 \"github.com/example/helloworld-operator/api/v1alpha1\"\n)\n\n// MarkReconciler reconciles a Mark object\ntype MarkReconciler struct {\n\tclient.Client\n\tScheme *runtime.Scheme\n}\n\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks/status,verbs=get;update;patch\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks/finalizers,verbs=update\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=deployments,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;\n//+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete\n\n// Reconcile is part of the main kubernetes reconciliation loop which aims to\n// move the current state of the cluster closer to the desired state.\n// TODO(user): Modify the Reconcile function to compare the state specified by\n// the Mark object against the actual cluster state, and then\n// perform operations to make the cluster state reflect the state specified by\n// the user.\n//\n// For more details, check Reconcile and its Result here:\n// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile\nfunc (r *MarkReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\t_ = log.FromContext(ctx)\n\n\t// TODO(user): your logic here\n\n\tmark := \u0026hellov1alpha1.Mark{}\n\n\terr := r.Get(ctx, req.NamespacedName, mark)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlog.Log.Info(\"Mark resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\tlog.Log.Error(err, \"Failed to get Mark\")\n\t\treturn ctrl.Result{}, err\n\t}\n\t// Check if the deployment already exists, if not create a new one\n\tfound := \u0026v1.Deployment{}\n\terr = r.Get(ctx, types.NamespacedName{Name: mark.Name, Namespace: mark.Namespace}, found)\n\tif err != nil \u0026\u0026 errors.IsNotFound(err) {\n\t\t// Define a new deployment\n\t\tdep := r.deploymentForMark(mark)\n\t\tlog.Log.Info(\"Creating a new Deployment\", \"Deployment.Namespace\", dep, \"Deployment.Name\", dep.Name)\n\t\terr = r.Create(ctx, dep)\n\t\tif err != nil {\n\t\t\tlog.Log.Error(err, \"Failed to create new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// Deployment created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Log.Error(err, \"Failed to get Deployment\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tpodList := \u0026v12.PodList{}\n\tlistOpts := []client.ListOption{\n\t\tclient.InNamespace(mark.Namespace),\n\t\tclient.MatchingLabels(labelsForMark(mark.Name)),\n\t}\n\tif err = r.List(ctx, podList, listOpts...); err != nil {\n\t\tlog.Log.Error(err, \"Failed to list pods\", \"Mark.Namespace\", mark.Namespace, \"Mark.Name\", mark.Name)\n\t\treturn ctrl.Result{}, err\n\t}\n\tpodNames := getPodNames(podList.Items)\n\n\t// Update status.Nodes if needed\n\tif !reflect.DeepEqual(podNames, mark.Status.Instances) {\n\t\tmark.Status.Instances = podNames\n\t\terr := r.Status().Update(ctx, mark)\n\t\tif err != nil {\n\t\t\tlog.Log.Error(err, \"Failed to update Mark status\")\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t}\n\n\treturn ctrl.Result{}, nil\n}\n\nfunc getPodNames(pods []v12.Pod) []string {\n\tvar podNames []string\n\tfor _, pod := range pods {\n\t\tpodNames = append(podNames, pod.Name)\n\t}\n\treturn podNames\n}\n\nfunc (r *MarkReconciler) deploymentForMark(m *hellov1alpha1.Mark) *v1.Deployment {\n\tls := labelsForMark(m.Name)\n\treplicas := m.Spec.Count\n\n\tdep := \u0026v1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      m.Name,\n\t\t\tNamespace: m.Namespace,\n\t\t},\n\t\tSpec: v1.DeploymentSpec{\n\t\t\tReplicas: \u0026replicas,\n\t\t\tSelector: \u0026metav1.LabelSelector{\n\t\t\t\tMatchLabels: ls,\n\t\t\t},\n\t\t\tTemplate: v12.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: ls,\n\t\t\t\t},\n\t\t\t\tSpec: v12.PodSpec{\n\t\t\t\t\tContainers: []v12.Container{{\n\t\t\t\t\t\tImage:   \"busybox\",\n\t\t\t\t\t\tName:    \"mark\",\n\t\t\t\t\t\tCommand: []string{\"sleep\", \"3600\"},\n\t\t\t\t\t\tPorts: []v12.ContainerPort{{\n\t\t\t\t\t\t\tContainerPort: 1234,\n\t\t\t\t\t\t\tName:          \"mark\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t// Set PodSet instance as the owner and controller\n\t_ = ctrl.SetControllerReference(m, dep, r.Scheme)\n\treturn dep\n}\n\nfunc labelsForMark(name string) map[string]string {\n\treturn map[string]string{\"app\": \"mark\", \"podSet_cr\": name}\n}\n\n// SetupWithManager sets up the controller with the Manager.\nfunc (r *MarkReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(\u0026hellov1alpha1.Mark{}).\n\t\tOwns(\u0026v1.Deployment{}).\n\t\tComplete(r)\n}\n\n```\n\n### 构建operator镜像\n\n执行 `make docker-build`. 整个Markfile文件的内容如下：\n\n```makefile\n# VERSION defines the project version for the bundle.\n# Update this value when you upgrade the version of your project.\n# To re-generate a bundle for another specific version without changing the standard setup, you can:\n# - use the VERSION as arg of the bundle target (e.g make bundle VERSION=0.0.2)\n# - use environment variables to overwrite this value (e.g export VERSION=0.0.2)\nVERSION ?= 0.0.1\n\n# CHANNELS define the bundle channels used in the bundle.\n# Add a new line here if you would like to change its default config. (E.g CHANNELS = \"candidate,fast,stable\")\n# To re-generate a bundle for other specific channels without changing the standard setup, you can:\n# - use the CHANNELS as arg of the bundle target (e.g make bundle CHANNELS=candidate,fast,stable)\n# - use environment variables to overwrite this value (e.g export CHANNELS=\"candidate,fast,stable\")\nifneq ($(origin CHANNELS), undefined)\nBUNDLE_CHANNELS := --channels=$(CHANNELS)\nendif\n\n# DEFAULT_CHANNEL defines the default channel used in the bundle.\n# Add a new line here if you would like to change its default config. (E.g DEFAULT_CHANNEL = \"stable\")\n# To re-generate a bundle for any other default channel without changing the default setup, you can:\n# - use the DEFAULT_CHANNEL as arg of the bundle target (e.g make bundle DEFAULT_CHANNEL=stable)\n# - use environment variables to overwrite this value (e.g export DEFAULT_CHANNEL=\"stable\")\nifneq ($(origin DEFAULT_CHANNEL), undefined)\nBUNDLE_DEFAULT_CHANNEL := --default-channel=$(DEFAULT_CHANNEL)\nendif\nBUNDLE_METADATA_OPTS ?= $(BUNDLE_CHANNELS) $(BUNDLE_DEFAULT_CHANNEL)\n\n# IMAGE_TAG_BASE defines the docker.io namespace and part of the image name for remote images.\n# This variable is used to construct full image tags for bundle and catalog images.\n#\n# For example, running 'make bundle-build bundle-push catalog-build catalog-push' will build and push both\n# mark8s.io/helloworld-operator-bundle:$VERSION and mark8s.io/helloworld-operator-catalog:$VERSION.\nIMAGE_TAG_BASE ?= harbor.cloudtogo.localtest/test/helloworld-operator\n\n# BUNDLE_IMG defines the image:tag used for the bundle.\n# You can use it as an arg. (E.g make bundle-build BUNDLE_IMG=\u003csome-registry\u003e/\u003cproject-name-bundle\u003e:\u003ctag\u003e)\nBUNDLE_IMG ?= $(IMAGE_TAG_BASE)-bundle:v$(VERSION)\n\n# Image URL to use all building/pushing image targets\nIMG ?= ${IMAGE_TAG_BASE}:latest\n# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.\nENVTEST_K8S_VERSION = 1.16\n\n# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)\nifeq (,$(shell go env GOBIN))\nGOBIN=$(shell go env GOPATH)/bin\nelse\nGOBIN=$(shell go env GOBIN)\nendif\n\n# Setting SHELL to bash allows bash commands to be executed by recipes.\n# This is a requirement for 'setup-envtest.sh' in the test target.\n# Options are set to exit when a recipe line exits non-zero or a piped command fails.\nSHELL = /usr/bin/env bash -o pipefail\n.SHELLFLAGS = -ec\n\n.PHONY: all\nall: build\n\n##@ General\n\n# The help target prints out all targets with their descriptions organized\n# beneath their categories. The categories are represented by '##@' and the\n# target descriptions by '##'. The awk commands is responsible for reading the\n# entire set of makefiles included in this invocation, looking for lines of the\n# file as xyz: ## something, and then pretty-format the target and help. Then,\n# if there's a line with ##@ something, that gets pretty-printed as a category.\n# More info on the usage of ANSI control characters for terminal formatting:\n# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters\n# More info on the awk command:\n# http://linuxcommand.org/lc3_adv_awk.php\n\n.PHONY: help\nhelp: ## Display this help.\n\t@awk 'BEGIN {FS = \":.*##\"; printf \"\\nUsage:\\n  make \\033[36m\u003ctarget\u003e\\033[0m\\n\"} /^[a-zA-Z_0-9-]+:.*?##/ { printf \"  \\033[36m%-15s\\033[0m %s\\n\", $$1, $$2 } /^##@/ { printf \"\\n\\033[1m%s\\033[0m\\n\", substr($$0, 5) } ' $(MAKEFILE_LIST)\n\n##@ Development\n\n.PHONY: manifests\nmanifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.\n\t$(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths=\"./...\" output:crd:artifacts:config=config/crd/bases\n\n.PHONY: generate\ngenerate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.\n\t$(CONTROLLER_GEN) object:headerFile=\"hack/boilerplate.go.txt\" paths=\"./...\"\n\n.PHONY: fmt\nfmt: ## Run go fmt against code.\n\tgo fmt ./...\n\n.PHONY: vet\nvet: ## Run go vet against code.\n\tgo vet ./...\n\n.PHONY: test\ntest: manifests generate fmt vet envtest ## Run tests.\n\tKUBEBUILDER_ASSETS=\"$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)\" go test ./... -coverprofile cover.out\n\n##@ Build\n\n.PHONY: build\nbuild: generate fmt vet ## Build manager binary.\n\tgo build -o bin/manager main.go\n\n.PHONY: run\nrun: manifests generate fmt vet ## Run a controller from your host.\n\tgo run ./main.go\n\n.PHONY: docker-build\ndocker-build: test ## Build docker image with the manager.\n\tdocker build -t ${IMG} .\n\n.PHONY: docker-push\ndocker-push: ## Push docker image with the manager.\n\tdocker push ${IMG}\n\n##@ Deployment\n\nifndef ignore-not-found\n  ignore-not-found = false\nendif\n\n.PHONY: install\ninstall: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config.\n\t$(KUSTOMIZE) build config/crd | kubectl apply -f -\n\n.PHONY: uninstall\nuninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.\n\t$(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f -\n\n.PHONY: deploy\ndeploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config.\n\tcd config/manager \u0026\u0026 $(KUSTOMIZE) edit set image controller=${IMG}\n\t$(KUSTOMIZE) build config/default | kubectl apply -f -\n\n.PHONY: undeploy\nundeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.\n\t$(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f -\n\nCONTROLLER_GEN = $(shell pwd)/bin/controller-gen\n.PHONY: controller-gen\ncontroller-gen: ## Download controller-gen locally if necessary.\n\t$(call go-get-tool,$(CONTROLLER_GEN),sigs.k8s.io/controller-tools/cmd/controller-gen@v0.7.0)\n\nKUSTOMIZE = $(shell pwd)/bin/kustomize\n.PHONY: kustomize\nkustomize: ## Download kustomize locally if necessary.\n\t$(call go-get-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/v3@v3.8.7)\n\nENVTEST = $(shell pwd)/bin/setup-envtest\n.PHONY: envtest\nenvtest: ## Download envtest-setup locally if necessary.\n\t$(call go-get-tool,$(ENVTEST),sigs.k8s.io/controller-runtime/tools/setup-envtest@latest)\n\n# go-get-tool will 'go get' any package $2 and install it to $1.\nPROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))\ndefine go-get-tool\n@[ -f $(1) ] || { \\\nset -e ;\\\nTMP_DIR=$$(mktemp -d) ;\\\ncd $$TMP_DIR ;\\\ngo mod init tmp ;\\\necho \"Downloading $(2)\" ;\\\nGOBIN=$(PROJECT_DIR)/bin go get $(2) ;\\\nrm -rf $$TMP_DIR ;\\\n}\nendef\n\n.PHONY: bundle\nbundle: manifests kustomize ## Generate bundle manifests and metadata, then validate generated files.\n\toperator-sdk generate kustomize manifests -q\n\tcd config/manager \u0026\u0026 $(KUSTOMIZE) edit set image controller=$(IMG)\n\t$(KUSTOMIZE) build config/manifests | operator-sdk generate bundle -q --overwrite --version $(VERSION) $(BUNDLE_METADATA_OPTS)\n\toperator-sdk bundle validate ./bundle\n\n.PHONY: bundle-build\nbundle-build: ## Build the bundle image.\n\tdocker build -f bundle.Dockerfile -t $(BUNDLE_IMG) .\n\n.PHONY: bundle-push\nbundle-push: ## Push the bundle image.\n\t$(MAKE) docker-push IMG=$(BUNDLE_IMG)\n\n.PHONY: opm\nOPM = ./bin/opm\nopm: ## Download opm locally if necessary.\nifeq (,$(wildcard $(OPM)))\nifeq (,$(shell which opm 2\u003e/dev/null))\n\t@{ \\\n\tset -e ;\\\n\tmkdir -p $(dir $(OPM)) ;\\\n\tOS=$(shell go env GOOS) \u0026\u0026 ARCH=$(shell go env GOARCH) \u0026\u0026 \\\n\tcurl -sSLo $(OPM) https://github.com/operator-framework/operator-registry/releases/download/v1.19.1/$${OS}-$${ARCH}-opm ;\\\n\tchmod +x $(OPM) ;\\\n\t}\nelse\nOPM = $(shell which opm)\nendif\nendif\n\n# A comma-separated list of bundle images (e.g. make catalog-build BUNDLE_IMGS=example.com/operator-bundle:v0.1.0,example.com/operator-bundle:v0.2.0).\n# These images MUST exist in a registry and be pull-able.\nBUNDLE_IMGS ?= $(BUNDLE_IMG)\n\n# The image tag given to the resulting catalog image (e.g. make catalog-build CATALOG_IMG=example.com/operator-catalog:v0.2.0).\nCATALOG_IMG ?= $(IMAGE_TAG_BASE)-catalog:v$(VERSION)\n\n# Set CATALOG_BASE_IMG to an existing catalog image tag to add $BUNDLE_IMGS to that image.\nifneq ($(origin CATALOG_BASE_IMG), undefined)\nFROM_INDEX_OPT := --from-index $(CATALOG_BASE_IMG)\nendif\n\n# Build a catalog image by adding bundle images to an empty catalog using the operator package manager tool, 'opm'.\n# This recipe invokes 'opm' in 'semver' bundle add mode. For more information on add modes, see:\n# https://github.com/operator-framework/community-operators/blob/7f1438c/docs/packaging-operator.md#updating-your-existing-operator\n.PHONY: catalog-build\ncatalog-build: opm ## Build a catalog image.\n\t$(OPM) index add --container-tool docker --mode semver --tag $(CATALOG_IMG) --bundles $(BUNDLE_IMGS) $(FROM_INDEX_OPT)\n\n# Push the catalog image.\n.PHONY: catalog-push\ncatalog-push: ## Push a catalog image.\n\t$(MAKE) docker-push IMG=$(CATALOG_IMG)\n\n```\n\n与docker build相关内容如下：\n\n```makefile\nIMAGE_TAG_BASE ?= harbor.cloudtogo.localtest/test/helloworld-operator\n# Image URL to use all building/pushing image targets\nIMG ?= ${IMAGE_TAG_BASE}:latest\n\n.PHONY: docker-build\ndocker-build: test ## Build docker image with the manager.\n\tdocker build -t ${IMG} .\n```\n\nharbor.cloudtogo.localtest 是我自己的私有仓库，你要测试的话，得改成自己的。\n\n执行 `make docker-build` , 它会基于目录下的Dockefile进行镜像构建，里面有几个坑需要注意下，Dockerfile的完整内容如下：\n\n```dockerfile\n# Build the manager binary\nFROM golang:1.16 as builder\n\nWORKDIR /workspace\n\n# Copy the Go Modules manifests\nCOPY go.mod go.mod\nCOPY go.sum go.sum\n# cache deps before building and copying source so that we don't need to re-download as much\n# and so that source changes don't invalidate our downloaded layer\nRUN go env -w GO111MODULE=on\nRUN go env -w GOPROXY=https://goproxy.cn,direct\nRUN go mod download\n\n# Copy the go source\nCOPY main.go main.go\nCOPY api/ api/\nCOPY controllers/ controllers/\n\n# Build\nRUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager main.go\n\n# Use distroless as minimal base image to package the manager binary\n# Refer to https://github.com/GoogleContainerTools/distroless for more details\n#FROM gcr.io/distroless/static:nonroot\nFROM katanomi/distroless-static:nonroot\nWORKDIR /\nCOPY --from=builder /workspace/manager .\nUSER 65532:65532\n\nENTRYPOINT [\"/manager\"]\n\n```\n\n（1）编译的时候需要配置goproxy\n\n镜像在build的时候，报了个错，错误为：go: github.com/onsi/ginkgo@v1.16.4: Get “https://proxy.golang.org/github.com/onsi/ginkgo/@v/v1.16.4.\n\n解决就是在 Dockerfile中在go mod download之前加上\n\n```dockerfile\nRUN go env -w GO111MODULE=on\nRUN go env -w GOPROXY=https://goproxy.cn,direct\n```\n\n（2）gcr镜像拉取不到\n\n原 `gcr.io/distroless/static:nonroot` 改为 `katanomi/distroless-static:nonroot`\n\n执行 `make docker-build` 后，镜像就成功的生成到当前虚拟机了。只要使用docker push 就可以推送到镜像仓库了。\n\n![gcr image](./image/gcr-image.png)\n\n### 部署operator\n\n执行 `make deploy` .当然，不可能这么顺利的。我好像遇到了两个错，一个是镜像拉取不到，另一个就是权限的问题\n\n（1）controller-manager的镜像更换\n\n有makefile可知，controller-manager的位置为：config/default/manager_auth_proxy_patch.yaml\n\n更改镜像后的完成内容为\n\n```yaml\n# This patch inject a sidecar container which is a HTTP proxy for the\n# controller manager, it performs RBAC authorization against the Kubernetes API using SubjectAccessReviews.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: controller-manager\n  namespace: system\nspec:\n  template:\n    spec:\n      containers:\n      - name: kube-rbac-proxy\n        image: kubesphere/kube-rbac-proxy:v0.8.0\n        args:\n        - \"--secure-listen-address=0.0.0.0:8443\"\n        - \"--upstream=http://127.0.0.1:8080/\"\n        - \"--logtostderr=true\"\n        - \"--v=10\"\n        ports:\n        - containerPort: 8443\n          protocol: TCP\n          name: https\n      - name: manager\n        args:\n        - \"--health-probe-bind-address=:8081\"\n        - \"--metrics-bind-address=127.0.0.1:8080\"\n        - \"--leader-elect\"\n```\n\n（2）权限问题\n\ndeploy后，效果基本如下：\n\n![deployed](./image/deployed.png)\n\n然后我们创建一个CR，它的位置在：config/samples/hello_v1alpha1_mark.yaml，内容如下\n\n```yaml\napiVersion: hello.mark8s.io/v1alpha1\nkind: Mark\nmetadata:\n  name: mark-sample\n  namespace: helloworld-operator-system\nspec:\n  count: 2\n```\n\n我们使用 kubectl apply -f config/samples/hello_v1alpha1_mark.yaml ，但是发现并没有生成deployment。于是需要查看 pod/helloworld-operator-controller-manager-c598f6dd7-796jr 的日志\n\n```bash\nkubectl logs helloworld-operator-controller-manager-c598f6dd7-796jr -n helloworld-operator-system -c manager\n```\n\n发现报watch deployment等错误\n\n解决这个得去修改controller的代码，位置在：controllers/mark_controller.go\n\n```go\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks/status,verbs=get;update;patch\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=marks/finalizers,verbs=update\n//+kubebuilder:rbac:groups=hello.mark8s.io,resources=deployments,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;\n//+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete\n```\n\n加完，重新执行 `make deploy` 部署就ok了\n\n![finished](./image/finished.png)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmark8s%2Fhelloworld-operator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmark8s%2Fhelloworld-operator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmark8s%2Fhelloworld-operator/lists"}