summaryrefslogtreecommitdiff
path: root/saharaclient/osc/v1/jobs.py
blob: 27f1f882c9e4454715bffe5a828b5df4d2e93792 (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# Copyright (c) 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils as osc_utils
from oslo_log import log as logging
from oslo_serialization import jsonutils

from saharaclient.osc import utils

JOB_FIELDS = ['id', 'job_template_id', 'cluster_id', 'input_id', 'output_id',
              'start_time', 'end_time', 'status', 'is_public', 'is_protected',
              'engine_job_id']

JOB_STATUS_CHOICES = ['done-with-error', 'failed', 'killed', 'pending',
                      'running', 'succeeded', 'to-be-killed']


def _format_job_output(data):
    data['status'] = data['info']['status']
    del data['info']
    data['job_template_id'] = data.pop('job_id')


class ExecuteJob(command.ShowOne):
    """Executes job"""

    log = logging.getLogger(__name__ + ".ExecuteJob")

    def get_parser(self, prog_name):
        parser = super(ExecuteJob, self).get_parser(prog_name)

        parser.add_argument(
            '--job-template',
            metavar="<job-template>",
            help="Name or ID of the job template "
                 "[REQUIRED if JSON is not provided]",
        )
        parser.add_argument(
            '--cluster',
            metavar="<cluster>",
            help="Name or ID of the cluster "
                 "[REQUIRED if JSON is not provided]",
        )
        parser.add_argument(
            '--input',
            metavar="<input>",
            help="Name or ID of the input data source",
        )
        parser.add_argument(
            '--output',
            metavar="<output>",
            help="Name or ID of the output data source",
        )
        parser.add_argument(
            '--params',
            metavar="<name:value>",
            nargs='+',
            help="Parameters to add to the job"
        )
        parser.add_argument(
            '--args',
            metavar="<argument>",
            nargs='+',
            help="Arguments to add to the job"
        )
        parser.add_argument(
            '--public',
            action='store_true',
            default=False,
            help='Make the job public',
        )
        parser.add_argument(
            '--protected',
            action='store_true',
            default=False,
            help='Make the job protected',
        )
        configs = parser.add_mutually_exclusive_group()
        configs.add_argument(
            '--config-json',
            metavar='<filename>',
            help='JSON representation of the job configs'
        )
        configs.add_argument(
            '--configs',
            metavar="<name:value>",
            nargs='+',
            help="Configs to add to the job"
        )
        parser.add_argument(
            '--interface',
            metavar='<filename>',
            help='JSON representation of the interface'
        )
        parser.add_argument(
            '--json',
            metavar='<filename>',
            help='JSON representation of the job. Other arguments will not be '
                 'taken into account if this one is provided'
        )
        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        if parsed_args.json:
            blob = osc_utils.read_blob_file_contents(parsed_args.json)
            try:
                template = jsonutils.loads(blob)
            except ValueError as e:
                raise exceptions.CommandError(
                    'An error occurred when reading '
                    'template from file %s: %s' % (parsed_args.json, e))

            if 'job_configs' in template:
                template['configs'] = template.pop('job_configs')

            data = client.job_executions.create(**template).to_dict()
        else:
            if not parsed_args.cluster or not parsed_args.job_template:
                raise exceptions.CommandError(
                    'At least --cluster, --job-template, arguments should be '
                    'specified or json template should be provided with '
                    '--json argument')

            job_configs = {}

            if parsed_args.interface:
                blob = osc_utils.read_blob_file_contents(parsed_args.json)
                try:
                    parsed_args.interface = jsonutils.loads(blob)
                except ValueError as e:
                    raise exceptions.CommandError(
                        'An error occurred when reading '
                        'interface from file %s: %s' % (parsed_args.json, e))

            if parsed_args.config_json:
                blob = osc_utils.read_blob_file_contents(parsed_args.configs)
                try:
                    job_configs['configs'] = jsonutils.loads(blob)
                except ValueError as e:
                    raise exceptions.CommandError(
                        'An error occurred when reading '
                        'configs from file %s: %s' % (parsed_args.json, e))
            elif parsed_args.configs:
                job_configs['configs'] = dict(
                    map(lambda x: x.split(':', 1), parsed_args.configs))

            if parsed_args.args:
                job_configs['args'] = parsed_args.args

            if parsed_args.params:
                job_configs['params'] = dict(
                    map(lambda x: x.split(':', 1), parsed_args.params))

            jt_id = utils.get_resource_id(
                client.jobs, parsed_args.job_template)
            cluster_id = utils.get_resource_id(
                client.clusters, parsed_args.cluster)
            if parsed_args.input not in [None, "", "None"]:
                input_id = utils.get_resource_id(
                    client.data_sources, parsed_args.input)
            else:
                input_id = None
            if parsed_args.output not in [None, "", "None"]:
                output_id = utils.get_resource_id(
                    client.data_sources, parsed_args.output)
            else:
                output_id = None

            data = client.job_executions.create(
                job_id=jt_id, cluster_id=cluster_id, input_id=input_id,
                output_id=output_id, interface=parsed_args.interface,
                configs=job_configs, is_public=parsed_args.public,
                is_protected=parsed_args.protected).to_dict()

        sys.stdout.write(
            'Job "{job}" has been started successfully.\n'.format(
                job=data['id']))

        _format_job_output(data)
        data = utils.prepare_data(data, JOB_FIELDS)

        return self.dict2columns(data)


class ListJobs(command.Lister):
    """Lists jobs"""

    log = logging.getLogger(__name__ + ".ListJobs")

    def get_parser(self, prog_name):
        parser = super(ListJobs, self).get_parser(prog_name)
        parser.add_argument(
            '--long',
            action='store_true',
            default=False,
            help='List additional fields in output',
        )
        parser.add_argument(
            '--status',
            metavar="<status>",
            choices=JOB_STATUS_CHOICES,
            help="List jobs with specific status"
        )

        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        data = client.job_executions.list()
        for job in data:
            job.status = job.info['status']

        if parsed_args.status:
            data = [job for job in data
                    if job.info['status'] == parsed_args.status.replace(
                        '-', '').upper()]

        if parsed_args.long:
            columns = ('id', 'cluster id', 'job id', 'status', 'start time',
                       'end time')
            column_headers = utils.prepare_column_headers(columns)

        else:
            columns = ('id', 'cluster id', 'job id', 'status')
            column_headers = utils.prepare_column_headers(columns)

        return (
            column_headers,
            (osc_utils.get_item_properties(
                s,
                columns
            ) for s in data)
        )


class ShowJob(command.ShowOne):
    """Display job details"""

    log = logging.getLogger(__name__ + ".ShowJob")

    def get_parser(self, prog_name):
        parser = super(ShowJob, self).get_parser(prog_name)
        parser.add_argument(
            "job",
            metavar="<job>",
            help="ID of the job to display",
        )

        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        data = client.job_executions.get(parsed_args.job).to_dict()

        _format_job_output(data)
        data = utils.prepare_data(data, JOB_FIELDS)

        return self.dict2columns(data)


class DeleteJob(command.Command):
    """Deletes job"""

    log = logging.getLogger(__name__ + ".DeleteJob")

    def get_parser(self, prog_name):
        parser = super(DeleteJob, self).get_parser(prog_name)
        parser.add_argument(
            "job",
            metavar="<job>",
            nargs="+",
            help="ID(s) of the job(s) to delete",
        )
        parser.add_argument(
            '--wait',
            action='store_true',
            default=False,
            help='Wait for the job(s) delete to complete',
        )

        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing
        for job_id in parsed_args.job:
            client.job_executions.delete(job_id)
            sys.stdout.write(
                'Job "{job}" deletion has been started.\n'.format(job=job_id))

        if parsed_args.wait:
            for job_id in parsed_args.job:
                if not utils.wait_for_delete(client.job_executions, job_id):
                    self.log.error(
                        'Error occurred during job deleting: %s' %
                        job_id)
                else:
                    sys.stdout.write(
                        'Job "{job}" has been removed successfully.\n'.format(
                            job=job_id))


class UpdateJob(command.ShowOne):
    """Updates job"""

    log = logging.getLogger(__name__ + ".UpdateJob")

    def get_parser(self, prog_name):
        parser = super(UpdateJob, self).get_parser(prog_name)

        parser.add_argument(
            'job',
            metavar="<job>",
            help="ID of the job to update",
        )
        public = parser.add_mutually_exclusive_group()
        public.add_argument(
            '--public',
            action='store_true',
            help='Make the job public (Visible from other projects)',
            dest='is_public'
        )
        public.add_argument(
            '--private',
            action='store_false',
            help='Make the job private (Visible only from this project)',
            dest='is_public'
        )
        protected = parser.add_mutually_exclusive_group()
        protected.add_argument(
            '--protected',
            action='store_true',
            help='Make the job protected',
            dest='is_protected'
        )
        protected.add_argument(
            '--unprotected',
            action='store_false',
            help='Make the job unprotected',
            dest='is_protected'
        )

        parser.set_defaults(is_public=None, is_protected=None)

        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        update_dict = utils.create_dict_from_kwargs(
            is_public=parsed_args.is_public,
            is_protected=parsed_args.is_protected)

        data = client.job_executions.update(
            parsed_args.job, **update_dict).job_execution

        _format_job_output(data)
        data = utils.prepare_data(data, JOB_FIELDS)

        return self.dict2columns(data)