|
| 1 | +""" |
| 2 | +Go Runtime Validation |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import subprocess |
| 8 | + |
| 9 | +from aws_lambda_builders.exceptions import MisMatchRuntimeError |
| 10 | + |
| 11 | +LOG = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class GoRuntimeValidator(object): |
| 15 | + |
| 16 | + LANGUAGE = "go" |
| 17 | + SUPPORTED_RUNTIMES = { |
| 18 | + "go1.x" |
| 19 | + } |
| 20 | + |
| 21 | + def __init__(self, runtime): |
| 22 | + self.runtime = runtime |
| 23 | + self._valid_runtime_path = None |
| 24 | + |
| 25 | + def has_runtime(self): |
| 26 | + """ |
| 27 | + Checks if the runtime is supported. |
| 28 | + :param string runtime: Runtime to check |
| 29 | + :return bool: True, if the runtime is supported. |
| 30 | + """ |
| 31 | + return self.runtime in self.SUPPORTED_RUNTIMES |
| 32 | + |
| 33 | + def validate(self, runtime_path): |
| 34 | + """ |
| 35 | + Checks if the language supplied matches the required lambda runtime |
| 36 | + :param string runtime_path: runtime to check eg: /usr/bin/go |
| 37 | + :raises MisMatchRuntimeError: Version mismatch of the language vs the required runtime |
| 38 | + """ |
| 39 | + if not self.has_runtime(): |
| 40 | + LOG.warning("'%s' runtime is not " |
| 41 | + "a supported runtime", self.runtime) |
| 42 | + return None |
| 43 | + |
| 44 | + expected_major_version = int(self.runtime.replace(self.LANGUAGE, "").split('.')[0]) |
| 45 | + min_expected_minor_version = 11 if expected_major_version == 1 else 0 |
| 46 | + |
| 47 | + p = subprocess.Popen([runtime_path, "version"], |
| 48 | + cwd=os.getcwd(), |
| 49 | + stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 50 | + out, _ = p.communicate() |
| 51 | + |
| 52 | + if p.returncode == 0: |
| 53 | + out_parts = out.decode().split() |
| 54 | + if len(out_parts) >= 3: |
| 55 | + version_parts = [int(x) for x in out_parts[2].replace(self.LANGUAGE, "").split('.')] |
| 56 | + if len(version_parts) == 3: |
| 57 | + if version_parts[0] == expected_major_version and version_parts[1] >= min_expected_minor_version: |
| 58 | + self._valid_runtime_path = runtime_path |
| 59 | + return self._valid_runtime_path |
| 60 | + |
| 61 | + # otherwise, raise mismatch exception |
| 62 | + raise MisMatchRuntimeError(language=self.LANGUAGE, |
| 63 | + required_runtime=self.runtime, |
| 64 | + runtime_path=runtime_path) |
| 65 | + |
| 66 | + @property |
| 67 | + def validated_runtime_path(self): |
| 68 | + return self._valid_runtime_path |
0 commit comments