aboutsummaryrefslogtreecommitdiff
path: root/lava-v2-submit-jobs.py
blob: 62695796590a8b8917be31ad5dd5bd91fbc4d86f (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
#!/usr/bin/python
#
# Copyright (C) 2016, 2017 Linaro Limited
# Author: Matt Hart <matthew.hart@linaro.org>
#
# Copyright (C) 2017 Collabora Limited
# Author: Guillaume Tucker <guillaume.tucker@collabora.com>
#
# This module is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

# Usage ./lava-v2-submit-jobs.py --username test --token xxxx --lab lab-name --jobs jobfolder

import os
import xmlrpclib
import yaml
import subprocess
import fnmatch
import time
import re
import argparse
import httplib
import json
import configparser

from lib import utils
from lib import configuration
from kernelci import lava

DEVICE_ONLINE_STATUS = ['idle', 'running', 'reserved']
JOBS = {}
SUBMITTED = {}

def submit_jobs(connection):
    print "Fetching all devices from LAVA"
    all_devices = connection.scheduler.all_devices()
    print "Fetching all device-types from LAVA"
    all_device_types = connection.scheduler.all_device_types()
    print "Fetching all device-type aliases from LAVA"
    all_aliases = []
    try:
        for alias in connection.scheduler.aliases.list():
            all_aliases.append(connection.scheduler.aliases.show(alias))
    except (xmlrpclib.ProtocolError, xmlrpclib.Fault, IOError, ValueError) as e:
        print("Unable to retrieve device_type aliases from LAVA; continuing")
        print(e)

    result = True

    print "Submitting Jobs to Server..."
    for job in JOBS:
        try:
            with open(job, 'rb') as stream:
                job_data = stream.read()
            job_info = yaml.safe_load(job_data)
            # Check if request device(s) are available
            if 'device_type' in job_info:
                device_type = lava.get_device_type_by_name(job_info['device_type'], all_device_types, all_aliases)
                if device_type:
                    if device_type_has_available(device_type, all_devices):
                        print "Submitting job %s to device-type %s" % (job_info.get('job_name', 'unknown'), job_info['device_type'])
                        job_id = connection.scheduler.submit_job(job_data)
                        SUBMITTED[job] = job_id
                    else:
                        print "Found device-type %s on server, but it had no available pipeline devices" % device_type['name']
            elif 'device_group' in job_info:
                print "Multinode Job Detected! Not supported yet :("
            elif 'vm_group' in job_info:
                print "VMGroup Job Detected! Not supported yet :("
            else:
                print "Should never get here - no idea what job type"
                print os.path.basename(job) + ' : skip'
        except (xmlrpclib.ProtocolError, xmlrpclib.Fault, IOError, ValueError) as e:
            print "Job submission error!"
            print job
            print e
            result = False
            continue

    return result

def load_jobs(top):
    for root, dirnames, filenames in os.walk(top):
        for filename in fnmatch.filter(filenames, '*.yaml'):
            JOBS[os.path.join(root, filename)] = None

def device_type_has_available(device_type, all_devices):
    for device in all_devices:
        if device[1] == device_type['name']:
            if device[2].lower() in DEVICE_ONLINE_STATUS:
                try:
                    return device[4]
                except IndexError:
                    print "LAVA all_devices() XMLRPC does not support pipeline"
                    return False
    return False

def main(args):
    config = configuration.get_config(args)

    jobs_submitted = config.get('submitted')
    lab = config.get('lab')
    if jobs_submitted:
        if not lab:
            raise Exception("Lab name required when saving submitted jobs")
        if os.path.exists(jobs_submitted):
            os.unlink(jobs_submitted)

    if config.get("repo"):
        retrieve_jobs(config.get("repo"))

    jobs = config.get("jobs")
    print("Loading jobs from {}".format(jobs))
    load_jobs(jobs)

    if not JOBS:
        print("No jobs to submit")
        result = False
    else:
        start_time = time.time()
        labs_config = configparser.ConfigParser()
        labs_config.read('labs.ini')
        lava_api = labs_config[config.get("lab")]['api']
        print("LAVA API: {}".format(lava_api))
        url = utils.validate_input(config.get("username"),
                                   config.get("token"),
                                   lava_api)
        connection = utils.connect(url)
        result = submit_jobs(connection)
        if jobs_submitted and SUBMITTED:
            print("Saving submitted jobs data in {}".format(jobs_submitted))
            data = {
                'start_time': start_time,
                'lab': config.get('lab'),
                'jobs': {k: v for k, v in SUBMITTED.iteritems() if v},
            }
            with open(jobs_submitted, 'w') as json_file:
                json.dump(data, json_file)

    exit(0 if result is True else 1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration for the LAVA server")
    parser.add_argument("--section", default="default",
                        help="section in the LAVA config file")
    parser.add_argument("--lab", help="KernelCI Lab Name")
    parser.add_argument("--jobs", required=True,
                        help="path to jobs directory (default is cwd)")
    parser.add_argument("--username", help="username for the LAVA server")
    parser.add_argument("--token", help="token for LAVA server api")
    parser.add_argument("--repo", help="git repo for LAVA jobs")
    parser.add_argument("--submitted",
                        help="path to JSON file to save submitted jobs data")
    args = vars(parser.parse_args())
    main(args)