github.com/cilium/cilium@v1.16.2/pkg/gops/cell.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package gops
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/cilium/hive/cell"
    10  	gopsAgent "github.com/google/gops/agent"
    11  	"github.com/sirupsen/logrus"
    12  	"github.com/spf13/pflag"
    13  
    14  	"github.com/cilium/cilium/pkg/logging/logfields"
    15  	"github.com/cilium/cilium/pkg/option"
    16  )
    17  
    18  // Cell creates the cell for the gops agent, a tool to list and diagnose Go processes.
    19  // See https://github.com/google/gops.
    20  func Cell(defaultPort uint16) cell.Cell {
    21  	return cell.Module(
    22  		"gops",
    23  		"Gops Agent",
    24  
    25  		cell.Config(GopsConfig{GopsPort: defaultPort}),
    26  		cell.Invoke(registerGopsHooks),
    27  	)
    28  }
    29  
    30  type GopsConfig struct {
    31  	GopsPort uint16 // Port for gops server to listen on
    32  }
    33  
    34  func (def GopsConfig) Flags(flags *pflag.FlagSet) {
    35  	flags.Uint16(option.GopsPort, def.GopsPort, "Port for gops server to listen on")
    36  }
    37  
    38  func registerGopsHooks(lc cell.Lifecycle, log logrus.FieldLogger, cfg GopsConfig) {
    39  	addr := fmt.Sprintf("127.0.0.1:%d", cfg.GopsPort)
    40  	addrField := logrus.Fields{"address": addr, logfields.LogSubsys: "gops"}
    41  	log = log.WithFields(addrField)
    42  	lc.Append(cell.Hook{
    43  		OnStart: func(cell.HookContext) error {
    44  			log.Info("Started gops server")
    45  			return gopsAgent.Listen(gopsAgent.Options{
    46  				Addr:                   addr,
    47  				ReuseSocketAddrAndPort: true,
    48  			})
    49  		},
    50  		OnStop: func(cell.HookContext) error {
    51  			gopsAgent.Close()
    52  			log.Info("Stopped gops server")
    53  			return nil
    54  		},
    55  	})
    56  }