#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Swift API availability and performance script
#
# Authors:
#   Chris Chandler <cjchand@gmail.com>
#

from swiftclient import client
from statsd import StatsClient
import logging

# Populate variables from ../vars/main.yaml
auth_url       = "{{ openstack.auth_url }}"
username       = "{{ openstack.username }}"
password       = "{{ openstack.password }}"
region         = "{{ openstack.region }}"
tenant         = "{{ openstack.tenant }}"
container_name = "{{ openstack.container_name }}"
verify         =  {{ openstack.insecure }}
statsd_host    = "{{ metrics.statsd_host }}"
statsd_port    =  {{ metrics.statsd_port }}
statsd_prefix  = "{{ metrics.statsd_prefix }}" + "swift"

statsd_client = StatsClient(host=statsd_host, port=statsd_port, prefix=statsd_prefix)
logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        filename='/var/log/openstack-api-availability/check_swift_api.log')

try:
    swift_api_timer = statsd_client.timer('response_time')
    swift_client = client.Connection(user=username,key=password,tenant_name=tenant,authurl=auth_url,auth_version='2.0')
    swift_api_timer.start()
    swift_account = swift_client.get_account()
    swift_api_timer.stop()

    if swift_account and len(swift_account[1]) > 0:
        logging.info('OK: Got Swift account info for %s' % (tenant))
        statsd_client.incr('result.pass')
    else:
        logging.info('Unable to get information for tenant %s' (tenant))
        statsd_client.incr('result.fail')

except Exception as e:
    logging.info(e)
    logging.info('CRITICAL: Failed to get container for tenant %s and user %s' % (tenant, username))
    statsd_client.incr('result.fail')
