DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (a41a482b7876)

VCS Links

Line Code
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
import argparse
import json
import logging
import site
import taskcluster
import yaml
import copy
from urllib import unquote
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

from os import path

site.addsitedir(path.join(path.dirname(__file__), "../../lib/python"))

from kickoff.actions import generate_action_task, submit_action_task, find_decision_task_id

log = logging.getLogger(__name__)


# data structure:
# {action_name: tuple of possible cases}
# A case is a tuple of required actions tasks
REQUIRED_GRAPHS_PER_SUPPORTED_ACTION = {
    'promote_firefox_partners': (
        ('promote_firefox_rc',),
        ('promote_firefox',),
    ),
    'publish_fennec': (
        ('promote_fennec',),
    ),
    'push_devedition': (
        ('promote_devedition',),
    ),
    'push_firefox': (
        ('ship_firefox_rc', 'promote_firefox_rc',),
        ('promote_firefox',),
    ),
    'ship_devedition': (
        ('push_devedition', 'promote_devedition',),
    ),
    'ship_fennec_rc': (
        ('promote_fennec',),
    ),
    'ship_fennec': (
        ('ship_fennec_rc', 'promote_fennec',),   # There is no promote_fennec_rc
        ('promote_fennec',),
    ),
    'ship_firefox': (
        ('push_firefox', 'ship_firefox_rc', 'promote_firefox_rc',),
        ('push_firefox', 'promote_firefox',),
    ),
    'ship_firefox_rc': (
        ('promote_firefox_rc',),
    ),
    'push_thunderbird': (
        ('promote_thunderbird',),
    ),
    'ship_thunderbird': (
        ('push_thunderbird', 'promote_thunderbird',),
    ),
}


def get_trust_domain(releases_config, product):
    for entry in releases_config:
        if entry['product'] == product:
            return entry['trust_domain']
    raise RuntimeError("Unknown product %s", product)


def get_repo_param_prefix(releases_config, product):
    for entry in releases_config:
        if entry['product'] == product:
            return entry.get('repo_param_prefix', '')
    raise RuntimeError("Unknown product %s", product)


def get_task(task_id):
    queue = taskcluster.Queue()
    return queue.task(task_id)


# https://www.peterbe.com/plog/best-practice-with-retries-with-requests
def requests_retry_session(
    retries=5,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session


def get_artifact_text(queue, task_id, path):
    """Retries download + returns the contents of the artifact"""
    url = unquote(queue.buildUrl('getLatestArtifact', task_id, path))
    r = requests_retry_session().get(url, timeout=60)
    r.raise_for_status()
    return r.text


def get_release_flavors_of_previous_graphs(action_task_id, previous_graph_ids):
    all_previous_graphs = [action_task_id] + previous_graph_ids

    log.info('Fetching task definitions of: {}'.format(all_previous_graphs))
    all_tasks_definitions_per_task_id = {task_id: get_task(task_id) for task_id in all_previous_graphs}
    all_flavors_per_task_id = {
        task_id: task_def.get('extra', {}).get('action', {}).get('context', {}).get('input', {})\
        .get('release_promotion_flavor', None)
        for task_id, task_def in all_tasks_definitions_per_task_id.items()
    }
    return {
        task_id: flavor
        for task_id, flavor in all_flavors_per_task_id.items()
        if flavor is not None
    }


def check_required_previous_graphs_are_present(action_flavor, flavors_per_task_id):
    required_flavors_cases = REQUIRED_GRAPHS_PER_SUPPORTED_ACTION[action_flavor]
    for required_flavors in required_flavors_cases:
        if all(flavor in flavors_per_task_id.values() for flavor in required_flavors):
            log.info('Found all expected previous graphs for action "{}": "{}"'.format(action_flavor, required_flavors))
            return

    raise Exception('Previous graphs could not match any of the expected ones. Expected: {}. Given: {}'
        .format(required_flavors_cases, flavors_per_task_id)
    )



def main():
    logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s",
                        level=logging.INFO)
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action-task-id", required=True,
        help="Task ID of the initial action task (promote_fennec or promote_firefox"
    )
    parser.add_argument(
        "--decision-task-id",
        help="(Optional) Specify the decision task of the revision to use. "
        "Normally we would use the revision from the action_task_id, but "
        "we may want to specify a separate revision for this action, e.g. when "
        "we land a fix for the push or ship phases but don't want to re-promote."
    )
    parser.add_argument("--previous-graph-ids",
                        help="Override previous graphs.")
    parser.add_argument("--release-runner-config", required=True, type=argparse.FileType('r'),
                        help="Release runner config")
    parser.add_argument("--action-flavor", required=True, choices=REQUIRED_GRAPHS_PER_SUPPORTED_ACTION.keys())
    parser.add_argument("--partner-build-num", type=int, default=1,
                        help="Specify the partner build number")
    parser.add_argument("--partner-subset", type=str,
                        help="Specify a comma-delimited subset of partners to repack")
    parser.add_argument("--force", action="store_true", default=False,
                        help="Submit action task without asking")
    args = parser.parse_args()
    release_runner_config = yaml.safe_load(args.release_runner_config)
    tc_config = {
        "credentials": {
            "clientId": release_runner_config["taskcluster"].get("client_id"),
            "accessToken": release_runner_config["taskcluster"].get("access_token"),
        },
        "maxRetries": 12,
    }
    queue = taskcluster.Queue(tc_config)

    prev_action_task = get_task(args.action_task_id)
    action_task_input = copy.deepcopy(prev_action_task["extra"]["action"]["context"]["input"])

    decision_task_id = args.decision_task_id
    if decision_task_id:
        params_yaml = get_artifact_text(queue, decision_task_id, 'public/parameters.yml')
    else:
        params_yaml = get_artifact_text(queue, args.action_task_id, 'public/parameters.yml')

    product = args.action_flavor.split('_')[1]
    repo_param_prefix = get_repo_param_prefix(release_runner_config['releases'], product)

    parameters = yaml.safe_load(params_yaml)
    project = parameters["project"]
    revision = parameters['{}head_rev'.format(repo_param_prefix)]

    if not decision_task_id:
        trust_domain = get_trust_domain(release_runner_config['releases'], product)
        decision_task_id = find_decision_task_id(
            trust_domain=trust_domain,
            project=project, revision=revision,
        )

    previous_graph_ids = []
    if args.previous_graph_ids:
        previous_graph_ids.extend(args.previous_graph_ids.split(','))
    if decision_task_id not in previous_graph_ids:
        previous_graph_ids.insert(0, decision_task_id)

    flavors_per_task_id = get_release_flavors_of_previous_graphs(args.action_task_id, previous_graph_ids)
    check_required_previous_graphs_are_present(args.action_flavor, flavors_per_task_id)

    action_task_input.update({
        "release_promotion_flavor": args.action_flavor,
        "previous_graph_ids": previous_graph_ids + [args.action_task_id],
    })
    if 'partner' in args.action_flavor:
        action_task_input.update({
            "release_partner_build_number": args.partner_build_num,
        })
        if args.partner_subset:
            action_task_input['release_partners'] = args.partner_subset.split(',')
    action_task_id, action_task = generate_action_task(
            decision_task_id=decision_task_id,
            action_task_input=action_task_input,
    )

    log.info("Submitting action task %s for %s", action_task_id, args.action_flavor)
    log.info("Project: %s", project)
    log.info("Revision: %s", revision)
    log.info("Next version: %s", action_task_input["next_version"])
    log.info("Build number: %s", action_task_input["build_number"])
    log.info("Task definition:\n%s", json.dumps(action_task, sort_keys=True, indent=2))
    if not args.force:
        yes_no = raw_input("Submit the task? [y/N]: ")
        if yes_no not in ('y', 'Y'):
            log.info("Not submitting")
            exit(1)

    submit_action_task(queue=queue, action_task_id=action_task_id,
                       action_task=action_task)


if __name__ == "__main__":
    main()