k8sexec

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2024 License: MIT Imports: 15 Imported by: 0

README

k8sexec

k8sexec is based on the k8s.io framework. Its major purpose is to execute commands on containers. k8sexec.Exec() method executes a command, commands or scripts provided through standard input ('stdin') or as arguments ('args'), or a combination of both. It returns a pointer to an instance of ExecutionStatus, which encapsulates the results of the command execution. This includes details such as the exit code, error messages, and the outputs captured from both the standard output and standard error streams.

It must be mentioned that k8sexec.Exec() allows to execute all kinds of scripts/commands through stdin. Below example shows how to embed lse.sh (Linux Smart Enumeration) script into a go binary and then execute it through stdin.

EXAMPLE:

package simpleexec

import (
	"github.com/hhruszka/k8sexec"
	"fmt"
	_ "embed"
	v1 "k8s.io/api/core/v1"
	"bytes"
)

//go:embed lse.sh
var lse []byte

func test(kubeconfig string, namespace string)  []*k8sexec.ExecutionStatus {
	var results []*k8sexec.ExecutionStatus
		
	k8s,err := k8sexec.NewK8SExec(kubeconfig,namespace)
	if err!= nil {
		return nil
    }
	
	cnt,pods,err := k8s.GetUniquePods()
	if err != nil {
		return nil
    }
	
	fmt.Printf("Found %d pods\n",cnt)
	
	for _, pod := range pods {
	    for _,container := range pod.Spec.Containers {
            lsescript := bytes.NewBuffer(lse)
			
            result := k8s.Exec(pod.Name, container.Name, []string{"sh"}, lsescript)
            results = append(results,result)
	    }
	}
	
	return results
}

Additionally, k8sexec module provides functions for retrieving pods, deployments and statefulset that can be used to automate enumeration of containers or any other information.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetExitCodeDescription

func GetExitCodeDescription(code ExitCode) string

GetExitCodeDescription returns a string description for a given exit code. It looks up the code in the predefined exitCodeDescriptions map. If the code is found, it returns the corresponding description. If not, it returns "Unknown exit code".

Types

type ExecutionStatus

type ExecutionStatus struct {
	Pod       string   `json:"Pod"`
	Container string   `json:"Container"`
	RetCode   ExitCode `json:"RetCode"`
	Error     []string `json:"Error"`
	Stdout    []string `json:"Stdout"`
	Stderr    []string `json:"Stderr"`
}

ExecutionStatus encapsulates the result and details of executing a command within a specific container. It includes both identification and outcome information. The container is specified by its name and the associated pod's name, provided in the Container and Pod fields, respectively. The execution outcome is detailed as follows: - RetCode: The exit code of the command executed within the container. A zero value typically indicates success. - Error: A string representation of any error that occurred during command execution, as reported by the Kubernetes API. - Stdout: The standard output generated by the command. - Stderr: The standard error output generated by the command, if any.

func NewExecutionStatus

func NewExecutionStatus(pod string, container string, retCode ExitCode, error string, stdout string, stderr string) *ExecutionStatus

NewExecutionStatus initializes a new instance of the ExecutionStatus type, providing a method to encapsulate the outcome of a command's execution within a structured format. This function serves as a constructor, setting up an ExecutionStatus instance.

type ExitCode

type ExitCode int

ExitCode is an enumeration of possible exit codes with descriptive names. It provides a more idiomatic way to refer to exit codes within the Go application.

const (
	InternalAppError ExitCode = iota - 1
	Success
	GeneralError
	IncorrectUsage
	CommandCannotExecute  = 126
	CommandNotFound       = 127
	InvalidArgumentToExit = 128
	// Skips to specific values after the iota increment
	ScriptTerminatedByControlC ExitCode = 130
	ExitStatusOutOfRange       ExitCode = 255
	// Signal based exit codes (128+n)
	FatalErrorSignal1 ExitCode = 129
	// FatalErrorSignal2 is omitted as it overlaps with ScriptTerminatedByControlC
	FatalErrorSignal3  ExitCode = 131
	FatalErrorSignal4  ExitCode = 132
	FatalErrorSignal5  ExitCode = 133
	FatalErrorSignal6  ExitCode = 134
	FatalErrorSignal7  ExitCode = 135
	FatalErrorSignal8  ExitCode = 136
	FatalErrorSignal9  ExitCode = 137
	FatalErrorSignal10 ExitCode = 138
	FatalErrorSignal11 ExitCode = 139
	FatalErrorSignal12 ExitCode = 140
	FatalErrorSignal13 ExitCode = 141
	FatalErrorSignal14 ExitCode = 142
	FatalErrorSignal15 ExitCode = 143
)

func GetExitCode

func GetExitCode(err error) (ExitCode, string)

GetExitCode returns an ExitCode retrieved from CodeExitError type returned by k8s.io/client-go/util/exec and a corresponding description from exitCodeDescriptions map.

type K8SExec

type K8SExec struct {
	Config    *rest.Config
	Clientset *kubernetes.Clientset
	Namespace string
}

K8SExec defines the context for modules executing commands in Kubernetes environments. It includes details necessary for operations, such as cluster configuration, target pod and container, and authentication credentials, facilitating effective interaction with Kubernetes resources.

func NewK8SExec

func NewK8SExec(kubeconfig string, namespace string) (info *K8SExec, err error)

NewK8SExec creates and initializes an instance of the K8SExec type. It takes Kubernetes configuration information as parameters, which are required to access and interact with the Kubernetes cluster. This function ensures that the created K8SExec instance is ready to use for executing commands within Kubernetes pods and containers, by embedding necessary configuration details.

func (*K8SExec) CheckUtilInContainer

func (k8s *K8SExec) CheckUtilInContainer(podName, containerName string, util string) bool

CheckUtilInContainer verifies the existence of a specified 'util' binary within a container, identified by the container's name and the associated pod's name.

func (*K8SExec) Exec

func (k8s *K8SExec) Exec(podName string, containerName string, args []string, stdin io.Reader) *ExecutionStatus

Exec executes a command provided through standard input ('stdin') or as arguments ('args'), or a combination of both. This function returns a pointer to an instance of ExecutionStatus, which encapsulates the results of the command execution. This includes details such as the exit code, error messages, and the outputs captured from both the standard output and standard error streams.

func (*K8SExec) GetDeployments

func (k8s *K8SExec) GetDeployments() (*v1.DeploymentList, error)

GetDeployments retrieves all Deployments within the namespace specified in the 'k8s' context. It leverages the Kubernetes client-go library to query the Kubernetes API for Deployments, aiming to streamline the process of managing Kubernetes resources. This function returns an array of Deployments along with any error encountered during the query, thus enabling comprehensive oversight of Deployment resources within the designated namespace.

func (*K8SExec) GetPod

func (k8s *K8SExec) GetPod(podName string, options metaV1.GetOptions) (*coreV1.Pod, error)

GetPod retrieves a Pod based on its name within the specified namespace. The namespace is provided by the 'k8s' context. This function simplifies the process of locating a specific Pod within a namespace, leveraging the Kubernetes client-go library to interact with the Kubernetes API. It returns the found Pod and any error encountered during the retrieval process.

func (*K8SExec) GetPods

func (k8s *K8SExec) GetPods(options metaV1.ListOptions) ([]coreV1.Pod, error)

GetPods retrieves all Pods within the namespace specified by the 'k8s' context. This function utilizes the Kubernetes client-go library to fetch a list of Pods from the specified namespace, facilitating the management and interaction with Kubernetes resources. It returns a list of Pods and any error encountered during the retrieval process.

func (*K8SExec) GetStatefulSets

func (k8s *K8SExec) GetStatefulSets() (*v1.StatefulSetList, error)

GetStatefulSets fetches all StatefulSets within the specified namespace, as determined by the 'k8s' context. Utilizing the client-go library, this function communicates with the Kubernetes API to gather StatefulSets, facilitating detailed management and operational oversight of these specific Kubernetes resources. It returns a collection of StatefulSets and any errors encountered in the process, ensuring comprehensive access to StatefulSet configurations within the given namespace.

func (*K8SExec) GetUniquePods

func (k8s *K8SExec) GetUniquePods() (int, []coreV1.Pod, error)

GetPods retrieves a comprehensive and unique list of Pods within a given namespace, as provided by the 'k8s' context. It targets Pods associated with Deployments, StatefulSets, and those directly within the namespace, ensuring no duplicates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL