Reconnect in grpc

Hi I was trying k6 with grpc .So How I can reconnect for grpc. Like if it got disconnect in between how to reconnect it within the k6 test script.

Hmm I guess one way to do it now would be to catch connection errors and reconnect when they occur. But the k6 gRPC API is pretty bare-bones right now, so it could probably use some improvements here. Can you please add a new feature request issue in GitHub with your use case and suggestion how we can improve it?

But how i can catch it… for this
if (__ITER == 0) {
client.connect(‘localhost:9000’,{
plaintext: true},{ timeout: 60});
}

So it it get disconnect den how to reconnect this.

My mistake, only client.connect() will throw an exception if it doesn’t connect, client.invoke() will just return a response with status equal to 4 (i.e. grpc.StatusDeadlineExceeded, see the gRPC constants in the docs). You can use console.log(JSON.stringify(response)) to see all of the details. Here’s a code example of how you could then reconnect:

import grpc from 'k6/net/grpc';
import { sleep } from 'k6';

export const options = {
    iterations: 10,
};

let client = new grpc.Client();
// Download addsvc.proto for https://grpcb.in/, located at:
// https://raw.githubusercontent.com/moul/pb/master/addsvc/addsvc.proto
// and put it in the same folder as this script.
client.load(null, './addsvc.proto');

let connected = false;

export default function () {
    if (!connected) {
        console.log(`Connecting in iteration ${__ITER}...`);
        client.connect('grpcb.in:9001', { timeout: '5s' });
        connected = true;
    }

    let response = client.invoke('addsvc.Add/Sum', {
        a: 1,
        b: 2
    }, { timeout: '5s' });

    //console.log(JSON.stringify(response));

    if (response.status == grpc.StatusDeadlineExceeded) {
        console.log(`${__ITER} timed out, disconnecting...`);
        connected = false;
        client.close(); // not really needed, I think, but just in case
        //TODO: emit some error metric?
        return;
    }

    console.log(`${__ITER} result: ${response.message.v}`);

    sleep(3);
}

That said, gRPC tries to keep a connection alive and reconnect at all costs, so the re-connection logic might be superfluous. If you start this test with internet (so it connects successfully in the first iterations), then disconnect from your network for a few iterations, then turn on your net again, the remaining iterations will finish successfully. And that will happen even without the re-connection logic in the test script… In any case, I added Improve gRPC connection state management · Issue #1808 · grafana/k6 · GitHub to consider the issue some more, feel free to share your specific use case and requirements in there.

1 Like