summaryrefslogtreecommitdiffstats
path: root/abs/core/xymon/hbnotes.py
blob: d18a606f44b3969a2b5cd385bc630a124a454950 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# import MySQL module

import MySQLdb
import sys
import getopt
import socket
import os


def create_dot_file():

    try:
        import  ignoreclient
        ignorehostlist=ignoreclient.ignorehosts
    except:
        print "could not find the ignore list"
        ignorehostlist="'ignoreme'"



    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    cursor = db.cursor()

    SQL="SELECT DISTINCT(hostname) from settings where hostname not in(%s)"
    cursor.execute(SQL %ignorehostlist)
    result = cursor.fetchall()
    frontonly="_FRONTEND_"
    masterbackend="_MASTERBACKEND_"
    masterbacked_w_fe="_MASTERFRONTEND_"
    slave_w_fe="_SLAVEFE_"
    slave="_SLAVEBACKEND_"
    stand_alone="_STANDALONE_"
    dotMBE=""
    dotfrontend=list()
    dotslave=list()
    dotslavefe=list()
    tunerdict = {}
    for row in result:
       hostname = row[0]
       dot_hostname = row[0].replace('.','_')
       dot_hostname = row[0].replace('-','__')
       #Find the system type
       cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HostRunFrontend');",(row))
       hostvalues=cursor.fetchall()
       if  len(hostvalues) == 2:
          if hostvalues[1][1] == 'Frontend_only':
             frontonly+=","+dot_hostname
             dotfrontend.append(dot_hostname)

          elif hostvalues[1][1] == 'Standalone':
             stand_alone+=","+dot_hostname
             dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Standalone  \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
             dotfrontend.append(dot_hostname)
             cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
             tuners=cursor.fetchall()
             tstring=""

             if len(tuners) == 0:
                 tunerdict["MBE"]="no tuners \\n"
             else:
                for t in tuners:
                    tstring+=t[0]
                    tstring+=t[1]
                    tstring+='\\n'
                    tunerdict["MBE"]=tstring

          elif hostvalues[1][1] == 'Master_backend':

              if hostvalues[0][1]=='0':
                  masterbackend+=","+dot_hostname
                  dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Master Backend \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
              else:
                  masterbacked_w_fe+=","+dot_hostname
                  dotMBE="MBE" + " [ label=\"" + dot_hostname  + "  \\n Master Backend with frontend  \" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=blue4 style=filled   ] "
                  dotfrontend.append(dot_hostname)
              cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
              tuners=cursor.fetchall()
              tstring=""

              if len(tuners) <= 0:
                tunerdict["MBE"]="no tuners \\n"
              else:
                #print tuners
                for t in tuners:
                        tstring+=t[0]
                        tstring+=t[1]
                        tstring+='\\n'
                        tunerdict["MBE"]=tstring

          elif hostvalues[1][1] == 'Slave_backend':
              cursor.execute("select cardtype,defaultinput  from capturecard  where hostname=%s;",(row))
              tuners=cursor.fetchall()
              #slave withoutfe
              if hostvalues[0][1]=='0':
                  slave+=","+dot_hostname
                  dotslave.append(dot_hostname)
                  tstring=""
                  if len(tuners) <= 0:
                      tunerdict["STUNER"+dot_hostname]="No Tuners"
                  else:
                      for t in tuners:
                            tstring+=t[0]
                            tstring+=t[1]
                            tstring+='\\n'
                            tunerdict["STUNER"+dot_hostname]=tstring
              else:
                  #slave with fe
                  tstring=""
                  if len(tuners) <= 0:
                     tunerdict["STUNER"+dot_hostname]="No Tuners"
                  else:
                      for t in tuners:
                            tstring+=t[0]
                            tstring+=t[1]
                            tstring+='\\n'
                            tunerdict["STUNER"+dot_hostname]=tstring
                  slave_w_fe+=","+dot_hostname
                  dotslave.append(dot_hostname)
                  dotfrontend.append(dot_hostname)


#----------------------------------Create graphviz dot files
    dotfilename="/home/xymon/server/etc/mythdot"
    try:
        dotfile=open(dotfilename,'w')
        dotfile.write("digraph G {   " + "\n" )
        dotfile.write("graph [bgcolor=transparent]" + "\n" )
        #print tunerdict

        #define the nodes
        dotfile.write( dotMBE + "  \n" )

        dotfile.write("tunermbe"+   " [ label= \"" + tunerdict["MBE"] +     "\" , shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tuner.png\"   fontcolor=\"white\"  color=red ]  \n" )

        for fe in dotfrontend:
            dotfile.write("FEND"+fe + "[ label=\"frontend \\n " + fe +     "\" ,shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tv.png\" , fontcolor=\"white\" , imagescale=\"true\"  color=\"gold2\" ]   \n" )

        for fe in dotslave:
            cslave="STUNER"+fe
            #adding tuners to dot file
            if tunerdict[cslave] != "" :
                dotfile.write(cslave+   " [ label= \"" + tunerdict[cslave] +     "\" , shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/tuner.png\"   fontcolor=\"white\"  color=red ]  \n" )
            #adding slave to dot file
            dotfile.write("SLAVE"+fe + "[ label=\"slave backend \\n " + fe +     "\" shapefile=\"/data/srv/httpd/htdocs/xymon/gifs/be.png\"  fontcolor=\"white\"  color=green ]   \n" )

        #connect up the nodes!
        dotfile.write("tunermbe -> MBE  [color=\"red\"] \n  "  )

        for fe in dotfrontend:
            dotfile.write("MBE  -> FEND" + fe + "[color=\"gold2\"]   \n  "  )

        for fe in dotslave:
            cslave="STUNER"+fe
            dotfile.write("SLAVE" + fe + "-> MBE [color=\"green\"]  \n  "  )
            if tunerdict[cslave] != "" :
                dotfile.write(cslave + "-> SLAVE"+fe +  "[color=\"red\"]"  "\n"  )



        dotfile.write("}  " + "\n"   )
        dotfile.close()
    except:
        print "Problem writing %s" %dotfilename


    cmd="/usr/bin/unflatten -l1 -c3 -f " + dotfilename + " |/usr/bin/dot -Tpng  -o/data/srv/httpd/htdocs/xymon/gifs/network.png "
 #   cmd="/usr/bin/circo -Tpng  -o/data/srv/httpd/htdocs/xymon/gifs/network.png " + dotfilename

    results=os.popen(cmd,'r')
    return frontonly,masterbackend,masterbacked_w_fe,slave_w_fe,slave,stand_alone





def createdropdown(currenthostype):
    dir = "/data/storage/disk0/backup/system_backups"
    dropdown='''
    </br>
     <input name="param2" type="radio"  value="Restore" />Restore Database: </>
     <select name="param1">\n'''
    os.chdir(dir)
    if os.path.exists(dir):
        files = os.listdir(dir)
        files.sort(key=lambda x: os.path.getmtime(x) , reverse=True)
        #for file in os.listdir(dir):
        if len(files) > 20:
            del files[20:]

        for file in files:
            if (file.endswith(".tgz")):
                dropdown+='        <option value="' + file + '">' + file + '</option> \n'
    dropdown+='''
    </select>
    </br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="param8" >Partial Restore<br>

    <br>
    <input name="param2" type="radio" value="Upload"  />Upload File to Restore: </>
    <input name="uFile"  type="file" size="40">

    <br><br>
    <input name="param2" type="radio" value="Backup" checked="checked" />Backup System<br />
    '''

    #This is for the d/l backup option
    dropdown+='''

    </br>
    <input name="param2" type="radio"  value="Dbackup" />Download Backup: </>
    <select name="param7">\n\n </br>'''

    for file in files:
        if (file.endswith(".tgz")):
            dropdown+='        <option value="' + file + '">' + file + '</option> \n'

    dropdown+='''
    </select>

    </br>
    </br>
    <input name="param2" type="radio" value="Optimize"  />Optimize Database<br />
    '''

    if currenthostype == "Master_backend":
        dropdown+='</br><input name="param2" type="radio" value="ShutdownAll"  />Shutdown All Systems (except master backend)<br /> \n'

    #Add option to restart MBE
    dropdown+='</br> <input name="param2" type="radio" value="RestartMBE"  />Restart MBE service<br /> \n'

    dropdown+='''    </br></br>\n'''
    return dropdown


def create_notes():
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    cursor.execute("SELECT DISTINCT(hostname) from settings")
    result = cursor.fetchall()
    for row in result:
       #cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HostHwuuid');",(row))
       cursor.execute("select value,data  from settings where hostname=%s and value in ('HostSystemType','HardwareProfilePublicUUID');",(row))
       hostvalues=cursor.fetchall()
       #This is here to ignore non LinHES hosts, or those that don't have a HostSystemType
       if len(hostvalues) == 0:
           continue
       found_uuid="false"
       filename="/home/xymon/server/www/notes/"
       filename+=str(row[0])
       filename+=(".html")
       try:
            file = open(filename,'w')
       except:
            print "problem opening %s" %filename
            continue

       string='''
<html>
<head>  <style type="text/css">@import "/frame.css";</style>
<SCRIPT>

function do_submission()
{
  document.form.submit();
}


function Do_it ()
{
    chosen = ""
    len = document.form.param2.length
    for (i = 0; i <len; i++)
    {
        if (document.form.param2[i].checked)
        {
            chosen = document.form.param2[i].value
        }
    }


    if (chosen == "Restore")
    {
        if (confirm('Continue with database restore?'))
        {
            do_submission();
            }
        else
        {
            alert("The database was not restored.");
        }
    }
    else if (chosen == "Backup")
    {
        if (confirm('Continue with database backup?'))
        {
            do_submission();
        }
        else
        {
            alert("Backup cancelled.");
        }
    }
    else if (chosen == "Upload")
    {
        if (confirm('Upload the backup file to the server?'))
        {
            do_submission();
        }
    }
    else if (chosen == "Optimize")
    {
        if (confirm('Continue with database maintenance?'))
        {
            do_submission();
        }
        else
        {
            alert("Optimization cancelled.");
        }
    }



    else if (chosen == "Shutdown")
    {
        if (confirm('Continue with server shutdown?'))
        {
            do_submission();
            alert("The system is powering off.");
        }
    }

    else if (chosen == "Reboot")
    {
        if (confirm('Continue with server restart?'))
        {
            do_submission();
            alert("The system is restarting.");
        }
    }

    else if (chosen == "ShutdownAll")
    {
        if (confirm('Continue with powering off all servers except master backend?'))
        {
            do_submission();
            alert("Systems are powering off.");
        }

    }

    else if (chosen == "Update")
    {
        if (confirm('Continue with applying updates?'))
        {
            do_submission();
        }

    }

    else
    {
        //alert("not restore")
        do_submission();
    }
}

</SCRIPT>
</head>

'''
       file.write(string)

       for i in range( 0 , len(hostvalues)):
            value=hostvalues[i][0]
            data=hostvalues[i][1]
            currenthostype=''
            currenthostname=''
            #if  value == "HostHwuuid" :
            if  value == "HardwareProfilePublicUUID" :
                if data != "blank" :
                    found_uuid="true"
                    uuid=data
            if value == "HostSystemType" :
                currenthostname= str(row[0]).strip()
                currenthostype=str(data).strip()
                header="<h1>" + currenthostname + " (" + currenthostype + ") </h1>"
                file.write(header + '\n')


       if found_uuid == "true" :
            string=str("http://smolt.mythtv.org/client/show?uuid=")
            string+=str(uuid)
            file.write("<A href=\""  )
            file.write(string)
            file.write("\" >" +  str(uuid)   + "</A>")
       else:
            file.write( "uuid  not found, please submit a hardware profile" )
       buttonform_top='''
    <div id="resultbox" >
        <form name="form" action="/process.py"  enctype="multipart/form-data" method="POST" >
    '''


       buttonform_bottom='''
       </br>
        <input name="param2" type="radio"  value="Update" />Update System: </>
            <select name="param3">
                <option value="Myth_only">Myth only</option>
                <option value="All"> Full System</option>
            </select>
        </br>
        </br>
        <input name="param2" type="radio"  value="Kill" />Restart Interface: </>
            <select name="param6">
                <option value="killmyth">MythFrontend</option>
                <option value="killX">Full UI</option>
            </select>
        </br>
        </br>
        <input name="param2" type="radio"  value="Shutdown" />Shutdown System<br />
        </br>
        <input name="param2" type="radio"  value="Reboot" />Reboot System<br />
        </br>
        <input name="param2" type="radio"  value="WOL" />Wake on LAN<br />
        </br>
        <input name="hiddenparam" type="hidden" value="
    '''

       oldurlform=''' "/>
        <input name="param4" type="hidden" value="
    '''
       closetag='''
           "/>
        </br>
    </div>
    </br>
    <div id="center_button" >
        <!--<input id="submitbutton" type="submit" />-->
        <a href="Javascript:Do_it();">
        <img src="/go.png"></a>
    </form>
    </div>
'''

       if currenthostype == "Master_backend" or currenthostype == "Standalone":
            mbeoptions=createdropdown(currenthostype)

       else:
            mbeoptions=''
       returnurl="/xymon/notes/"
       returnurl+=str(row[0])
       returnurl+=(".html")
       file.write('</br> </br>  ')
       file.write(buttonform_top)
       file.write(mbeoptions)
       file.write(buttonform_bottom)
       file.write(str(row[0]))
       file.write(oldurlform)
       file.write(returnurl)
       file.write(closetag)

       string=('</html>')
       file.write(string)


def create_hobbit_analysis(frontonly,
                           masterbackend,
                           masterbacked_w_fe,
                           slave_w_fe,
                           slave,
                           stand_alone):

    hobbitfile="/home/xymon/server/etc/analysis.cfg"
    hobbitf=open(hobbitfile,'r')
    hobbitconfig=hobbitf.readlines()
    hobbitf.close()
    try:
        hobbitf=open(hobbitfile,'w')
        print "FE",frontonly
        print "MBE",masterbackend
        print "MBEwFW",masterbacked_w_fe
        print "SLAVEwFW",slave_w_fe
        print "SLAVE",slave
        print "STD",stand_alone

        for line in hobbitconfig:
            if line.startswith("HOST"):
                cline=line.split("=")
                if cline[1].startswith("_FRONTEND_"):
                    pline="HOST="
                    pline+=frontonly.strip()
                    hobbitf.write(pline + "\n")
                elif cline[1].startswith("_MASTERBACKEND_"):
                    pline="HOST="
                    pline+=masterbackend.strip()
                    #print pline
                    hobbitf.write(pline+ "\n")
                elif cline[1].startswith("_MASTERFRONTEND_"):
                    pline="HOST="
                    pline+=masterbacked_w_fe.strip()
                    #print pline
                    hobbitf.write(pline+ "\n")
                elif cline[1].startswith("_SLAVEBACKEND_"):
                    pline="HOST="
                    pline+=slave.strip()
                    #print pline
                    hobbitf.write(pline+ "\n")
                elif cline[1].startswith("_SLAVEFE_"):
                    pline="HOST="
                    pline+=slave_w_fe.strip()
                    #print pline
                    hobbitf.write(pline+ "\n")
                else:
                    #print line
                    hobbitf.write(line)
            else:
                #print line
                hobbitf.write(line)
        hobbitf.close()
    except:
        print "problem writing analysis.cfg"

def main(argv):
    frontonly,masterbackend,masterbacked_w_fe,slave_w_fe,slave,stand_alone = create_dot_file()
    create_notes()
    create_hobbit_analysis(frontonly,
                           masterbackend,
                           masterbacked_w_fe,
                           slave_w_fe,
                           slave,
                           stand_alone)


if __name__ == "__main__":
    main(sys.argv[1:])