---
# System prepended metadata

title: Assignment - Operator
tags: [Assignment, Operator]

---

# Assignment - Operator
###### tags: `Assignment`, `Operator`

## Requirement

+ code-generator v.1.17 (在v1.18時有做更新)
+ Install [metrics-server](https://github.com/kubernetes-sigs/metrics-server)
    + If you have installed [prometheus](https://hackmd.io/bjIo-HRcSOCJzYVyxE4OKg#kube-prometheus) in your cluster, you have done this step.
    + Check
    ```bash
     $ kubectl top pods
    ```
    ![](https://i.imgur.com/x80aYGX.png)
    + You can get the resource Info by calling the metrics api

## Problem Description

在這次作業中，我們要實作一個自定義的Operator，功能是能夠持續蒐集該Pod中所有container的CPU與Memory使用情況

TODO:

+ 新增一個Custom Resource
    + kind: PodMonitor
    + group: lsalab.nthu
    + shortNames: pm
+ 實現Control logic
    + 新增PodMonitor instance, 則啟動一個pm-{podname}
    ![](https://i.imgur.com/A23okMn.png)
    ![](https://i.imgur.com/4mtbzl3.png)
    + 刪除PodMonitor instance, 則刪除對應的pm-{podname}
    ![](https://i.imgur.com/USOLKJF.png)

+ 打包一個image作為pm-{podname}的image
    + 主要用於蒐集該Pod中所有container的CPU與Memory使用情況
        + [Get current resource usage of a pod in Kubernetes with Go client
by calling metrics api](https://stackoverflow.com/questions/52763291/get-current-resource-usage-of-a-pod-in-kubernetes-with-go-client/53032629)
    + CPU與Memory使用情況以檔案與log的形式輸出
  ```bash
  $ kubectl logs {podname}
  ```
  ![](https://i.imgur.com/RWg6IjA.png)

  ```bash
  $ cat {path of volumemount}
  ```
  ![](https://i.imgur.com/Sdy1jYS.png)
+ 配置ServiceAccount
    + 設置ClusterRole:
        + 賦予Operator & image (collect resource info) 管理Pod 和 PodMonitor 的CRUD權限
    + 設置ServiceAccount:
        + 在運行Pod時的身分驗證
        + 為Operator創建ServiceAccount
        + 為image (collect resource info)創建ServiceAccount
    + 設置ClusterRoleBinding
        + 將ServiceAccount與ClusterRole連結起來
:::info
可以參考scheduling framework作業所提供的rbac.yaml
或是下面的Reference
:::

## Reference 

+ 使用client-go自定义开发Kubernetes
https://xuchao918.github.io/2019/02/13/%E4%BD%BF%E7%94%A8client-go%E8%87%AA%E5%AE%9A%E4%B9%89%E5%BC%80%E5%8F%91Kubernetes/
+ How to generate client codes for Kubernetes Custom Resource Definitions (CRD)
https://itnext.io/how-to-generate-client-codes-for-kubernetes-custom-resource-definitions-crd-b4b9907769ba
+ rbac
https://kubernetes.io/docs/reference/access-authn-authz/rbac/
+ sample-controller
https://github.com/kubernetes/sample-controller
+ Programming Kubernetes
https://www.oreilly.com/library/view/programming-kubernetes/9781492047094/
+ Service Account
https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
+ Controller - 動手實作 Kubernetes 自定義控制器
https://k2r2bai.com/tags/Kubernetes/


