github.com/pingcap/tidb-lightning@v5.0.0-rc.0.20210428090220-84b649866577+incompatible/lightning/worker/worker.go (about)

     1  // Copyright 2019 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 worker
    15  
    16  import (
    17  	"context"
    18  	"time"
    19  
    20  	"github.com/pingcap/tidb-lightning/lightning/metric"
    21  )
    22  
    23  type Pool struct {
    24  	limit   int
    25  	workers chan *Worker
    26  	name    string
    27  }
    28  
    29  type Worker struct {
    30  	ID int64
    31  }
    32  
    33  func NewPool(ctx context.Context, limit int, name string) *Pool {
    34  	workers := make(chan *Worker, limit)
    35  	for i := 0; i < limit; i++ {
    36  		workers <- &Worker{ID: int64(i + 1)}
    37  	}
    38  
    39  	metric.IdleWorkersGauge.WithLabelValues(name).Set(float64(limit))
    40  	return &Pool{
    41  		limit:   limit,
    42  		workers: workers,
    43  		name:    name,
    44  	}
    45  }
    46  
    47  func (pool *Pool) Apply() *Worker {
    48  	start := time.Now()
    49  	worker := <-pool.workers
    50  	metric.IdleWorkersGauge.WithLabelValues(pool.name).Set(float64(len(pool.workers)))
    51  	metric.ApplyWorkerSecondsHistogram.WithLabelValues(pool.name).Observe(time.Since(start).Seconds())
    52  	return worker
    53  }
    54  
    55  func (pool *Pool) Recycle(worker *Worker) {
    56  	if worker == nil {
    57  		panic("invalid restore worker")
    58  	}
    59  	pool.workers <- worker
    60  	metric.IdleWorkersGauge.WithLabelValues(pool.name).Set(float64(len(pool.workers)))
    61  }
    62  
    63  func (pool *Pool) HasWorker() bool {
    64  	return len(pool.workers) > 0
    65  }