|
| 1 | +// Module included in the following assemblies: |
| 2 | +// |
| 3 | +// * applications/operator_sdk/osdk-monitoring-prometheus.adoc |
| 4 | + |
| 5 | +[id='osdk-monitoring-prometheus-metrics-helper-{context}'] |
| 6 | += Metrics helper |
| 7 | + |
| 8 | +In Go-based Operators generated using the Operator SDK, the following helper |
| 9 | +function exposes general metrics about the running program: |
| 10 | + |
| 11 | +[source,go] |
| 12 | +---- |
| 13 | +func ExposeMetricsPort(ctx context.Context, port int32) (*v1.Service, error) |
| 14 | +---- |
| 15 | + |
| 16 | +These metrics are inherited from the `controller-runtime` library API. The |
| 17 | +metrics are by default served on `:8383/metrics`. |
| 18 | + |
| 19 | +A Service object is created with the metrics port exposed, which can be then |
| 20 | +accessed by Prometheus. The Service object is garbage collected when the leader |
| 21 | +Pod's root owner is deleted. |
| 22 | + |
| 23 | +The following example is present in the `cmd/manager/main.go` file in all |
| 24 | +Operators generated using the Operator SDK: |
| 25 | + |
| 26 | +[source,go] |
| 27 | +---- |
| 28 | + import( |
| 29 | + "github.com/operator-framework/operator-sdk/pkg/metrics" |
| 30 | + "sigs.k8s.io/controller-runtime/pkg/manager" |
| 31 | + ) |
| 32 | +
|
| 33 | + // Change the below variables to serve metrics on different host or port. |
| 34 | + var metricsHost = "0.0.0.0" <1> |
| 35 | + var metricsPort int32 = 8383 <2> |
| 36 | +
|
| 37 | + // Pass metrics address to controller-runtime manager |
| 38 | + mgr, err := manager.New(cfg, manager.Options{ |
| 39 | + Namespace: namespace, |
| 40 | + MetricsBindAddress: fmt.Sprintf("%s:%d", metricsHost, metricsPort), |
| 41 | + }) |
| 42 | +
|
| 43 | + ... |
| 44 | +
|
| 45 | + // Create Service object to expose the metrics port. |
| 46 | + _, err = metrics.ExposeMetricsPort(ctx, metricsPort) |
| 47 | + if err != nil { |
| 48 | + // handle error |
| 49 | + log.Info(err.Error()) |
| 50 | + } |
| 51 | +---- |
| 52 | +<1> Host the metrics are exposed on. |
| 53 | +<2> Port the metrics are exposed on. |
0 commit comments