【Python】JMeter の実行結果をスプレッドシートに出力するスクリプトを書いてみた【gspread】

こんにちは。
JMeter が出力する結果を Google のスプレッドシートに出力してみようと考えまして、調べてみると Python に便利なライブラリがあったんで作ってみました。
※ 下記の JMeter デプロイ用 Playbook にも入れているのでよければご利用くださいませ。
https://github.com/keisukesanuki/jmeter-MS

Python スクリプト

#!/usr/bin/python3

import gspread
import json
import csv
import sys
import itertools

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

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

# 数字と文字コンバーター
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)

第一引数に csv ファイルを指定することで、結果をスプレッドシートに出力するスクリプトです。
このスクリプトを後述の JMeter 起動用スクリプトで利用します。

シェルスクリプト

#!/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}_th${JMETER_THREAD}${2}/ -r

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

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

JMeter は json で結果を出力するので jq で無理やり csv に変換してます。

Python だと簡単に実装できて楽ですね。

補足

スクリプトの実行に下記のパッケージ導入が必要です。

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

【AWS】EBS のスナップショットを取得して世代管理してみる【シェルスクリプト】

こんにちは。
表題の通りです。
DLM でもよいのですが、最長のインターバルが 24 時間なので、要件が合わない時のために。

#!/bin/sh

# スナップショットの保持世代数を定義
LOTATE_NUM=3
# ホストネームを定義
HOSTNAME=
# スナップショットを取得するボリュームIDを定義
VOLID=

# スナップショットを取得
aws ec2 create-snapshot --volume-id $VOLID --tag-specification 'ResourceType="snapshot",Tags=[{Key="Name",Value="script-create"}]' --description "$HOSTNAME snapshot"

# 指定した世代数分になるようにスナップショットを削除
SNAPSHOTS_NUM=`aws ec2 describe-snapshots --output text | grep $VOLID | grep "$HOSTNAME snapshot" | wc -l`
while [ ${SNAPSHOTS_NUM} -gt ${LOTATE_NUM} ]
do
        aws ec2 delete-snapshot --snapshot-id `aws ec2 describe-snapshots --output text | grep $VOLID | grep "$HOSTNAME snapshot" | sort -k 8 | awk 'NR==1 {print $7}'`
        SNAPSHOTS_NUM=`aws ec2 describe-snapshots --output text | grep $VOLID | grep "$HOSTNAME snapshot" | wc -l`
done

# awscli の導入

curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
sudo python get-pip.py
sudo pip install awscli
aws configure

【LINE Notify】シェルスクリプトでWEBスクレイピングしてみた【bash】

よくチェックするサイトに新着記事が投降されたら、LINE NotifyのAPIを叩いて通知するコードを書いてみました。

#!/bin/bash

# LINEのTOKENを定義
TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# WEBページの情報を取得
MSG=`curl https://www.megamouth.info/archive | grep "<a class=\"entry-title-link\"" | sed -e 's/<[^>]*>//g' | nl`
# 作業ディレクトリの定義
OPE_DIR=/opt/SCRAPING/megamouth
# 実行時のWEBページ情報を記録するファイルを定義
INFO_FILE=$OPE_DIR/info.txt
# 前回実行時のWEBページ情報を記録するファイルを定義
PRE_INFO_FILE=$OPE_DIR/pre_info.txt

if [ ! -e $OPE_DIR ]; then
        # ディレクトリの作成
        mkdir -p $OPE_DIR
fi

# 前回実行時の記録ファイルが無ければ作成し通知
if [ ! -e $PRE_INFO_FILE ]; then
        curl https://www.megamouth.info/archive | grep "<a class=\"entry-title-link\"" | sed -e 's/<[^>]*>//g' | nl > $PRE_INFO_FILE
        curl -X POST -H "Authorization: Bearer ${TOKEN}" -F "message=${MSG}" https://notify-api.line.me/api/notify
        exit 0
fi

# 今回取得した情報を変数に代入
curl https://www.megamouth.info/archive | grep "<a class=\"entry-title-link\"" | sed -e 's/<[^>]*>//g' | nl > $INFO_FILE

# 前回と今回取得した情報を比較
diff -s $INFO_FILE $PRE_INFO_FILE

# DIFFの実行結果を変数に代入
DIFF_STATUS=$?

if [ ${DIFF_STATUS} -eq 1 ]; then
        # 前回取得した情報と今回取得した情報に差異があれば通知
        curl -X POST -H "Authorization: Bearer ${TOKEN}" -F "message=${MSG}" https://notify-api.line.me/api/notify
elif [ ${DIFF_STATUS} -eq 2 ]; then
        # diff実行時にエラーが発生すればエラーを通知
        curl -X POST -H "Authorization: Bearer ${TOKEN}" -F "message=error" https://notify-api.line.me/api/notify
fi

# 情報ファイルを更新
cp -fp $INFO_FILE $PRE_INFO_FILE

なんだかもっといろいろと使えそうですね。
アラート通知とか。。
↓皆さんもぜひ
LINE Notify