标签获取
replicaSets获取
deployment 的产生pod流程如下: deployment->replicaSets->pod。
deployment 先产生replicaSets, replicaSets再产生pod。所以我们可以根据以下步骤获取到pod。
- 根据标签获取到replicaSets
- 根据replicaSets ownerReferences字段进行过滤。就可以得到属于某个deployment的replicaset。
- 根据标签获取到pods
- 根据pods ownerReferences字段进行过滤。就可以得到属于某个replicaset的pods。
func (r *Usecase) podsListByDeploymentV2(deployment *appv1.Deployment) ([]v1.Pod, error) { replicaSetSelector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, xerrors.WithStack(err) } replicaSetListOptions := metav1.ListOptions{LabelSelector: replicaSetSelector.String()} allReplicaSets, err := r.k8sClient.AppsV1().ReplicaSets(deployment.Namespace).List(context.TODO(), replicaSetListOptions) if err != nil { return nil, xerrors.WithStack(err) } ownedReplicaSetsUids := make(map[types.UID]struct{}) for i := range allReplicaSets.Items { if !metav1.IsControlledBy(&allReplicaSets.Items[i], deployment) { continue } ownedReplicaSetsUids[allReplicaSets.Items[i].UID] = struct{}{} } podSelector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return nil, xerrors.WithStack(err) } podListOptions := metav1.ListOptions{LabelSelector: podSelector.String()} allPods, err := r.k8sClient.CoreV1().Pods(deployment.Namespace).List(context.TODO(), podListOptions) if err != nil { return nil, xerrors.WithStack(err) } //replicaSetUID := replicaSet.UID rsPods := make([]v1.Pod, 0) for i, pod := range allPods.Items { controllerRef := metav1.GetControllerOf(&allPods.Items[i]) if controllerRef != nil { if _, ok := ownedReplicaSetsUids[controllerRef.UID]; ok { rsPods = append(rsPods, pod) continue } } podStatus := r.k8sRepo.GetPodStatus(&pod) if podStatus.Status == repo.TerminatingStatus { // 终止态的也可以认为属于这个deployment rsPods = append(rsPods, pod) continue } } return rsPods, nil }