docker監控工具,docker實現locust+prometheus+grafana性能測試監控

 2023-10-15 阅读 64 评论 0

摘要:1.?Locust + Prometheus + Grafana 簡單總結起來就是:實現一個Locust的prometheus的exporter,將數據導入prometheus,然后使用grafana進行數據展示。 2.安裝python和docker,整個項目框架如下圖所示 commmon可以放置常用的方法,比如

1.?Locust + Prometheus + Grafana

簡單總結起來就是:實現一個Locust的prometheus的exporter,將數據導入prometheus,然后使用grafana進行數據展示。

2.安裝python和docker,整個項目框架如下圖所示

commmon可以放置常用的方法,比如獲取數據,mysql操作等方法

data放置數據

docker監控工具。prometheus_exporter采集locust的性能結果,?locust結果的采集在boomer 項目下有一個年久失修的 exporter 實現——prometheus_exporter.py

import six
from itertools import chain
from flask import request, Response
from locust import stats as locust_stats, runners as locust_runners
from locust import User, task, events
from prometheus_client import Metric, REGISTRY, exposition# This locustfile adds an external web endpoint to the locust master, and makes it serve as a prometheus exporter.
# Runs it as a normal locustfile, then points prometheus to it.
# locust -f prometheus_exporter.py --master# Lots of code taken from [mbolek's locust_exporter](https://github.com/mbolek/locust_exporter), thx mbolek!class LocustCollector(object):registry = REGISTRYdef __init__(self, environment, runner):self.environment = environmentself.runner = runnerdef collect(self):# collect metrics only when locust runner is hatching or running.runner = self.runnerif runner and runner.state in (locust_runners.STATE_SPAWNING, locust_runners.STATE_RUNNING):stats = []for s in chain(locust_stats.sort_stats(runner.stats.entries), [runner.stats.total]):stats.append({"method": s.method,"name": s.name,"num_requests": s.num_requests,"num_failures": s.num_failures,"avg_response_time": s.avg_response_time,"min_response_time": s.min_response_time or 0,"max_response_time": s.max_response_time,"current_rps": s.current_rps,"median_response_time": s.median_response_time,"ninetieth_response_time": s.get_response_time_percentile(0.9),# only total stats can use current_response_time, so sad.# "current_response_time_percentile_95": s.get_current_response_time_percentile(0.95),"avg_content_length": s.avg_content_length,"current_fail_per_sec": s.current_fail_per_sec})# perhaps StatsError.parse_error in e.to_dict only works in python slave, take notices!errors = [e.to_dict() for e in six.itervalues(runner.stats.errors)]metric = Metric('locust_user_count', 'Swarmed users', 'gauge')metric.add_sample('locust_user_count', value=runner.user_count, labels={})yield metricmetric = Metric('locust_errors', 'Locust requests errors', 'gauge')for err in errors:metric.add_sample('locust_errors', value=err['occurrences'],labels={'path': err['name'], 'method': err['method'],'error': err['error']})yield metricis_distributed = isinstance(runner, locust_runners.MasterRunner)if is_distributed:metric = Metric('locust_slave_count', 'Locust number of slaves', 'gauge')metric.add_sample('locust_slave_count', value=len(runner.clients.values()), labels={})yield metricmetric = Metric('locust_fail_ratio', 'Locust failure ratio', 'gauge')metric.add_sample('locust_fail_ratio', value=runner.stats.total.fail_ratio, labels={})yield metricmetric = Metric('locust_state', 'State of the locust swarm', 'gauge')metric.add_sample('locust_state', value=1, labels={'state': runner.state})yield metricstats_metrics = ['avg_content_length', 'avg_response_time', 'current_rps', 'current_fail_per_sec','max_response_time', 'ninetieth_response_time', 'median_response_time','min_response_time','num_failures', 'num_requests']for mtr in stats_metrics:mtype = 'gauge'if mtr in ['num_requests', 'num_failures']:mtype = 'counter'metric = Metric('locust_stats_' + mtr, 'Locust stats ' + mtr, mtype)for stat in stats:# Aggregated stat's method label is None, so name it as Aggregated# locust has changed name Total to Aggregated since 0.12.1if 'Aggregated' != stat['name']:metric.add_sample('locust_stats_' + mtr, value=stat[mtr],labels={'path': stat['name'], 'method': stat['method']})else:metric.add_sample('locust_stats_' + mtr, value=stat[mtr],labels={'path': stat['name'], 'method': 'Aggregated'})yield metric@events.init.add_listener
def locust_init(environment, runner, **kwargs):print("locust init event received")if environment.web_ui and runner:@environment.web_ui.app.route("/export/prometheus")def prometheus_exporter():registry = REGISTRYencoder, content_type = exposition.choose_encoder(request.headers.get('Accept'))if 'name[]' in request.args:registry = REGISTRY.restricted_registry(request.args.get('name[]'))body = encoder(registry)return Response(body, content_type=content_type)REGISTRY.register(LocustCollector(environment, runner))class Dummy(User):@task(2)def hello(self):pass

docker-compose 或者swarm管理locust master和work,這里是單機主從配置

locustfile.py為接口測試設計,下為網上的一個demo

from locust import HttpLocust, TaskSet, task, betweenclass NoSlowQTaskSet(TaskSet):def on_start(self):# 登錄data = {"username": "admin", "password": "admin"}self.client.post("/user/login", json=data)@task(50)def getTables(self):r = self.client.get("/newsql/api/getTablesByAppId?appId=1")@task(50)def get_apps(self):r = self.client.get("/user/api/getApps")class MyLocust(HttpUser):task_set = NoSlowQTaskSethost = "http://localhost:9528"

prometheus.yml文件?prometheus配置文件

global:scrape_interval: 15sevaluation_interval: 15sscrape_configs:- job_name: prometheusstatic_configs:- targets: ['localhost:9090']labels:instance: prometheus- job_name: locustmetrics_path: '/export/prometheus'static_configs:- targets: ['192.168.20.8:8089']labels:instance: locust

?3.用docker built構建locust鏡像,我這里鏡像名為locust:v1,然后執行docker init ,docker stack deploy -c ./docker-compose.yml? test (或者執行docker-compose up -d)啟動locust matser和work,此時就可以訪問locust頁面,http://ip:8089,可以進行性能測試

4.訪問http://masterip:8089/export/prometheus是否正常,也可以執行性能測試,查看該頁面收集數據是否正常

routeros docker、5.安裝prometheus和grafana鏡像

docker pull prom/prometheus
docker pull grafana/grafana

并用下面命令啟動兩個服務

docker run -d --name prometheus -p 9090:9090 -v $PWD/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
docker run -d --name grafana -p 3000:3000 grafana/grafana

啟動之后可通過http://ip:9090/查看prometheus是否啟動正常

6.網頁端訪問 localhost:3000 驗證部署成功

?選擇添加 prometheus 數據源

然后再配置模板,導入模板有幾種方式,選擇一種方式將dashboard模板導入

最后效果展示

?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/144464.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息