admin.py 5.97 KB
Newer Older
Marc Duez's avatar
Marc Duez committed
1
# coding: utf8
Marc Duez's avatar
Marc Duez committed
2
import gluon.contrib.simplejson, re
3
import os.path, subprocess
4
import vidjil_utils
5
from collections import defaultdict
6

7
MAX_LOG_LINES = 500
8

Marc Duez's avatar
Marc Duez committed
9 10 11 12 13 14 15 16
if request.env.http_origin:
    response.headers['Access-Control-Allow-Origin'] = request.env.http_origin  
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Max-Age'] = 86400
    

## return admin_panel
def index():
17
    if auth.has_membership("admin"):
18 19 20 21 22 23
        p = subprocess.Popen(["uptime"], stdout=subprocess.PIPE)
        uptime, err = p.communicate()
        
        p = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE)
        disk_use, err = p.communicate()
        
24 25
        d = monitor()
        return dict(d,
26 27 28
                    uptime=uptime,
                    disk_use=disk_use
                    )
29 30 31


def monitor():
Marc Duez's avatar
Marc Duez committed
32 33 34 35 36
    """
    >>> monitor().has_key('worker')
    True
    
    """
37
    # External monitor
38 39 40 41 42 43 44

    last_results = ''
    for res in db(db.scheduler_task.id == db.results_file.scheduler_task_id).select(orderby=~db.results_file.id,
                                                                                    limitby=(0,10)):
        last_results += res.scheduler_task.status[0]


45
    return dict (worker = len(db().select(db.scheduler_worker.ALL)),
46 47
                 queued = len(db(db.scheduler_task.status=='QUEUED').select()),
                 assigned = len(db(db.scheduler_task.status=='ASSIGNED').select()),
48 49
                 running = len(db(db.scheduler_task.status=='RUNNING').select()),
                 last_results = last_results)
Marc Duez's avatar
Marc Duez committed
50
    
Marc Duez's avatar
Marc Duez committed
51 52 53 54
    
def log():
    if auth.has_membership("admin"):
        
55
        
Marc Duez's avatar
Marc Duez committed
56
        lines = []
57
        file = open(defs.DIR_LOG+request.vars["file"])
58 59
        log_format = request.vars['format'] if 'format' in request.vars else ''

60 61 62
        if log_format == 'raw':
            return {'raw': ''.join(file.readlines()), 'format': log_format}

63 64
        if "filter" not in request.vars :
            request.vars["filter"] = ""
Marc Duez's avatar
Marc Duez committed
65
            
66 67
        for row in reversed(file.readlines()) :

68 69 70 71 72 73 74
            if not vidjil_utils.filter(row, request.vars["filter"]) :
                continue

            if not log_format: # == 'vidjil'
                line = { 'mes': row, 'date': '', 'date2': '', 'user': '', 'type':'', 'file':''}

            else:
75 76 77 78
                # Parses lines such as
                # [11889] 2015-02-01 12:01:28,367     INFO - default.py:312 1.23.45.67/user/Toto <Toto> xxxxx log message
                # [11889] 2015-02-01 12:01:28,367     INFO - default.py:312 1.23.45.67 log message
                # [11889] 2015-02-01 12:01:28,367     INFO - default.py:312 log message
Marc Duez's avatar
Marc Duez committed
79 80 81 82 83 84 85 86 87 88
                line = {}

                tmp = re.split('\t+| +', row) 

                line["date"] = tmp[1]
                line["date2"] = tmp[2].split(',')[0]
                line["type"] = tmp[3]
                line["file"] = tmp[5]

                if tmp[6] != "Creating":
89 90 91 92 93 94 95
                    if '<' in tmp[8]:
                        line["user"] = tmp[8] + ' ' + tmp[7]
                        j = 9
                    else:
                        line["user"] = tmp[7]
                        j = 8
                    line["mes"] = " ".join(tmp[j:])
Marc Duez's avatar
Marc Duez committed
96 97
                else:
                    line["user"] = ""
98
                    line["mes"] = " ".join(tmp[6:])
Marc Duez's avatar
Marc Duez committed
99

100 101
                line["mes"] = vidjil_utils.log_links(line["mes"])

102 103
            ### Stores log line
            lines.append(line)
Marc Duez's avatar
Marc Duez committed
104

105
            if len(lines) >= MAX_LOG_LINES :
106
                break
Marc Duez's avatar
Marc Duez committed
107
            
108
        return {'lines': lines, 'format': log_format}
Marc Duez's avatar
Marc Duez committed
109 110 111 112 113 114 115 116 117 118 119

## to use after change in the upload folder
def repair_missing_files():
    if auth.has_membership("admin"):
        
        flist = ""
        for row in db(db.sequence_file.id>0 and db.sequence_file.data_file != None).select() : 
            seq_file = defs.DIR_SEQUENCES+row.data_file
            
            if not os.path.exists(seq_file) :
                db.sequence_file[row.id] = dict(data_file = None)
120
                flist += " : " + str(row.filename)
Marc Duez's avatar
Marc Duez committed
121
            else :
122
                size = os.path.getsize(seq_file)
Marc Duez's avatar
Marc Duez committed
123 124
                db.sequence_file[row.id] = dict(size_file = size)
                
Mathieu Giraud's avatar
Mathieu Giraud committed
125
        res = {"success" : "true", "message" : "references to missing files have been removed from the database"+flist}
Marc Duez's avatar
Marc Duez committed
126
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
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

    
def make_backup():
    if auth.has_membership("admin"):
        
        db.export_to_csv_file(open('backup.csv', 'wb'))
                
        res = {"success" : "true", "message" : ""}
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
    
    
def repair():
    if auth.has_membership("admin"):
        
        flist = "fix creator "
        for row in db(db.patient.creator == None).select() : 
            flist += " : " + str(row.id)
            db.patient[row.id] = dict(creator = auth.user_id)
            
        flist += "fix event "
        for row in db(db.auth_event.user_id == None).select() : 
            flist += " : " + str(row.id)
            db.auth_event[row.id] = dict(user_id = auth.user_id)
            
        flist += "fix permission "
        db(db.auth_permission.group_id == None).delete();
        
        flist += "fix sequence_file provider "
        for row in db(db.sequence_file.provider == None).select() :
            flist += " : " + str(row.id)
            db.sequence_file[row.id] = dict(provider = auth.user_id)
      
        flist += "fix sequence_file patient "
        db(db.sequence_file.patient_id == None).delete();
        
        flist += "fix results_file "
        db(db.results_file.sequence_file_id == None).delete()
    
        flist += "fix fused file "
        for row in db(db.fused_file.fuse_date == None).select() :
            flist += " : " + str(row.id)
            db.fused_file[row.id] = dict(fuse_date = "1970-01-01 00:00:00")
        
        res = {"success" : "true", "message" : "plop!! " + flist}
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))