github.com/grailbio/base@v0.0.11/grail/biofs/biofseventlog/biofseventlog.go (about)

     1  // biofseventlog creates usage events for biofs, a GRAIL-internal program. biofs has to be internal
     2  // because it runs fsnodefuse with some fsnode.T's derived from other internal code, but it also
     3  // uses github.com/grailbio packages like s3file.
     4  package biofseventlog
     5  
     6  import (
     7  	"strconv"
     8  	"sync"
     9  	"time"
    10  
    11  	"github.com/grailbio/base/config"
    12  	"github.com/grailbio/base/eventlog"
    13  	"github.com/grailbio/base/log"
    14  	"github.com/grailbio/base/must"
    15  )
    16  
    17  const configName = "biofs/eventer"
    18  
    19  func init() {
    20  	config.Default(configName, "eventer/nop")
    21  }
    22  
    23  // UsedFeature creates an event for usage of the named feature.
    24  func UsedFeature(featureName string) {
    25  	var eventer eventlog.Eventer
    26  	must.Nil(config.Instance(configName, &eventer))
    27  	eventer.Event("usedFeature",
    28  		"name", featureName,
    29  		"buildTime", getCoarseBuildTimestamp())
    30  }
    31  
    32  // CoarseNow returns times with precision truncated by CoarseTime.
    33  func CoarseNow() time.Time { return CoarseTime(time.Now()) }
    34  
    35  // CoarseTime truncates t's precision to a nearby week. It's used to improve event log anonymity.
    36  func CoarseTime(t time.Time) time.Time {
    37  	weekMillis := 7 * 24 * time.Hour.Milliseconds()
    38  	now := t.UnixMilli()
    39  	now /= weekMillis
    40  	now *= weekMillis
    41  	return time.UnixMilli(now)
    42  }
    43  
    44  var (
    45  	buildTimestamp       string
    46  	coarseBuildTimestamp = "unknown"
    47  	buildTimestampOnce   sync.Once
    48  )
    49  
    50  // getCoarseBuildTimestamp returns the (probably bazel-injected) build timestamp
    51  // with precision truncated to CoarseTime, or a message if data is unavailable.
    52  func getCoarseBuildTimestamp() string {
    53  	buildTimestampOnce.Do(func() {
    54  		if buildTimestamp == "" {
    55  			return
    56  		}
    57  		buildSecs, err := strconv.ParseInt(buildTimestamp, 10, 64)
    58  		if err != nil {
    59  			log.Error.Printf("biofseventlog: error parsing build timestamp: %v", err)
    60  			return
    61  		}
    62  		coarseBuildTime := CoarseTime(time.Unix(buildSecs, 0))
    63  		coarseBuildTimestamp = coarseBuildTime.Format("20060102")
    64  	})
    65  	return coarseBuildTimestamp
    66  }