#!/usr/bin/env python2.7
# coding=utf-8
"""
take FQDN from command line,
loads host data from custer api,
prints host resources, some info about workloads, remainder resources
"""
import copy
import datetime
import json
import sys
import time
import urllib2


FULL_CLUSTER_URL = "http://capi-sas.yandex-team.ru:29100/rest/v0/state/0"


def get_status(workload):
    try:
        state = workload["feedback"]["state"]
    except KeyError:
        state = "UNKNOWN"

    try:
        target_state = workload["entity"]["targetState"]
    except KeyError:
        target_state = "n/a"

    return "%s, target=%s" % (state, target_state)


AT_CLASS = "@class"

def extract_resource_from_map(resource_map):
    resource_name = resource_map[AT_CLASS].split(".")[-1]
    pairs = [x[1] for x in resource_map.items() if x[0] != AT_CLASS]
    try:
        volume = pairs[0]
    except IndexError:
        volume = 0
    return "%s = %s" % (resource_name, volume)


def get_entity_tags(entity):
    return set(x[0] for x in entity["computingRequirements"]["resources"].items() if x[1]["@class"] == "ru.yandex.schedulers.cluster.api.computing.NamedCountable")


def check_r2_entity(entity):
    # if "capi:cluster:r2" in get_entity_tags(entity):
    #     print entity["entity"]["slot"]
    if ("capi:env:prod:vanilla" not in get_entity_tags(entity)) and ("jobapi_production" in get_entity_tags(entity)):
        print entity["entity"]["slot"]


def report_host_resources(host_data):
    if "entities" in host_data:
        workloads = host_data['entities']
        for idx, workload in enumerate(workloads):
            check_r2_entity(workload)


def main():
    print "# %s" % (datetime.datetime.now(), )
    print "# downloading cluster state...",
    sys.stdout.flush()

    start = time.time()
    raw = urllib2.urlopen(FULL_CLUSTER_URL).read()

    print "done. %d bytes, %.2f sec" % (len(raw), time.time() - start)
    sys.stdout.flush()

    full_cluster_state = json.loads(raw)
    print "# cluster state version: %s" % (full_cluster_state["version"], )
    print

    hosts_map = full_cluster_state['hosts']

    for host_data in hosts_map.itervalues():
        report_host_resources(host_data)


if __name__ == '__main__':
    main()
