JobStart.py 4.99 KB
Newer Older
1
2
import time

Lionel Walter's avatar
Lionel Walter committed
3
from flask_restful import Resource, reqparse, current_app
4
from flasgger import swag_from
5

6
7
8
9
10
from import_api_app.models.Error import ImportApiError

from import_api_app.resources.KafkaTopics import create_topics
from import_api_app.resources.HelmStart import start
from import_api_app.resources.JobReport import get_report
11
from import_api_app.resources.WriteJobResultsToDrupal import write_results, update_status
12

Lionel Walter's avatar
Lionel Walter committed
13
14
from kubernetes import client

15
16
from threading import Thread

Lionel Walter's avatar
Lionel Walter committed
17
18
import requests

19
20
21
22

class JobStart(Resource):
    # Todo validate requests
    # @swag.validate('job-parameters')
23
24
    @swag_from('JobStart.yml')
    def post(self, institution_id, record_set_id, process_id, job_name):
25
26
27
28
29

        parser = reqparse.RequestParser()
        parser.add_argument('job-parameters', type=dict)
        args = parser.parse_args()
        job_parameters = args['job-parameters']
30
31
32
        job_parameters['institutionId'] = institution_id
        job_parameters['recordSetId'] = record_set_id
        job_parameters['processId'] = process_id
33

Lionel Walter's avatar
Lionel Walter committed
34
35
36
        # to debug parameters sent by drupal
        current_app.logger.debug(job_parameters)

37
38
39
40
41
42
43
44
45
        # todo take care of creation of process_id-reporting
        job_topic = f"{process_id}-{job_name}"
        job_reporting_topic = f"{process_id}-{job_name}-reporting"

        topics = [
            job_topic,
            job_reporting_topic,
        ]

46
47
48
49
50
51
        # if we are in the first step, text-file-validation, we create the generic reporting topic
        # (and remove its content if it already exists)
        if job_name == 'text-file-validation':
            process_reporting_topic = f"{process_id}-reporting"
            topics.append(process_reporting_topic)

Lionel Walter's avatar
Lionel Walter committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        if job_name == 'mapper-service':
            # load mapping file from url
            try:
                # only allow mapping file at url starting with
                mapping_file_url = job_parameters['configFileName']
                if not(mapping_file_url.startswith(
                        'https://gitlab.switch.ch/memoriav/memobase-2020/'
                )):
                    return {
                               'error': 'The url of the mapping file should start'
                                        'with https://gitlab.switch.ch/memoriav/memobase-2020/'
                           }, 500
                response = requests.get(mapping_file_url)
                mapping_file_content = response.text

Lionel Walter's avatar
Lionel Walter committed
67
68
                config_map_name = process_id+"-mapper-service-mapping-config"

Lionel Walter's avatar
Lionel Walter committed
69
70
71
                # Instantiate the configmap object
                metadata = client.V1ObjectMeta(
                    labels=dict(app="import-api-app"),
Lionel Walter's avatar
Lionel Walter committed
72
                    name=config_map_name,
Lionel Walter's avatar
Lionel Walter committed
73
74
75
76
77
78
                    namespace=current_app.config['NAMESPACE'],
                )

                configmap = client.V1ConfigMap(
                    api_version="v1",
                    kind="ConfigMap",
Lionel Walter's avatar
Lionel Walter committed
79
                    data=dict(mapping=mapping_file_content),
Lionel Walter's avatar
Lionel Walter committed
80
81
82
                    metadata=metadata
                )

Lionel Walter's avatar
Lionel Walter committed
83
84
85
86
                # use mapping as well as name for the config as above
                job_parameters['configFileName'] = "mapping"
                job_parameters['configMapName'] = config_map_name

Lionel Walter's avatar
Lionel Walter committed
87
88
89
90
91
92
93
94
95
96
97
98
                v1 = client.CoreV1Api()

                v1.create_namespaced_config_map(
                    namespace=current_app.config['NAMESPACE'],
                    body=configmap
                )
            except Exception:
                return {
                           'error': 'impossible to load the mapping file as a config map. Url: '
                                    + mapping_file_url
                       }, 500

99
        try:
Lionel Walter's avatar
Lionel Walter committed
100
            create_topics(topics)
101
102
103
104
        except ImportApiError as e:
            return {'error': e.message}, 500

        try:
105
            helm_result = start(process_id, job_name, job_parameters)
106
107
        except ImportApiError as e:
            return {'error': e.message}, 500
108

109
        FlaskThread(target=reporting, args=(
110
            job_name,
111
            job_reporting_topic,
112
113
            job_parameters['drupalJobLogResultUuid'],
            job_parameters['drupalJobUuid']
114
        )).start()
115

116
        return helm_result
117

118

119
120
121
122
123
124
125
126
127
128
class FlaskThread(Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.app = current_app._get_current_object()

    def run(self):
        with self.app.app_context():
            super().run()


129
def reporting(job_name, job_reporting_topic, drupal_job_log_uuid, drupal_job_uuid):
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    # wait a bit before consuming results
    time.sleep(3)

    try:
        report = get_report(job_reporting_topic)
    except ImportApiError as e:
        return {'error': e.message}, 500

    # write report
    # todo check if drupalJobLogResultUuid is defined
    try:
        write_results(drupal_job_log_uuid, report["report"])
    except ImportApiError as e:
        return {'error': e.message}, 500
144
145
146
147
148

    try:
        update_status(drupal_job_uuid, job_name)
    except ImportApiError as e:
        return {'error': e.message}, 500