...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/workflow/task/collector/stdout.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/workflow/task/collector

     1  // Copyright 2021 Chaos Mesh Authors.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package collector
    15  
    16  import (
    17  	"context"
    18  	"strings"
    19  
    20  	v1 "k8s.io/api/core/v1"
    21  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    22  	"k8s.io/client-go/kubernetes"
    23  	"k8s.io/client-go/rest"
    24  )
    25  
    26  const Stdout string = "stdout"
    27  
    28  type StdoutCollector struct {
    29  	restConfig    *rest.Config
    30  	namespace     string
    31  	podName       string
    32  	containerName string
    33  }
    34  
    35  func NewStdoutCollector(restConfig *rest.Config, namespace string, podName string, containerName string) *StdoutCollector {
    36  	return &StdoutCollector{restConfig: restConfig, namespace: namespace, podName: podName, containerName: containerName}
    37  }
    38  
    39  func (it *StdoutCollector) CollectContext(ctx context.Context) (env map[string]interface{}, err error) {
    40  	client, err := kubernetes.NewForConfig(it.restConfig)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	request := client.CoreV1().Pods(it.namespace).GetLogs(it.podName, &v1.PodLogOptions{
    46  		TypeMeta:  metav1.TypeMeta{},
    47  		Container: it.containerName,
    48  	}).Context(ctx)
    49  
    50  	var bytes []byte
    51  	if bytes, err = request.Do().Raw(); err != nil {
    52  		return nil, err
    53  	}
    54  	stdout := strings.TrimSpace(string(bytes))
    55  
    56  	return map[string]interface{}{Stdout: stdout}, nil
    57  }
    58