しまかぜメモ

@kinunoriの雑なメモ

OpenStack で Snapshot(image) の状態をMackerelで監視するスクリプト

久しぶりにRuby書いた。力技感がすごい。
そしてMackerelは本当に便利。使うほどに好きになる。

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
​
require 'httpclient'
require 'json'
​
class Nova
  def keystone
    auth_request_json = '{
      "auth" : { "tenantName" : "テナント名",
      "passwordCredentials" : { "username" : "ユーザ名", "password" : "いつもの" }
      }
    }'
​
    keystone_client = HTTPClient.new
    keystone_endpoint_uri = 'http://OpenStackのURL:35357/v2.0/tokens'
    keystone_response = keystone_client.post_content(keystone_endpoint_uri, auth_request_json, 'Content-Type' => 'application/json' )
    keystone_response_hashed = JSON.parse(keystone_response)
​
    keystone_response_endpoint_parsed = keystone_response_hashed['access']['serviceCatalog'][0]['endpoints'][0]
    @nova_endpoint_uri = keystone_response_endpoint_parsed.values[0]
​
    @keystone_auth_token = keystone_response_hashed['access']['token']['id']
  end
​
  def nova_images
    keystone
​
    nova_images_client = HTTPClient.new(default_header: {"X-Auth-Token" => @keystone_auth_token })
​
    nova_images_endpoint_uri = @nova_endpoint_uri + "/images/detail"
    nova_images_response = nova_images_client.get_content(nova_images_endpoint_uri, "q" => "status" )
    nova_images_response_hasged = JSON.parse(nova_images_response)
​
    return  nova_images_response_hasged
  end
end
​
i = 0
image_init = Nova.new
image_parsed = image_init.nova_images["images"]
image_status = "none"
​
while image_parsed.size > i do
  if image_parsed[i]["status"] != "ACTIVE"
    image_status = image_parsed[i]["name"] + " is " + image_parsed[i]["status"]
    p image_status
  end
  i += 1
end
​
p "snapshots are all active." if image_status == "none"
​
exit (image_status != "none" ? 2 : image_status == "none" ? 0 : 1)

あとは、mackerel-agent.confでカスタムスクリプトを追加してスクリプトを実行すればOK。
snapshot(image)がACTIVE以外のものがあった場合、リスト化してMackerelに表示される。
notification_interval=30、max_check_attempts=3あたりがおすすめ。