github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/gadgets/prometheus/tracer/tracer.go (about)

     1  // Copyright 2023 The Inspektor Gadget 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  //go:build !withoutebpf
    16  
    17  package tracer
    18  
    19  import (
    20  	"go.opentelemetry.io/otel/metric"
    21  
    22  	"github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets"
    23  	igprometheus "github.com/inspektor-gadget/inspektor-gadget/pkg/prometheus"
    24  	"github.com/inspektor-gadget/inspektor-gadget/pkg/prometheus/config"
    25  )
    26  
    27  type Tracer struct {
    28  	meterProvider metric.MeterProvider
    29  	config        *config.Config
    30  }
    31  
    32  func (t *Tracer) Init(gadgetCtx gadgets.GadgetContext) error {
    33  	params := gadgetCtx.GadgetParams()
    34  	metricsConfig := params.Get(ParamConfig).AsBytes()
    35  
    36  	config, err := config.ParseConfig(metricsConfig)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	t.config = config
    41  	return nil
    42  }
    43  
    44  func (t *Tracer) Close() {
    45  }
    46  
    47  func (t *Tracer) Run(gadgetCtx gadgets.GadgetContext) error {
    48  	ctx := gadgetCtx.Context()
    49  	gadgetCtx.Logger().Debugf("config: %+v", t.config)
    50  
    51  	cleanup, err := igprometheus.CreateMetrics(ctx, t.config, t.meterProvider)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	defer cleanup()
    56  
    57  	gadgetCtx.Logger().Info("Publishing metrics...")
    58  
    59  	<-ctx.Done()
    60  
    61  	return nil
    62  }
    63  
    64  func (g *GadgetDesc) NewInstance() (gadgets.Gadget, error) {
    65  	return &Tracer{}, nil
    66  }
    67  
    68  func (t *Tracer) SetMetricsProvider(meter metric.MeterProvider) {
    69  	t.meterProvider = meter
    70  }
    71  
    72  func (t *Tracer) GetPrometheusConfig() *config.Config {
    73  	return t.config
    74  }