Example #1
0
def _connect():
    """Initial connect to the worker."""
    worker_assignment = _get_host_worker_assignment()
    if worker_assignment is None:
        raise AssertionError
    if worker_assignment.worker_name is None:
        raise AssertionError
    if worker_assignment.project_name is None:
        raise AssertionError

    root_cert = _get_root_cert(worker_assignment.project_name)
    if not root_cert:
        logs.log_warn("TLS certs not yet generated.")
        time.sleep(WAIT_TLS_CERT_SECONDS)
        sys.exit(0)

    environment.set_value(
        "QUEUE_OVERRIDE",
        untrusted.platform_name(worker_assignment.project_name, "linux"),
    )

    server_name = worker_assignment.worker_name
    if not environment.get_value("LOCAL_DEVELOPMENT"):
        server_name += untrusted.internal_network_domain()

    _host_state.worker_bot_name = worker_assignment.worker_name

    credentials = grpc.ssl_channel_credentials(root_cert)
    _host_state.channel = grpc.secure_channel(
        "%s:%d" % (server_name, config.PORT),
        credentials=credentials,
        options=config.GRPC_OPTIONS,
    )
    _host_state.stub = UntrustedRunnerStub(_host_state.channel)

    logs.log("Connecting to worker %s..." % server_name)
    _host_state.channel.subscribe(_channel_connectivity_changed,
                                  try_to_connect=True)

    channel_state = _check_channel_state(
        config.INITIAL_CONNECT_TIMEOUT_SECONDS)
    if channel_state == ChannelState.INCONSISTENT:
        logs.log_warn("Worker inconsistent on initial connect.")
        monitoring_metrics.HOST_INCONSISTENT_COUNT.increment()
        host_exit_no_return(return_code=0)

    if channel_state != ChannelState.READY:
        raise untrusted.HostException("Failed to connect to worker.")

    environment.set_value("WORKER_BOT_NAME", worker_assignment.worker_name)

    _host_state.heartbeat_thread = threading.Thread(target=_do_heartbeat)
    _host_state.heartbeat_thread.daemon = True
    _host_state.heartbeat_thread.start()
def generate_cert(project_name):
    """Generate a self signed cerficate."""
    # Defer imports to avoid issues on Python 2.
    from OpenSSL import crypto

    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    cert = crypto.X509()
    cert.get_subject().C = 'US'
    cert.get_subject().CN = '*' + untrusted.internal_network_domain()
    cert.get_subject().O = project_name
    cert.set_serial_number(9001)
    cert.set_notBefore(b'20000101000000Z')
    cert.set_notAfter(b'21000101000000Z')
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(key)
    cert.sign(key, 'sha256')

    cert_contents = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    key_contents = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
    return cert_contents, key_contents