job_manager.py 35.6 KB
Newer Older
1
import os
2
import shutil
3
import subprocess
4
from datetime import datetime
5
import time
6
import threading
7
import re
8
from dgenies.config_reader import AppConfigReader
9
from dgenies.database import Job, Session
10
from peewee import DoesNotExist
11
12
from .fasta import Fasta
from .functions import Functions
13
import requests
14
from requests.exceptions import ConnectionError
15
import wget
16
from jinja2 import Template
17
import traceback
18
from pathlib import Path
19
from urllib import request, parse
20
from dgenies.bin.split_fa import Splitter
Floreal Cabanettes's avatar
Floreal Cabanettes committed
21
from dgenies.bin.index import index_file
22
from dgenies.bin.filter_contigs import Filter
23
24
from dgenies.bin.merge_splitted_chrms import Merger
from dgenies.bin.sort_paf import Sorter
25
from dgenies.lib.paf import Paf
26
27
import gzip
import io
28
import binascii
29
import glob
30
31
32
33


class JobManager:

Floreal Cabanettes's avatar
Floreal Cabanettes committed
34
    def __init__(self, id_job: str, email: str=None, query: Fasta=None, target: Fasta=None, mailer=None):
35
36
        self.id_job = id_job
        self.email = email
37
38
        self.query = query
        self.target = target
39
        self.error = ""
40
        self.id_process = "-1"
41
        # Get configs:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
42
        self.config = AppConfigReader()
43
        # Outputs:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
44
        self.output_dir = os.path.join(self.config.app_data, id_job)
45
        self.preptime_file = os.path.join(self.output_dir, "prep_times")
46
        self.query_index_split = os.path.join(self.output_dir, "query_split.idx")
47
        self.paf = os.path.join(self.output_dir, "map.paf")
48
        self.paf_raw = os.path.join(self.output_dir, "map_raw.paf")
49
50
        self.idx_q = os.path.join(self.output_dir, "query.idx")
        self.idx_t = os.path.join(self.output_dir, "target.idx")
51
        self.logs = os.path.join(self.output_dir, "logs.txt")
52
        self.mailer = mailer
53

54
55
56
57
58
    @staticmethod
    def is_gz_file(filepath):
        with open(filepath, 'rb') as test_f:
            return binascii.hexlify(test_f.read(2)) == b'1f8b'

59
60
61
    def get_file_size(self, filepath: str):
        file_size = os.path.getsize(filepath)
        if filepath.endswith(".gz") and file_size <= self.config.max_upload_size:
62
63
            with gzip.open(filepath, 'rb') as file_obj:
                file_size = file_obj.seek(0, io.SEEK_END)
64
65
        return file_size

66
67
68
69
70
71
    def get_query_split(self):
        query_split = os.path.join(self.output_dir, "split_" + os.path.basename(self.query.get_path()))
        if query_split.endswith(".gz"):
            return query_split[:-3]
        return query_split

72
    def set_inputs_from_res_dir(self):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
73
        res_dir = os.path.join(self.config.app_data, self.id_job)
74
75
76
77
78
        query_file = os.path.join(res_dir, ".query")
        if os.path.exists(query_file):
            with open(query_file) as q_f:
                file_path = q_f.readline()
                self.query = Fasta(
Floreal Cabanettes's avatar
Floreal Cabanettes committed
79
                    name=os.path.splitext(os.path.basename(file_path.replace(".gz", "")).split("_", 1)[1])[0],
80
                    path=file_path,
81
82
83
84
85
86
87
                    type_f="local"
                )
        target_file = os.path.join(res_dir, ".target")
        if os.path.exists(target_file):
            with open(target_file) as t_f:
                file_path = t_f.readline()
                self.target = Fasta(
Floreal Cabanettes's avatar
Floreal Cabanettes committed
88
                    name=os.path.splitext(os.path.basename(file_path.replace(".gz", "")).split("_", 1)[1])[0],
89
90
91
92
                    path=file_path,
                    type_f="local"
                )

93
    def check_job_success(self):
94
95
        if os.path.exists(self.paf_raw):
            if os.path.getsize(self.paf_raw) > 0:
96
                return "success"
97
98
            else:
                return "no-match"
Floreal Cabanettes's avatar
Floreal Cabanettes committed
99
        return "fail"
100

101
102
103
104
105
106
    def is_query_filtered(self):
        return os.path.exists(os.path.join(self.output_dir, ".filter-query"))

    def is_target_filtered(self):
        return os.path.exists(os.path.join(self.output_dir, ".filter-target"))

107
    def get_mail_content(self, status):
108
        message = "D-Genies\n\n"
109
        if status == "success":
Floreal Cabanettes's avatar
Floreal Cabanettes committed
110
            message += "Your job %s was completed successfully!\n\n" % self.id_job
111
            message += str("Your job {0} is finished. You can see  the results by clicking on the link below:\n"
Floreal Cabanettes's avatar
Floreal Cabanettes committed
112
                           "{1}/result/{0}\n\n").format(self.id_job, self.config.web_url)
113
114
        else:
            message += "Your job %s has failed!\n\n" % self.id_job
115
116
            if self.error != "":
                message += self.error.replace("#ID#", self.id_job).replace("<br/>", "\n")
117
                message += "\n\n"
118
119
120
            else:
                message += "Your job %s has failed. You can try again. " \
                           "If the problem persists, please contact the support.\n\n" % self.id_job
121
        message += "Sequences compared in this analysis:\n"
122
123
124
125
        if self.query is not None:
            message += "Target: %s\nQuery: %s\n\n" % (self.target.get_name(), self.query.get_name())
        else:
            message += "Target: %s\n\n" % self.target.get_name()
126
127
128
129
130
131
132
133
134
        if status == "success":
            if self.is_target_filtered():
                message += str("Note: target fasta has been filtered because it contains too small contigs."
                               "To see which contigs has been removed from the analysis, click on the link below:\n"
                               "{1}/filter-out/{0}/target\n\n").format(self.id_job, self.config.web_url)
            if self.is_query_filtered():
                message += str("Note: query fasta has been filtered because it contains too small contigs."
                               "To see which contigs has been removed from the analysis, click on the link below:\n"
                               "{1}/filter-out/{0}/query\n\n").format(self.id_job, self.config.web_url)
135
136
        message += "See you soon on D-Genies,\n"
        message += "The team"
137
        return message
138

139
    def get_mail_content_html(self, status):
140
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "mail_templates", "job_notification.html"))\
Floreal Cabanettes's avatar
Floreal Cabanettes committed
141
142
                as t_file:
            template = Template(t_file.read())
Floreal Cabanettes's avatar
Floreal Cabanettes committed
143
            return template.render(job_name=self.id_job, status=status, url_base=self.config.web_url,
144
145
                                   query_name=self.query.get_name() if self.query is not None else "",
                                   target_name=self.target.get_name(),
146
147
                                   error=self.error,
                                   target_filtered=self.is_target_filtered(), query_filtered=self.is_query_filtered())
148

149
    def get_mail_subject(self, status):
150
        if status == "success" or status == "no-match":
Floreal Cabanettes's avatar
Floreal Cabanettes committed
151
            return "DGenies - Job completed: %s" % self.id_job
152
        else:
153
            return "DGenies - Job failed: %s" % self.id_job
154

155
156
    def send_mail(self):
        # Retrieve infos:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
157
158
159
160
161
162
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            if self.email is None:
                self.email = job.email
            status = job.status
            self.error = job.error
163

Floreal Cabanettes's avatar
Floreal Cabanettes committed
164
            # Send:
165
166
167
168
            self.mailer.send_mail(recipients=[self.email],
                                  subject=self.get_mail_subject(status),
                                  message=self.get_mail_content(status),
                                  message_html=self.get_mail_content_html(status))
169

170
171
172
    def search_error(self):
        logs = os.path.join(self.output_dir, "logs.txt")
        if os.path.exists(logs):
173
174
175
176
177
            lines = subprocess.check_output(['tail', '-2', logs]).decode("utf-8").split("\n")
            if re.match(r"\[morecore] \d+ bytes requested but not available.", lines[1]) or \
                    re.match(r"\[morecore] \d+ bytes requested but not available.", lines[1]) or \
                    re.match(r"\[morecore] insufficient memory", lines[0]) or \
                    re.match(r"\[morecore] insufficient memory", lines[1]):
178
179
180
181
                return "Your job #ID# has failed because of memory limit exceeded. May be your sequences are too big?" \
                       "<br/>You can contact the support for more information."
        return "Your job #ID# has failed. You can try again.<br/>If the problem persists, please contact the support."

182
    def __launch_local(self):
183
184
185
186
187
188
189
190
        if self.query is not None:
            cmd = ["/usr/bin/time", "-f", "%e %M", self.config.minimap2_exec, "-t", self.config.nb_threads,
                   self.target.get_path(), self.get_query_split()]
        else:
            cmd = ["/usr/bin/time", "-f", "%e %M", self.config.minimap2_exec, "-t", self.config.nb_threads, "-X",
                   self.target.get_path(), self.target.get_path()]
        with open(self.logs, "w") as logs, open(self.paf_raw, "w") as paf_raw:
            p = subprocess.Popen(cmd, stdout=paf_raw, stderr=logs)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            job.id_process = p.pid
            job.status = "started"
            job.save()
            p.wait()
            if p.returncode == 0:
                status = self.check_job_success()
                job.status = status
                job.save()
                return status == "success"
            job.status = "fail"
            self.error = self.search_error()
            job.error = self.error
205
            job.save()
206
        return False
207

208
209
210
211
212
    def check_job_status_slurm(self):
        """
        Check status of a SLURM job run
        :return: True if the job has successfully ended
        """
Floreal Cabanettes's avatar
Floreal Cabanettes committed
213
        status = subprocess.check_output("sacct -p -n --format=state,maxvmsize,elapsed -j %s.batch" % self.id_process,
214
                                         shell=True).decode("utf-8").strip("\n")
215

216
        status = status.split("|")
217

218
219
220
        success = status[0] == "COMPLETED"
        if success:
            mem_peak = int(status[1][:-1])  # Remove the K letter
Floreal Cabanettes's avatar
Floreal Cabanettes committed
221
            elapsed_full = list(map(int, status[2].split(":")))
222
223
224
            elapsed = elapsed_full[0] * 3600 + elapsed_full[1] * 60 + elapsed_full[2]
            with open(self.logs, "a") as logs:
                logs.write("%s %d" % (elapsed, mem_peak))
225
226
227
228
229
230
231
232

        return success

    def check_job_status_sge(self):
        """
        Check status of a SGE job run
        :return: True if the job jas successfully ended
        """
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
        status = "-1"
        start = None
        end = None
        mem_peak = None
        acct = subprocess.check_output("qacct -d 1 -j %s" % self.id_process,
                                         shell=True).decode("utf-8")
        lines = acct.split("\n")
        for line in lines:
            if line.startswith("failed"):
                status = re.split(r"\s+", line, 1)[1]
            elif line.startswith("start_time"):
                start = datetime.strptime(re.split(r"\s+", line, 1)[1], "%a %b %d %H:%M:%S %Y")
            elif line.startswith("end_time"):
                end = datetime.strptime(re.split(r"\s+", line, 1)[1], "%a %b %d %H:%M:%S %Y")
            elif line.startswith("maxvmem"):
                mem_peak = re.split(r"\s+", line, 1)[1]
                if mem_peak.endswith("G"):
                    mem_peak = int(mem_peak[-1]) * 1024 * 1024
                elif mem_peak.endswith("M"):
                    mem_peak = int(mem_peak[-1]) * 1024

        if status == "0":
            if start is not None and end is not None and mem_peak is not None:
                elapsed = end - start
                elapsed = elapsed.seconds
                with open(self.logs, "a") as logs:
                    logs.write("%s %d" % (elapsed, mem_peak))
260
261
262
263

        return status == "0"

    def update_job_status(self, status, id_process=None):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
264
265
266
267
268
269
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            job.status = status
            if id_process is not None:
                job.id_process = id_process
            job.save()
270

271
    def launch_to_cluster(self, step, batch_system_type, command, args, log_out, log_err):
272
        import drmaa
273
        from dgenies.lib.drmaasession import DrmaaSession
274
275
276
        drmaa_session = DrmaaSession()
        s = drmaa_session.session
        jt = s.createJobTemplate()
277
278
279
280
        jt.remoteCommand = command
        jt.args = args
        if log_out == log_err:
            jt.joinFiles = True
Floreal Cabanettes's avatar
Floreal Cabanettes committed
281
            jt.outputPath = ":" + log_out
282
        else:
283
284
285
            jt.joinFiles = False
            jt.outputPath = ":" + log_out
            jt.errorPath = ":" + log_err
286
287
288
289
290

        native_specs = self.config.drmaa_native_specs
        if batch_system_type == "slurm":
            if native_specs == "###DEFAULT###":
                native_specs = "--mem-per-cpu={0} --ntasks={1} --time={2}"
291
292
293
            if step == "prepare":
                jt.nativeSpecification = native_specs.format(8000, 1, "02:00:00")
            elif step == "start":
294
                jt.nativeSpecification = native_specs.format(
Floreal Cabanettes's avatar
Floreal Cabanettes committed
295
                    self.config.cluster_memory // self.config.cluster_threads * 1000, self.config.cluster_threads,
296
                    "02:00:00")
297
        elif batch_system_type == "sge":
298
299
            if native_specs == "###DEFAULT###":
                native_specs = "-l mem={0},h_vmem={0} -pe parallel_smp {1}"
300
301
302
            if step == "prepare":
                jt.nativeSpecification = native_specs.format(8000, 1)
            elif step == "start":
303
                jt.nativeSpecification = native_specs.format(
Floreal Cabanettes's avatar
Floreal Cabanettes committed
304
                    self.config.cluster_memory // self.config.cluster_threads * 1000, self.config.cluster_threads)
305
306
307
308
        jt.workingDirectory = self.output_dir
        jobid = s.runJob(jt)
        self.id_process = jobid

309
        self.update_job_status("scheduled-cluster" if step == "start" else "prepare-scheduled", jobid)
310
311
312

        retval = s.wait(jobid, drmaa.Session.TIMEOUT_WAIT_FOREVER)
        if retval.hasExited and (self.check_job_status_slurm() if batch_system_type == "slurm" else
313
314
315
316
317
        self.check_job_status_sge()):
            if step == "start":
                status = self.check_job_success()
            else:
                status = "prepared"
318
319
320
321
322
            # job = Job.get(id_job=self.id_job)
            # job.status = status
            # db.commit()
            self.update_job_status(status)
            s.deleteJobTemplate(jt)
323
            return status == "success" or status == "prepared"
324
325
326
327
        self.update_job_status("fail")
        s.deleteJobTemplate(jt)
        return False

328
329
330
331
332
333
334
335
336
337
338
339
    def __launch_drmaa(self, batch_system_type):
        if self.query is not None:
            args = ["-t", self.config.nb_threads, self.target.get_path(), self.get_query_split()]
        else:
            args = ["-t", self.config.nb_threads, "-X", self.target.get_path(), self.target.get_path()]
        return self.launch_to_cluster(step="start",
                                      batch_system_type=batch_system_type,
                                      command=self.config.minimap2_cluster_exec,
                                      args=args,
                                      log_out=self.paf_raw,
                                      log_err=self.logs)

340
341
    def __getting_local_file(self, fasta: Fasta, type_f):
        finale_path = os.path.join(self.output_dir, type_f + "_" + os.path.basename(fasta.get_path()))
342
        shutil.move(fasta.get_path(), finale_path)
343
344
        with open(os.path.join(self.output_dir, "." + type_f), "w") as save_file:
            save_file.write(finale_path)
345
346
        return finale_path

347
    def __getting_file_from_url(self, fasta: Fasta, type_f):
348
349
350
351
352
353
354
355
356
357
358
359
360
        """
        Download file from URL
        :param fasta: Fasta object describing the input file {Fasta}
        :param type_f: type of the file (query or target) {str}
        :return: Tuple:
            [0] True if no error happened, else False
            [1] If an error happened, True if the error was saved for the job, else False (will be saved later)
            [2] Finale path of the downloaded file {str}
            [3] Name of the downloaded file {str}
        """
        try:
            dl_path = wget.download(fasta.get_path(), self.output_dir, None)
        except ConnectionError:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
361
362
363
364
365
366
            with Job.connect():
                job = Job.get(Job.id_job == self.id_job)
                job.status = "fail"
                job.error = "<p>Url <b>%s</b> is not valid!</p>" \
                            "<p>If this is unattended, please contact the support.</p>" % fasta.get_path()
                job.save()
367
            return False, True, None, None
368
369
370
371
372
373
        filename = os.path.basename(dl_path)
        name = os.path.splitext(filename.replace(".gz", ""))[0]
        finale_path = os.path.join(self.output_dir, type_f + "_" + filename)
        shutil.move(dl_path, finale_path)
        with open(os.path.join(self.output_dir, "." + type_f), "w") as save_file:
            save_file.write(finale_path)
374
        return True, False, finale_path, name
375
376

    def __check_url(self, fasta: Fasta):
377
378
        url = fasta.get_path()
        if url.startswith("http://") or url.startswith("https://"):
379
380
381
            try:
                filename = requests.head(url, allow_redirects=True).url.split("/")[-1]
            except ConnectionError:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
382
383
384
385
386
387
                with Job.connect():
                    job = Job.get(Job.id_job == self.id_job)
                    job.status = "fail"
                    job.error = "<p>Url <b>%s</b> is not valid!</p>" \
                                "<p>If this is unattended, please contact the support.</p>" % fasta.get_path()
                    job.save()
388
                return False
389
390
391
392
393
        elif url.startswith("ftp://"):
            filename = url.split("/")[-1]
        else:
            filename = None
        if filename is not None:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
394
            allowed = Functions.allowed_file(filename)
395
            if not allowed:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
396
397
398
399
400
401
402
403
404
                with Job.connect():
                    job = Job.get(Job.id_job == self.id_job)
                    job.status = "fail"
                    job.error = "<p>File <b>%s</b> downloaded from <b>%s</b> is not a Fasta file!</p>" \
                                "<p>If this is unattended, please contact the support.</p>" % (filename, url)
                    job.save()
        else:
            allowed = False
            with Job.connect():
405
                job = Job.get(Job.id_job == self.id_job)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
406
                job.status = "fail"
Floreal Cabanettes's avatar
Floreal Cabanettes committed
407
408
                job.error = "<p>Url <b>%s</b> is not a valid URL!</p>" \
                            "<p>If this is unattended, please contact the support.</p>" % (url)
409
                job.save()
410
411
        return allowed

412
413
414
415
416
    def clear(self):
        shutil.rmtree(self.output_dir)

    @staticmethod
    def get_pending_local_number():
Floreal Cabanettes's avatar
Floreal Cabanettes committed
417
418
419
        with Job.connect():
            return len(Job.select().where((Job.batch_type == "local") & (Job.status != "success") &
                                          (Job.status != "fail") & (Job.status != "no-match")))
420

421
422
423
424
425
426
427
428
    def check_file(self, input_type, should_be_local, max_upload_size_readable):
        """

        :param input_type: query or target
        :param should_be_local: True if job should be treated locally
        :param max_upload_size_readable: max upload size human readable
        :return: (True if correct, True if error set [for fail], True if should be local)
        """
Floreal Cabanettes's avatar
Floreal Cabanettes committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
        with Job.connect():
            my_input = getattr(self, input_type)
            if my_input.get_path().endswith(".gz") and not self.is_gz_file(my_input.get_path()):
                # Check file is correctly gzipped
                job = Job.get(Job.id_job == self.id_job)
                job.status = "fail"
                job.error = "Query file is not a correct gzip file"
                job.save()
                self.clear()
                return False, True, None
            # Check size:
            file_size = self.get_file_size(my_input.get_path())
            if -1 < self.config.max_upload_size < file_size:
                job = Job.get(Job.id_job == self.id_job)
                job.status = "fail"
                job.error = "Query file exceed size limit of %d Mb (uncompressed)" % max_upload_size_readable
                job.save()
                self.clear()
                return False, True, None
            if self.config.batch_system_type != "local" and file_size >= getattr(self.config, "min_%s_size" % input_type):
                should_be_local = False
450
451
452
        return True, False, should_be_local

    def download_files_with_pending(self, files_to_download, should_be_local, max_upload_size_readable):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
453
454
455
456
457
458
459
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            job.status = "getfiles-waiting"
            job.save()
            # Create a session:
            s_id = Session.new(True)
            session = Session.get(s_id=s_id)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
460

Floreal Cabanettes's avatar
Floreal Cabanettes committed
461
462
463
464
465
466
467
468
469
470
            try:
                correct = True
                error_set = False
                allowed = session.ask_for_upload(True)
                while not allowed:
                    time.sleep(15)
                    session = Session.get(s_id=s_id)
                    allowed = session.ask_for_upload(False)
                if allowed:
                    job.status = "getfiles"
Floreal Cabanettes's avatar
Floreal Cabanettes committed
471
                    job.save()
Floreal Cabanettes's avatar
Floreal Cabanettes committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
                    for file, input_type in files_to_download:
                        correct, error_set, finale_path, filename = self.__getting_file_from_url(file, input_type)
                        if not correct:
                            break
                        my_input = getattr(self, input_type)
                        my_input.set_path(finale_path)
                        my_input.set_name(filename)
                        correct, error_set, should_be_local = self.check_file(input_type, should_be_local,
                                                                              max_upload_size_readable)
                        if not correct:
                            break

                    if correct and job.batch_type != "local" and should_be_local \
                            and self.get_pending_local_number() < self.config.max_run_local:
                        job.batch_type = "local"
                        job.save()
                else:
                    correct = False
            except:  # Except all possible exceptions
Floreal Cabanettes's avatar
Floreal Cabanettes committed
491
                correct = False
Floreal Cabanettes's avatar
Floreal Cabanettes committed
492
493
494
                error_set = False
            session.delete_instance()
            self._after_start(correct, error_set)
495

496
    def getting_files(self):
497
498
499
500
501
        """
        Get files for the job
        :return: Tuple:
            [0] True if getting files succeed, False else
            [1] If error happenned, True if error already saved for the job, False else (error will be saved later)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
502
            [2] True if no data must be downloaded (will be downloaded with pending if True)
503
        """
Floreal Cabanettes's avatar
Floreal Cabanettes committed
504
505
506
507
508
509
510
511
512
513
514
515
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            job.status = "getfiles"
            job.save()
            correct = True
            should_be_local = True
            max_upload_size_readable = self.config.max_upload_size / 1024 / 1024  # Set it in Mb
            files_to_download = []
            if self.query is not None:
                if self.query.get_type() == "local":
                    self.query.set_path(self.__getting_local_file(self.query, "query"))
                    correct, error_set, should_be_local = self.check_file("query", should_be_local,
516
517
                                                                          max_upload_size_readable)
                    if not correct:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
518
                        return False, error_set, True
Floreal Cabanettes's avatar
Floreal Cabanettes committed
519
520
                elif self.__check_url(self.query):
                    files_to_download.append([self.query, "query"])
521
                else:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
522
                    return False, True, True
Floreal Cabanettes's avatar
Floreal Cabanettes committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
            if correct:
                if self.target is not None:
                    if self.target.get_type() == "local":
                        self.target.set_path(self.__getting_local_file(self.target, "target"))
                        correct, error_set, should_be_local = self.check_file("target", should_be_local,
                                                                              max_upload_size_readable)
                        if not correct:
                            return False, error_set, True
                    elif self.__check_url(self.target):
                        files_to_download.append([self.target, "target"])
                    else:
                        return False, True, True

            all_downloaded = True
            if correct :
                if len(files_to_download) > 0:
                    all_downloaded = False
                    thread = threading.Timer(0, self.download_files_with_pending,
                                             kwargs={"files_to_download": files_to_download,
                                                     "should_be_local": should_be_local,
                                                     "max_upload_size_readable": max_upload_size_readable})
                    thread.start()  # Start the execution

                elif correct and job.batch_type != "local" and should_be_local \
                        and self.get_pending_local_number() < self.config.max_run_local:
                    job.batch_type = "local"
                    job.save()
Floreal Cabanettes's avatar
Floreal Cabanettes committed
550
        return correct, False, all_downloaded
551

552
553
554
555
556
    def send_mail_post(self):
        """
        Send mail using POST url (we have no access to mailer)
        """
        key = Functions.random_string(15)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
557
        key_file = os.path.join(self.config.app_data, self.id_job, ".key")
558
559
560
        with open(key_file, "w") as k_f:
            k_f.write(key)
        data = parse.urlencode({"key": key}).encode()
Floreal Cabanettes's avatar
Floreal Cabanettes committed
561
        req = request.Request(self.config.web_url + "/send-mail/" + self.id_job, data=data)
562
563
564
565
        resp = request.urlopen(req)
        if resp.getcode() != 200:
            print("Job %s: Send mail failed!" % self.id_job)

566
567
    def run_job_in_thread(self, batch_system_type="local"):
        thread = threading.Timer(1, self.run_job, kwargs={"batch_system_type": batch_system_type})
568
569
        thread.start()  # Start the execution

570
571
572
573
    def prepare_data_in_thread(self):
        thread = threading.Timer(1, self.prepare_data)
        thread.start()  # Start the execution

574
    def prepare_data_cluster(self, batch_system_type):
575
576
577
578
        args = [self.config.cluster_prepare_script,
                "-t", self.target.get_path(),
                "-m", self.target.get_name(),
                "-p", self.preptime_file]
579
        if self.query is not None:
580
581
582
            args += ["-q", self.query.get_path(),
                     "-u", self.get_query_split(),
                     "-n", self.query.get_name()]
583
584
        return self.launch_to_cluster(step="prepare",
                                      batch_system_type=batch_system_type,
585
                                      command=self.config.cluster_python_script,
586
587
588
589
590
                                      args=args,
                                      log_out=self.logs,
                                      log_err=self.logs)

    def prepare_data_local(self):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
591
        with open(self.preptime_file, "w") as ptime, Job.connect():
592
593
594
            job = Job.get(Job.id_job == self.id_job)
            job.status = "preparing"
            job.save()
595
            ptime.write(str(round(time.time())) + "\n")
596
597
598
599
600
            error_tail = "Please check your input file and try again."
            if self.query is not None:
                fasta_in = self.query.get_path()
                splitter = Splitter(input_f=fasta_in, name_f=self.query.get_name(), output_f=self.get_query_split(),
                                    query_index=self.query_index_split)
601
602
603
604
605
606
607
608
609
610
611
612
                if splitter.split():
                    filtered_fasta = os.path.join(os.path.dirname(self.get_query_split()), "filtered_" +
                                                  os.path.basename(self.get_query_split()))
                    filter_f = Filter(fasta=self.get_query_split(),
                                      index_file=self.query_index_split,
                                      type_f="query",
                                      min_filtered=round(splitter.nb_contigs / 4),
                                      split=True,
                                      out_fasta=filtered_fasta,
                                      replace_fa=True)
                    filter_f.filter()
                else:
613
614
615
616
617
618
                    job.status = "fail"
                    job.error = "<br/>".join(["Query fasta file is not valid!", error_tail])
                    job.save()
                    if self.config.send_mail_status:
                        self.send_mail_post()
                    return False
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
            uncompressed = None
            if self.target.get_path().endswith(".gz"):
                uncompressed = self.target.get_path()[:-3]
            success, nb_contigs = index_file(self.target.get_path(), self.target.get_name(), self.idx_t, uncompressed)
            if success:
                in_fasta = self.target.get_path()
                if uncompressed is not None:
                    in_fasta = uncompressed
                filtered_fasta = os.path.join(os.path.dirname(in_fasta), "filtered_" + os.path.basename(in_fasta))
                filter_f = Filter(fasta=in_fasta,
                                  index_file=self.idx_t,
                                  type_f="target",
                                  min_filtered=round(nb_contigs / 4),
                                  split=False,
                                  out_fasta=filtered_fasta,
                                  replace_fa=True)
                is_filtered = filter_f.filter()
                if uncompressed is not None:
                    if is_filtered:
                        os.remove(self.target.get_path())
                        self.target.set_path(uncompressed)
                        with open(os.path.join(self.output_dir, ".target"), "w") as save_file:
                            save_file.write(uncompressed)
                    else:
                        os.remove(uncompressed)
            else:
                if uncompressed is not None:
                    try:
                        os.remove(uncompressed)
                    except FileNotFoundError:
                        pass
650
                job.status = "fail"
651
                job.error = "<br/>".join(["Target fasta file is not valid!", error_tail])
652
                job.save()
653
654
655
                if self.config.send_mail_status:
                    self.send_mail_post()
                return False
656
            ptime.write(str(round(time.time())) + "\n")
657
            job.status = "prepared"
658
            job.save()
659

660
    def prepare_data(self):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
661
662
663
664
665
666
        with Job.connect():
            job = Job.get(Job.id_job == self.id_job)
            if job.batch_type == "local":
                self.prepare_data_local()
            else:
                self.prepare_data_cluster(job.batch_type)
667

668
669
    def run_job(self, batch_system_type):
        success = False
670
671
        if batch_system_type == "local":
            success = self.__launch_local()
672
673
        elif batch_system_type in ["slurm", "sge"]:
            success = self.__launch_drmaa(batch_system_type)
674
        if success:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
            with Job.connect():
                job = Job.get(Job.id_job == self.id_job)
                with open(self.logs) as logs:
                    measures = logs.readlines()[-1].strip("\n").split(" ")
                    map_elapsed = round(float(measures[0]))
                    job.mem_peak = int(measures[1])
                with open(self.preptime_file) as ptime:
                    lines = ptime.readlines()
                    start = int(lines[0].strip("\n"))
                    end = int(lines[1].strip("\n"))
                    prep_elapsed = end - start
                    job.time_elapsed = prep_elapsed + map_elapsed
                job.status = "merging"
                job.save()
                if self.query is not None:
                    start = time.time()
                    paf_raw = self.paf_raw + ".split"
                    os.remove(self.get_query_split())
                    merger = Merger(self.paf_raw, paf_raw, self.query_index_split,
                                    self.idx_q)
                    merger.merge()
                    os.remove(self.paf_raw)
                    os.remove(self.query_index_split)
                    self.paf_raw = paf_raw
                    end = time.time()
                    job.time_elapsed += end - start
                else:
                    shutil.copyfile(self.idx_t, self.idx_q)
                    Path(os.path.join(self.output_dir, ".all-vs-all")).touch()
                sorter = Sorter(self.paf_raw, self.paf)
                sorter.sort()
706
                os.remove(self.paf_raw)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
707
708
                if self.target is not None and os.path.exists(self.target.get_path()):
                    os.remove(self.target.get_path())
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
                if os.path.isfile(os.path.join(self.output_dir, ".do-sort")):
                    paf = Paf(paf=self.paf,
                              idx_q=self.idx_q,
                              idx_t=self.idx_t,
                              auto_parse=False)
                    paf.sort()
                    if not paf.parsed:
                        success = False
                        job = Job.get(Job.id_job == self.id_job)
                        job.status = "fail"
                        job.error = "Error while sorting query. Please contact us to report the bug"
                if success:
                    job = Job.get(Job.id_job == self.id_job)
                    job.status = "success"
                    job.save()
Floreal Cabanettes's avatar
Floreal Cabanettes committed
724
        if self.config.send_mail_status:
725
726
            self.send_mail_post()

727
    def _after_start(self, success, error_set):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
728
729
        with Job.connect():
            if success:
730
                job = Job.get(Job.id_job == self.id_job)
Floreal Cabanettes's avatar
Floreal Cabanettes committed
731
                job.status = "waiting"
732
                job.save()
Floreal Cabanettes's avatar
Floreal Cabanettes committed
733
734
735
736
737
738
739
740
            else:
                if not error_set:
                    job = Job.get(Job.id_job == self.id_job)
                    job.status = "fail"
                    job.error = "<p>Error while getting input files. Please contact the support to report the bug.</p>"
                    job.save()
                if self.config.send_mail_status:
                    self.send_mail()
741

742
    def start_job(self):
743
        try:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
744
745
746
            success, error_set, all_downloaded = self.getting_files()
            if not success or all_downloaded:
                self._after_start(success, error_set)
747

748
749
        except Exception:
            print(traceback.print_exc())
Floreal Cabanettes's avatar
Floreal Cabanettes committed
750
751
752
753
754
755
756
            with Job.connect():
                job = Job.get(Job.id_job == self.id_job)
                job.status = "fail"
                job.error = "<p>An unexpected error has occurred. Please contact the support to report the bug.</p>"
                job.save()
                if self.config.send_mail_status:
                    self.send_mail()
757

758
    def launch(self):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
        with Job.connect():
            j1 = Job.select().where(Job.id_job == self.id_job)
            if len(j1) > 0:
                print("Old job found without result dir existing: delete it from BDD!")
                for j11 in j1:
                    j11.delete_instance()
            if self.target is not None:
                job = Job.create(id_job=self.id_job, email=self.email, batch_type=self.config.batch_system_type,
                                 date_created=datetime.now())
                job.save()
                if not os.path.exists(self.output_dir):
                    os.mkdir(self.output_dir)
                thread = threading.Timer(1, self.start_job)
                thread.start()
            else:
                job = Job.create(id_job=self.id_job, email=self.email, batch_type=self.config.batch_system_type,
                                 date_created=datetime.now(), status="fail")
                job.save()
777
778

    def status(self):
779
        try:
Floreal Cabanettes's avatar
Floreal Cabanettes committed
780
781
782
783
            with Job.connect():
                job = Job.get(Job.id_job == self.id_job)
                return {"status": job.status, "mem_peak": job.mem_peak, "time_elapsed": job.time_elapsed,
                        "error": job.error}
784
        except DoesNotExist:
785
            return {"status": "unknown", "error": ""}