k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/chaos/monkey.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package chaos 18 19 import ( 20 "fmt" 21 "strings" 22 "sync" 23 24 "k8s.io/apimachinery/pkg/util/sets" 25 clientset "k8s.io/client-go/kubernetes" 26 "k8s.io/perf-tests/clusterloader2/api" 27 "k8s.io/perf-tests/clusterloader2/pkg/provider" 28 ) 29 30 // Monkey simulates kubernetes component failures 31 type Monkey struct { 32 client clientset.Interface 33 provider provider.Provider 34 nodeKiller *NodeKiller 35 } 36 37 // NewMonkey constructs a new Monkey object. 38 func NewMonkey(client clientset.Interface, provider provider.Provider) *Monkey { 39 return &Monkey{client: client, provider: provider} 40 } 41 42 // Init initializes Monkey with given config. 43 // When stopCh is closed, the Monkey will stop simulating failures. 44 func (m *Monkey) Init(config api.ChaosMonkeyConfig, stopCh <-chan struct{}) (*sync.WaitGroup, error) { 45 wg := sync.WaitGroup{} 46 if config.NodeFailure != nil { 47 nodeKiller, err := NewNodeKiller(*config.NodeFailure, m.client, config.ExcludedNodes, m.provider) 48 if err != nil { 49 return nil, err 50 } 51 m.nodeKiller = nodeKiller 52 wg.Add(1) 53 go m.nodeKiller.Run(stopCh, &wg) 54 } 55 56 return &wg, nil 57 } 58 59 // Summary logs Monkey execution 60 func (m *Monkey) Summary() string { 61 var sb strings.Builder 62 if m.nodeKiller != nil { 63 sb.WriteString(fmt.Sprintf("Summary of Chaos Monkey execution\n")) 64 sb.WriteString(m.nodeKiller.Summary()) 65 } 66 return sb.String() 67 } 68 69 // KilledNodes returns the set of nodes which shouldn't be restarted again. 70 func (m *Monkey) KilledNodes() sets.String { 71 if m.nodeKiller != nil { 72 return m.nodeKiller.killedNodes 73 } 74 return sets.NewString() 75 }