...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/workflow/task/collector/collector.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  
    21  	"k8s.io/client-go/rest"
    22  	"sigs.k8s.io/controller-runtime/pkg/client"
    23  )
    24  
    25  // Collector is a set of tools for collecting parameters/context from user defined task
    26  type Collector interface {
    27  	CollectContext(ctx context.Context) (env map[string]interface{}, err error)
    28  }
    29  
    30  type ComposeCollector struct {
    31  	collectors []Collector
    32  }
    33  
    34  func (it *ComposeCollector) CollectContext(ctx context.Context) (env map[string]interface{}, err error) {
    35  	if len(it.collectors) == 0 {
    36  		return nil, nil
    37  	}
    38  	if len(it.collectors) == 1 {
    39  		return it.collectors[0].CollectContext(ctx)
    40  	}
    41  
    42  	result := make(map[string]interface{})
    43  	for _, collector := range it.collectors {
    44  		temp, err := collector.CollectContext(ctx)
    45  		if err != nil {
    46  			return nil, err
    47  		}
    48  		mapExtend(result, temp)
    49  	}
    50  	return result, nil
    51  }
    52  
    53  // mapExtend will merge another map into the origin map, value with duplicated key will be replaced.
    54  // origin map should not be nil
    55  func mapExtend(origin map[string]interface{}, another map[string]interface{}) {
    56  	if origin == nil || another == nil {
    57  		return
    58  	}
    59  	for k, v := range another {
    60  		origin[k] = v
    61  	}
    62  }
    63  
    64  func DefaultCollector(kubeClient client.Client, restConfig *rest.Config, namespace, podName, containerName string) Collector {
    65  	return &ComposeCollector{collectors: []Collector{
    66  		NewExitCodeCollector(kubeClient, namespace, podName, containerName),
    67  		NewStdoutCollector(restConfig, namespace, podName, containerName),
    68  	}}
    69  }
    70