knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/cleanup.go (about) 1 /* 2 Copyright 2018 The Knative 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 test 18 19 import ( 20 "os" 21 "os/signal" 22 "sync" 23 ) 24 25 type logFunc func(template string, args ...interface{}) 26 27 var cleanup struct { 28 once sync.Once 29 mutex sync.RWMutex 30 funcs []func() 31 } 32 33 func waitForInterrupt() { 34 c := make(chan os.Signal, 1) 35 signal.Notify(c, os.Interrupt) 36 37 go func() { 38 <-c 39 40 cleanup.mutex.RLock() 41 defer cleanup.mutex.RUnlock() 42 43 for i := len(cleanup.funcs) - 1; i >= 0; i-- { 44 cleanup.funcs[i]() 45 } 46 47 os.Exit(1) 48 }() 49 } 50 51 // CleanupOnInterrupt will execute the function if an interrupt signal is caught 52 // Deprecated - use OnInterrupt 53 func CleanupOnInterrupt(f func(), log logFunc) { 54 OnInterrupt(f) 55 } 56 57 // OnInterrupt registers a cleanup function to run if an interrupt signal is caught 58 func OnInterrupt(cleanupFunc func()) { 59 cleanup.once.Do(waitForInterrupt) 60 61 cleanup.mutex.Lock() 62 defer cleanup.mutex.Unlock() 63 64 cleanup.funcs = append(cleanup.funcs, cleanupFunc) 65 }