blob: d140416b0c7e60453d9469826c097fcd8fb014ac [file] [log] [blame]
Dimitrios Mavrommatisf0c06322017-10-31 23:49:04 -07001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.artemis.impl.moas;
18
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.google.common.annotations.Beta;
21import io.netty.buffer.ByteBuf;
22import io.netty.channel.ChannelHandler.Sharable;
23import io.netty.channel.ChannelHandlerContext;
24import io.netty.channel.ChannelInboundHandlerAdapter;
25import org.apache.commons.lang.exception.ExceptionUtils;
26import org.onlab.packet.IpAddress;
27import org.onosproject.artemis.impl.objects.ArtemisMessage;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import java.io.IOException;
32import java.net.InetSocketAddress;
33import java.net.SocketAddress;
34
35/**
36 * MOAS Server channel handler.
37 */
38@Sharable
39@Beta
40public class MoasServerHandler extends ChannelInboundHandlerAdapter {
41
42 private static final Logger log =
43 LoggerFactory.getLogger(MoasServerHandler.class);
44
45 private MoasServerController controller;
46
47 MoasServerHandler(MoasServerController controller) {
48 this.controller = controller;
49 }
50
51 @Override
52 public void channelActive(ChannelHandlerContext ctx) throws Exception {
53 final SocketAddress address = ctx.channel().remoteAddress();
54 if (!(address instanceof InetSocketAddress)) {
55 log.warn("Invalid client connection. MOAS is identified based on IP");
56 ctx.close();
57 return;
58 }
59
60 final InetSocketAddress inetAddress = (InetSocketAddress) address;
61 final String host = inetAddress.getHostString();
62 log.info("New client connected to the Server: {}", host);
63
64 controller.deviceAgent.addMoas(IpAddress.valueOf(host), ctx);
65 }
66
67 @Override
68 public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
69 ByteBuf in = (ByteBuf) msg;
70 String strMsg = in.toString(io.netty.util.CharsetUtil.US_ASCII);
71
72 ObjectMapper mapper = new ObjectMapper();
73 ArtemisMessage actObj = mapper.readValue(strMsg, ArtemisMessage.class);
74
75 controller.packetAgent.processMoasPacket(actObj, ctx);
76 }
77
78 @Override
79 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
80 log.error(ExceptionUtils.getFullStackTrace(cause));
81 cause.printStackTrace();
82 ctx.close();
83 }
84
85}