github.com/m3db/m3@v1.5.1-0.20231129193456-75a402aa583b/src/m3em/node/concurrent_executor.go (about)

     1  // Copyright (c) 2017 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package node
    22  
    23  import (
    24  	"fmt"
    25  	"sync"
    26  	"time"
    27  
    28  	xerrors "github.com/m3db/m3/src/x/errors"
    29  	xsync "github.com/m3db/m3/src/x/sync"
    30  )
    31  
    32  type executor struct {
    33  	sync.Mutex
    34  	wg      sync.WaitGroup
    35  	timeout time.Duration
    36  	workers xsync.WorkerPool
    37  	nodes   []ServiceNode
    38  	fn      ServiceNodeFn
    39  	err     xerrors.MultiError
    40  }
    41  
    42  // NewConcurrentExecutor returns a new concurrent executor
    43  func NewConcurrentExecutor(
    44  	nodes []ServiceNode,
    45  	concurrency int,
    46  	timeout time.Duration,
    47  	fn ServiceNodeFn,
    48  ) ConcurrentExecutor {
    49  	workerPool := xsync.NewWorkerPool(concurrency)
    50  	workerPool.Init()
    51  	return &executor{
    52  		timeout: timeout,
    53  		workers: workerPool,
    54  		nodes:   nodes,
    55  		fn:      fn,
    56  	}
    57  }
    58  
    59  func (e *executor) addError(err error) {
    60  	e.Lock()
    61  	defer e.Unlock()
    62  	e.err = e.err.Add(err)
    63  }
    64  
    65  func (e *executor) Run() error {
    66  	e.wg.Add(len(e.nodes))
    67  	for idx := range e.nodes {
    68  		node := e.nodes[idx]
    69  		if ok := e.workers.GoWithTimeout(func() {
    70  			defer e.wg.Done()
    71  			e.addError(e.fn(node))
    72  		}, e.timeout); !ok {
    73  			e.addError(fmt.Errorf("unable to execute node %s operation due to worker timeout", node.ID()))
    74  		}
    75  	}
    76  	e.wg.Wait()
    77  	return e.err.FinalError()
    78  }