View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.net.server;
18  
19  import java.io.BufferedReader;
20  import java.io.ByteArrayInputStream;
21  import java.io.EOFException;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.InputStreamReader;
25  import java.io.ObjectInputStream;
26  import java.io.OptionalDataException;
27  import java.net.DatagramPacket;
28  import java.net.DatagramSocket;
29  
30  import org.apache.logging.log4j.core.config.ConfigurationFactory;
31  import org.apache.logging.log4j.core.util.Log4jThread;
32  
33  /**
34   * Listens for events over a socket connection.
35   * 
36   * @param <T>
37   *            The kind of input stream read
38   */
39  public class UdpSocketServer<T extends InputStream> extends AbstractSocketServer<T> {
40  
41      private final DatagramSocket datagramSocket;
42  
43      // max size so we only have to deal with one packet
44      private final int maxBufferSize = 1024 * 65 + 1024;
45  
46      /**
47       * Constructor.
48       * 
49       * @param port
50       *            to listen on.
51       * @param logEventInput
52       * @throws IOException
53       *             If an error occurs.
54       */
55      public UdpSocketServer(final int port, final LogEventBridge<T> logEventInput) throws IOException {
56          super(port, logEventInput);
57          this.datagramSocket = new DatagramSocket(port);
58      }
59  
60      /**
61       * Creates a socket server that reads JSON log events.
62       * 
63       * @param port
64       *            the port to listen
65       * @return a new a socket server
66       * @throws IOException
67       *             if an I/O error occurs when opening the socket.
68       */
69      public static UdpSocketServer<InputStream> createJsonSocketServer(final int port) throws IOException {
70          return new UdpSocketServer<>(port, new JsonInputStreamLogEventBridge());
71      }
72  
73      /**
74       * Creates a socket server that reads serialized log events.
75       * 
76       * @param port
77       *            the port to listen
78       * @return a new a socket server
79       * @throws IOException
80       *             if an I/O error occurs when opening the socket.
81       */
82      public static UdpSocketServer<ObjectInputStream> createSerializedSocketServer(final int port) throws IOException {
83          return new UdpSocketServer<>(port, new ObjectInputStreamLogEventBridge());
84      }
85  
86      /**
87       * Creates a socket server that reads XML log events.
88       * 
89       * @param port
90       *            the port to listen
91       * @return a new a socket server
92       * @throws IOException
93       *             if an I/O error occurs when opening the socket.
94       */
95      public static UdpSocketServer<InputStream> createXmlSocketServer(final int port) throws IOException {
96          return new UdpSocketServer<>(port, new XmlInputStreamLogEventBridge());
97      }
98  
99      /**
100      * Main startup for the server.
101      * 
102      * @param args
103      *            The command line arguments.
104      * @throws Exception
105      *             if an error occurs.
106      */
107     public static void main(final String[] args) throws Exception {
108         if (args.length < 1 || args.length > 2) {
109             System.err.println("Incorrect number of arguments");
110             printUsage();
111             return;
112         }
113         final int port = Integer.parseInt(args[0]);
114         if (port <= 0 || port >= MAX_PORT) {
115             System.err.println("Invalid port number");
116             printUsage();
117             return;
118         }
119         if (args.length == 2 && args[1].length() > 0) {
120             ConfigurationFactory.setConfigurationFactory(new ServerConfigurationFactory(args[1]));
121         }
122         final UdpSocketServer<ObjectInputStream> socketServer = UdpSocketServer.createSerializedSocketServer(port);
123         final Thread server = new Log4jThread(socketServer);
124         server.start();
125         final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
126         while (true) {
127             final String line = reader.readLine();
128             if (line == null || line.equalsIgnoreCase("Quit") || line.equalsIgnoreCase("Stop")
129                     || line.equalsIgnoreCase("Exit")) {
130                 socketServer.shutdown();
131                 server.join();
132                 break;
133             }
134         }
135     }
136 
137     private static void printUsage() {
138         System.out.println("Usage: ServerSocket port configFilePath");
139     }
140 
141     /**
142      * Accept incoming events and processes them.
143      */
144     @Override
145     public void run() {
146         while (isActive()) {
147             if (datagramSocket.isClosed()) {
148                 // OK we're done.
149                 return;
150             }
151             try {
152                 final byte[] buf = new byte[maxBufferSize];
153                 final DatagramPacket packet = new DatagramPacket(buf, buf.length);
154                 datagramSocket.receive(packet);
155                 final ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());
156                 logEventInput.logEvents(logEventInput.wrapStream(bais), this);
157             } catch (final OptionalDataException e) {
158                 if (datagramSocket.isClosed()) {
159                     // OK we're done.
160                     return;
161                 }
162                 logger.error("OptionalDataException eof=" + e.eof + " length=" + e.length, e);
163             } catch (final EOFException e) {
164                 if (datagramSocket.isClosed()) {
165                     // OK we're done.
166                     return;
167                 }
168                 logger.info("EOF encountered");
169             } catch (final IOException e) {
170                 if (datagramSocket.isClosed()) {
171                     // OK we're done.
172                     return;
173                 }
174                 logger.error("Exception encountered on accept. Ignoring. Stack Trace :", e);
175             }
176         }
177     }
178 
179     /**
180      * Shutdown the server.
181      */
182     public void shutdown() {
183         this.setActive(false);
184         Thread.currentThread().interrupt();
185         datagramSocket.close();
186     }
187 }