github.com/interconnectedcloud/qdr-operator@v0.0.0-20210826174505-576d2b33dac7/test/e2e/framework/cleanup.go (about)

     1  /*
     2  Copyright 2019 The Interconnectedcloud 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 framework
    18  
    19  import "sync"
    20  
    21  // CleanupActionHandle is an integer pointer type for handling cleanup action
    22  type CleanupActionHandle *int
    23  
    24  var cleanupActionsLock sync.Mutex
    25  var cleanupActions = map[CleanupActionHandle]func(){}
    26  
    27  // AddCleanupAction installs a function that will be called in the event of the
    28  // whole test being terminated.  This allows arbitrary pieces of the overall
    29  // test to hook into SynchronizedAfterSuite().
    30  func AddCleanupAction(fn func()) CleanupActionHandle {
    31  	p := CleanupActionHandle(new(int))
    32  	cleanupActionsLock.Lock()
    33  	defer cleanupActionsLock.Unlock()
    34  	cleanupActions[p] = fn
    35  	return p
    36  }
    37  
    38  // RemoveCleanupAction removes a function that was installed by
    39  // AddCleanupAction.
    40  func RemoveCleanupAction(p CleanupActionHandle) {
    41  	cleanupActionsLock.Lock()
    42  	defer cleanupActionsLock.Unlock()
    43  	delete(cleanupActions, p)
    44  }
    45  
    46  // RunCleanupActions runs all functions installed by AddCleanupAction.  It does
    47  // not remove them (see RemoveCleanupAction) but it does run unlocked, so they
    48  // may remove themselves.
    49  func RunCleanupActions() {
    50  	list := []func(){}
    51  	func() {
    52  		cleanupActionsLock.Lock()
    53  		defer cleanupActionsLock.Unlock()
    54  		for _, fn := range cleanupActions {
    55  			list = append(list, fn)
    56  		}
    57  	}()
    58  	// Run unlocked.
    59  	for _, fn := range list {
    60  		fn()
    61  	}
    62  }