summaryrefslogtreecommitdiffstats
path: root/abs/core/LinHES-system/myth_mtc.py
blob: 78473138d1c2e919405b4d323a17f142f008b684 (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
#!/usr/bin/python2
import sys, subprocess
import optparse
import re
import socket
import os
import datetime,time
import shlex

try:
    from MythTV import MythBE
    mythtv = MythBE()
except:
    mythtv = None

#print mythtv.db.getSetting( 'Theme', socket.gethostname())

def get_timestamp():
    now = datetime.datetime.now()
#date = "%s-%s-%s" %(now.year, now.month, now.day)
    date = (now.strftime('%Y-%m-%d %H:%M')) 
    return date


def optimize():
   
    try:
        cursor = mythtv.db.cursor()
        cursor.execute("SHOW tables")
        result = cursor.fetchall()
    except:
        print "    Problem getting tables from database"
	return
    ops=["REPAIR","OPTIMIZE","ANALYZE"]
    for row in result:
        ctable=row[0]
        for op in ops:
            print "    %s %s" %(op,ctable)
            cmd= "%s  table %s" %(op,ctable)
            cursor.execute(cmd)


def upcoming_check():
    print "    Checking for upcoming shows"
    try:
        upcoming = mythtv.getUpcomingRecordings()
    except:
        return True
    try:
        show=str(upcoming[0])
        show=show.strip()
        showtime=show.partition("(")[2].strip(")")
        now=time.time()
        rec_time=time.strptime( showtime ,"%Y-%m-%d %H:%M:%S" )
        r=time.mktime(rec_time)
        time_diff= ( r - now ) / 60
    except:
        time_diff=100
        show="No show"
    if ( time_diff  >  30) :
        return True
    else:
        print "      %s is upcoming in %s" %(show,time_diff)
        return False


def schemalock_check():
    print "    Checking if schema is locked"
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from schemalock")
        results=c.fetchone()
        schemalock=results[0]
    except:
        return True

    if schemalock == 0:
        return True
    else:
        print "      schema is locked"
        return False

def job_check():
    print "    Checking jobqueue"
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from jobqueue where status = 4")
        results=c.fetchone()
    except:
        return True
    jobs= results[0]
    if jobs == 0 :
        return True
    else:
        print "      jobs are running"
        return False


def in_use():
    print "    Checking if programs are in use"
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from inuseprograms")
        results=c.fetchone()
    except:
        return True
    prginuse=results[0]
    if prginuse == 0 :
        return True
    else:
        print "      Programs in use"
        return False

def mfd_check():
    print "    Checking is mythfilldatabase is running"
    ps = subprocess.Popen("ps ax -o pid= -o args= ", shell=True, stdout=subprocess.PIPE)
    ps_pid = ps.pid
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    proc_name="mythfilldatabase"
    for line in output.split("\n"):
        res = re.findall("(\d+) (.*)", line)
        if res:
            pid = int(res[0][0])
            if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:
                print "      mythfilldatabase is running"
                return False

    return True

def bail_if_another_is_running():
    cmd = shlex.split("pgrep -u {} -f {}".format(os.getuid(), __file__))
    pids = subprocess.check_output(cmd).strip().split('\n')
    if len(pids) > 1:
        pids.remove("{}".format(os.getpid()))
        print "Exiting! Found {} is already running (pids): {}".format(
            __file__, " ".join(pids))
        raise SystemExit(1)


def idle_check():
    print "\n%s Checking Idle" %(get_timestamp())
    if  (   upcoming_check() and schemalock_check() and job_check()  and in_use() and  mfd_check()  ):
        idle=True
        print "\n%s Myth is idle" %(get_timestamp())
    else:
        idle=False
        print "\n%s Myth is NOT idle" %(get_timestamp())
    return idle

def run_stuff():
    if idle_check():
        print "\n#######################################"
        print "\n%s Running Optimize" %(get_timestamp())
        optimize()

        print "\n#######################################"
        print "\n%s Running Backup" %(get_timestamp())
        os.system('/usr/LH/bin/lh_system_backup_job')

        print "\n#######################################"
        print "\n%s Running System Update" %(get_timestamp())
        os.system('/usr/LH/bin/lh_system_host_update')

        print "\n#######################################"
        continue_loop=False
    else:
        continue_loop=True
    return continue_loop

#---------------------------------
bail_if_another_is_running()
starttime=time.time()
ctin=True
while ctin:
    ctin=run_stuff()
    if  ctin:
        print "\n%s Waiting 10 minutes before trying again." %(get_timestamp())
        time.sleep(600)
        
    current_time=time.time()
    if (current_time - starttime) > 3000 :
        ctin = False
        print "\n%s Time Exceeded 50 minutes. Quitting.)" %(get_timestamp())
        exit(1)