github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/sqlparse/tidbparser/dependency/util/misc.go (about)

     1  // Copyright 2016 PingCAP, Inc.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package util
    15  
    16  import (
    17  	"runtime"
    18  	"time"
    19  
    20  	"github.com/juju/errors"
    21  )
    22  
    23  const (
    24  	// DefaultMaxRetries indicates the max retry count.
    25  	DefaultMaxRetries = 30
    26  	// RetryInterval indicates retry interval.
    27  	RetryInterval uint64 = 500
    28  )
    29  
    30  // RunWithRetry will run the f with backoff and retry.
    31  // retryCnt: Max retry count
    32  // backoff: When run f failed, it will sleep backoff * triedCount time.Millisecond.
    33  // Function f should have two return value. The first one is an bool which indicate if the err if retryable.
    34  // The second is if the f meet any error.
    35  func RunWithRetry(retryCnt int, backoff uint64, f func() (bool, error)) (err error) {
    36  	for i := 1; i <= retryCnt; i++ {
    37  		var retryAble bool
    38  		retryAble, err = f()
    39  		if err == nil || !retryAble {
    40  			return errors.Trace(err)
    41  		}
    42  		sleepTime := time.Duration(backoff*uint64(i)) * time.Millisecond
    43  		time.Sleep(sleepTime)
    44  	}
    45  	return errors.Trace(err)
    46  }
    47  
    48  // GetStack gets the stacktrace.
    49  func GetStack() []byte {
    50  	const size = 4096
    51  	buf := make([]byte, size)
    52  	stackSize := runtime.Stack(buf, false)
    53  	buf = buf[:stackSize]
    54  	return buf
    55  }