[Notes] [Git][BuildGrid/buildgrid][mablanch/71-buildstream-support] 3 commits: utils.py: Add a simple file writer helper



Title: GitLab

Martin Blanchard pushed to branch mablanch/71-buildstream-support at BuildGrid / buildgrid

Commits:

2 changed files:

Changes:

  • buildgrid/_app/bots/buildbox.py
    ... ... @@ -16,82 +16,100 @@
    16 16
     import os
    
    17 17
     import subprocess
    
    18 18
     import tempfile
    
    19
    +import uuid
    
    19 20
     
    
    20 21
     from google.protobuf import any_pb2
    
    21 22
     
    
    22 23
     from buildgrid._protos.build.bazel.remote.execution.v2 import remote_execution_pb2
    
    23
    -from buildgrid._protos.google.bytestream import bytestream_pb2_grpc
    
    24
    -from buildgrid.utils import parse_to_pb2_from_fetch
    
    24
    +from buildgrid._protos.google.bytestream import bytestream_pb2, bytestream_pb2_grpc
    
    25
    +from buildgrid.utils import create_digest, parse_to_pb2_from_fetch
    
    26
    +from buildgrid.utils import read_file, write_file
    
    25 27
     
    
    26 28
     
    
    27 29
     def work_buildbox(context, lease):
    
    30
    +    """Executes a lease for a build action, using buildbox.
    
    31
    +    """
    
    32
    +
    
    33
    +    stub_bytestream = bytestream_pb2_grpc.ByteStreamStub(context.cas_channel)
    
    34
    +    local_cas_directory = context.local_cas
    
    28 35
         logger = context.logger
    
    29 36
     
    
    30
    -    action_digest_any = lease.payload
    
    31 37
         action_digest = remote_execution_pb2.Digest()
    
    32
    -    action_digest_any.Unpack(action_digest)
    
    38
    +    lease.payload.Unpack(action_digest)
    
    39
    +
    
    40
    +    action = parse_to_pb2_from_fetch(remote_execution_pb2.Action(),
    
    41
    +                                     stub_bytestream, action_digest)
    
    33 42
     
    
    34
    -    stub = bytestream_pb2_grpc.ByteStreamStub(context.cas_channel)
    
    43
    +    command = parse_to_pb2_from_fetch(remote_execution_pb2.Command(),
    
    44
    +                                      stub_bytestream, action.command_digest)
    
    35 45
     
    
    36
    -    action = remote_execution_pb2.Action()
    
    37
    -    parse_to_pb2_from_fetch(action, stub, action_digest)
    
    46
    +    environment = dict()
    
    47
    +    for variable in command.environment_variables:
    
    48
    +        if variable.name not in ['PWD']:
    
    49
    +            environment[variable.name] = variable.value
    
    38 50
     
    
    39
    -    casdir = context.local_cas
    
    40
    -    remote_command = remote_execution_pb2.Command()
    
    41
    -    parse_to_pb2_from_fetch(remote_command, stub, action.command_digest)
    
    51
    +    if command.working_directory:
    
    52
    +        working_directory = command.working_directory
    
    53
    +    else:
    
    54
    +        working_directory = '/'
    
    42 55
     
    
    43
    -    environment = dict((x.name, x.value) for x in remote_command.environment_variables)
    
    44 56
         logger.debug("command hash: {}".format(action.command_digest.hash))
    
    45 57
         logger.debug("vdir hash: {}".format(action.input_root_digest.hash))
    
    46
    -    logger.debug("\n{}".format(' '.join(remote_command.arguments)))
    
    47
    -
    
    48
    -    # Input hash must be written to disk for buildbox.
    
    49
    -    os.makedirs(os.path.join(casdir, 'tmp'), exist_ok=True)
    
    50
    -    with tempfile.NamedTemporaryFile(dir=os.path.join(casdir, 'tmp')) as input_digest_file:
    
    51
    -        with open(input_digest_file.name, 'wb') as f:
    
    52
    -            f.write(action.input_root_digest.SerializeToString())
    
    53
    -            f.flush()
    
    54
    -
    
    55
    -        with tempfile.NamedTemporaryFile(dir=os.path.join(casdir, 'tmp')) as output_digest_file:
    
    56
    -            command = ['buildbox',
    
    57
    -                       '--remote={}'.format(context.remote_cas_url),
    
    58
    -                       '--input-digest={}'.format(input_digest_file.name),
    
    59
    -                       '--output-digest={}'.format(output_digest_file.name),
    
    60
    -                       '--local={}'.format(casdir)]
    
    58
    +    logger.debug("\n{}".format(' '.join(command.arguments)))
    
    59
    +
    
    60
    +    os.makedirs(os.path.join(local_cas_directory, 'tmp'), exist_ok=True)
    
    61
    +    os.makedirs(context.fuse_dir, exist_ok=True)
    
    62
    +
    
    63
    +    with tempfile.NamedTemporaryFile(dir=os.path.join(local_cas_directory, 'tmp')) as input_digest_file:
    
    64
    +        # Input hash must be written to disk for BuildBox
    
    65
    +        write_file(input_digest_file.name, action.input_root_digest.SerializeToString())
    
    66
    +
    
    67
    +        with tempfile.NamedTemporaryFile(dir=os.path.join(local_cas_directory, 'tmp')) as output_digest_file:
    
    68
    +            command_line = ['buildbox',
    
    69
    +                            '--remote={}'.format(context.remote_cas_url),
    
    70
    +                            '--input-digest={}'.format(input_digest_file.name),
    
    71
    +                            '--output-digest={}'.format(output_digest_file.name),
    
    72
    +                            '--chdir={}'.format(working_directory),
    
    73
    +                            '--local={}'.format(local_cas_directory)]
    
    61 74
     
    
    62 75
                 if context.cas_client_key:
    
    63
    -                command.append('--client-key={}'.format(context.cas_client_key))
    
    76
    +                command_line.append('--client-key={}'.format(context.cas_client_key))
    
    64 77
                 if context.cas_client_cert:
    
    65
    -                command.append('--client-cert={}'.format(context.cas_client_cert))
    
    78
    +                command_line.append('--client-cert={}'.format(context.cas_client_cert))
    
    66 79
                 if context.cas_server_cert:
    
    67
    -                command.append('--server-cert={}'.format(context.cas_server_cert))
    
    80
    +                command_line.append('--server-cert={}'.format(context.cas_server_cert))
    
    68 81
     
    
    69
    -            if 'PWD' in environment and environment['PWD']:
    
    70
    -                command.append('--chdir={}'.format(environment['PWD']))
    
    82
    +            command_line.append(context.fuse_dir)
    
    83
    +            command_line.extend(command.arguments)
    
    71 84
     
    
    72
    -            command.append(context.fuse_dir)
    
    73
    -            command.extend(remote_command.arguments)
    
    74
    -
    
    75
    -            logger.debug(' '.join(command))
    
    85
    +            logger.debug(' '.join(command_line))
    
    76 86
                 logger.debug("Input root digest:\n{}".format(action.input_root_digest))
    
    77 87
                 logger.info("Launching process")
    
    78 88
     
    
    79
    -            proc = subprocess.Popen(command,
    
    80
    -                                    stdin=subprocess.PIPE,
    
    81
    -                                    stdout=subprocess.PIPE)
    
    82
    -            proc.communicate()
    
    89
    +            command_line = subprocess.Popen(command_line,
    
    90
    +                                            stdin=subprocess.PIPE,
    
    91
    +                                            stdout=subprocess.PIPE)
    
    92
    +            # TODO: Should return the stdout and stderr to the user.
    
    93
    +            command_line.communicate()
    
    94
    +
    
    95
    +            output_digest = remote_execution_pb2.Digest()
    
    96
    +            output_digest.ParseFromString(read_file(output_digest_file.name))
    
    83 97
     
    
    84
    -            output_root_digest = remote_execution_pb2.Digest()
    
    85
    -            with open(output_digest_file.name, 'rb') as f:
    
    86
    -                output_root_digest.ParseFromString(f.read())
    
    87
    -            logger.debug("Output root digest: {}".format(output_root_digest))
    
    98
    +            logger.debug("Output root digest: {}".format(output_digest))
    
    88 99
     
    
    89
    -            if len(output_root_digest.hash) < 64:
    
    100
    +            if len(output_digest.hash) < 64:
    
    90 101
                     logger.warning("Buildbox command failed - no output root digest present.")
    
    91
    -            output_file = remote_execution_pb2.OutputDirectory(tree_digest=output_root_digest)
    
    102
    +
    
    103
    +            # TODO: Have BuildBox helping us creating the Tree instance here
    
    104
    +            # See https://gitlab.com/BuildStream/buildbox/issues/7 for details
    
    105
    +            output_tree_digest = _cas_tree_maker(stub_bytestream, output_digest)
    
    106
    +
    
    107
    +            output_directory = remote_execution_pb2.OutputDirectory()
    
    108
    +            output_directory.tree_digest.CopyFrom(output_tree_digest)
    
    109
    +            output_directory.path = os.path.relpath(working_directory, start='/')
    
    92 110
     
    
    93 111
         action_result = remote_execution_pb2.ActionResult()
    
    94
    -    action_result.output_directories.extend([output_file])
    
    112
    +    action_result.output_directories.extend([output_directory])
    
    95 113
     
    
    96 114
         action_result_any = any_pb2.Any()
    
    97 115
         action_result_any.Pack(action_result)
    
    ... ... @@ -99,3 +117,40 @@ def work_buildbox(context, lease):
    99 117
         lease.result.CopyFrom(action_result_any)
    
    100 118
     
    
    101 119
         return lease
    
    120
    +
    
    121
    +
    
    122
    +def _cas_tree_maker(stub_bytestream, directory_digest):
    
    123
    +    # Generates and stores a Tree for a given Directory
    
    124
    +    output_tree = remote_execution_pb2.Tree()
    
    125
    +
    
    126
    +    def list_directories(parent_directory):
    
    127
    +        directory_list = list()
    
    128
    +        for directory_node in parent_directory.directories:
    
    129
    +            directory = parse_to_pb2_from_fetch(remote_execution_pb2.Directory(),
    
    130
    +                                                stub_bytestream, directory_node.digest)
    
    131
    +            directory_list.extend(list_directories(directory))
    
    132
    +            directory_list.append(directory)
    
    133
    +
    
    134
    +        return directory_list
    
    135
    +
    
    136
    +    root_directory = parse_to_pb2_from_fetch(remote_execution_pb2.Directory(),
    
    137
    +                                             stub_bytestream, directory_digest)
    
    138
    +    output_tree.children.extend(list_directories(root_directory))
    
    139
    +    output_tree.root.CopyFrom(root_directory)
    
    140
    +
    
    141
    +    output_tree_blob = output_tree.SerializeToString()
    
    142
    +    output_tree_digest = create_digest(output_tree_blob)
    
    143
    +
    
    144
    +    # XXX: BuildBox does not support instance name for now...
    
    145
    +    resource_name = '/'.join(['uploads', str(uuid.uuid4()),
    
    146
    +                              'blobs', output_tree_digest.hash, str(output_tree_digest.size_bytes)])
    
    147
    +
    
    148
    +    write_request = bytestream_pb2.WriteRequest(resource_name=resource_name)
    
    149
    +    write_request.data = output_tree_blob
    
    150
    +    write_request.finish_write = True
    
    151
    +
    
    152
    +    write_response = stub_bytestream.Write(iter([write_request]))
    
    153
    +
    
    154
    +    assert write_response.committed_size == len(output_tree_blob)
    
    155
    +
    
    156
    +    return output_tree_digest

  • buildgrid/utils.py
    ... ... @@ -243,6 +243,21 @@ def read_file(file_path):
    243 243
             return byte_file.read()
    
    244 244
     
    
    245 245
     
    
    246
    +def write_file(file_path, content):
    
    247
    +    """Dumps raw memory content to a file.
    
    248
    +
    
    249
    +    Args:
    
    250
    +        file_path (str): path to the target file.
    
    251
    +        content (bytes): raw file's content.
    
    252
    +
    
    253
    +    Raises:
    
    254
    +        OSError: If `file_path` does not exist or is not writable.
    
    255
    +    """
    
    256
    +    with open(file_path, 'wb') as byte_file:
    
    257
    +        byte_file.write(content)
    
    258
    +        byte_file.flush()
    
    259
    +
    
    260
    +
    
    246 261
     def output_file_maker(file_path, input_path):
    
    247 262
         """Creates an :obj:`OutputFile` from a local file.
    
    248 263
     
    



  • [Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]