:>/dev/null

ラガードエンジニアの不撓不屈の精神/unlearning/go beyond

CloudWatchでCustomMetrix設定

表記の通りCloudWatchに監視項目を追加する必要が発生したので調査した時の勉強メモ。

  • CustomMetrix追加手順
    • aws configureがインストールされてない環境での手順
    • cloudwatchのsrcファイル(今回は「CloudWatch-1.0.20.0」)をインストール
    • カスタムメトリクス取得するファイル作成
    • 下記スクリプト内容を記述
    • cron設定にて定期監視
      • ※crontabにて設定した場合環境変数が読み込まれない為各実行コマンド位置までフルパスを指定する必要あり
    • 「cloudwatch→すべて→CustomMetrix→InstanceId→対象インスタンス」の手順にてグラフ化
    • 必要に応じてcloudwatch→ダッシュボード追加

■CustomMetrix監視項目

#!/bin/bash

FILTER="*testItem*"

export AWS_CLOUDWATCH_HOME=/usr/local/bin/CloudWatch-1.0.20.0
export AWS_CREDENTIAL_FILE=$AWS_CLOUDWATCH_HOME/credential
export PATH=$AWS_CLOUDWATCH_HOME/bin:$PATH
export EC2_REGION=ap-northeast-1
export JAVA_HOME=/usr/lib/jvm/jre

InstanceId=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)

NodeCnt=`~/.local/bin/aws ec2 describe-instances --filters "Name=tag:Name,Values=$FILTER" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].[InstanceId]" --output text |wc -l`

echo $NodeCnt

/usr/local/bin/CloudWatch-1.0.20.0/bin/mon-put-data --metric-name "CustomMetrix Item" --namespace "CustomMetrix" --dimensions "InstanceId=$InstanceId" --value "$NodeCnt"

■crontab設定

$ crontab -l
*/5 * * * * /bin/sh /home/centos/chk-item 1> /dev/null

設定に問題無ければ、5分間隔でグラフ描写される。
監視項目(CustomMetrix)の追加が簡易に行えるのawsは便利。

terminal is not big enough

sshターミナル環境でtopコマンド発行時、terminal is not big enoughが表示され出力されないので調査した時の勉強メモ。

  • sshターミナルでtopコマンド発行
    • 発生内容:Sorry, terminal is not big enough
    • 対応:代替えコマンド発行(mpstat -P ALL)
[root@**** ~]# top
top - 12:29:03 up 67 days, 47 min,  1 user,  load average: 0.17, 0.15, 0.15
Tasks: 648 total,   1 running, 647 sleeping,   0 stopped,   0 zombie
Cpu(s):  1.7%us,  0.4%sy,  0.0%ni, 97.9%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Mem:  132111780k total, 85066756k used, 47045024k free,   370724k buffers
Swap:   524284k total,   250892k used,   273392k free, 75117400k cached
 Sorry, terminal is not big enough
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 3256 root      20   0 15.2g 4.2g 5212 S 50.2  3.3  16477:55 ruby
17742 root      20   0 15424 1564  832 R  3.9  0.0   0:00.02 top
    1 root      20   0 19340 1348 1124 S  0.0  0.0   0:01.96 init

↑でSorry, terminal is not big enough発生。

■代替えコマンド発行

[root@**** ~]# mpstat -P ALL
Linux 2.6.32-696.16.1.el6.x86_64 (www.test.co.jp)   12/11/2018  _x86_64_    (32 CPU)

12:24:03 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
12:24:03 PM  all    1.65    0.00    0.39    0.00    0.00    0.07    0.00    0.00   97.88
12:24:03 PM    0    1.80    0.00    0.60    0.01    0.00    0.06    0.00    0.00   97.53
12:24:03 PM    1    1.71    0.00    0.31    0.00    0.00    0.00    0.00    0.00   97.97
...

CPUコア毎に確認出来た。
さまざまなアプローチ方法を知っているかがポイントになる。

aws環境でfluentd経由を用いたログ基盤構築

aws環境でログ基盤を構築する必要があり、周辺関連の知識がたりなさすぎたので調査した時の勉強メモ。

  • lamda関数
    • 処理フロー
    • クラアント(td-agent)→Kinesis firehose→lamdba→s3 f:id:oguguman:20181103205729p:plain
#
# lamdba
#

import boto3
import json
import base64

import time
import sys 
import pprint
from datetime import datetime

def lambda_handler(event, context):
    firehose = boto3.client('firehose')
    s3 = boto3.resource('s3')
    output = []
    
#
# firehose
# 

        import pprint; pprint.pprint('firehose------')
        import pprint; pprint.pprint(firehose)
        
        strjson = json.dumps('ccc')
        encodedata = base64.b64encode(strjson.encode())
        output_json = {
            'recordId': event['records'][num]['recordId'],
            'result': 'Ok',
            'data': event['records'][num]['data'],
        }
        output.append(output_json)
        
        import pprint; pprint.pprint(event)
        import pprint; pprint.pprint(event['records'])
        import pprint; pprint.pprint(event['records'][num]['recordId'])

#
# s3
#

        bucket = 'testfirehosetokyo'
        key = 'test/test_' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.txt'
        file_contents = str(output)
    
        time_info = []
        stime = time.time()
        s3_obj = s3.Object(bucket, key)
        result = s3_obj.put( Body=file_contents )
        etime = time.time()
        time_info.append(etime - stime)


    return {
        'records': output
    }      
  • GlueでETL処理
    • 処理フロー
    • s3→Glueで既存項目にColumn追加→s3(指定パスへ出力)
      f:id:oguguman:20181104132207p:plain
#
# Glue
#

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame
from pyspark.sql.functions import *
from pyspark.sql.functions import lit

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

# 引数からパスを生成
basepath = "s3://testfirehosetokyo/sample_glue_for_result"
s3path = basepath + "/test"

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
## @type: DataSource
## @args: [database = "sample_glue_db", table_name = "10", transformation_ctx = "datasource0"]
## @return: datasource0
## @inputs: []
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "sample_glue_db", table_name = "10", transformation_ctx = "datasource0")
## @type: ApplyMapping
## @args: [mapping = [("time", "string", "time", "string"), ("message", "string", "message", "string"), ("worker", "int", "worker", "int")], transformation_ctx = "applymapping1"]
## @return: applymapping1
## @inputs: [frame = datasource0]
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("time", "string", "time", "string"), ("message", "string", "message", "string"), ("worker", "int", "worker", "int"),("time", "string", "testcol", "string")], transformation_ctx = "applymapping1")
## @type: DataSink
## @args: [connection_type = "s3", connection_options = {"path": "s3://testfirehosetokyo/sample_glue_for_result"}, format = "json", transformation_ctx = "datasink2"]
## @return: datasink2
## @inputs: [frame = applymapping1]
#datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1, connection_type = "s3", connection_options = {"path": "s3://testfirehosetokyo/sample_glue_for_result"}, format = "json", transformation_ctx = "datasink2")

df = applymapping1.toDF()
#Column追加
df = df.withColumn('pint2', lit(123))
dyf = DynamicFrame.fromDF(df, glueContext, 'dyf')

# DynamicFrameをJSON形式でS3に書き出す 
glueContext.write_dynamic_frame.from_options( 
    frame=dyf, 
    connection_type='s3', 
    connection_options={'path':s3path}, 
    format='json')
  • ログ送信側クラアント設定
    • 処理フロー
    • クラアント(td-agent)→Kinesis firehose
      f:id:oguguman:20181104132054p:plain
#
# td-agent
#

yum install redhat-lsb-core
yum install aws-kinesis-agent
td-agent-gem install fluent-plugin-kinesis

※1x系(version指定)
td-agent-gem install fluent-plugin-kinesis --no-document -V -v 1.3.0


[root@vm**** td-agent]# cat teststream.conf
<source>
  type tail
  path /tmp/testlog.log
  pos_file /tmp/testlog.pos
  format none
  message_key log_line
  tag teststream.test.test
</source>

<match teststream.**>
  type kinesis_firehose

  region ap-northeast-1
  delivery_stream_name teststream
  flush_interval 1s
  include_time_key true
  include_tag_key true
  buffer_chunk_limit 1m
  try_flush_interval 0.1
  queued_chunk_flush_interval 0.01
  num_threads 1
</match>

まずは触ってみたが関連知識が不足しているのが実感できた。。
1歩ずつでも触ってアウトプットして行こう。

td-agentでログ欠損が発生した

fluent(td-agent)で、Buffer溢れにによるログ欠損が発生したのでその時の調査・対応を下記へ記載しておく。

・対応フロー

  • コンソールからtd-agentのログ状況確認
  • Bufferの蓄積状況確認
  • td-agent.conf確認
  • td-agent.conf設定変更
  • td-agnetサービス再起動

以下、設定環境:td-agent version0.12

□ Kibana上でログ欠損が発生

・コンソールからtd-agentのログ状況確認

# less /var/log/td-agent/td-agent.log
2018-09-11 03:28:43 +0900 [warn]: emit transaction failed: error_class=Fluent::BufferQueueLimitError error="queue size exceeds limit" tag="www.nginx.access-json"
  2018-09-11 03:28:43 +0900 [warn]: /opt/td-agent/embedded/lib/ruby/gems/2.1.0/gems/fluentd-0.12.40/lib/fluent/buffer.rb:204:in `block in emit'

queue size exceeds limitが発生してる。

・Bufferの蓄積状況確認

# cd {buffer_dir}
# ll -h /data/buffer/secure-forward.* |wc -l
2054

・td-agent.conf設定確認 (一部抜粋)

# less td-agent.conf
        buffer_chunk_limit  2m
        buffer_queue_limit  2048

・td-agent.conf設定変更 (一部抜粋)

# less td-agent.conf
        buffer_chunk_limit  2m
        buffer_queue_limit  4096

↑の設定変更によりログが流れた。
※今回、master -> standby構成を組んだがmaster側でBuffer溢れが発生している状況においても、standby側に流れない状況

また、今回設定した送信部分のconf内容を抜粋して記載。

  <match **>
    @id testid.match
    @type forest
    subtype copy
    <template>
      <store>
        @id secure_forward
        @type secure_forward
        self_hostname test123.co.jp
        shared_key testkey
        secure yes
        ca_cert_path /etc/td-agent/ca/ca-cert.pem
        keep_alive 300
        num_threads 1
        <server>
          host testbudder.co.jp
          port 24284
          username test
          password ******
        </server>
        flush_interval 0s
        try_flush_interval  0.1
        queued_chunk_flush_interval 0.01
        buffer_type file
        buffer_path /data/buffer/secure-forward_${tag}.*
        buffer_chunk_limit  2m
        buffer_queue_limit  6000000 # 2 * 6000000 = 120T
        retry_wait 5s # default: 1.0
#        retry_limit 10
        reload_connections true
        reload_on_failure true
        heartbeat_type tcp
        heartbeat_interval 10s

        phi_threshold 100 # default: 16
        hard_timeout 200s # default: equals to send_timeout
        require_ack_response true
        send_timeout 60s # default 60s
        ack_response_timeout 61s # default 190s

        max_retry_wait 1h # default: inifinity
        disable_retry_limit true # DO NOT discard buffer anyway
        require_ack_response true # Qos 1 (At least once)
        flush_at_shutdown true
      </store>
    </template>
  </match>

上記設定でログ欠損発生せず稼働している。

ref

fluentd 1.0 でログの欠損を防ぐ · the world as code

ansible playbook performance tuning

ansibleでplaybookを書いていたが、大規模化するにつれ実行時間を要するようになり調査・対応を下記へ記載しておく。

以下、設定環境:ansible version2.1

・ansible.confパラメータチューニング

# cat .ansible.cfg
[defaults]
transport=ssh
pipelining=True
forks=100

fact_caching = jsonfile
fact_caching_connection = /tmp/cache
fact_caching_timeout = 86400 # seconds

[ssh_connection]
ssh_args=-o ControlMaster=auto -o ControlPersist=30m
scp_if_ssh=True
control_path=%(directory)s/%%h-%%r

・strategy設定(linear, free)

  • linear
    • 今まで(〜1.9)と同じ動作
    • 全てのホストでそれぞれのタスクを次タスクに行く前に終わらせる
    • 並列処理で各ホストのタスクを実施する
    • デフォルトは5並列で並列数の設定が可能
    • 1.9以前と同様、serialパラメータとの併用で並列数が設定出来る
  • free
    • ホスト間においてタイミングの調整など取らずとにかく早く終わるように実行する

playbookにstrategyを記載

# cat test.yml

---
- hosts: testhosts
  become: yes
  strategy: free
  become_method: su
  become_user: root
  roles:
     - td-agent

規模が大きくなる場合、playbook実行に時間を要するようになる。
上記で設定でパフォーマンス改善が見込めそう。cacheをMWにする事によりより汎用性が高まりそうではある。

mongodbでのslowlog設定

Mongodb に関してslowlog出力設定での調査・対応を下記へ記載しておく。
mongosに設定追加は「profile currently not supported via mongos」とエラーとなる為、shard(mongod)に設定をする。
mongodへ設定追加後、mongosで解析行う。

  • 以下対応フロー
    • mongodで起動パラメータ追加(ログにスロークエリを出力)
      • /etc/init.d/mongodへパラメータ設定
    • 設定ファイルの出力確認
    • 必要に応じて閾値調整
    • db.currentOp()
      • 実行中のクエリを確認
    • db.coll.find().explain()
      • 実行計画を確認

以下、設定環境:mongo version2.4

・起動時パラメータ追加方法

#vi /etc/init.d/mongod

//--profile
//プロファイルのレベル
//1: 閾値以上の時間のかかったクエリを残す
//2: 全てのクエリを残す
//
//--slowms
//閾値(ms)

#OPTIONS=" -f $CONFIGFILE"
OPTIONS=" -f $CONFIGFILE --profile=1 --slowms=100"

・出力サンプルイメージ

Thu Aug  9 14:10:09.069 [conn40] query testsite_mongo.offerwall_click_data query: { $query: { $and: [ { app_id_to: 100 }, { user_id: "10999999" } ] }, $orderby: { create_date: -1 } } planSummary: IXSCAN { create_date: 1.0 } ntoreturn:2 ntoskip:0 nscanned:128538 nscannedObjects:128538 keyUpdates:0 numYields:0 locks(micros) r:113561 nreturned:0 reslen:20 113ms

上記での嵌ったポイントとして設定ファイルへの出力方法がある。
mongo shellから実行する場合、オンライン(db.setProfilingLevel(1,20))にてON/OFF可能であるがファイル出力方法に時間を要した。
※出力先はsystem.profileというcollectionに収集され、ログ出力されない
起動時のパラメータを上記設定追加する事で正常稼働した。

ref)

MongoDBで実行したクエリをログに出力する

hiyokur.hatenablog.com

stackoverflow.com

https://www.mysoftkey.com/mongodb/profiling-for-slow-query-log-in-mongodb/

logrotate設定のエラー改善されない事象に関して

apacheaccess_logをカスタム出力設定後、ローテート設定したが正常稼働せず調査・対応を下記へ記載しておく。

  • 以下対応フロー
    • apacheaccess_logを稼働出力設定する
    • ログローテート設定に上記出力したファイルをローテート設定
    • ログローテート実行
    • ログローテートエラー発生
    • ログローテート設定修正
    • ログローテート再実行
      • ログローテートエラー改善されず
    • ログローテートスタータスファイル削除
    • ログローテート再実行
      • ログローテート正常稼働

以下ポイント部分のみ抜粋

// option
// d:dry run
// v:詳細出力
// f:強制実行

// ログローテートテスト実行
# /usr/sbin/logrotate -dv /etc/logrotate.d/apache

// ログローテート実行
# /usr/sbin/logrotate /etc/logrotate.d/apache

// ログローテート強制実行
# /usr/sbin/logrotate -f /etc/logrotate.d/apache

// ログローテート状況保存ファイル削除
# rm /var/lib/logrotate.status

上記での嵌ったポイントとして/var/lib/logrotate.statusファイル削除を行ってない場合エラー改善されない事がある