go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/tsmon/callback.go (about) 1 // Copyright 2016 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package tsmon 16 17 import ( 18 "context" 19 20 "go.chromium.org/luci/common/tsmon/types" 21 ) 22 23 // Callback is a function that is run at metric collection time to set the 24 // values of one or more metrics. A callback can be registered with 25 // RegisterCallback. 26 type Callback func(ctx context.Context) 27 28 // A GlobalCallback is a Callback with the list of metrics it affects, so those 29 // metrics can be reset after they are flushed. 30 type GlobalCallback struct { 31 Callback 32 metrics []types.Metric 33 } 34 35 // RegisterCallback registers a callback function that will be run at metric 36 // collection time to set the values of one or more metrics. RegisterCallback 37 // should be called from an init() function in your module. 38 func RegisterCallback(f Callback) { 39 RegisterCallbackIn(context.Background(), f) 40 } 41 42 // RegisterCallbackIn is like RegisterCallback but registers in a given context. 43 func RegisterCallbackIn(ctx context.Context, f Callback) { 44 GetState(ctx).RegisterCallbacks(f) 45 } 46 47 // RegisterGlobalCallback registers a callback function that will be run once 48 // per minute on *one* instance of your application. It is supported primarily 49 // on GAE. 50 // 51 // You must specify the list of metrics that your callback affects - these 52 // metrics will be reset after flushing to ensure they are not sent by multiple 53 // instances. 54 // 55 // RegisterGlobalCallback should be called from an init() function in your 56 // module. 57 func RegisterGlobalCallback(f Callback, metrics ...types.Metric) { 58 RegisterGlobalCallbackIn(context.Background(), f, metrics...) 59 } 60 61 // RegisterGlobalCallbackIn is like RegisterGlobalCallback but registers in a 62 // given context. 63 func RegisterGlobalCallbackIn(ctx context.Context, f Callback, metrics ...types.Metric) { 64 if len(metrics) == 0 { 65 panic("RegisterGlobalCallback called without any metrics") 66 } 67 68 GetState(ctx).RegisterGlobalCallbacks(GlobalCallback{f, metrics}) 69 }