天天看點

Kubernetes必備知識: Selectors

所屬技術領域:

K8s

|名詞定義|

Label不是唯一的,很多object可能有相同的label。

通過label selector,用戶端/使用者可以指定一個object集合,通過label selector對object的集合進行操作。

|技術特點|

 Label selector的例子

最常見的 Selector 就是相等型 Selector。現在舉一個簡單的例子:

假設系統中有四個 Pod,每個 Pod 都有辨別系統層級和環境的标簽,我們通過 Tie:front 這個标簽,可以比對左邊欄的 Pod,相等型 Selector 還可以包括多個相等條件,多個相等條件之間是邏輯”與“的關系。

在剛才的例子中,通過 Tie=front,Env=dev 的 Selector,我們可以篩選出所有 Tie=front,而且 Env=dev 的 Pod,也就是下圖中左上角的 Pod。另外一種 Selector 是集合型 Selector,在例子中,Selector 篩選所有環境是 test 或者 gray 的 Pod。

除了 in 的集合操作外,還有 notin 集合操作,比如 tie notin(front,back),将會篩選所有 tie 不是 front 且不是 back 的 Pod。另外,也可以根據是否存在某 lable 的篩選,如:Selector release,篩選所有帶 release 标簽的 Pod。集合型和相等型的 Selector,也可以用“,”來連接配接,同樣的辨別邏輯”與“的關系。

 Label selector的類型

Label selector有兩種類型:

equality-based :可以使用=、==、!=操作符,可以使用逗号分隔多個表達式

set-based :可以使用in、notin、!操作符,另外還可以沒有操作符,直接寫出某個label的key,表示過濾有某個key的object而不管該key的value是何值,!表示沒有該label的object

使用

1.kubectl get pods -l environment=production,tier=frontend

2.kubectl get pods -l 'environment in (production, qa)'

 API使用 label selector

1.在service、replicationcontroller等object中有對pod的label selector,使用方法隻能使用等于操作,例如:

selector:

component: redis           

2.Job, Deployment, Replica Set, Daemon Set 類型支援set-based 操作

matchLabels:

component: redis           

matchExpressions:

- {key: tier, operator: In, values: [cache]}
- {key: environment, operator: NotIn, values: [dev]}           

matchlabels是{key,value}對的映射。matchlabels映射中的單個{key,value}等價于matchexpressions的元素,其鍵字段為“key”,運算符為“in”,值數組僅包含“value”。matchexpressions是pod選擇器需求的清單。有效的運算符包括in、notin、exists和doesnotexist。對于in和notin,設定的值必須為非空。matchlabels和matchexpressions中的所有要求都被放在一起-必須滿足所有這些要求才能比對

 Label Selector的表達式

目前有兩種Label Selector的表達式:基于等式的(Equality-based)和基于集合(Set-based)。

基于等式的表達式比對标簽執行個體:

• name=redis-slave:比對所有具有标簽name=redis-slave的資源對象。

• env!=production: 比對不具有标簽name=production的資源對象。

基于集合方式的表達式比對标簽執行個體:

• name in (redis-slave, redis-master):比對所有具有标簽name=redis-slave或name=redis-master的資源對象。

• name not in (php-frontend):比對不具有标簽name=php-frontend的資源對象。

可以通過多個Label Selector表達式的組合實作複雜的條件選擇,多個表達式之間用“,”分隔即可,幾個條件是and的關系,即同時滿足多個條件,如:

• name=redis-slave, env!=production

• name not in (php-frontend), env!=production

Label Selector在k8s中重要使用場景有下面幾處:

• kube-controller-manage程序通過資源對象RC上定義的Label Selector來篩選要監控的Pod副本的數量。

• kube-proxy程序通過Service的Label Selector來選擇對于那個的Pod,自動建立起Service對應每個Pod的請求轉發路由表,進而實作Service的智能負載均衡機制。

• 通過對某些Node定義特定的Label,并且Pod定義檔案中使用NodeSelector這種标簽排程政策,kube-schedule程序可以實作Pod“定向排程”的特性。

|資料來源|

名詞定義:

https://blog.csdn.net/textdemo123/article/details/101774622

技術特點:

https://www.jianshu.com/p/edd3c243c894

繼續閱讀