aboutsummaryrefslogtreecommitdiffstats
path: root/configserver/src/main/java/com/yahoo/vespa/serviceview/ServiceModel.java
blob: 1978c2b241a869a9802b6b8fb7fff263f339d2c1 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.serviceview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import com.yahoo.vespa.serviceview.bindings.ApplicationView;
import com.yahoo.vespa.serviceview.bindings.ClusterView;
import com.yahoo.vespa.serviceview.bindings.HostService;
import com.yahoo.vespa.serviceview.bindings.ModelResponse;
import com.yahoo.vespa.serviceview.bindings.ServicePort;
import com.yahoo.vespa.serviceview.bindings.ServiceView;

import edu.umd.cs.findbugs.annotations.NonNull;

/**
 * A transposed view for cloud.config.model.
 *
 * @author <a href="mailto:steinar@yahoo-inc.com">Steinar Knutsen</a>
 */
public final class ServiceModel {
    private static final String CLUSTERCONTROLLER_TYPENAME = "container-clustercontroller";

    private static final String CONTENT_CLUSTER_TYPENAME = "content";

    private final Map<String, Service> servicesMap;

    /**
     * An ordered list of the clusters in this config model.
     */
    @NonNull
    public final ImmutableList<Cluster> clusters;

    ServiceModel(ModelResponse modelConfig) {
        Table<String, String, List<Service>> services = HashBasedTable.create();
        for (HostService h : modelConfig.hosts) {
            String hostName = h.name;
            for (com.yahoo.vespa.serviceview.bindings.Service s : h.services) {
                addService(services, hostName, s);
            }
        }
        List<Cluster> sortingBuffer = new ArrayList<>();
        for (Cell<String, String, List<Service>> c : services.cellSet()) {
            sortingBuffer.add(new Cluster(c.getRowKey(), c.getColumnKey(), c.getValue()));
        }
        Collections.sort(sortingBuffer);
        ImmutableList.Builder<Cluster> clustersBuilder = new ImmutableList.Builder<>();
        clustersBuilder.addAll(sortingBuffer);
        clusters = clustersBuilder.build();
        Map<String, Service> seenIdentifiers = new HashMap<>();
        for (Cluster c : clusters) {
            for (Service s : c.services) {
                List<String> identifiers = s.getIdentifiers();
                for (String identifier : identifiers) {
                    if (seenIdentifiers.containsKey(identifier)) {
                        throw new RuntimeException(
                                "Congrats, you have a publishable result. We have a very unexpected hash collision" + " between "
                                        + seenIdentifiers.get(identifier) + " and " + s + ".");
                    }
                    seenIdentifiers.put(identifier, s);
                }
            }
        }
        ImmutableMap.Builder<String, Service> servicesBuilder = new ImmutableMap.Builder<>();
        servicesBuilder.putAll(seenIdentifiers);
        servicesMap = servicesBuilder.build();
    }

    private static void addService(Table<String, String, List<Service>> services,
            String hostName,
            com.yahoo.vespa.serviceview.bindings.Service s) {
        boolean hasStateApi = false;
        int statePort = 0;
        List<Integer> ports = new ArrayList<>(s.ports.size());
        for (ServicePort port : s.ports) {
            ports.add(port.number);
            if (!hasStateApi && port.hasTags("http", "state")) {
                hasStateApi = true;
                statePort = port.number;
            }
        }
        // ignore hosts without state API
        if (hasStateApi) {
            Service service = new Service(s.type, hostName, statePort, s.clustername, s.clustertype, s.configid, ports, s.name);
            getAndSetEntry(services, s.clustername, s.clustertype).add(service);
        }
    }

    private static List<Service> getAndSetEntry(Table<String, String, List<Service>> services, String clusterName, String clusterType) {
        List<Service> serviceList = services.get(clusterName, clusterType);
        if (serviceList == null) {
            serviceList = new ArrayList<>();
            services.put(clusterName, clusterType, serviceList);
        }
        return serviceList;
    }

    /**
     * The top level view of a given application.
     *
     * @return a top level view of the entire application in a form suitable for
     *         consumption by a REST API
     */
    public ApplicationView showAllClusters(String uriBase, String applicationIdentifier) {
        ApplicationView response = new ApplicationView();
        List<ClusterView> clusterViews = new ArrayList<>();
        for (Cluster c : clusters) {
            clusterViews.add(showCluster(c, uriBase, applicationIdentifier));
        }
        response.clusters = clusterViews;
        return response;
    }

    private ClusterView showCluster(Cluster c, String uriBase, String applicationIdentifier) {
        List<ServiceView> services = new ArrayList<>();
        for (Service s : c.services) {
            ServiceView service = new ServiceView();
            StringBuilder buffer = getLinkBuilder(uriBase).append(applicationIdentifier).append('/');
            service.url = buffer.append("service/").append(s.getIdentifier(s.statePort)).append("/state/v1/").toString();
            service.serviceType = s.serviceType;
            service.serviceName = s.name;
            service.configId = s.configId;
            service.host = s.host;
            addLegacyLink(uriBase, applicationIdentifier, s, service);
            services.add(service);
        }
        ClusterView v = new ClusterView();
        v.services = services;
        v.name = c.name;
        v.type = c.type;
        if (CONTENT_CLUSTER_TYPENAME.equals(c.type)) {
            Service s = getFirstClusterController();
            StringBuilder buffer = getLinkBuilder(uriBase).append(applicationIdentifier).append('/');
            buffer.append("service/").append(s.getIdentifier(s.statePort)).append("/cluster/v2/").append(c.name);
            v.url = buffer.toString();
        } else {
            v.url = null;
        }
        return v;
    }

    private void addLegacyLink(String uriBase, String applicationIdentifier, Service s, ServiceView service) {
        if (s.serviceType.equals("storagenode") || s.serviceType.equals("distributor")) {
            StringBuilder legacyBuffer = getLinkBuilder(uriBase);
            legacyBuffer.append("legacy/").append(applicationIdentifier).append('/');
            legacyBuffer.append("service/").append(s.getIdentifier(s.statePort)).append('/');
            service.legacyStatusPages = legacyBuffer.toString();
        }
    }

    private Service getFirstServiceInstanceByType(@NonNull String typeName) {
        for (Cluster c : clusters) {
            for (Service s : c.services) {
                if (typeName.equals(s.serviceType)) {
                    return s;
                }
            }
        }
        throw new IllegalStateException("This installation has but no service of required type: "
                + typeName + ".");
    }

    private Service getFirstClusterController() {
        // This is used assuming all cluster controllers know of all fleet controllers in an application
        return getFirstServiceInstanceByType(CLUSTERCONTROLLER_TYPENAME);
    }

    private StringBuilder getLinkBuilder(String uriBase) {
        StringBuilder buffer = new StringBuilder(uriBase);
        if (!uriBase.endsWith("/")) {
            buffer.append('/');
        }
        return buffer;
    }

    @Override
    public String toString() {
        final int maxLen = 3;
        StringBuilder builder = new StringBuilder();
        builder.append("ServiceModel [clusters=")
                .append(clusters.subList(0, Math.min(clusters.size(), maxLen))).append("]");
        return builder.toString();
    }


    /**
     * Match an identifier with a service for this cluster.
     *
     * @param identifier
     *            an opaque service identifier generated by the service
     * @return the corresponding Service instance
     */
    public Service getService(String identifier) {
        return servicesMap.get(identifier);
    }

    /**
     * Find a service based on host and port.
     *
     * @param host
     *            the name of the host running the service
     * @param port
     *            a port owned by the service
     * @param self
     *            the service which generated the host data
     * @return a service instance fullfilling the criteria
     * @throws IllegalArgumentException
     *             if no matching service is found
     */
    public Service resolve(String host, int port, Service self) {
        Integer portAsObject = Integer.valueOf(port);
        String realHost;
        if ("localhost".equals(host)) {
            realHost = self.host;
        } else {
            realHost = host;
        }
        for (Cluster c : clusters) {
            for (Service s : c.services) {
                if (s.host.equals(realHost) && s.ports.contains(portAsObject)) {
                    return s;
                }
            }
        }
        throw new IllegalArgumentException("No registered service owns port " + port + " on host " + realHost + ".");
    }

}