github.com/GoogleCloudPlatform/testgrid@v0.0.174/util/log.go (about)

     1  /*
     2  Copyright 2021 The TestGrid Authors.
     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 util has convenience functions for use throughout TestGrid.
    18  package util
    19  
    20  import (
    21  	"context"
    22  	"time"
    23  
    24  	"github.com/sirupsen/logrus"
    25  )
    26  
    27  // Progress log every duration, including an ETA for completion.
    28  // Returns a function for updating the current index
    29  func Progress(ctx context.Context, log logrus.FieldLogger, every time.Duration, total int, msg string) func(int) {
    30  	start := time.Now()
    31  	ch := make(chan int, 1)
    32  	go func() {
    33  		timer := time.NewTimer(every)
    34  		defer timer.Stop()
    35  		var current int
    36  		for {
    37  			select {
    38  			case <-ctx.Done():
    39  				return
    40  			case current = <-ch:
    41  				// updated index
    42  			case now := <-timer.C:
    43  				elapsed := now.Sub(start)
    44  				var rate time.Duration
    45  				if current > 0 {
    46  					rate = elapsed / time.Duration(current)
    47  				}
    48  				eta := time.Duration(total-current) * rate
    49  
    50  				log.WithFields(logrus.Fields{
    51  					"current": current,
    52  					"total":   total,
    53  					"percent": (100 * current) / total,
    54  					"remain":  eta.Round(time.Minute),
    55  					"eta":     now.Add(eta).Round(time.Minute),
    56  					"start":   start.Round(time.Minute),
    57  				}).Info(msg)
    58  				timer.Reset(every)
    59  			}
    60  		}
    61  	}()
    62  
    63  	return func(idx int) {
    64  		select {
    65  		case ch <- idx:
    66  		default:
    67  		}
    68  	}
    69  }