github.com/xmidt-org/webpa-common@v1.11.9/device/drain/tracker.go (about)

     1  package drain
     2  
     3  import (
     4  	"sync/atomic"
     5  	"time"
     6  
     7  	"github.com/xmidt-org/webpa-common/xmetrics"
     8  )
     9  
    10  // Progress represents a snapshot of what a drain job has done so far.
    11  type Progress struct {
    12  	// Visited is the number of devices handled so far.  This value will not
    13  	// exceed the Job.Count value.
    14  	Visited int `json:"visited"`
    15  
    16  	// Drained is the count of visited devices that have actually been disconnected
    17  	// due to the drain.  Devices can disconnect or be disconnected outside a drain job,
    18  	// so this value can be lower than Visited, even in a job that has finished.
    19  	Drained int `json:"drained"`
    20  
    21  	// Started is the UTC system time at which the drain job was started.
    22  	Started time.Time `json:"started"`
    23  
    24  	// Finished is the UTC system time at which the drain job finished or was canceled.
    25  	// If the job is running, this field will be nil.
    26  	Finished *time.Time `json:"finished,omitempty"`
    27  }
    28  
    29  type tracker struct {
    30  	visited  int32
    31  	drained  int32
    32  	started  time.Time
    33  	finished atomic.Value
    34  	counter  xmetrics.Adder
    35  }
    36  
    37  func (t *tracker) Progress() Progress {
    38  	p := Progress{
    39  		Visited: int(atomic.LoadInt32(&t.visited)),
    40  		Drained: int(atomic.LoadInt32(&t.drained)),
    41  		Started: t.started,
    42  	}
    43  
    44  	if finished, ok := t.finished.Load().(time.Time); ok && !finished.IsZero() {
    45  		p.Finished = &finished
    46  	}
    47  
    48  	return p
    49  }
    50  
    51  func (t *tracker) addVisited(delta int) {
    52  	atomic.AddInt32(&t.visited, int32(delta))
    53  }
    54  
    55  func (t *tracker) addDrained(delta int) {
    56  	atomic.AddInt32(&t.drained, int32(delta))
    57  	t.counter.Add(float64(delta))
    58  }
    59  
    60  func (t *tracker) done(timestamp time.Time) {
    61  	t.finished.Store(timestamp)
    62  }