agones.dev/agones@v1.54.0/test/eviction/evictpod.go (about)

     1  // Copyright 2023 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License
    14  
    15  // evictpod.go --pod <pod> --namespace <namespace> initiates a pod eviction
    16  // using the k8s eviction API.
    17  package main
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"path/filepath"
    23  
    24  	policy "k8s.io/api/policy/v1"
    25  	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/client-go/kubernetes"
    27  	"k8s.io/client-go/util/homedir"
    28  
    29  	"agones.dev/agones/pkg/util/runtime"
    30  )
    31  
    32  // Borrowed from https://stackoverflow.com/questions/62803041/how-to-evict-or-delete-pods-from-kubernetes-using-golang-client
    33  func evictPod(ctx context.Context, client *kubernetes.Clientset, name, namespace string) error {
    34  	return client.PolicyV1().Evictions(namespace).Evict(ctx, &policy.Eviction{
    35  		ObjectMeta: meta_v1.ObjectMeta{
    36  			Name:      name,
    37  			Namespace: namespace,
    38  		}})
    39  }
    40  
    41  func main() {
    42  	ctx := context.Background()
    43  
    44  	kubeconfig := flag.String("kubeconfig", filepath.Join(homedir.HomeDir(), ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    45  	namespace := flag.String("namespace", "default", "Namespace (defaults to `default`)")
    46  	pod := flag.String("pod", "", "Pod name (required)")
    47  	flag.Parse()
    48  	logger := runtime.NewLoggerWithSource("evictpod")
    49  
    50  	if *pod == "" {
    51  		logger.Fatal("--pod must be non-empty")
    52  	}
    53  
    54  	config, err := runtime.InClusterBuildConfig(logger, *kubeconfig)
    55  	if err != nil {
    56  		logger.WithError(err).Fatalf("Could not build config: %v", err)
    57  	}
    58  
    59  	kubeClient, err := kubernetes.NewForConfig(config)
    60  	if err != nil {
    61  		logger.WithError(err).Fatalf("Could not create the kubernetes clientset: %v", err)
    62  	}
    63  
    64  	if err := evictPod(ctx, kubeClient, *pod, *namespace); err != nil {
    65  		logger.WithError(err).Fatalf("Pod eviction failed: %v", err)
    66  	}
    67  }