def main():
  args = parser.parse_args()

  base_json = '{}'
  if args.base:
    with v2_2_image.FromTarball(args.base) as v2_2_img:
      base_json = v2_2_img.config_file()
  data = json.loads(base_json)

  layers = []
  for layer in args.layer:
    layers.append(utils.ExtractValue(layer))

  labels = KeyValueToDict(args.labels)
  for label, value in labels.iteritems():
    if value.startswith('@'):
      with open(value[1:], 'r') as f:
        labels[label] = f.read()

  output = v2_2_metadata.Override(data, v2_2_metadata.Overrides(
      author='Bazel', created_by='bazel build ...',
      layers=layers, entrypoint=args.entrypoint, cmd=args.command,
      user=args.user, labels=labels, env=KeyValueToDict(args.env),
      ports=args.ports, volumes=args.volumes, workdir=args.workdir),
                                  architecture=_PROCESSOR_ARCHITECTURE,
                                  operating_system=_OPERATING_SYSTEM)

  with open(args.output, 'w') as fp:
    json.dump(output, fp, sort_keys=True)
    fp.write('\n')
    def config_file(self):
        """The raw blob string of the config file."""
        if self._config_file is None:
            _PROCESSOR_ARCHITECTURE = 'amd64'
            _OPERATING_SYSTEM = 'linux'

            entrypoint = self._overrides.pop('Entrypoint', [])
            env = self._overrides.pop('Env', {})
            exposed_ports = self._overrides.pop('ExposedPorts', {})

            output = v2_2_metadata.Override(
                json.loads('{}'),
                v2_2_metadata.Overrides(
                    author='Bazel',
                    created_by='bazel build ...',
                    layers=[k for k in self._diff_id_to_u_layer],
                    entrypoint=entrypoint,
                    env=env,
                    ports=exposed_ports),
                architecture=_PROCESSOR_ARCHITECTURE,
                operating_system=_OPERATING_SYSTEM)
            output['rootfs'] = {
                'diff_ids': [k for k in self._diff_id_to_u_layer]
            }
            if len(self._overrides) > 0:
                output.update(self._overrides)
            self._config_file = json.dumps(output, sort_keys=True)
        return self._config_file
def main():
  args = parser.parse_args()

  def Stamp(inp):
    """Perform substitutions in the provided value."""
    if not args.stamp_info_file or not inp:
      return inp
    format_args = {}
    for infofile in args.stamp_info_file:
      with open(infofile) as info:
        for line in info:
          line = line.strip('\n')
          key, value = line.split(' ', 1)
          if key in format_args:
            print ('WARNING: Duplicate value for key "%s": '
                   'using "%s"' % (key, value))
          format_args[key] = value

    return inp.format(**format_args)

  base_json = '{}'
  if args.base:
    with open(args.base, 'r') as r:
      base_json = r.read()
  data = json.loads(base_json)

  layers = []
  for layer in args.layer:
    layers.append(utils.ExtractValue(layer))

  labels = KeyValueToDict(args.labels)
  for label, value in six.iteritems(labels):
    if value.startswith('@'):
      with open(value[1:], 'r') as f:
        labels[label] = f.read()
    elif '{' in value:
      labels[label] = Stamp(value)

  output = v2_2_metadata.Override(data, v2_2_metadata.Overrides(
      author='Bazel', created_by='bazel build ...',
      layers=layers, entrypoint=list(map(Stamp, fix_dashdash(args.entrypoint))),
      cmd=list(map(Stamp, fix_dashdash(args.command))), user=Stamp(args.user),
      labels=labels, env={
        k: Stamp(v)
        for (k, v) in six.iteritems(KeyValueToDict(args.env))
      },
      ports=args.ports, volumes=args.volumes, workdir=Stamp(args.workdir)),
                                  architecture=_PROCESSOR_ARCHITECTURE,
                                  operating_system=_OPERATING_SYSTEM)

  with open(args.output, 'w') as fp:
    json.dump(output, fp, sort_keys=True)
    fp.write('\n')
Exemple #4
0
  def __init__(self,
               base,
               tar_gz,
               diff_id = None,
               overrides = None):
    """Creates a new layer on top of a base with optional tar.gz.

    Args:
      base: a base DockerImage for a new layer.
      tar_gz: an optional gzipped tarball passed as a bytes with filesystem
          changeset.
      diff_id: an optional string containing the digest of the
          uncompressed tar_gz.
      overrides: an optional metadata.Overrides object of properties to override
          on the base image.
    """
    self._base = base
    manifest = json.loads(self._base.manifest())
    config_file = json.loads(self._base.config_file())

    overrides = overrides or metadata.Overrides()
    overrides = overrides.Override(created_by=docker_name.USER_AGENT)

    if tar_gz:
      self._blob = tar_gz
      self._blob_sum = docker_digest.SHA256(self._blob)
      manifest['layers'].append({
          'digest': self._blob_sum,
          'mediaType': docker_http.LAYER_MIME,
          'size': len(self._blob),
      })
      if not diff_id:
        diff_id = docker_digest.SHA256(self.uncompressed_blob(self._blob_sum))

      # Takes naked hex.
      overrides = overrides.Override(layers=[diff_id[len('sha256:'):]])
    else:
      # The empty layer.
      overrides = overrides.Override(layers=[docker_digest.SHA256(b'', '')])

    config_file = metadata.Override(config_file, overrides)

    self._config_file = json.dumps(config_file, sort_keys=True)
    utf8_encoded_config = self._config_file.encode('utf8')
    manifest['config']['digest'] = docker_digest.SHA256(utf8_encoded_config)
    manifest['config']['size'] = len(utf8_encoded_config)
    self._manifest = json.dumps(manifest, sort_keys=True)
def main():
    args = parser.parse_args()

    def Stamp(inp):
        """Perform substitutions in the provided value."""
        if not args.stamp_info_file or not inp:
            return inp
        format_args = {}
        for infofile in args.stamp_info_file:
            with open(infofile) as info:
                for line in info:
                    line = line.strip('\n')
                    key, value = line.split(' ', 1)
                    if key in format_args:
                        print('WARNING: Duplicate value for key "%s": '
                              'using "%s"' % (key, value))
                    format_args[key] = value

        return inp.format(**format_args)

    base_json = '{}'
    if args.base:
        with open(args.base, 'r') as r:
            base_json = r.read()
    data = json.loads(base_json)

    layers = []
    for layer in args.layer:
        layers.append(utils.ExtractValue(layer))

    labels = KeyValueToDict(args.labels)
    for label, value in six.iteritems(labels):
        if value.startswith('@'):
            with open(value[1:], 'r') as f:
                labels[label] = f.read()
        elif '{' in value:
            labels[label] = Stamp(value)

    creation_time = None
    if args.creation_time:
        creation_time = Stamp(args.creation_time)
        try:
            # If creation_time is parsable as a floating point type, assume unix epoch
            # timestamp.
            parsed_unix_timestamp = float(creation_time)
            if parsed_unix_timestamp > 1.0e+11:
                # Bazel < 0.12 was bugged and used milliseconds since unix epoch as
                # the default. Values > 1e11 are assumed to be unix epoch
                # milliseconds.
                parsed_unix_timestamp = parsed_unix_timestamp / 1000.0

            # Construct a RFC 3339 date/time from the Unix epoch.
            creation_time = (datetime.datetime.utcfromtimestamp(
                parsed_unix_timestamp).strftime("%Y-%m-%dT%H:%M:%S.%fZ"))
        except ValueError:
            # Otherwise, assume RFC 3339 date/time format.
            pass

    output = v2_2_metadata.Override(
        data,
        v2_2_metadata.Overrides(
            author='Bazel',
            created_by='bazel build ...',
            layers=layers,
            entrypoint=list(map(Stamp, fix_dashdash(args.entrypoint))),
            cmd=list(map(Stamp, fix_dashdash(args.command))),
            creation_time=creation_time,
            user=Stamp(args.user),
            labels=labels,
            env={
                k: Stamp(v)
                for (k, v) in six.iteritems(KeyValueToDict(args.env))
            },
            ports=args.ports,
            volumes=args.volumes,
            workdir=Stamp(args.workdir)),
        architecture=_PROCESSOR_ARCHITECTURE,
        operating_system=_OPERATING_SYSTEM)

    with open(args.output, 'w') as fp:
        json.dump(output, fp, sort_keys=True)
        fp.write('\n')