#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Keystone monitoring script for Nagios
#
# Copyright © 2012 eNovance <licensing@enovance.com>
#
# Author: Julien Danjou <julien@danjou.info>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys
import argparse
from keystoneclient.v2_0 import client
from keystoneclient import exceptions


STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3


parser = argparse.ArgumentParser(description='Check an OpenStack Keystone server.')
parser.add_argument('--auth_url', metavar='URL', type=str,
                    required=True,
                    help='Keystone URL')
parser.add_argument('--username', metavar='username', type=str,
                    required=True,
                    help='username to use for authentication')
parser.add_argument('--password', metavar='password', type=str,
                    required=True,
                    help='password to use for authentication')
parser.add_argument('--tenant', metavar='tenant', type=str,
                    required=True,
                    help='tenant name to use for authentication')
parser.add_argument('--region_name', metavar='region_name', type=str,
                    help='Region to select for authentication')
parser.add_argument('--no-admin', action='store_true', default=False,
                    help='Don\'t perform admin tests, useful if user is not admin')
parser.add_argument('services', metavar='SERVICE', type=str, nargs='*',
                    help='services to check for')
args = parser.parse_args()


try:
    c = client.Client(username=args.username,
                  tenant_name=args.tenant,
                  password=args.password,
                  auth_url=args.auth_url,
                  region_name=args.region_name)
    if not c.authenticate():
        raise Exception("Authentication failed")
    if not args.no_admin:
        if not c.tenants.list():
            raise Exception("Tenant list is empty")
except Exception as e:
    print str(e)
    sys.exit(STATE_CRITICAL)

msgs = []
endpoints = c.service_catalog.get_endpoints()
services = args.services or endpoints.keys()
for service in services:
    if not service in endpoints.keys():
        msgs.append("`%s' service is missing" % service)
        continue

    if not len(endpoints[service]):
        msgs.append("`%s' service is empty" % service)
        continue

    if not any([ "publicURL" in endpoint.keys() for endpoint in endpoints[service] ]):
        msgs.append("`%s' service has no publicURL" % service)

if msgs:
    print ", ".join(msgs)
    sys.exit(STATE_WARNING)

print "Got token %s for user %s and tenant %s" % (c.auth_token, c.auth_user_id, c.auth_tenant_id)
sys.exit(STATE_OK)
