#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Swift monitoring script for munin
#
# 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 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
import json

try:
    if sys.argv[1] == "config":
        print 'graph_title Swift cluster dispersion'
        print 'graph_category swift'

        print 'object_missing_two.type GAUGE'
        print 'object_missing_two.label Objects missing two copies'
        print 'object_retries.type GAUGE'
        print 'object_retries.label Objects retries'
        print 'object_copies_expected.type GAUGE'
        print 'object_copies_expected.label Objects copies expected'
        print 'object_missing_one.type GAUGE'
        print 'object_missing_one.label Objects missing one copy'
        print 'object_copies_found.type GAUGE'
        print 'object_copies_found.label Objects copies found'
        print 'object_missing_all.type GAUGE'
        print 'object_missing_all.label Objects missing all copies'
        print 'object_overlapping.type GAUGE'
        print 'object_overlapping.label Objects overlapping partitions'

        print 'container_missing_two.type GAUGE'
        print 'container_missing_two.label Containers missing two copies'
        print 'container_retries.type GAUGE'
        print 'container_retries.label Containers retries'
        print 'container_copies_expected.type GAUGE'
        print 'container_copies_expected.label Containers copies expected'
        print 'container_missing_one.type GAUGE'
        print 'container_missing_one.label Containers missing one copy'
        print 'container_copies_found.type GAUGE'
        print 'container_copies_found.label Containers copies found'
        print 'container_missing_all.type GAUGE'
        print 'container_missing_all.label Containers missing all copies'
        print 'container_overlapping.type GAUGE'
        print 'container_overlapping.label Containers overlapping paritions'
    sys.exit(0)
except IndexError:
    pass

with os.popen("swift-dispersion-report -j %s" \
                  % os.getenv("SWIFT_DISPERSION_CONFIG", "/etc/swift/dispersion.conf")) as report:
    stats = json.load(report)

for type_, values in stats.iteritems():
    for key, value in values.iteritems():
        print "%s_%s.value %d" % (type_, key, value)
