SlideShare a Scribd company logo
1 of 20
Download to read offline
Kubernetes Internal #8(2021/05/26)
SUDA Kazuki, Preferred Networks, Inc.
@superbrothers
kubectl internal
@superbrothers
!
SUDA Kazuki / @superbrothers
▶ Preferred Networks, Inc. / エンジニア
▶ Kubernetes Meetup Tokyo, Prometheus Meetup Tokyo ほか、共同主催者
▶ Cloud Native Ambassador (CNCF)
▶ 「Kubernetes実践⼊⾨」、「みんなのDocker/Kubernetes」共著書
▶ 「⼊⾨ Prometheus」、「Kubernetes で実践するクラウドネイティブ DevOps」監訳書
2
@superbrothers
!
なぜ実装レベルに関する知⾒・理解を深めたいのか
単純に業務の役⽴つ
▶ 挙動から想像するより実装を⾒たほうが早いこともある
+ オープンソースならソースコードが⾒放題
▶ 壊れていると困るので直ってほしい
+ イシューを作成する次のステップとして⾃分で直しちゃったほうが早いこともある
▶ 使っているソフトウェアに貢献したい
+ 機能追加は議論が必要だったりお作法も難しいがバグ修正は簡単で貢献度も⾼くてオススメ
5
@superbrothers
!
アジェンダ
▶ kubectl の実装を知ろう
▶ ちょっとした不便を kubectl プラグインで解決しよう
6
@superbrothers
!
kubectl delete コマンドを例に
kubectl の実装を知ろう
@superbrothers
!
kubectl
▶ Kubernetes の CLI ツール
▶ 主な役割は kube-apiserver とやり取りしての Kubernetes オブジェクトの取得、作成、変更、削除
+ やり取りには github.com/kubernetes/client-go が使⽤されている
▶ CLI アプリケーションの作成には、github.com/spf13/cobra が使⽤されている
▶ そのほか、github.com/kubernetes/cli-runtime にヘルパ関数がある
8
@superbrothers
!
Worker Node
kube-proxy
kubelet
Container Runtime
OS
ControlPlane Node
etcd
kube-apiserver
kube-controller-manager
kube-scheduler
kubectl
REST
$ kubectl help
kubectl controls the Kubernetes cluster manager.
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
Basic Commands (Beginner):
create Create a resource from a file or from stdin.
expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
run Run a particular image on the cluster
set Set specific features on objects
Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources
edit Edit a resource on the server
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet or Replication Controller
autoscale Auto-scale a Deployment, ReplicaSet, StatefulSet, or ReplicationController
Cluster Management Commands:
certificate Modify certificate resources.
cluster-info Display cluster info
top Display Resource (CPU/Memory) usage.
cordon Mark node as unschedulable
uncordon Mark node as schedulable
drain Drain node in preparation for maintenance
taint Update the taints on one or more nodes
Troubleshooting and Debugging Commands:
describe Show details of a specific resource or group of resources
logs Print the logs for a container in a pod
@superbrothers
!
kubectl delete コマンド
▶ cmd/kubectl/kubectl.go
+ main 関数
▶ staging/src/k8s.io/kubectl/pkg/cmd/cmd.go
+ ルートコマンド(kubectl)の実装
▶ staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go
+ delete サブコマンドの実装
11
type DeleteOptions struct {
...
}
func NewCmdDelete(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
deleteFlags := NewDeleteCommandFlags("containing the resource to delete.")
cmd := &cobra.Command{
Use: "delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)])",
DisableFlagsInUseLine: true,
Short: i18n.T("...."),
Long: deleteLong,
Example: deleteExample,
Run: func(cmd *cobra.Command, args []string) {
o, err := deleteFlags.ToOptions(nil, streams)
cmdutil.CheckErr(err)
cmdutil.CheckErr(o.Complete(f, args, cmd))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.RunDelete(f))
},
SuggestFor: []string{"rm"},
}
deleteFlags.AddFlags(cmd)
cmdutil.AddDryRunFlag(cmd)
return cmd
}
func (o *DeleteOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error {
...
}
func (o *DeleteOptions) Validate() error {
...
}
func (o *DeleteOptions) RunDelete(f cmdutil.Factory) error {
...
}
https://github.com/kubernetes/kubernetes/blob/v1.21.1/staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go
@superbrothers
!
typed client と dynamic client
▶ typed client(型付きクライアント)
+ k8s.io/client-go/kubernetes
+ map[string]interface{} のようなデータ構造を使⽤せずに各 GVK(GroupVersionKind)に
Go の type を使⽤する
+ 使いやすく、型の安全性があり、簡潔で読みやすい
+ ⼀⽅でコンパイル時に型を知っておく必要があり柔軟性がない
▶ dynamic client(動的クライアント)
+ k8s.io/client-go/dynamic
+ Json.Unmarshal の出⼒をラップする unstructured.Unstructured という type のみを使う
+ type に関する情報を開発者が提供する必要がある
+ 様々なリソースを⼀緒くたに扱う場合に有⽤
13
clientset.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})
gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: “deployment"}
client.Resource(gvr).Namespace(namespace).Get(context.TODO, name, metav1.GetOptions{})
@superbrothers
!
ちょっとした不便を
kubectl プラグインで解決しよう
@superbrothers
!
kubectl プラグインとは
▶ kubectl に任意のサブコマンドを追加する機能
▶ Kubernetes が拡張性を重視するなかで CLI ツールの拡張機能として提供されている
▶ ⼀般的に git-style と呼ばれるプラグイン機構を採⽤
+ PATH の通ったディレクトリに配置された実⾏ファイルの名前が特定のプレフィックスで
開始しているものを呼び出す
+ kubectl プラグインの場合はプレフィックスが「kubectl-」
15
$ kubectl plugin list
The following compatible plugins are available:
/home/ksuda/.krew/bin/kubectl-images
/home/ksuda/.krew/bin/kubectl-krew
/home/ksuda/.krew/bin/kubectl-open_svc
/home/ksuda/.krew/bin/kubectl-rolesum
/home/ksuda/.krew/bin/kubectl-tree
/home/ksuda/.krew/bin/kubectl-view_secret
/home/ksuda/.krew/bin/kubectl-view_serviceaccount_kubeconfig
@superbrothers
!
kubectl プラグインをつくる
▶ kubectl コマンドの出⼒をレインボーにする🌈
16
$ cat <<EOL > kubectl-lol
#!/usr/bin/env bash
exec kubectl "$@" | lolcat
EOL
$ chmod +x kubectl-lol
$ mv kubectl-lol /usr/local/bin/
$ kubectl lol get po -A
@superbrothers
!
kubectl のプラグイン機構
▶ cmd/kubectl/kubectl.go
+ main 関数
▶ staging/src/k8s.io/kubectl/pkg/cmd/cmd.go
+ ルートコマンドが呼び出される前に kubectl に存在しておらず「kubectl-」プレフィックスを
つけた名前を持つ実⾏ファイルが存在していれば実⾏
17
@superbrothers
!
kubectl way なプラグインをつくるのに便利なライブラリ
▶ k8s.io/cli-runtime
+ —kubeconfig や —context、—output などのフラグをサポート
▶ k8s.io/kubectl
+ kubectl の内部で使われている便利関数などが使える
そのほか、https://github.com/kubernetes/sample-cli-plugin が参考になる。
18
@superbrothers
!
kubectl プラグインを配布する
▶ kubectl plugin マネージャ Krew
+ プラグインマネージャで、インデックスに登録されたプラグインをインストール、管理できる
+ これ⾃体も kubectl プラグインとして実装されている
+ インデックスリポジトリ: https://github.com/kubernetes-sigs/krew-index
+ カスタムインデックス機能もある
+ https://krew.sigs.k8s.io/docs/user-guide/custom-indexes/
▶ Homebrew
+ 信頼と実績
19
@superbrothers
!
Thanks / Question?
▶ SUDA Kazuki, @superbrothers
▶ Slide: https://speakerdeck.com/superbrothers/
20

More Related Content

What's hot

What's hot (20)

CuPy v4 and v5 roadmap
CuPy v4 and v5 roadmapCuPy v4 and v5 roadmap
CuPy v4 and v5 roadmap
 
Chainer v4 and v5
Chainer v4 and v5Chainer v4 and v5
Chainer v4 and v5
 
Applying of the NVIDIA CUDA to the video processing in the task of the roundw...
Applying of the NVIDIA CUDA to the video processing in the task of the roundw...Applying of the NVIDIA CUDA to the video processing in the task of the roundw...
Applying of the NVIDIA CUDA to the video processing in the task of the roundw...
 
Parallel Implementation of K Means Clustering on CUDA
Parallel Implementation of K Means Clustering on CUDAParallel Implementation of K Means Clustering on CUDA
Parallel Implementation of K Means Clustering on CUDA
 
[AI07] Revolutionizing Image Processing with Cognitive Toolkit
[AI07] Revolutionizing Image Processing with Cognitive Toolkit[AI07] Revolutionizing Image Processing with Cognitive Toolkit
[AI07] Revolutionizing Image Processing with Cognitive Toolkit
 
Cloud Services - Gluecon 2010
Cloud Services - Gluecon 2010Cloud Services - Gluecon 2010
Cloud Services - Gluecon 2010
 
Using Docker for GPU Accelerated Applications
Using Docker for GPU Accelerated ApplicationsUsing Docker for GPU Accelerated Applications
Using Docker for GPU Accelerated Applications
 
PL/CUDA - Fusion of HPC Grade Power with In-Database Analytics
PL/CUDA - Fusion of HPC Grade Power with In-Database AnalyticsPL/CUDA - Fusion of HPC Grade Power with In-Database Analytics
PL/CUDA - Fusion of HPC Grade Power with In-Database Analytics
 
A Look Inside Google’s Data Center Networks
A Look Inside Google’s Data Center NetworksA Look Inside Google’s Data Center Networks
A Look Inside Google’s Data Center Networks
 
1101: GRID 技術セッション 2:vGPU Sizing
1101: GRID 技術セッション 2:vGPU Sizing1101: GRID 技術セッション 2:vGPU Sizing
1101: GRID 技術セッション 2:vGPU Sizing
 
TensorFlow Wide and Deep Model
TensorFlow Wide and Deep ModelTensorFlow Wide and Deep Model
TensorFlow Wide and Deep Model
 
Introduction to GPUs in HPC
Introduction to GPUs in HPCIntroduction to GPUs in HPC
Introduction to GPUs in HPC
 
Taking Your Database Beyond the Border of a Single Kubernetes Cluster
Taking Your Database Beyond the Border of a Single Kubernetes ClusterTaking Your Database Beyond the Border of a Single Kubernetes Cluster
Taking Your Database Beyond the Border of a Single Kubernetes Cluster
 
PCCC21:日本電気株式会社「一台何役?SX-Aurora TSUBASA最新情報」
PCCC21:日本電気株式会社「一台何役?SX-Aurora TSUBASA最新情報」PCCC21:日本電気株式会社「一台何役?SX-Aurora TSUBASA最新情報」
PCCC21:日本電気株式会社「一台何役?SX-Aurora TSUBASA最新情報」
 
RAPIDS Overview
RAPIDS OverviewRAPIDS Overview
RAPIDS Overview
 
HPC on OpenStack
HPC on OpenStackHPC on OpenStack
HPC on OpenStack
 
High Performance Cloud Computing
High Performance Cloud ComputingHigh Performance Cloud Computing
High Performance Cloud Computing
 
第11回 配信講義 計算科学技術特論A(2021)
第11回 配信講義 計算科学技術特論A(2021)第11回 配信講義 計算科学技術特論A(2021)
第11回 配信講義 計算科学技術特論A(2021)
 
MEW22 22nd Machine Evaluation Workshop Microsoft
MEW22 22nd Machine Evaluation Workshop MicrosoftMEW22 22nd Machine Evaluation Workshop Microsoft
MEW22 22nd Machine Evaluation Workshop Microsoft
 
Microsoft Azure in HPC scenarios
Microsoft Azure in HPC scenariosMicrosoft Azure in HPC scenarios
Microsoft Azure in HPC scenarios
 

Similar to kubectl internal / Kubernetes Internal #8

Similar to kubectl internal / Kubernetes Internal #8 (20)

Docker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshopDocker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshop
 
Kubernetes Operability Tooling (GOTO Chicago 2019)
Kubernetes Operability Tooling (GOTO Chicago 2019)Kubernetes Operability Tooling (GOTO Chicago 2019)
Kubernetes Operability Tooling (GOTO Chicago 2019)
 
Container Deployment and Management with kubernetes
Container Deployment and Management with kubernetesContainer Deployment and Management with kubernetes
Container Deployment and Management with kubernetes
 
Keynote #Tech - Google : aperçu de la gestion des services distribués chez Go...
Keynote #Tech - Google : aperçu de la gestion des services distribués chez Go...Keynote #Tech - Google : aperçu de la gestion des services distribués chez Go...
Keynote #Tech - Google : aperçu de la gestion des services distribués chez Go...
 
Learn kubernetes in 90 minutes
Learn kubernetes in 90 minutesLearn kubernetes in 90 minutes
Learn kubernetes in 90 minutes
 
Improving the Accumulo User Experience
 Improving the Accumulo User Experience Improving the Accumulo User Experience
Improving the Accumulo User Experience
 
An Ensemble Core with Docker - Solving a Real Pain in the PaaS
An Ensemble Core with Docker - Solving a Real Pain in the PaaS An Ensemble Core with Docker - Solving a Real Pain in the PaaS
An Ensemble Core with Docker - Solving a Real Pain in the PaaS
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
Kubernetes + Python = ❤ - Cloud Native Prague
Kubernetes + Python = ❤ - Cloud Native PragueKubernetes + Python = ❤ - Cloud Native Prague
Kubernetes + Python = ❤ - Cloud Native Prague
 
Slides - Kubernetes on GKE.pdf
Slides - Kubernetes on GKE.pdfSlides - Kubernetes on GKE.pdf
Slides - Kubernetes on GKE.pdf
 
Acquia BLT for the Win, or How to speed up the project setup, development an...
Acquia BLT for the Win, or  How to speed up the project setup, development an...Acquia BLT for the Win, or  How to speed up the project setup, development an...
Acquia BLT for the Win, or How to speed up the project setup, development an...
 
Kubernetes Basis: Pods, Deployments, and Services
Kubernetes Basis: Pods, Deployments, and ServicesKubernetes Basis: Pods, Deployments, and Services
Kubernetes Basis: Pods, Deployments, and Services
 
Kubernetes - Sailing a Sea of Containers
Kubernetes - Sailing a Sea of ContainersKubernetes - Sailing a Sea of Containers
Kubernetes - Sailing a Sea of Containers
 
pyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfpyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdf
 
Deploy the blockchain network using kubernetes ap is on google cloud
Deploy the blockchain network using kubernetes ap is on google cloudDeploy the blockchain network using kubernetes ap is on google cloud
Deploy the blockchain network using kubernetes ap is on google cloud
 
Learning Docker with Thomas
Learning Docker with ThomasLearning Docker with Thomas
Learning Docker with Thomas
 
Docker as an every day work tool
Docker as an every day work toolDocker as an every day work tool
Docker as an every day work tool
 
5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CI5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CI
 
YEGOR MAKSYMCHUK «Using Kubernetes for organization performance tests»
YEGOR MAKSYMCHUK «Using Kubernetes for organization performance tests»YEGOR MAKSYMCHUK «Using Kubernetes for organization performance tests»
YEGOR MAKSYMCHUK «Using Kubernetes for organization performance tests»
 
Check the version with fixes. Link in description
Check the version with fixes. Link in descriptionCheck the version with fixes. Link in description
Check the version with fixes. Link in description
 

More from Preferred Networks

More from Preferred Networks (20)

PodSecurityPolicy からGatekeeper に移行しました / Kubernetes Meetup Tokyo #57
PodSecurityPolicy からGatekeeper に移行しました / Kubernetes Meetup Tokyo #57PodSecurityPolicy からGatekeeper に移行しました / Kubernetes Meetup Tokyo #57
PodSecurityPolicy からGatekeeper に移行しました / Kubernetes Meetup Tokyo #57
 
Optunaを使ったHuman-in-the-loop最適化の紹介 - 2023/04/27 W&B 東京ミートアップ #3
Optunaを使ったHuman-in-the-loop最適化の紹介 - 2023/04/27 W&B 東京ミートアップ #3Optunaを使ったHuman-in-the-loop最適化の紹介 - 2023/04/27 W&B 東京ミートアップ #3
Optunaを使ったHuman-in-the-loop最適化の紹介 - 2023/04/27 W&B 東京ミートアップ #3
 
Kubernetes + containerd で cgroup v2 に移行したら "failed to create fsnotify watcher...
Kubernetes + containerd で cgroup v2 に移行したら "failed to create fsnotify watcher...Kubernetes + containerd で cgroup v2 に移行したら "failed to create fsnotify watcher...
Kubernetes + containerd で cgroup v2 に移行したら "failed to create fsnotify watcher...
 
深層学習の新しい応用と、 それを支える計算機の進化 - Preferred Networks CEO 西川徹 (SEMICON Japan 2022 Ke...
深層学習の新しい応用と、 それを支える計算機の進化 - Preferred Networks CEO 西川徹 (SEMICON Japan 2022 Ke...深層学習の新しい応用と、 それを支える計算機の進化 - Preferred Networks CEO 西川徹 (SEMICON Japan 2022 Ke...
深層学習の新しい応用と、 それを支える計算機の進化 - Preferred Networks CEO 西川徹 (SEMICON Japan 2022 Ke...
 
Kubernetes ControllerをScale-Outさせる方法 / Kubernetes Meetup Tokyo #55
Kubernetes ControllerをScale-Outさせる方法 / Kubernetes Meetup Tokyo #55Kubernetes ControllerをScale-Outさせる方法 / Kubernetes Meetup Tokyo #55
Kubernetes ControllerをScale-Outさせる方法 / Kubernetes Meetup Tokyo #55
 
Kaggle Happywhaleコンペ優勝解法でのOptuna使用事例 - 2022/12/10 Optuna Meetup #2
Kaggle Happywhaleコンペ優勝解法でのOptuna使用事例 - 2022/12/10 Optuna Meetup #2Kaggle Happywhaleコンペ優勝解法でのOptuna使用事例 - 2022/12/10 Optuna Meetup #2
Kaggle Happywhaleコンペ優勝解法でのOptuna使用事例 - 2022/12/10 Optuna Meetup #2
 
最新リリース:Optuna V3の全て - 2022/12/10 Optuna Meetup #2
最新リリース:Optuna V3の全て - 2022/12/10 Optuna Meetup #2最新リリース:Optuna V3の全て - 2022/12/10 Optuna Meetup #2
最新リリース:Optuna V3の全て - 2022/12/10 Optuna Meetup #2
 
Optuna Dashboardの紹介と設計解説 - 2022/12/10 Optuna Meetup #2
Optuna Dashboardの紹介と設計解説 - 2022/12/10 Optuna Meetup #2Optuna Dashboardの紹介と設計解説 - 2022/12/10 Optuna Meetup #2
Optuna Dashboardの紹介と設計解説 - 2022/12/10 Optuna Meetup #2
 
スタートアップが提案する2030年の材料開発 - 2022/11/11 QPARC講演
スタートアップが提案する2030年の材料開発 - 2022/11/11 QPARC講演スタートアップが提案する2030年の材料開発 - 2022/11/11 QPARC講演
スタートアップが提案する2030年の材料開発 - 2022/11/11 QPARC講演
 
Deep Learningのための専用プロセッサ「MN-Core」の開発と活用(2022/10/19東大大学院「 融合情報学特別講義Ⅲ」)
Deep Learningのための専用プロセッサ「MN-Core」の開発と活用(2022/10/19東大大学院「 融合情報学特別講義Ⅲ」)Deep Learningのための専用プロセッサ「MN-Core」の開発と活用(2022/10/19東大大学院「 融合情報学特別講義Ⅲ」)
Deep Learningのための専用プロセッサ「MN-Core」の開発と活用(2022/10/19東大大学院「 融合情報学特別講義Ⅲ」)
 
PFNにおける研究開発(2022/10/19 東大大学院「融合情報学特別講義Ⅲ」)
PFNにおける研究開発(2022/10/19 東大大学院「融合情報学特別講義Ⅲ」)PFNにおける研究開発(2022/10/19 東大大学院「融合情報学特別講義Ⅲ」)
PFNにおける研究開発(2022/10/19 東大大学院「融合情報学特別講義Ⅲ」)
 
自然言語処理を 役立てるのはなぜ難しいのか(2022/10/25東大大学院「自然言語処理応用」)
自然言語処理を 役立てるのはなぜ難しいのか(2022/10/25東大大学院「自然言語処理応用」)自然言語処理を 役立てるのはなぜ難しいのか(2022/10/25東大大学院「自然言語処理応用」)
自然言語処理を 役立てるのはなぜ難しいのか(2022/10/25東大大学院「自然言語処理応用」)
 
Kubernetes にこれから入るかもしれない注目機能!(2022年11月版) / TechFeed Experts Night #7 〜 コンテナ技術を語る
Kubernetes にこれから入るかもしれない注目機能!(2022年11月版) / TechFeed Experts Night #7 〜 コンテナ技術を語るKubernetes にこれから入るかもしれない注目機能!(2022年11月版) / TechFeed Experts Night #7 〜 コンテナ技術を語る
Kubernetes にこれから入るかもしれない注目機能!(2022年11月版) / TechFeed Experts Night #7 〜 コンテナ技術を語る
 
Matlantis™のニューラルネットワークポテンシャルPFPの適用範囲拡張
Matlantis™のニューラルネットワークポテンシャルPFPの適用範囲拡張Matlantis™のニューラルネットワークポテンシャルPFPの適用範囲拡張
Matlantis™のニューラルネットワークポテンシャルPFPの適用範囲拡張
 
PFNのオンプレ計算機クラスタの取り組み_第55回情報科学若手の会
PFNのオンプレ計算機クラスタの取り組み_第55回情報科学若手の会PFNのオンプレ計算機クラスタの取り組み_第55回情報科学若手の会
PFNのオンプレ計算機クラスタの取り組み_第55回情報科学若手の会
 
続・PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜 #2
続・PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜 #2続・PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜 #2
続・PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜 #2
 
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
Kubernetes Service Account As Multi-Cloud Identity / Cloud Native Security Co...
 
KubeCon + CloudNativeCon Europe 2022 Recap / Kubernetes Meetup Tokyo #51 / #k...
KubeCon + CloudNativeCon Europe 2022 Recap / Kubernetes Meetup Tokyo #51 / #k...KubeCon + CloudNativeCon Europe 2022 Recap / Kubernetes Meetup Tokyo #51 / #k...
KubeCon + CloudNativeCon Europe 2022 Recap / Kubernetes Meetup Tokyo #51 / #k...
 
KubeCon + CloudNativeCon Europe 2022 Recap - Batch/HPCの潮流とScheduler拡張事例 / Kub...
KubeCon + CloudNativeCon Europe 2022 Recap - Batch/HPCの潮流とScheduler拡張事例 / Kub...KubeCon + CloudNativeCon Europe 2022 Recap - Batch/HPCの潮流とScheduler拡張事例 / Kub...
KubeCon + CloudNativeCon Europe 2022 Recap - Batch/HPCの潮流とScheduler拡張事例 / Kub...
 
独断と偏見で選んだ Kubernetes 1.24 の注目機能と今後! / Kubernetes Meetup Tokyo 50
独断と偏見で選んだ Kubernetes 1.24 の注目機能と今後! / Kubernetes Meetup Tokyo 50独断と偏見で選んだ Kubernetes 1.24 の注目機能と今後! / Kubernetes Meetup Tokyo 50
独断と偏見で選んだ Kubernetes 1.24 の注目機能と今後! / Kubernetes Meetup Tokyo 50
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

kubectl internal / Kubernetes Internal #8

  • 1. Kubernetes Internal #8(2021/05/26) SUDA Kazuki, Preferred Networks, Inc. @superbrothers kubectl internal
  • 2. @superbrothers ! SUDA Kazuki / @superbrothers ▶ Preferred Networks, Inc. / エンジニア ▶ Kubernetes Meetup Tokyo, Prometheus Meetup Tokyo ほか、共同主催者 ▶ Cloud Native Ambassador (CNCF) ▶ 「Kubernetes実践⼊⾨」、「みんなのDocker/Kubernetes」共著書 ▶ 「⼊⾨ Prometheus」、「Kubernetes で実践するクラウドネイティブ DevOps」監訳書 2
  • 3.
  • 4.
  • 5. @superbrothers ! なぜ実装レベルに関する知⾒・理解を深めたいのか 単純に業務の役⽴つ ▶ 挙動から想像するより実装を⾒たほうが早いこともある + オープンソースならソースコードが⾒放題 ▶ 壊れていると困るので直ってほしい + イシューを作成する次のステップとして⾃分で直しちゃったほうが早いこともある ▶ 使っているソフトウェアに貢献したい + 機能追加は議論が必要だったりお作法も難しいがバグ修正は簡単で貢献度も⾼くてオススメ 5
  • 6. @superbrothers ! アジェンダ ▶ kubectl の実装を知ろう ▶ ちょっとした不便を kubectl プラグインで解決しよう 6
  • 8. @superbrothers ! kubectl ▶ Kubernetes の CLI ツール ▶ 主な役割は kube-apiserver とやり取りしての Kubernetes オブジェクトの取得、作成、変更、削除 + やり取りには github.com/kubernetes/client-go が使⽤されている ▶ CLI アプリケーションの作成には、github.com/spf13/cobra が使⽤されている ▶ そのほか、github.com/kubernetes/cli-runtime にヘルパ関数がある 8
  • 9. @superbrothers ! Worker Node kube-proxy kubelet Container Runtime OS ControlPlane Node etcd kube-apiserver kube-controller-manager kube-scheduler kubectl REST
  • 10. $ kubectl help kubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/ Basic Commands (Beginner): create Create a resource from a file or from stdin. expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service run Run a particular image on the cluster set Set specific features on objects Basic Commands (Intermediate): explain Documentation of resources get Display one or many resources edit Edit a resource on the server delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource scale Set a new size for a Deployment, ReplicaSet or Replication Controller autoscale Auto-scale a Deployment, ReplicaSet, StatefulSet, or ReplicationController Cluster Management Commands: certificate Modify certificate resources. cluster-info Display cluster info top Display Resource (CPU/Memory) usage. cordon Mark node as unschedulable uncordon Mark node as schedulable drain Drain node in preparation for maintenance taint Update the taints on one or more nodes Troubleshooting and Debugging Commands: describe Show details of a specific resource or group of resources logs Print the logs for a container in a pod
  • 11. @superbrothers ! kubectl delete コマンド ▶ cmd/kubectl/kubectl.go + main 関数 ▶ staging/src/k8s.io/kubectl/pkg/cmd/cmd.go + ルートコマンド(kubectl)の実装 ▶ staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go + delete サブコマンドの実装 11
  • 12. type DeleteOptions struct { ... } func NewCmdDelete(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command { deleteFlags := NewDeleteCommandFlags("containing the resource to delete.") cmd := &cobra.Command{ Use: "delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)])", DisableFlagsInUseLine: true, Short: i18n.T("...."), Long: deleteLong, Example: deleteExample, Run: func(cmd *cobra.Command, args []string) { o, err := deleteFlags.ToOptions(nil, streams) cmdutil.CheckErr(err) cmdutil.CheckErr(o.Complete(f, args, cmd)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.RunDelete(f)) }, SuggestFor: []string{"rm"}, } deleteFlags.AddFlags(cmd) cmdutil.AddDryRunFlag(cmd) return cmd } func (o *DeleteOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error { ... } func (o *DeleteOptions) Validate() error { ... } func (o *DeleteOptions) RunDelete(f cmdutil.Factory) error { ... } https://github.com/kubernetes/kubernetes/blob/v1.21.1/staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go
  • 13. @superbrothers ! typed client と dynamic client ▶ typed client(型付きクライアント) + k8s.io/client-go/kubernetes + map[string]interface{} のようなデータ構造を使⽤せずに各 GVK(GroupVersionKind)に Go の type を使⽤する + 使いやすく、型の安全性があり、簡潔で読みやすい + ⼀⽅でコンパイル時に型を知っておく必要があり柔軟性がない ▶ dynamic client(動的クライアント) + k8s.io/client-go/dynamic + Json.Unmarshal の出⼒をラップする unstructured.Unstructured という type のみを使う + type に関する情報を開発者が提供する必要がある + 様々なリソースを⼀緒くたに扱う場合に有⽤ 13 clientset.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{}) gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: “deployment"} client.Resource(gvr).Namespace(namespace).Get(context.TODO, name, metav1.GetOptions{})
  • 15. @superbrothers ! kubectl プラグインとは ▶ kubectl に任意のサブコマンドを追加する機能 ▶ Kubernetes が拡張性を重視するなかで CLI ツールの拡張機能として提供されている ▶ ⼀般的に git-style と呼ばれるプラグイン機構を採⽤ + PATH の通ったディレクトリに配置された実⾏ファイルの名前が特定のプレフィックスで 開始しているものを呼び出す + kubectl プラグインの場合はプレフィックスが「kubectl-」 15 $ kubectl plugin list The following compatible plugins are available: /home/ksuda/.krew/bin/kubectl-images /home/ksuda/.krew/bin/kubectl-krew /home/ksuda/.krew/bin/kubectl-open_svc /home/ksuda/.krew/bin/kubectl-rolesum /home/ksuda/.krew/bin/kubectl-tree /home/ksuda/.krew/bin/kubectl-view_secret /home/ksuda/.krew/bin/kubectl-view_serviceaccount_kubeconfig
  • 16. @superbrothers ! kubectl プラグインをつくる ▶ kubectl コマンドの出⼒をレインボーにする🌈 16 $ cat <<EOL > kubectl-lol #!/usr/bin/env bash exec kubectl "$@" | lolcat EOL $ chmod +x kubectl-lol $ mv kubectl-lol /usr/local/bin/ $ kubectl lol get po -A
  • 17. @superbrothers ! kubectl のプラグイン機構 ▶ cmd/kubectl/kubectl.go + main 関数 ▶ staging/src/k8s.io/kubectl/pkg/cmd/cmd.go + ルートコマンドが呼び出される前に kubectl に存在しておらず「kubectl-」プレフィックスを つけた名前を持つ実⾏ファイルが存在していれば実⾏ 17
  • 18. @superbrothers ! kubectl way なプラグインをつくるのに便利なライブラリ ▶ k8s.io/cli-runtime + —kubeconfig や —context、—output などのフラグをサポート ▶ k8s.io/kubectl + kubectl の内部で使われている便利関数などが使える そのほか、https://github.com/kubernetes/sample-cli-plugin が参考になる。 18
  • 19. @superbrothers ! kubectl プラグインを配布する ▶ kubectl plugin マネージャ Krew + プラグインマネージャで、インデックスに登録されたプラグインをインストール、管理できる + これ⾃体も kubectl プラグインとして実装されている + インデックスリポジトリ: https://github.com/kubernetes-sigs/krew-index + カスタムインデックス機能もある + https://krew.sigs.k8s.io/docs/user-guide/custom-indexes/ ▶ Homebrew + 信頼と実績 19
  • 20. @superbrothers ! Thanks / Question? ▶ SUDA Kazuki, @superbrothers ▶ Slide: https://speakerdeck.com/superbrothers/ 20