summaryrefslogtreecommitdiff
path: root/submit-json.py
blob: 095c1492a056dda416f67d084a9ff5c6e1ec8763 (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
#!/usr/bin/python

import os
import sys
import json
import xmlrpclib
import urllib2
import re

def obfuscate_credentials(s):
    return re.sub(r'([^ ]:).+?(@)', r'\1xxx\2', s)

def lava_submit(config):
    # LAVA user
    lava_user = os.environ.get('LAVA_USER')
    if lava_user is None:
        f = open('/var/run/lava/lava-user')
        lava_user = f.read().strip()
        f.close()

    # LAVA token
    lava_token = os.environ.get('LAVA_TOKEN')
    if lava_token is None:
        f = open('/var/run/lava/lava-token')
        lava_token = f.read().strip()
        f.close()

    # LAVA server URL
    lava_server = os.environ.get('LAVA_SERVER',
                                 'validation.linaro.org/lava-server/RPC2/')

    # LAVA server base URL
    lava_server_root = lava_server.rstrip('/')
    if lava_server_root.endswith('/RPC2'):
        lava_server_root = lava_server_root[:-len('/RPC2')]

    try:
        server_url = \
            'https://{lava_user:>s}:{lava_token:>s}@{lava_server:>s}'
        server = \
            xmlrpclib.ServerProxy(server_url.format(
                lava_user=lava_user,
                lava_token=lava_token,
                lava_server=lava_server), verbose=False)
        print server
        lava_job_id = server.scheduler.submit_job(config)
    except xmlrpclib.ProtocolError, e:
        print 'Error making a LAVA request:', obfuscate_credentials(str(e))
        sys.exit(1)
    except xmlrpclib.Fault as err:
        print "A fault occurred"
        print "Fault code: %d" % err.faultCode
        print "Fault string: %s" % err.faultString
        sys.exit(1)

    print 'LAVA Job Id: %s, URL: http://%s/scheduler/job/%s' % \
          (lava_job_id, lava_server_root, lava_job_id)
    json.dump({'lava_url': 'http://' + lava_server_root,
               'job_id': lava_job_id}, open('lava-job-info', 'w'))


def main():
    '''Script entry point.
    We should be called from Jenkins and expect the following to be defined:
    pass json file as first parameter or in stdin
    '''

    if len(sys.argv) <= 1:
       # no command line parameter, read stdin
       config=sys.stdin.read()
    else:
       try:
           json_fp = open(sys.argv[1])
           config = json_fp.read()
           json_fp.close()
       except IOError as e:
           print "I/O error({0}): {1}".format(e.errno, e.strerror)

    print config

    skip_lava = os.environ.get('SKIP_LAVA')
    if skip_lava is None:
        lava_submit(config)
    else:
        print 'LAVA job submission skipped.'


if __name__ == '__main__':
    main()