summaryrefslogtreecommitdiffstats
path: root/abs/core/xymon/hobbitadd.py
blob: 4ce32a29fb88847f9b89ec1f6dc41469ab1643ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/python2
#polls the hobbit server for ghost clients.  If it finds ghosts it will make a new bb-hosts file
#with the new clients.
#Will not add duplicate clients
#return code of 0 means a new file was written, anything else is an error or no inserts occured
import urllib2
import string
import sys
import MySQLdb
import re


def findghosts():
    ghostitems=[]
    try:
        f = urllib2.urlopen("http://localhost/xymon/hobbit-cgi/ghostlist.sh?SORT=name&MAXAGE=300&TEXT")
    except urllib2.HTTPError, e:
        if e.code != 200:
            print 'error find ghost list'
            sys.exit(1)
    else:
        ghostitems_full = f.readlines()
        f.close()
        #'''<h3><center>Failed to retrieve ghostlist from server</center></h3> #'''
        for i in ghostitems_full:
            if i.find("Failed to retrieve") >= 0  :
                print "exiting because xymon ghost list failed"
                print i
                sys.exit(1)
            if i.find('127.0.0') == -1 :
               ghostitems.append(i.strip())
               print "ghost host found: %s" %i.strip()
            else:
               continue
    #ghostitems = ['192.168.1.233\t\tfeste32', '192.168.1.127\t\tjams3']
    return ghostitems

def readbb():
    bblist = []
    strip_list = []
    try:
        infile = open('/home/xymon/etc/hosts.cfg', 'r')
        #infile = open('/tmp/old-bb', 'r')
    except(IOError), e:
        print "couldn't open hosts.cfg file"
        sys.exit(1)
    else:
        bblist = infile.readlines()
        for line in bblist:
            strip_list.append(line.strip())


    infile.close()
    return strip_list


def ghost_type(ghostlist):
    match_gdict={}
    #query db with ghostname
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    for item in ghostlist:
        host = item.split()[1].strip()
        cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType');",(host))
        hostvalues=cursor.fetchall()
        #this is here in case the db fails
        if len(hostvalues) == 0:
            hostvalues = (('HostSystemType','unknown system'),)

        #should return something like this(('HostSystemType', 'Frontend_only'),)
        #hostvalues = (('HostSystemType', 'Frontend_only'),)
        if  len(hostvalues) == 1:
            #get current systemtype and make it all lowercase
            current_hostvalue = hostvalues[0][1].lower()
            try:
                value = match_gdict[current_hostvalue]
                value.append(item)
                match_gdict[current_hostvalue] = value
            except:
                match_gdict[current_hostvalue] = [item]


    #{'Frontend_only': ['feste32', 'feste3', 'feste33']}
    return match_gdict

def check_duplicate(host_list,server):
    server_no_space=re.sub(r'\s', '',server)
    for line in host_list:
        line_no_space=re.sub(r'\s', '',line)

        if line_no_space.find(server_no_space) > -1  :
            #print "server in hostlist"
            return True
        else:
            continue


    return False

def create_new_hosts(matched_gdict,host_list):
    #loop over key in gdict
    for key,value in matched_gdict.iteritems():
        groupline = "title %s" %key
        #print key
        if key == "unknown system":
            host_append_line = "%s #"
        else:
            host_append_line = "%s #func"

        if groupline in host_list:
            insert_index = host_list.index(groupline) + 1
            for server in value:
                if check_duplicate(host_list,server) == False :
                    #host_append_line = "%s #func" %(server)
                    host_list.insert(insert_index,host_append_line %server)
        else:
            host_list.append(groupline)
            for server in value:
                #host_append_line = "%s #func" %(server)
                host_list.append(host_append_line %server)


    outfile = open("/home/xymon/etc/hosts.cfg","w")
    #outfile = open("/tmp/new-bb","w")
    for i in host_list:
        outfile.write(i + '\n' )
        outfile.close
    return



def go():
    ghostlist = findghosts()
    #print ghostlist

    if len(ghostlist) == 0 :
        sys.exit()

    #match ghosts to system type
    matched_gdict = ghost_type(ghostlist)

    host_list = readbb()
    create_new_hosts(matched_gdict,host_list)

if __name__ == "__main__":
    go()