# #!/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 print_resources(hostname, prefix, resources, label):
#     print "# %s" % (label, )
#     resource_dump = [extract_resource_from_map(r)
#                      for r in resources.values()]
#     print "\n".join("%s:%s: %s" % (hostname, prefix, x) for x in sorted(resource_dump))
#     print
#
#
# def report_host_resources(hostname, host_data):
#     host_resources = delete_tags(host_data['computingResources']['resources'])
#     # delete tags
#     print_resources(hostname, "hw", host_resources, "host resources")
#
#     remainder = copy.deepcopy(host_resources)
#
#     if "entities" in host_data:
#         print "# entities"
#         workloads = host_data['entities']
#         for idx, workload in enumerate(workloads):
#             slot = workload['entity']['slot']
#
#             w_resources = delete_tags(workload["computingRequirements"]["resources"])
#             remainder = subtract_resources(remainder, w_resources, slot, get_status(workload))
#     else:
#         print "No entities at host"
#
#     print
#     print_resources(hostname, "remain", remainder, "remainder resources")
#     print
#
#
# def delete_tags(resources):
#     resource_names = resources.keys()
#     for k in resource_names:
#         blob = resources[k]
#         if blob['@class'] in ("ru.yandex.schedulers.cluster.api.computing.NamedCountable",
#                               "ru.yandex.schedulers.cluster.api.computing.PortsUDP",
#                               "ru.yandex.schedulers.cluster.api.computing.PortsTCP"):
#             del resources[k]
#     return resources
#
#
# def subtract_resources(remainder2, w_resources, slot, label):
#     remainder = copy.deepcopy(remainder2)
#
#     for k, v in w_resources.iteritems():
#         if k not in remainder:
#             print "not found:", k
#             continue
#         if k == "ru.yandex.schedulers.cluster.api.computing.RAM":
#             remainder[k]["capacity"] -= v["capacity"]
#         elif k == "ru.yandex.schedulers.cluster.api.computing.HDDSpace":
#             remainder[k]["capacity"] -= v["capacity"]
#         elif k == "ru.yandex.schedulers.cluster.api.computing.CPUPower":
#             remainder[k]["powerPercents"] -= v["powerPercents"]
#             # print "%d%% CPU --> %s -- %s" % (v["powerPercents"], slot, label)
#
#     return remainder
#
#
# def main(hosts):
#     if not hosts:
#         sys.exit("please specify some FQDN to get info about")
#
#     print "# %s" % (datetime.datetime.now(), )
#     print "# downloading cluster state...",
#     sys.stdout.flush()
#
#     start = time.time()
#     # raw = urllib2.urlopen(FULL_CLUSTER_URL).read()
#     raw = open("/Users/abcdenis/tmp/capi.json").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 hostname in sorted(hosts):
#         # print "=== %s ===" % (hostname, )
#         if hostname not in hosts_map:
#             print "ERROR: not found in cluster state"
#             print
#             continue
#
#         host_data = hosts_map[hostname]
#         report_host_resources(hostname, host_data)
#
#
# if __name__ == '__main__':
#     main(sys.argv[1:])
