|
| 1 | +#!/usr/bin/env groovy |
| 2 | + |
| 3 | +/** |
| 4 | + * Copyright (c) 2018 Informatics Matters Ltd. |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * The PipelineTester Container Executor class. The class is responsible for |
| 21 | + * executing a pipeline command in the supplied Docker container image. |
| 22 | + */ |
| 23 | +class ContainerExecutor { |
| 24 | + |
| 25 | + /** |
| 26 | + * Executes the given command in the supplied container image. |
| 27 | + * |
| 28 | + * @param imageName The image to run the command in |
| 29 | + * @param command The command to run |
| 30 | + * @param timeoutSeconds The time to allow for the command to execute |
| 31 | + * @return A list containing the STDOUT and STDERR encapsulated in a |
| 32 | + * StringBuilder(), an integer command exit code and a timeout |
| 33 | + * boolean (set if the program execution timed out) |
| 34 | + */ |
| 35 | + static execute(String command, String imageName, |
| 36 | + String pin, String pout, |
| 37 | + int timeoutSeconds) { |
| 38 | + |
| 39 | + StringBuilder sout = new StringBuilder() |
| 40 | + StringBuilder serr = new StringBuilder() |
| 41 | + |
| 42 | + String cmd = "docker run -v $pin:/data -v $pout:/output" + |
| 43 | + " -w /output -e PIN=/data -e POUT=/output $imageName" + |
| 44 | + " sh -c '$command'" |
| 45 | + |
| 46 | + def proc = ['sh', '-c', cmd].execute(null, new File('.')) |
| 47 | + proc.consumeProcessOutput(sout, serr) |
| 48 | + proc.waitForOrKill((long)timeoutSeconds * 1000) |
| 49 | + int exitValue = proc.exitValue() |
| 50 | + |
| 51 | + // Timeout? |
| 52 | + // |
| 53 | + // Some exit codes have a special meaning. |
| 54 | + // |
| 55 | + // We can, for example, assume that the process was killed |
| 56 | + // if the exit code is 143 as 143, which is 128 + 15, means |
| 57 | + // the program died with signal 15 (SIGTERM). |
| 58 | + // See http://www.tldp.org/LDP/abs/html/exitcodes.html. |
| 59 | + boolean timeout = exitValue == 143 ? true : false |
| 60 | + |
| 61 | + return [sout, serr, exitValue, timeout] |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments