Skip to content

Commit

Permalink
fix: quit minikube service when there is no available pods
Browse files Browse the repository at this point in the history
  • Loading branch information
ComradeProgrammer committed Mar 2, 2023
1 parent aca5f29 commit 69d1127
Show file tree
Hide file tree
Showing 15 changed files with 106 additions and 0 deletions.
8 changes: 8 additions & 0 deletions cmd/minikube/cmd/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,14 @@ You may select another namespace by using 'minikube service {{.service}} -n <nam
out.String(fmt.Sprintf("%s\n", serviceURLs))
}
}
// check whether all pods of this service is crashed
clientset, err := kapi.Client(cname)
if err != nil {
exit.Error(reason.InternalKubernetesClient, "Failed to acquire Kubernetes client", err)
}
if err := service.CheckServicePods(clientset.CoreV1(), svc.Name, namespace); err != nil {
exit.Error(reason.SvcUnreachable, "error checking service", err)
}
}

if driver.NeedsPortForward(co.Config.Driver) && services != nil {
Expand Down
2 changes: 2 additions & 0 deletions pkg/minikube/reason/reason.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,8 @@ var (
SvcCheckTimeout = Kind{ID: "SVC_CHECK_TIMEOUT", ExitCode: ExSvcTimeout}
// minikube was unable to access a service
SvcTimeout = Kind{ID: "SVC_TIMEOUT", ExitCode: ExSvcTimeout}
// minikube finds that the service has not available pods
SvcUnreachable = Kind{ID: "SVC_UNREACHABLE", ExitCode: ExSvcNotFound}
// minikube failed to list services for the specified namespace
SvcList = Kind{ID: "SVC_LIST", ExitCode: ExSvcError}
// minikube failed to start a tunnel
Expand Down
28 changes: 28 additions & 0 deletions pkg/minikube/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,31 @@ func DeleteSecret(cname string, namespace, name string) error {

return nil
}

// check whether there are running pods for a service
func CheckServicePods(clientset typed_core.CoreV1Interface, svcName, namespace string) error {
svc, err := clientset.Services(namespace).Get(context.Background(), svcName, meta.GetOptions{})
if err != nil {
return errors.Wrap(err, "Get service")
}
// There are four types of service in k8s: NodePort, ClusterIp, LoadBalancer and ExternalName
// However, NodePort means that this service will not be exposed outside the cluster
// while ExternalName means that this service is not provided by this k8s cluster
// So we only check when service type is NodePort or LoadBalancer
if svc.Spec.Type != core.ServiceTypeNodePort && svc.Spec.Type != core.ServiceTypeLoadBalancer {
return nil
}
pods, err := clientset.Pods(namespace).List(context.Background(), meta.ListOptions{
LabelSelector: labels.Set(svc.Spec.Selector).AsSelector().String(),
})
if err != nil {
return errors.Wrap(err, "List Pods")
}

for _, pod := range pods.Items {
if pod.Status.Phase == core.PodRunning {
return nil
}
}
return fmt.Errorf("no valid pod for service %s found", svcName)
}
3 changes: 3 additions & 0 deletions site/content/en/docs/contrib/tests.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,9 @@ verifies that minikube pause works
## TestInsufficientStorage
makes sure minikube status displays the correct info if there is insufficient disk space on the machine

## TestInvalidService
makes sure minikube will not start a tunnel for a unavailable service who has no running pods

## TestRunningBinaryUpgrade
upgrades a running legacy cluster to minikube at HEAD

Expand Down
25 changes: 25 additions & 0 deletions test/integration/functional_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ func TestFunctional(t *testing.T) {
{"ComponentHealth", validateComponentHealth},
{"LogsCmd", validateLogsCmd},
{"LogsFileCmd", validateLogsFileCmd},
{"InvalidService", validInvalidService},
}
for _, tc := range tests {
tc := tc
Expand Down Expand Up @@ -2207,3 +2208,27 @@ func validateVersionCmd(ctx context.Context, t *testing.T, profile string) {
})

}

// validInvalidService makes sure minikube will not start a tunnel for a unavailable service who has no running pods
func validInvalidService(ctx context.Context, t *testing.T, profile string) {

// try to start an invalid service. This service is linked to a pod whose image name is invalid, so this pos will never become running
rrApply, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "apply", "-f", filepath.Join(*testdataDir, "invalidsvc.yaml")))
defer func() {
// Cleanup test configurations in advance of future tests
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "delete", "-f", filepath.Join(*testdataDir, "invalidsvc.yaml")))
if err != nil {
t.Fatalf("clean up %s failed: %v", rr.Command(), err)
}
}()
if err != nil {
t.Fatalf("%s failed: %v", rrApply.Command(), err)
}
time.Sleep(3 * time.Second)

// try to expose a service, this action is supposed to fail
rrService, err := Run(t, exec.CommandContext(context.TODO(), Target(), "service", "invalid-svc", "-p", profile))
if err == nil || rrService.ExitCode == 0 {
t.Fatalf("%s should have failed: ", rrService.Command())
}
}
31 changes: 31 additions & 0 deletions test/integration/testdata/invalidsvc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
apiVersion: v1
kind: Pod
metadata:
labels:
run: invalid-svc
name: invalid-svc
namespace: default
spec:
containers:
- name: nginx
image: nonexistingimage:latest
ports:
- containerPort: 80
protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
labels:
run: invalid-svc
name: invalid-svc
namespace: default
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
run: invalid-svc
sessionAffinity: None
type: NodePort
1 change: 1 addition & 0 deletions translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "dry-run Modus. Validiert die Konfiguration, aber ändert den System Zustand nicht",
"dry-run validation complete!": "dry-run Validierung komplett!",
"enable failed": "aktivieren fehlgeschlagen",
"error checking service": "",
"error creating clientset": "Fehler beim Anlegen des Clientsets",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down
1 change: 1 addition & 0 deletions translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "",
"enable failed": "",
"error checking service": "",
"error creating clientset": "",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down
1 change: 1 addition & 0 deletions translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "mode simulation. Valide la configuration, mais ne modifie pas l'état du système",
"dry-run validation complete!": "validation de la simulation terminée !",
"enable failed": "échec de l'activation",
"error checking service": "",
"error creating clientset": "erreur lors de la création de l'ensemble de clients",
"error creatings urls": "erreur lors de la création d'urls",
"error getting defaults: {{.error}}": "erreur lors de l'obtention des valeurs par défaut : {{.error}}",
Expand Down
1 change: 1 addition & 0 deletions translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "dry-run モード。設定は検証しますが、システムの状態は変更しません",
"dry-run validation complete!": "dry-run の検証が終了しました!",
"enable failed": "有効化に失敗しました",
"error checking service": "",
"error creating clientset": "clientset 作成中にエラー",
"error creatings urls": "URL 作成でエラー",
"error getting defaults: {{.error}}": "デフォルト取得中にエラー: {{.error}}",
Expand Down
1 change: 1 addition & 0 deletions translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "dry-run 검증 완료!",
"enable failed": "활성화가 실패하였습니다",
"error checking service": "",
"error creating clientset": "clientset 생성 오류",
"error creating machine client": "머신 client 생성 오류",
"error creatings urls": "",
Expand Down
1 change: 1 addition & 0 deletions translations/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "",
"enable failed": "",
"error checking service": "",
"error creating clientset": "",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down
1 change: 1 addition & 0 deletions translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "",
"enable failed": "",
"error checking service": "",
"error creating clientset": "",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down
1 change: 1 addition & 0 deletions translations/strings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "",
"enable failed": "",
"error checking service": "",
"error creating clientset": "",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down
1 change: 1 addition & 0 deletions translations/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,7 @@
"dry-run mode. Validates configuration, but does not mutate system state": "",
"dry-run validation complete!": "",
"enable failed": "开启失败",
"error checking service": "",
"error creating clientset": "",
"error creatings urls": "",
"error getting defaults: {{.error}}": "",
Expand Down

0 comments on commit 69d1127

Please sign in to comment.