summaryrefslogtreecommitdiffstats
path: root/java/jvpp/gen/jvppgen/jvpp_callback_facade_gen.py
blob: ebc552bfda6637fb5f103123d30c0534724cddad (plain)
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env python2
#
# Copyright (c) 2016,2018 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from string import Template

from jvpp_model import is_control_ping, is_dump, is_request, is_event, is_control_ping_reply


def generate_callback_facade(work_dir, model, logger):
    """ Generates callback facade """
    logger.debug("Generating JVpp callback facade for %s" % model.json_api_files)
    _generate_ifc(work_dir, model),
    _generate_impl(work_dir, model)
    _generate_callback(work_dir, model)


def _generate_ifc(work_dir, model):
    with open("%s/CallbackJVpp%s.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_IFC_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_ifc_methods(model)
        ))

_IFC_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Callback Java API representation of $plugin_package plugin.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public interface CallbackJVpp${plugin_name} extends io.fd.vpp.jvpp.notification.EventRegistryProvider, java.lang.AutoCloseable {

    // TODO add send

$methods
}
""")


def _generate_ifc_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_control_ping(msg):
            # Skip control ping managed by jvpp registry.
            continue
        if not (is_dump(msg) or is_request(msg)):
            # Skip replies and messages that do not not have replies (e.g events/counters).
            continue
        template = _IFC_NO_ARG_METHOD_TEMPLATE
        if msg.has_fields:
            template = _IFC_METHOD_TEMPLATE
        methods.append(template.substitute(
            name=msg.java_name_lower,
            plugin_package=plugin_package,
            request=msg.java_name_upper,
            reply=msg.reply_java
        ))
    return "\n".join(methods)

_IFC_NO_ARG_METHOD_TEMPLATE = Template(
    """    void $name($plugin_package.callback.${reply}Callback callback) throws io.fd.vpp.jvpp.VppInvocationException;""")

_IFC_METHOD_TEMPLATE = Template(
    """    void $name($plugin_package.dto.$request request, $plugin_package.callback.${reply}Callback callback) throws io.fd.vpp.jvpp.VppInvocationException;""")


def _generate_impl(work_dir, model):
    with open("%s/CallbackJVpp%sFacade.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_IMPL_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_impl_methods(model)
        ))

_IMPL_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Default implementation of Callback${plugin_name}JVpp interface.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public final class CallbackJVpp${plugin_name}Facade implements CallbackJVpp${plugin_name} {

    private final $plugin_package.JVpp${plugin_name} jvpp;
    private final java.util.Map<Integer, io.fd.vpp.jvpp.callback.JVppCallback> callbacks;
    private final $plugin_package.notification.${plugin_name}EventRegistryImpl eventRegistry = new $plugin_package.notification.${plugin_name}EventRegistryImpl();
    /**
     * <p>Create CallbackJVpp${plugin_name}Facade object for provided JVpp instance.
     * Constructor internally creates CallbackJVppFacadeCallback class for processing callbacks
     * and then connects to provided JVpp instance
     *
     * @param jvpp provided io.fd.vpp.jvpp.JVpp instance
     *
     * @throws java.io.IOException in case instance cannot connect to JVPP
     */
    public CallbackJVpp${plugin_name}Facade(final io.fd.vpp.jvpp.JVppRegistry registry, final $plugin_package.JVpp${plugin_name} jvpp) throws java.io.IOException {
        this.jvpp = java.util.Objects.requireNonNull(jvpp,"jvpp is null");
        this.callbacks = new java.util.HashMap<>();
        java.util.Objects.requireNonNull(registry, "JVppRegistry should not be null");
        registry.register(jvpp, new CallbackJVpp${plugin_name}FacadeCallback(this.callbacks, eventRegistry));
    }

    @Override
    public $plugin_package.notification.${plugin_name}EventRegistry getEventRegistry() {
        return eventRegistry;
    }

    @Override
    public void close() throws Exception {
        jvpp.close();
    }

    // TODO add send()

$methods
}
""")


def _generate_impl_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_control_ping(msg):
            # Skip control ping managed by jvpp registry.
            continue
        if not (is_dump(msg) or is_request(msg)):
            # Skip replies and messages that do not not have replies (e.g events/counters).
            continue
        template = _IMPL_NO_ARG_METHOD_TEMPLATE
        if msg.has_fields:
            template = _IMPL_METHOD_TEMPLATE
        methods.append(template.substitute(
            name=msg.java_name_lower,
            plugin_package=plugin_package,
            request=msg.java_name_upper,
            reply=msg.reply_java
        ))
    return "\n".join(methods)

_IMPL_NO_ARG_METHOD_TEMPLATE = Template(
    """    public final void $name($plugin_package.callback.${reply}Callback callback) throws io.fd.vpp.jvpp.VppInvocationException {
        synchronized (callbacks) {
            callbacks.put(jvpp.$name(), callback);
        }
    }
""")

_IMPL_METHOD_TEMPLATE = Template("""    public final void $name($plugin_package.dto.$request request, $plugin_package.callback.${reply}Callback callback) throws io.fd.vpp.jvpp.VppInvocationException {
        synchronized (callbacks) {
            callbacks.put(jvpp.$name(request), callback);
        }
    }
""")


def _generate_callback(work_dir, model):
    with open("%s/CallbackJVpp%sFacadeCallback.java" % (work_dir, model.plugin_java_name), "w") as f:
        f.write(_CALLBACK_TEMPLATE.substitute(
            plugin_package=model.plugin_package,
            json_filename=model.json_api_files,
            plugin_name=model.plugin_java_name,
            methods=_generate_callback_methods(model)
        ))

_CALLBACK_TEMPLATE = Template("""
package $plugin_package.callfacade;

/**
 * <p>Implementation of JVppGlobalCallback interface for Java Callback API.
 * <br>It was generated by jvpp_callback_facade_gen.py based on $json_filename.
 */
public final class CallbackJVpp${plugin_name}FacadeCallback implements $plugin_package.callback.JVpp${plugin_name}GlobalCallback {

    private final java.util.Map<Integer, io.fd.vpp.jvpp.callback.JVppCallback> requests;
    private final $plugin_package.notification.Global${plugin_name}EventCallback eventCallback;
    private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(CallbackJVpp${plugin_name}FacadeCallback.class.getName());

    public CallbackJVpp${plugin_name}FacadeCallback(final java.util.Map<Integer, io.fd.vpp.jvpp.callback.JVppCallback> requestMap,
                                      final $plugin_package.notification.Global${plugin_name}EventCallback eventCallback) {
        this.requests = requestMap;
        this.eventCallback = eventCallback;
    }

    @Override
    public void onError(io.fd.vpp.jvpp.VppCallbackException reply) {

        io.fd.vpp.jvpp.callback.JVppCallback failedCall;
        synchronized(requests) {
            failedCall = requests.remove(reply.getCtxId());
        }

        if(failedCall != null) {
            try {
                failedCall.onError(reply);
            } catch(RuntimeException ex) {
                ex.addSuppressed(reply);
                LOG.log(java.util.logging.Level.WARNING, java.lang.String.format("Callback: %s failed while handling exception: %s", failedCall, reply), ex);
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onControlPingReply(final io.fd.vpp.jvpp.dto.ControlPingReply reply) {

        io.fd.vpp.jvpp.callback.ControlPingCallback callback;
        final int replyId = reply.context;
        synchronized(requests) {
            callback = (io.fd.vpp.jvpp.callback.ControlPingCallback) requests.remove(replyId);
        }

        if(callback != null) {
            callback.onControlPingReply(reply);
        }
    }

$methods
}
""")


def _generate_callback_methods(model):
    plugin_package = model.plugin_package
    methods = []
    for msg in model.messages:
        if is_dump(msg) or is_request(msg):
            continue
        if is_control_ping_reply(msg):
            # Skip control ping managed by jvpp registry.
            continue

        # Generate callbacks for all messages except for dumps and requests (handled by vpp, not client).
        template = _CALLBACK_METHOD_TEMPLATE
        if is_event(msg):
            template = _CALLBACK_EVENT_METHOD_TEMPLATE
        msg_name = msg.java_name_upper
        methods.append(template.substitute(
            message=msg_name,
            callback="%sCallback" % msg_name,
            plugin_package=plugin_package
        ))
    return "\n".join(methods)

_CALLBACK_METHOD_TEMPLATE = Template("""
    @Override
    @SuppressWarnings("unchecked")
    public void on${message}(final $plugin_package.dto.${message} reply) {

        $plugin_package.callback.$callback callback;
        final int replyId = reply.context;
        if (LOG.isLoggable(java.util.logging.Level.FINE)) {
            LOG.fine(java.lang.String.format("Received ${message} event message: %s", reply));
        }
        synchronized(requests) {
            callback = ($plugin_package.callback.$callback) requests.remove(replyId);
        }

        if(callback != null) {
            callback.on${message}(reply);
        }
    }
""")

_CALLBACK_EVENT_METHOD_TEMPLATE = Template("""
    @Override
    @SuppressWarnings("unchecked")
    public void on${message}($plugin_package.dto.${message} notification) {
        if (LOG.isLoggable(java.util.logging.Level.FINE)) {
            LOG.fine(java.lang.String.format("Received ${message} event message: %s", notification));
        }
        eventCallback.on${message}(notification);
    }
""")