classify-users: determine type of Athena accounts
[user/alex/software/my-snippets.git] / hosts-to-contacts
1 #!/usr/bin/python
2
3 import collections
4 import sys
5
6 import moira
7
8 def find_contact(hostname):
9     try:
10         result = moira.query('get_host', hostname.upper(), '*', '*', '*')
11         assert len(result) == 1
12         return result[0]['contact']
13     except moira.MoiraException, e:
14         print >>sys.stderr, "Got %s while processing %s" % (e, hostname, )
15         return "(err)"
16
17 def find_contacts(hostnames):
18     contact_map = collections.defaultdict(list)
19     for hostname in hostnames:
20         contact = find_contact(hostname)
21         contact_map[contact].append(hostname)
22     return contact_map
23
24 def print_contacts(contact_map):
25     sorted_map = sorted(contact_map.items(), key=lambda x: len(x[1]))
26     for contact, hosts in sorted_map:
27         print "%s\t%d\t%s" % (contact, len(hosts), hosts)
28
29 def init():
30     moira.connect()
31
32 if __name__ == '__main__':
33     hostnames = []
34     for line in sys.stdin:
35         hostnames.append(line.strip())
36     init()
37     contact_map = find_contacts(hostnames)
38     print_contacts(contact_map)