github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/util/cancel_monitor.go (about)

     1  // Copyright 2020 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  	"context"
    18  	"time"
    19  
    20  	"github.com/pingcap/log"
    21  	"go.uber.org/zap"
    22  )
    23  
    24  // MonitorCancelLatency monitors the latency from ctx being cancelled
    25  // the first returned function should be called when the cancellation is done
    26  // the second returned function should be called to mark the cancellation is started, it will start a
    27  // background go routine to monitor the latency util finish is called or cancellation is done
    28  func MonitorCancelLatency(ctx context.Context, identifier string) (func(), func()) {
    29  	finishedCh := make(chan struct{})
    30  	start := func() {
    31  		go func() {
    32  			log.Debug("MonitorCancelLatency: Cancelled", zap.String("identifier", identifier))
    33  			ticker := time.NewTicker(time.Second)
    34  			defer ticker.Stop()
    35  			elapsed := 0
    36  			for {
    37  				select {
    38  				case <-finishedCh:
    39  					log.Debug("MonitorCancelLatency: Monitored routine exited", zap.String("identifier", identifier))
    40  					return
    41  				case <-ticker.C:
    42  					elapsed++
    43  					log.Warn("MonitorCancelLatency: Cancellation is taking too long",
    44  						zap.String("identifier", identifier),
    45  						zap.Int("duration", elapsed), zap.Error(ctx.Err()))
    46  				}
    47  			}
    48  		}()
    49  	}
    50  	return func() {
    51  		close(finishedCh)
    52  	}, start
    53  }