Commit Graph

30 Commits

Author SHA1 Message Date
Norman Maurer
e4995be33c Use allocator when constructing ByteBufHolder sub-types or use Unpool… (#9377)
Motivation:

In many places Netty uses Unpooled.buffer(0) while should use EMPTY_BUFFER. We can't change this due to back compatibility in the constructors but can use Unpooled.EMPTY_BUFFER in some cases to ensure we not allocate at all. In others we can directly use the allocator either from the Channel / ChannelHandlerContext or the request / response.

Modification:

- Use Unpooled.EMPTY_BUFFER where possible
- Use allocator where possible

Result:

Fixes #9345 for websockets and http package
2019-07-18 10:36:03 +02:00
Norman Maurer
3d6e6136a9
Decouple EventLoop details from the IO handling for each transport to… (#8680)
* Decouble EventLoop details from the IO handling for each transport to allow easy re-use of code and customization

Motiviation:

As today extending EventLoop implementations to add custom logic / metrics / instrumentations is only possible in a very limited way if at all. This is due the fact that most implementations are final or even package-private. That said even if these would be public there are the ability to do something useful with these is very limited as the IO processing and task processing are very tightly coupled. All of the mentioned things are a big pain point in netty 4.x and need improvement.

Modifications:

This changeset decoubled the IO processing logic from the task processing logic for the main transport (NIO, Epoll, KQueue) by introducing the concept of an IoHandler. The IoHandler itself is responsible to wait for IO readiness and process these IO events. The execution of the IoHandler itself is done by the SingleThreadEventLoop as part of its EventLoop processing. This allows to use the same EventLoopGroup (MultiThreadEventLoupGroup) for all the mentioned transports by just specify a different IoHandlerFactory during construction.

Beside this core API change this changeset also allows to easily extend SingleThreadEventExecutor / SingleThreadEventLoop to add custom logic to it which then can be reused by all the transports. The ideas are very similar to what is provided by ScheduledThreadPoolExecutor (that is part of the JDK). This allows for example things like:

  * Adding instrumentation / metrics:
    * how many Channels are registered on an SingleThreadEventLoop
    * how many Channels were handled during the IO processing in an EventLoop run
    * how many task were handled during the last EventLoop / EventExecutor run
    * how many outstanding tasks we have
    ...
    ...
  * Implementing custom strategies for choosing the next EventExecutor / EventLoop to use based on these metrics.
  * Use different Promise / Future / ScheduledFuture implementations
  * decorate Runnable / Callables when submitted to the EventExecutor / EventLoop

As a lot of functionalities are folded into the MultiThreadEventLoopGroup and SingleThreadEventLoopGroup this changeset also removes:

  * AbstractEventLoop
  * AbstractEventLoopGroup
  * EventExecutorChooser
  * EventExecutorChooserFactory
  * DefaultEventLoopGroup
  * DefaultEventExecutor
  * DefaultEventExecutorGroup

Result:

Fixes https://github.com/netty/netty/issues/8514 .
2019-01-23 08:32:05 +01:00
Stephane Landelle
97d871a755 Validate cookie name and value characters Motivation:
RFC6265 specifies which characters are allowed in a cookie name and value.

Netty is currently too lax, which can used for HttpOnly escaping.

Modification:

In ServerCookieDecoder: discard cookie key-value pairs that contain invalid characters.
In ClientCookieEncoder: throw an exception when trying to encode cookies with invalid characters.

Result:

The problem described in the motivation section is fixed.
2015-05-07 06:33:36 +02:00
Eric Anderson
bd224286f5 [#3531] Create SslContext.Builder
Motivation:

SslContext factory methods have gotten out of control; it's past time to
swap to a builder.

Modifications:

New Builder class. The existing factory methods must be left as-is for
backward compatibility.

Result:

Fixes #3531
2015-04-14 07:28:34 +02:00
Trustin Lee
4ce994dd4f Fix backward compatibility from the previous backport
Motivation:

The commit 50e06442c3 changed the type of
the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1
backward-incompatible with 4.0.

It also introduces newer utility classes such as HttpHeaderUtil, which
deprecates most static methods in HttpHeaders.  To ease the migration
between 4.1 and 5.0, we should deprecate all static methods that are
non-existent in 5.0, and provide proper counterpart.

Modification:

- Revert the changes in HttpHeaders.Names and Values
- Deprecate all static methods in HttpHeaders in favor of:
  - HttpHeaderUtil
  - the member methods of HttpHeaders
  - AsciiString
- Add integer and date access methods to HttpHeaders for easier future
  migration to 5.0
- Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP
  constants in AsciiString
  - Deprecate HttpHeaders.Names and Values
  - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually
    lowercased in all WebSocket versions but the oldest one
- Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP
  constants in AsciiString
  - Deprecate RtspHeaders.*
- Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of
  the parameters are AsciiString
- Avoid using AsciiString.toString() repetitively
  - Change the parameter type of some methods from String to
    CharSequence

Result:

Backward compatibility is recovered.  New classes and methods will make
the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are
ported to master.
2014-11-01 01:00:25 +09:00
Trustin Lee
223efc5f99 Clean up the examples
Motivation:

The examples have not been updated since long time ago, showing various
issues fixed in this commit.

Modifications:

- Overall simplification to reduce LoC
  - Use system properties to get options instead of parsing args.
  - Minimize option validation
  - Just use System.out/err instead of Logger
  - Do not pass config as parameters - just access it directly
  - Move the main logic to main(String[]) instead of creating a new
    instance meaninglessly
    - Update netty-build-21 to make checkstyle not complain
  - Remove 'throws Exception' clause if possible
- Line wrap at 120 (previously at 80)
- Add an option to enable SSL for most examples
- Use ChannelFuture.sync() instead of await()
- Use System.out for the actual result. Use System.err otherwise.
- Delete examples that are not very useful:
  - applet
  - websocket/html5
  - websocketx/sslserver
  - localecho/multithreaded
- Add run-example.sh which simplifies launching an example from command
  line
- Rewrite FileServer example

Result:

Shorter and simpler examples.  A user can focus more on what it actually
does than miscellaneous stuff.  A user can launch an example very
easily.
2014-05-23 17:13:09 +09:00
Trustin Lee
b6c0c0c95f Add an OpenSslEngine and the universal API for enabling SSL
Motivation:

Some users already use an SSLEngine implementation in finagle-native. It
wraps OpenSSL to get higher SSL performance.  However, to take advantage
of it, finagle-native must be compiled manually, and it means we cannot
pull it in as a dependency and thus we cannot test our SslHandler
against the OpenSSL-based SSLEngine.  For an instance, we had #2216.

Because the construction procedures of JDK SSLEngine and OpenSslEngine
are very different from each other, we also need to provide a universal
way to enable SSL in a Netty application.

Modifications:

- Pull netty-tcnative in as an optional dependency.
  http://netty.io/wiki/forked-tomcat-native.html
- Backport NativeLibraryLoader from 4.0
- Move OpenSSL-based SSLEngine implementation into our code base.
  - Copied from finagle-native; originally written by @jpinner et al.
  - Overall cleanup by @trustin.
- Run all SslHandler tests with both default SSLEngine and OpenSslEngine
- Add a unified API for creating an SSL context
  - SslContext allows you to create a new SSLEngine or a new SslHandler
    with your PKCS#8 key and X.509 certificate chain.
  - Add JdkSslContext and its subclasses
  - Add OpenSslServerContext
- Add ApplicationProtocolSelector to ensure the future support for NPN
  (NextProtoNego) and ALPN (Application Layer Protocol Negotiation) on
  the client-side.
- Add SimpleTrustManagerFactory to help a user write a
  TrustManagerFactory easily, which should be useful for those who need
  to write an alternative verification mechanism. For example, we can
  use it to implement an unsafe TrustManagerFactory that accepts
  self-signed certificates for testing purposes.
- Add InsecureTrustManagerFactory and FingerprintTrustManager for quick
  and dirty testing
- Add SelfSignedCertificate class which generates a self-signed X.509
  certificate very easily.
- Update all our examples to use SslContext.newClient/ServerContext()
- SslHandler now logs the chosen cipher suite when handshake is
  finished.

Result:

- Cleaner unified API for configuring an SSL client and an SSL server
  regardless of its internal implementation.
- When native libraries are available, OpenSSL-based SSLEngine
  implementation is selected automatically to take advantage of its
  performance benefit.
- Examples take advantage of this modification and thus are cleaner.
2014-05-18 02:54:06 +09:00
jwilson
38d04c927f Tweak snoop example to send a full HTTP request.
Without this, future HTTP requests on this channel will
silently fail because the HttpObjectEncoder will be left
in an unhappy state.
2014-02-01 18:35:38 +01:00
Norman Maurer
c0580cfe71 Fix examples 2013-07-11 11:25:40 +02:00
Trustin Lee
23d0178494 Introduce EventExecutor.shutdownGracefully() that deprecates shutdown()
shutdownGracefully() provides two optional parameters that give more
control over when an executor has to be shut down.

- Related issue: #1307
- Add shutdownGracefully(..) and isShuttingDown()
- Deprecate shutdown() / shutdownNow()
- Replace lastAccessTime with lastExecutionTime and update it after task
  execution for accurate quiet period check
  - runAllTasks() and runShutdownTasks() update it automatically.
  - Add updateLastExecutionTime() so that subclasses can update it
- Add a constructor parameter that tells not to add an unncessary wakeup
  task in execute() if addTask() wakes up the executor thread
  automatically.  Previously, execute() always called wakeup() after
  addTask(), which often caused an extra dummy task in the task queue.
- Use shutdownGracefully() wherever possible / Deprecation javadoc
- Reduce the running time of SingleThreadEventLoopTest from 40s to 15s
  using custom graceful shutdown parameters

- Other changes made along with this commit:
  - takeTask() does not throw InterruptedException anymore.
    - Returns null on interruption or wakeup
  - Make sure runShutdownTasks() return true even if an exception was
    raised while running the shutdown tasks
  - Remove unnecessary isShutdown() checks
  - Consistent use of SingleThreadEventExecutor.nanoTime()

Replace isWakeupOverridden with a constructor parameter
2013-05-01 10:52:38 +09:00
Trustin Lee
b7797917ab Deprecate Bootstrap.shutdown() and use EventLoopGroup.shutdown() wherever possible
There are still some tests that use Bootstrap.shutdown() though.  They need non-trivial refactoring, which will come soon.
2013-04-03 16:15:33 +09:00
Norman Maurer
5b81e1692d Move non socket specific stuff out of the socket package, part 2 2013-02-01 10:32:27 +01:00
Trustin Lee
788d7e9b8b Remove Bootstrap operations that require a promise and add various ad-hoc bind() and connect() operations
- Update examples to use the newly added bind() and connect()
  operations.
2013-01-30 20:11:00 +09:00
Trustin Lee
34820511ff Second HTTP overhaul
- Rename message types for clarity
  - HttpMessage -> FullHttpMessage
  - HttpHeader -> HttpMessage
  - HttpRequest -> FullHttpRequest
  - HttpResponse -> FulllHttpResponse
  - HttpRequestHeader -> HttpRequest
  - HttpResponseHeader -> HttpResponse
- HttpContent now extends ByteBufHolder; no more content() method
- Make HttpHeaders abstract, make its header access methods public, and
  add DefaultHttpHeaders
- Header accessor methods in HttpMessage and LastHttpContent are
  replaced with HttpMessage.headers() and
  LastHttpContent.trailingHeaders(). Both methods return HttpHeaders.
- Remove setters wherever possible and remove 'get' prefix
- Instead of calling setContent(), a user can either specify the content
  when constructing a message or write content into the buffer.
  (e.g. m.content().writeBytes(...))
- Overall cleanup & fixes
2013-01-16 23:46:02 +09:00
Norman Maurer
b7de868003 [#677] Overhaul HTTP codec
This commit tries to simplify the handling of Http easier and more consistent. This has a effect of many channges. Including:
 - HttpMessage was renamed to HttpHeader and the setContent and getContent methods were removed
 - HttpChunk was renamed to HttpContent
 - HttpChunkTrailer was renamed to LastHttpContent
 - HttpCodecUtil was merged into HttpHeaders

Now a "complete" Http message (request or response) contains of the following parts:
 - HttpHeader (HttpRequestHeader or HttpResponseHeader)
 - 0 - n HttpContent objects which contains parts of the content of the message
 - 1 LastHttpContent which marks the end of the message and contains the remaining data of the content

I also changed the sematic of HttpResponse and HttpRequest, these now represent a "complete" message which contains the HttpHeader and the HttpLastContent, and so can be used to eeasily send requests. The HttpMessageAggregator was renamed to HttpObjectAggregator and produce HttpResponse / HttpRequest message.
2013-01-15 17:51:12 +01:00
Trustin Lee
a07fb94fe7 Prefer "str".equals(var) to var.equals("str") / Add proper null checks 2012-11-12 08:59:54 +09:00
norman
df72356d7d Rename classes as result of descussion on #594 2012-09-12 14:04:41 +02:00
norman
ec1339d775 Finish the refactoring of bootstrap 2012-09-11 09:34:51 +02:00
Trustin Lee
d298707198 [#502] Split EventLoop/EventExecutor into parent and children
- Add EventExecutorGroup and EventLoopGroup
- EventExecutor and EventLoop extends EventExecutorGroup and
  EventLoopGroup
  - They form their own group so that .next() returns itself.
- Rename Bootstrap.eventLoop() to group()
- Rename parameter names such as executor to group
- Rename *EventLoop/Executor to *EventLoop/ExecutorGroup
- Rename *ChildEventLoop/Executor to *EventLoop/Executor
2012-08-10 20:17:18 +09:00
Trustin Lee
6d2f6d697d Make CookieEncoder and CookieDecoder stateless
- Also: CookieEncoder is split into ServerCookieEncoder and
  ClientCookieEncoder
2012-06-26 05:26:54 +09:00
Trustin Lee
5e93d206ff Overhaul - Split ChannelHandler & Merge ChannelHandlerContext
- Extracted some handler methods from ChannelInboundHandler into
  ChannelStateHandler
- Extracted some handler methods from ChannelOutboundHandler into
  ChannelOperationHandler
- Moved exceptionCaught and userEventTriggered are now in
  ChannelHandler
  
- Channel(Inbound|Outbound)HandlerContext is merged into
  ChannelHandlerContext
- ChannelHandlerContext adds direct access methods for inboud and
  outbound buffers
  - The use of ChannelBufferHolder is minimal now.
    - Before: inbound().byteBuffer()
    - After: inboundByteBuffer()
    - Simpler and better performance
    
- Bypass buffer types were removed because it just does not work at all
  with the thread model.
  - All handlers that uses a bypass buffer are broken.  Will fix soon.

- CombinedHandlerAdapter does not make sense anymore either because
  there are four handler interfaces to consider and often the two
  handlers will implement the same handler interface such as
  ChannelStateHandler.  Thinking of better ways to provide this feature
2012-06-07 14:52:33 +09:00
Trustin Lee
1eced1e9e3 Update license headers 2012-06-04 13:31:44 -07:00
Trustin Lee
3b2c25e8ed Rename (Server)Bootstrap.(child)initializer to (child)handler
- The handler you specify with initializer() is actually simply added
  to the pipeline and that's all.  It's ChannelInitializer which does
  additional work.  For example, a user can specify just a single
  handler with initializer() and it will still work.  This is especially
  common for Bootstrap, so I renamed initializer to handler, which makes
  more sense.
2012-06-03 01:00:16 -07:00
Trustin Lee
8237afff64 Ported most examples
- Renamed ChannelBootstrap to Bootstrap
- Renamed ServerChannelBootstrap to ServerBootstrap
- Moved bootstrap classes to io.netty.bootstrap as before
- Moved unfoldAndAdd() to a separate utility class
- Fixed a bug in unfoldAndAdd() where it did not handle ChannelBuffer
  correctly
2012-05-29 16:41:26 -07:00
Trustin Lee
a1bdf671f1 Simplified EventLoop implementation names
- Also
  - Fixed a test failure
  - Fixed compiler warnings related with ChannelInitializer type
    parameters
2012-05-25 15:51:22 -07:00
Trustin Lee
af37ec4f23 Ported the HTTP snoop example to the new API
- Replaced pipeline factories with initializers
- Ported essential parts related with HTTP to the new API
- Replaced ChannelHandlerAdapter.combine() with CombinedChannelHandler
- Fixed a bug where ReplayingDecoder does not notify the next handler
- Fixed a bug where ReplayingDecoder calls wrong callDecode() method
- Added a destination buffer as an argument to AbstractChannel.doRead()
  for easier implementation
- Fixed a bug where NioSocketChannel did not try to increase the inbound
  buffer size (moved the logic to AbstractChannel)
2012-05-20 14:19:11 +09:00
Trustin Lee
368156f5d0 Another round of the new API design
- Channel now creates a ChannelPipeline by itself

  I find no reason to allow a user to use one's own pipeline
  implementation since I saw nobody does except for the cases where a
  user wants to add a user attribute to a channel, which is now covered
  by AttributeMap.

- Removed ChannelEvent and its subtypes because they are replaced by
  direct method invocation.
- Replaced ChannelSink with Channel.unsafe()
- Various getter renaming (e.g. Channel.getId() -> Channel.id())
- Added ChannelHandlerInvoker interface
- Implemented AbstractChannel and AbstractServerChannel
- Some other changes I don't remember
2012-05-01 17:19:41 +09:00
Norman Maurer
60d9364604 First round of remove the boss-thread. See #240 2012-03-28 20:19:39 +02:00
Norman Maurer
4636309597 Fix HttpSnoopClient. See #183 2012-02-12 12:36:04 +01:00
Trustin Lee
b7cfc6b7f0 Rename HTTP snoop example classes for disambiguation 2012-01-15 00:28:25 +09:00