Te tuhi i tetahi kaiwhakahaere mo Kubernetes i Golang

Tuhipoka. whakamaori.: Ko nga kaiwhakahaere he raupaparorohiko awhina mo Kubernetes, i hangaia hei whakaaunoa i nga mahi o ia ra ki runga i nga taonga tautau ina puta etahi huihuinga. Kua tuhia e matou mo nga kaiwhakahaere i roto tenei tuhinga, i korero ai ratou mo nga whakaaro me nga maataapono taketake o a raatau mahi. Engari ki te mea he tirohanga ake taua mea mai i te taha o te whakahaere i nga waahanga kua oti te hanga mo Kubernetes, ko te whakamaoritanga o te tuhinga hou e whakaarohia ana inaianei ko te tirohanga a te kaiwhakawhanake/DevOps miihini e pohehe ana i te whakatinanatanga o tetahi kaiwhakahaere hou.

Te tuhi i tetahi kaiwhakahaere mo Kubernetes i Golang

I whakatau ahau ki te tuhi i tenei pou me tetahi tauira tino ora i muri i aku ngana ki te rapu tuhinga mo te hanga i tetahi kaiwhakahaere mo Kubernetes, i haere ma te ako i te waehere.

Ko te tauira ka whakaahuahia ko tenei: i roto i ta maatau roopu Kubernetes, ia Namespace e tohu ana i te taiao pouaka kirikiri o tetahi kapa, a, i pirangi matou ki te whakawhāiti i te uru ki a raatau kia taea ai e nga kapa te purei i o ratou ake pouaka kirikiri anake.

Ka taea e koe te whakatutuki i taau e hiahia ana ma te tautapa ki tetahi kaiwhakamahi he roopu kei a ia RoleBinding ki motuhake Namespace и ClusterRole me nga mana whakatika. Ka penei te ahua o te whakaaturanga YAML:

---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: kubernetes-team-1
  namespace: team-1
subjects:
- kind: Group
  name: kubernetes-team-1
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: edit
apiGroup: rbac.authorization.k8s.io

(rolebinding.yamli roto raw)

Waihangatia tetahi RoleBinding Ka taea e koe te mahi a-ringa, engari i muri i te whakawhiti i nga tohu mokowā ingoa rau, ka waiho hei mahi hoha. I konei ka whai waahi nga kaiwhakahaere Kubernetes—ka taea e koe te whakaaunoa i te hanga rauemi Kubernetes i runga i nga huringa ki nga rauemi. I roto i to maatau e hiahia ana matou ki te hanga RoleBinding i te wa e hanga ana Namespace.

Tuatahi, me tautuhi te mahi maine mahi ana i te tatūnga e hiahiatia ana hei whakahaere i te tauākī kātahi ka karanga i te mahi tauākī:

(Tuhipoka. whakamaori.: i konei me raro ko nga korero i roto i te waehere ka whakamaoritia ki te reo Russian. I tua atu, kua whakatikahia te nuku ki nga mokowā hei utu mo nga ripa [e taunakitia ana ki te Haere] anake kia pai ake te panui i roto i te tahora Habr. I muri i ia rarangi ingoa he hononga ki te taketake i runga i te GitHub, kei reira nga korero me nga ripa reo Ingarihi e rongoa ana.)

func main() {
  // Устанавливаем вывод логов в консольный STDOUT
  log.SetOutput(os.Stdout)

  sigs := make(chan os.Signal, 1) // Создаем канал для получения сигналов ОС
  stop := make(chan struct{})     // Создаем канал для получения стоп-сигнала

  // Регистрируем получение SIGTERM в канале sigs
  signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) 

  // Goroutines могут сами добавлять себя в WaitGroup,
 // чтобы завершения их выполнения дожидались
  wg := &sync.WaitGroup{} 

  runOutsideCluster := flag.Bool("run-outside-cluster", false, "Set this flag when running outside of the cluster.")
  flag.Parse()
  // Создаем clientset для взаимодействия с кластером Kubernetes
  clientset, err := newClientSet(*runOutsideCluster)

  if err != nil {
    panic(err.Error())
  }

  controller.NewNamespaceController(clientset).Run(stop, wg)

  <-sigs // Ждем сигналов (до получения сигнала более ничего не происходит)
  log.Printf("Shutting down...")

  close(stop) // Говорим goroutines остановиться
  wg.Wait()   // Ожидаем, что все остановлено
}

(matua.haerei roto raw)

Ka mahia e matou nga mea e whai ake nei:

  1. Ka whirihorahia e matou he kaihautu mo nga tohu punaha whakahaere motuhake kia pai ai te whakamutua o te kaiwhakahaere.
  2. Ka whakamahia e matou WaitGroupkia pai te whakamutu i nga goroutine katoa i mua i te whakamutu i te tono.
  3. Ka whakaratohia e matou te uru ki te roopu ma te hanga clientset.
  4. Whakarewatanga NamespaceController, kei roto katoa o maatau whakaaro.

Inaianei kei te hiahia tatou i te kaupapa mo te arorau, a, i roto i a maatau koinei te mea kua whakahuahia NamespaceController:

// NamespaceController следит через Kubernetes API за изменениями
// в пространствах имен и создает RoleBinding для конкретного namespace.
type NamespaceController struct {
  namespaceInformer cache.SharedIndexInformer
  kclient           *kubernetes.Clientset
}

// NewNamespaceController создает новый NewNamespaceController
func NewNamespaceController(kclient *kubernetes.Clientset) *NamespaceController {
  namespaceWatcher := &NamespaceController{}

  // Создаем информер для слежения за Namespaces
  namespaceInformer := cache.NewSharedIndexInformer(
    &cache.ListWatch{
      ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
        return kclient.Core().Namespaces().List(options)
      },
      WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
        return kclient.Core().Namespaces().Watch(options)
      },
    },
    &v1.Namespace{},
    3*time.Minute,
    cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
  )

  namespaceInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
    AddFunc: namespaceWatcher.createRoleBinding,
  })

  namespaceWatcher.kclient = kclient
  namespaceWatcher.namespaceInformer = namespaceInformer

  return namespaceWatcher
}

(kaiwhakahaere.haerei roto raw)

I konei ka whirihora tatou SharedIndexInformer, ka tatari tika (ma te keteroki) mo nga huringa o nga waahi ingoa (panui atu mo nga kaiwhakatakoto korero i roto i te tuhinga "Me pehea te mahi a te Kubernetes kaihōtaka?"- āhua. whakamaori.). Whai muri i tenei ka hono tatou EventHandler ki te kai-whakamohio, na ka taapirihia he mokowā ingoa (Namespace) ka karangahia te mahi createRoleBinding.

Ko te mahi e whai ake nei ko te tautuhi i tenei mahi createRoleBinding:

func (c *NamespaceController) createRoleBinding(obj interface{}) {
  namespaceObj := obj.(*v1.Namespace)
  namespaceName := namespaceObj.Name

  roleBinding := &v1beta1.RoleBinding{
    TypeMeta: metav1.TypeMeta{
      Kind:       "RoleBinding",
      APIVersion: "rbac.authorization.k8s.io/v1beta1",
    },
    ObjectMeta: metav1.ObjectMeta{
      Name:      fmt.Sprintf("ad-kubernetes-%s", namespaceName),
      Namespace: namespaceName,
    },
    Subjects: []v1beta1.Subject{
      v1beta1.Subject{
        Kind: "Group",
        Name: fmt.Sprintf("ad-kubernetes-%s", namespaceName),
      },
    },
    RoleRef: v1beta1.RoleRef{
      APIGroup: "rbac.authorization.k8s.io",
        Kind:     "ClusterRole",
        Name:     "edit",
    },
  }

  _, err := c.kclient.Rbac().RoleBindings(namespaceName).Create(roleBinding)

  if err != nil {
    log.Println(fmt.Sprintf("Failed to create Role Binding: %s", err.Error()))
  } else {
    log.Println(fmt.Sprintf("Created AD RoleBinding for Namespace: %s", roleBinding.Name))
  }
}

(kaiwhakahaere.haerei roto raw)

Ka whiwhi tatou i te mokowāingoa hei obj ka huri hei ahanoa Namespace. Na ka tautuhia e matou RoleBinding, i runga i te kōnae YAML i whakahuahia i te timatanga, ma te whakamahi i te ahanoa kua whakaratohia Namespace me te hanga RoleBinding. Ka mutu, ka takiuru tatou mehemea i angitu te hanganga.

Ko te mahi whakamutunga ka tautuhia ko Run:

// Run запускает процесс ожидания изменений в пространствах имён
// и действия в соответствии с этими изменениями.
func (c *NamespaceController) Run(stopCh <-chan struct{}, wg *sync.WaitGroup) {
  // Когда эта функция завершена, пометим как выполненную
  defer wg.Done()

  // Инкрементируем wait group, т.к. собираемся вызвать goroutine
  wg.Add(1)

  // Вызываем goroutine
  go c.namespaceInformer.Run(stopCh)

  // Ожидаем получения стоп-сигнала
  <-stopCh
}

(kaiwhakahaere.haerei roto raw)

Anei e korero ana WaitGroupka whakarewahia te goroutine katahi ka karanga namespaceInformer, kua tautuhia i mua. Ka tae mai te tohu mutu, ka mutu te mahi, whakamohio WaitGroup, kua kore e mahia, ka puta tenei mahi.

Ka kitea nga korero mo te hanga me te whakahaere i tenei tauākī i runga i te kāhui Kubernetes putunga i runga i GitHub.

Ko te mea mo te kaiwhakahaere e hanga ana RoleBinding āhea Namespace i roto i te roopu Kubernetes, kua rite.

Source: will.com

Tāpiri i te kōrero