[Osaka/Yokohama] Looking for infrastructure/server side engineers!

[Osaka/Yokohama] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Low cost] Wasabi object storage construction and operation service

[Low cost] Wasabi object storage construction and operation service

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “beSIM”

[Compatible with over 200 countries] Global eSIM “beSIM”

[Compatible with Chinese corporations] Chinese cloud / server construction, operation and maintenance

[Compatible with Chinese corporations] Chinese cloud / server construction, operation and maintenance

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

【Python3】JMeterの実行結果をgoogleスプレッドシートに出力してみる【gspread】

こんにちは。
SS チームのしめじです。
時折、負荷試験の案件に携わることがあるのですが、JMeter の実行結果を毎回記録するのが怠かったので、実行結果を google スプレッドシートに出力するスクリプトを作ってみました。
Let's 自動化!!

事前準備

下記3点を事前に準備する必要があります。
・Google Drive API / Google Sheets APIの有効化
・秘密鍵( JSON データ)のダウンロード
・スプレッドシートの共有設定

諸々は下記からどうぞ!
https://console.developers.google.com/

それと、必要なパッケージ類は事前にインストールしておいてくださいね。
※ CentOS7 であれば、下記コマンドで OK です!

yum install python3 python-devel jq
pip3 install gspread
pip3 install oauth2client

スクリプト1( Python )

コマンドライン引数に指定した csv をスプレッドシートに出力する Python スクリプトです。
Python には「gspread」というスプレッドシート操作用の便利なライブラリがあるので、ありがたく利用させて頂きます。

#!/usr/bin/python3

import gspread
import json
import csv
import sys
import itertools

# シークレットキーを絶対パスで指定
SECRETJSON = "/usr/local/jmeter/bin/sacred-drive.json"
# スプレッドシートキーを定義
SPREADSHEET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

############################################################################
## 関数

# 数字と文字コンバーター
def num2alpha(num):
    if num<=26:
        return chr(64+num)
    elif num%26==0:
        return num2alpha(num//26-1)+chr(90)
    else:
        return num2alpha(num//26)+chr(64+num%26)

#############################################################################
## 認証

# お約束
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']

# ダウンロードした json ファイルを定義
credentials = ServiceAccountCredentials.from_json_keyfile_name(SECRETJSON, scope)

# Google API にログイン
gc = gspread.authorize(credentials)

# スプレッドシートのシート1を開く
worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1


##############################################################################
## 処理

# コマンドライン引数を取得
args = sys.argv
csvfile = args[1]

# CSV ファイルの内容を配列に代入
with open(csvfile) as fp:
    results_list_ex = list(csv.reader(fp))

# 2次元配列を1次元配列に変換
results_list = list(itertools.chain.from_iterable(results_list_ex))

# カウント変数初期化
COUNT_NUM = 1
# 空白行探索
while str(len(worksheet.cell(COUNT_NUM, 1).value)) != "0":
        COUNT_NUM += 1

# 編集する範囲を指定
cell_list = worksheet.range('A'+str(COUNT_NUM)+':'+num2alpha(len(results_list))+str(COUNT_NUM))

# cell_listにresults_listの配列を代入
for i,cell in enumerate(cell_list):
    cell.value = results_list[i]

# 結果の保存
worksheet.update_cells(cell_list)

下記2点は適宜環境に併せる必要があります。
・「SECRETJSON」に Google API の秘密鍵ファイルを指定してください。
・「SPREADSHEET_KEY」に結果を出力するシートのキーを指定してください。

こちらの Python スクリプトを後述のシェルスクリプトで利用します。

スクリプト2(シェルスクリプト)

#!/bin/sh

DATE=$(date +"%Y%m%d")
OPTIME=$(date +"%Y%m%d-%H%M%S")
# 結果出力先ディレクトリを指定
LOGDIR=/var/www/html/${DATE}
# JMX ファイルを指定
FILE_JMX=/usr/local/jmeter/bin/templates/build-web-test-plan.jmx

# 日付ディレクトリの作成
mkdir -p ${LOGDIR}

# JMeter 実行
/usr/local/jmeter/bin/jmeter -Dsun.net.inetaddr.ttl=0 -n -t ${FILE_JMX} -j ${LOGDIR}/${OPTIME}.log -l ${LOGDIR}/${OPTIME}.jtl -e -o ${LOGDIR}/${OPTIME}/ -r

# CSV ファイルの作成
cat ${LOGDIR}/${OPTIME}/statistics.json | jq  -r ". [] | [.transaction,.sampleCount,.errorCount,.errorPct,.meanResTime,.minResTime,.maxResTime,.pct1ResTime,.pct2ResTime,.pct3ResTime,.throughput,.receivedKBytesPerSec,.sentKBytesPerSec] | @csv" | grep "Total" > ${LOGDIR}/${OPTIME}/statistics.csv

# スプレッドシートに結果を出力
/usr/local/bin/main.py ${LOGDIR}/${OPTIME}/statistics.csv

json で出力された結果を csv に整形して、Python スクリプトに渡してあげる感じですね。
スクリプトの処理内容としては、
① JMeter を実行
② json 形式の結果を csv に変換
③ csv を読み込んで、スプレッドシートにアペンド
みたいな感じです。

使用例

実際に使ってみましょう!

[root@test-server2-1 bin]# ./start-controller_cui.sh
Creating summariser 
<summary>
Created the tree successfully using /usr/local/jmeter/bin/templates/build-web-test-plan.jmx
Configuring remote engine: 192.168.33.11
Starting remote engines
Starting the test @ Thu Jun 25 04:59:38 JST 2020 (1593028778488)
Remote engines have been started
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump message on port 4445
summary =      2 in 00:00:02 =    1.2/s Avg:   215 Min:   139 Max:   291 Err:     0 (0.00%)
Tidying up remote @ Thu Jun 25 04:59:41 JST 2020 (1593028781684)
... end of run
[root@test-server2-1 bin]# ls /var/www/html/20200625/20200625-033715_th/statistics.csv
/var/www/html/20200625/20200625-033715_th/statistics.csv

うん、正常に実行されましたね! CSV ファイルも作成されているみたいです。
肝心のスプレッドシートを確認してみましょう。

できたー。
もう一回実行してみましょう!

ちゃんと次の行に出力されていますね。OK です!

終わりに

如何でしたでしょうか?
Python の豊富なライブラリを使用すれば、かなり手軽に簡単に実装することが出来ますね。

あと、将来的には以下のような項目も同時に出力できるように機能改修していきたいです。

1. 実行した時間( YYYY/MM/DD hh:mm:ss )
2. JMeter の実行パラメータ
・コントローラーの台数
・スレーブの台数
・スレッド数
・ループ回数
・ランプUPタイム
3. JMeter が出力した HTML ファイルへのリンク

ではでは。

この記事がお役に立てば【 いいね 】のご協力をお願いいたします!
0
読み込み中...
0 票, 平均: 0.00 / 10
1,217
X facebook はてなブックマーク pocket
[2024.6.30 CentOS support ended] CentOS server migration solution

[2024.6.30 CentOS support ended] CentOS server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

[Osaka/Yokohama] Actively recruiting infrastructure engineers and server side engineers!

The person who wrote this article

About the author

Shimeji mushrooms

CERTIFICATE:
- TOEIC 835
- LPIC304
- AWS Solution Architect Associate
- AWS Solution Architect Professional
- GCP Professional Cloud Architect
- IPA SC (not registered)

Kagome, Kagome,
the old man behind me, that's it.

It's my uncle. (2018)