summaryrefslogtreecommitdiffstats
path: root/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCService.java
blob: 7c404207737c9c653d0f64f590c7a64c355e1f3c (plain) (blame)
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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.network.rpc;

import com.yahoo.jrt.slobrok.api.IMirror;
import com.yahoo.jrt.slobrok.api.Mirror;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * An RPCService represents a set of remote sessions matching a service pattern. The sessions are monitored using the
 * slobrok. If multiple sessions are available, round robin is used to balance load between them.
 *
 * @author havardpe
 */
public class RPCService {

    private final IMirror mirror;
    private final String pattern;
    private int addressIdx = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
    private int addressGen = 0;
    private List<Mirror.Entry> addressList = null;

    /**
     * Create a new RPCService backed by the given network and using the given service pattern.
     *
     * @param mirror  The naming server to send queries to.
     * @param pattern The pattern to use when querying.
     */
    public RPCService(IMirror mirror, String pattern) {
        this.mirror = mirror;
        this.pattern = pattern;
    }

    /**
     * Resolve a concrete address from this service. This service may represent multiple remote sessions, so this will
     * select one that is online.
     *
     * @return A concrete service address.
     */
    public RPCServiceAddress resolve() {
        if (pattern.startsWith("tcp/")) {
            int pos = pattern.lastIndexOf('/');
            if (pos > 0 && pos < pattern.length() - 1) {
                RPCServiceAddress ret = new RPCServiceAddress(pattern, pattern.substring(0, pos));
                if (!ret.isMalformed()) {
                    return ret;
                }
            }
        } else {
            if (addressGen != mirror.updates()) {
                addressGen = mirror.updates();
                addressList = mirror.lookup(pattern);
            }
            if (addressList != null && !addressList.isEmpty()) {
                addressIdx = ++addressIdx % addressList.size();
                Mirror.Entry entry = addressList.get(addressIdx);
                return new RPCServiceAddress(entry.getName(), entry.getSpec());
            }
        }
        return null;
    }

    /**
     * Returns the pattern used when querying for the naming server for addresses. This is given at construtor time.
     *
     * @return The service pattern.
     */
    String getPattern() {
        return pattern;
    }
}