LoginSignup
0
1

More than 3 years have passed since last update.

How to create /metrics on connexion

Posted at

Overview

connexionとはOASを利用してAPIエンドポイントとpython関数をmapするためのpythonパッケージです。

Flaskベースで作成されており、flaskではdecorationで @app.route("/") 等と
エンドポイントを指定してHTTPリクエストと関数の関係を記述していたものを、OAS側に記載することで
ドキュメントと機能の実装を同時にできるという優れもの。

使い方やConnexionの説明は今回の趣旨では無いので詳しくは下記等を参照していただけると良い。

How to create /metrics for Prometheus

connexionはAPIのフロントエンドを作る上で非常に便利だが、そういう使い方なので
実際のAPIを提供しているものについて監視などもできると非常に便利。
昨今はPrometheusを使うのが流行っているようなので同様に作ってみようと思うと
なんらかのexporterを使う or 作ることになる。

flaskをそのまま使っているならばこちらを組み込み、flaskとしてhttp serverを起動する際に
フックしてやればいいのだが、残念ながらconnexionをフックするだけでは動作しない模様。
https://pypi.org/project/prometheus-flask-exporter/

swagger.ymlを読んでいるが故に起動プログラムの所にいきなりの記述はできない。
ということでswagger.ymlから呼ばれるプログラムを上手いことやってやる必要があるようだ。

Create swagger.yml

こんな風に /metrics パスを切り、ここをprometheus向けのexporter URLとする。


  /metrics:
    get:
      summary: Prometheus metrics exporter page
      description: Return metrics for prometheus 
      operationId: prometheus_exporter.Prometheus_exporter.showmetrics
      tags:
        - prometheus
      responses:
        default:
          $ref: '#/components/responses/example'

python method

呼ばれるプログラム自体はこんな風にしておく。
prometheus_clientをロードしREGISTRY等を登録する。
こうしておけばmetricsをええ具合に公開できるようになる。
どのようなデータを公開するかはprometheus_clientの仕様と
入れたいデータに依存するのでこれまた割愛。

#!/usr/bin/env python3
#  -*- coding: utf-8 -*-
from prometheus_client import generate_latest
from prometheus_client import Gauge
from prometheus_client import REGISTRY
from api import hpe


class Prometheus_exporter(object):
    registry = REGISTRY

    @classmethod
    def showmetrics(self):

        metrics = generate_latest(self.registry)
        return metrics, 200

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1