11789: Merge branch 'master' into 11789-arvput-exclude-flag
[arvados.git] / lib / crunchstat / crunchstat.go
index 03cfa7d3ef2570826ff4b1279783711d1e00597d..f4915c0e3e9f8e34a61ba20d488bd8edd3428190 100644 (file)
@@ -1,3 +1,7 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
 // Package crunchstat reports resource usage (CPU, memory, disk,
 // network) for a cgroup.
 package crunchstat
@@ -56,7 +60,8 @@ type Reporter struct {
        lastDiskSample   map[string]ioSample
        lastCPUSample    cpuSample
 
-       done chan struct{}
+       done    chan struct{} // closed when we should stop reporting
+       flushed chan struct{} // closed when we have made our last report
 }
 
 // Start starts monitoring in a new goroutine, and returns
@@ -72,6 +77,7 @@ type Reporter struct {
 // Callers should not modify public data fields after calling Start.
 func (r *Reporter) Start() {
        r.done = make(chan struct{})
+       r.flushed = make(chan struct{})
        go r.run()
 }
 
@@ -81,6 +87,7 @@ func (r *Reporter) Start() {
 // Nothing will be logged after Stop returns.
 func (r *Reporter) Stop() {
        close(r.done)
+       <-r.flushed
 }
 
 func (r *Reporter) readAllOrWarn(in io.Reader) ([]byte, error) {
@@ -366,6 +373,8 @@ func (r *Reporter) doCPUStats() {
 // Report stats periodically until we learn (via r.done) that someone
 // called Stop.
 func (r *Reporter) run() {
+       defer close(r.flushed)
+
        r.reportedStatFile = make(map[string]string)
 
        if !r.waitForCIDFile() || !r.waitForCgroup() {