summaryrefslogtreecommitdiffstats
path: root/container-disc/src/main/java/com/yahoo/container/usability/BindingsOverviewHandler.java
blob: 8f4435a511adabb7cfcc471f2e899b013d80f83e (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.usability;

import com.google.inject.Inject;
import com.yahoo.component.ComponentId;
import com.yahoo.component.provider.ComponentRegistry;
import com.yahoo.container.Container;
import com.yahoo.container.jdisc.JdiscBindingsConfig;
import com.yahoo.jdisc.handler.AbstractRequestHandler;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.FastContentWriter;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpRequest.Method;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author gjoranv
 * @since 5.18
 */
public class BindingsOverviewHandler extends AbstractRequestHandler {

    private final JdiscBindingsConfig bindingsConfig;

    @Inject
    public BindingsOverviewHandler(JdiscBindingsConfig bindingsConfig) {
        this.bindingsConfig = bindingsConfig;
    }

    @Override
    public ContentChannel handleRequest(com.yahoo.jdisc.Request request, ResponseHandler handler) {
        JSONObject json;
        int statusToReturn;

        if (request instanceof HttpRequest && ((HttpRequest) request).getMethod() != Method.GET) {
            json = errorMessageInJson();
            statusToReturn = com.yahoo.jdisc.Response.Status.METHOD_NOT_ALLOWED;
        } else {
            json = new StatusResponse(bindingsConfig).render();
            statusToReturn = com.yahoo.jdisc.Response.Status.OK;
        }

        FastContentWriter writer = new FastContentWriter(new ResponseDispatch() {
            @Override
            protected com.yahoo.jdisc.Response newResponse() {
                com.yahoo.jdisc.Response response = new com.yahoo.jdisc.Response(statusToReturn);
                response.headers().add("Content-Type", Arrays.asList(new String[]{"application/json"}));
                return response;
            }
        }.connect(handler));

        try {
            writer.write(json.toString());
        } finally {
            writer.close();
        }

        return new IgnoredContent();
    }

    private JSONObject errorMessageInJson() {
        JSONObject error = new JSONObject();
        try {
            error.put("error", "This API, "
                    + this.getClass().getSimpleName()
                    + ", only supports HTTP GET."
                    + " You are probably looking for another API/path.");
        } catch (org.json.JSONException e) {
            // just ignore it
        }
        return error;
    }

    static JSONArray renderRequestHandlers(JdiscBindingsConfig bindingsConfig,
                                           Map<ComponentId, ? extends RequestHandler> handlersById) {
        JSONArray ret = new JSONArray();

        for (Map.Entry<ComponentId, ? extends RequestHandler> handlerEntry : handlersById.entrySet()) {
            String id = handlerEntry.getKey().stringValue();
            RequestHandler handler = handlerEntry.getValue();

            JSONObject handlerJson = renderComponent(handler, handlerEntry.getKey());
            addBindings(bindingsConfig, id, handlerJson);
            ret.put(handlerJson);
        }
        return ret;
    }

    private static void addBindings(JdiscBindingsConfig bindingsConfig, String id, JSONObject handlerJson) {
        List<String> serverBindings = new ArrayList<>();

        JdiscBindingsConfig.Handlers handlerConfig = bindingsConfig.handlers(id);
        if (handlerConfig != null) {
            serverBindings = handlerConfig.serverBindings();
        }
        putJson(handlerJson, "serverBindings", renderBindings(serverBindings));
    }

    private static JSONArray renderBindings(List<String> bindings) {
        JSONArray ret = new JSONArray();

        for (String binding : bindings)
            ret.put(binding);

        return ret;
    }

    private static JSONObject renderComponent(Object component, ComponentId id) {
        JSONObject jc = new JSONObject();
        putJson(jc, "id", id.stringValue());
        addBundleInfo(jc, component);
        return jc;
    }

    private static void addBundleInfo(JSONObject jsonObject, Object component) {
        BundleInfo bundleInfo = bundleInfo(component);
        putJson(jsonObject, "class", bundleInfo.className);
        putJson(jsonObject, "bundle", bundleInfo.bundleName);

    }

    private static BundleInfo bundleInfo(Object component) {
        try {
            Bundle bundle = FrameworkUtil.getBundle(component.getClass());

            String bundleName = bundle != null ?
                    bundle.getSymbolicName() + ":" + bundle.getVersion() :
                    "From classpath";
            return new BundleInfo(component.getClass().getName(), bundleName);
        } catch (Exception | NoClassDefFoundError e) {
            return new BundleInfo("Unavailable, reconfiguration in progress.", "");
        }
    }

    private static void putJson(JSONObject json, String key, Object value) {
        try {
            json.put(key, value);
        } catch (JSONException e) {
            // The original JSONException lacks key-value info.
            throw new RuntimeException("Trying to add invalid JSON object with key '" + key + "' and value '" + value + "' - " + e.getMessage(), e);
        }
    }

    static final class BundleInfo {
        public final String className;
        public final String bundleName;
        BundleInfo(String className, String bundleName) {
            this.className = className;
            this.bundleName = bundleName;
        }
    }

    static final class StatusResponse {

        private final JdiscBindingsConfig bindingsConfig;

        StatusResponse(JdiscBindingsConfig bindingsConfig) {
            this.bindingsConfig = bindingsConfig;
        }

        public JSONObject render() {
            JSONObject root = new JSONObject();

            putJson(root, "handlers",
                    renderRequestHandlers(bindingsConfig, Container.get().getRequestHandlerRegistry().allComponentsById()));

            return root;
        }

    }

    private class IgnoredContent implements ContentChannel {
        @Override
        public void write(ByteBuffer buf, CompletionHandler handler) {
            handler.completed();
        }

        @Override
        public void close(CompletionHandler handler) {
            handler.completed();
        }
    }
}