...

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