github.com/vmware/govmomi@v0.43.0/vim25/progress/aggregator.go (about)

     1  /*
     2  Copyright (c) 2014 VMware, Inc. All Rights Reserved.
     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 progress
    18  
    19  import "sync"
    20  
    21  type Aggregator struct {
    22  	downstream Sinker
    23  	upstream   chan (<-chan Report)
    24  
    25  	done chan struct{}
    26  	w    sync.WaitGroup
    27  }
    28  
    29  func NewAggregator(s Sinker) *Aggregator {
    30  	a := &Aggregator{
    31  		downstream: s,
    32  		upstream:   make(chan (<-chan Report)),
    33  
    34  		done: make(chan struct{}),
    35  	}
    36  
    37  	a.w.Add(1)
    38  	go a.loop()
    39  
    40  	return a
    41  }
    42  
    43  func (a *Aggregator) loop() {
    44  	defer a.w.Done()
    45  
    46  	dch := a.downstream.Sink()
    47  	defer close(dch)
    48  
    49  	for {
    50  		select {
    51  		case uch := <-a.upstream:
    52  			// Drain upstream channel
    53  			for e := range uch {
    54  				dch <- e
    55  			}
    56  		case <-a.done:
    57  			return
    58  		}
    59  	}
    60  }
    61  
    62  func (a *Aggregator) Sink() chan<- Report {
    63  	ch := make(chan Report)
    64  	a.upstream <- ch
    65  	return ch
    66  }
    67  
    68  // Done marks the aggregator as done. No more calls to Sink() may be made and
    69  // the downstream progress report channel will be closed when Done() returns.
    70  func (a *Aggregator) Done() {
    71  	close(a.done)
    72  	a.w.Wait()
    73  }