...

Source file src/k8s.io/kubernetes/test/integration/framework/goleak.go

Documentation: k8s.io/kubernetes/test/integration/framework

     1  /*
     2  Copyright 2017 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 framework
    18  
    19  import (
    20  	"testing"
    21  	"time"
    22  
    23  	"go.uber.org/goleak"
    24  	"k8s.io/apiserver/pkg/server/healthz"
    25  )
    26  
    27  // IgnoreBackgroundGoroutines returns options for goleak.Find
    28  // which ignore goroutines created by "go test" and init functions,
    29  // like the one from go.opencensus.io/stats/view/worker.go.
    30  //
    31  // Goroutines that normally get created later when using the apiserver
    32  // get created already when calling this function, therefore they
    33  // also get ignored.
    34  func IgnoreBackgroundGoroutines() []goleak.Option {
    35  	// Ensure that on-demand goroutines are running.
    36  	_ = healthz.LogHealthz.Check(nil)
    37  
    38  	return []goleak.Option{goleak.IgnoreCurrent()}
    39  }
    40  
    41  // GoleakCheck sets up leak checking for a test or benchmark.
    42  // The check runs as cleanup operation and records an
    43  // error when goroutines were leaked.
    44  func GoleakCheck(tb testing.TB, opts ...goleak.Option) {
    45  	// Must be called *before* creating new goroutines.
    46  	opts = append(opts, IgnoreBackgroundGoroutines()...)
    47  
    48  	tb.Cleanup(func() {
    49  		if err := goleakFindRetry(opts...); err != nil {
    50  			tb.Error(err.Error())
    51  		}
    52  	})
    53  }
    54  
    55  func goleakFindRetry(opts ...goleak.Option) error {
    56  	// Several tests don't wait for goroutines to stop. goleak.Find retries
    57  	// internally, but not long enough. 5 seconds seemed to be enough for
    58  	// most tests, even when testing in the CI.
    59  	timeout := 5 * time.Second
    60  	start := time.Now()
    61  	for {
    62  		err := goleak.Find(opts...)
    63  		if err == nil {
    64  			return nil
    65  		}
    66  		if time.Now().Sub(start) >= timeout {
    67  			return err
    68  		}
    69  	}
    70  }
    71  

View as plain text