summaryrefslogtreecommitdiffstats
path: root/netconf/restconf/restconf-nb-bierman02/src/main/java/org/opendaylight/netconf/sal/streams/websockets/WebSocketServer.java
blob: a295c54a3f9351fa37574cd82d7fbb61362d09a8 (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
/*
 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.netconf.sal.streams.websockets;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.opendaylight.netconf.sal.streams.listeners.Notificator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@link WebSocketServer} is the singleton responsible for starting and stopping the
 * web socket server.
 */
public final class WebSocketServer implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);

    private static final String DEFAULT_ADDRESS = "0.0.0.0";

    private static WebSocketServer instance = null;

    private final String address;
    private final int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;


    private WebSocketServer(final String address, final int port) {
        this.address = address;
        this.port = port;
    }

    /**
     * Create singleton instance of {@link WebSocketServer}.
     *
     * @param port TCP port used for this server
     * @return instance of {@link WebSocketServer}
     */
    private static WebSocketServer createInstance(final int port) {
        instance = createInstance(DEFAULT_ADDRESS, port);
        return instance;
    }

    public static WebSocketServer createInstance(final String address, final int port) {
        checkState(instance == null, "createInstance() has already been called");
        checkArgument(port >= 1024, "Privileged port (below 1024) is not allowed");

        instance = new WebSocketServer(requireNonNull(address, "Address cannot be null."), port);
        LOG.info("Created WebSocketServer on {}:{}", address, port);
        return instance;
    }

    /**
     * Get the websocket of TCP port.
     *
     * @return websocket TCP port
     */
    public int getPort() {
        return port;
    }

    /**
     * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}.
     *
     * @return instance of {@link WebSocketServer}
     */
    public static WebSocketServer getInstance() {
        return requireNonNull(instance, "createInstance() must be called prior to getInstance()");
    }

    /**
     * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}.
     * If an instance doesnt exist create one with the provided fallback port.
     *
     * @return instance of {@link WebSocketServer}
     */
    public static WebSocketServer getInstance(final int fallbackPort) {
        if (instance != null) {
            return instance;
        }

        LOG.warn("No instance for WebSocketServer found, creating one with a fallback port: {}", fallbackPort);
        return createInstance(fallbackPort);
    }

    /**
     * Destroy the existing instance.
     */
    public static void destroyInstance() {
        checkState(instance != null, "createInstance() must be called prior to destroyInstance()");

        instance.stop();
        instance = null;
        LOG.info("Destroyed WebSocketServer.");
    }

    @Override
    @SuppressWarnings("checkstyle:IllegalCatch")
    public void run() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketServerInitializer());

            final Channel channel = serverBootstrap.bind(address, port).sync().channel();
            LOG.info("Web socket server started at address {}, port {}.", address, port);

            channel.closeFuture().sync();
        } catch (final InterruptedException e) {
            LOG.error("Web socket server encountered an error during startup attempt on port {}", port, e);
        } catch (Throwable throwable) {
            // sync() re-throws exceptions declared as Throwable, so the compiler doesn't see them
            LOG.error("Error while binding to address {}, port {}", address, port, throwable);
            throw throwable;
        } finally {
            stop();
        }
    }

    /**
     * Stops the web socket server and removes all listeners.
     */
    private void stop() {
        LOG.info("Stopping the web socket server instance on port {}", port);
        Notificator.removeAllListeners();
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
            bossGroup = null;
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
            workerGroup = null;
        }
    }

}