summaryrefslogtreecommitdiffstats
path: root/abs/mv-core/local-website/contents/process.py
blob: d74fb4740d23e998dd91e8d57f15309329647158 (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
#!/usr/bin/python
import sys
import cgi
import os
import socket
import time
try:
    import cgitb
    cgitb.enable()
except ImportError:
    sys.stderr = sys.stdout
def cgiprint(inline=''):
    sys.stdout.write(inline)
    sys.stdout.write('\r\n')
    sys.stdout.flush()
contentheader = 'Content-Type: text/html'

thepage = '''<html><head>
<title>%s</title>
</head><body>
%s
</body></html>
'''
h1 = '<h1>%s</h1>'

def getform(theform, valuelist, notpresent='', nolist=False):
    """
    This function, given a CGI form as a
    FieldStorage instance, extracts the
    data from it, based on valuelist
    passed in. Any non-present values are
    set to '' - although this can be
    changed. (e.g. to return None so you
    can test for missing keywords - where
    '' is a valid answer but to have the
    field missing isn't.) It also takes a
    keyword argument 'nolist'. If this is
    True list values only return their
    first value.
    """
    data = {}
    for field in valuelist:


        if not theform.has_key(field):
        #  if the field is not present (or was empty)
            data[field] = notpresent

        else:
        # the field is present


	    print type(theform[field])

            if  type(theform[field]) != type([]):
            # is it a list or a single item
	    	print type(theform[field])
                data[field] = theform[field].value

            else:

                if not nolist:
                # do we want a list ?
                    data[field] = theform.getlist(field)

                else:
                    data[field] = theform.getfirst(field)

                    # just fetch the first item
    return data

def getall(theform, nolist=False):
    """
    Passed a form (cgi.FieldStorage
    instance) return *all* the values.
    This doesn't take into account
    multipart form data (file uploads).
    It also takes a keyword argument
    'nolist'. If this is True list values
    only return their first value.
    """
    data = {}
    for field in theform.keys():
    # we can't just iterate over it, but must use the keys() method
        if type(theform[field]) ==  type([]):
            if not nolist:
                data[field] = theform.getlist(field)
            else:
                data[field] = theform.getfirst(field)
        else:
            data[field] = theform[field].value
    return data

def isblank(indict):
    """
    Passed an indict of values it checks
    if any of the values are set. Returns
    True if the indict is empty, else
    returns False. I use it on the a form
    processed with getform to tell if my
    CGI has been activated without any
    form values.
    """
    for key in indict.keys():
        if indict[key]:
            return False
    return True

def go_backup(myhost):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
        command= "sudo /usr/bin/backup_job  "
        command2="sleep 2; /data/srv/hobbit/server/ext/hbnotes.py"
        results=os.popen(command,'r')
        os.popen(command2,'r')
    else:
        sshcmd="ssh -o StrictHostKeyChecking=no -o ConnectTimeout=1 -i /data/srv/.nobody_ssh/id_dsa mythtv@"
        sshcmd+=myhost.strip()
        cmd=' "sudo /etc/cron.daily/backup_cron ; sudo su nobody -c /data/srv/hobbit/server/ext/hbnotes.py"'
        command=sshcmd + cmd + " 2>&1 "
        results=os.popen(command,'r')
    #print command


    return  results


def go_restore(restorefile,myhost):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
        localcommand="sudo /usr/bin/restore_job.sh "
        command= localcommand + restorefile
    else:
        sshcmd="ssh -o StrictHostKeyChecking=no -o ConnectTimeout=1 -i /data/srv/.nobody_ssh/id_dsa mythtv@"
        sshcmd+=myhost.strip()
        cmd=' "sudo /usr/bin/restore_job.sh   "   '
        command=sshcmd + cmd + restorefile + " 2>&1 "

    results=os.popen(command,'r')
    return  results

def go_optimize(myhost):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
       command="/usr/bin/optimize_mythdb.py"
       results=os.popen(command,'r')
    else:
        results='oops'
    return  results

def go_update(myhost,update_type):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
         cmd="sudo /usr/bin/update_system "
         command=cmd + update_type

    else:
        #sshcmd="ssh -o StrictHostKeyChecking=no -i /data/srv/.nobody_ssh/id_dsa mythtv@"
        #sshcmd+=myhost.strip()
        #cmd=" sudo /usr/bin/update_system "
        #cmd+=update_type
        #command=sshcmd + cmd + " 2>&1 "
        #using func now
        cmd=" call pacman update_system "
        cmd+=update_type
        command="sudo /usr/bin/func " + myhost.strip() + " " + cmd
        print command

        #print command

    results=os.popen(command,'r')
    return  results

def go_updateall(allupdate_type):

        cmd=" sudo /usr/bin/update_system_all "
        cmd+=allupdate_type
        command= cmd + " 2>&1 "
        results=os.popen(command,'r')
    	return  results


def go_shutdown(myhost):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
        message="Shutdown from MBE:::ALT"
        os.system("/usr/bin/osdClient.pl  " + myhost.strip() + "  5000 " +  "\"" +  message + "\""   )
        time.sleep(3)
        command="sudo  /sbin/poweroff "
    else:
        command="sudo /usr/bin/func " + myhost.strip() +  " call power poweroff "
    message="Shutdown from MBE:::ALT"
    os.system("/usr/bin/osdClient.pl  " + myhost.strip() + "  5000 " +  "\"" +  message + "\""   )
    time.sleep(3)

    results=os.popen(command,'r')
    return  results

def go_shutdownall():
    import MySQLdb
    #import mysql
    #find all hosts(minus myself)
    #loop through results shutdown as we go.
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
   # execute SQL statement
    myhostname = socket.gethostname()
    results=["Sent shutdown command to: \n "]
    cursor.execute("SELECT distinct(hostname) from settings where not  hostname = %s ; ",(myhostname))
    result = cursor.fetchall()

    for row in result:
         go_shutdown(row[0])
         results.append(row[0])

    #shutdown myself.
    #go_shutdown(myhostname)
    #results.append(myhostname)
    return  results

def go_reboot(myhost):
    myhostname = socket.gethostname()
    if myhostname.strip() == myhost.strip():
	message="Reboot from MBE:::ALT"
	os.system("/usr/bin/osdClient.pl  " + myhost.strip() + "  5000 " +  "\"" +  message + "\""   )
	time.sleep(3)
        command="sudo  /sbin/reboot "
    else:
        #sshcmd="ssh -o StrictHostKeyChecking=no -o ConnectTimeout=1 -i /data/srv/.nobody_ssh/id_dsa mythtv@"
        #sshcmd+=myhost.strip()
        #cmd=" sudo poweroff"
        #command=sshcmd + cmd + " 2>&1 "
        #using func
        command="sudo /usr/bin/func " + myhost.strip() +  " call power reboot "
	message="Reboot from MBE:::ALT"
	os.system("/usr/bin/osdClient.pl  " + myhost.strip() + "  5000 " +  "\"" +  message + "\""   )
	time.sleep(3)

    results=os.popen(command,'r')
    return  results

def go_wake(myhost):
    command="/usr/bin/wakeonlan.sh " + myhost.strip()
    results=os.popen(command,'r')
    return  results


mainpage = '''
 <html><head>
 <style type="text/css">@import "/frame.css";</style>
 <!--<meta http-equiv="refresh" content="6">-->
 <title>Receiving a Form</title>
 </head><body>%s</body></html>'''

error = '''
    <h1>Error</h1>
    <h2>No Form Submission Was Received</h2>'''

result = '''
    <h1>%s of %s</h1>
'''
possible_parameters = ['param1', 'param2', 'param3', 'param4','hiddenparam','param5']

if __name__ == '__main__':
    cgiprint(contentheader)   # content header
    cgiprint()                # finish headers with blank line

    theform = cgi.FieldStorage()
    #print theform
    formdict = getform(theform, possible_parameters)
    #print possible_parameters

    if isblank(formdict):
        body = error
    else:
        name = formdict['param1']
        radio = formdict['param2']  # should be 'this' or 'that'
        if radio != 'Restore' :
            name = ""
        update_type = formdict['param3']
        oldurl = formdict['param4']
        hidden = formdict['hiddenparam']
	all_update_type=formdict['param5']
        body = result % (radio, hidden)




    print mainpage % body
    selection=radio
    myhost=hidden

    if selection == "Restore":
        mylogfile=go_restore(name,myhost)
    elif selection == "Backup":
        mylogfile=go_backup(myhost)
    elif selection == "Update":
        mylogfile=go_update(myhost,update_type)
    elif selection == "Shutdown":
        mylogfile=go_shutdown(myhost)
    elif selection == "Reboot":
        mylogfile=go_reboot(myhost)
    elif selection == "Optimize":
        mylogfile=go_optimize(myhost)
    elif selection == "WOL":
        mylogfile=go_wake(myhost)
    elif selection == "UpdateAll":
        mylogfile=go_updateall(all_update_type)
    elif selection == "ShutdownAll":
        mylogfile=go_shutdownall()

    box='''
     <div style="border: 1px solid #aaa; width:600px; height:500px; overflow:auto; color:#FFF;text-align:left;">
         <code id="box" style="display: block; height: 500px; width: 600px; overflow: auto;">
    '''

    endbox='''
         </code>
     </div>
    '''
    javascript='''
    <script type="text/javascript">
        var objDiv = document.getElementById("box");
        objDiv.scrollTop = objDiv.scrollHeight;
    </script>
     '''

    print box
    for line in mylogfile:
        print line + '</br> \r\n'

    print endbox
    print '<a href=',  oldurl,     '  > Back </a> '
    #print oldurl
    print javascript