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

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 = (now.strftime('%Y-%m-%d %H:%M'))
    return date

def getFreePercentForDir(dir):
    stats = os.statvfs(dir)
    total = (stats.f_blocks)
    avail = (stats.f_bavail)
    return (total - avail) / float(total)

def check_home():
    #get the mythtv home dir
    sys.path.append('/usr/MythVantage/bin/')
    config_file = "mv_config"
    data_config = __import__(config_file,  globals(),  locals(),  [])

    freePcent = getFreePercentForDir(data_config.MYTHHOME)
    print "  Home directory percent used: " + str(freePcent * 100) + "%"
    if float(freePcent) > .9:
        print "    Home directory is greater than 90% used. Clearing caches..."
        cmd = "/usr/bin/rm -rf " + data_config.MYTHHOME + "/.mythtv/{*cache,Cache-*,tmp/*,MythMusic/AlbumArt/*}"
        subprocess.call(["sh", "-c", cmd])
        print "    Restarting mythfrontend..."
        subprocess.call(["killall", "mythfrontend"])
        cmd = "/usr/bin/rm -rf " + data_config.MYTHHOME + "/.cache/*"
        subprocess.call(["sh", "-c", cmd])
        cmd = "/usr/bin/rm -rf " + data_config.MYTHHOME + "/.plexht/userdata/Thumbnails/*"
        subprocess.call(["sh", "-c", cmd])
        cmd = "/usr/bin/rm -rf " + data_config.MYTHHOME + "/.plexht/userdata/ThemeMusicCache/*"
        subprocess.call(["sh", "-c", cmd])
        freePcent = getFreePercentForDir(data_config.MYTHHOME)
        print "  Home directory percent used: " + str(freePcent * 100) + "%"
    else:
        print "    Home directory is less than 90% used. Not clearing caches."
    return 0

def optimize():
    try:
        cursor = mythtv.db.cursor()
        cursor.execute("SHOW tables")
        result = cursor.fetchall()
    except:
        print "\n%s Problem getting tables from the database" %(get_timestamp())
        return 1
    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)
    return 0

def cleanup_inuseprograms():
    fourHoursAgo=datetime.datetime.today() - datetime.timedelta(hours=4)
    cmd="DELETE FROM inuseprograms WHERE lastupdatetime < '%s';" %fourHoursAgo
    try:
        cursor = mythtv.db.cursor()
        cursor.execute(cmd)
    except:
        print "\n%s Problem cleaning inuseprograms in database" %(get_timestamp())


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 run_stuff():
    print "\n%s" %get_timestamp()

    if (len(sys.argv) == 1) or ("--noidlecheck" in sys.argv) and (len(sys.argv) == 2):
        runall = True
    else:
        runall = False

    if ("--noidlecheck" in sys.argv):
        print "No system idle check will be done."
        idle = 0
    else:
        idle = subprocess.call(["/usr/bin/python2", "/usr/LH/bin/idle.py"])

    if not idle:
        if ("--check_home" in sys.argv) or runall:
            print "\n#######################################"
            print "\n%s Checking size of MythTV home" %(get_timestamp())
            if not check_home():
                print "\nFinished checking size of MythTV home"
            else:
                return True

        if ("--optimize" in sys.argv) or runall:
            print "\n#######################################"
            print "\n%s Running Optimize" %(get_timestamp())
            if not optimize():
                print "\nFinished Optimize"
            else:
                return True

        if ("--backup" in sys.argv) or runall:
            print "\n#######################################"
            print "\n%s Running Backup" %(get_timestamp())
            if not os.system('/usr/LH/bin/lh_system_backup_job'):
                print "\nFinished Backup"

        if ("--update" in sys.argv) or runall:
            print "\n#######################################"
            print "\n%s Running System Update" %(get_timestamp())
            if not os.system('/usr/LH/bin/lh_system_host_update'):
                print "\nFinished 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:
    cleanup_inuseprograms()
    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)