Network profiling is back !

This commit is contained in:
ProfMobius committed 2014-05-12 19:44:34 +02:00
1 parent 0f47d1b0d5
commit da4d3f5a12
13 files changed
+1026 -57

No files matched your search

@@ -0,0 +1,293 @@
package cpw.mods.fml.common.network;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.AttributeKey;
import java.util.List;
import mcp.mobius.mobiuscore.profiler.ProfilerSection;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetworkManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
public class FMLOutboundHandler extends ChannelOutboundHandlerAdapter {
public static final AttributeKey<OutboundTarget> FML_MESSAGETARGET = new AttributeKey<OutboundTarget>("fml:outboundTarget");
public static final AttributeKey<Object> FML_MESSAGETARGETARGS = new AttributeKey<Object>("fml:outboundTargetArgs");
public enum OutboundTarget {
/**
* The packet is sent nowhere. It will be on the {@link EmbeddedChannel#outboundMessages()} Queue.
*
* @author cpw
*
*/
NOWHERE(Sets.immutableEnumSet(Side.CLIENT, Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
// NOOP
}
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
return null;
}
},
/**
* The packet is sent to the {@link NetworkDispatcher} supplied as an argument.
*
* @author cpw
*
*/
DISPATCHER(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
if (!(args instanceof NetworkDispatcher))
{
throw new RuntimeException("DISPATCHER expects a NetworkDispatcher");
}
}
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
return ImmutableList.of((NetworkDispatcher)args);
}
},
/**
* The packet is sent to the originator of the packet. This requires the inbound packet
* to have it's originator information set.
*
* @author cpw
*
*/
REPLY(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
// NOOP
}
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
return ImmutableList.of(packet.getDispatcher());
}
},
/**
* The packet is sent to the {@link EntityPlayerMP} supplied as an argument.
*
* @author cpw
*
*/
PLAYER(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
if (!(args instanceof EntityPlayerMP))
{
throw new RuntimeException("PLAYER target expects a Player arg");
}
}
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
EntityPlayerMP player = (EntityPlayerMP) args;
NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
return ImmutableList.of(dispatcher);
}
},
/**
* The packet is dispatched to all players connected to the server.
* @author cpw
*
*/
ALL(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
}
@SuppressWarnings("unchecked")
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
ImmutableList.Builder<NetworkDispatcher> builder = ImmutableList.<NetworkDispatcher>builder();
for (EntityPlayerMP player : (List<EntityPlayerMP>)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList)
{
NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
builder.add(dispatcher);
}
return builder.build();
}
},
/**
* The packet is sent to all players in the dimension identified by the integer argument.
* @author cpw
*
*/
DIMENSION(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
if (!(args instanceof Integer))
{
throw new RuntimeException("DIMENSION expects an integer argument");
}
}
@SuppressWarnings("unchecked")
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
int dimension = (Integer)args;
ImmutableList.Builder<NetworkDispatcher> builder = ImmutableList.<NetworkDispatcher>builder();
for (EntityPlayerMP player : (List<EntityPlayerMP>)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList)
{
if (dimension == player.dimension)
{
NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
builder.add(dispatcher);
}
}
return builder.build();
}
},
/**
* The packet is sent to all players within range of the {@link TargetPoint} argument supplied.
*
* @author cpw
*
*/
ALLAROUNDPOINT(Sets.immutableEnumSet(Side.SERVER))
{
@Override
public void validateArgs(Object args)
{
if (!(args instanceof TargetPoint))
{
throw new RuntimeException("ALLAROUNDPOINT expects a TargetPoint argument");
}
}
@SuppressWarnings("unchecked")
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
TargetPoint tp = (TargetPoint)args;
ImmutableList.Builder<NetworkDispatcher> builder = ImmutableList.<NetworkDispatcher>builder();
for (EntityPlayerMP player : (List<EntityPlayerMP>)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList)
{
if (player.dimension == tp.dimension)
{
double d4 = tp.x - player.posX;
double d5 = tp.y - player.posY;
double d6 = tp.z - player.posZ;
if (d4 * d4 + d5 * d5 + d6 * d6 < tp.range * tp.range)
{
NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
builder.add(dispatcher);
}
}
}
return builder.build();
}
},
/**
* The packet is sent to the server this client is currently conversing with.
* @author cpw
*
*/
TOSERVER(Sets.immutableEnumSet(Side.CLIENT))
{
@Override
public void validateArgs(Object args)
{
}
@Override
public List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet)
{
NetworkManager clientConnection = FMLCommonHandler.instance().getClientToServerNetworkManager();
return clientConnection == null ? ImmutableList.<NetworkDispatcher>of() : ImmutableList.of(clientConnection.channel().attr(NetworkDispatcher.FML_DISPATCHER).get());
}
};
private OutboundTarget(ImmutableSet<Side> sides)
{
this.allowed = sides;
}
public final ImmutableSet<Side> allowed;
public abstract void validateArgs(Object args);
public abstract List<NetworkDispatcher> selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
if (!(msg instanceof FMLProxyPacket))
{
return;
}
FMLProxyPacket pkt = (FMLProxyPacket) msg;
OutboundTarget outboundTarget;
Object args = null;
NetworkDispatcher dispatcher = ctx.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
// INTERNAL message callback - let it pass out
if (dispatcher != null)
{
ctx.write(msg, promise);
return;
}
outboundTarget = ctx.channel().attr(FML_MESSAGETARGET).get();
Side channelSide = ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get();
if (outboundTarget != null && outboundTarget.allowed.contains(channelSide))
{
args = ctx.channel().attr(FML_MESSAGETARGETARGS).get();
outboundTarget.validateArgs(args);
}
else if (channelSide == Side.CLIENT)
{
outboundTarget = OutboundTarget.TOSERVER;
}
else
{
throw new FMLNetworkException("Packet arrived at the outbound handler without a valid target!");
}
List<NetworkDispatcher> dispatchers = outboundTarget.selectNetworks(args, ctx, pkt);
// This will drop the messages into the output queue at the embedded channel
if (dispatchers == null)
{
ctx.write(msg, promise);
return;
}
for (NetworkDispatcher targetDispatcher : dispatchers)
{
ProfilerSection.PACKET_OUTBOUND.stop(pkt);
targetDispatcher.sendProxy((FMLProxyPacket) msg);
}
}
}
@@ -0,0 +1,148 @@
package cpw.mods.fml.common.network.internal;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import java.io.IOException;
import mcp.mobius.mobiuscore.profiler.ProfilerSection;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import net.minecraft.network.play.server.S3FPacketCustomPayload;
import org.apache.logging.log4j.Level;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.network.FMLNetworkException;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.relauncher.Side;
public class FMLProxyPacket extends Packet {
final String channel;
private Side target;
private final ByteBuf payload;
private INetHandler netHandler;
private NetworkDispatcher dispatcher;
private FMLProxyPacket(byte[] payload, String channel)
{
this(Unpooled.wrappedBuffer(payload), channel);
}
public FMLProxyPacket(S3FPacketCustomPayload original)
{
this(original.func_149168_d(), original.func_149169_c());
this.target = Side.CLIENT;
}
public FMLProxyPacket(C17PacketCustomPayload original)
{
this(original.func_149558_e(), original.func_149559_c());
this.target = Side.SERVER;
}
public FMLProxyPacket(ByteBuf payload, String channel)
{
this.channel = channel;
this.payload = payload;
}
/**
* Reads the raw packet data from the data stream.
*/
@Override
public void readPacketData(PacketBuffer packetbuffer) throws IOException
{
// NOOP - we are not built this way
}
/**
* Writes the raw packet data to the data stream.
*/
@Override
public void writePacketData(PacketBuffer packetbuffer) throws IOException
{
// NOOP - we are not built this way
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
@Override
public void processPacket(INetHandler inethandler)
{
ProfilerSection.PACKET_INBOUND.stop(this);
this.netHandler = inethandler;
EmbeddedChannel internalChannel = NetworkRegistry.INSTANCE.getChannel(this.channel, this.target);
if (internalChannel != null)
{
internalChannel.attr(NetworkRegistry.NET_HANDLER).set(this.netHandler);
try
{
internalChannel.writeInbound(this);
}
catch (FMLNetworkException ne)
{
FMLLog.log(Level.ERROR, ne, "There was a network exception handling a packet on channel %s", channel);
dispatcher.rejectHandshake(ne.getMessage());
}
catch (Throwable t)
{
FMLLog.log(Level.ERROR, t, "There was a critical exception handling a packet on channel %s", channel);
dispatcher.rejectHandshake("A fatal error has occured, this connection is terminated");
}
}
}
public String channel()
{
return channel;
}
public ByteBuf payload()
{
return payload;
}
public INetHandler handler()
{
return netHandler;
}
public Packet toC17Packet()
{
return new C17PacketCustomPayload(channel, payload.array());
}
public Packet toS3FPacket()
{
return new S3FPacketCustomPayload(channel, payload.array());
}
public void setTarget(Side target)
{
this.target = target;
}
public void setDispatcher(NetworkDispatcher networkDispatcher)
{
this.dispatcher = networkDispatcher;
}
public NetworkManager getOrigin()
{
return this.dispatcher != null ? this.dispatcher.manager : null;
}
public NetworkDispatcher getDispatcher()
{
return this.dispatcher;
}
public Side getTarget()
{
return target;
}
}
@@ -15,6 +15,9 @@ public enum ProfilerSection implements IProfilerBase{
//HANDLER_TICKSTOP (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick stop.
PACKET_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis
PACKET_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis
//PACKETFML_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis
//PACKETFML_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis
NETWORK_TICK (RunType.ONREQUEST, Side.SERVER), //The time it takes for the server to handle the packets during a tick.
EVENT_INVOKE (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Timing of the event invokation
@@ -1,10 +1,14 @@
package mcp.mobius.opis.data.holders.newtypes;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
@@ -16,27 +20,32 @@ public class DataPacket implements ISerializable{
public DataByteSize size;
public DataByteRate rate;
public DataAmountRate amount;
public String type;
public CachedString type;
public DataPacket(){
}
public DataPacket(int id){
this.id = id;
this.size = new DataByteSize(0);
this.rate = new DataByteRate(0, 5);
public DataPacket(Packet packet){
this.type = new CachedString(packet.getClass().getSimpleName());
this.size = new DataByteSize(0);
this.rate = new DataByteRate(0, 5);
this.amount = new DataAmountRate(0, 5);
//try {
// this.type = ((Class)(Packet.packetIdToClassMap.lookup(this.id))).getSimpleName();
//} catch (Exception e) {
this.type = "<UNUSED>";
//}
}
public DataPacket fill(Packet packet){
//this.size.size += packet.getPacketSize() + 1;
//this.rate.size += packet.getPacketSize() + 1;
//this.amount.size += 1;
public DataPacket fill(Packet packet, int pktsize){
/*
PacketBuffer buff = new PacketBuffer(Unpooled.buffer());
int pktsize = 0;
try{
packet.writePacketData(buff);
pktsize = buff.readableBytes();
} catch (Exception e){
}
*/
this.size.size += pktsize;
this.rate.size += pktsize;
this.amount.size += 1;
return this;
}
@@ -47,23 +56,18 @@ public class DataPacket implements ISerializable{
@Override
public void writeToStream(ByteArrayDataOutput stream){
stream.writeInt(this.id);
this.size.writeToStream(stream);
this.rate.writeToStream(stream);
this.amount.writeToStream(stream);
this.type.writeToStream(stream);
}
public static DataPacket readFromStream(ByteArrayDataInput stream){
DataPacket retVal = new DataPacket();
retVal.id = stream.readInt();
retVal.size = DataByteSize.readFromStream(stream);
retVal.rate = DataByteRate.readFromStream(stream);
retVal.amount = DataAmountRate.readFromStream(stream);
//try {
// retVal.type = ((Class)(Packet.packetIdToClassMap.lookup(retVal.id))).getSimpleName();
//} catch (Exception e) {
retVal.type = "<UNUSED>";
//}
retVal.type = CachedString.readFromStream(stream);
return retVal;
}
@@ -7,6 +7,7 @@ import java.io.IOException;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import mcp.mobius.opis.data.holders.ISerializable;
public class DataPacket250 implements ISerializable{
@@ -24,14 +25,13 @@ public class DataPacket250 implements ISerializable{
this.amount = new DataAmountRate(0, 5);
}
/*
public DataPacket250 fill(Packet packet){
this.size.size += packet.getPacketSize() + 1;
this.rate.size += packet.getPacketSize() + 1;
public DataPacket250 fill(FMLProxyPacket packet){
int pktsize = packet.payload().readableBytes();//packet.payload().array().length;
this.size.size += pktsize;
this.rate.size += pktsize;
this.amount.size += 1;
return this;
}
*/
public void startInterval(){
this.rate.reset();
@@ -3,6 +3,9 @@ package mcp.mobius.opis.data.profilers;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import mcp.mobius.opis.data.holders.newtypes.DataPacket;
import mcp.mobius.opis.data.holders.newtypes.DataPacket250;
@@ -11,19 +14,13 @@ import mcp.mobius.opis.helpers.Helpers;
public class ProfilerPacket extends ProfilerAbstract {
public long dataAmount = 0;
public ArrayList<DataPacket> data = new ArrayList<DataPacket>();
public HashMap<String, DataPacket> data = new HashMap<String, DataPacket>();
public HashMap<String, DataPacket250> data250 = new HashMap<String, DataPacket250>();
public ArrayList<DataPacket> jabbaSpec = new ArrayList<DataPacket>();
public ProfilerPacket(){
for (int i = 0; i < 256; i++)
data.add(new DataPacket(i));
}
public void startInterval(){
for (DataPacket packet : data)
for (DataPacket packet : data.values())
packet.startInterval();
for (DataPacket250 packet : data250.values())
@@ -36,27 +33,36 @@ public class ProfilerPacket extends ProfilerAbstract {
}
@Override
public void start(Object key) {
/*
if (key != null && Helpers.getEffectiveSide() == Side.SERVER){
//System.out.printf("%s | %s\n", Thread.currentThread().getClass(), Thread.currentThread().getName());
public void start(Object msg, Object size) {
if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)){
if (!(msg instanceof FMLProxyPacket)){
Packet pkt = (Packet) msg;
Packet packet = (Packet)key;
dataAmount += packet.getPacketSize() + 1;
data.get(packet.getPacketId()).fill(packet);
if (packet.getPacketId() == 250){
String channel = ((Packet250CustomPayload)packet).channel;
try{
data250.get(channel).fill(packet);
data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer)size);
} catch (Exception e){
data250.put(channel, new DataPacket250(channel));
data250.get(channel).fill(packet);
data.put(msg.getClass().getSimpleName(), new DataPacket((Packet)msg));
data.get(msg.getClass().getSimpleName()).fill(pkt, (Integer)size);
}
}
}
*/
}
@Override
public void stop(Object msg) {
if ((msg != null) && (Helpers.getEffectiveSide() == Side.SERVER)){
if (msg instanceof FMLProxyPacket){
FMLProxyPacket pkt = (FMLProxyPacket) msg;
String channel = pkt.channel();
try{
data250.get(channel).fill(pkt);
} catch (Exception e){
data250.put(channel, new DataPacket250(channel));
data250.get(channel).fill(pkt);
}
}
}
}
}
@@ -121,8 +121,8 @@ public enum OpisServerTickHandler{
if (timer5000.isDone()){
updatePlayers();
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_OUTBOUND, ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).data));
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_INBOUND, ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).data));
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_OUTBOUND, new ArrayList<DataPacket>( ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).data.values())));
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_INBOUND, new ArrayList<DataPacket>( ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).data.values())));
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_OUTBOUND_250, new ArrayList<DataPacket250>( ((ProfilerPacket)ProfilerSection.PACKET_OUTBOUND.getProfiler()).data250.values())));
PacketManager.sendPacketToAllSwing(new NetDataList(Message.LIST_PACKETS_INBOUND_250, new ArrayList<DataPacket250>( ((ProfilerPacket)ProfilerSection.PACKET_INBOUND.getProfiler()).data250.values())));
@@ -6,8 +6,12 @@ import cpw.mods.fml.relauncher.Side;
public class Helpers {
public static Side getEffectiveSide(){
Thread thr = Thread.currentThread();
if ((thr.getName().equals("Server thread")) || (thr.getName().contains("Netty IO")))
{
return Side.SERVER;
}
return FMLCommonHandler.instance().getEffectiveSide();
return Side.CLIENT;
/*
if ((thr instanceof ThreadMinecraftServer) || (thr instanceof ServerListenThread) || (thr instanceof TcpWriterThread) || (thr instanceof TcpReaderThread))
+2 -1
View File
@@ -170,7 +170,7 @@ public class modOpis {
ProfilerSection.TICK .setProfiler(new ProfilerTick());
ProfilerSection.TILEENT_UPDATETIME .setProfiler(new ProfilerTileEntityUpdate());
ProfilerSection.PACKET_INBOUND .setProfiler(new ProfilerPacket());
ProfilerSection.PACKET_OUTBOUND .setProfiler(new ProfilerPacket());
ProfilerSection.PACKET_OUTBOUND .setProfiler(new ProfilerPacket());
ProfilerSection.NETWORK_TICK .setProfiler(new ProfilerNetworkTick());
event.registerServerCommand(new CommandChunkList());
@@ -195,6 +195,7 @@ public class modOpis {
event.registerServerCommand(new CommandHelp());
//GameRegistry.registerPlayerTracker(PlayerTracker.instance());
//DeadManSwitch.startDeadManSwitch(MinecraftServer.getServer());
@@ -29,9 +29,9 @@ public class PanelOutbound extends JPanelMsgHandler implements ITabPanel {
add(scrollPane, "cell 0 0,grow");
table = new JTableStats(
new String[] {"Type", "ID", "Amount", "Rate", "Total Size"},
new Class[] {String.class, Integer.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class},
new int[] {SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT}
new String[] {"Type", "Amount", "Rate", "Total Size"},
new Class[] {String.class, DataAmountRate.class, DataByteRate.class, DataByteSize.class},
new int[] {SwingConstants.LEFT, SwingConstants.RIGHT, SwingConstants.RIGHT, SwingConstants.RIGHT}
);
scrollPane.setViewportView(table);
@@ -52,7 +52,6 @@ public class PanelOutbound extends JPanelMsgHandler implements ITabPanel {
if (packet.type.equals("<UNUSED>")) continue;
model.addRow(new Object[] {
packet.type,
packet.id,
packet.amount,
packet.rate,
packet.size
@@ -0,0 +1,395 @@
package net.minecraft.network;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GenericFutureListener;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.util.Queue;
import javax.crypto.SecretKey;
import mcp.mobius.mobiuscore.profiler.ProfilerSection;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.CryptManager;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.MessageDeserializer;
import net.minecraft.util.MessageDeserializer2;
import net.minecraft.util.MessageSerializer;
import net.minecraft.util.MessageSerializer2;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public class NetworkManager extends SimpleChannelInboundHandler
{
private static final Logger logger = LogManager.getLogger();
public static final Marker logMarkerNetwork = MarkerManager.getMarker("NETWORK");
public static final Marker logMarkerPackets = MarkerManager.getMarker("NETWORK_PACKETS", logMarkerNetwork);
public static final AttributeKey attrKeyConnectionState = new AttributeKey("protocol");
public static final AttributeKey attrKeyReceivable = new AttributeKey("receivable_packets");
public static final AttributeKey attrKeySendable = new AttributeKey("sendable_packets");
public static final NioEventLoopGroup eventLoops = new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build());
/**
* Whether this NetworkManager deals with the client or server side of the connection
*/
private final boolean isClientSide;
/**
* The queue for received, unprioritized packets that will be processed at the earliest opportunity
*/
private final Queue receivedPacketsQueue = Queues.newConcurrentLinkedQueue();
/** The queue for packets that require transmission */
private final Queue outboundPacketsQueue = Queues.newConcurrentLinkedQueue();
/** The active channel used to send data */
private Channel channel;
/** The address of the remote party */
private SocketAddress socketAddress;
/** The INetHandler instance responsible for processing received packets */
private INetHandler netHandler;
/**
* The current connection state, being one of: HANDSHAKING, PLAY, STATUS, LOGIN
*/
private EnumConnectionState connectionState;
/** A String indicating why the network has shutdown. */
private IChatComponent terminationReason;
private static final String __OBFID = "CL_00001240";
public NetworkManager(boolean p_i45147_1_)
{
this.isClientSide = p_i45147_1_;
}
public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception
{
super.channelActive(p_channelActive_1_);
this.channel = p_channelActive_1_.channel();
this.socketAddress = this.channel.remoteAddress();
this.setConnectionState(EnumConnectionState.HANDSHAKING);
}
/**
* Sets the new connection state and registers which packets this channel may send and receive
*/
public void setConnectionState(EnumConnectionState p_150723_1_)
{
this.connectionState = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).getAndSet(p_150723_1_);
this.channel.attr(attrKeyReceivable).set(p_150723_1_.func_150757_a(this.isClientSide));
this.channel.attr(attrKeySendable).set(p_150723_1_.func_150754_b(this.isClientSide));
this.channel.config().setAutoRead(true);
logger.debug("Enabled auto read");
}
public void channelInactive(ChannelHandlerContext p_channelInactive_1_)
{
this.closeChannel(new ChatComponentTranslation("disconnect.endOfStream", new Object[0]));
}
public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_)
{
this.closeChannel(new ChatComponentTranslation("disconnect.genericReason", new Object[] {"Internal Exception: " + p_exceptionCaught_2_}));
}
protected void channelRead0(ChannelHandlerContext p_150728_1_, Packet p_150728_2_)
{
if (this.channel.isOpen())
{
if (p_150728_2_.hasPriority())
{
p_150728_2_.processPacket(this.netHandler);
}
else
{
this.receivedPacketsQueue.add(p_150728_2_);
}
}
}
/**
* Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular
* connection state (protocol)
*/
public void setNetHandler(INetHandler p_150719_1_)
{
Validate.notNull(p_150719_1_, "packetListener", new Object[0]);
logger.debug("Set listener of {} to {}", new Object[] {this, p_150719_1_});
this.netHandler = p_150719_1_;
}
/**
* Will flush the outbound queue and dispatch the supplied Packet if the channel is ready, otherwise it adds the
* packet to the outbound queue and registers the GenericFutureListener to fire after transmission
*/
public void scheduleOutboundPacket(Packet p_150725_1_, GenericFutureListener ... p_150725_2_)
{
if (this.channel != null && this.channel.isOpen())
{
this.flushOutboundQueue();
this.dispatchPacket(p_150725_1_, p_150725_2_);
}
else
{
this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(p_150725_1_, p_150725_2_));
}
}
/**
* Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the
* packet, otherwise it will add a task for the channel eventloop thread to do that.
*/
private void dispatchPacket(final Packet p_150732_1_, final GenericFutureListener[] p_150732_2_)
{
final EnumConnectionState enumconnectionstate = EnumConnectionState.func_150752_a(p_150732_1_);
final EnumConnectionState enumconnectionstate1 = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get();
if (enumconnectionstate1 != enumconnectionstate && !( p_150732_1_ instanceof FMLProxyPacket))
{
logger.debug("Disabled auto read");
this.channel.config().setAutoRead(false);
}
if (this.channel.eventLoop().inEventLoop())
{
if (enumconnectionstate != enumconnectionstate1 && !( p_150732_1_ instanceof FMLProxyPacket))
{
this.setConnectionState(enumconnectionstate);
}
this.channel.writeAndFlush(p_150732_1_).addListeners(p_150732_2_).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
else
{
this.channel.eventLoop().execute(new Runnable()
{
private static final String __OBFID = "CL_00001241";
public void run()
{
if (enumconnectionstate != enumconnectionstate1 && !( p_150732_1_ instanceof FMLProxyPacket))
{
NetworkManager.this.setConnectionState(enumconnectionstate);
}
NetworkManager.this.channel.writeAndFlush(p_150732_1_).addListeners(p_150732_2_).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
});
}
}
/**
* Will iterate through the outboundPacketQueue and dispatch all Packets
*/
private void flushOutboundQueue()
{
if (this.channel != null && this.channel.isOpen())
{
while (!this.outboundPacketsQueue.isEmpty())
{
NetworkManager.InboundHandlerTuplePacketListener inboundhandlertuplepacketlistener = (NetworkManager.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll();
this.dispatchPacket(inboundhandlertuplepacketlistener.field_150774_a, inboundhandlertuplepacketlistener.field_150773_b);
}
}
}
/**
* Checks timeouts and processes all packets received
*/
public void processReceivedPackets()
{
this.flushOutboundQueue();
EnumConnectionState enumconnectionstate = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get();
if (this.connectionState != enumconnectionstate)
{
if (this.connectionState != null)
{
this.netHandler.onConnectionStateTransition(this.connectionState, enumconnectionstate);
}
this.connectionState = enumconnectionstate;
}
if (this.netHandler != null)
{
for (int i = 1000; !this.receivedPacketsQueue.isEmpty() && i >= 0; --i)
{
Packet packet = (Packet)this.receivedPacketsQueue.poll();
packet.processPacket(this.netHandler);
}
this.netHandler.onNetworkTick();
}
this.channel.flush();
}
/**
* Return the InetSocketAddress of the remote endpoint
*/
public SocketAddress getSocketAddress()
{
return this.socketAddress;
}
/**
* Closes the channel, the parameter can be used for an exit message (not certain how it gets sent)
*/
public void closeChannel(IChatComponent p_150718_1_)
{
if (this.channel.isOpen())
{
this.channel.close();
this.terminationReason = p_150718_1_;
}
}
/**
* True if this NetworkManager uses a memory connection (single player game). False may imply both an active TCP
* connection or simply no active connection at all
*/
public boolean isLocalChannel()
{
return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel;
}
/**
* Prepares a clientside NetworkManager: establishes a connection to the address and port supplied and configures
* the channel pipeline. Returns the newly created instance.
*/
@SideOnly(Side.CLIENT)
public static NetworkManager provideLanClient(InetAddress p_150726_0_, int p_150726_1_)
{
final NetworkManager networkmanager = new NetworkManager(true);
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group(eventLoops)).handler(new ChannelInitializer()
{
private static final String __OBFID = "CL_00001242";
protected void initChannel(Channel p_initChannel_1_)
{
try
{
p_initChannel_1_.config().setOption(ChannelOption.IP_TOS, Integer.valueOf(24));
}
catch (ChannelException channelexception1)
{
;
}
try
{
p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(false));
}
catch (ChannelException channelexception)
{
;
}
p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(20)).addLast("splitter", new MessageDeserializer2()).addLast("decoder", new MessageDeserializer()).addLast("prepender", new MessageSerializer2()).addLast("encoder", new MessageSerializer()).addLast("packet_handler", networkmanager);
}
})).channel(NioSocketChannel.class)).connect(p_150726_0_, p_150726_1_).syncUninterruptibly();
return networkmanager;
}
/**
* Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel
* pipeline. Returns the newly created instance.
*/
@SideOnly(Side.CLIENT)
public static NetworkManager provideLocalClient(SocketAddress p_150722_0_)
{
final NetworkManager networkmanager = new NetworkManager(true);
((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group(eventLoops)).handler(new ChannelInitializer()
{
private static final String __OBFID = "CL_00001243";
protected void initChannel(Channel p_initChannel_1_)
{
p_initChannel_1_.pipeline().addLast("packet_handler", networkmanager);
}
})).channel(LocalChannel.class)).connect(p_150722_0_).syncUninterruptibly();
return networkmanager;
}
/**
* Adds an encoder+decoder to the channel pipeline. The parameter is the secret key used for encrypted communication
*/
public void enableEncryption(SecretKey p_150727_1_)
{
this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptingDecoder(CryptManager.func_151229_a(2, p_150727_1_)));
this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptingEncoder(CryptManager.func_151229_a(1, p_150727_1_)));
}
/**
* Returns true if this NetworkManager has an active channel, false otherwise
*/
public boolean isChannelOpen()
{
return this.channel != null && this.channel.isOpen();
}
/**
* Gets the current handler for processing packets
*/
public INetHandler getNetHandler()
{
return this.netHandler;
}
/**
* If this channel is closed, returns the exit message, null otherwise.
*/
public IChatComponent getExitMessage()
{
return this.terminationReason;
}
/**
* Switches the channel to manual reading modus
*/
public void disableAutoRead()
{
this.channel.config().setAutoRead(false);
}
protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Object p_channelRead0_2_)
{
this.channelRead0(p_channelRead0_1_, (Packet)p_channelRead0_2_);
}
public Channel channel()
{
/** The active channel used to send data */
return channel;
}
static class InboundHandlerTuplePacketListener
{
private final Packet field_150774_a;
private final GenericFutureListener[] field_150773_b;
private static final String __OBFID = "CL_00001244";
public InboundHandlerTuplePacketListener(Packet p_i45146_1_, GenericFutureListener ... p_i45146_2_)
{
this.field_150774_a = p_i45146_1_;
this.field_150773_b = p_i45146_2_;
}
}
}
@@ -0,0 +1,62 @@
package net.minecraft.util;
import com.google.common.collect.BiMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.io.IOException;
import java.util.List;
import mcp.mobius.mobiuscore.profiler.ProfilerSection;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public class MessageDeserializer extends ByteToMessageDecoder
{
private static final Logger logger = LogManager.getLogger();
private static final Marker field_150799_b = MarkerManager.getMarker("PACKET_RECEIVED", NetworkManager.logMarkerPackets);
private static final String __OBFID = "CL_00001252";
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws IOException
{
if (p_decode_2_.readableBytes() != 0)
{
PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
int i = packetbuffer.readVarIntFromBuffer();
Packet packet = Packet.generatePacket((BiMap)p_decode_1_.channel().attr(NetworkManager.attrKeyReceivable).get(), i);
ProfilerSection.PACKET_INBOUND.start(packet, packetbuffer.capacity());
if (packet == null)
{
throw new IOException("Bad packet id " + i);
}
else
{
packet.readPacketData(packetbuffer);
if (packetbuffer.readableBytes() > 0)
{
throw new IOException("Packet was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i);
}
else
{
p_decode_3_.add(packet);
if (logger.isDebugEnabled())
{
logger.debug(field_150799_b, " IN: [{}:{}] {}[{}]", new Object[] {p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get(), Integer.valueOf(i), packet.getClass().getName(), packet.serialize()});
}
}
}
}
}
}
@@ -0,0 +1,54 @@
package net.minecraft.util;
import com.google.common.collect.BiMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.io.IOException;
import mcp.mobius.mobiuscore.profiler.ProfilerSection;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public class MessageSerializer extends MessageToByteEncoder
{
private static final Logger logger = LogManager.getLogger();
private static final Marker field_150797_b = MarkerManager.getMarker("PACKET_SENT", NetworkManager.logMarkerPackets);
private static final String __OBFID = "CL_00001253";
protected void encode(ChannelHandlerContext p_150796_1_, Packet p_150796_2_, ByteBuf p_150796_3_) throws IOException
{
Integer integer = (Integer)((BiMap)p_150796_1_.channel().attr(NetworkManager.attrKeySendable).get()).inverse().get(p_150796_2_.getClass());
if (logger.isDebugEnabled())
{
logger.debug(field_150797_b, "OUT: [{}:{}] {}[{}]", new Object[] {p_150796_1_.channel().attr(NetworkManager.attrKeyConnectionState).get(), integer, p_150796_2_.getClass().getName(), p_150796_2_.serialize()});
}
if (integer == null)
{
throw new IOException("Can\'t serialize unregistered packet");
}
else
{
PacketBuffer packetbuffer = new PacketBuffer(p_150796_3_);
packetbuffer.writeVarIntToBuffer(integer.intValue());
p_150796_2_.writePacketData(packetbuffer);
ProfilerSection.PACKET_OUTBOUND.start(p_150796_2_, packetbuffer.readableBytes());
}
}
protected void encode(ChannelHandlerContext p_encode_1_, Object p_encode_2_, ByteBuf p_encode_3_) throws IOException
{
this.encode(p_encode_1_, (Packet)p_encode_2_, p_encode_3_);
}
}