go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/appengine/internal/metrics/context.go (about) 1 // Copyright 2021 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 metrics 16 17 import ( 18 "context" 19 20 bbmetrics "go.chromium.org/luci/buildbucket/metrics" 21 "go.chromium.org/luci/common/tsmon/target" 22 ) 23 24 var serviceInfoCtxKey = "holds the service information" 25 26 type serviceInfo struct { 27 service string 28 job string 29 instance string 30 } 31 32 // WithBuilder returns a context for a Builder target with the given info. 33 // 34 // WithServiceInfo must be called once before this function. Otherwise, this panics. 35 func WithBuilder(ctx context.Context, project, bucket, builder string) context.Context { 36 val := ctx.Value(&serviceInfoCtxKey) 37 if val == nil { 38 panic("missing service info; forgot to call metrics.WithServiceInfo()?") 39 } 40 info := val.(*serviceInfo) 41 42 return target.Set(ctx, &bbmetrics.BuilderTarget{ 43 Project: project, 44 Bucket: bucket, 45 Builder: builder, 46 47 ServiceName: info.service, 48 JobName: info.job, 49 InstanceID: info.instance, 50 }) 51 } 52 53 // WithServiceInfo sets the service info to be set in the Builder target. 54 // 55 // Call this in the initialization of a server process. 56 func WithServiceInfo(ctx context.Context, service, job, instance string) context.Context { 57 return context.WithValue(ctx, &serviceInfoCtxKey, &serviceInfo{ 58 service: service, 59 job: job, 60 instance: instance, 61 }) 62 }