All files / src docker.ts

99.06% Statements 318/321
100% Branches 39/39
75% Functions 3/4
99.06% Lines 318/321

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3221x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import Dockerode, { AuthConfig } from "dockerode";
 
export interface BuildResponse {
  stream?: string;
  errorDetail?: { message: string };
  error?: string;
}
 
export interface PushResponse {
  status?: string;
  progressDetail?: { current?: number; total?: number };
  progress?: string;
  id?: string;
  errorDetail?: { message: string };
  error?: string;
  aux?: {
    Tag: string;
    Digest: string;
    Size: number;
  };
}
 
export interface DockerBuildOptions extends Dockerode.ImageBuildOptions {
  /**
   * Extra hosts to add to /etc/hosts
   */
  extrahosts?: string;
  /**
   * A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file’s contents are placed into a file called Dockerfile and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the dockerfile parameter is also specified, there must be a file with the corresponding path inside the tarball.
   */
  remote?: string;
  /**
   * Do not use the cache when building the image.
   * Default: `false`
   */
  nocache?: boolean;
  /**
   * JSON array of images used for build cache resolution.
   */
  cachefrom?: string;
  /**
   * Attempt to pull the image even if an older image exists locally.
   */
  pull?: string;
  /**
   * Remove intermediate containers after a successful build.
   */
  rm?: boolean;
  /**
   * Always remove intermediate containers, even upon failure.
   */
  forcerm?: boolean;
  /**
   * Set memory limit for build.
   */
  memory?: number;
  /**
   * Total memory (memory + swap). Set as `-1` to disable swap.
   */
  memoryswap?: number;
  /**
   * CPU shares (relative weight).
   */
  cpushares?: number;
  /**
   * CPUs in which to allow execution (e.g., `0-3`, `0,1`).
   */
  cpusetcpus?: number;
  /**
   * The length of a CPU period in microseconds.
   */
  cpuperiod?: number;
  /**
   * Microseconds of CPU time that the container can get in a CPU period.
   */
  cpuquota?: number;
  /**
   * JSON map of string pairs for build-time variables. Users pass these values at build-time. Docker uses the buildargs as the environment context for commands run via the Dockerfile RUN instruction, or for variable expansion in other Dockerfile instructions. This is not meant for passing secret values.
   *
   * For example, the build arg FOO=bar would become {"FOO":"bar"} in JSON. This would result in the query parameter buildargs={"FOO":"bar"}. Note that {"FOO":"bar"} should be URI component encoded.
   *
   * Read more about the buildargs instruction.
   * @link {https://docs.docker.com/engine/reference/builder/#arg}
   */
  buildargs?: { [key: string]: string };
  /**
   * Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB.
   */
  shmsize?: number;
  /**
   * Squash the resulting images layers into a single layer. (Experimental release only.)
   */
  squash?: boolean;
  /**
   * Arbitrary key/value labels to set on the image, as a JSON map of string pairs.
   */
  labels?: { [key: string]: string };
  /**
   * Sets the networking mode for the run commands during build. Supported standard values are: `bridge`, `host`, `none`, and `container:<name|id>`. Any other value is taken as a custom network's name to which this container should connect to.
   */
  networkmode?: string;
  /**
   * Platform in the format os[/arch[/variant]]. Default: ""
   */
  platform?: string;
  /**
   * Target build stage. Default: ""
   */
  target?: string;
}
 
export interface BuildOptions {
  /**
   * The context directory where the Docker image is built from.
   */
  directory?: string;
  /**
   * The files to use.
   */
  files?: string[];
  /**
   * Options to pass to the Docker build command.
   */
  buildOptions?: DockerBuildOptions;
  /**
   * Path within the build context to the Dockerfile. This is ignored if remote is specified and points to an external Dockerfile.
   */
  dockerfile?: string;
}
 
export interface PullOptions {
  authconfig?: AuthConfig | undefined;
}
 
export interface PullResponse {
  status?: string;
}
 
export class Docker {
  static instance = new Dockerode();

  /* c8 ignore start */
  /**
   * Build an image from a tar archive with a Dockerfile in it.
   * The Dockerfile specifies how the image is built from the tar archive. It is typically in the archive's root, but can be at a different path or have a different name by specifying the dockerfile parameter. See the Dockerfile reference for more information.
   * The Docker daemon performs a preliminary validation of the Dockerfile before starting the build, and returns an error if the syntax is incorrect. After that, each instruction is run one-by-one until the ID of the new image is output.
   * The build is canceled if the client drops the connection by quitting or being killed.
   * @param {string} tag - The tag to build
   * @param {BuildOptions} [options] - The build options
   * @returns
   */
  /* c8 ignore end */
  static async build(
    tag: string,
    options: BuildOptions = {}
  ): Promise<{
    status: boolean;
    message: string;
  }> {
    if (!tag) {
      throw new Error("Tag is required");
    }
 
    if (!options.directory) {
      options.directory = process.cwd();
    }
    if (!options.dockerfile) {
      options.dockerfile = "Dockerfile";
    }
 
    if (!options.files) {
      options.files = [options.dockerfile];
    } else {
      if (!options.files.includes(options.dockerfile)) {
        options.files.push(options.dockerfile);
      }
    }
 
    if (!options.buildOptions) {
      options.buildOptions = {};
    }
 
    let status = false,
      message = "Could not build image";
 
    try {
      const stream = await Docker.instance.buildImage(
        {
          context: options.directory,
          src: options.files,
        },
        {
          t: tag,
          q: true,
          dockerfile: options.dockerfile,
          ...options.buildOptions,
        }
      );
 
      const buildResponse: BuildResponse[] = await new Promise(
        (resolve, reject) => {
          Docker.instance.modem.followProgress(stream, (err, res) =>
            err ? reject(err) : resolve(res)
          );
        }
      );
 
      if (buildResponse.length) {
        const buildOutput = buildResponse[buildResponse.length - 1];
        status = typeof buildOutput.error === "undefined";
 
        if (status) {
          message = buildOutput.stream;
        } else {
          message = buildOutput.error.trim();
        }
      }
    } catch (e) {
      message = e.message.trim();
    }
    return {
      status,
      message,
    };
  }
 
  /**
   * Create a new image by either pulling it from a registry
   * @param {string} tag - The tag to pull
   * @param {Dockerode.ImagePushOptions} [options] - The pull options
   * @returns
   */
  static async push(tag: string, options: Dockerode.ImagePushOptions = {}) {
    if (!tag) {
      throw new Error("Tag is required");
    }
 
    let status = false,
      message = "Could not build image",
      data = {};
 
    try {
      const image = Docker.instance.getImage(tag);
      const pushResponse: PushResponse[] = await new Promise(
        (resolve, reject) => {
          image.push(options, async (err, s) => {
            if (err) {
              reject(err);
            }
            Docker.instance.modem.followProgress(s as any, (err, res) =>
              err ? reject(err) : resolve(res)
            );
          });
        }
      );
 
      const pushOutput = pushResponse[pushResponse.length - 1];
 
      status = typeof pushOutput.error === "undefined";
 
      if (pushResponse.length) {
        const buildOutput = pushResponse[pushResponse.length - 1];
        status = typeof buildOutput.error === "undefined";
 
        if (status) {
          message = buildOutput.aux.Digest;
          data = buildOutput.aux;
        } else {
          message = buildOutput.error.trim();
        }
      }
    } catch (e) {
      message = e.message;
    }
    return {
      status,
      message,
      data,
    };
  }
 
  static async pull(tag: string, options: PullOptions = {}) {
    if (!tag) {
      throw new Error("Tag is required");
    }
 
    let status = false,
      message = "Could not pull image";
 
    try {
      const pullResponse: PullResponse[] = await new Promise(
        (resolve, reject) => {
          Docker.instance.pull(tag, options, async (err, s) => {
            if (err) {
              reject(err);
            }
            Docker.instance.modem.followProgress(s as any, (err, res) =>
              err ? reject(err) : resolve(res)
            );
          });
        }
      );
 
      if (pullResponse.length) {
        const pullOutput = pullResponse[pullResponse.length - 1];
        status = typeof pullOutput.status !== "undefined";
 
        if (status) {
          message = pullOutput.status;
        }
      }
    } catch (e) {
      message = e.message.trim();
    }
 
    return {
      status,
      message,
    };
  }
}