aboutsummaryrefslogtreecommitdiff
path: root/build-scripts/post-build-lava.py
blob: 6e349780be7d0c0f5b1d7483d8c0ada0494e2190 (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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#!/usr/bin/env python
import sys
import os
import re
import json
import copy
import xmlrpclib
import fileinput
import urllib


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

# Map a TARGET_PRODUCT to LAVA parameters.
PRODUCT_MAP = {
    "pandaboard": {
        "test_device_type": "panda"
            },
    "full_panda": {
        "test_device_type": "panda"
            },
    "beagleboard": {
        "test_device_type": "beaglexm"
            },
    "snowball": {
        "test_device_type": "snowball_sd"
            },
    "iMX53": {
        "test_device_type": "mx53loco"
            },
    "origen": {
        "test_device_type": "origen",
            },
    "vexpress": {
        "test_device_type": "vexpress-a9",
            },
    "vexpress_rtsm": {
        "test_device_type": "rtsm_ve-a15x4-a7x4",
            },
    "juno": {
        "test_device_type": "wg",
        "test_stream": "/private/team/wg/wg-private/",
            },
    "fvp": {
        "test_device_type": "rtsm_fvp_base-aemv8a",
            },
    "juice": {
        "test_device_type": "rtsm_fvp_base-aemv8a",
            },
    "aosp_maguro": {
        "test_device_type": "nexus",
            },
    "full_maguro": {
        "test_device_type": "nexus",
            },
    "full_arndale": {
        "test_device_type": "arndale",
            },
    "hi4511": {
        "test_device_type": "k3v2",
            },
    "full_jacinto6evm" : {
        "test_device_type": "vayu",
            },
    "fujitsu": {
        "test_device_type": "aa9",
        "test_stream": "/private/team/fujitsu/ci-LT-Fujitsu-working-tree/"
            },
}

OPTION_SUFFIX = "_OPTION"
TIMEOUT_SUFFIX = "_TIMEOUT"
# Special token for LAVA_TEST_PLAN that allows the build owner to encode a
# reboot in between test actions.
REBOOT_TOKEN = '[system-reboot]'

# CONSTANTS DEFINITION
DEFAULT_LAVA_SCHEMA = 'https'
DEFAULT_LAVA_URL = 'validation.linaro.org/RPC2/'
DEFAULT_LAVA_STREAM = '/private/team/linaro/android-daily/'
DEFAULT_LAVA_DIR = '/var/run/lava/'
DEFAULT_LAVA_USER_FILE = '%s/lava-user' % DEFAULT_LAVA_DIR
DEFAULT_LAVA_TOKEN_FILE = '%s/lava-token' % DEFAULT_LAVA_DIR
DEFAULT_DOWNLOAD_BASE_URL = 'http://snapshots.linaro.org/android/'
DEFAULT_TIMEOUT_VALUE = 18000

# Environment variables name
ENV_LAVA_STREAM = 'LAVA_STREAM'
ENV_LAVA_SERVER = 'LAVA_SERVER'
ENV_LAVA_DEVICE = 'LAVA_DEVICE'
ENV_LAVA_DEVICE_TYPE = 'LAVA_DEVICE_TYPE'
ENV_LAVA_TEST_PLAN = 'LAVA_TEST_PLAN'
ENV_LAVA_TEST_PLAN_SEC_PRE = 'LAVA_TEST_PLAN_SECONDARY_'
ENV_LAVA_TOKEN_FILE = 'LAVA_TOKEN_FILE'
ENV_LAVA_USER = 'LAVA_USER'
# Build url, defined by android-build, e.g.
# https://android-build.linaro.org/jenkins/job/linaro-android_leb-panda/61/
ENV_BUILD_URL = 'BUILD_URL'
ENV_DEFAULT_TIMEOUT = 'DEFAULT_TIMEOUT'
# Target product name, user defined, e.g. pandaboard
ENV_TARGET_PRODUCT = 'TARGET_PRODUCT'
ENV_BOOTLOADER_TYPE = 'BOOTLOADER_TYPE'


class LAVADeviceBase(object):
    """
    Base class for definition of the device type and target in lava job.
    """

    def __init__(self, name=None):
        self.name = name


class LAVADeviceType(LAVADeviceBase):
    """
    Representation the definition of the device type in lava job.
    """


class LAVADeviceTarget(LAVADeviceBase):
    """
    Representation the definition of the device target in lava job.
    """


def get_env_var(name, default=None):
    return os.environ.get(name, default)


def get_lava_device_type_or_target():
    '''
    Here we support the specification by both,
    LAVA_DEVICE or LAVA_DEVICE_TYPE, and we can specify
    both of them at the same time.
    '''
    devices = []

    # allow to submit to a specific device
    test_device = get_env_var(ENV_LAVA_DEVICE)
    if test_device:
        targets = test_device.split(',')
        for dev_target in targets:
            dev_target = dev_target.strip()
            if dev_target:
                devices.append(LAVADeviceTarget(name=dev_target))

    # allow overload lava device_type by build config
    test_device_type = get_env_var(ENV_LAVA_DEVICE_TYPE)

    target_product = get_env_var(ENV_TARGET_PRODUCT)
    # only use the default device type when neither of
    # LAVA_DEVICE or LAVA_DEVICE_TYPE is specified.
    # or say we will not use the value when any of
    # LAVA_DEVICE or LAVA_DEVICE_TYPE is specified.
    if (not test_device_type) and (not test_device):
        test_device_type = PRODUCT_MAP[target_product]["test_device_type"]
    if test_device_type:
        types = test_device_type.split(',')
        for dev_type in types:
            dev_type = dev_type.strip()
            if dev_type:
                devices.append(LAVADeviceType(name=dev_type))

    return devices


def get_schema_and_url():
    lava_server = get_env_var(ENV_LAVA_SERVER)
    if lava_server is None:
        schema = DEFAULT_LAVA_SCHEMA
        url_no_schema = DEFAULT_LAVA_URL
    elif lava_server.find('://') >= 0:
        schema = lava_server[:lava_server.find('://')]
        url_no_schema = lava_server[lava_server.find('://') + len('://'):]
    else:
        ## the case that no https and http specified in the url
        ## like: validation.linaro.org/RPC2/
        schema = DEFAULT_LAVA_SCHEMA
        url_no_schema = lava_server
    return (schema, url_no_schema)

def get_job_list():
    job_list = ['LAVA_JOB_URL']
    sec_job_prefix = 'LAVA_JOB_URL_'

    for var in os.environ.keys():
        if var.startswith(sec_job_prefix):
            job_list.append(var)
    job_list.sort()

    return job_list

def get_plan_list():
    plan_list = [ENV_LAVA_TEST_PLAN]
    sec_plan_prefix = ENV_LAVA_TEST_PLAN_SEC_PRE

    for var in os.environ.keys():
        if var.startswith(sec_plan_prefix):
            plan_list.append(var)
    plan_list.sort()

    return plan_list


def check_target_product():
    # Board-specific parameters
    target_product = get_env_var(ENV_TARGET_PRODUCT)
    if target_product not in PRODUCT_MAP:
        # We don't know how to test this job, so skip testing.
        print "Don't know how to test this board. Skip testing."
        sys.exit(1)


def gen_lava_test_shell_action(test_name=None, test_para=None):
    if not test_para or not test_name:
        return None
    key_value_ary = test_para.split()
    key_value_hash = {}
    for pair_line in key_value_ary:
        pair = pair_line.split('=', 1)
        if len(pair) != 2:
            continue
        if pair[0]:
            key_value_hash[pair[0]] = pair[1]
    parameters = {}
    if key_value_hash.get('timeout'):
        parameters['timeout'] = int(key_value_hash.get('timeout'))

    if test_name == 'lava-test-shell-url':
        if key_value_hash.get('url'):
            parameters["testdef_urls"] = [key_value_hash['url']]
        else:
            return None
        action = {
                    "command": "lava_test_shell",
                    "parameters": parameters
                 }
        return action
    else:
        if not key_value_hash.get('repo'):
            return None

        repo = {}
        if test_name == 'lava-test-shell-git':
            repo = {"git-repo": key_value_hash.get('repo')}
        elif test_name == 'lava-test-shell-bzr':
            repo = {"bzr-repo": key_value_hash.get('repo')}
        else:
            return None

        if key_value_hash.get('revision'):
            repo["revision"] = key_value_hash.get('revision')
        if key_value_hash.get('testdef'):
            repo["testdef"] = key_value_hash.get('testdef')

        parameters["testdef_repos"] = [repo]
        action = {
                    "command": "lava_test_shell",
                    "parameters": parameters
                 }

        return action


def gen_reboot_action(test_para=None):
    action = {"command": "boot_linaro_android_image"}
    if not test_para:
        return action
    key_value_ary = test_para.split()
    key_value_hash = {}
    for pair_line in key_value_ary:
        pair = pair_line.split('=', 1)
        if len(pair) != 2:
            continue
        if pair[0]:
            key_value_hash[pair[0]] = pair[1]

    parameters = {}
    adb_check_val = key_value_hash.get('adb_check')
    if adb_check_val and adb_check_val.lower() == 'true':
        parameters['adb_check'] = True
        action['parameters'] = parameters

    return action


def gen_lava_android_test_actions(tests=[]):
    actions = []
    if len(tests) == 0:
        return actions
    test_actions = []
    for test in tests:
        #support the special action for android test,
        #like android_install_cts_medias
        if test.startswith("android_"):
            continue

        #skip lava-test-shell test
        if test.startswith("lava-test-shell"):
            continue

        if test.startswith(REBOOT_TOKEN):
            continue
        ## support for test that specified with option like methanol,methanol(DEFAULT)
        if test.find('(') >= 0\
            and test.rfind(')') > test.find('('):
            test = test[:test.find('(')].strip()
            if not test:
                continue
        test_actions.append(test)

    ## make the next test installation be able to execute
    ## when one test installation failed
    for test_action in list(set(test_actions)):
        inst_action = {
                          "command": "lava_android_test_install",
                          "parameters": {
                                        # ensure only unique test names
                                        "tests": [test_action]
                                         }
                            }
        actions.append(inst_action)

    for test in tests:

        ## support for test that specified with option like methanol,methanol(DEFAULT)
        ## for this case, get the option from the test
        test_option = ''
        if test.find('(') >= 0 and test.rfind(')') > test.find('(') \
            and test[:test.find('(')].strip():
            test_option = test[test.find('(') + 1: test.rfind(')')]
            test = test[:test.find('(')].strip()

        if test.startswith('lava-test-shell'):
            run_action = gen_lava_test_shell_action(test_name=test,
                                                    test_para=test_option)
            if run_action:
                actions.append(run_action)
            continue

        if test.startswith(REBOOT_TOKEN):
            run_action = gen_reboot_action(test_para=test_option)
            if run_action:
                actions.append(run_action)
            continue

        parameters = {}
        if not test_option:
            test_option = os.environ.get('%s%s' % (test.upper(), OPTION_SUFFIX))

        if test_option:
            parameters['option'] = test_option

        timeout_option = os.environ.get('%s%s' % (test.upper(),
                                                  TIMEOUT_SUFFIX))
        if timeout_option:
            parameters['timeout'] = int(timeout_option)

        if test.startswith('android_'):
            run_action = {
                          "command": test,
                          "parameters": parameters
                        }
            actions.append(run_action)
        elif test == 'hostshell-workload':
            config = "config.csv"
            workload_url = "ssh://linaro-lava@mombin.canonical.com/srv/linaro-private.git.linaro.org/people/bhoj/workload-automation.git"
            config_list = []
            config_prefix = "WORKLOAD_CONFIG_"
            url_prefix = "WORKLOAD_URL"
            for var in os.environ.keys():
                if var.startswith(config_prefix):
                    config_list.append(var)
                elif var == url_prefix:
                    workload_url = os.environ.get(var)
            config_list.sort()
            for var in config_list:
                config = os.environ.get(var)
                run_action = {
                              "command": "lava_android_test_run",
                              "parameters": {
                              "option": "-c %s -g %s " % (config, workload_url),
                              "test_name": test
                                           }
                            }
                actions.append(run_action)
                actions.append({"command": "boot_linaro_android_image"})
        else:
            parameters['test_name'] = test
            run_action = {
                          "command": "lava_android_test_run",
                          "parameters": parameters
                        }
            actions.append(run_action)

    return actions


def gen_test_plan_actions(test_plan=None):
    if test_plan is None:
        test_plan = os.environ.get("LAVA_TEST_PLAN")
    if test_plan is None:
        test_plan = '0xbench, glmark2, monkey'
    test_plans = test_plan.split(',')
    for index in range(len(test_plans)):
        test_plans[index] = test_plans[index].strip()
        if test_plans[index] == "test_android_0xbench":
            test_plans[index] = "0xbench"
    return gen_lava_android_test_actions(test_plans)


def gen_command_action(commands=[], cmd_file=None, parser=None, timeout=None):
    parameters = None
    if commands:
        parameters = {'commands': commands}
    elif cmd_file:
        parameters = {'command_file': cmd_file}

    if parameters and parser:
        parameters['parser'] = parser

    if timeout:
        parameters['timeout'] = int(timeout)

    action = {"command": "lava_android_test_run_custom",
              "parameters": parameters}
    return action


def gen_custom_actions():
    test_actions = []
    prefix = 'LAVA_TEST_'
    pat_suffix = '_PATTERN'
    sec_job_prefix = 'LAVA_TEST_PLAN_SECONDARY_'
    test_list = []
    for var in os.environ.keys():
        if var.startswith(prefix) and (not var.endswith(pat_suffix)) \
           and (var != 'LAVA_TEST_PLAN') \
           and (not var.startswith(sec_job_prefix)) \
           and (not var.endswith(TIMEOUT_SUFFIX)):
            test_list.append(var)
    test_list.sort()
    for var in test_list:
        cmd = os.environ.get(var)
        pattern = os.environ.get('%s%s' % (var, pat_suffix))
        timeout = os.environ.get('%s%s' % (var, TIMEOUT_SUFFIX))
        test_actions.append(gen_command_action(commands=[cmd],
                                                parser=pattern,
                                                timeout=timeout))

    return test_actions


def gen_monkeyrunner_actions():
    test_actions = []
    prefix = 'MONKEY_RUNNER_URL_'
    test_list = []
    for var in os.environ.keys():
        if var.startswith(prefix) and (not var.endswith(TIMEOUT_SUFFIX)):
            test_list.append(var)
    test_list.sort()
    for var in test_list:
        url = os.environ.get(var)
        parameters = {"url": url}
        timeout = os.environ.get('%s%s' % (var, TIMEOUT_SUFFIX))
        if timeout:
            parameters['timeout'] = int(timeout)
        action = {
                    "command": "lava_android_test_run_monkeyrunner",
                    "parameters": parameters
                 }
        test_actions.append(action)
    return test_actions


def gen_test_actions():
    test_actions = []
    test_actions.extend(gen_custom_actions())
    test_actions.extend(gen_test_plan_actions())
    test_actions.extend(gen_monkeyrunner_actions())
    return test_actions


def gen_deploy_action():

    # Job name, defined by android-build, e.g. linaro-android_leb-panda
    job_name = os.environ.get("JOB_NAME")
    frontend_job_name = "~" + job_name.replace("_", "/", 1)

    # Build number, defined by android-build, e.g. 61
    build_number = os.environ.get("BUILD_NUMBER")

    # download base URL, this may differ from job URL if we don't host
    # downloads in Jenkins any more
    download_url = "%s/%s/%s/" % (DEFAULT_DOWNLOAD_BASE_URL,
                                  frontend_job_name,
                                  build_number)

    # Set the file extension based on the type of artifacts
    artifact_type = os.environ.get("MAKE_TARGETS", "tarball")
    if artifact_type == "droidcore":
        file_extension = "img"
    else:
        file_extension = "tar.bz2"

    action = {"command": "deploy_linaro_android_image",
              "parameters": {
                    "boot": "%s%s%s" % (download_url,
                                        "/boot.", file_extension),
                    "system": "%s%s%s" % (download_url,
                                         "/system.", file_extension),
                    "data": "%s%s%s" % (download_url,
                                       "/userdata.", file_extension)
                  },
              "metadata": {
                    "android.name": job_name,
                    "android.build": '%s' % build_number,
                    "android.url": get_env_var(ENV_BUILD_URL)
                  }
             }

    bootloadertype = get_env_var(ENV_BOOTLOADER_TYPE)
    if bootloadertype == "uefi":
        action["parameters"]["bootloadertype"] = "uefi"

    return action


def gen_boot_action():
    # Some devices need not boot to GUI like the Tiny Android builds and builds
    # which need a proprietary binary overlay to be installed before expecting
    # GUI.
    boot_action = {"command": "boot_linaro_android_image"}

    wait_for_homescreen = os.environ.get("LAVA_WAIT_FOR_HOMESCREEN", 'true')
    if wait_for_homescreen.lower() in ['0', 'false', 'no']:
        boot_action["parameters"] = {"wait_for_home_screen": False}
    return boot_action


def gen_install_binaries_action():
    # User can disable the installation of android binaries (doing this will
    # disable hardware acceleration)
    ENV_LAVA_ANDROID_BINARIES = 'LAVA_ANDROID_BINARIES'
    enable_binaries = get_env_var(ENV_LAVA_ANDROID_BINARIES, 'false')

    # Not set, default to False, because this is relevant only for panda
    # from Vishal
    if enable_binaries.lower() in ['1', 'true', 'yes']:
        return {"command": "android_install_binaries"}


def gen_submit_action():

    (schema, url_no_schema) = get_schema_and_url()
    schema_url = '%s://%s' % (schema, url_no_schema)

    lava_stream = get_env_var(ENV_LAVA_STREAM, DEFAULT_LAVA_STREAM)

    target_product = get_env_var(ENV_TARGET_PRODUCT)
    submit_action = {"command": "submit_results_on_host",
                     "parameters": {
                            "server": schema_url,
                            "stream": PRODUCT_MAP[target_product].get(
                              "test_stream", lava_stream)
                      }
                    }

    return submit_action


def gen_config(actions=[], device=None):
    if not isinstance(device, LAVADeviceBase):
        print "Not supported type of device %s" % type(device)
        return None

    # Set the default timeout for all test, also used as the timeout value of
    # the total job when it's value bigger than 24 * 60 * 60
    # if this value is not set, then use the 18000 seconds as the default value
    default_timeout = get_env_var(ENV_DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_VALUE)

    config_json = {"job_name": get_env_var(ENV_BUILD_URL),
                   "image_type": 'android',
                   "timeout": int(default_timeout),
                   "actions": actions
                  }

    # test_device set will win over test_device_type
    # LAVA parameter naming could use more consistency
    if isinstance(device, LAVADeviceType):
        config_json["device_type"] = device.name
    else:
        config_json["target"] = device.name

    config = json.dumps(config_json, indent=4)

    print config
    return config


def submit_job(config=None, plan=None):
    if (not config) or (not plan):
        print "Config or plan is None"
        return

    # get the lava token used for submit job
    lava_token_f = get_env_var(ENV_LAVA_TOKEN_FILE)
    if lava_token_f is None:
        lava_token_f = DEFAULT_LAVA_TOKEN_FILE
    else:
        lava_token_f = '%s/%s' % (DEFAULT_LAVA_DIR, lava_token_f)

    with open(lava_token_f) as fd:
        lava_token = fd.read().strip()

    # get the lava user used for submit job
    lava_user = get_env_var(ENV_LAVA_USER)
    if lava_user is None:
        f = open(DEFAULT_LAVA_USER_FILE)
        lava_user = f.read().strip()
        f.close()

    (schema, lava_server_no_schema) = get_schema_and_url()
    try:
        report_url = ("%(schema)s://%(lava_user)s:%(lava_token)s@"
                      "%(lava_server_no_schema)s") % dict(
                                schema=schema,
                                lava_user=lava_user,
                                lava_token=lava_token,
                                lava_server_no_schema=lava_server_no_schema)
        server = xmlrpclib.ServerProxy(report_url)
        lava_job_id = server.scheduler.submit_job(config)
        lava_server_root = lava_server_no_schema.rstrip("/")
        if lava_server_root.endswith("/RPC2"):
            lava_server_root = lava_server_root[:-len("/RPC2")]
    except xmlrpclib.ProtocolError, e:
        print "Error making a LAVA request:", obfuscate_credentials(str(e))
        return

    print "LAVA Job Id: %s, URL: %s://%s/scheduler/job/%s" % \
    (lava_job_id, schema, lava_server_root, lava_job_id)

    if plan == "LAVA_TEST_PLAN":
        json.dump({
                    'lava_url': "%s://%s" % (schema, lava_server_root),
                    'job_id': lava_job_id,
                  }, open('out/lava-job-info', 'w'))
    else:
        if isinstance(lava_job_id, int):
            append_id = lava_job_id
        else:
            append_id = lava_job_id[0]
        json.dump({
                     'lava_url': "%s://%s" % (schema, lava_server_root),
                     'job_id': lava_job_id,
                  }, open('out/lava-job-info-' + str(append_id), 'w'))

def replace(fp, pattern, subst):
    print pattern
    print subst
    for line in fileinput.input(fp, inplace=1):
        if pattern in line:
            line = line.replace(pattern, subst)
        sys.stdout.write(line)
    fileinput.close()

def submit_job_from_url():
    """This routine updates a predefined job with the parameters specific
    to this particular build"""
    job_list = get_job_list()
    for job in job_list:
        lava_job_url = get_env_var(job)
        if lava_job_url is None:
            print "Error: No LAVA_JOB_URL provided"
            return
        urllib.urlretrieve(lava_job_url,"job.json")
        # Job name, defined by android-build, e.g. linaro-android_leb-panda
        job_name = os.environ.get("JOB_NAME")
        frontend_job_name = "~" + job_name.replace("_", "/", 1)

        # Build number, defined by android-build, e.g. 61
        build_number = os.environ.get("BUILD_NUMBER")

        # download base URL, this may differ from job URL if we don't host
        # downloads in Jenkins any more
        download_url = "%s/%s/%s/" % (DEFAULT_DOWNLOAD_BASE_URL,
                                      frontend_job_name,
                                      build_number)
        # Set the file extension based on the type of artifacts
        artifact_type = os.environ.get("MAKE_TARGETS", "tarball")
        if artifact_type == "droidcore":
            file_extension = "img"
        else:
            file_extension = "tar.bz2"

        boot_subst = "%s%s%s" % (download_url, "/boot.", file_extension)
        system_subst = "%s%s%s" % (download_url, "/system.", file_extension)
        userdata_subst = "%s%s%s" % (download_url, "/userdata.", file_extension)

        replace("job.json", "%%ANDROID_BOOT%%", boot_subst)
        replace("job.json", "%%ANDROID_SYSTEM%%", system_subst)
        replace("job.json", "%%ANDROID_DATA%%", userdata_subst)
        replace("job.json", "%%ANDROID_META_NAME%%", job_name)
        replace("job.json", "%%JOB_NAME%%", job_name)
        replace("job.json", "%%ANDROID_META_BUILD%%",  build_number)
        replace("job.json", "%%ANDROID_META_URL%%", get_env_var(ENV_BUILD_URL))
        replace("job.json", "%%BUNDLE_STREAM%%", get_env_var(ENV_LAVA_STREAM, DEFAULT_LAVA_STREAM))
        replace("job.json", "%%WA2_JOB_NAME%%", build_number)

        devices = get_lava_device_type_or_target()

        for device in devices:
            replace("job.json", "%%DUT_TYPE%%",  device.name)
            with open("job.json", 'r') as fin:
                print fin.read()
            with open("job.json") as fd:
                config = fd.read().strip()
            submit_job(config=config, plan=lava_job_url)

def main():
    """Script entry point: return some JSON based on calling args.
    We should be called from Jenkins and expect the following to
    be defined: $TARGET_PRODUCT $JOB_NAME $BUILD_NUMBER $BUILD_URL"""

    check_target_product()

    """Check for request to generate JSON from previous jsons"""
    if get_env_var('SUBMIT_JOB_FROM_URL') == 'true':
        submit_job_from_url()

    """Don't submit LAVA_TEST_PLAN when not intended"""
    if get_env_var('SUBMIT_JOB_FROM_TEST_PLAN') != 'false':
        common_actions = [gen_deploy_action()]

        install_binaries_action = gen_install_binaries_action()
        if install_binaries_action:
            common_actions.append(install_binaries_action)

        common_actions.append(gen_boot_action())

        plan_list = get_plan_list()
        # Create a copy of common actions
        for plan in plan_list:
            actions = copy.deepcopy(common_actions)
            if plan == "LAVA_TEST_PLAN":
                actions.extend(gen_test_actions())
            else:
                actions.extend(gen_test_plan_actions(get_env_var(plan)))
            actions.append(gen_submit_action())

            devices = get_lava_device_type_or_target()
            for dev in devices:
                config = gen_config(actions=actions, device=dev)
                submit_job(config=config, plan=plan)


if __name__ == "__main__":
        main()