|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# This is a thin wrapper for AWS Codebuild API to kick off a build, wait for it to finish, |
| 4 | +# and tail build logs while it is running. |
| 5 | + |
| 6 | +import os |
| 7 | +import json |
| 8 | +from typing import Dict, Any, List, Optional, AsyncGenerator |
| 9 | +from datetime import datetime |
| 10 | +import asyncio |
| 11 | +import sys |
| 12 | +import argparse |
| 13 | +import boto3 |
| 14 | + |
| 15 | + |
| 16 | +class LogTailer: |
| 17 | + """ A simple cloudwatch log tailer. """ |
| 18 | + |
| 19 | + _next_token: Optional[str] |
| 20 | + |
| 21 | + def __init__(self, client, log_group: str, log_stream: str): |
| 22 | + self._client = client |
| 23 | + self._next_token = None |
| 24 | + self._log_group = log_group |
| 25 | + self._log_stream = log_stream |
| 26 | + |
| 27 | + def _get_log_events_args(self) -> Dict[str, Any]: |
| 28 | + res = dict( |
| 29 | + logGroupName=self._log_group, |
| 30 | + logStreamName=self._log_stream, |
| 31 | + limit=100, |
| 32 | + startFromHead=True, |
| 33 | + ) |
| 34 | + if self._next_token: |
| 35 | + res["nextToken"] = self._next_token |
| 36 | + return res |
| 37 | + |
| 38 | + async def tail_chunk(self) -> List[Dict[str, str]]: |
| 39 | + max_sleep = 5.0 |
| 40 | + SLEEP_TIME = 0.5 |
| 41 | + |
| 42 | + while max_sleep > 0: |
| 43 | + resp = self._client.get_log_events(**self._get_log_events_args()) |
| 44 | + events = resp["events"] |
| 45 | + self._next_token = resp.get("nextForwardToken") |
| 46 | + if events: |
| 47 | + return events |
| 48 | + else: |
| 49 | + max_sleep -= SLEEP_TIME |
| 50 | + await asyncio.sleep(SLEEP_TIME) |
| 51 | + else: |
| 52 | + return [] |
| 53 | + |
| 54 | + async def read_all_chunks(self) -> AsyncGenerator[List[Dict[str, str]], None]: |
| 55 | + while True: |
| 56 | + resp = self._client.get_log_events(**self._get_log_events_args()) |
| 57 | + events = resp["events"] |
| 58 | + self._next_token = resp.get("nextForwardToken") |
| 59 | + if events: |
| 60 | + yield events |
| 61 | + else: |
| 62 | + return |
| 63 | + |
| 64 | + |
| 65 | +async def _wait_build_state( |
| 66 | + client, build_id, desired_phase: Optional[str], desired_states: List[str] |
| 67 | +) -> Dict[str, Any]: |
| 68 | + """ Wait until the build is in one of the desired states, or in the desired phase. """ |
| 69 | + while True: |
| 70 | + resp = client.batch_get_builds(ids=[build_id]) |
| 71 | + assert len(resp["builds"]) == 1 |
| 72 | + build = resp["builds"][0] |
| 73 | + if build["buildStatus"] in desired_states: |
| 74 | + return build |
| 75 | + for phase in build["phases"]: |
| 76 | + if desired_phase and (phase["phaseType"] == desired_phase): |
| 77 | + return build |
| 78 | + |
| 79 | + await asyncio.sleep(2) |
| 80 | + |
| 81 | + |
| 82 | +def print_log_event(event) -> None: |
| 83 | + print( |
| 84 | + str(datetime.fromtimestamp(event["timestamp"] / 1000.0)), |
| 85 | + event["message"], |
| 86 | + end="", |
| 87 | + ) |
| 88 | + |
| 89 | + |
| 90 | +async def main() -> None: |
| 91 | + parser = argparse.ArgumentParser(description="Process some integers.") |
| 92 | + parser.add_argument( |
| 93 | + "--project-name", default="feast-ci-project", type=str, help="Project name" |
| 94 | + ) |
| 95 | + parser.add_argument( |
| 96 | + "--source-location", |
| 97 | + type=str, |
| 98 | + help="Source location, e.g. https://github.com/feast/feast.git", |
| 99 | + ) |
| 100 | + parser.add_argument( |
| 101 | + "--source-version", type=str, help="Source version, e.g. master" |
| 102 | + ) |
| 103 | + parser.add_argument( |
| 104 | + "--location-from-prow", action='store_true', help="Infer source location and version from prow environment variables" |
| 105 | + ) |
| 106 | + args = parser.parse_args() |
| 107 | + |
| 108 | + if args.location_from_prow: |
| 109 | + job_spec = json.loads(os.getenv('JOB_SPEC', '')) |
| 110 | + source_location = job_spec['refs']['repo_link'] |
| 111 | + source_version = source_version_from_prow_job_spec(job_spec) |
| 112 | + else: |
| 113 | + source_location = args.source_location |
| 114 | + source_version = args.source_version |
| 115 | + |
| 116 | + await run_build( |
| 117 | + project_name=args.project_name, |
| 118 | + source_location=source_location, |
| 119 | + source_version=source_version, |
| 120 | + ) |
| 121 | + |
| 122 | +def source_version_from_prow_job_spec(job_spec: Dict[str, Any]) -> str: |
| 123 | + pull = job_spec['refs']['pulls'][0] |
| 124 | + return f'refs/pull/{pull["number"]}/head^{{{pull["sha"]}}}' |
| 125 | + |
| 126 | +async def run_build(project_name: str, source_version: str, source_location: str): |
| 127 | + print(f"Building {project_name} at {source_version}", file=sys.stderr) |
| 128 | + logs_client = boto3.client("logs", region_name="us-west-2") |
| 129 | + codebuild_client = boto3.client("codebuild", region_name="us-west-2") |
| 130 | + |
| 131 | + print("Submitting the build..", file=sys.stderr) |
| 132 | + build_resp = codebuild_client.start_build( |
| 133 | + projectName=project_name, |
| 134 | + sourceLocationOverride=source_location, |
| 135 | + sourceVersion=source_version, |
| 136 | + ) |
| 137 | + |
| 138 | + build_id = build_resp["build"]["id"] |
| 139 | + |
| 140 | + try: |
| 141 | + print( |
| 142 | + "Waiting for the INSTALL phase to start before tailing the log", |
| 143 | + file=sys.stderr, |
| 144 | + ) |
| 145 | + build = await _wait_build_state( |
| 146 | + codebuild_client, |
| 147 | + build_id, |
| 148 | + desired_phase="INSTALL", |
| 149 | + desired_states=["SUCCEEDED", "FAILED", "STOPPED", "TIMED_OUT", "FAULT"], |
| 150 | + ) |
| 151 | + |
| 152 | + if build["buildStatus"] != "IN_PROGRESS": |
| 153 | + print( |
| 154 | + f"Build failed before install phase: {build['buildStatus']}", |
| 155 | + file=sys.stderr, |
| 156 | + ) |
| 157 | + sys.exit(1) |
| 158 | + |
| 159 | + log_tailer = LogTailer( |
| 160 | + logs_client, |
| 161 | + log_stream=build["logs"]["streamName"], |
| 162 | + log_group=build["logs"]["groupName"], |
| 163 | + ) |
| 164 | + |
| 165 | + waiter_task = asyncio.create_task( |
| 166 | + _wait_build_state( |
| 167 | + codebuild_client, |
| 168 | + build_id, |
| 169 | + desired_phase=None, |
| 170 | + desired_states=["SUCCEEDED", "FAILED", "STOPPED", "TIMED_OUT", "FAULT"], |
| 171 | + ) |
| 172 | + ) |
| 173 | + |
| 174 | + while not waiter_task.done(): |
| 175 | + events = await log_tailer.tail_chunk() |
| 176 | + for event in events: |
| 177 | + print_log_event(event) |
| 178 | + |
| 179 | + build_status = waiter_task.result()["buildStatus"] |
| 180 | + if build_status == "SUCCEEDED": |
| 181 | + print(f"Build {build_status}", file=sys.stderr) |
| 182 | + else: |
| 183 | + print(f"Build {build_status}", file=sys.stderr) |
| 184 | + sys.exit(1) |
| 185 | + except KeyboardInterrupt: |
| 186 | + print(f"Stopping build {build_id}", file=sys.stderr) |
| 187 | + codebuild_client.stop_build(id=build_id) |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + asyncio.run(main()) |
0 commit comments