instance_id
stringlengths
17
39
repo
stringclasses
8 values
issue_id
stringlengths
14
34
pr_id
stringlengths
14
34
linking_methods
sequencelengths
1
3
base_commit
stringlengths
40
40
merge_commit
stringlengths
0
40
hints_text
sequencelengths
0
106
resolved_comments
sequencelengths
0
119
created_at
unknown
labeled_as
sequencelengths
0
7
problem_title
stringlengths
7
174
problem_statement
stringlengths
0
55.4k
gold_files
sequencelengths
0
10
gold_files_postpatch
sequencelengths
1
10
test_files
sequencelengths
0
60
gold_patch
stringlengths
220
5.83M
test_patch
stringlengths
386
194k
split_random
stringclasses
3 values
split_time
stringclasses
3 values
issue_start_time
timestamp[ns]
issue_created_at
unknown
issue_by_user
stringlengths
3
21
split_repo
stringclasses
3 values
provectus/kafka-ui/1520_1524
provectus/kafka-ui
provectus/kafka-ui/1520
provectus/kafka-ui/1524
[ "timestamp(timedelta=0.0, similarity=0.9533965407773565)" ]
42a004af1c46e10c1c127472edcb02f78f601675
4390923e482c08d1e27ff0e1e783231f9fc6ee5c
[]
[]
"2022-01-31T15:46:15Z"
[ "type/bug", "scope/frontend", "status/accepted", "status/confirmed", "type/regression" ]
Too short visible list for Schema compatibility level selector
### Is your proposal related to a problem? <!-- Provide a clear and concise description of what the problem is. For example, "I'm always frustrated when..." --> (Write your answer here.) There is list of 3 levels (other are invisible) on Schema overview and Schema Edit pages (see attachment) There is a scroll slider there but it`s not visible by default. ### Describe the solution you'd like <!-- Provide a clear and concise description of what you want to happen. --> (Describe your proposed solution here.) Make the scroll slider visible by default for the selector of Schema Compatibility level ### Describe alternatives you've considered <!-- Let us know about other solutions you've tried or researched. --> (Write your answer here.) ### Additional context <!-- Is there anything else you can add about the proposal? You might want to link to related issues here, if you haven't already. --> (Write your answer here.) <img width="1499" alt="Screenshot 2022-01-31 at 10 59 34" src="https://user-images.githubusercontent.com/92585878/151766141-5bd8aa5d-414d-4a14-8a1d-cb4b3de6acac.png">
[ "kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap", "kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap", "kafka-ui-react-app/src/components/common/Select/Select.styled.ts", "kafka-ui-react-app/src/theme/theme.ts" ]
[ "kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap", "kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap", "kafka-ui-react-app/src/components/common/Select/Select.styled.ts", "kafka-ui-react-app/src/theme/theme.ts" ]
[]
diff --git a/kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap b/kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap index 0f83bd30884..282738e8de0 100644 --- a/kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap +++ b/kafka-ui-react-app/src/components/Connect/List/__tests__/__snapshots__/ListItem.spec.tsx.snap @@ -335,6 +335,11 @@ exports[`Connectors ListItem matches snapshot 1`] = ` "hover": "#171A1C", "normal": "#171A1C", }, + "optionList": Object { + "scrollbar": Object { + "backgroundColor": "#ABB5BA", + }, + }, }, "switch": Object { "checked": "#29A352", diff --git a/kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap b/kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap index fb75a98ba78..84e17d8d92c 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap +++ b/kafka-ui-react-app/src/components/Topics/Topic/Details/__test__/__snapshots__/Details.spec.tsx.snap @@ -342,6 +342,11 @@ exports[`Details when it has readonly flag does not render the Action button a T "hover": "#171A1C", "normal": "#171A1C", }, + "optionList": Object { + "scrollbar": Object { + "backgroundColor": "#ABB5BA", + }, + }, }, "switch": Object { "checked": "#29A352", diff --git a/kafka-ui-react-app/src/components/common/Select/Select.styled.ts b/kafka-ui-react-app/src/components/common/Select/Select.styled.ts index 67df6d86f7c..dd5f730d72b 100644 --- a/kafka-ui-react-app/src/components/common/Select/Select.styled.ts +++ b/kafka-ui-react-app/src/components/common/Select/Select.styled.ts @@ -70,6 +70,17 @@ export const OptionList = styled.ul` color: ${(props) => props.theme.select.color.normal}; overflow-y: scroll; z-index: 10; + + &::-webkit-scrollbar { + -webkit-appearance: none; + width: 7px; + } + + &::-webkit-scrollbar-thumb { + border-radius: 4px; + background-color: ${(props) => + props.theme.select.optionList.scrollbar.backgroundColor}; + } `; export const Option = styled.li<OptionProps>` diff --git a/kafka-ui-react-app/src/theme/theme.ts b/kafka-ui-react-app/src/theme/theme.ts index b480a657767..4edae75f6ae 100644 --- a/kafka-ui-react-app/src/theme/theme.ts +++ b/kafka-ui-react-app/src/theme/theme.ts @@ -240,6 +240,11 @@ const theme = { active: Colors.neutral[70], disabled: Colors.neutral[10], }, + optionList: { + scrollbar: { + backgroundColor: Colors.neutral[30], + }, + }, }, input: { borderColor: {
null
val
train
2022-02-01T11:14:05
"2022-01-31T09:06:16Z"
agolosen
train
provectus/kafka-ui/1556_1568
provectus/kafka-ui
provectus/kafka-ui/1556
provectus/kafka-ui/1568
[ "timestamp(timedelta=1.0, similarity=0.8694037738763447)" ]
6424a88acadc1f85cabf66a982cbe08ee7e11914
136f12d76ac8d65233d13cbf7301ac5cb9873ad4
[ "Hi, thanks for reaching out.\r\n\r\nAn example comes within #1568. \r\n\r\nLet me know if you more questions!", "Hi, thank you for the answer.\r\n", "An example is located [here](https://github.com/provectus/kafka-ui/blob/master/documentation/compose/kafka-ssl.yml).", "Hi, no changes on my side.\r\nI tried to set pass like file containing the password, but only get error:\r\n```\r\nkafka-ui | Caused by: java.security.UnrecoverableKeyException: Password verification failed\r\nkafka-ui | at java.base/sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:790)\r\n```\r\nAfter that return pass like string, and keep same error like first message\r\n\r\n**docker-compose**\r\nversion: '3'\r\n\r\nservices:\r\n kafka-ui:\r\n image: provectuslabs/kafka-ui:master\r\n container_name: kafka-ui\r\n ports:\r\n - \"8080:8080\"\r\n restart: always\r\n volumes:\r\n - ./cert:/opt/java/openjdk/lib/security\r\n environment:\r\n KAFKA_CLUSTERS_0_NAME: TBCR_DSO\r\n KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: d5tbcr-kfc002lk.corp.dev:9092,d5tbcr-kfc003lk.corp.dev:9092,d5tbcr-kfc004lk.corp.dev:9092\r\n KAFKA_CLUSTERS_0_PROPERTIES_SECURITY_PROTOCOL: SSL\r\n KAFKA_CLUSTERS_0_PROPERTIES_SSL_KEYSTORE_LOCATION: /opt/java/openjdk/lib/security/tbcr-keystore.jks\r\n KAFKA_CLUSTERS_0_PROPERTIES_SSL_KEYSTORE_PASSWORD: pass_as_string\r\n KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_LOCATION: /opt/java/openjdk/lib/security/tbcr-omni-tech-client.jks\r\n KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_PASSWORD: pass_as_string\r\n\r\n\r\n**logs**\r\nkafka-ui | 2022-02-09 10:08:12,188 INFO [parallel-1] o.a.k.c.a.AdminClientConfig: AdminClientConfig values:\r\nkafka-ui | bootstrap.servers = [d5tbcr-kfc002lk.corp.dev:9092, d5tbcr-kfc003lk.corp.dev:9092, d5tbcr-kfc004lk.corp.dev:9092]\r\nkafka-ui | client.dns.lookup = use_all_dns_ips\r\nkafka-ui | client.id =\r\nkafka-ui | connections.max.idle.ms = 300000\r\nkafka-ui | default.api.timeout.ms = 60000\r\nkafka-ui | metadata.max.age.ms = 300000\r\nkafka-ui | metric.reporters = []\r\nkafka-ui | metrics.num.samples = 2\r\nkafka-ui | metrics.recording.level = INFO\r\nkafka-ui | metrics.sample.window.ms = 30000\r\nkafka-ui | receive.buffer.bytes = 65536\r\nkafka-ui | reconnect.backoff.max.ms = 1000\r\nkafka-ui | reconnect.backoff.ms = 50\r\nkafka-ui | request.timeout.ms = 30000\r\nkafka-ui | retries = 2147483647\r\nkafka-ui | retry.backoff.ms = 100\r\nkafka-ui | sasl.client.callback.handler.class = null\r\nkafka-ui | sasl.jaas.config = null\r\nkafka-ui | sasl.kerberos.kinit.cmd = /usr/bin/kinit\r\nkafka-ui | sasl.kerberos.min.time.before.relogin = 60000\r\nkafka-ui | sasl.kerberos.service.name = null\r\nkafka-ui | sasl.kerberos.ticket.renew.jitter = 0.05\r\nkafka-ui | sasl.kerberos.ticket.renew.window.factor = 0.8\r\nkafka-ui | sasl.login.callback.handler.class = null\r\nkafka-ui | sasl.login.class = null\r\nkafka-ui | sasl.login.refresh.buffer.seconds = 300\r\nkafka-ui | sasl.login.refresh.min.period.seconds = 60\r\nkafka-ui | sasl.login.refresh.window.factor = 0.8\r\nkafka-ui | sasl.login.refresh.window.jitter = 0.05\r\nkafka-ui | sasl.mechanism = GSSAPI\r\nkafka-ui | security.protocol = SSL\r\nkafka-ui | security.providers = null\r\nkafka-ui | send.buffer.bytes = 131072\r\nkafka-ui | socket.connection.setup.timeout.max.ms = 30000\r\nkafka-ui | socket.connection.setup.timeout.ms = 10000\r\nkafka-ui | ssl.cipher.suites = null\r\nkafka-ui | ssl.enabled.protocols = [TLSv1.2, TLSv1.3]\r\nkafka-ui | ssl.endpoint.identification.algorithm = https\r\nkafka-ui | ssl.engine.factory.class = null\r\nkafka-ui | ssl.key.password = null\r\nkafka-ui | ssl.keymanager.algorithm = SunX509\r\nkafka-ui | ssl.keystore.certificate.chain = null\r\nkafka-ui | ssl.keystore.key = null\r\nkafka-ui | ssl.keystore.location = /opt/java/openjdk/lib/security/tbcr-keystore.jks\r\nkafka-ui | ssl.keystore.password = [hidden]\r\nkafka-ui | ssl.keystore.type = JKS\r\nkafka-ui | ssl.protocol = TLSv1.3\r\nkafka-ui | ssl.provider = null\r\nkafka-ui | ssl.secure.random.implementation = null\r\nkafka-ui | ssl.trustmanager.algorithm = PKIX\r\nkafka-ui | ssl.truststore.location = /opt/java/openjdk/lib/security/tbcr-omni-tech-client.jks\r\nkafka-ui | ssl.truststore.password = [hidden]\r\nkafka-ui | ssl.truststore.type = JKS\r\nkafka-ui | 2022-02-09 10:08:12,290 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka version: 2.8.0\r\nkafka-ui | 2022-02-09 10:08:12,290 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka commitId: ebb1d6e21cc92130\r\nkafka-ui | 2022-02-09 10:08:12,290 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka startTimeMs: 1644401292290\r\nkafka-ui | 2022-02-09 10:08:14,397 ERROR [kafka-admin-client-thread | adminclient-32] c.p.k.u.s.MetricsService: Failed\r\nto collect cluster TBCR_DSO info\r\nkafka-ui | java.lang.IllegalStateException: Error while creating AdminClient for Cluster TBCR_DSO\r\nkafka-ui | at com.provectus.kafka.ui.service.AdminClientServiceImpl.lambda$createAdminClient$3(AdminClientServiceIm\r\npl.java:44)\r\nkafka-ui | at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3732)\r\nkafka-ui | at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)\r\nkafka-ui | at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onError(FluxMapFuseable.java:140)\r\nkafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:192)\r\nkafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:259)\r\nkafka-ui | at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:194)\r\nkafka-ui | at com.provectus.kafka.ui.service.ReactiveAdminClient.lambda$toMono$1(ReactiveAdminClient.java:97)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:\r\n175)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:\r\n162)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238)\r\nkafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:73)\r\nkafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:57)\r\nkafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238)\r\nkafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$9.handleResponse(KafkaAdminClient.java:2126)\r\nkafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.handleResponses(KafkaAdminClient.\r\njava:1189)\r\nkafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.processRequests(KafkaAdminClient.\r\njava:1341)\r\nkafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.run(KafkaAdminClient.java:1264)\r\nkafka-ui | at java.base/java.lang.Thread.run(Thread.java:830)\r\nkafka-ui | Caused by: org.apache.kafka.common.errors.ClusterAuthorizationException: Cluster authorization failed.\r\nkafka-ui | 2022-02-09 10:08:14,397 DEBUG [kafka-admin-client-thread | adminclient-32] c.p.k.u.s.ClustersMetricsSchedule\r\nr: Metrics updated for cluster: TBCR_DSO\r\n", "@manifiko Mind hoping on our discord? I'll explain how to set it up with your configuration.\r\nhttps://discord.gg/4DWzD7pGE5", "Hi @manifiko, Did you find any solution for this issue? I am too facing same problem and my SSL configuration works fine with Conduktor and few other tool which uses AdminClient but doesn't seems to be working with Kafka-ui", "@SukhmeetSethi hey, feel free to open up a new discussion or we can discuss your problem in our discord.", "For us the problem is we noticed from the startup message that the \"ssl.key.password\" parameter is not loaded. \r\n\r\nUsing the 'docker-compose-ssl.yaml' one now to test. What is the environment variable to pass that ?", "> For us the problem is we noticed from the startup message that the \"ssl.key.password\" parameter is not loaded.\r\n> \r\n> Using the 'docker-compose-ssl.yaml' one now to test. What is the environment variable to pass that ?\r\n\r\nIf someone is looking for it, this is the environment variable to set _\"ssl.key.password\"_ :\r\n`KAFKA_CLUSTERS_0_PROPERTIES_SSL_KEY_PASSWORD`" ]
[ "I think we dont need this constants here, pls move/embed to KafkaSSLManager", "minor, but I think naming is vague and too general here", "Why do we need this special config? Could we just push these params?", "Discussed, found the problem, turns out it does work with properties.", "location of this this file is not obvious ( /etc/kafka/secrets/kafka.keystore.jks )\r\n\r\nLet's make it more explicit. ", "let's name it kafka.truststore.jks inside docker too)", "done", "done, what I could" ]
"2022-02-07T15:18:10Z"
[ "type/documentation", "status/duplicate" ]
Kafka with SSL doesn't work
Hello. Try connect to three kafka brokers. KAFKA_CLUSTERS_0 have not security and all ok KAFKA_CLUSTERS_1 and KAFKA_CLUSTERS_2 have SSL. in docker compose add certs and all configs. as a result, kafka without ssl is only connected, two othert crash with exception **Caused by: org.apache.kafka.common.errors.ClusterAuthorizationException: Cluster authorization failed.** ofset explorer and conductor with this certs and settings connect successfully **docker-compose** version: '3' services: kafka-ui: image: provectuslabs/kafka-ui:master container_name: kafka-ui ports: - "8080:8080" restart: always volumes: - ./cert:/opt/java/openjdk/lib/security environment: - KAFKA_CLUSTERS_0_NAME=TB - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=d5tbcr-kfc001lk.corp.dev:9092 - KAFKA_CLUSTERS_1_NAME=AF - KAFKA_CLUSTERS_1_BOOTSTRAPSERVERS=d5aflc-kfc001lk.corp.dev:9092 - KAFKA_CLUSTERS_1_PROPERTIES_SECURITY_PROTOCOL=SSL - KAFKA_CLUSTERS_1_PROPERTIES_SSL_KEYSTORE_LOCATION=/opt/java/openjdk/lib/security/keystore.jks - KAFKA_CLUSTERS_1_PROPERTIES_SSL_KEYSTORE_PASSWORD=[pass] - KAFKA_CLUSTERS_1_PROPERTIES_SSL_KEYSTORE_TYPE=JKS - KAFKA_CLUSTERS_1_PROPERTIES_SSL_TRUSTSTORE_LOCATION=/opt/java/openjdk/lib/security/kafka-trust.pfx - KAFKA_CLUSTERS_1_PROPERTIES_SSL_TRUSTSTORE_PASSWORD=[pass] - KAFKA_CLUSTERS_1_PROPERTIES_SSL_TRUSTSTORE_TYPE=PKCS12 - KAFKA_CLUSTERS_2_NAME=FB - KAFKA_CLUSTERS_2_BOOTSTRAPSERVERS=d5pbrc-kfc002lk.corp.dev:9092 - KAFKA_CLUSTERS_2_PROPERTIES_SECURITY_PROTOCOL=SSL - KAFKA_CLUSTERS_2_PROPERTIES_SSL_KEYSTORE_LOCATION=/opt/java/openjdk/lib/security/keystore.jks - KAFKA_CLUSTERS_2_PROPERTIES_SSL_KEYSTORE_PASSWORD=[pass] - KAFKA_CLUSTERS_2_PROPERTIES_SSL_KEYSTORE_TYPE=JKS - KAFKA_CLUSTERS_2_PROPERTIES_SSL_TRUSTSTORE_LOCATION=/opt/java/openjdk/lib/security/omni-tech-client.jks - KAFKA_CLUSTERS_2_PROPERTIES_SSL_TRUSTSTORE_PASSWORD=[pass] - KAFKA_CLUSTERS_2_PROPERTIES_SSL_TRUSTSTORE_TYPE=JKS **LOGS** kafka-ui | 2022-02-05 21:51:44,118 INFO [background-preinit] o.h.v.i.u.Version: HV000001: Hibernate Validator 6.2.0.Final kafka-ui | 2022-02-05 21:51:44,152 INFO [main] c.p.k.u.KafkaUiApplication: Starting KafkaUiApplication using Java 13.0.9 on 17f613c3648a with PID 1 (/kafka-ui-api.jar started by root in /) kafka-ui | 2022-02-05 21:51:44,155 DEBUG [main] c.p.k.u.KafkaUiApplication: Running with Spring Boot v2.5.6, Spring v5.3.12 kafka-ui | 2022-02-05 21:51:44,156 INFO [main] c.p.k.u.KafkaUiApplication: No active profile set, falling back to default profiles: default kafka-ui | 2022-02-05 21:51:45,981 INFO [main] o.s.d.r.c.RepositoryConfigurationDelegate: Bootstrapping Spring Data LDAP repositories in DEFAULT mode. kafka-ui | 2022-02-05 21:51:46,046 INFO [main] o.s.d.r.c.RepositoryConfigurationDelegate: Finished Spring Data repository scanning in 54 ms. Found 0 LDAP repository interfaces. kafka-ui | 2022-02-05 21:51:47,097 INFO [main] o.s.b.a.s.r.ReactiveUserDetailsServiceAutoConfiguration: kafka-ui | kafka-ui | Using generated security password: 01036954-fda0-42eb-9ff6-2f0fd4a4f7e3 kafka-ui | kafka-ui | 2022-02-05 21:51:47,399 INFO [main] c.p.k.u.s.DeserializationService: Using SchemaRegistryAwareRecordSerDe for cluster 'TB' kafka-ui | 2022-02-05 21:51:47,407 INFO [main] c.p.k.u.s.DeserializationService: Using SchemaRegistryAwareRecordSerDe for cluster 'AF' kafka-ui | 2022-02-05 21:51:47,408 INFO [main] c.p.k.u.s.DeserializationService: Using SchemaRegistryAwareRecordSerDe for cluster 'FB' kafka-ui | 2022-02-05 21:51:48,155 INFO [main] o.s.b.a.e.w.EndpointLinksResolver: Exposing 2 endpoint(s) beneath base path '/actuator' kafka-ui | 2022-02-05 21:51:48,360 WARN [main] c.p.k.u.c.a.DisabledAuthSecurityConfig: Authentication is disabled. Access will be unrestricted. kafka-ui | 2022-02-05 21:51:48,602 INFO [main] o.s.l.c.s.AbstractContextSource: Property 'userDn' not set - anonymous context will be used for read-write operations kafka-ui | 2022-02-05 21:51:48,985 INFO [main] o.s.b.w.e.n.NettyWebServer: Netty started on port 8080 kafka-ui | 2022-02-05 21:51:49,012 INFO [main] c.p.k.u.KafkaUiApplication: Started KafkaUiApplication in 5.787 seconds (JVM running for 6.384) kafka-ui | 2022-02-05 21:51:49,054 DEBUG [parallel-1] c.p.k.u.s.ClustersMetricsScheduler: Start getting metrics for kafkaCluster: TB kafka-ui | 2022-02-05 21:51:49,055 DEBUG [parallel-2] c.p.k.u.s.ClustersMetricsScheduler: Start getting metrics for kafkaCluster: AF kafka-ui | 2022-02-05 21:51:49,057 DEBUG [parallel-3] c.p.k.u.s.ClustersMetricsScheduler: Start getting metrics for kafkaCluster: FB kafka-ui | 2022-02-05 21:51:49,084 INFO [parallel-2] o.a.k.c.a.AdminClientConfig: AdminClientConfig values: kafka-ui | bootstrap.servers = [d5aflc-kfc001lk.corp.dev:9092] kafka-ui | client.dns.lookup = use_all_dns_ips kafka-ui | client.id = kafka-ui | connections.max.idle.ms = 300000 kafka-ui | default.api.timeout.ms = 60000 kafka-ui | metadata.max.age.ms = 300000 kafka-ui | metric.reporters = [] kafka-ui | metrics.num.samples = 2 kafka-ui | metrics.recording.level = INFO kafka-ui | metrics.sample.window.ms = 30000 kafka-ui | receive.buffer.bytes = 65536 kafka-ui | reconnect.backoff.max.ms = 1000 kafka-ui | reconnect.backoff.ms = 50 kafka-ui | request.timeout.ms = 30000 kafka-ui | retries = 2147483647 kafka-ui | retry.backoff.ms = 100 kafka-ui | sasl.client.callback.handler.class = null kafka-ui | sasl.jaas.config = null kafka-ui | sasl.kerberos.kinit.cmd = /usr/bin/kinit kafka-ui | sasl.kerberos.min.time.before.relogin = 60000 kafka-ui | sasl.kerberos.service.name = null kafka-ui | sasl.kerberos.ticket.renew.jitter = 0.05 kafka-ui | sasl.kerberos.ticket.renew.window.factor = 0.8 kafka-ui | sasl.login.callback.handler.class = null kafka-ui | sasl.login.class = null kafka-ui | sasl.login.refresh.buffer.seconds = 300 kafka-ui | sasl.login.refresh.min.period.seconds = 60 kafka-ui | sasl.login.refresh.window.factor = 0.8 kafka-ui | sasl.login.refresh.window.jitter = 0.05 kafka-ui | sasl.mechanism = GSSAPI kafka-ui | security.protocol = SSL kafka-ui | security.providers = null kafka-ui | send.buffer.bytes = 131072 kafka-ui | socket.connection.setup.timeout.max.ms = 30000 kafka-ui | socket.connection.setup.timeout.ms = 10000 kafka-ui | ssl.cipher.suites = null kafka-ui | ssl.enabled.protocols = [TLSv1.2, TLSv1.3] kafka-ui | ssl.endpoint.identification.algorithm = https kafka-ui | ssl.engine.factory.class = null kafka-ui | ssl.key.password = null kafka-ui | ssl.keymanager.algorithm = SunX509 kafka-ui | ssl.keystore.certificate.chain = null kafka-ui | ssl.keystore.key = null kafka-ui | ssl.keystore.location = /opt/java/openjdk/lib/security/keystore.jks kafka-ui | ssl.keystore.password = [hidden] kafka-ui | ssl.keystore.type = JKS kafka-ui | ssl.protocol = TLSv1.3 kafka-ui | ssl.provider = null kafka-ui | ssl.secure.random.implementation = null kafka-ui | ssl.trustmanager.algorithm = PKIX kafka-ui | ssl.truststore.certificates = null kafka-ui | ssl.truststore.location = /opt/java/openjdk/lib/security/kafka-trust.pfx kafka-ui | ssl.truststore.password = [hidden] kafka-ui | ssl.truststore.type = PKCS12 kafka-ui | kafka-ui | 2022-02-05 21:51:49,087 INFO [parallel-3] o.a.k.c.a.AdminClientConfig: AdminClientConfig values: kafka-ui | bootstrap.servers = [d5pbrc-kfc002lk.corp.dev:9092] kafka-ui | client.dns.lookup = use_all_dns_ips kafka-ui | client.id = kafka-ui | connections.max.idle.ms = 300000 kafka-ui | default.api.timeout.ms = 60000 kafka-ui | metadata.max.age.ms = 300000 kafka-ui | metric.reporters = [] kafka-ui | metrics.num.samples = 2 kafka-ui | metrics.recording.level = INFO kafka-ui | metrics.sample.window.ms = 30000 kafka-ui | receive.buffer.bytes = 65536 kafka-ui | reconnect.backoff.max.ms = 1000 kafka-ui | reconnect.backoff.ms = 50 kafka-ui | request.timeout.ms = 30000 kafka-ui | retries = 2147483647 kafka-ui | retry.backoff.ms = 100 kafka-ui | sasl.client.callback.handler.class = null kafka-ui | sasl.jaas.config = null kafka-ui | sasl.kerberos.kinit.cmd = /usr/bin/kinit kafka-ui | sasl.kerberos.min.time.before.relogin = 60000 kafka-ui | sasl.kerberos.service.name = null kafka-ui | sasl.kerberos.ticket.renew.jitter = 0.05 kafka-ui | sasl.kerberos.ticket.renew.window.factor = 0.8 kafka-ui | sasl.login.callback.handler.class = null kafka-ui | sasl.login.class = null kafka-ui | sasl.login.refresh.buffer.seconds = 300 kafka-ui | sasl.login.refresh.min.period.seconds = 60 kafka-ui | sasl.login.refresh.window.factor = 0.8 kafka-ui | sasl.login.refresh.window.jitter = 0.05 kafka-ui | sasl.mechanism = GSSAPI kafka-ui | security.protocol = SSL kafka-ui | security.providers = null kafka-ui | send.buffer.bytes = 131072 kafka-ui | socket.connection.setup.timeout.max.ms = 30000 kafka-ui | socket.connection.setup.timeout.ms = 10000 kafka-ui | ssl.cipher.suites = null kafka-ui | ssl.enabled.protocols = [TLSv1.2, TLSv1.3] kafka-ui | ssl.endpoint.identification.algorithm = https kafka-ui | ssl.engine.factory.class = null kafka-ui | ssl.key.password = null kafka-ui | ssl.keymanager.algorithm = SunX509 kafka-ui | ssl.keystore.certificate.chain = null kafka-ui | ssl.keystore.key = null kafka-ui | ssl.keystore.location = /opt/java/openjdk/lib/security/keystore.jks kafka-ui | ssl.keystore.password = [hidden] kafka-ui | ssl.keystore.type = JKS kafka-ui | ssl.protocol = TLSv1.3 kafka-ui | ssl.provider = null kafka-ui | ssl.secure.random.implementation = null kafka-ui | ssl.trustmanager.algorithm = PKIX kafka-ui | ssl.truststore.certificates = null kafka-ui | ssl.truststore.location = /opt/java/openjdk/lib/security/omni-tech-client.jks kafka-ui | ssl.truststore.password = [hidden] kafka-ui | ssl.truststore.type = JKS kafka-ui | kafka-ui | 2022-02-05 21:51:49,088 INFO [parallel-1] o.a.k.c.a.AdminClientConfig: AdminClientConfig values: kafka-ui | bootstrap.servers = [d5tbcr-kfc001lk.corp.dev:9092] kafka-ui | client.dns.lookup = use_all_dns_ips kafka-ui | client.id = kafka-ui | connections.max.idle.ms = 300000 kafka-ui | default.api.timeout.ms = 60000 kafka-ui | metadata.max.age.ms = 300000 kafka-ui | metric.reporters = [] kafka-ui | metrics.num.samples = 2 kafka-ui | metrics.recording.level = INFO kafka-ui | metrics.sample.window.ms = 30000 kafka-ui | receive.buffer.bytes = 65536 kafka-ui | reconnect.backoff.max.ms = 1000 kafka-ui | reconnect.backoff.ms = 50 kafka-ui | request.timeout.ms = 30000 kafka-ui | retries = 2147483647 kafka-ui | retry.backoff.ms = 100 kafka-ui | sasl.client.callback.handler.class = null kafka-ui | sasl.jaas.config = null kafka-ui | sasl.kerberos.kinit.cmd = /usr/bin/kinit kafka-ui | sasl.kerberos.min.time.before.relogin = 60000 kafka-ui | sasl.kerberos.service.name = null kafka-ui | sasl.kerberos.ticket.renew.jitter = 0.05 kafka-ui | sasl.kerberos.ticket.renew.window.factor = 0.8 kafka-ui | sasl.login.callback.handler.class = null kafka-ui | sasl.login.class = null kafka-ui | sasl.login.refresh.buffer.seconds = 300 kafka-ui | sasl.login.refresh.min.period.seconds = 60 kafka-ui | sasl.login.refresh.window.factor = 0.8 kafka-ui | sasl.login.refresh.window.jitter = 0.05 kafka-ui | sasl.mechanism = GSSAPI kafka-ui | security.protocol = PLAINTEXT kafka-ui | security.providers = null kafka-ui | send.buffer.bytes = 131072 kafka-ui | socket.connection.setup.timeout.max.ms = 30000 kafka-ui | socket.connection.setup.timeout.ms = 10000 kafka-ui | ssl.cipher.suites = null kafka-ui | ssl.enabled.protocols = [TLSv1.2, TLSv1.3] kafka-ui | ssl.endpoint.identification.algorithm = https kafka-ui | ssl.engine.factory.class = null kafka-ui | ssl.key.password = null kafka-ui | ssl.keymanager.algorithm = SunX509 kafka-ui | ssl.keystore.certificate.chain = null kafka-ui | ssl.keystore.key = null kafka-ui | ssl.keystore.location = null kafka-ui | ssl.keystore.password = null kafka-ui | ssl.keystore.type = JKS kafka-ui | ssl.protocol = TLSv1.3 kafka-ui | ssl.provider = null kafka-ui | ssl.secure.random.implementation = null kafka-ui | ssl.trustmanager.algorithm = PKIX kafka-ui | ssl.truststore.certificates = null kafka-ui | ssl.truststore.location = null kafka-ui | ssl.truststore.password = null kafka-ui | ssl.truststore.type = JKS kafka-ui | kafka-ui | 2022-02-05 21:51:49,295 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka version: 2.8.0 kafka-ui | 2022-02-05 21:51:49,295 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka commitId: ebb1d6e21cc92130 kafka-ui | 2022-02-05 21:51:49,295 INFO [parallel-1] o.a.k.c.u.AppInfoParser: Kafka startTimeMs: 1644097909291 kafka-ui | 2022-02-05 21:51:50,180 INFO [parallel-3] o.a.k.c.u.AppInfoParser: Kafka version: 2.8.0 kafka-ui | 2022-02-05 21:51:50,181 INFO [parallel-3] o.a.k.c.u.AppInfoParser: Kafka commitId: ebb1d6e21cc92130 kafka-ui | 2022-02-05 21:51:50,182 INFO [parallel-3] o.a.k.c.u.AppInfoParser: Kafka startTimeMs: 1644097910180 kafka-ui | 2022-02-05 21:51:50,248 INFO [parallel-2] o.a.k.c.u.AppInfoParser: Kafka version: 2.8.0 kafka-ui | 2022-02-05 21:51:50,248 INFO [parallel-2] o.a.k.c.u.AppInfoParser: Kafka commitId: ebb1d6e21cc92130 kafka-ui | 2022-02-05 21:51:50,248 INFO [parallel-2] o.a.k.c.u.AppInfoParser: Kafka startTimeMs: 1644097910248 kafka-ui | 2022-02-05 21:51:51,017 DEBUG [kafka-admin-client-thread | adminclient-3] c.p.k.u.s.ClustersMetricsScheduler: Metrics updated for cluster: TB kafka-ui | 2022-02-05 21:51:51,622 ERROR [kafka-admin-client-thread | adminclient-2] c.p.k.u.s.MetricsService: Failed to collect cluster FB info kafka-ui | java.lang.IllegalStateException: Error while creating AdminClient for Cluster FB kafka-ui | at com.provectus.kafka.ui.service.AdminClientServiceImpl.lambda$createAdminClient$3(AdminClientServiceImpl.java:44) kafka-ui | at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3732) kafka-ui | at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94) kafka-ui | at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onError(FluxMapFuseable.java:140) kafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:192) kafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:259) kafka-ui | at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:194) kafka-ui | at com.provectus.kafka.ui.service.ReactiveAdminClient.lambda$toMono$1(ReactiveAdminClient.java:97) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:175) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:162) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:73) kafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:57) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$9.handleResponse(KafkaAdminClient.java:2126) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.handleResponses(KafkaAdminClient.java:1189) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.processRequests(KafkaAdminClient.java:1341) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.run(KafkaAdminClient.java:1264) kafka-ui | at java.base/java.lang.Thread.run(Thread.java:830) kafka-ui | Caused by: org.apache.kafka.common.errors.ClusterAuthorizationException: Cluster authorization failed. kafka-ui | 2022-02-05 21:51:51,623 DEBUG [kafka-admin-client-thread | adminclient-2] c.p.k.u.s.ClustersMetricsScheduler: Metrics updated for cluster: FB kafka-ui | 2022-02-05 21:51:51,881 ERROR [kafka-admin-client-thread | adminclient-1] c.p.k.u.s.MetricsService: Failed to collect cluster AF info kafka-ui | java.lang.IllegalStateException: Error while creating AdminClient for Cluster AF kafka-ui | at com.provectus.kafka.ui.service.AdminClientServiceImpl.lambda$createAdminClient$3(AdminClientServiceImpl.java:44) kafka-ui | at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3732) kafka-ui | at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94) kafka-ui | at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onError(FluxMapFuseable.java:140) kafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:192) kafka-ui | at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:259) kafka-ui | at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:194) kafka-ui | at com.provectus.kafka.ui.service.ReactiveAdminClient.lambda$toMono$1(ReactiveAdminClient.java:97) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:175) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$WhenCompleteBiConsumer.accept(KafkaFutureImpl.java:162) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:61) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl$Applicant.accept(KafkaFutureImpl.java:49) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:73) kafka-ui | at org.apache.kafka.common.KafkaFuture$AllOfAdapter.accept(KafkaFuture.java:57) kafka-ui | at org.apache.kafka.common.internals.KafkaFutureImpl.completeExceptionally(KafkaFutureImpl.java:238) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$9.handleResponse(KafkaAdminClient.java:2126) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.handleResponses(KafkaAdminClient.java:1189) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.processRequests(KafkaAdminClient.java:1341) kafka-ui | at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.run(KafkaAdminClient.java:1264) kafka-ui | at java.base/java.lang.Thread.run(Thread.java:830) kafka-ui | Caused by: org.apache.kafka.common.errors.ClusterAuthorizationException: Cluster authorization failed. kafka-ui | 2022-02-05 21:51:51,881 DEBUG [kafka-admin-client-thread | adminclient-1] c.p.k.u.s.ClustersMetricsScheduler: Metrics updated for cluster: AF
[ "README.md", "documentation/compose/DOCKER_COMPOSE.md" ]
[ "README.md", "documentation/compose/DOCKER_COMPOSE.md", "documentation/compose/kafka-ssl.yml", "documentation/compose/ssl/creds", "documentation/compose/ssl/generate_certs.sh" ]
[]
diff --git a/README.md b/README.md index 10e61d65c0f..55deb5f4a0f 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,18 @@ To run UI for Apache Kafka, you can use a pre-built Docker image or build it loc We have plenty of [docker-compose files](documentation/compose/DOCKER_COMPOSE.md) as examples. They're built for various configuration stacks. +# Guides + +- [SSO configuration](documentation/guides/SSO.md) +- [AWS IAM configuration](documentation/guides/AWS_IAM.md) +- [Docker-compose files](documentation/guides/yaml-description.md) +- [Connection to a secure broker]() + +## Connecting to a Secure Broker + +The app supports TLS (SSL) and SASL connections for [encryption and authentication](http://kafka.apache.org/090/documentation.html#security). <br/> +An example is located [here](documentation/compose/kafka-ssl.yml). + ### Configuration File Example of how to configure clusters in the [application-local.yml](https://github.com/provectus/kafka-ui/blob/master/kafka-ui-api/src/main/resources/application-local.yml) configuration file: @@ -97,7 +109,7 @@ kafka: Configure as many clusters as you need by adding their configs below separated with `-`. -## Running From Docker Image +## Running a Docker Image The official Docker image for UI for Apache Kafka is hosted here: [hub.docker.com/r/provectuslabs/kafka-ui](https://hub.docker.com/r/provectuslabs/kafka-ui). Launch Docker container in the background: @@ -131,18 +143,6 @@ Check [building.md](documentation/project/contributing/building.md) Check [running.md](documentation/project/contributing/running.md) -# Guides - -- [SSO configuration](documentation/guides/SSO.md) -- [AWS IAM configuration](documentation/guides/AWS_IAM.md) -- [Docker-compose files](documentation/guides/yaml-description.md) - -## Connecting to a Secure Broker - -UI for Apache Kafka supports TLS (SSL) and SASL connections for [encryption and authentication](http://kafka.apache.org/090/documentation.html#security). This can be configured by providing a combination of the following files (placed into the Kafka root directory): - -To be continued - ## Liveliness and readiness probes Liveliness and readiness endpoint is at `/actuator/health`. Info endpoint (build info) is located at `/actuator/info`. diff --git a/documentation/compose/DOCKER_COMPOSE.md b/documentation/compose/DOCKER_COMPOSE.md index c7379efe9e1..02a3a6e157e 100644 --- a/documentation/compose/DOCKER_COMPOSE.md +++ b/documentation/compose/DOCKER_COMPOSE.md @@ -1,12 +1,13 @@ # Descriptions of docker-compose configurations (*.yaml) -1. [kafka-ui.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui.yaml) - Default configuration with 2 kafka clusters with two nodes of Schema Registry, one kafka-connect and a few dummy topics. -2. [kafka-clusters-only.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-clusters-only.yaml) - A configuration for development purposes, everything besides `kafka-ui` itself (to be run locally). -3. [kafka-cluster-sr-auth.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-cluster-sr-auth.yaml) - Schema registry with authentication. -4. [kafka-ui-auth-context.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-auth-context.yaml) - Basic (username/password) authentication with custom path (URL) (issue 861). -5. [kafka-ui-connectors.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-connectors.yaml) - Configuration with different connectors (github-source, s3, sink-activities, source-activities) and Ksql functionality. -6. [kafka-ui-jmx-secured.yml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-jmx-secured.yml) - Kafka’s JMX with SSL and authentication. -7. [kafka-ui-reverse-proxy.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-reverse-proxy.yaml) - An example for using the app behind a proxy (like nginx). -8. [kafka-ui-sasl.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-sasl.yaml) - SASL auth for Kafka. -9. [kafka-ui-traefik-proxy.yaml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-traefik-proxy.yaml) - Traefik specific proxy configuration. -10. [kafka-ui-zookeeper-ssl.yml](https://github.com/provectus/kafka-ui/blob/master/docker/kafka-ui-zookeeper-ssl.yml) - SSL enabled zookeeper. +1. [kafka-ui.yaml](./kafka-ui.yaml) - Default configuration with 2 kafka clusters with two nodes of Schema Registry, one kafka-connect and a few dummy topics. +2. [kafka-clusters-only.yaml](./kafka-clusters-only.yaml) - A configuration for development purposes, everything besides `kafka-ui` itself (to be run locally). +3. [kafka-ui-ssl.yml](./kafka-ssl.yml) - Connect to Kafka via TLS/SSL +4. [kafka-cluster-sr-auth.yaml](./kafka-cluster-sr-auth.yaml) - Schema registry with authentication. +5. [kafka-ui-auth-context.yaml](./kafka-ui-auth-context.yaml) - Basic (username/password) authentication with custom path (URL) (issue 861). +6. [kafka-ui-connectors.yaml](./kafka-ui-connectors.yaml) - Configuration with different connectors (github-source, s3, sink-activities, source-activities) and Ksql functionality. +7. [kafka-ui-jmx-secured.yml](./kafka-ui-jmx-secured.yml) - Kafka’s JMX with SSL and authentication. +8. [kafka-ui-reverse-proxy.yaml](./kafka-ui-reverse-proxy.yaml) - An example for using the app behind a proxy (like nginx). +9. [kafka-ui-sasl.yaml](./kafka-ui-sasl.yaml) - SASL auth for Kafka. +10. [kafka-ui-traefik-proxy.yaml](./kafka-ui-traefik-proxy.yaml) - Traefik specific proxy configuration. +11. [kafka-ui-zookeeper-ssl.yml](./kafka-ui-zookeeper-ssl.yml) - SSL enabled zookeeper. diff --git a/documentation/compose/kafka-ssl.yml b/documentation/compose/kafka-ssl.yml new file mode 100644 index 00000000000..b298cdc9d65 --- /dev/null +++ b/documentation/compose/kafka-ssl.yml @@ -0,0 +1,58 @@ +--- +version: '3.4' +services: + + kafka-ui: + container_name: kafka-ui + image: provectuslabs/kafka-ui:latest + ports: + - 8080:8080 + depends_on: + - zookeeper0 + - kafka0 + environment: + KAFKA_CLUSTERS_0_NAME: local + KAFKA_CLUSTERS_0_PROPERTIES_SECURITY_PROTOCOL: SSL + KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092 # SSL LISTENER! + KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper0:2181 + KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_LOCATION: /kafka.truststore.jks + KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_PASSWORD: secret # A FILE WITH THE TRUSTSTORE PASSWORD + volumes: + - ./ssl/kafka.truststore.jks:/kafka.truststore.jks + + zookeeper0: + image: confluentinc/cp-zookeeper:6.0.1 + environment: + ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: 2000 + ports: + - 2181:2181 + + kafka0: + image: confluentinc/cp-kafka:6.0.1 + hostname: kafka0 + depends_on: + - zookeeper0 + ports: + - '9092:9092' + environment: + KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: zookeeper0:2181 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_ADVERTISED_LISTENERS: SSL://kafka0:29092,PLAINTEXT_HOST://localhost:9092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: SSL:SSL,PLAINTEXT_HOST:PLAINTEXT + KAFKA_INTER_BROKER_LISTENER_NAME: SSL + KAFKA_SECURITY_PROTOCOL: SSL + KAFKA_SSL_ENABLED_MECHANISMS: PLAIN,SSL + KAFKA_SSL_KEYSTORE_FILENAME: kafka.keystore.jks + KAFKA_SSL_KEYSTORE_CREDENTIALS: creds + KAFKA_SSL_KEY_CREDENTIALS: creds + KAFKA_SSL_TRUSTSTORE_FILENAME: kafka.truststore.jks + KAFKA_SSL_TRUSTSTORE_CREDENTIALS: creds + #KAFKA_SSL_CLIENT_AUTH: 'required' + KAFKA_SSL_CLIENT_AUTH: "requested" + KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM: '' # COMMON NAME VERIFICATION IS DISABLED SERVER-SIDE + volumes: + - ./ssl/creds:/etc/kafka/secrets/creds + - ./ssl/kafka.truststore.jks:/etc/kafka/secrets/kafka.truststore.jks + - ./ssl/kafka.keystore.jks:/etc/kafka/secrets/kafka.keystore.jks \ No newline at end of file diff --git a/documentation/compose/ssl/creds b/documentation/compose/ssl/creds new file mode 100644 index 00000000000..536aca34dba --- /dev/null +++ b/documentation/compose/ssl/creds @@ -0,0 +1,1 @@ +secret \ No newline at end of file diff --git a/documentation/compose/ssl/generate_certs.sh b/documentation/compose/ssl/generate_certs.sh new file mode 100644 index 00000000000..ebb916657bd --- /dev/null +++ b/documentation/compose/ssl/generate_certs.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash + +set -eu + +KEYSTORE_FILENAME="kafka.keystore.jks" +VALIDITY_IN_DAYS=3650 +DEFAULT_TRUSTSTORE_FILENAME="kafka.truststore.jks" +TRUSTSTORE_WORKING_DIRECTORY="truststore" +KEYSTORE_WORKING_DIRECTORY="keystore" +CA_CERT_FILE="ca-cert" +KEYSTORE_SIGN_REQUEST="cert-file" +KEYSTORE_SIGN_REQUEST_SRL="ca-cert.srl" +KEYSTORE_SIGNED_CERT="cert-signed" + +export COUNTRY=US +export STATE=IL +export ORGANIZATION_UNIT=SE +export CITY=Chicago +export PASSWORD=secret + +COUNTRY=$COUNTRY +STATE=$STATE +OU=$ORGANIZATION_UNIT +CN=kafka0 # COMMON NAME VERIFICATION GOES BRR +LOCATION=$CITY +PASS=$PASSWORD + +function file_exists_and_exit() { + echo "'$1' cannot exist. Move or delete it before" + echo "re-running this script." + exit 1 +} + +if [ -e "$KEYSTORE_WORKING_DIRECTORY" ]; then + file_exists_and_exit $KEYSTORE_WORKING_DIRECTORY +fi + +if [ -e "$CA_CERT_FILE" ]; then + file_exists_and_exit $CA_CERT_FILE +fi + +if [ -e "$KEYSTORE_SIGN_REQUEST" ]; then + file_exists_and_exit $KEYSTORE_SIGN_REQUEST +fi + +if [ -e "$KEYSTORE_SIGN_REQUEST_SRL" ]; then + file_exists_and_exit $KEYSTORE_SIGN_REQUEST_SRL +fi + +if [ -e "$KEYSTORE_SIGNED_CERT" ]; then + file_exists_and_exit $KEYSTORE_SIGNED_CERT +fi + +echo "Welcome to the Kafka SSL keystore and trust store generator script." + +trust_store_file="" +trust_store_private_key_file="" + + if [ -e "$TRUSTSTORE_WORKING_DIRECTORY" ]; then + file_exists_and_exit $TRUSTSTORE_WORKING_DIRECTORY + fi + + mkdir $TRUSTSTORE_WORKING_DIRECTORY + echo + echo "OK, we'll generate a trust store and associated private key." + echo + echo "First, the private key." + echo + + openssl req -new -x509 -keyout $TRUSTSTORE_WORKING_DIRECTORY/ca-key \ + -out $TRUSTSTORE_WORKING_DIRECTORY/ca-cert -days $VALIDITY_IN_DAYS -nodes \ + -subj "/C=$COUNTRY/ST=$STATE/L=$LOCATION/O=$OU/CN=$CN" + + trust_store_private_key_file="$TRUSTSTORE_WORKING_DIRECTORY/ca-key" + + echo + echo "Two files were created:" + echo " - $TRUSTSTORE_WORKING_DIRECTORY/ca-key -- the private key used later to" + echo " sign certificates" + echo " - $TRUSTSTORE_WORKING_DIRECTORY/ca-cert -- the certificate that will be" + echo " stored in the trust store in a moment and serve as the certificate" + echo " authority (CA). Once this certificate has been stored in the trust" + echo " store, it will be deleted. It can be retrieved from the trust store via:" + echo " $ keytool -keystore <trust-store-file> -export -alias CARoot -rfc" + + echo + echo "Now the trust store will be generated from the certificate." + echo + + keytool -keystore $TRUSTSTORE_WORKING_DIRECTORY/$DEFAULT_TRUSTSTORE_FILENAME \ + -alias CARoot -import -file $TRUSTSTORE_WORKING_DIRECTORY/ca-cert \ + -noprompt -dname "C=$COUNTRY, ST=$STATE, L=$LOCATION, O=$OU, CN=$CN" -keypass $PASS -storepass $PASS -storetype JKS + + trust_store_file="$TRUSTSTORE_WORKING_DIRECTORY/$DEFAULT_TRUSTSTORE_FILENAME" + + echo + echo "$TRUSTSTORE_WORKING_DIRECTORY/$DEFAULT_TRUSTSTORE_FILENAME was created." + + # don't need the cert because it's in the trust store. + rm $TRUSTSTORE_WORKING_DIRECTORY/$CA_CERT_FILE + +echo +echo "Continuing with:" +echo " - trust store file: $trust_store_file" +echo " - trust store private key: $trust_store_private_key_file" + +mkdir $KEYSTORE_WORKING_DIRECTORY + +echo +echo "Now, a keystore will be generated. Each broker and logical client needs its own" +echo "keystore. This script will create only one keystore. Run this script multiple" +echo "times for multiple keystores." +echo +echo " NOTE: currently in Kafka, the Common Name (CN) does not need to be the FQDN of" +echo " this host. However, at some point, this may change. As such, make the CN" +echo " the FQDN. Some operating systems call the CN prompt 'first / last name'" + +# To learn more about CNs and FQDNs, read: +# https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/X509ExtendedTrustManager.html + +keytool -keystore $KEYSTORE_WORKING_DIRECTORY/$KEYSTORE_FILENAME \ + -alias localhost -validity $VALIDITY_IN_DAYS -genkey -keyalg RSA \ + -noprompt -dname "C=$COUNTRY, ST=$STATE, L=$LOCATION, O=$OU, CN=$CN" -keypass $PASS -storepass $PASS -storetype JKS + +echo +echo "'$KEYSTORE_WORKING_DIRECTORY/$KEYSTORE_FILENAME' now contains a key pair and a" +echo "self-signed certificate. Again, this keystore can only be used for one broker or" +echo "one logical client. Other brokers or clients need to generate their own keystores." + +echo +echo "Fetching the certificate from the trust store and storing in $CA_CERT_FILE." +echo + +keytool -keystore $trust_store_file -export -alias CARoot -rfc -file $CA_CERT_FILE -keypass $PASS -storepass $PASS + +echo +echo "Now a certificate signing request will be made to the keystore." +echo +keytool -keystore $KEYSTORE_WORKING_DIRECTORY/$KEYSTORE_FILENAME -alias localhost \ + -certreq -file $KEYSTORE_SIGN_REQUEST -keypass $PASS -storepass $PASS + +echo +echo "Now the trust store's private key (CA) will sign the keystore's certificate." +echo +openssl x509 -req -CA $CA_CERT_FILE -CAkey $trust_store_private_key_file \ + -in $KEYSTORE_SIGN_REQUEST -out $KEYSTORE_SIGNED_CERT \ + -days $VALIDITY_IN_DAYS -CAcreateserial +# creates $KEYSTORE_SIGN_REQUEST_SRL which is never used or needed. + +echo +echo "Now the CA will be imported into the keystore." +echo +keytool -keystore $KEYSTORE_WORKING_DIRECTORY/$KEYSTORE_FILENAME -alias CARoot \ + -import -file $CA_CERT_FILE -keypass $PASS -storepass $PASS -noprompt +rm $CA_CERT_FILE # delete the trust store cert because it's stored in the trust store. + +echo +echo "Now the keystore's signed certificate will be imported back into the keystore." +echo +keytool -keystore $KEYSTORE_WORKING_DIRECTORY/$KEYSTORE_FILENAME -alias localhost -import \ + -file $KEYSTORE_SIGNED_CERT -keypass $PASS -storepass $PASS + +echo +echo "All done!" +echo +echo "Deleting intermediate files. They are:" +echo " - '$KEYSTORE_SIGN_REQUEST_SRL': CA serial number" +echo " - '$KEYSTORE_SIGN_REQUEST': the keystore's certificate signing request" +echo " (that was fulfilled)" +echo " - '$KEYSTORE_SIGNED_CERT': the keystore's certificate, signed by the CA, and stored back" +echo " into the keystore" + + rm $KEYSTORE_SIGN_REQUEST_SRL + rm $KEYSTORE_SIGN_REQUEST + rm $KEYSTORE_SIGNED_CERT
null
val
train
2022-02-08T10:42:15
"2022-02-05T22:19:20Z"
iamtechnomage
train
provectus/kafka-ui/1591_1595
provectus/kafka-ui
provectus/kafka-ui/1591
provectus/kafka-ui/1595
[ "timestamp(timedelta=0.0, similarity=1.0000000000000002)" ]
217f0ead0d871205f7a05062cdf56649b8eecc79
95a9047114b499c61e478c584ea14c66d7d8ef3e
[ "Hello there montebove! 👋\n\nThank you and congratulations 🎉 for opening your very first issue in this project! 💖\n\nIn case you want to claim this issue, please comment down below! We will try to get back to you as soon as we can. 👀", "Hi @montebove \r\n\r\n> 2)Modify generated server to create an Internal Load Balancer on AWS EKS\r\n\r\n\r\nDo you mean the service? If so, could you please share the details of the service that you have now after the changes? As yaml file if possible please.", "Here is the service.yaml. With identical modifications works fine on old 2.0 version. I changed extension to .txt because .yaml it's no supported by github\r\n[service.yaml.txt](https://github.com/provectus/kafka-ui/files/8050027/service.yaml.txt)\r\n", "The warning you mentioned itself shouldn't be a problem itself.", "@montebove thank you. Do I understand it correctly: as soon as the load balancer is up, you are trying to access the webui via the load balancer hostname and port 80?", "Exactly, I try to access the webui with the load balancer on port 80 but I get disconnected without receiving a single byte. After this in the pod log I see what I posted before.", "Thank you for the information @montebove! I will try to reproduce the case using the provided information and come back if anything.", "Thank you @5hin0bi . I am available for any following test you need.", "@montebove if you have time we could jump into our discord to discuss the situation in more details. Just let me know if it's OK with you.", "SOLVED:\r\nThere is a problem in the chart but not a real bug. I was using last helm chart version but as Kubernetes download new images only if it is a different version as ifnotpresent is specified I actually used always the old 2.0 version docker image. Forcing deployment to download the image all started to work. The problem originated from the fact I previously, some months ago, installed the 2.0 version and the Helm chart indicated as image version provectuslabs/kafka-ui:latest (at that time 2.0), but after months the new Helm chart asked for the same provectuslabs/kafka-ui:latest and Kubernetes doesn't distinguishes that actually are not the same. I would suggest to use an explicit docker image version in Helm chart something like for the current version provectuslabs/kafka-ui:0.3.3", "@montebove thank you for the info. Glad it works. We'll take a look." ]
[]
"2022-02-13T09:58:42Z"
[ "type/bug", "status/accepted", "scope/k8s" ]
Specify distinct image tag version for helm chart
**Describe the bug** Trying to upgrade to last 3.3 version after the kafka-ui started, when trying to access to the Web UI I get immediately disconnected and in containers log I see these lines: `15:45:34.875 [parallel-1] DEBUG com.provectus.kafka.ui.service.MetricsUpdateService - Start getting metrics for kafkaCluster: strimzi 15:45:55.587 [boundedElastic-1] WARN com.provectus.kafka.ui.exception.ErrorCode - Multiple class com.provectus.kafka.ui.exception.ErrorCode values refer to code 4001 15:45:55.708 [boundedElastic-2] DEBUG org.springframework.http.codec.json.Jackson2JsonEncoder - [694106d4] Encoding [class ErrorResponse { code: 5000 message: 404 NOT_FOUND timestamp: 1644594355588 req (truncated)...] 15:45:55.709 [boundedElastic-1] DEBUG org.springframework.http.codec.json.Jackson2JsonEncoder - [cfe32b23] Encoding [class ErrorResponse { code: 5000 message: 404 NOT_FOUND timestamp: 1644594355588 req (truncated)...] 15:46:04.875 [parallel-1] DEBUG com.provectus.kafka.ui.service.MetricsUpdateService - Start getting metrics for kafkaCluster: strimzi` After few minutes containers restart because probing fails. The old kafka-ui 2.0 version works fine on the same Kubernetes. **Set up** version 0.3.3 Kubernetes 1.21 on Amazon EKS **Steps to Reproduce** 1)Install last version with Helm chart 2)Modify generated server to create an Internal Load Balancer on AWS EKS 3)try to access to the Web UI **Expected behavior** I can access the UI
[ ".github/workflows/release.yaml", "charts/kafka-ui/values.yaml" ]
[ ".github/workflows/release.yaml", "charts/kafka-ui/values.yaml" ]
[]
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index a88c7d05d81..12c11a771d2 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -109,6 +109,7 @@ jobs: run: | export version=${{needs.release.outputs.version}} sed -i "s/version:.*/version: ${version}/" charts/kafka-ui/Chart.yaml + sed -i "s/appVersion:.*/appVersion: ${version}/" charts/kafka-ui/Chart.yaml - name: add chart run: | diff --git a/charts/kafka-ui/values.yaml b/charts/kafka-ui/values.yaml index 3fc0754aff5..43cbf869f6b 100644 --- a/charts/kafka-ui/values.yaml +++ b/charts/kafka-ui/values.yaml @@ -5,7 +5,7 @@ image: repository: provectuslabs/kafka-ui pullPolicy: IfNotPresent # Overrides the image tag whose default is the chart appVersion. - tag: "latest" + tag: "" imagePullSecrets: [] nameOverride: ""
null
val
train
2022-02-13T12:08:37
"2022-02-11T15:57:21Z"
montebove
train
provectus/kafka-ui/1604_1605
provectus/kafka-ui
provectus/kafka-ui/1604
provectus/kafka-ui/1605
[ "timestamp(timedelta=1.0, similarity=0.9517366317775952)" ]
4862687956ad7880332d26aecc047064a524b0e9
da27d3c844373cfb61ee78a4047311d9a592d91e
[]
[]
"2022-02-15T08:25:14Z"
[ "type/bug", "status/accepted", "status/confirmed", "scope/infrastructure" ]
Fix release and tag naming
Need to name release and tag as it was previously. ``` Release name: 0.3.2 Tag name: v0.3.2 ```
[ ".github/release_drafter.yaml" ]
[ ".github/release_drafter.yaml" ]
[]
diff --git a/.github/release_drafter.yaml b/.github/release_drafter.yaml index 21ad76787bc..952d2b5d905 100644 --- a/.github/release_drafter.yaml +++ b/.github/release_drafter.yaml @@ -1,5 +1,5 @@ -name-template: 'v$RESOLVED_VERSION' -tag-template: '$RESOLVED_VERSION' +name-template: '$RESOLVED_VERSION' +tag-template: 'v$RESOLVED_VERSION' template: | ## Changes $CHANGES
null
test
train
2022-02-15T12:01:40
"2022-02-15T08:22:21Z"
5hin0bi
train
provectus/kafka-ui/1606_1607
provectus/kafka-ui
provectus/kafka-ui/1606
provectus/kafka-ui/1607
[ "timestamp(timedelta=0.0, similarity=0.9492560378155623)" ]
ce8627ea59be60367c3d824375dd3feca6f8479a
4862687956ad7880332d26aecc047064a524b0e9
[]
[]
"2022-02-15T10:15:31Z"
[ "type/bug", "status/accepted", "status/confirmed", "scope/infrastructure" ]
[Bug] Fix workflow for documentation
Documentation is not triggered due to incorrect path filters. Need to fix.
[ ".github/workflows/documentation.yaml" ]
[ ".github/workflows/documentation.yaml" ]
[]
diff --git a/.github/workflows/documentation.yaml b/.github/workflows/documentation.yaml index 2a1171394dc..464af01fe80 100644 --- a/.github/workflows/documentation.yaml +++ b/.github/workflows/documentation.yaml @@ -7,8 +7,8 @@ on: - reopened - synchronize paths: - - 'documentation/*' - - './*.md' + - 'documentation/**' + - '**.md' jobs: build-and-test: runs-on: ubuntu-latest
null
test
train
2022-02-14T19:26:51
"2022-02-15T10:13:03Z"
5hin0bi
train
provectus/kafka-ui/1608_1645
provectus/kafka-ui
provectus/kafka-ui/1608
provectus/kafka-ui/1645
[ "timestamp(timedelta=0.0, similarity=0.8484217522077585)" ]
8125814eed049c2f91f53c140b5f9221d8a45bd4
b8761b500de0609a2e1fe94f6f47151a6f4b7722
[]
[]
"2022-02-21T10:43:31Z"
[ "status/accepted", "scope/infrastructure", "type/feature" ]
[Feature] Add workflow to check workflows in .github/workflows/**
Currently we have required job build-and-test for different paths that pull requests affect. However, we lack the job for changes in workflows path and merges are possible only with admin privileges. The task is to add the workflow that will contain build-and-test job for changes in .github/workflows/** path.
[ ".github/workflows/aws_publisher.yaml", ".github/workflows/helm.yaml", ".github/workflows/release_drafter.yml", ".github/workflows/welcome-first-time-contributors.yml" ]
[ ".github/workflows/aws_publisher.yaml", ".github/workflows/helm.yaml", ".github/workflows/release_drafter.yml", ".github/workflows/welcome-first-time-contributors.yml", ".github/workflows/workflow_linter.yaml" ]
[]
diff --git a/.github/workflows/aws_publisher.yaml b/.github/workflows/aws_publisher.yaml index 052f4e8ed9e..39468d4dde3 100644 --- a/.github/workflows/aws_publisher.yaml +++ b/.github/workflows/aws_publisher.yaml @@ -48,4 +48,4 @@ jobs: arguments: "-color=false -on-error=abort -var=kafka_ui_release_version=${{ github.event.inputs.KafkaUIReleaseVersion }}" target: kafka-ui-infra/ami/kafka-ui.pkr.hcl env: - PACKER_LOG: 1 \ No newline at end of file + PACKER_LOG: 1 diff --git a/.github/workflows/helm.yaml b/.github/workflows/helm.yaml index 18abec82f01..b11f7ccc2e1 100644 --- a/.github/workflows/helm.yaml +++ b/.github/workflows/helm.yaml @@ -26,7 +26,7 @@ jobs: echo "NEXT K8S VERSIONS ARE GOING TO BE TESTED: $K8S_VERSIONS" echo "" for version in $K8S_VERSIONS - do + do echo $version; helm template charts/kafka-ui -f charts/kafka-ui/values.yaml | kubeval --additional-schema-locations https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master --strict -v $version; done diff --git a/.github/workflows/release_drafter.yml b/.github/workflows/release_drafter.yml index 89b1779ffcb..742254b942e 100644 --- a/.github/workflows/release_drafter.yml +++ b/.github/workflows/release_drafter.yml @@ -16,4 +16,4 @@ jobs: config-name: release_drafter.yaml disable-autolabeler: true env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/welcome-first-time-contributors.yml b/.github/workflows/welcome-first-time-contributors.yml index f0caa2053e1..b0258c9235b 100644 --- a/.github/workflows/welcome-first-time-contributors.yml +++ b/.github/workflows/welcome-first-time-contributors.yml @@ -21,7 +21,7 @@ jobs: Thank you and congratulations 🎉 for opening your very first issue in this project! 💖 In case you want to claim this issue, please comment down below! We will try to get back to you as soon as we can. 👀 - + pr-message: | Hello there ${{ github.actor }}! 👋 diff --git a/.github/workflows/workflow_linter.yaml b/.github/workflows/workflow_linter.yaml new file mode 100644 index 00000000000..92012e77455 --- /dev/null +++ b/.github/workflows/workflow_linter.yaml @@ -0,0 +1,22 @@ +name: "Workflow linter" +on: + pull_request: + types: + - "opened" + - "reopened" + - "synchronize" + - "edited" + paths: + - ".github/workflows/**" +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} + - name: Install yamllint + run: sudo apt install -y yamllint + - name: Validate workflow yaml files + run: yamllint .github/workflows/. -d relaxed -f github --no-warnings
null
train
train
2022-02-21T10:40:06
"2022-02-15T10:48:46Z"
5hin0bi
train
provectus/kafka-ui/1615_1617
provectus/kafka-ui
provectus/kafka-ui/1615
provectus/kafka-ui/1617
[ "timestamp(timedelta=0.0, similarity=0.9267386712500169)" ]
c3d44c95c27826a7cc6275cf6ae58411097efb8f
6428cbef4a2948748fd58eec3dbc764aa713d527
[]
[]
"2022-02-16T15:21:54Z"
[ "type/bug", "scope/infrastructure" ]
[Bug] fix sonar scans
Sonar scans were broken after recent workflow updates. Need to fix it.
[ ".github/workflows/backend.yml", ".github/workflows/e2e-checks.yaml", ".github/workflows/frontend.yaml", ".github/workflows/pr-checks.yaml", "kafka-ui-react-app/sonar-project.properties" ]
[ ".github/workflows/backend.yml", ".github/workflows/e2e-checks.yaml", ".github/workflows/frontend.yaml", ".github/workflows/pr-checks.yaml", "kafka-ui-react-app/sonar-project.properties" ]
[]
diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 573f1b08ac7..4cebf3557cb 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -1,13 +1,20 @@ name: backend on: + push: + branches: + - master pull_request_target: - types: ['opened', 'edited', 'reopened', 'synchronize'] + types: ["opened", "edited", "reopened", "synchronize"] paths: - - 'kafka-ui-api/**' + - "kafka-ui-api/**" jobs: build-and-test: runs-on: ubuntu-latest steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} - name: Cache local Maven repository uses: actions/cache@v2 with: @@ -15,11 +22,6 @@ jobs: key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - - uses: actions/checkout@v2 - - name: compose app - id: step_five - run: | - docker-compose -f ./documentation/compose/kafka-ui.yaml up -d - name: Set up JDK 1.13 uses: actions/setup-java@v1 with: @@ -30,9 +32,24 @@ jobs: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - - name: Build and analyze + - name: Build and analyze pull request target + if: ${{ github.event_name == 'pull_request_target' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN_BACKEND }} + run: | + mvn versions:set -DnewVersion=${{ github.event.pull_request.head.sha }} + mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ + -Dsonar.projectKey=com.provectus:kafka-ui_backend \ + -Dsonar.pullrequest.key=${{ github.event.pull_request.number }} \ + -Dsonar.pullrequest.branch=${{ github.head_ref }} \ + -Dsonar.pullrequest.base=${{ github.base_ref }} + - name: Build and analyze push master + if: ${{ github.event_name == 'push' }} env: - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN_BACKEND }} run: | mvn versions:set -DnewVersion=$GITHUB_SHA - mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar + mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ + -Dsonar.projectKey=com.provectus:kafka-ui_backend diff --git a/.github/workflows/e2e-checks.yaml b/.github/workflows/e2e-checks.yaml index 9145b32ca6d..832b07c85c8 100644 --- a/.github/workflows/e2e-checks.yaml +++ b/.github/workflows/e2e-checks.yaml @@ -1,16 +1,19 @@ name: e2e-checks on: pull_request_target: - types: [ 'opened', 'edited', 'reopened', 'synchronize' ] + types: ["opened", "edited", "reopened", "synchronize"] paths: - - 'kafka-ui-api/**' - - 'kafka-ui-contract/**' - - 'kafka-ui-react-app/**' - - 'kafka-ui-e2e-checks/**' + - "kafka-ui-api/**" + - "kafka-ui-contract/**" + - "kafka-ui-react-app/**" + - "kafka-ui-e2e-checks/**" jobs: build-and-test: runs-on: ubuntu-latest steps: + - uses: actions/checkout@v2 + with: + ref: ${{ github.event.pull_request.head.sha }} - name: Cache local Maven repository uses: actions/cache@v2 with: @@ -18,7 +21,6 @@ jobs: key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - - uses: actions/checkout@v2 - name: Set the values id: set_env_values run: | @@ -34,7 +36,7 @@ jobs: - name: Build with Maven id: build_app run: | - mvn versions:set -DnewVersion=$GITHUB_SHA + mvn versions:set -DnewVersion=${{ github.event.pull_request.head.sha }} mvn clean package -DskipTests ${{ github.event.inputs.extraMavenOptions }} - name: compose app id: compose_app @@ -43,7 +45,7 @@ jobs: docker-compose -f ./documentation/compose/kafka-ui-connectors.yaml up -d - name: e2e run run: | - mvn versions:set -DnewVersion=$GITHUB_SHA + mvn versions:set -DnewVersion=${{ github.event.pull_request.head.sha }} mvn -pl '!kafka-ui-api' test -Pprod - name: Generate allure report uses: simple-elf/allure-report-action@master @@ -67,8 +69,8 @@ jobs: uses: Sibz/[email protected] with: authToken: ${{secrets.GITHUB_TOKEN}} - context: 'Test report' - state: 'success' + context: "Test report" + state: "success" sha: ${{ github.event.pull_request.head.sha || github.sha }} target_url: https://${{ github.repository_owner }}.github.io/kafka-ui/allure/allure-results/${{ github.run_number }} - name: Dump docker logs on failure diff --git a/.github/workflows/frontend.yaml b/.github/workflows/frontend.yaml index 631981d1ed9..7dd97ebea7a 100644 --- a/.github/workflows/frontend.yaml +++ b/.github/workflows/frontend.yaml @@ -4,10 +4,10 @@ on: branches: - master pull_request_target: - types: ['opened', 'edited', 'reopened', 'synchronize'] + types: ["opened", "edited", "reopened", "synchronize"] paths: - - 'kafka-ui-contract/**' - - 'kafka-ui-react-app/**' + - "kafka-ui-contract/**" + - "kafka-ui-react-app/**" jobs: build-and-test: env: @@ -15,41 +15,43 @@ jobs: NODE_ENV: dev runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - with: - # Disabling shallow clone is recommended for improving relevancy of reporting - fetch-depth: 0 - - name: Use Node.js - uses: actions/setup-node@v1 - with: - node-version: "14" - - name: Cache node dependency - uses: actions/cache@v1 - with: - path: kafka-ui-react-app/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-node- - - name: Install Node dependencies - run: | - cd kafka-ui-react-app/ - npm install - - name: Generate sources - run: | - cd kafka-ui-react-app/ - npm run gen:sources - - name: Linter - run: | - cd kafka-ui-react-app/ - npm run lint - - name: Tests - run: | - cd kafka-ui-react-app/ - npm run test:CI - - name: SonarCloud Scan - uses: workshur/sonarcloud-github-action@improved_basedir - with: - projectBaseDir: ./kafka-ui-react-app - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN_FRONTEND }} + - uses: actions/checkout@v2 + with: + # Disabling shallow clone is recommended for improving relevancy of reporting + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} + - name: Use Node.js + uses: actions/setup-node@v1 + with: + node-version: "14" + - name: Cache node dependency + uses: actions/cache@v1 + with: + path: kafka-ui-react-app/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + - name: Install Node dependencies + run: | + cd kafka-ui-react-app/ + npm install + - name: Generate sources + run: | + cd kafka-ui-react-app/ + npm run gen:sources + - name: Linter + run: | + cd kafka-ui-react-app/ + npm run lint + - name: Tests + run: | + cd kafka-ui-react-app/ + npm run test:CI + - name: SonarCloud Scan + uses: workshur/sonarcloud-github-action@improved_basedir + with: + projectBaseDir: ./kafka-ui-react-app + args: -Dsonar.pullrequest.key=${{ github.event.pull_request.number }} -Dsonar.pullrequest.branch=${{ github.head_ref }} -Dsonar.pullrequest.base=${{ github.base_ref }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN_FRONTEND }} diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 48b47c5196f..74ff75b833d 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -1,7 +1,7 @@ -name: 'PR Checklist checked' +name: "PR Checklist checked" on: pull_request_target: - types: [opened, edited, synchronized, reopened] + types: [opened, edited, synchronize, reopened] jobs: task-check: @@ -12,4 +12,4 @@ jobs: repo-token: "${{ secrets.GITHUB_TOKEN }}" - uses: dekinderfiets/[email protected] with: - repo-token: '${{ secrets.GITHUB_TOKEN }}' + repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/kafka-ui-react-app/sonar-project.properties b/kafka-ui-react-app/sonar-project.properties index ecab3f4713a..2275c2e2383 100644 --- a/kafka-ui-react-app/sonar-project.properties +++ b/kafka-ui-react-app/sonar-project.properties @@ -1,4 +1,4 @@ -sonar.projectKey=provectus_kafka-ui_frontend +sonar.projectKey=com.provectus:kafka-ui_frontend sonar.organization=provectus sonar.sources=.
null
train
train
2022-02-16T15:58:36
"2022-02-16T13:47:28Z"
5hin0bi
train
provectus/kafka-ui/1625_1634
provectus/kafka-ui
provectus/kafka-ui/1625
provectus/kafka-ui/1634
[ "timestamp(timedelta=0.0, similarity=0.9640426703985836)" ]
efb8410bd631dbd3f3ffab4f532c8e0d5445660e
25d00988ad1e9d4f5acb7087afee144f2ce6e91b
[]
[]
"2022-02-18T08:37:14Z"
[ "type/bug", "status/accepted", "status/confirmed", "scope/infrastructure" ]
Trigger backend workflow if pom.xml in the repo root is changed
pom.xml mvnw? mvnw.cmd?
[ ".github/workflows/backend.yml", ".github/workflows/e2e-checks.yaml" ]
[ ".github/workflows/backend.yml", ".github/workflows/e2e-checks.yaml" ]
[]
diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 4cebf3557cb..73663a5392b 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -7,6 +7,7 @@ on: types: ["opened", "edited", "reopened", "synchronize"] paths: - "kafka-ui-api/**" + - "pom.xml" jobs: build-and-test: runs-on: ubuntu-latest diff --git a/.github/workflows/e2e-checks.yaml b/.github/workflows/e2e-checks.yaml index 832b07c85c8..00581514dfb 100644 --- a/.github/workflows/e2e-checks.yaml +++ b/.github/workflows/e2e-checks.yaml @@ -7,6 +7,7 @@ on: - "kafka-ui-contract/**" - "kafka-ui-react-app/**" - "kafka-ui-e2e-checks/**" + - "pom.xml" jobs: build-and-test: runs-on: ubuntu-latest
null
val
train
2022-02-17T17:26:15
"2022-02-17T16:44:26Z"
5hin0bi
train
provectus/kafka-ui/1661_1681
provectus/kafka-ui
provectus/kafka-ui/1661
provectus/kafka-ui/1681
[ "timestamp(timedelta=0.0, similarity=0.8415795965537826)" ]
fd7ba5e1958966423e0966fcf1ac25f66ce61429
04fbd05d117ef54083e33631d9a8fec4beb32745
[]
[]
"2022-02-25T11:42:52Z"
[ "scope/infrastructure" ]
Implement a workflow for periodic CVE scanning
With a manual run so far. #1656 #1240
[]
[ ".github/workflows/cve.yaml" ]
[]
diff --git a/.github/workflows/cve.yaml b/.github/workflows/cve.yaml new file mode 100644 index 00000000000..8a8c2ac09ed --- /dev/null +++ b/.github/workflows/cve.yaml @@ -0,0 +1,68 @@ +name: CVE checks docker master +on: + workflow_dispatch: + schedule: + # * is a special character in YAML so you have to quote this string + - cron: '0 8 15 * *' +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Set up JDK 1.13 + uses: actions/setup-java@v1 + with: + java-version: 1.13 + + - name: Build project + id: build + run: | + mvn versions:set -DnewVersion=$GITHUB_SHA + mvn clean package -DskipTests + export VERSION=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec) + echo "::set-output name=version::${VERSION}" + + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: Cache Docker layers + uses: actions/cache@v2 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + - name: Build docker image + uses: docker/build-push-action@v2 + with: + builder: ${{ steps.buildx.outputs.name }} + context: kafka-ui-api + platforms: linux/amd64 + push: false + load: true + tags: | + provectuslabs/kafka-ui:${{ steps.build.outputs.version }} + build-args: | + JAR_FILE=kafka-ui-api-${{ steps.build.outputs.version }}.jar + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache + + - name: Run CVE checks + uses: aquasecurity/[email protected] + with: + image-ref: "provectuslabs/kafka-ui:${{ steps.build.outputs.version }}" + format: "table" + exit-code: "1"
null
test
train
2022-02-25T08:18:14
"2022-02-22T15:46:05Z"
Haarolean
train
provectus/kafka-ui/1961_2011
provectus/kafka-ui
provectus/kafka-ui/1961
provectus/kafka-ui/2011
[ "timestamp(timedelta=71.0, similarity=0.9106017175741157)" ]
8393232a8301277fd397b5910134dc2a754fda52
99e2663c24303c2a3319b770070ed081de961eba
[]
[]
"2022-05-23T07:06:24Z"
[ "scope/frontend", "type/refactoring", "status/accepted", "type/chore" ]
Upgrade react-router-dom to v6
### Is your proposal related to a problem? App uses legacy version of react-router-dom ### Describe the solution you'd like Please follow instruction from https://reactrouter.com/docs/en/v6/upgrading/v5
[ "kafka-ui-react-app/package-lock.json", "kafka-ui-react-app/package.json" ]
[ "kafka-ui-react-app/package-lock.json", "kafka-ui-react-app/package.json" ]
[]
diff --git a/kafka-ui-react-app/package-lock.json b/kafka-ui-react-app/package-lock.json index afff9bf5238..b177a59b33d 100644 --- a/kafka-ui-react-app/package-lock.json +++ b/kafka-ui-react-app/package-lock.json @@ -36,7 +36,7 @@ "react-multi-select-component": "^4.0.6", "react-redux": "^7.2.6", "react-router": "^5.2.0", - "react-router-dom": "^5.3.1", + "react-router-dom": "^6.3.0", "redux": "^4.1.1", "redux-thunk": "^2.3.0", "sass": "^1.43.4", @@ -16158,7 +16158,6 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/history/-/history-5.3.0.tgz", "integrity": "sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==", - "dev": true, "dependencies": { "@babel/runtime": "^7.7.6" } @@ -24876,53 +24875,27 @@ } }, "node_modules/react-router-dom": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.3.1.tgz", - "integrity": "sha512-f0pj/gMAbv9e8gahTmCEY20oFhxhrmHwYeIwH5EO5xu0qme+wXtsdB8YfUOAZzUz4VaXmb58m3ceiLtjMhqYmQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.3.0.tgz", + "integrity": "sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw==", "dependencies": { - "@babel/runtime": "^7.12.13", - "history": "^4.9.0", - "loose-envify": "^1.3.1", - "prop-types": "^15.6.2", - "react-router": "5.3.1", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0" + "history": "^5.2.0", + "react-router": "6.3.0" }, "peerDependencies": { - "react": ">=15" - } - }, - "node_modules/react-router-dom/node_modules/history": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz", - "integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==", - "dependencies": { - "@babel/runtime": "^7.1.2", - "loose-envify": "^1.2.0", - "resolve-pathname": "^3.0.0", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0", - "value-equal": "^1.0.1" + "react": ">=16.8", + "react-dom": ">=16.8" } }, "node_modules/react-router-dom/node_modules/react-router": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-5.3.1.tgz", - "integrity": "sha512-v+zwjqb7bakqgF+wMVKlAPTca/cEmPOvQ9zt7gpSNyPXau1+0qvuYZ5BWzzNDP1y6s15zDwgb9rPN63+SIniRQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.3.0.tgz", + "integrity": "sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==", "dependencies": { - "@babel/runtime": "^7.12.13", - "history": "^4.9.0", - "hoist-non-react-statics": "^3.1.0", - "loose-envify": "^1.3.1", - "mini-create-react-context": "^0.4.0", - "path-to-regexp": "^1.7.0", - "prop-types": "^15.6.2", - "react-is": "^16.6.0", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0" + "history": "^5.2.0" }, "peerDependencies": { - "react": ">=15" + "react": ">=16.8" } }, "node_modules/react-router/node_modules/history": { @@ -40798,7 +40771,6 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/history/-/history-5.3.0.tgz", "integrity": "sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==", - "dev": true, "requires": { "@babel/runtime": "^7.7.6" } @@ -47342,47 +47314,20 @@ } }, "react-router-dom": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.3.1.tgz", - "integrity": "sha512-f0pj/gMAbv9e8gahTmCEY20oFhxhrmHwYeIwH5EO5xu0qme+wXtsdB8YfUOAZzUz4VaXmb58m3ceiLtjMhqYmQ==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.3.0.tgz", + "integrity": "sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw==", "requires": { - "@babel/runtime": "^7.12.13", - "history": "^4.9.0", - "loose-envify": "^1.3.1", - "prop-types": "^15.6.2", - "react-router": "5.3.1", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0" + "history": "^5.2.0", + "react-router": "6.3.0" }, "dependencies": { - "history": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz", - "integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==", - "requires": { - "@babel/runtime": "^7.1.2", - "loose-envify": "^1.2.0", - "resolve-pathname": "^3.0.0", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0", - "value-equal": "^1.0.1" - } - }, "react-router": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-5.3.1.tgz", - "integrity": "sha512-v+zwjqb7bakqgF+wMVKlAPTca/cEmPOvQ9zt7gpSNyPXau1+0qvuYZ5BWzzNDP1y6s15zDwgb9rPN63+SIniRQ==", - "requires": { - "@babel/runtime": "^7.12.13", - "history": "^4.9.0", - "hoist-non-react-statics": "^3.1.0", - "loose-envify": "^1.3.1", - "mini-create-react-context": "^0.4.0", - "path-to-regexp": "^1.7.0", - "prop-types": "^15.6.2", - "react-is": "^16.6.0", - "tiny-invariant": "^1.0.2", - "tiny-warning": "^1.0.0" + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.3.0.tgz", + "integrity": "sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==", + "requires": { + "history": "^5.2.0" } } } diff --git a/kafka-ui-react-app/package.json b/kafka-ui-react-app/package.json index 9c7c6490329..7f01e4a5e01 100644 --- a/kafka-ui-react-app/package.json +++ b/kafka-ui-react-app/package.json @@ -32,7 +32,7 @@ "react-multi-select-component": "^4.0.6", "react-redux": "^7.2.6", "react-router": "^5.2.0", - "react-router-dom": "^5.3.1", + "react-router-dom": "^6.3.0", "redux": "^4.1.1", "redux-thunk": "^2.3.0", "sass": "^1.43.4",
null
val
train
2022-05-27T12:29:54
"2022-05-12T11:07:46Z"
workshur
train
provectus/kafka-ui/2287_2396
provectus/kafka-ui
provectus/kafka-ui/2287
provectus/kafka-ui/2396
[ "timestamp(timedelta=8499.0, similarity=0.8878472267011186)" ]
edb7da6fce83e149b9e9c34182708f17f1c1240c
b1bcf3061341af472e4c1f99e548320902667629
[ "is not actual as we agreed with the team due to useless of Steps class on current framework stage" ]
[]
"2022-08-04T13:32:58Z"
[ "type/enhancement", "scope/QA", "status/accepted" ]
[e2e] Prepare steps for topic
create a separate Class with steps src/test/java/com/provectus/kafka/ui/steps/kafka (TopicSteps.java) 1. create steps such createTopic, deleteTopic, isTopicExist etc See tests that should be automated https://docs.google.com/spreadsheets/d/1Vf6yZSqCYwh33t-pTy1PiYewk-jFSfPZppzIuUVVyO0/edit#gid=0 2. Remove all sleeps, if needed to some wait, all asserts should be in test Refactor test class src/test/java/com/provectus/kafka/ui/tests/TopicTests.java with new steps
[ "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java", "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java", "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java" ]
[ "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java", "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java", "kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java" ]
[ "kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/steps/kafka/TopicSteps.java", "kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/tests/TopicTests.java" ]
diff --git a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java index bd6bc8fc0de..b22821db44a 100644 --- a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java +++ b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicCreateEditSettingsView.java @@ -21,7 +21,7 @@ public TopicCreateEditSettingsView setTopicName(String topicName) { } public TopicCreateEditSettingsView setMinInsyncReplicas(Integer minInsyncReplicas) { - $("input[name=minInsyncReplicas]").setValue(minInsyncReplicas.toString()); + $("input[name=minInSyncReplicas]").setValue(minInsyncReplicas.toString()); return this; } diff --git a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java index a71d49e0f51..46e9d130ba5 100644 --- a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java +++ b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicView.java @@ -30,8 +30,8 @@ public TopicView goTo(String cluster, String topic) { @Step public TopicView isOnTopicViewPage() { - $(By.linkText("Overview")).shouldBe(Condition.visible); - return this; + $(By.linkText("Overview")).shouldBe(Condition.visible); + return this; } @SneakyThrows diff --git a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java index cfd120f3a01..82a5bd37028 100644 --- a/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java +++ b/kafka-ui-e2e-checks/src/main/java/com/provectus/kafka/ui/pages/topic/TopicsList.java @@ -3,8 +3,8 @@ import com.codeborne.selenide.CollectionCondition; import com.codeborne.selenide.Condition; import com.codeborne.selenide.Selenide; -import com.provectus.kafka.ui.helpers.TestConfiguration; import com.provectus.kafka.ui.extensions.WaitUtils; +import com.provectus.kafka.ui.helpers.TestConfiguration; import com.provectus.kafka.ui.utils.BrowserUtils; import io.qameta.allure.Step; import lombok.SneakyThrows; @@ -32,18 +32,17 @@ public TopicsList isOnPage() { } @Step - public TopicCreateEditSettingsView pressCreateNewTopic(){ + public TopicCreateEditSettingsView pressCreateNewTopic() { BrowserUtils.javaExecutorClick($x("//button[normalize-space(text()) ='Add a Topic']")); return new TopicCreateEditSettingsView(); } @Step - public TopicsList isTopicVisible(String topicName) { - $$("tbody td>a") + public boolean isTopicVisible(String topicName) { + return $$("tbody td>a") .shouldBe(CollectionCondition.sizeGreaterThan(4)) .find(Condition.exactText(topicName)) - .shouldBe(Condition.visible); - return this; + .is(Condition.visible); } @SneakyThrows @@ -53,12 +52,8 @@ public TopicView openTopic(String topicName) { } @SneakyThrows - public TopicsList isTopicNotVisible(String topicName) { - $$x("//table/tbody/tr/td[2]") - .shouldBe(CollectionCondition.sizeGreaterThanOrEqual(4)) - .find(Condition.exactText(topicName)) - .shouldBe(Condition.not(Condition.visible)); - return this; + public boolean isTopicNotVisible(String topicName) { + return $$x("//table/tbody/tr/td[2]") + .find(Condition.exactText(topicName)).is(Condition.visible); } - }
diff --git a/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/steps/kafka/TopicSteps.java b/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/steps/kafka/TopicSteps.java new file mode 100644 index 00000000000..d179c33e5bb --- /dev/null +++ b/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/steps/kafka/TopicSteps.java @@ -0,0 +1,106 @@ +package com.provectus.kafka.ui.steps.kafka; + +import com.provectus.kafka.ui.pages.Pages; +import com.provectus.kafka.ui.pages.topic.TopicView; +import com.provectus.kafka.ui.pages.topic.TopicsList; +import io.qameta.allure.Step; +import lombok.SneakyThrows; + +import static org.apache.kafka.common.utils.Utils.readFileAsString; + +public class TopicSteps extends Pages { + private static final TopicSteps INSTANSE = new TopicSteps(); + + @Step("Create new topic") + public static TopicSteps createNewTopic(String topicName) { + new TopicsList().pressCreateNewTopic() + .setTopicName(topicName) + .sendData(); + return INSTANSE; + } + + @Step("Open topic list") + public static TopicSteps openTopicList(String topicName) { + new TopicsList().openTopic(topicName); + return INSTANSE; + } + + @Step("Update topic") + public static TopicSteps updateTopic(String topicName, String policyValue, String timeToRetainValue, String maxSizeOnDisk, String MaxMessageBytes) { + new TopicsList().openTopic(topicName) + .isOnTopicViewPage() + .openEditSettings() + .selectCleanupPolicy(policyValue) + .setMinInsyncReplicas(10) + .setTimeToRetainDataInMs(timeToRetainValue) + .setMaxSizeOnDiskInGB(maxSizeOnDisk) + .setMaxMessageBytes(MaxMessageBytes) + .sendData() + .isOnTopicViewPage(); + return INSTANSE; + } + + @SneakyThrows + @Step("Produce message") + public static TopicSteps produceMessage(String topicName, String contentMessage, String keyMessage) { + new TopicsList().openTopic(topicName) + .openTopicMenu(TopicView.TopicMenu.MESSAGES) + .clickOnButton("Produce Message") + .setContentFiled(readFileAsString(contentMessage)) + .setKeyField(readFileAsString(keyMessage)) + .submitProduceMessage(); + return INSTANSE; + } + + + @Step("Delete topic") + public static TopicSteps deleteTopic(String topicName) { + new TopicsList().openTopic(topicName) + .isOnTopicViewPage() + .deleteTopic(); + return INSTANSE; + } + + + @Step("Is on topic view page") + public TopicView isOnTopicViewPage() { + return INSTANSE.topicView.isOnTopicViewPage(); + + } + + @Step("Is on page") + public TopicsList isOnPage() { + return topicsList.isOnPage(); + } + + @Step("Is key message visible") + public static boolean isKeyMessageVisible(String messageText) { + return new TopicView().isKeyMessageVisible(messageText); + } + + @Step("Is content message visible") + public static boolean isContentMessageVisible(String contentText) { + return new TopicView().isContentMessageVisible(contentText); + } + + + @Step("Is topic not visible") + public static boolean isTopicNotVisible(String topicName) { + return new TopicsList().isTopicNotVisible(topicName); + + } + + + @Step("Is topic visible in the list") + public static boolean IsTopicVisible(String topicName) { + return new TopicsList().isTopicVisible(topicName); + } + + +} + + + + + + diff --git a/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/tests/TopicTests.java b/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/tests/TopicTests.java index a962b8ceabb..260c23146ed 100644 --- a/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/tests/TopicTests.java +++ b/kafka-ui-e2e-checks/src/test/java/com/provectus/kafka/ui/tests/TopicTests.java @@ -3,7 +3,7 @@ import com.provectus.kafka.ui.base.BaseTest; import com.provectus.kafka.ui.helpers.Helpers; import com.provectus.kafka.ui.pages.MainPage; -import com.provectus.kafka.ui.pages.topic.TopicView; +import com.provectus.kafka.ui.steps.kafka.TopicSteps; import com.provectus.kafka.ui.utils.qaseIO.Status; import com.provectus.kafka.ui.utils.qaseIO.annotation.AutomationStatus; import com.provectus.kafka.ui.utils.qaseIO.annotation.Suite; @@ -52,20 +52,14 @@ public static void afterAll() { public void createTopic() { pages.open() .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS); - pages.topicsList.pressCreateNewTopic() - .setTopicName(NEW_TOPIC) - .sendData() + TopicSteps.createNewTopic(NEW_TOPIC) .isOnTopicViewPage(); pages.open() - .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS) - .topicIsVisible(NEW_TOPIC); - helpers.apiHelper.deleteTopic(SECOND_LOCAL, NEW_TOPIC); - pages.open() - .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS) - .topicIsNotVisible(NEW_TOPIC); + .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS); + Assertions.assertTrue(TopicSteps.IsTopicVisible(NEW_TOPIC)); } - @Disabled("Due to issue https://github.com/provectus/kafka-ui/issues/1500 ignore this test") + @SneakyThrows @DisplayName("should update a topic") @Issue("1500") @@ -74,28 +68,9 @@ public void createTopic() { @CaseId(197) @Test public void updateTopic() { - pages.openTopicsList(SECOND_LOCAL) - .isOnPage(); - pages.openTopicView(SECOND_LOCAL, TOPIC_TO_UPDATE) - .isOnTopicViewPage() - .openEditSettings() - .selectCleanupPolicy(COMPACT_POLICY_VALUE) - .setMinInsyncReplicas(10) - .setTimeToRetainDataInMs(UPDATED_TIME_TO_RETAIN_VALUE) - .setMaxSizeOnDiskInGB(UPDATED_MAX_SIZE_ON_DISK) - .setMaxMessageBytes(UPDATED_MAX_MESSAGE_BYTES) - .sendData() - .isOnTopicViewPage(); - - pages.openTopicsList(SECOND_LOCAL) - .isOnPage(); - pages.openTopicView(SECOND_LOCAL, TOPIC_TO_UPDATE) - .openEditSettings() - // Assertions - .cleanupPolicyIs(COMPACT_POLICY_VALUE) - .timeToRetainIs(UPDATED_TIME_TO_RETAIN_VALUE) - .maxSizeOnDiskIs(UPDATED_MAX_SIZE_ON_DISK) - .maxMessageBytesIs(UPDATED_MAX_MESSAGE_BYTES); + pages.open() + .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS); + TopicSteps.updateTopic(TOPIC_TO_UPDATE, COMPACT_POLICY_VALUE, UPDATED_TIME_TO_RETAIN_VALUE, UPDATED_MAX_SIZE_ON_DISK, UPDATED_MAX_MESSAGE_BYTES); } @SneakyThrows @@ -106,13 +81,10 @@ public void updateTopic() { @Test @Disabled // TODO: https://github.com/provectus/kafka-ui/issues/2373 public void deleteTopic() { - pages.openTopicsList(SECOND_LOCAL) - .isOnPage() - .openTopic(TOPIC_TO_DELETE) - .isOnTopicViewPage() - .deleteTopic() - .isOnPage() - .isTopicNotVisible(TOPIC_TO_DELETE); + pages.open() + .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS); + TopicSteps.deleteTopic(TOPIC_TO_DELETE); + Assertions.assertFalse(TopicSteps.isTopicNotVisible(TOPIC_TO_DELETE)); } @SneakyThrows @@ -122,16 +94,10 @@ public void deleteTopic() { @CaseId(222) @Test void produceMessage() { - pages.openTopicsList(SECOND_LOCAL) - .isOnPage() - .openTopic(TOPIC_TO_UPDATE) - .isOnTopicViewPage() - .openTopicMenu(TopicView.TopicMenu.MESSAGES) - .clickOnButton("Produce Message") - .setContentFiled(readFileAsString(CONTENT_TO_PRODUCE_MESSAGE)) - .setKeyField(readFileAsString(KEY_TO_PRODUCE_MESSAGE)) - .submitProduceMessage(); - Assertions.assertTrue(pages.topicView.isKeyMessageVisible(readFileAsString(KEY_TO_PRODUCE_MESSAGE))); - Assertions.assertTrue(pages.topicView.isContentMessageVisible(readFileAsString(CONTENT_TO_PRODUCE_MESSAGE).trim())); + pages.open() + .goToSideMenu(SECOND_LOCAL, MainPage.SideMenuOptions.TOPICS); + TopicSteps.produceMessage(TOPIC_TO_UPDATE, CONTENT_TO_PRODUCE_MESSAGE, KEY_TO_PRODUCE_MESSAGE); + Assertions.assertTrue(TopicSteps.isKeyMessageVisible(readFileAsString(KEY_TO_PRODUCE_MESSAGE))); + Assertions.assertTrue(TopicSteps.isContentMessageVisible(readFileAsString(CONTENT_TO_PRODUCE_MESSAGE).trim())); } }
train
train
2022-08-04T15:38:27
"2022-07-18T13:53:19Z"
kshpilchyna
train
provectus/kafka-ui/2308_2484
provectus/kafka-ui
provectus/kafka-ui/2308
provectus/kafka-ui/2484
[ "timestamp(timedelta=1.0, similarity=0.9138298394008482)" ]
63a451452250eb20e2230afaac6516604f639d69
0ca69fb142013c1ec73033af15de47e040f218a3
[]
[]
"2022-08-23T21:34:22Z"
[ "type/enhancement", "good first issue", "scope/frontend", "status/accepted" ]
No warning message about in use saved filter in case of deleting it
**Describe the bug** Possible to delete the saved filter although it's in use **Set up** https://www.kafka-ui.provectus.io/ **Steps to Reproduce** 1. Navigate to Topics 2. Select the Topic 3. Turn to Messages 4. Use the saved filter 5. Try to delete the used filter **Expected behavior** Should be shown warning message to announce that filter is in use at the moment when user try to delete it **Screenshots** https://user-images.githubusercontent.com/104780608/180067061-f9c7ab40-b93d-4269-9265-a281cedd7c55.mov
[ "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx" ]
[ "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx", "kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx index e9ff5366cd8..510fcd03590 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx +++ b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/AddFilter.tsx @@ -18,6 +18,7 @@ export interface FilterModalProps { activeFilterHandler(activeFilter: MessageFilters, index: number): void; toggleEditModal(): void; editFilter(value: FilterEdit): void; + activeFilter?: MessageFilters; } export interface AddMessageFilters extends MessageFilters { @@ -32,6 +33,7 @@ const AddFilter: React.FC<FilterModalProps> = ({ activeFilterHandler, toggleEditModal, editFilter, + activeFilter, }) => { const [savedFilterState, setSavedFilterState] = React.useState<boolean>(false); @@ -80,6 +82,7 @@ const AddFilter: React.FC<FilterModalProps> = ({ toggleEditModal(); editFilter({ index, filter }); }} + activeFilter={activeFilter} /> ) : ( <> diff --git a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx index dc8b8e6a334..18c4624e93d 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx +++ b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/FilterModal.tsx @@ -11,6 +11,7 @@ export interface FilterModalProps { deleteFilter(index: number): void; activeFilterHandler(activeFilter: MessageFilters, index: number): void; editSavedFilter(filter: FilterEdit): void; + activeFilter?: MessageFilters; } export interface FilterEdit { @@ -25,6 +26,7 @@ const FilterModal: React.FC<FilterModalProps> = ({ deleteFilter, activeFilterHandler, editSavedFilter, + activeFilter, }) => { const [addFilterModal, setAddFilterModal] = React.useState<boolean>(true); const toggleEditModal = () => { @@ -49,6 +51,7 @@ const FilterModal: React.FC<FilterModalProps> = ({ activeFilterHandler={activeFilterHandler} toggleEditModal={toggleEditModal} editFilter={editFilterHandler} + activeFilter={activeFilter} /> ) : ( <EditFilter diff --git a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx index 018a8ef1fff..957bc640279 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx +++ b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/Filters.tsx @@ -498,6 +498,7 @@ const Filters: React.FC<FiltersProps> = ({ deleteFilter={deleteFilter} activeFilterHandler={activeFilterHandler} editSavedFilter={editSavedFilter} + activeFilter={activeFilter} /> )} <S.FiltersMetrics> diff --git a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx index 279ad24b3e5..26036ae9aea 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx +++ b/kafka-ui-react-app/src/components/Topics/Topic/Messages/Filters/SavedFilters.tsx @@ -13,6 +13,7 @@ export interface Props { activeFilterHandler(activeFilter: MessageFilters, index: number): void; closeModal(): void; onGoBack(): void; + activeFilter?: MessageFilters; } const SavedFilters: FC<Props> = ({ @@ -22,11 +23,12 @@ const SavedFilters: FC<Props> = ({ activeFilterHandler, closeModal, onGoBack, + activeFilter, }) => { const [selectedFilter, setSelectedFilter] = React.useState(-1); const confirm = useConfirm(); - const activeFilter = () => { + const activateFilter = () => { if (selectedFilter > -1) { activeFilterHandler(filters[selectedFilter], selectedFilter); } @@ -34,9 +36,23 @@ const SavedFilters: FC<Props> = ({ }; const deleteFilterHandler = (index: number) => { - confirm(<>Are you sure want to remove {filters[index]?.name}?</>, () => { - deleteFilter(index); - }); + const filterName = filters[index]?.name; + const isFilterSelected = activeFilter && activeFilter.name === filterName; + + confirm( + <> + <p>Are you sure want to remove {filterName}?</p> + {isFilterSelected && ( + <> + <br /> + <p>Warning: this filter is currently selected.</p> + </> + )} + </>, + () => { + deleteFilter(index); + } + ); }; return ( @@ -78,7 +94,7 @@ const SavedFilters: FC<Props> = ({ buttonSize="M" buttonType="primary" type="button" - onClick={activeFilter} + onClick={activateFilter} > Select filter </Button>
null
train
train
2022-08-29T12:04:27
"2022-07-21T03:53:23Z"
armenuikafka
train
provectus/kafka-ui/2451_2552
provectus/kafka-ui
provectus/kafka-ui/2451
provectus/kafka-ui/2552
[ "timestamp(timedelta=2642.0, similarity=0.857957340403778)" ]
3bfdc98cc962560df5bb001bb2a63e0222d4bc9f
4a261c6e0b4aadaf13d235d74d5a74f84eefbe83
[ "@Haarolean can you please assign this to me ?", "Checked ok on http://master.internal.kafka-ui.provectus.io/ui/clusters/local/schemas\r\nWorks ok." ]
[]
"2022-09-08T16:57:32Z"
[ "type/bug", "good first issue", "scope/frontend", "status/accepted", "status/confirmed" ]
Improvement for the pagination "Go to page" field logic
**Describe the bug** Not allowed to decrease the "Go to page" value from 1, but possible to delete the value **Set up** https://www.kafka-ui.provectus.io/ **Steps to Reproduce** <!-- We'd like you to provide an example setup (via docker-compose, helm, etc.) to reproduce the problem, especially with a complex setups. --> Steps to reproduce the behavior: 1. Navigate to Topics 2. Delete the "Go to page" value **Expected behavior** Let to not allow too delete the "Go to page" fields value **Screenshots** https://user-images.githubusercontent.com/104780608/184827833-f3dfe350-7c97-4209-aded-f66108f4a232.mov **Additional context** <!-- (Add any other context about the problem here) -->
[ "kafka-ui-react-app/src/components/common/NewTable/Table.tsx" ]
[ "kafka-ui-react-app/src/components/common/NewTable/Table.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/common/NewTable/Table.tsx b/kafka-ui-react-app/src/components/common/NewTable/Table.tsx index 3b3a780674c..646762bf548 100644 --- a/kafka-ui-react-app/src/components/common/NewTable/Table.tsx +++ b/kafka-ui-react-app/src/components/common/NewTable/Table.tsx @@ -190,6 +190,25 @@ const Table: React.FC<TableProps<any>> = ({ return undefined; }; + // Prevent Users to paste negative values in go to page field + const preventPasteNegative = (event: React.ClipboardEvent) => { + const { clipboardData } = event; + if (clipboardData != null) { + const pastedData = parseFloat(clipboardData.getData('text')); + + if (pastedData < 0) { + event.preventDefault(); + } + } + }; + + // Prevent Users to type negative values in go to page field + const preventMinus = (event: React.KeyboardEvent) => { + if (event.code === 'Minus') { + event.preventDefault(); + } + }; + return ( <> {table.getSelectedRowModel().flatRows.length > 0 && Bar && ( @@ -333,6 +352,8 @@ const Table: React.FC<TableProps<any>> = ({ inputSize="M" max={table.getPageCount()} min={1} + onKeyPress={preventMinus} + onPaste={preventPasteNegative} onChange={({ target: { value } }) => { const index = value ? Number(value) - 1 : 0; table.setPageIndex(index);
null
test
train
2022-09-18T14:19:22
"2022-08-16T07:55:25Z"
armenuikafka
train
provectus/kafka-ui/2530_2602
provectus/kafka-ui
provectus/kafka-ui/2530
provectus/kafka-ui/2602
[ "timestamp(timedelta=1.0, similarity=0.9635293354085905)" ]
3bfdc98cc962560df5bb001bb2a63e0222d4bc9f
3b8cbd1dbf92300e795658c3496378f4abd25263
[ "messagesBehind field in api request", "I'd like to work on this task." ]
[]
"2022-09-18T11:36:16Z"
[ "type/enhancement", "good first issue", "scope/frontend", "status/accepted" ]
Add "Total lag" within Consumer group
**Describe the bug** Add "Total lag" into Consumer group profile **Set up** https://www.kafka-ui.provectus.io/ **Screenshots** <img width="1356" alt="total lag" src="https://user-images.githubusercontent.com/104780608/188556151-c77c8eba-0dd2-44b8-95c2-da5a8863a4aa.png">
[ "kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx" ]
[ "kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx b/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx index 912b88a8a38..f1ce947fdb7 100644 --- a/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx +++ b/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx @@ -103,6 +103,9 @@ const Details: React.FC = () => { <Metrics.Indicator label="Coordinator ID"> {consumerGroup.coordinator?.id} </Metrics.Indicator> + <Metrics.Indicator label="Total lag"> + {consumerGroup.messagesBehind} + </Metrics.Indicator> </Metrics.Section> </Metrics.Wrapper> <Table isFullwidth>
null
test
train
2022-09-18T14:19:22
"2022-09-06T05:42:20Z"
armenuikafka
train
provectus/kafka-ui/2537_2607
provectus/kafka-ui
provectus/kafka-ui/2537
provectus/kafka-ui/2607
[ "timestamp(timedelta=0.0, similarity=0.9627177911522665)" ]
596f4233fcd4f7ace80141f5e3b5e1f3ed640be5
9962d29926436ffa10d18db02edb839ee28e3951
[ "`/api/clusters/<cluster>/topics/<topic>/consumer-groups`, field \"topics\".", "I'd like to take this issue." ]
[]
"2022-09-19T13:23:56Z"
[ "good first issue", "scope/frontend", "status/accepted", "type/chore" ]
Add "Num of Topics" to Topic/Consumer tab
**Describe the bug** "Num of Topics" should be displayed within Topic/Consumer tab **Set up** https://www.kafka-ui.provectus.io/ **Steps to Reproduce** <!-- We'd like you to provide an example setup (via docker-compose, helm, etc.) to reproduce the problem, especially with a complex setups. --> Steps to reproduce the behavior: 1. Navigate to Topics 2. Open the Topic 3. Turn to Consumers tab **Expected behavior** The "num of Topics" should be displayed **Screenshots** <img width="1717" alt="num of topics" src="https://user-images.githubusercontent.com/104780608/188837318-c4392509-87fc-4005-bc10-a9a97b40a023.png">
[ "kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx" ]
[ "kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx b/kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx index 82551ac2502..d1d6c4ece2c 100644 --- a/kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx +++ b/kafka-ui-react-app/src/components/Topics/Topic/ConsumerGroups/TopicConsumerGroups.tsx @@ -22,6 +22,7 @@ const TopicConsumerGroups: React.FC = () => { <tr> <TableHeaderCell title="Consumer Group ID" /> <TableHeaderCell title="Num Of Members" /> + <TableHeaderCell title="Num Of Topics" /> <TableHeaderCell title="Messages Behind" /> <TableHeaderCell title="Coordinator" /> <TableHeaderCell title="State" /> @@ -40,6 +41,7 @@ const TopicConsumerGroups: React.FC = () => { </Link> </TableKeyLink> <td>{consumer.members}</td> + <td>{consumer.topics}</td> <td>{consumer.messagesBehind}</td> <td>{consumer.coordinator?.id}</td> <td>
null
train
train
2022-09-19T14:32:47
"2022-09-07T09:01:10Z"
armenuikafka
train
provectus/kafka-ui/2542_2614
provectus/kafka-ui
provectus/kafka-ui/2542
provectus/kafka-ui/2614
[ "timestamp(timedelta=1.0, similarity=0.9637324970299261)" ]
9962d29926436ffa10d18db02edb839ee28e3951
9632ffdbdbf119c2e6de41b6d992a2bd9bec3a20
[ "would be nice if that's possible to implement", "I'd like to work on this. " ]
[]
"2022-09-20T08:14:56Z"
[ "type/enhancement", "good first issue", "scope/frontend", "status/accepted", "hacktoberfest" ]
Add "Messages behind" for Topics within Consumer group profile
**Describe the bug** Add "Messages behind" for Topics within Consumer group profile **Set up** https://www.kafka-ui.provectus.io/ **Steps to Reproduce** <!-- We'd like you to provide an example setup (via docker-compose, helm, etc.) to reproduce the problem, especially with a complex setups. --> Steps to reproduce the behavior: 1. Navigate to Consumer group profile 2. Check the linked Topics list **Expected behavior** Should be displayed "Messages behind" for each Topic **Screenshots** <img width="1437" alt="messages behind" src="https://user-images.githubusercontent.com/104780608/189026697-d0fac45f-90eb-4429-9fec-30882ba55979.png">
[ "kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx", "kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx", "kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx" ]
[ "kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx", "kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx", "kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx b/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx index f1ce947fdb7..0a5c76b9de4 100644 --- a/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx +++ b/kafka-ui-react-app/src/components/ConsumerGroups/Details/Details.tsx @@ -113,6 +113,7 @@ const Details: React.FC = () => { <tr> <TableHeaderCell> </TableHeaderCell> <TableHeaderCell title="Topic" /> + <TableHeaderCell title="Messages behind" /> </tr> </thead> <tbody> diff --git a/kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx b/kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx index 7fab2e8b736..313ad234098 100644 --- a/kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx +++ b/kafka-ui-react-app/src/components/ConsumerGroups/Details/ListItem.tsx @@ -18,6 +18,15 @@ interface Props { const ListItem: React.FC<Props> = ({ clusterName, name, consumers }) => { const [isOpen, setIsOpen] = React.useState(false); + + const getTotalMessagesBehind = () => { + let count = 0; + consumers.forEach((consumer) => { + count += consumer?.messagesBehind || 0; + }); + return count; + }; + return ( <> <tr> @@ -29,6 +38,7 @@ const ListItem: React.FC<Props> = ({ clusterName, name, consumers }) => { <TableKeyLink> <Link to={clusterTopicPath(clusterName, name)}>{name}</Link> </TableKeyLink> + <td>{getTotalMessagesBehind()}</td> </tr> {isOpen && <TopicContents consumers={consumers} />} </> diff --git a/kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx b/kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx index 7a99ee07138..c83389c5af0 100644 --- a/kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx +++ b/kafka-ui-react-app/src/components/ConsumerGroups/Details/__tests__/Details.spec.tsx @@ -65,7 +65,7 @@ describe('Details component', () => { expect(screen.getByText(groupId)).toBeInTheDocument(); expect(screen.getByRole('table')).toBeInTheDocument(); - expect(screen.getAllByRole('columnheader').length).toEqual(2); + expect(screen.getAllByRole('columnheader').length).toEqual(3); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); });
null
train
train
2022-09-20T01:37:21
"2022-09-08T03:20:45Z"
armenuikafka
train
provectus/kafka-ui/2707_2773
provectus/kafka-ui
provectus/kafka-ui/2707
provectus/kafka-ui/2773
[ "timestamp(timedelta=2.0, similarity=0.9619268052186397)" ]
d5a5f66528ee6dbb73d182a864e74a9a04c2e384
76fbaa7ead44de2a9cb7baf6473c810394ac0e5b
[ "I reproduce the problem. It's showing like the screenshot down below. Is this issue still need to be modified? or it can be closed.\r\n![image](https://user-images.githubusercontent.com/113582273/196322270-3d89b7fe-9708-4637-a667-11117adbb36d.png)\r\n", "@winnie-chiu you're running an old version of the app, try `master`-labeled docker image instead of `latest`" ]
[ "```suggestion\r\n emptyMessage=\"No clusters are online\"\r\n```" ]
"2022-10-18T09:22:54Z"
[ "good first issue", "scope/frontend", "status/accepted", "type/chore" ]
Add message about not existing offline clusters in Dashboard
**Describe the bug** In case of missing offline clusters, user should see the corresponding message with toggling the offline clusters in Dashboard **Set up** https://www.kafka-ui.provectus.io/ **Steps to Reproduce** 1. Turn the "Only offline clusters" on 2. Make sure no clusters are available **Expected behavior** Should be shown "No Offline Clusters" message **Screenshots** <img width="1719" alt="disk usage data" src="https://user-images.githubusercontent.com/104780608/194301856-133ce9ee-df79-4734-86d6-6150ac088839.png">
[ "kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx", "kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx" ]
[ "kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx", "kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx" ]
[]
diff --git a/kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx b/kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx index f1aa4988112..966edecf1fd 100644 --- a/kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx +++ b/kafka-ui-react-app/src/components/Brokers/BrokersList/BrokersList.tsx @@ -193,7 +193,7 @@ const BrokersList: React.FC = () => { onRowClick={({ original: { brokerId } }) => navigate(clusterBrokerPath(clusterName, brokerId)) } - emptyMessage="Disk usage data not available" + emptyMessage="No clusters are online" /> </> ); diff --git a/kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx b/kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx index cf36c64059d..0c60cf4749c 100644 --- a/kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx +++ b/kafka-ui-react-app/src/components/Brokers/BrokersList/__test__/BrokersList.spec.tsx @@ -145,7 +145,7 @@ describe('BrokersList Component', () => { renderComponent(); expect(screen.getByRole('table')).toBeInTheDocument(); expect( - screen.getByRole('row', { name: 'Disk usage data not available' }) + screen.getByRole('row', { name: 'No clusters are online' }) ).toBeInTheDocument(); }); });
null
train
val
2023-03-09T19:10:11
"2022-10-06T11:31:44Z"
armenuikafka
train
netty/netty/72_73
netty/netty
netty/netty/72
netty/netty/73
[ "keyword_pr_to_issue" ]
3ecb93eadeaaf4df065862709dc4b456bd5a7f66
b39aad13418a61990649e6b69aab29b02cf9c7bf
[ "We love patches ;)\n", "I think we can preprocess by converting all ; to &. Is that OK?\n", "yes sounds right to me\n" ]
[]
"2011-11-22T19:15:46Z"
[ "improvement" ]
QueryStringDecoder should also support ;
QueryStringDecoder currently does not parse field1=value1;field2=value2 correctly. http://en.wikipedia.org/wiki/Query_string says This convention is a W3C recommendation.[3] W3C recommends that all web servers support semicolon separators in the place of ampersand separators.
[ "src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java index 743875e5b80..94d2715923a 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.java @@ -30,9 +30,11 @@ * Splits an HTTP query string into a path string and key-value parameter pairs. * This decoder is for one time use only. Create a new instance for each URI: * <pre> - * {@link QueryStringDecoder} decoder = new {@link QueryStringDecoder}("/hello?recipient=world"); + * {@link QueryStringDecoder} decoder = new {@link QueryStringDecoder}("/hello?recipient=world&x=1;y=2"); * assert decoder.getPath().equals("/hello"); * assert decoder.getParameters().get("recipient").equals("world"); + * assert decoder.getParameters().get("x").equals("1"); + * assert decoder.getParameters().get("y").equals("2"); * </pre> * * @author <a href="http://www.jboss.org/netty/">The Netty Project</a> @@ -73,7 +75,8 @@ public QueryStringDecoder(String uri, Charset charset) { throw new NullPointerException("charset"); } - this.uri = uri; + // http://en.wikipedia.org/wiki/Query_string + this.uri = uri.replace(';', '&'); this.charset = charset; } @@ -97,7 +100,8 @@ public QueryStringDecoder(URI uri, Charset charset){ throw new NullPointerException("charset"); } - this.uri = uri.toASCIIString(); + // http://en.wikipedia.org/wiki/Query_string + this.uri = uri.toASCIIString().replace(';', '&'); this.charset = charset; }
null
train
train
2011-11-22T17:29:54
"2011-11-22T16:56:04Z"
ngocdaothanh
val
netty/netty/87_98
netty/netty
netty/netty/87
netty/netty/98
[ "timestamp(timedelta=55667.0, similarity=0.8681251034619513)" ]
0d5c7d3d2e8a0de5aa48ecfc3bb761e90c633026
99446458b994809bcce36d9201a6a1bd78abdb95
[ "It's not really a build issue because it works without a problem with\nMaven. M2eclipse problem probably? write-version has to be executed at\nleast at code generation phase because it generates Version.java.\n\n## \n\nSent from a mobile device.\nOn Nov 30, 2011 10:55 AM, \"Vibul Imtarnasan\" <\[email protected]>\nwrote:\n\n> Just installed Eclipse Indigo Service Release 1\n> \n> It comes with M2E - Maven Integration for Eclipse 1.1\n> \n> When I load up the Netty project, I get the following error:\n> \n> ```\n> Plugin execution not covered by lifecycle configuration:\n> org.apache.maven.plugins:maven-antrun-plugin:1.7:run (execution:\n> write-version, phase: validate) pom.xml /netty line 320 Maven\n> Project Build Lifecycle Mapping Problem\n> ```\n> \n> ```\n> <plugin>\n> <artifactId>maven-antrun-plugin</artifactId>\n> <version>1.7</version>\n> <executions>\n> <execution>\n> <id>write-version</id>\n> <phase>validate</phase>\n> <goals>\n> <goal>run</goal>\n> </goals>\n> ...\n> </execution>\n> </plugin>\n> ```\n> \n> Seems like `maven-antrun-plugin` does not like the the `validate` phase.\n> \n> The error goes away if I set the phase to `package` - but I am not sure if\n> this is what is required.\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/87\n", "Yes, you are correct. This is an M2eclipse problem.\n\nI added the following to `pom.xml` just above the `<plugins>` element to make the error go away.\n\n``` xml\n <pluginManagement>\n <plugins>\n <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build \n itself. -->\n <plugin>\n <groupId>org.eclipse.m2e</groupId>\n <artifactId>lifecycle-mapping</artifactId>\n <version>1.0.0</version>\n <configuration>\n <lifecycleMappingMetadata>\n <pluginExecutions>\n <pluginExecution>\n <pluginExecutionFilter>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <versionRange>[1.7,)</versionRange>\n <goals>\n <goal>run</goal>\n </goals>\n </pluginExecutionFilter>\n <action>\n <ignore />\n </action>\n </pluginExecution>\n </pluginExecutions>\n </lifecycleMappingMetadata>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n```\n\nShould I send a pull request for this? Will it blow anything else up?\n", "I think it can't hurt.. so yes please do :)\n", "- Plugin execution not covered by lifecycle configuration: org.jahia.server:maven-jahia-plugin:2.25:native2ascii (execution: native2ascii, phase: generate-\n resources)\n - maven-enforcer-plugin (goal \"enforce\") is ignored by m2e. \n\nabove error give in pom.xml when create new web maven jahia project \nplz help me\n", "Possibly the tips at http://wiki.eclipse.org/M2E_plugin_execution_not_covered help. In my case, I used the tip \"ignore plugin goal\".\n", "??????\n", "Description Resource Path Location Type\nMapping file orm.xml does not have supported content for this JPA platform. orm.xml /spring-social-tutorial/src/main/java/META-INF JPA Problem\n", "Could someone please guide on this issue http://stackoverflow.com/questions/35523664/java-util-concurrent-executionexception-org-apache-catalina-lifecycleexception/35923065#35923065 ?\n" ]
[]
"2011-12-02T04:40:09Z"
[]
Build Issue with maven-antrun-plugin: "Plugin execution not covered by lifecycle configuration"
Just installed Eclipse Indigo Service Release 1 It comes with M2E - Maven Integration for Eclipse 1.1 When I load up the Netty project, I get the following error: ``` Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.7:run (execution: write-version, phase: validate) pom.xml /netty line 320 Maven Project Build Lifecycle Mapping Problem ``` ``` <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>write-version</id> <phase>validate</phase> <goals> <goal>run</goal> </goals> ... </execution> </plugin> ``` Seems like `maven-antrun-plugin` does not like the the `validate` phase. The error goes away if I set the phase to `package` - but I am not sure if this is what is required.
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index 44cc22f2176..c01a7926df6 100644 --- a/pom.xml +++ b/pom.xml @@ -207,6 +207,37 @@ </resource> </resources> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings only. + It has no influence on the Maven build itself. --> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-antrun-plugin</artifactId> + <versionRange>[1.7,)</versionRange> + <goals> + <goal>run</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore /> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> + <plugins> <plugin> <!-- See org.jboss:jboss-parent -->
null
val
train
2011-12-01T14:12:24
"2011-11-30T01:54:58Z"
veebs
val
netty/netty/122_123
netty/netty
netty/netty/122
netty/netty/123
[ "timestamp(timedelta=6308.0, similarity=0.9021925714996629)" ]
5398a5274afbeec894080cea147c785fbd417ece
62d715949e99dafe35ab056eca3cc022752cf7a5
[ "Maybe it's WebSocketClientHandshaker instead of (or in addition to) WebSocketClient.\n", "Pulled #123.\n", "Thanks veebs!\n" ]
[]
"2011-12-15T03:02:45Z"
[ "feature" ]
Allow custom headers on WebSocketClientFactory or WebSocketClient
A service may need to add service-specific headers in addition to the WebSocket handshake headers (such as additional application-specific authentication tokens). It'd be nice to be able to add those custom headers before the connect method is called on the WebSocketClient.
[ "src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java", "src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java" ]
[ "src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java", "src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java", "src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java" ]
[]
diff --git a/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java b/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java index 24064bb56b9..e45d1173c0c 100644 --- a/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java +++ b/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java @@ -51,4 +51,14 @@ public interface WebSocketClient { * @return Write future. Will fire when the data is sent. */ ChannelFuture send(WebSocketFrame frame); + + /** + * Adds a custom header to this client request + * + * @param header + * Name of header field to add to request + * @param value + * Value of header field added to request + */ + void addCustomHeader(String header, String value); } diff --git a/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java b/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java index 3649911ace6..2aecb843267 100644 --- a/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java +++ b/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java @@ -24,6 +24,8 @@ import java.net.InetSocketAddress; import java.net.URI; +import java.util.HashMap; +import java.util.Map; import io.netty.bootstrap.ClientBootstrap; import io.netty.channel.Channel; @@ -54,7 +56,8 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme private Channel channel; private WebSocketClientHandshaker handshaker = null; private final WebSocketSpecificationVersion version; - + private Map<String,String> customHeaders = null; + public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketSpecificationVersion version, WebSocketCallback callback) { this.bootstrap = bootstrap; this.url = url; @@ -65,7 +68,7 @@ public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketSpeci @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); - this.handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url, version, null, false); + this.handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url, version, null, false, customHeaders); handshaker.performOpeningHandshake(channel); } @@ -121,4 +124,11 @@ public URI getUrl() { public void setUrl(URI url) { this.url = url; } + + public void addCustomHeader(String header, String value){ + if(customHeaders == null){ + customHeaders = new HashMap<String,String>(); + } + customHeaders.put(header, value); + } } diff --git a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java index 5e2eb22847e..de734f46781 100644 --- a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java +++ b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java @@ -18,6 +18,7 @@ import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Map; import io.netty.buffer.ChannelBuffer; import io.netty.buffer.ChannelBuffers; @@ -41,16 +42,19 @@ public abstract class WebSocketClientHandshaker { private String subProtocolResponse = null; + protected Map<String,String> customHeaders = null; + /** * * @param webSocketURL * @param version * @param subProtocol */ - public WebSocketClientHandshaker(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol) { + public WebSocketClientHandshaker(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, Map<String,String> customHeaders) { this.webSocketURL = webSocketURL; this.version = version; this.subProtocolRequest = subProtocol; + this.customHeaders = customHeaders; } /** diff --git a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java index 3abbf8c2012..85323d5f88b 100644 --- a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java +++ b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java @@ -18,6 +18,7 @@ import java.net.URI; import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.Map; import io.netty.buffer.ChannelBuffers; import io.netty.channel.Channel; @@ -60,9 +61,12 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker { * server * @param subProtocol * Sub protocol request sent to the server. + * @param customHeaders + * Map of custom headers to add to the client request */ - public WebSocketClientHandshaker00(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol) { - super(webSocketURL, version, subProtocol); + public WebSocketClientHandshaker00(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, Map<String,String> customHeaders) { + super(webSocketURL, version, subProtocol, customHeaders); + } /** @@ -142,6 +146,13 @@ public void performOpeningHandshake(Channel channel) { if (this.getSubProtocolRequest() != null && !this.getSubProtocolRequest().equals("")) { request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, this.getSubProtocolRequest()); } + + if(customHeaders != null){ + for(String header: customHeaders.keySet()){ + request.addHeader(header, customHeaders.get(header)); + } + } + request.setContent(ChannelBuffers.copiedBuffer(key3)); channel.write(request); diff --git a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java index 1e6fdb1f481..ab98243c1ca 100644 --- a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java +++ b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker10.java @@ -16,6 +16,7 @@ package io.netty.handler.codec.http.websocketx; import java.net.URI; +import java.util.Map; import io.netty.channel.Channel; import io.netty.handler.codec.http.DefaultHttpRequest; @@ -68,9 +69,11 @@ public class WebSocketClientHandshaker10 extends WebSocketClientHandshaker { * @param allowExtensions * Allow extensions to be used in the reserved bits of the web * socket frame + * @param customHeaders + * Map of custom headers to add to the client request */ - public WebSocketClientHandshaker10(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions) { - super(webSocketURL, version, subProtocol); + public WebSocketClientHandshaker10(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions, Map<String,String> customHeaders) { + super(webSocketURL, version, subProtocol, customHeaders); this.allowExtensions = allowExtensions; } @@ -127,6 +130,12 @@ public void performOpeningHandshake(Channel channel) { } request.addHeader(Names.SEC_WEBSOCKET_VERSION, "8"); + if(customHeaders != null){ + for(String header: customHeaders.keySet()){ + request.addHeader(header, customHeaders.get(header)); + } + } + channel.write(request); channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket08FrameEncoder(true)); diff --git a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java index 262eb7d40c0..4e6fe75d3db 100644 --- a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java +++ b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker17.java @@ -16,6 +16,7 @@ package io.netty.handler.codec.http.websocketx; import java.net.URI; +import java.util.Map; import io.netty.channel.Channel; import io.netty.handler.codec.http.DefaultHttpRequest; @@ -51,7 +52,7 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker { private static final String protocol = null; private boolean allowExtensions = false; - + /** * Constructor specifying the destination web socket location and version to * initiate @@ -68,9 +69,11 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker { * @param allowExtensions * Allow extensions to be used in the reserved bits of the web * socket frame + * @param customHeaders + * Map of custom headers to add to the client request */ - public WebSocketClientHandshaker17(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions) { - super(webSocketURL, version, subProtocol); + public WebSocketClientHandshaker17(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions, Map<String,String> customHeaders) { + super(webSocketURL, version, subProtocol, customHeaders); this.allowExtensions = allowExtensions; } @@ -127,6 +130,11 @@ public void performOpeningHandshake(Channel channel) { } request.addHeader(Names.SEC_WEBSOCKET_VERSION, "13"); + if(customHeaders != null){ + for(String header: customHeaders.keySet()){ + request.addHeader(header, customHeaders.get(header)); + } + } channel.write(request); channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket13FrameEncoder(true)); diff --git a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java index e8738b52044..2ce3225b409 100644 --- a/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java +++ b/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java @@ -16,6 +16,7 @@ package io.netty.handler.codec.http.websocketx; import java.net.URI; +import java.util.Map; /** * Instances the appropriate handshake class to use for clients @@ -40,15 +41,15 @@ public class WebSocketClientHandshakerFactory { * socket frame * @throws WebSocketHandshakeException */ - public WebSocketClientHandshaker newHandshaker(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions) throws WebSocketHandshakeException { + public WebSocketClientHandshaker newHandshaker(URI webSocketURL, WebSocketSpecificationVersion version, String subProtocol, boolean allowExtensions, Map<String,String> customHeaders) throws WebSocketHandshakeException { if (version == WebSocketSpecificationVersion.V17) { - return new WebSocketClientHandshaker17(webSocketURL, version, subProtocol, allowExtensions); + return new WebSocketClientHandshaker17(webSocketURL, version, subProtocol, allowExtensions, customHeaders); } if (version == WebSocketSpecificationVersion.V10) { - return new WebSocketClientHandshaker10(webSocketURL, version, subProtocol, allowExtensions); + return new WebSocketClientHandshaker10(webSocketURL, version, subProtocol, allowExtensions, customHeaders); } if (version == WebSocketSpecificationVersion.V00) { - return new WebSocketClientHandshaker00(webSocketURL, version, subProtocol); + return new WebSocketClientHandshaker00(webSocketURL, version, subProtocol, customHeaders); } throw new WebSocketHandshakeException("Protocol version " + version.toString() + " not supported.");
null
test
train
2011-12-15T03:27:52
"2011-12-15T02:01:27Z"
rshelley
val
netty/netty/157_159
netty/netty
netty/netty/157
netty/netty/159
[ "timestamp(timedelta=10.0, similarity=0.9348904138647295)" ]
b96768c9a6e305c0000242d67b9ced3e24b8e067
a62509b60aee3c3d414792a3455996ac0d61b484
[ "Both pull requests merged.. Thanks!\n" ]
[]
"2012-01-22T00:13:02Z"
[]
ZlibDecoder does not support preset dictionary
Attempting to create a ZlibDecoder using the preset dictionary constructor throws a compression exception: org.jboss.netty.handler.codec.compression.CompressionException: failed to set the dictionary (-2) z.inflateSetDictionary should not be called until the inflate returns JZlib.Z_NEED_DICT
[ "codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java b/codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java index 1c89d42436b..7904ef5b60d 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java @@ -32,6 +32,7 @@ public class ZlibDecoder extends OneToOneDecoder { private final ZStream z = new ZStream(); + private byte[] dictionary; private volatile boolean finished; /** @@ -72,17 +73,13 @@ public ZlibDecoder(byte[] dictionary) { if (dictionary == null) { throw new NullPointerException("dictionary"); } + this.dictionary = dictionary; synchronized (z) { int resultCode; resultCode = z.inflateInit(JZlib.W_ZLIB); if (resultCode != JZlib.Z_OK) { ZlibUtil.fail(z, "initialization failure", resultCode); - } else { - resultCode = z.inflateSetDictionary(dictionary, dictionary.length); - if (resultCode != JZlib.Z_OK) { - ZlibUtil.fail(z, "failed to set the dictionary", resultCode); - } } } } @@ -131,6 +128,16 @@ protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) z.next_out_index = 0; switch (resultCode) { + case JZlib.Z_NEED_DICT: + if (dictionary == null) { + ZlibUtil.fail(z, "decompression failure", resultCode); + } else { + resultCode = z.inflateSetDictionary(dictionary, dictionary.length); + if (resultCode != JZlib.Z_OK) { + ZlibUtil.fail(z, "failed to set the dictionary", resultCode); + } + } + break; case JZlib.Z_STREAM_END: finished = true; // Do not decode anymore. z.inflateEnd();
null
val
train
2012-01-19T21:22:48
"2012-01-21T22:31:04Z"
jpinner
val
netty/netty/164_172
netty/netty
netty/netty/164
netty/netty/172
[ "timestamp(timedelta=1.0, similarity=0.8943262078098045)" ]
4116c44c7749f0889b5ceef6067bf13ff3c1ad21
617003235223024aeefbe2318838a3f726dcbffa
[]
[]
"2012-01-31T22:40:28Z"
[ "defect" ]
HttpContentEncoder/Decoder accepts the encoding whose qvalue is 0
The following accept-encoding headers have 0 qvalue which means 'do not accept', but Netty does not handle qvalues at all. We at least handle the case where qvalue is 0 or invalid so that we don't accept the wrong encodings. ``` [deflate;q=0, gzip, x-gzip, compress, x-compress]=> [gzip, x-gzip, compress, x-compress] [identity, *; q=0]=> [identity] ```
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "src/test/java/org/jboss/netty/handler/codec/http/HttpContentCompressorTest.java" ]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java index 803c2c53b56..8f455234f2f 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java @@ -83,12 +83,42 @@ protected String getTargetContentEncoding(String acceptEncoding) throws Exceptio } private ZlibWrapper determineWrapper(String acceptEncoding) { - // FIXME: Use the Q value. - if (acceptEncoding.indexOf("gzip") >= 0) { - return ZlibWrapper.GZIP; + float starQ = -1.0f; + float gzipQ = -1.0f; + float deflateQ = -1.0f; + for (String encoding : acceptEncoding.split(",")) { + float q = 1.0f; + int equalsPos = encoding.indexOf('='); + if (equalsPos != -1) { + try { + q = Float.valueOf(encoding.substring(equalsPos + 1)); + } catch (NumberFormatException e) { + // Ignore encoding + q = 0.0f; + } + } + if (encoding.indexOf("*") >= 0) { + starQ = q; + } else if (encoding.indexOf("gzip") >= 0 && q > gzipQ) { + gzipQ = q; + } else if (encoding.indexOf("deflate") >= 0 && q > deflateQ) { + deflateQ = q; + } } - if (acceptEncoding.indexOf("deflate") >= 0) { - return ZlibWrapper.ZLIB; + if (gzipQ > 0.0f || deflateQ > 0.0f) { + if (gzipQ >= deflateQ) { + return ZlibWrapper.GZIP; + } else { + return ZlibWrapper.ZLIB; + } + } + if (starQ > 0.0f) { + if (gzipQ == -1.0f) { + return ZlibWrapper.GZIP; + } + if (deflateQ == -1.0f) { + return ZlibWrapper.ZLIB; + } } return null; }
diff --git a/src/test/java/org/jboss/netty/handler/codec/http/HttpContentCompressorTest.java b/src/test/java/org/jboss/netty/handler/codec/http/HttpContentCompressorTest.java new file mode 100644 index 00000000000..3fb962ccabd --- /dev/null +++ b/src/test/java/org/jboss/netty/handler/codec/http/HttpContentCompressorTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2011 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package org.jboss.netty.handler.codec.http; + +import org.junit.Assert; +import org.junit.Test; + +public class HttpContentCompressorTest { + + private HttpContentCompressor httpContentCompressor = + new HttpContentCompressor(); + + @Test + public void testGetTargetContentEncoding() throws Exception { + HttpContentCompressor compressor = new HttpContentCompressor(); + + String[] tests = { + // Accept-Encoding -> Content-Encoding + "", null, + "*", "gzip", + "*;q=0.0", null, + "gzip", "gzip", + "compress, gzip;q=0.5", "gzip", + "gzip; q=0.5, identity", "gzip", + "gzip ; q=0.1", "gzip", + "gzip; q=0, deflate", "deflate", + " defalte ; q=0 , *;q=0.5", "gzip", + }; + for (int i = 0; i < tests.length; i += 2) { + String acceptEncoding = tests[i]; + String contentEncoding = tests[i + 1]; + String targetEncoding = compressor.getTargetContentEncoding(acceptEncoding); + Assert.assertEquals(contentEncoding, targetEncoding); + } + } +}
train
train
2012-01-31T21:02:00
"2012-01-27T08:27:40Z"
trustin
val
netty/netty/163_174
netty/netty
netty/netty/163
netty/netty/174
[ "timestamp(timedelta=0.0, similarity=0.9115166251394476)" ]
4116c44c7749f0889b5ceef6067bf13ff3c1ad21
9d8c833c75ff7cc8f79f2d9066392df5693f8bd0
[ "Yes if the buffers can be released somehow that would be great too. FYI - I did notice that once I change bits and memLevel down to 12 and 5 my memory usage drops 10x. On the compression side effective compression goes down from 5x to 3.25x. This is still quite an acceptable value.\n", "Sounds interesting...\n", "Yeah, large scale fun. :-)\n\nNorman Maurer wrote:\n\n> Sounds interesting...\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/163#issuecomment-3683752\n\n## \n\nhttp://gleamynode.net/\nhttp://twitter.com/trustin\nhttp://twitter.com/trustin_ko\nhttp://twitter.com/netty_project\n", "Current version of jzlib (1.1.0) exposes these settings in inflateInit and deflateInit.\n" ]
[]
"2012-02-02T00:02:46Z"
[ "improvement" ]
ZlibDecoder and HttpContentCompressor consumes too much memory
Got the following message: Hi Trustin - need your help to add a change to HttpContentCompressor. I need to set bits and memLevel along with compression level. Currently, compression level is the only value that can be set. Here is what the issue is - In our cluster we have 10-20K long lived user connections. Once I enabled compression on then I noticed that more than 70% requests were using compression consuming about 5G additional memory. A heap dump showed that there are 4 x 64K buffers per each connection held in Deflate.java. More specifically the members "window", "pending_buf", "prev" and "head" are each growing to 64K and holding on to the memory. What I have done is taken that current classes and modified so that I can set "bits" to 12 from 15 and "memLevel" to 5 form 8. This bring down memory consumption to 8K per buffer. I am about to check how much compression I lose due to this but seems like it's not that bad. On other clusters we have fewer connections so the defaults should be fine. If these values are adjustable we can tune it based on our cluster requirement. I need to see if both bits and memLevel needs to be set by user or bits can be calculated from memLevel (or the reverse). Even better, if would be great if we can release those large buffers when unused.
[ "src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java", "src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java", "src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java", "src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java", "src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java b/src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java index 5925d6fb890..bd518755ef7 100644 --- a/src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/compression/ZlibEncoder.java @@ -46,7 +46,8 @@ public class ZlibEncoder extends OneToOneEncoder implements LifeCycleAwareChanne private volatile ChannelHandlerContext ctx; /** - * Creates a new zlib encoder with the default compression level ({@code 6}) + * Creates a new zlib encoder with the default compression level ({@code 6}), + * default window bits ({@code 15}), default memory level ({@code 8}), * and the default wrapper ({@link ZlibWrapper#ZLIB}). * * @throws CompressionException if failed to initialize zlib @@ -56,7 +57,8 @@ public ZlibEncoder() { } /** - * Creates a new zlib encoder with the specified {@code compressionLevel} + * Creates a new zlib encoder with the specified {@code compressionLevel}, + * default window bits ({@code 15}), default memory level ({@code 8}), * and the default wrapper ({@link ZlibWrapper#ZLIB}). * * @param compressionLevel @@ -71,7 +73,8 @@ public ZlibEncoder(int compressionLevel) { } /** - * Creates a new zlib encoder with the default compression level ({@code 6}) + * Creates a new zlib encoder with the default compression level ({@code 6}), + * default window bits ({@code 15}), default memory level ({@code 8}), * and the specified wrapper. * * @throws CompressionException if failed to initialize zlib @@ -81,8 +84,10 @@ public ZlibEncoder(ZlibWrapper wrapper) { } /** - * Creates a new zlib encoder with the specified {@code compressionLevel} + * Creates a new zlib encoder with the specified {@code compressionLevel}, + * default window bits ({@code 15}), default memory level ({@code 8}), * and the specified wrapper. + * * @param compressionLevel * {@code 1} yields the fastest compression and {@code 9} yields the * best compression. {@code 0} means no compression. The default @@ -91,10 +96,43 @@ public ZlibEncoder(ZlibWrapper wrapper) { * @throws CompressionException if failed to initialize zlib */ public ZlibEncoder(ZlibWrapper wrapper, int compressionLevel) { + this(wrapper, compressionLevel, 15, 8); + } + + /** + * Creates a new zlib encoder with the specified {@code compressionLevel}, + * the specified {@code windowBits}, the specified {@code memLevel}, and + * the specified wrapper. + * + * @param compressionLevel + * {@code 1} yields the fastest compression and {@code 9} yields the + * best compression. {@code 0} means no compression. The default + * compression level is {@code 6}. + * @param windowBits + * The base two logarithm of the size of the history buffer. The + * value should be in the range {@code 9} to {@code 15} inclusive. + * Larger values result in better compression at the expense of + * memory usage. The default value is {@code 15}. + * @param memLevel + * How much memory should be allocated for the internal compression + * state. {@code 1} uses minimum memory and {@code 9} uses maximum + * memory. Larger values result in better and faster compression + * at the expense of memory usage. The default value is {@code 8} + * + * @throws CompressionException if failed to initialize zlib + */ + public ZlibEncoder(ZlibWrapper wrapper, int compressionLevel, int windowBits, int memLevel) { if (compressionLevel < 0 || compressionLevel > 9) { throw new IllegalArgumentException( - "compressionLevel: " + compressionLevel + - " (expected: 0-9)"); + "compressionLevel: " + compressionLevel + " (expected: 0-9)"); + } + if (windowBits < 9 || windowBits > 15) { + throw new IllegalArgumentException( + "windowBits: " + windowBits + " (expected: 9-15)"); + } + if (memLevel < 1 || memLevel > 9) { + throw new IllegalArgumentException( + "memLevel: " + memLevel + " (expected: 1-9)"); } if (wrapper == null) { throw new NullPointerException("wrapper"); @@ -106,7 +144,8 @@ public ZlibEncoder(ZlibWrapper wrapper, int compressionLevel) { } synchronized (z) { - int resultCode = z.deflateInit(compressionLevel, ZlibUtil.convertWrapperType(wrapper)); + int resultCode = z.deflateInit(compressionLevel, windowBits, memLevel, + ZlibUtil.convertWrapperType(wrapper)); if (resultCode != JZlib.Z_OK) { ZlibUtil.fail(z, "initialization failure", resultCode); } @@ -114,7 +153,8 @@ public ZlibEncoder(ZlibWrapper wrapper, int compressionLevel) { } /** - * Creates a new zlib encoder with the default compression level ({@code 6}) + * Creates a new zlib encoder with the default compression level ({@code 6}), + * default window bits ({@code 15}), default memory level ({@code 8}), * and the specified preset dictionary. The wrapper is always * {@link ZlibWrapper#ZLIB} because it is the only format that supports * the preset dictionary. @@ -128,7 +168,8 @@ public ZlibEncoder(byte[] dictionary) { } /** - * Creates a new zlib encoder with the specified {@code compressionLevel} + * Creates a new zlib encoder with the specified {@code compressionLevel}, + * default window bits ({@code 15}), default memory level ({@code 8}), * and the specified preset dictionary. The wrapper is always * {@link ZlibWrapper#ZLIB} because it is the only format that supports * the preset dictionary. @@ -142,17 +183,55 @@ public ZlibEncoder(byte[] dictionary) { * @throws CompressionException if failed to initialize zlib */ public ZlibEncoder(int compressionLevel, byte[] dictionary) { + this(compressionLevel, 15, 8, dictionary); + } + + /** + * Creates a new zlib encoder with the specified {@code compressionLevel}, + * the specified {@code windowBits}, the specified {@code memLevel}, + * and the specified preset dictionary. The wrapper is always + * {@link ZlibWrapper#ZLIB} because it is the only format that supports + * the preset dictionary. + * + * @param compressionLevel + * {@code 1} yields the fastest compression and {@code 9} yields the + * best compression. {@code 0} means no compression. The default + * compression level is {@code 6}. + * @param windowBits + * The base two logarithm of the size of the history buffer. The + * value should be in the range {@code 9} to {@code 15} inclusive. + * Larger values result in better compression at the expense of + * memory usage. The default value is {@code 15}. + * @param memLevel + * How much memory should be allocated for the internal compression + * state. {@code 1} uses minimum memory and {@code 9} uses maximum + * memory. Larger values result in better and faster compression + * at the expense of memory usage. The default value is {@code 8} + * @param dictionary the preset dictionary + * + * @throws CompressionException if failed to initialize zlib + */ + public ZlibEncoder(int compressionLevel, int windowBits, int memLevel, byte[] dictionary) { if (compressionLevel < 0 || compressionLevel > 9) { - throw new IllegalArgumentException("compressionLevel: " + compressionLevel + " (expected: 0-9)"); + throw new IllegalArgumentException( + "compressionLevel: " + compressionLevel + " (expected: 0-9)"); + } + if (windowBits < 9 || windowBits > 15) { + throw new IllegalArgumentException( + "windowBits: " + windowBits + " (expected: 9-15)"); + } + if (memLevel < 1 || memLevel > 9) { + throw new IllegalArgumentException( + "memLevel: " + memLevel + " (expected: 1-9)"); } - if (dictionary == null) { throw new NullPointerException("dictionary"); } synchronized (z) { int resultCode; - resultCode = z.deflateInit(compressionLevel, JZlib.W_ZLIB); // Default: ZLIB format + resultCode = z.deflateInit(compressionLevel, windowBits, memLevel, + JZlib.W_ZLIB); // Default: ZLIB format if (resultCode != JZlib.Z_OK) { ZlibUtil.fail(z, "initialization failure", resultCode); } else { diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java index 803c2c53b56..3e85fed46f3 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpContentCompressor.java @@ -30,16 +30,20 @@ public class HttpContentCompressor extends HttpContentEncoder { private final int compressionLevel; + private final int windowBits; + private final int memLevel; /** - * Creates a new handler with the default compression level (<tt>6</tt>). + * Creates a new handler with the default compression level (<tt>6</tt>), + * default window size (<tt>15</tt>) and default memory level (<tt>8</tt>). */ public HttpContentCompressor() { this(6); } /** - * Creates a new handler with the specified compression level. + * Creates a new handler with the specified compression level, default + * window size (<tt>15</tt>) and default memory level (<tt>8</tt>). * * @param compressionLevel * {@code 1} yields the fastest compression and {@code 9} yields the @@ -47,12 +51,44 @@ public HttpContentCompressor() { * compression level is {@code 6}. */ public HttpContentCompressor(int compressionLevel) { + this(compressionLevel, 15, 8); + } + + /** + * Creates a new handler with the specified compression level, window size, + * and memory level.. + * + * @param compressionLevel + * {@code 1} yields the fastest compression and {@code 9} yields the + * best compression. {@code 0} means no compression. The default + * compression level is {@code 6}. + * @param windowBits + * The base two logarithm of the size of the history buffer. The + * value should be in the range {@code 9} to {@code 15} inclusive. + * Larger values result in better compression at the expense of + * memory usage. The default value is {@code 15}. + * @param memLevel + * How much memory should be allocated for the internal compression + * state. {@code 1} uses minimum memory and {@code 9} uses maximum + * memory. Larger values result in better and faster compression + * at the expense of memory usage. The default value is {@code 8} + */ + public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel) { if (compressionLevel < 0 || compressionLevel > 9) { throw new IllegalArgumentException( - "compressionLevel: " + compressionLevel + - " (expected: 0-9)"); + "compressionLevel: " + compressionLevel + " (expected: 0-9)"); + } + if (windowBits < 9 || windowBits > 15) { + throw new IllegalArgumentException( + "windowBits: " + windowBits + " (expected: 9-15)"); + } + if (memLevel < 1 || memLevel > 9) { + throw new IllegalArgumentException( + "memLevel: " + memLevel + " (expected: 1-9)"); } this.compressionLevel = compressionLevel; + this.windowBits = windowBits; + this.memLevel = memLevel; } @Override @@ -62,7 +98,8 @@ protected EncoderEmbedder<ChannelBuffer> newContentEncoder(String acceptEncoding return null; } - return new EncoderEmbedder<ChannelBuffer>(new ZlibEncoder(wrapper, compressionLevel)); + return new EncoderEmbedder<ChannelBuffer>( + new ZlibEncoder(wrapper, compressionLevel, windowBits, memLevel)); } @Override diff --git a/src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java b/src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java index e98622109cf..ba8fefcc288 100644 --- a/src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java +++ b/src/main/java/org/jboss/netty/util/internal/jzlib/Deflate.java @@ -1298,9 +1298,9 @@ private int longest_match(int cur_match) { return lookahead; } - int deflateInit(ZStream strm, int level, int bits, WrapperType wrapperType) { + int deflateInit(ZStream strm, int level, int bits, int memLevel, WrapperType wrapperType) { return deflateInit2(strm, level, JZlib.Z_DEFLATED, bits, - JZlib.DEF_MEM_LEVEL, JZlib.Z_DEFAULT_STRATEGY, wrapperType); + memLevel, JZlib.Z_DEFAULT_STRATEGY, wrapperType); } private int deflateInit2(ZStream strm, int level, int method, int windowBits, diff --git a/src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java b/src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java index b28b5950801..2fbd6c0fda3 100644 --- a/src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java +++ b/src/main/java/org/jboss/netty/util/internal/jzlib/ZStream.java @@ -124,9 +124,13 @@ public int deflateInit(int level, int bits) { return deflateInit(level, bits, WrapperType.ZLIB); } - public int deflateInit(int level, int bits, @SuppressWarnings("rawtypes") Enum wrapperType) { + public int deflateInit(int level, int bits, Enum<?> wrapperType) { + return deflateInit(level, bits, JZlib.DEF_MEM_LEVEL, wrapperType); + } + + public int deflateInit(int level, int bits, int memLevel, @SuppressWarnings("rawtypes") Enum wrapperType) { dstate = new Deflate(); - return dstate.deflateInit(this, level, bits, (WrapperType) wrapperType); + return dstate.deflateInit(this, level, bits, memLevel, (WrapperType) wrapperType); } public int deflate(int flush) {
null
train
train
2012-01-31T21:02:00
"2012-01-27T08:20:24Z"
trustin
val
netty/netty/250_253
netty/netty
netty/netty/250
netty/netty/253
[ "timestamp(timedelta=744.0, similarity=0.8633606818966223)" ]
778f4a3cbcb203a47fb5400c268481809e20770d
b312203e947cacaceb03e9685de821ea22d2b700
[ "Hi Jeanfrancois,\n\nI just need clarification of your use case. Is your request for Netty to:\n1. Extract error status/messages sent from the browser\n2. Send error status/message to the browser\n3. Both?\n\nJust want to make sure I fully understand your use case.\n\nThanks.\n", "Hi,\n\nit's mostly for [AHC](https://github.com/sonatype/async-http-client). Right now when the server close the connection I do get called back with the close event, but I don't know the state of the 'close'. Was it closed by the client, server, a network outage etc. This is the information I would like to have. \n\nNow server side it is the same \"problem\", for [Nettosphere](https://github.com/Atmosphere/nettosphere) I also want to know the close reason. \n\nI was using Jetty as an example because Atmosphere supports it and get called back with the proper 'close' code. That's why I think it is doable in Netty/NIO as well.\n\nDoes it help?\n\nThanks\n\n-- Jeanfrancois\n", "Thanks, yes it does help my understanding.\n\nClosing status and message is an optional part of the spec (http://tools.ietf.org/html/rfc6455#section-5.5.1) that I have yet to implement.\n\nI will add extra properties and constructors to CloseWebSocketFrame to support the encoding/decoding of status and message.\n\nI'll try to get some time over the Easter break to submit the pull request.\n\nThanks\n", "Hi Jeanfrancois,\n\nI've just merged the code for this in master and version 3 branch. I've run the code against AutoBahn is it seems to be working ok. Please help test it and let us know if it is working correctly for you.\n\nTo send the status code on the client to the server, you will just have to supply the code and reason on the constructor:\n\n```\nnew CloseWebSocketFrame(1000, \"Some text message\")\n```\n\nTo read the status code and reason on the server, you will just have to:\n\n```\ncloseFrame.getStatusCode()\ncloseFrame.getReasonText()\n```\n\nRegards\nVibul\n", "Thanks. I will take a look today and report as soon as I can.\n", "Thanks Norman for fixing that.\n", "Salut, this works like a charm. AHC is now using 3.4.1-Final and the feature will be added in the upcoming 1.7.4 release. Thanks again!\n" ]
[]
"2012-04-09T04:46:30Z"
[]
[rfe] [websocket] Close cause code should be available
When closing a WebSocket connection using Javascript, it is possible to learn the closing 'cause'. As an example ``` _websocket.onclose = function(message) { var reason = message.reason; if (reason === "") { switch (message.code) { case 1000: reason = "Normal closure; the connection successfully completed whatever purpose for which " + "it was created."; break; case 1001: reason = "The endpoint is going away, either because of a server failure or because the " + "browser is navigating away from the page that opened the connection."; break; case 1002: reason = "The endpoint is terminating the connection due to a protocol error."; break; case 1003: reason = "The connection is being terminated because the endpoint received data of a type it " + "cannot accept (for example, a text-only endpoint received binary data)."; break; case 1004: reason = "The endpoint is terminating the connection because a data frame was received that " + "is too large."; break; case 1005: reason = "Unknown: no status code was provided even though one was expected."; break; case 1006: reason = "Connection was closed abnormally (that is, with no close frame being sent)."; break; } } ``` It is possible from Javascript to customize the error message and the associated logic. The Jetty Server is able to detect the close cause so it should be possible, using NIO, to support it.
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java", "example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java", "example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java index 1f8ed460282..8ed9acb20b5 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java @@ -15,7 +15,9 @@ */ package io.netty.handler.codec.http.websocketx; +import io.netty.buffer.ChannelBuffer; import io.netty.buffer.ChannelBuffers; +import io.netty.util.CharsetUtil; /** * Web Socket Frame for closing the connection @@ -30,7 +32,20 @@ public CloseWebSocketFrame() { } /** - * Creates a new close frame + * Creates a new empty close frame with closing status code and reason text + * + * @param statusCode + * Integer status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. For + * example, <tt>1000</tt> indicates normal closure. + * @param reasonText + * Reason text. Set to null if no text. + */ + public CloseWebSocketFrame(int statusCode, String reasonText) { + this(true, 0, statusCode, reasonText); + } + + /** + * Creates a new close frame with no losing status code and no reason text * * @param finalFragment * flag indicating if this frame is the final fragment @@ -38,8 +53,93 @@ public CloseWebSocketFrame() { * reserved bits used for protocol extensions */ public CloseWebSocketFrame(boolean finalFragment, int rsv) { + this(finalFragment, rsv, null); + } + + /** + * Creates a new close frame with closing status code and reason text + * + * @param finalFragment + * flag indicating if this frame is the final fragment + * @param rsv + * reserved bits used for protocol extensions + * @param statusCode + * Integer status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. For + * example, <tt>1000</tt> indicates normal closure. + * @param reasonText + * Reason text. Set to null if no text. + */ + public CloseWebSocketFrame(boolean finalFragment, int rsv, int statusCode, String reasonText) { + setFinalFragment(finalFragment); + setRsv(rsv); + + byte[] reasonBytes = new byte[0]; + if (reasonText != null) { + reasonBytes = reasonText.getBytes(CharsetUtil.UTF_8); + } + + ChannelBuffer binaryData = ChannelBuffers.buffer(2 + reasonBytes.length); + binaryData.writeShort(statusCode); + if (reasonBytes.length > 0) { + binaryData.writeBytes(reasonBytes); + } + + binaryData.readerIndex(0); + setBinaryData(binaryData); + } + + /** + * Creates a new close frame + * + * @param finalFragment + * flag indicating if this frame is the final fragment + * @param rsv + * reserved bits used for protocol extensions + * @param binaryData + * the content of the frame. Must be 2 byte integer followed by optional UTF-8 encoded string. + */ + public CloseWebSocketFrame(boolean finalFragment, int rsv, ChannelBuffer binaryData) { setFinalFragment(finalFragment); setRsv(rsv); + if (binaryData == null) { + setBinaryData(ChannelBuffers.EMPTY_BUFFER); + } else { + setBinaryData(binaryData); + } + } + + /** + * Returns the closing status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. If + * a status code is set, -1 is returned. + */ + public int getStatusCode() { + ChannelBuffer binaryData = this.getBinaryData(); + if (binaryData == null || binaryData.capacity() == 0) { + return -1; + } + + binaryData.readerIndex(0); + int statusCode = binaryData.readShort(); + binaryData.readerIndex(0); + + return statusCode; + } + + /** + * Returns the reason text as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a> If a reason + * text is not supplied, an empty string is returned. + */ + public String getReasonText() { + ChannelBuffer binaryData = this.getBinaryData(); + if (binaryData == null || binaryData.capacity() <= 2) { + return ""; + } + + binaryData.readerIndex(2); + String reasonText = binaryData.toString(CharsetUtil.UTF_8); + binaryData.readerIndex(0); + + return reasonText; } @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java index 5bd7ea00387..b590c11d8a9 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java @@ -284,8 +284,9 @@ protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffe } else if (frameOpcode == OPCODE_PONG) { return new PongWebSocketFrame(frameFinalFlag, frameRsv, framePayload); } else if (frameOpcode == OPCODE_CLOSE) { + checkCloseFrameBody(channel, framePayload); receivedClosingHandshake = true; - return new CloseWebSocketFrame(frameFinalFlag, frameRsv); + return new CloseWebSocketFrame(frameFinalFlag, frameRsv, framePayload); } // Processing for possible fragmented messages for text and binary @@ -391,4 +392,38 @@ private void checkUTF8String(Channel channel, byte[] bytes) throws CorruptedFram protocolViolation(channel, "invalid UTF-8 bytes"); } } + + protected void checkCloseFrameBody(Channel channel, ChannelBuffer buffer) throws CorruptedFrameException { + if (buffer == null || buffer.capacity() == 0) { + return; + } + if (buffer.capacity() == 1) { + protocolViolation(channel, "Invalid close frame body"); + } + + // Save reader index + int idx = buffer.readerIndex(); + buffer.readerIndex(0); + + // Must have 2 byte integer within the valid range + int statusCode = buffer.readShort(); + if ((statusCode >= 0 && statusCode <= 999) || (statusCode >= 1004 && statusCode <= 1006) + || (statusCode >= 1012 && statusCode <= 2999)) { + protocolViolation(channel, "Invalid close frame status code: " + statusCode); + } + + // May have UTF-8 message + if (buffer.readableBytes() > 0) { + byte[] b = new byte[buffer.readableBytes()]; + buffer.readBytes(b); + try { + new UTF8Output(b); + } catch (UTF8Exception ex) { + protocolViolation(channel, "Invalid close frame reason text. Invalid UTF-8 bytes"); + } + } + + // Restore reader index + buffer.readerIndex(idx); + } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java index 0729d0b5ad6..d04cb842c42 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java +++ b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java @@ -82,11 +82,10 @@ private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throw private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isDebugEnabled()) { - logger.debug(String - .format("Channel %s received %s", ctx.getChannel().getId(), frame.getClass().getSimpleName())); + logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), frame.getClass() + .getSimpleName())); } - if (frame instanceof CloseWebSocketFrame) { this.handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) {
null
test
train
2012-04-07T21:56:58
"2012-04-04T13:24:48Z"
jfarcand
val
netty/netty/250_254
netty/netty
netty/netty/250
netty/netty/254
[ "timestamp(timedelta=644.0, similarity=0.8633606818966223)" ]
16c3d4bc3c24d1481849ba1aba18122f14472395
372d794c3da684bf8c3611eaf8986b9388b24198
[ "Hi Jeanfrancois,\n\nI just need clarification of your use case. Is your request for Netty to:\n1. Extract error status/messages sent from the browser\n2. Send error status/message to the browser\n3. Both?\n\nJust want to make sure I fully understand your use case.\n\nThanks.\n", "Hi,\n\nit's mostly for [AHC](https://github.com/sonatype/async-http-client). Right now when the server close the connection I do get called back with the close event, but I don't know the state of the 'close'. Was it closed by the client, server, a network outage etc. This is the information I would like to have. \n\nNow server side it is the same \"problem\", for [Nettosphere](https://github.com/Atmosphere/nettosphere) I also want to know the close reason. \n\nI was using Jetty as an example because Atmosphere supports it and get called back with the proper 'close' code. That's why I think it is doable in Netty/NIO as well.\n\nDoes it help?\n\nThanks\n\n-- Jeanfrancois\n", "Thanks, yes it does help my understanding.\n\nClosing status and message is an optional part of the spec (http://tools.ietf.org/html/rfc6455#section-5.5.1) that I have yet to implement.\n\nI will add extra properties and constructors to CloseWebSocketFrame to support the encoding/decoding of status and message.\n\nI'll try to get some time over the Easter break to submit the pull request.\n\nThanks\n", "Hi Jeanfrancois,\n\nI've just merged the code for this in master and version 3 branch. I've run the code against AutoBahn is it seems to be working ok. Please help test it and let us know if it is working correctly for you.\n\nTo send the status code on the client to the server, you will just have to supply the code and reason on the constructor:\n\n```\nnew CloseWebSocketFrame(1000, \"Some text message\")\n```\n\nTo read the status code and reason on the server, you will just have to:\n\n```\ncloseFrame.getStatusCode()\ncloseFrame.getReasonText()\n```\n\nRegards\nVibul\n", "Thanks. I will take a look today and report as soon as I can.\n", "Thanks Norman for fixing that.\n", "Salut, this works like a charm. AHC is now using 3.4.1-Final and the feature will be added in the upcoming 1.7.4 release. Thanks again!\n" ]
[]
"2012-04-09T04:47:24Z"
[]
[rfe] [websocket] Close cause code should be available
When closing a WebSocket connection using Javascript, it is possible to learn the closing 'cause'. As an example ``` _websocket.onclose = function(message) { var reason = message.reason; if (reason === "") { switch (message.code) { case 1000: reason = "Normal closure; the connection successfully completed whatever purpose for which " + "it was created."; break; case 1001: reason = "The endpoint is going away, either because of a server failure or because the " + "browser is navigating away from the page that opened the connection."; break; case 1002: reason = "The endpoint is terminating the connection due to a protocol error."; break; case 1003: reason = "The connection is being terminated because the endpoint received data of a type it " + "cannot accept (for example, a text-only endpoint received binary data)."; break; case 1004: reason = "The endpoint is terminating the connection because a data frame was received that " + "is too large."; break; case 1005: reason = "Unknown: no status code was provided even though one was expected."; break; case 1006: reason = "Connection was closed abnormally (that is, with no close frame being sent)."; break; } } ``` It is possible from Javascript to customize the error message and the associated logic. The Jetty Server is able to detect the close cause so it should be possible, using NIO, to support it.
[ "src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java", "src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java", "src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java index e79c40b8157..9e904ddd001 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/CloseWebSocketFrame.java @@ -15,13 +15,14 @@ */ package org.jboss.netty.handler.codec.http.websocketx; +import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.util.CharsetUtil; /** * Web Socket Frame for closing the connection */ public class CloseWebSocketFrame extends WebSocketFrame { - /** * Creates a new empty close frame. */ @@ -30,7 +31,20 @@ public CloseWebSocketFrame() { } /** - * Creates a new close frame + * Creates a new empty close frame with closing status code and reason text + * + * @param statusCode + * Integer status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. For + * example, <tt>1000</tt> indicates normal closure. + * @param reasonText + * Reason text. Set to null if no text. + */ + public CloseWebSocketFrame(int statusCode, String reasonText) { + this(true, 0, statusCode, reasonText); + } + + /** + * Creates a new close frame with no losing status code and no reason text * * @param finalFragment * flag indicating if this frame is the final fragment @@ -38,8 +52,93 @@ public CloseWebSocketFrame() { * reserved bits used for protocol extensions */ public CloseWebSocketFrame(boolean finalFragment, int rsv) { + this(finalFragment, rsv, null); + } + + /** + * Creates a new close frame with closing status code and reason text + * + * @param finalFragment + * flag indicating if this frame is the final fragment + * @param rsv + * reserved bits used for protocol extensions + * @param statusCode + * Integer status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. For + * example, <tt>1000</tt> indicates normal closure. + * @param reasonText + * Reason text. Set to null if no text. + */ + public CloseWebSocketFrame(boolean finalFragment, int rsv, int statusCode, String reasonText) { setFinalFragment(finalFragment); setRsv(rsv); + + byte[] reasonBytes = new byte[0]; + if (reasonText != null) { + reasonBytes = reasonText.getBytes(CharsetUtil.UTF_8); + } + + ChannelBuffer binaryData = ChannelBuffers.buffer(2 + reasonBytes.length); + binaryData.writeShort(statusCode); + if (reasonBytes.length > 0) { + binaryData.writeBytes(reasonBytes); + } + + binaryData.readerIndex(0); + setBinaryData(binaryData); + } + + /** + * Creates a new close frame + * + * @param finalFragment + * flag indicating if this frame is the final fragment + * @param rsv + * reserved bits used for protocol extensions + * @param binaryData + * the content of the frame. Must be 2 byte integer followed by optional UTF-8 encoded string. + */ + public CloseWebSocketFrame(boolean finalFragment, int rsv, ChannelBuffer binaryData) { + setFinalFragment(finalFragment); + setRsv(rsv); + if (binaryData == null) { + setBinaryData(ChannelBuffers.EMPTY_BUFFER); + } else { + setBinaryData(binaryData); + } + } + + /** + * Returns the closing status code as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a>. If + * a status code is set, -1 is returned. + */ + public int getStatusCode() { + ChannelBuffer binaryData = this.getBinaryData(); + if (binaryData == null || binaryData.capacity() == 0) { + return -1; + } + + binaryData.readerIndex(0); + int statusCode = binaryData.readShort(); + binaryData.readerIndex(0); + + return statusCode; + } + + /** + * Returns the reason text as per <a href="http://tools.ietf.org/html/rfc6455#section-7.4">RFC 6455</a> If a reason + * text is not supplied, an empty string is returned. + */ + public String getReasonText() { + ChannelBuffer binaryData = this.getBinaryData(); + if (binaryData == null || binaryData.capacity() <= 2) { + return ""; + } + + binaryData.readerIndex(2); + String reasonText = binaryData.toString(CharsetUtil.UTF_8); + binaryData.readerIndex(0); + + return reasonText; } @Override diff --git a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java index 9d2cf1b2dc0..cd9cf5c9d73 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/websocketx/WebSocket08FrameDecoder.java @@ -284,8 +284,9 @@ protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffe } else if (frameOpcode == OPCODE_PONG) { return new PongWebSocketFrame(frameFinalFlag, frameRsv, framePayload); } else if (frameOpcode == OPCODE_CLOSE) { + checkCloseFrameBody(channel, framePayload); receivedClosingHandshake = true; - return new CloseWebSocketFrame(frameFinalFlag, frameRsv); + return new CloseWebSocketFrame(frameFinalFlag, frameRsv, framePayload); } // Processing for possible fragmented messages for text and binary @@ -391,4 +392,38 @@ private void checkUTF8String(Channel channel, byte[] bytes) throws CorruptedFram protocolViolation(channel, "invalid UTF-8 bytes"); } } + + protected void checkCloseFrameBody(Channel channel, ChannelBuffer buffer) throws CorruptedFrameException { + if (buffer == null || buffer.capacity() == 0) { + return; + } + if (buffer.capacity() == 1) { + protocolViolation(channel, "Invalid close frame body"); + } + + // Save reader index + int idx = buffer.readerIndex(); + buffer.readerIndex(0); + + // Must have 2 byte integer within the valid range + int statusCode = buffer.readShort(); + if ((statusCode >= 0 && statusCode <= 999) || (statusCode >= 1004 && statusCode <= 1006) + || (statusCode >= 1012 && statusCode <= 2999)) { + protocolViolation(channel, "Invalid close frame status code: " + statusCode); + } + + // May have UTF-8 message + if (buffer.readableBytes() > 0) { + byte[] b = new byte[buffer.readableBytes()]; + buffer.readBytes(b); + try { + new UTF8Output(b); + } catch (UTF8Exception ex) { + protocolViolation(channel, "Invalid close frame reason text. Invalid UTF-8 bytes"); + } + } + + // Restore reader index + buffer.readerIndex(idx); + } }
null
train
train
2012-04-07T22:01:36
"2012-04-04T13:24:48Z"
jfarcand
val
netty/netty/269_271
netty/netty
netty/netty/269
netty/netty/271
[ "timestamp(timedelta=2098.0, similarity=0.8531394699270975)" ]
3d762a7594d9cbd7f9289627665ebdfeeb049f58
690323a438d4bbd7ea9ad65b550dc2bfbeafdd16
[ "First test are looking ok so far.. need todo some benchmarks \n" ]
[]
"2012-04-18T19:56:06Z"
[ "improvement" ]
Use gathering writes when using java >= 7
We disabled gathering writes because of some java bug. The problem is now fixed in java7 and above, so we should use it of we detect a java version >= 7. See http://bugs.sun.com/view_bug.do?bug_id=6812202 http://bugs.sun.com/view_bug.do?bug_id=6210541
[ "src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java", "src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java" ]
[ "src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java", "src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java" ]
[ "src/test/java/org/jboss/netty/channel/socket/NioGatheringWriteBenchmark.java" ]
diff --git a/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java b/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java index fc72fd7ea48..66d1cd0da9e 100644 --- a/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java +++ b/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java @@ -26,6 +26,8 @@ import java.util.Collections; import java.util.List; +import org.jboss.netty.util.internal.DetectionUtil; + /** * A virtual buffer which shows multiple buffers as a single merged buffer. It @@ -275,6 +277,9 @@ public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + if (DetectionUtil.javaVersion() >= 7) { + return (int) out.write(toByteBuffers(index, length)); + } // XXX Gathering write is not supported because of a known issue. // See http://bugs.sun.com/view_bug.do?bug_id=6210541 // This issue appeared in 2004 and is still unresolved!? diff --git a/src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java b/src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java index 14f5f96c415..6fec6306bcf 100644 --- a/src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java +++ b/src/main/java/org/jboss/netty/channel/socket/nio/SocketSendBufferPool.java @@ -20,11 +20,14 @@ import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; +import java.nio.channels.GatheringByteChannel; import java.nio.channels.WritableByteChannel; import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.CompositeChannelBuffer; import org.jboss.netty.channel.DefaultFileRegion; import org.jboss.netty.channel.FileRegion; +import org.jboss.netty.util.internal.DetectionUtil; final class SocketSendBufferPool { @@ -65,6 +68,9 @@ private SendBuffer acquire(ChannelBuffer src) { return EMPTY_BUFFER; } + if (src instanceof CompositeChannelBuffer && DetectionUtil.javaVersion() >= 7) { + return new GatheringSendBuffer(src.toByteBuffers()); + } if (src.isDirect()) { return new UnpooledSendBuffer(src.toByteBuffer()); } @@ -249,6 +255,80 @@ public void release() { } } } + + class GatheringSendBuffer implements SendBuffer { + + private final ByteBuffer[] buffers; + private final int last; + private long written; + private final int total; + + GatheringSendBuffer(ByteBuffer[] buffers) { + this.buffers = buffers; + this.last = buffers.length - 1; + int total = 0; + for (ByteBuffer buf: buffers) { + total += buf.remaining(); + } + this.total = total; + } + + public boolean finished() { + return !buffers[last].hasRemaining(); + } + + public long writtenBytes() { + return written; + } + + public long totalBytes() { + return total; + } + + public long transferTo(WritableByteChannel ch) throws IOException { + if (ch instanceof GatheringByteChannel) { + long w = ((GatheringByteChannel) ch).write(buffers); + written += w; + return w; + } else { + int send = 0; + for (ByteBuffer buf: buffers) { + if (buf.hasRemaining()) { + int w = ch.write(buf); + if (w == 0) { + break; + } else { + send += w; + } + } + } + written += send; + return send; + } + } + + public long transferTo(DatagramChannel ch, SocketAddress raddr) throws IOException { + int send = 0; + for (ByteBuffer buf: buffers) { + if (buf.hasRemaining()) { + int w = ch.send(buf, raddr); + if (w == 0) { + break; + } else { + send += w; + } + } + } + written += send; + + return send; + } + + public void release() { + // nothing todo + } + + } final class FileSendBuffer implements SendBuffer {
diff --git a/src/test/java/org/jboss/netty/channel/socket/NioGatheringWriteBenchmark.java b/src/test/java/org/jboss/netty/channel/socket/NioGatheringWriteBenchmark.java new file mode 100644 index 00000000000..409a0457910 --- /dev/null +++ b/src/test/java/org/jboss/netty/channel/socket/NioGatheringWriteBenchmark.java @@ -0,0 +1,133 @@ +package org.jboss.netty.channel.socket; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; + +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; + +public class NioGatheringWriteBenchmark { + + final static byte[] first = new byte[1024]; + final static byte[] second = new byte[1024 * 10]; + + final static ChannelBuffer firstDirect = ChannelBuffers.directBuffer(first.length); + final static ChannelBuffer secondDirect = ChannelBuffers.directBuffer(second.length); + + + + static { + for (int i = 0; i < first.length; i++) { + first[i] = (byte) i; + } + + for (int i = 0; i < second.length; i++) { + second[i] = (byte) i; + } + + firstDirect.writeBytes(first); + secondDirect.writeBytes(second); + } + + final static ChannelBuffer firstHeap = ChannelBuffers.wrappedBuffer(second); + final static ChannelBuffer secondHeap = ChannelBuffers.wrappedBuffer(second); + + public static void main(String args[]) throws IOException { + if (args.length != 2) { + System.err.println("Give argument direct|heap|mixed $rounds"); + System.exit(1); + + } + final ServerSocket socket = new ServerSocket(); + socket.bind(new InetSocketAddress(0)); + + Thread serverThread = new Thread(new Runnable() { + public void run() { + while(!Thread.interrupted()) { + try { + final Socket acceptedSocket = socket.accept(); + new Thread(new Runnable() { + + public void run() { + InputStream in = null; + try { + in = acceptedSocket.getInputStream(); + int i = 0; + + while ((i = in.read()) != -1) { + //System.out.print(i); + } + } catch (IOException e) { + if (in != null) { + try { + in.close(); + } catch (IOException e1) { + // ignore + } + } + } + } + }).start(); + } catch (IOException e) { + // ignore + } + + + } + } + }); + serverThread.start(); + + ClientBootstrap cb = new ClientBootstrap(new NioClientSocketChannelFactory()); + ChannelFuture future = cb.connect(socket.getLocalSocketAddress()); + assertTrue(future.awaitUninterruptibly().isSuccess()); + Channel channel = future.getChannel(); + + + ChannelFuture f = null; + long start = System.currentTimeMillis(); + + ChannelBuffer firstBuf; + ChannelBuffer secondBuf; + + String type = args[0]; + if (type.equalsIgnoreCase("direct")) { + firstBuf = firstDirect; + secondBuf = secondDirect; + } else if (type.equalsIgnoreCase("heap")) { + firstBuf = firstHeap; + secondBuf = secondHeap; + } else if (type.equalsIgnoreCase("mixed")) { + firstBuf = firstDirect; + secondBuf = secondHeap; + } else { + throw new IllegalArgumentException("Use direct|heap|mixed as arguments"); + } + + int rounds = Integer.parseInt(args[1]); + + for (int i = 0; i < rounds; i++) { + f = channel.write(ChannelBuffers.wrappedBuffer(firstBuf.duplicate(), secondBuf.duplicate())); + } + assertTrue(f.awaitUninterruptibly().isSuccess()); + long stop = System.currentTimeMillis() - start; + ChannelFuture cf = channel.close(); + assertTrue(cf.awaitUninterruptibly().isSuccess()); + socket.close(); + serverThread.interrupt(); + + System.out.println("Execute " + rounds + " in " + stop + "ms"); + + + } + +}
train
train
2012-04-17T20:15:20
"2012-04-18T12:54:50Z"
normanmaurer
val
netty/netty/290_299
netty/netty
netty/netty/290
netty/netty/299
[ "keyword_pr_to_issue" ]
97069027a8e6324fd1a59ced4259ac8d6c5b516c
e1be65201c6d3a5f6e0560f7d0bc4f66d9b0eacd
[ "All changes proposed through git pull request\n" ]
[]
"2012-05-02T09:40:10Z"
[ "improvement" ]
Optimize HttpPostRequest in Disk access on AbstractXXXHttpData
Hi, It should be related to V4 only (except if Post support is in 3.X). I made several improvements on HttpPostRequest support. This first set is about moving the "flush" operations at the end of the write, not at every write (not useful). Frederic
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java index 1cf8bd9f223..2a851139d03 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java @@ -115,9 +115,9 @@ public void setContent(ChannelBuffer buffer) throws IOException { int written = 0; while (written < size) { written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); } buffer.readerIndex(buffer.readerIndex() + written); + localfileChannel.force(false); localfileChannel.close(); completed = true; } @@ -141,7 +141,6 @@ public void addContent(ChannelBuffer buffer, boolean last) } while (written < localsize) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } size += localsize; buffer.readerIndex(buffer.readerIndex() + written); @@ -154,6 +153,7 @@ public void addContent(ChannelBuffer buffer, boolean last) FileOutputStream outputStream = new FileOutputStream(file); fileChannel = outputStream.getChannel(); } + fileChannel.force(false); fileChannel.close(); fileChannel = null; completed = true; @@ -191,9 +191,10 @@ public void setContent(InputStream inputStream) throws IOException { while (read > 0) { byteBuffer.position(read).flip(); written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); read = inputStream.read(bytes); } + localfileChannel.force(false); + localfileChannel.close()); size = written; if (definedSize > 0 && definedSize < size) { file.delete(); @@ -288,6 +289,8 @@ public boolean renameTo(File dest) throws IOException { FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); + in.close(); + out.close(); if (destsize == size) { file.delete(); file = dest; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java index 482c735833d..5aba02572ef 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java @@ -200,8 +200,8 @@ public boolean renameTo(File dest) throws IOException { int written = 0; while (written < length) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } + fileChannel.force(false); fileChannel.close(); isRenamed = true; return written == length; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java index 61687639241..3c1c0267dcb 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java @@ -116,18 +116,59 @@ public String toString() { private HttpPostBodyUtil() { } - //Some commons methods between HttpPostRequestDecoder and HttpMessageDecoder + /** - * Skip control Characters - * @param buffer - */ - static void skipControlCharacters(ChannelBuffer buffer) { - for (;;) { - char c = (char) buffer.readUnsignedByte(); - if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { - buffer.readerIndex(buffer.readerIndex() - 1); - break; + * Exception when NO Backend Array is found + */ + static class SeekAheadNoBackArrayException extends Exception { + private static final long serialVersionUID = -630418804938699495L; + } + + /** + * This class intends to decrease the CPU in seeking ahead some bytes in + * HttpPostRequestDecoder + */ + static class SeekAheadOptimize { + byte[] bytes; + + int readerIndex; + + int pos; + + int limit; + + ChannelBuffer buffer; + + /** + * @param buffer + */ + SeekAheadOptimize(ChannelBuffer buffer) throws SeekAheadNoBackArrayException { + if (!buffer.hasArray()) { + throw new SeekAheadNoBackArrayException(); } + this.buffer = buffer; + this.bytes = buffer.array(); + this.pos = this.readerIndex = buffer.readerIndex(); + this.limit = buffer.writerIndex(); + } + + /** + * + * @param minus this value will be used as (currentPos - minus) to set + * the current readerIndex in the buffer. + */ + void setReadPosition(int minus) { + pos -= minus; + readerIndex = pos; + buffer.readerIndex(readerIndex); + } + + void clear() { + this.buffer = null; + this.bytes = null; + this.limit = 0; + this.pos = 0; + this.readerIndex = 0; } } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java index 8f1ea9e1dff..912e4d18d51 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java @@ -26,6 +26,8 @@ import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadNoBackArrayException; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadOptimize; import org.jboss.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism; /** @@ -427,7 +429,7 @@ private void addHttpData(InterfaceHttpData data) { * @throws ErrorDataDecoderException if there is a problem with the charset decoding or * other errors */ - private void parseBodyAttributes() throws ErrorDataDecoderException { + private void parseBodyAttributesStandard() throws ErrorDataDecoderException { int firstpos = undecodedChunk.readerIndex(); int currentpos = firstpos; int equalpos = firstpos; @@ -538,6 +540,141 @@ private void parseBodyAttributes() throws ErrorDataDecoderException { } } + /** + * This method fill the map and list with as much Attribute as possible from Body in + * not Multipart mode. + * + * @throws ErrorDataDecoderException if there is a problem with the charset decoding or + * other errors + */ + private void parseBodyAttributes() throws ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + parseBodyAttributesStandard(); + return; + } + int firstpos = undecodedChunk.readerIndex(); + int currentpos = firstpos; + int equalpos = firstpos; + int ampersandpos = firstpos; + if (currentStatus == MultiPartStatus.NOTSTARTED) { + currentStatus = MultiPartStatus.DISPOSITION; + } + boolean contRead = true; + try { + loop: + while (sao.pos < sao.limit) { + char read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos ++; + switch (currentStatus) { + case DISPOSITION:// search '=' + if (read == '=') { + currentStatus = MultiPartStatus.FIELD; + equalpos = currentpos - 1; + String key = decodeAttribute( + undecodedChunk.toString(firstpos, equalpos - firstpos, charset), + charset); + currentAttribute = factory.createAttribute(request, key); + firstpos = currentpos; + } else if (read == '&') { // special empty FIELD + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset); + currentAttribute = factory.createAttribute(request, key); + currentAttribute.setValue(""); // empty + addHttpData(currentAttribute); + currentAttribute = null; + firstpos = currentpos; + contRead = true; + } + break; + case FIELD:// search '&' or end of line + if (read == '&') { + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = true; + } else if (read == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos++; + if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 2; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } else { + // Error + sao.setReadPosition(0); + contRead = false; + throw new ErrorDataDecoderException("Bad end of line"); + } + } else { + if (sao.limit > 0) { + currentpos --; + } + } + } else if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 1; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } + break; + default: + // just stop + sao.setReadPosition(0); + contRead = false; + break loop; + } + } + if (isLastChunk && currentAttribute != null) { + // special case + ampersandpos = currentpos; + if (ampersandpos > firstpos) { + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + } else if (! currentAttribute.isCompleted()) { + setFinalBuffer(ChannelBuffers.EMPTY_BUFFER); + } + firstpos = currentpos; + currentStatus = MultiPartStatus.EPILOGUE; + return; + } + if (contRead && currentAttribute != null) { + // reset index except if to continue in case of FIELD status + if (currentStatus == MultiPartStatus.FIELD) { + currentAttribute.addContent( + undecodedChunk.slice(firstpos, currentpos - firstpos), + false); + firstpos = currentpos; + } + undecodedChunk.readerIndex(firstpos); + } else { + // end of line so keep index + } + } catch (ErrorDataDecoderException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw e; + } catch (IOException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw new ErrorDataDecoderException(e); + } + } + private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException { currentAttribute.addContent(buffer, true); String value = decodeAttribute( @@ -700,6 +837,37 @@ private InterfaceHttpData decodeMultipart(MultiPartStatus state) } } + /** + * Skip control Characters + */ + void skipControlCharacters() { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e) { + skipControlCharactersStandard(undecodedChunk); + return; + } + + while (sao.pos < sao.limit) { + char c = (char) (sao.bytes[sao.pos ++] & 0xFF); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + sao.setReadPosition(1); + return; + } + } + sao.setReadPosition(0); + } + static void skipControlCharactersStandard(ChannelBuffer buffer) { + for (;;) { + char c = (char) buffer.readUnsignedByte(); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + buffer.readerIndex(buffer.readerIndex() - 1); + break; + } + } + } + /** * Find the next Multipart Delimiter * @param delimiter delimiter to find @@ -714,7 +882,7 @@ private InterfaceHttpData findMultipartDelimiter(String delimiter, throws ErrorDataDecoderException { // --AaB03x or --AaB03x-- int readerIndex = undecodedChunk.readerIndex(); - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); skipOneLine(); String newline; try { @@ -755,7 +923,7 @@ private InterfaceHttpData findMultipartDisposition() } // read many lines until empty line with newline found! Store all data while (!skipOneLine()) { - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); String newline; try { newline = readLine(); @@ -1038,7 +1206,7 @@ private void cleanMixedAttributes() { * @throws NotEnoughDataDecoderException Need more chunks and * reset the readerInder to the previous value */ - private String readLine() throws NotEnoughDataDecoderException { + private String readLineStandard() throws NotEnoughDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { StringBuilder sb = new StringBuilder(64); @@ -1062,7 +1230,49 @@ private String readLine() throws NotEnoughDataDecoderException { undecodedChunk.readerIndex(readerIndex); throw new NotEnoughDataDecoderException(); } - + /** + * Read one line up to the CRLF or LF + * @return the String from one line + * @throws NotEnoughDataDecoderException Need more chunks and + * reset the readerInder to the previous value + */ + private String readLine() throws NotEnoughDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + return readLineStandard(); + } + int readerIndex = undecodedChunk.readerIndex(); + try { + StringBuilder sb = new StringBuilder(64); + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } + } else { + sb.append((char) nextByte); + } + } else if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } else { + sb.append((char) nextByte); + } + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + /** * Read a FileUpload data as Byte (Binary) and add the bytes directly to the * FileUpload. If the delimiter is found, the FileUpload is completed. @@ -1071,7 +1281,7 @@ private String readLine() throws NotEnoughDataDecoderException { * do not reset the readerInder since some values will be already added to the FileOutput * @throws ErrorDataDecoderException write IO error occurs with the FileUpload */ - private void readFileUploadByteMultipart(String delimiter) + private void readFileUploadByteMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); // found the decoder limit @@ -1157,12 +1367,128 @@ private void readFileUploadByteMultipart(String delimiter) } } + /** + * Read a FileUpload data as Byte (Binary) and add the bytes directly to the + * FileUpload. If the delimiter is found, the FileUpload is completed. + * @param delimiter + * @throws NotEnoughDataDecoderException Need more chunks but + * do not reset the readerInder since some values will be already added to the FileOutput + * @throws ErrorDataDecoderException write IO error occurs with the FileUpload + */ + private void readFileUploadByteMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + readFileUploadByteMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex); + if (found) { + // found so lastPosition is correct and final + try { + currentFileUpload.addContent(buffer, true); + // just before the CRLF and delimiter + undecodedChunk.readerIndex(lastPosition); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } else { + // possibly the delimiter is partially found but still the last position is OK + try { + currentFileUpload.addContent(buffer, false); + // last valid char (not CR, not LF, not beginning of delimiter) + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } + } + /** * Load the field value from a Multipart request * @throws NotEnoughDataDecoderException Need more chunks * @throws ErrorDataDecoderException */ - private void loadFieldMultipart(String delimiter) + private void loadFieldMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { @@ -1252,6 +1578,120 @@ private void loadFieldMultipart(String delimiter) } } + /** + * Load the field value from a Multipart request + * @throws NotEnoughDataDecoderException Need more chunks + * @throws ErrorDataDecoderException + */ + private void loadFieldMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + loadFieldMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + try { + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + if (found) { + // found so lastPosition is correct + // but position is just after the delimiter (either close delimiter or simple one) + // so go back of delimiter size + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), true); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + } else { + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), false); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + } + /** * Clean the String from any unallowed character * @return the cleaned String diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java index 7458be48a89..292b0bc4d17 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java @@ -64,7 +64,7 @@ public void addContent(ChannelBuffer buffer, boolean last) throws IOException { .getName()); if (((MemoryAttribute) attribute).getChannelBuffer() != null) { diskAttribute.addContent(((MemoryAttribute) attribute) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } attribute = diskAttribute; } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java index 5180ce5178b..15d44119182 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java @@ -57,7 +57,7 @@ public void addContent(ChannelBuffer buffer, boolean last) definedSize); if (((MemoryFileUpload) fileUpload).getChannelBuffer() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } fileUpload = diskFileUpload; }
null
train
train
2012-05-02T11:29:20
"2012-04-29T12:36:34Z"
fredericBregier
val
netty/netty/292_299
netty/netty
netty/netty/292
netty/netty/299
[ "keyword_pr_to_issue" ]
97069027a8e6324fd1a59ced4259ac8d6c5b516c
e1be65201c6d3a5f6e0560f7d0bc4f66d9b0eacd
[ "All changes propose through Git Pull request\n" ]
[]
"2012-05-02T09:40:10Z"
[ "improvement" ]
Optimize HttpPostRequest in Buffer access on HttpPostRequestDecoder
Hi, It should be related to V4 only (except if Post support is in 3.X). I made several improvements on HttpPostRequest support. This second set is about improving the buffer access. Too many readByte() where occuring. This improvement almost divide by 2 the CPU consumption. Frederic
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java index 1cf8bd9f223..2a851139d03 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java @@ -115,9 +115,9 @@ public void setContent(ChannelBuffer buffer) throws IOException { int written = 0; while (written < size) { written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); } buffer.readerIndex(buffer.readerIndex() + written); + localfileChannel.force(false); localfileChannel.close(); completed = true; } @@ -141,7 +141,6 @@ public void addContent(ChannelBuffer buffer, boolean last) } while (written < localsize) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } size += localsize; buffer.readerIndex(buffer.readerIndex() + written); @@ -154,6 +153,7 @@ public void addContent(ChannelBuffer buffer, boolean last) FileOutputStream outputStream = new FileOutputStream(file); fileChannel = outputStream.getChannel(); } + fileChannel.force(false); fileChannel.close(); fileChannel = null; completed = true; @@ -191,9 +191,10 @@ public void setContent(InputStream inputStream) throws IOException { while (read > 0) { byteBuffer.position(read).flip(); written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); read = inputStream.read(bytes); } + localfileChannel.force(false); + localfileChannel.close()); size = written; if (definedSize > 0 && definedSize < size) { file.delete(); @@ -288,6 +289,8 @@ public boolean renameTo(File dest) throws IOException { FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); + in.close(); + out.close(); if (destsize == size) { file.delete(); file = dest; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java index 482c735833d..5aba02572ef 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java @@ -200,8 +200,8 @@ public boolean renameTo(File dest) throws IOException { int written = 0; while (written < length) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } + fileChannel.force(false); fileChannel.close(); isRenamed = true; return written == length; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java index 61687639241..3c1c0267dcb 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java @@ -116,18 +116,59 @@ public String toString() { private HttpPostBodyUtil() { } - //Some commons methods between HttpPostRequestDecoder and HttpMessageDecoder + /** - * Skip control Characters - * @param buffer - */ - static void skipControlCharacters(ChannelBuffer buffer) { - for (;;) { - char c = (char) buffer.readUnsignedByte(); - if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { - buffer.readerIndex(buffer.readerIndex() - 1); - break; + * Exception when NO Backend Array is found + */ + static class SeekAheadNoBackArrayException extends Exception { + private static final long serialVersionUID = -630418804938699495L; + } + + /** + * This class intends to decrease the CPU in seeking ahead some bytes in + * HttpPostRequestDecoder + */ + static class SeekAheadOptimize { + byte[] bytes; + + int readerIndex; + + int pos; + + int limit; + + ChannelBuffer buffer; + + /** + * @param buffer + */ + SeekAheadOptimize(ChannelBuffer buffer) throws SeekAheadNoBackArrayException { + if (!buffer.hasArray()) { + throw new SeekAheadNoBackArrayException(); } + this.buffer = buffer; + this.bytes = buffer.array(); + this.pos = this.readerIndex = buffer.readerIndex(); + this.limit = buffer.writerIndex(); + } + + /** + * + * @param minus this value will be used as (currentPos - minus) to set + * the current readerIndex in the buffer. + */ + void setReadPosition(int minus) { + pos -= minus; + readerIndex = pos; + buffer.readerIndex(readerIndex); + } + + void clear() { + this.buffer = null; + this.bytes = null; + this.limit = 0; + this.pos = 0; + this.readerIndex = 0; } } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java index 8f1ea9e1dff..912e4d18d51 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java @@ -26,6 +26,8 @@ import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadNoBackArrayException; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadOptimize; import org.jboss.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism; /** @@ -427,7 +429,7 @@ private void addHttpData(InterfaceHttpData data) { * @throws ErrorDataDecoderException if there is a problem with the charset decoding or * other errors */ - private void parseBodyAttributes() throws ErrorDataDecoderException { + private void parseBodyAttributesStandard() throws ErrorDataDecoderException { int firstpos = undecodedChunk.readerIndex(); int currentpos = firstpos; int equalpos = firstpos; @@ -538,6 +540,141 @@ private void parseBodyAttributes() throws ErrorDataDecoderException { } } + /** + * This method fill the map and list with as much Attribute as possible from Body in + * not Multipart mode. + * + * @throws ErrorDataDecoderException if there is a problem with the charset decoding or + * other errors + */ + private void parseBodyAttributes() throws ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + parseBodyAttributesStandard(); + return; + } + int firstpos = undecodedChunk.readerIndex(); + int currentpos = firstpos; + int equalpos = firstpos; + int ampersandpos = firstpos; + if (currentStatus == MultiPartStatus.NOTSTARTED) { + currentStatus = MultiPartStatus.DISPOSITION; + } + boolean contRead = true; + try { + loop: + while (sao.pos < sao.limit) { + char read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos ++; + switch (currentStatus) { + case DISPOSITION:// search '=' + if (read == '=') { + currentStatus = MultiPartStatus.FIELD; + equalpos = currentpos - 1; + String key = decodeAttribute( + undecodedChunk.toString(firstpos, equalpos - firstpos, charset), + charset); + currentAttribute = factory.createAttribute(request, key); + firstpos = currentpos; + } else if (read == '&') { // special empty FIELD + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset); + currentAttribute = factory.createAttribute(request, key); + currentAttribute.setValue(""); // empty + addHttpData(currentAttribute); + currentAttribute = null; + firstpos = currentpos; + contRead = true; + } + break; + case FIELD:// search '&' or end of line + if (read == '&') { + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = true; + } else if (read == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos++; + if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 2; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } else { + // Error + sao.setReadPosition(0); + contRead = false; + throw new ErrorDataDecoderException("Bad end of line"); + } + } else { + if (sao.limit > 0) { + currentpos --; + } + } + } else if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 1; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } + break; + default: + // just stop + sao.setReadPosition(0); + contRead = false; + break loop; + } + } + if (isLastChunk && currentAttribute != null) { + // special case + ampersandpos = currentpos; + if (ampersandpos > firstpos) { + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + } else if (! currentAttribute.isCompleted()) { + setFinalBuffer(ChannelBuffers.EMPTY_BUFFER); + } + firstpos = currentpos; + currentStatus = MultiPartStatus.EPILOGUE; + return; + } + if (contRead && currentAttribute != null) { + // reset index except if to continue in case of FIELD status + if (currentStatus == MultiPartStatus.FIELD) { + currentAttribute.addContent( + undecodedChunk.slice(firstpos, currentpos - firstpos), + false); + firstpos = currentpos; + } + undecodedChunk.readerIndex(firstpos); + } else { + // end of line so keep index + } + } catch (ErrorDataDecoderException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw e; + } catch (IOException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw new ErrorDataDecoderException(e); + } + } + private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException { currentAttribute.addContent(buffer, true); String value = decodeAttribute( @@ -700,6 +837,37 @@ private InterfaceHttpData decodeMultipart(MultiPartStatus state) } } + /** + * Skip control Characters + */ + void skipControlCharacters() { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e) { + skipControlCharactersStandard(undecodedChunk); + return; + } + + while (sao.pos < sao.limit) { + char c = (char) (sao.bytes[sao.pos ++] & 0xFF); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + sao.setReadPosition(1); + return; + } + } + sao.setReadPosition(0); + } + static void skipControlCharactersStandard(ChannelBuffer buffer) { + for (;;) { + char c = (char) buffer.readUnsignedByte(); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + buffer.readerIndex(buffer.readerIndex() - 1); + break; + } + } + } + /** * Find the next Multipart Delimiter * @param delimiter delimiter to find @@ -714,7 +882,7 @@ private InterfaceHttpData findMultipartDelimiter(String delimiter, throws ErrorDataDecoderException { // --AaB03x or --AaB03x-- int readerIndex = undecodedChunk.readerIndex(); - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); skipOneLine(); String newline; try { @@ -755,7 +923,7 @@ private InterfaceHttpData findMultipartDisposition() } // read many lines until empty line with newline found! Store all data while (!skipOneLine()) { - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); String newline; try { newline = readLine(); @@ -1038,7 +1206,7 @@ private void cleanMixedAttributes() { * @throws NotEnoughDataDecoderException Need more chunks and * reset the readerInder to the previous value */ - private String readLine() throws NotEnoughDataDecoderException { + private String readLineStandard() throws NotEnoughDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { StringBuilder sb = new StringBuilder(64); @@ -1062,7 +1230,49 @@ private String readLine() throws NotEnoughDataDecoderException { undecodedChunk.readerIndex(readerIndex); throw new NotEnoughDataDecoderException(); } - + /** + * Read one line up to the CRLF or LF + * @return the String from one line + * @throws NotEnoughDataDecoderException Need more chunks and + * reset the readerInder to the previous value + */ + private String readLine() throws NotEnoughDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + return readLineStandard(); + } + int readerIndex = undecodedChunk.readerIndex(); + try { + StringBuilder sb = new StringBuilder(64); + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } + } else { + sb.append((char) nextByte); + } + } else if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } else { + sb.append((char) nextByte); + } + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + /** * Read a FileUpload data as Byte (Binary) and add the bytes directly to the * FileUpload. If the delimiter is found, the FileUpload is completed. @@ -1071,7 +1281,7 @@ private String readLine() throws NotEnoughDataDecoderException { * do not reset the readerInder since some values will be already added to the FileOutput * @throws ErrorDataDecoderException write IO error occurs with the FileUpload */ - private void readFileUploadByteMultipart(String delimiter) + private void readFileUploadByteMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); // found the decoder limit @@ -1157,12 +1367,128 @@ private void readFileUploadByteMultipart(String delimiter) } } + /** + * Read a FileUpload data as Byte (Binary) and add the bytes directly to the + * FileUpload. If the delimiter is found, the FileUpload is completed. + * @param delimiter + * @throws NotEnoughDataDecoderException Need more chunks but + * do not reset the readerInder since some values will be already added to the FileOutput + * @throws ErrorDataDecoderException write IO error occurs with the FileUpload + */ + private void readFileUploadByteMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + readFileUploadByteMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex); + if (found) { + // found so lastPosition is correct and final + try { + currentFileUpload.addContent(buffer, true); + // just before the CRLF and delimiter + undecodedChunk.readerIndex(lastPosition); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } else { + // possibly the delimiter is partially found but still the last position is OK + try { + currentFileUpload.addContent(buffer, false); + // last valid char (not CR, not LF, not beginning of delimiter) + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } + } + /** * Load the field value from a Multipart request * @throws NotEnoughDataDecoderException Need more chunks * @throws ErrorDataDecoderException */ - private void loadFieldMultipart(String delimiter) + private void loadFieldMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { @@ -1252,6 +1578,120 @@ private void loadFieldMultipart(String delimiter) } } + /** + * Load the field value from a Multipart request + * @throws NotEnoughDataDecoderException Need more chunks + * @throws ErrorDataDecoderException + */ + private void loadFieldMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + loadFieldMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + try { + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + if (found) { + // found so lastPosition is correct + // but position is just after the delimiter (either close delimiter or simple one) + // so go back of delimiter size + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), true); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + } else { + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), false); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + } + /** * Clean the String from any unallowed character * @return the cleaned String diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java index 7458be48a89..292b0bc4d17 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java @@ -64,7 +64,7 @@ public void addContent(ChannelBuffer buffer, boolean last) throws IOException { .getName()); if (((MemoryAttribute) attribute).getChannelBuffer() != null) { diskAttribute.addContent(((MemoryAttribute) attribute) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } attribute = diskAttribute; } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java index 5180ce5178b..15d44119182 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java @@ -57,7 +57,7 @@ public void addContent(ChannelBuffer buffer, boolean last) definedSize); if (((MemoryFileUpload) fileUpload).getChannelBuffer() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } fileUpload = diskFileUpload; }
null
test
train
2012-05-02T11:29:20
"2012-04-29T12:57:39Z"
fredericBregier
val
netty/netty/291_299
netty/netty
netty/netty/291
netty/netty/299
[ "keyword_pr_to_issue" ]
97069027a8e6324fd1a59ced4259ac8d6c5b516c
e1be65201c6d3a5f6e0560f7d0bc4f66d9b0eacd
[ "All changes proposed through git pull request\n" ]
[]
"2012-05-02T09:40:10Z"
[ "defect" ]
Fix a small issue on HttpPostRequest on addContent
Hi, It should be related to V4 only (except if Post support is in 3.X). A fix for issue where addContent may try to finalize too early a content while this is the last block to add. Frederc
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java index 1cf8bd9f223..2a851139d03 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractDiskHttpData.java @@ -115,9 +115,9 @@ public void setContent(ChannelBuffer buffer) throws IOException { int written = 0; while (written < size) { written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); } buffer.readerIndex(buffer.readerIndex() + written); + localfileChannel.force(false); localfileChannel.close(); completed = true; } @@ -141,7 +141,6 @@ public void addContent(ChannelBuffer buffer, boolean last) } while (written < localsize) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } size += localsize; buffer.readerIndex(buffer.readerIndex() + written); @@ -154,6 +153,7 @@ public void addContent(ChannelBuffer buffer, boolean last) FileOutputStream outputStream = new FileOutputStream(file); fileChannel = outputStream.getChannel(); } + fileChannel.force(false); fileChannel.close(); fileChannel = null; completed = true; @@ -191,9 +191,10 @@ public void setContent(InputStream inputStream) throws IOException { while (read > 0) { byteBuffer.position(read).flip(); written += localfileChannel.write(byteBuffer); - localfileChannel.force(false); read = inputStream.read(bytes); } + localfileChannel.force(false); + localfileChannel.close()); size = written; if (definedSize > 0 && definedSize < size) { file.delete(); @@ -288,6 +289,8 @@ public boolean renameTo(File dest) throws IOException { FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); + in.close(); + out.close(); if (destsize == size) { file.delete(); file = dest; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java index 482c735833d..5aba02572ef 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/AbstractMemoryHttpData.java @@ -200,8 +200,8 @@ public boolean renameTo(File dest) throws IOException { int written = 0; while (written < length) { written += fileChannel.write(byteBuffer); - fileChannel.force(false); } + fileChannel.force(false); fileChannel.close(); isRenamed = true; return written == length; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java index 61687639241..3c1c0267dcb 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostBodyUtil.java @@ -116,18 +116,59 @@ public String toString() { private HttpPostBodyUtil() { } - //Some commons methods between HttpPostRequestDecoder and HttpMessageDecoder + /** - * Skip control Characters - * @param buffer - */ - static void skipControlCharacters(ChannelBuffer buffer) { - for (;;) { - char c = (char) buffer.readUnsignedByte(); - if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { - buffer.readerIndex(buffer.readerIndex() - 1); - break; + * Exception when NO Backend Array is found + */ + static class SeekAheadNoBackArrayException extends Exception { + private static final long serialVersionUID = -630418804938699495L; + } + + /** + * This class intends to decrease the CPU in seeking ahead some bytes in + * HttpPostRequestDecoder + */ + static class SeekAheadOptimize { + byte[] bytes; + + int readerIndex; + + int pos; + + int limit; + + ChannelBuffer buffer; + + /** + * @param buffer + */ + SeekAheadOptimize(ChannelBuffer buffer) throws SeekAheadNoBackArrayException { + if (!buffer.hasArray()) { + throw new SeekAheadNoBackArrayException(); } + this.buffer = buffer; + this.bytes = buffer.array(); + this.pos = this.readerIndex = buffer.readerIndex(); + this.limit = buffer.writerIndex(); + } + + /** + * + * @param minus this value will be used as (currentPos - minus) to set + * the current readerIndex in the buffer. + */ + void setReadPosition(int minus) { + pos -= minus; + readerIndex = pos; + buffer.readerIndex(readerIndex); + } + + void clear() { + this.buffer = null; + this.bytes = null; + this.limit = 0; + this.pos = 0; + this.readerIndex = 0; } } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java index 8f1ea9e1dff..912e4d18d51 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpPostRequestDecoder.java @@ -26,6 +26,8 @@ import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadNoBackArrayException; +import org.jboss.netty.handler.codec.http2.HttpPostBodyUtil.SeekAheadOptimize; import org.jboss.netty.handler.codec.http.HttpPostBodyUtil.TransferEncodingMechanism; /** @@ -427,7 +429,7 @@ private void addHttpData(InterfaceHttpData data) { * @throws ErrorDataDecoderException if there is a problem with the charset decoding or * other errors */ - private void parseBodyAttributes() throws ErrorDataDecoderException { + private void parseBodyAttributesStandard() throws ErrorDataDecoderException { int firstpos = undecodedChunk.readerIndex(); int currentpos = firstpos; int equalpos = firstpos; @@ -538,6 +540,141 @@ private void parseBodyAttributes() throws ErrorDataDecoderException { } } + /** + * This method fill the map and list with as much Attribute as possible from Body in + * not Multipart mode. + * + * @throws ErrorDataDecoderException if there is a problem with the charset decoding or + * other errors + */ + private void parseBodyAttributes() throws ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + parseBodyAttributesStandard(); + return; + } + int firstpos = undecodedChunk.readerIndex(); + int currentpos = firstpos; + int equalpos = firstpos; + int ampersandpos = firstpos; + if (currentStatus == MultiPartStatus.NOTSTARTED) { + currentStatus = MultiPartStatus.DISPOSITION; + } + boolean contRead = true; + try { + loop: + while (sao.pos < sao.limit) { + char read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos ++; + switch (currentStatus) { + case DISPOSITION:// search '=' + if (read == '=') { + currentStatus = MultiPartStatus.FIELD; + equalpos = currentpos - 1; + String key = decodeAttribute( + undecodedChunk.toString(firstpos, equalpos - firstpos, charset), + charset); + currentAttribute = factory.createAttribute(request, key); + firstpos = currentpos; + } else if (read == '&') { // special empty FIELD + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + String key = decodeAttribute(undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset); + currentAttribute = factory.createAttribute(request, key); + currentAttribute.setValue(""); // empty + addHttpData(currentAttribute); + currentAttribute = null; + firstpos = currentpos; + contRead = true; + } + break; + case FIELD:// search '&' or end of line + if (read == '&') { + currentStatus = MultiPartStatus.DISPOSITION; + ampersandpos = currentpos - 1; + setFinalBuffer(undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = true; + } else if (read == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + read = (char) (sao.bytes[sao.pos ++] & 0xFF); + currentpos++; + if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 2; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } else { + // Error + sao.setReadPosition(0); + contRead = false; + throw new ErrorDataDecoderException("Bad end of line"); + } + } else { + if (sao.limit > 0) { + currentpos --; + } + } + } else if (read == HttpCodecUtil.LF) { + currentStatus = MultiPartStatus.PREEPILOGUE; + ampersandpos = currentpos - 1; + sao.setReadPosition(0); + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + firstpos = currentpos; + contRead = false; + break loop; + } + break; + default: + // just stop + sao.setReadPosition(0); + contRead = false; + break loop; + } + } + if (isLastChunk && currentAttribute != null) { + // special case + ampersandpos = currentpos; + if (ampersandpos > firstpos) { + setFinalBuffer( + undecodedChunk.slice(firstpos, ampersandpos - firstpos)); + } else if (! currentAttribute.isCompleted()) { + setFinalBuffer(ChannelBuffers.EMPTY_BUFFER); + } + firstpos = currentpos; + currentStatus = MultiPartStatus.EPILOGUE; + return; + } + if (contRead && currentAttribute != null) { + // reset index except if to continue in case of FIELD status + if (currentStatus == MultiPartStatus.FIELD) { + currentAttribute.addContent( + undecodedChunk.slice(firstpos, currentpos - firstpos), + false); + firstpos = currentpos; + } + undecodedChunk.readerIndex(firstpos); + } else { + // end of line so keep index + } + } catch (ErrorDataDecoderException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw e; + } catch (IOException e) { + // error while decoding + undecodedChunk.readerIndex(firstpos); + throw new ErrorDataDecoderException(e); + } + } + private void setFinalBuffer(ChannelBuffer buffer) throws ErrorDataDecoderException, IOException { currentAttribute.addContent(buffer, true); String value = decodeAttribute( @@ -700,6 +837,37 @@ private InterfaceHttpData decodeMultipart(MultiPartStatus state) } } + /** + * Skip control Characters + */ + void skipControlCharacters() { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e) { + skipControlCharactersStandard(undecodedChunk); + return; + } + + while (sao.pos < sao.limit) { + char c = (char) (sao.bytes[sao.pos ++] & 0xFF); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + sao.setReadPosition(1); + return; + } + } + sao.setReadPosition(0); + } + static void skipControlCharactersStandard(ChannelBuffer buffer) { + for (;;) { + char c = (char) buffer.readUnsignedByte(); + if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { + buffer.readerIndex(buffer.readerIndex() - 1); + break; + } + } + } + /** * Find the next Multipart Delimiter * @param delimiter delimiter to find @@ -714,7 +882,7 @@ private InterfaceHttpData findMultipartDelimiter(String delimiter, throws ErrorDataDecoderException { // --AaB03x or --AaB03x-- int readerIndex = undecodedChunk.readerIndex(); - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); skipOneLine(); String newline; try { @@ -755,7 +923,7 @@ private InterfaceHttpData findMultipartDisposition() } // read many lines until empty line with newline found! Store all data while (!skipOneLine()) { - HttpPostBodyUtil.skipControlCharacters(undecodedChunk); + skipControlCharacters(undecodedChunk); String newline; try { newline = readLine(); @@ -1038,7 +1206,7 @@ private void cleanMixedAttributes() { * @throws NotEnoughDataDecoderException Need more chunks and * reset the readerInder to the previous value */ - private String readLine() throws NotEnoughDataDecoderException { + private String readLineStandard() throws NotEnoughDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { StringBuilder sb = new StringBuilder(64); @@ -1062,7 +1230,49 @@ private String readLine() throws NotEnoughDataDecoderException { undecodedChunk.readerIndex(readerIndex); throw new NotEnoughDataDecoderException(); } - + /** + * Read one line up to the CRLF or LF + * @return the String from one line + * @throws NotEnoughDataDecoderException Need more chunks and + * reset the readerInder to the previous value + */ + private String readLine() throws NotEnoughDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + return readLineStandard(); + } + int readerIndex = undecodedChunk.readerIndex(); + try { + StringBuilder sb = new StringBuilder(64); + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } + } else { + sb.append((char) nextByte); + } + } else if (nextByte == HttpCodecUtil.LF) { + sao.setReadPosition(0); + return sb.toString(); + } else { + sb.append((char) nextByte); + } + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + /** * Read a FileUpload data as Byte (Binary) and add the bytes directly to the * FileUpload. If the delimiter is found, the FileUpload is completed. @@ -1071,7 +1281,7 @@ private String readLine() throws NotEnoughDataDecoderException { * do not reset the readerInder since some values will be already added to the FileOutput * @throws ErrorDataDecoderException write IO error occurs with the FileUpload */ - private void readFileUploadByteMultipart(String delimiter) + private void readFileUploadByteMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); // found the decoder limit @@ -1157,12 +1367,128 @@ private void readFileUploadByteMultipart(String delimiter) } } + /** + * Read a FileUpload data as Byte (Binary) and add the bytes directly to the + * FileUpload. If the delimiter is found, the FileUpload is completed. + * @param delimiter + * @throws NotEnoughDataDecoderException Need more chunks but + * do not reset the readerInder since some values will be already added to the FileOutput + * @throws ErrorDataDecoderException write IO error occurs with the FileUpload + */ + private void readFileUploadByteMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + readFileUploadByteMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + // save last valid position + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex); + if (found) { + // found so lastPosition is correct and final + try { + currentFileUpload.addContent(buffer, true); + // just before the CRLF and delimiter + undecodedChunk.readerIndex(lastPosition); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } else { + // possibly the delimiter is partially found but still the last position is OK + try { + currentFileUpload.addContent(buffer, false); + // last valid char (not CR, not LF, not beginning of delimiter) + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + } + } + /** * Load the field value from a Multipart request * @throws NotEnoughDataDecoderException Need more chunks * @throws ErrorDataDecoderException */ - private void loadFieldMultipart(String delimiter) + private void loadFieldMultipartStandard(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); try { @@ -1252,6 +1578,120 @@ private void loadFieldMultipart(String delimiter) } } + /** + * Load the field value from a Multipart request + * @throws NotEnoughDataDecoderException Need more chunks + * @throws ErrorDataDecoderException + */ + private void loadFieldMultipart(String delimiter) + throws NotEnoughDataDecoderException, ErrorDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + loadFieldMultipartStandard(delimiter); + return; + } + int readerIndex = undecodedChunk.readerIndex(); + try { + // found the decoder limit + boolean newLine = true; + int index = 0; + int lastPosition = undecodedChunk.readerIndex(); + boolean found = false; + + while (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (newLine) { + // Check the delimiter + if (nextByte == delimiter.codePointAt(index)) { + index ++; + if (delimiter.length() == index) { + found = true; + sao.setReadPosition(0); + break; + } + continue; + } else { + newLine = false; + index = 0; + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } else { + // continue until end of line + if (nextByte == HttpCodecUtil.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 2; + } + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } else if (nextByte == HttpCodecUtil.LF) { + newLine = true; + index = 0; + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex() - 1; + } else { + sao.setReadPosition(0); + lastPosition = undecodedChunk.readerIndex(); + } + } + } + if (found) { + // found so lastPosition is correct + // but position is just after the delimiter (either close delimiter or simple one) + // so go back of delimiter size + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), true); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + } else { + try { + currentAttribute.addContent( + undecodedChunk.slice(readerIndex, lastPosition - readerIndex), false); + } catch (IOException e) { + throw new ErrorDataDecoderException(e); + } + undecodedChunk.readerIndex(lastPosition); + throw new NotEnoughDataDecoderException(); + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + } + /** * Clean the String from any unallowed character * @return the cleaned String diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java index 7458be48a89..292b0bc4d17 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java @@ -64,7 +64,7 @@ public void addContent(ChannelBuffer buffer, boolean last) throws IOException { .getName()); if (((MemoryAttribute) attribute).getChannelBuffer() != null) { diskAttribute.addContent(((MemoryAttribute) attribute) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } attribute = diskAttribute; } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java index 5180ce5178b..15d44119182 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java @@ -57,7 +57,7 @@ public void addContent(ChannelBuffer buffer, boolean last) definedSize); if (((MemoryFileUpload) fileUpload).getChannelBuffer() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload) - .getChannelBuffer(), last); + .getChannelBuffer(), true); } fileUpload = diskFileUpload; }
null
val
train
2012-05-02T11:29:20
"2012-04-29T12:51:06Z"
fredericBregier
val
netty/netty/300_301
netty/netty
netty/netty/300
netty/netty/301
[ "timestamp(timedelta=165015.0, similarity=0.8659035254419507)" ]
308afcaa405dffb7bf7bd93e0956376e8b8e2529
be094d8aaa3696ac572a68acf9b98fb3866332a6
[]
[]
"2012-05-02T12:15:03Z"
[ "defect" ]
Small race in ChunkedWriteHandler
We have a small race in ChunkedWriteHandler as currentMessageEvent is not "marked" volatile. This needs to get changed
[ "src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java" ]
[ "src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java b/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java index 96b2838511b..1e714ed3b0d 100644 --- a/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java +++ b/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java @@ -19,6 +19,7 @@ import java.nio.channels.ClosedChannelException; import java.util.Queue; +import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; @@ -78,6 +79,9 @@ public class ChunkedWriteHandler implements ChannelUpstreamHandler, ChannelDowns private final Queue<MessageEvent> queue = QueueFactory.createQueue(MessageEvent.class); private volatile ChannelHandlerContext ctx; + + private final AtomicBoolean flush = new AtomicBoolean(false); + private MessageEvent currentEvent; /** @@ -116,12 +120,11 @@ public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) assert offered; final Channel channel = ctx.getChannel(); - if (channel.isWritable()) { + + // call flush if the channel is writable or not connected. flush(..) will take care of the rest + if (channel.isWritable() || !channel.isConnected()) { this.ctx = ctx; flush(ctx, false); - } else if (!channel.isConnected()) { - this.ctx = ctx; - discard(ctx, false); } } @@ -147,7 +150,6 @@ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) private void discard(ChannelHandlerContext ctx, boolean fireNow) { ClosedChannelException cause = null; - boolean fireExceptionCaught = false; for (;;) { MessageEvent currentEvent = this.currentEvent; @@ -173,13 +175,12 @@ private void discard(ChannelHandlerContext ctx, boolean fireNow) { cause = new ClosedChannelException(); } currentEvent.getFuture().setFailure(cause); - fireExceptionCaught = true; currentEvent = null; } - if (fireExceptionCaught) { + if (cause != null) { if (fireNow) { Channels.fireExceptionCaught(ctx.getChannel(), cause); } else { @@ -188,95 +189,110 @@ private void discard(ChannelHandlerContext ctx, boolean fireNow) { } } - private synchronized void flush(ChannelHandlerContext ctx, boolean fireNow) throws Exception { - final Channel channel = ctx.getChannel(); - if (!channel.isConnected()) { - discard(ctx, fireNow); - } + private void flush(ChannelHandlerContext ctx, boolean fireNow) { + boolean acquired = false; + + // use CAS to see if the have flush already running, if so we don't need to take futher actions + if (acquired = flush.compareAndSet(false, true)) { + try { + + final Channel channel = ctx.getChannel(); + if (!channel.isConnected()) { + discard(ctx, fireNow); + } - while (channel.isWritable()) { - if (currentEvent == null) { - currentEvent = queue.poll(); - } + while (channel.isWritable()) { + if (currentEvent == null) { + currentEvent = queue.poll(); + } + if (currentEvent == null) { + break; + } - if (currentEvent == null) { - break; - } + if (currentEvent.getFuture().isDone()) { + // Skip the current request because the previous partial write + // attempt for the current request has been failed. + currentEvent = null; + } else { + final MessageEvent currentEvent = this.currentEvent; + Object m = currentEvent.getMessage(); + if (m instanceof ChunkedInput) { + ChunkedInput chunks = (ChunkedInput) m; + Object chunk; + boolean endOfInput; + boolean suspend; + try { + chunk = chunks.nextChunk(); + endOfInput = chunks.isEndOfInput(); + if (chunk == null) { + chunk = ChannelBuffers.EMPTY_BUFFER; + // No need to suspend when reached at the end. + suspend = !endOfInput; + } else { + suspend = false; + } + } catch (Throwable t) { + this.currentEvent = null; - if (currentEvent.getFuture().isDone()) { - // Skip the current request because the previous partial write - // attempt for the current request has been failed. - currentEvent = null; - } else { - final MessageEvent currentEvent = this.currentEvent; - Object m = currentEvent.getMessage(); - if (m instanceof ChunkedInput) { - ChunkedInput chunks = (ChunkedInput) m; - Object chunk; - boolean endOfInput; - boolean suspend; - try { - chunk = chunks.nextChunk(); - endOfInput = chunks.isEndOfInput(); - if (chunk == null) { - chunk = ChannelBuffers.EMPTY_BUFFER; - // No need to suspend when reached at the end. - suspend = !endOfInput; - } else { - suspend = false; - } - } catch (Throwable t) { - this.currentEvent = null; + currentEvent.getFuture().setFailure(t); + if (fireNow) { + fireExceptionCaught(ctx, t); + } else { + fireExceptionCaughtLater(ctx, t); + } - currentEvent.getFuture().setFailure(t); - if (fireNow) { - fireExceptionCaught(ctx, t); - } else { - fireExceptionCaughtLater(ctx, t); - } + closeInput(chunks); + break; + } - closeInput(chunks); - break; - } + if (suspend) { + // ChunkedInput.nextChunk() returned null and it has + // not reached at the end of input. Let's wait until + // more chunks arrive. Nothing to write or notify. + break; + } else { + ChannelFuture writeFuture; + if (endOfInput) { + this.currentEvent = null; + closeInput(chunks); + writeFuture = currentEvent.getFuture(); + } else { + writeFuture = future(channel); + writeFuture.addListener(new ChannelFutureListener() { + public void operationComplete(ChannelFuture future) + throws Exception { + if (!future.isSuccess()) { + currentEvent.getFuture().setFailure(future.getCause()); + closeInput((ChunkedInput) currentEvent.getMessage()); + } + } + }); + } - if (suspend) { - // ChunkedInput.nextChunk() returned null and it has - // not reached at the end of input. Let's wait until - // more chunks arrive. Nothing to write or notify. - break; - } else { - ChannelFuture writeFuture; - if (endOfInput) { - this.currentEvent = null; - closeInput(chunks); - writeFuture = currentEvent.getFuture(); + Channels.write( + ctx, writeFuture, chunk, + currentEvent.getRemoteAddress()); + } } else { - writeFuture = future(channel); - writeFuture.addListener(new ChannelFutureListener() { - public void operationComplete(ChannelFuture future) - throws Exception { - if (!future.isSuccess()) { - currentEvent.getFuture().setFailure(future.getCause()); - closeInput((ChunkedInput) currentEvent.getMessage()); - } - } - }); + this.currentEvent = null; + ctx.sendDownstream(currentEvent); } + } - Channels.write( - ctx, writeFuture, chunk, - currentEvent.getRemoteAddress()); + if (!channel.isConnected()) { + discard(ctx, fireNow); + break; } - } else { - this.currentEvent = null; - ctx.sendDownstream(currentEvent); } + } finally { + // mark the flush as done + flush.set(false); } - - if (!channel.isConnected()) { - discard(ctx, fireNow); - break; - } + } + + Channel channel = ctx.getChannel(); + if (acquired && !channel.isConnected() || (channel.isWritable() && !queue.isEmpty())) { + flush(ctx, fireNow); } }
null
train
train
2012-05-02T12:13:00
"2012-05-02T10:04:43Z"
normanmaurer
val
netty/netty/317_318
netty/netty
netty/netty/317
netty/netty/318
[ "keyword_pr_to_issue" ]
33cee3dc9d5f5cf46c0201c624b2d5eb25dcc50a
88331593f607bd4579236c97671a1d1769827b81
[ "Hi @robotbrains \n\nConcerning the moveTo, is it renameTo() you talk about ? (I suppose yes)\n\nI would recommend to not use HttpChunkAggregator, since one of the interest of this upload feature is to limit as much as possible the memory impact. Having such a HttpChunkAggregator in your pipeline will put all the file in memory before putting it on disk, which is then unuseful (if it fits of course).\n\nNow on your behavior, it should not give you only the file -10K when renameTo is used.\nIndeed, FileUpload.length returns the number of bytes written to the underlying file (or buffer if in memory).\nWhen using a MixedFileUpload (through DefaultHttpDataFactory with a limit), it starts with a MemoryFileUpload until it reaches the limit size (about 16KB), then writes all the previous bytes to a new DiskFileUpload, then writes the extra new bytes that will oversize the limit.\nOn my side, I did not see such issue. However I most of the time use no HttpChunkAggregator, but I do not know if this might be the issue.\n\nIf you have an example of your issue, I would try to see where it should come from.\nIt might a be a bug...\n", "Again me, I just try by adding a HttpChunkAggregator (with huge size allow) to check, and it works on my side too.\nNote however that when I try to get very huge file, I get a heapspace memory issue on the server side (due to the aggregator).\nIf I removed the aggregator, then everything is ok again, whatever the size (and memory footprint still limited to few KB).\n\nIf you have an example where we can reproduce the error, we will surely fix it.\n", "My message said it had no aggregator. I need to be able to handle very large files and don't want to run out of memory.\n\nYes, it is renameTo(), not moveTo().\n\nIt should copy from the memory, but doesn't in the drop I have, which is from Monday this week.\n\n-Keith\n", "Sorry, I read too quickly your message. Indeed, no Aggregator.\n\nI will get the current 3.5 to see if I can reproduce the behaviour.\nBy the way, do you use a Java client to send the file, or do you use a web browser and then which one ?\n", "I use Chrome. I also tested and got the same behavior with Firefox, wanted to make sure it wasn't a Chrome bug.\n", "Chrome Version 19.0.1084.41\nFirefox 12.0\n", "I would have loved to respond with a patch, but am crushed for time right now, so once I found the disk only solution worked I quit looking in the code.\n", "I have found the reason. One of the patch was not applied.\nI am currently making the necessary patches.\n\nThank you for reporting this issue !\n", "I think you can download again the last revision and check if it is ok now (I have tested on my side of course).\nThen if it is ok, you could close this issue.\n", "OK, will check later today. Thanks!\n", "@robotbrains did you have time yet to check ?\n", "Checking now.\n", "I can't compile.\n\nsoftware/netty/netty-netty-80a2ae6/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java:[278,12] error: cannot find symbol\n\nThat is all I got from Maven. The code has \n\nDetectionUtil.javaVersion() >= 7\n\non that line. No import.\n\nAdding that in for my test, but it should be fixed.\n", "I just fixed this.. That was my fault!\n", "Everything works great now. Many thanks!\n" ]
[ "This will break compatiblity with java5\n", "This will break compatiblity with java5\n", "This will break compatiblity with java5\n", "This will break compatiblity with java5\n", "This will break compatiblity with java5\n", "Ah, I see !\nUnderstood\n" ]
"2012-05-10T18:00:56Z"
[]
MixedFileUpload in Netty 3.5.0 snapshot doesn't write out entire file.
I duplicated the functionality of file upload handler in the example for my application. My HttpDataFactory was done the same way as the example, where I would have a certain size which would be in memory only, but it it got larger, it would be on disk. I also had no HttpChunkAggregator in my pipeline. HttpDataFactory factory = new DefaultHttpDataFactory( DefaultHttpDataFactory.MINSIZE); This worked great for small files, an I was able to take a small file upload and use FileUpload.moveTo() to put it elsewhere in the file system. However, if I did a much larger file, say several meg, the file from FileUpload.moveTo() would be missing about 10K of the file. However, FileUpload.length() would give the correct file length. The subclass of the FileUpload was MixedFileUpload. When I switched to disk-only HttpDataFactory factory = new DefaultHttpDataFactory(true); the FileUpload.moveTo() would give me all of the bytes. I would assume the expected behavior for Mixed would be to get the entire file. I didn't have time to dig too deeply, perhaps the memory upload used for the first few chunks that fit under the minimum are not first written to the file when it switches over to Disk. After changing to disk only I was able to upload 4 Gig files, no problem. Thanks for adding this functionality, it was great.
[ "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java", "src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java index 292b0bc4d17..caad1b492fb 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedAttribute.java @@ -64,7 +64,7 @@ public void addContent(ChannelBuffer buffer, boolean last) throws IOException { .getName()); if (((MemoryAttribute) attribute).getChannelBuffer() != null) { diskAttribute.addContent(((MemoryAttribute) attribute) - .getChannelBuffer(), true); + .getChannelBuffer(), false); } attribute = diskAttribute; } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java index 15d44119182..19ca643627d 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/MixedFileUpload.java @@ -57,7 +57,7 @@ public void addContent(ChannelBuffer buffer, boolean last) definedSize); if (((MemoryFileUpload) fileUpload).getChannelBuffer() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload) - .getChannelBuffer(), true); + .getChannelBuffer(), false); } fileUpload = diskFileUpload; }
null
val
train
2012-05-10T10:15:40
"2012-05-10T13:45:10Z"
robotbrains
val
netty/netty/336_341
netty/netty
netty/netty/336
netty/netty/341
[ "timestamp(timedelta=52706.0, similarity=0.9171606088937482)" ]
288ed13b6b14375204316d68c28f446cb7b9d23d
a477eb23149e5c03baf88d2f139a54ce553ff0af
[]
[]
"2012-05-18T19:01:39Z"
[ "improvement" ]
Make SslBufferPool's methods public
We should make all Methods of SslBufferPool public so its easy to have a custom implementation in another package. For example a user may want to have a custom impl that use direct ByteBuffers.
[ "src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java", "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[ "src/main/java/org/jboss/netty/handler/ssl/DefaultSslBufferPool.java", "src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java", "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/ssl/DefaultSslBufferPool.java b/src/main/java/org/jboss/netty/handler/ssl/DefaultSslBufferPool.java new file mode 100644 index 00000000000..3c2dc387bde --- /dev/null +++ b/src/main/java/org/jboss/netty/handler/ssl/DefaultSslBufferPool.java @@ -0,0 +1,109 @@ +/* + * Copyright 2011 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package org.jboss.netty.handler.ssl; + +import java.nio.ByteBuffer; + +import javax.net.ssl.SSLEngine; + +public class DefaultSslBufferPool implements SslBufferPool { + + private static final int DEFAULT_POOL_SIZE = MAX_PACKET_SIZE * 1024; + + private final ByteBuffer[] pool; + private final int maxBufferCount; + private int index; + + /** + * Creates a new buffer pool whose size is {@code 18113536}, which can + * hold {@code 1024} buffers. + */ + public DefaultSslBufferPool() { + this(DEFAULT_POOL_SIZE); + } + + /** + * Creates a new buffer pool. + * + * @param maxPoolSize the maximum number of bytes that this pool can hold + */ + public DefaultSslBufferPool(int maxPoolSize) { + if (maxPoolSize <= 0) { + throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize); + } + + int maxBufferCount = maxPoolSize / MAX_PACKET_SIZE; + if (maxPoolSize % MAX_PACKET_SIZE != 0) { + maxBufferCount ++; + } + + pool = new ByteBuffer[maxBufferCount]; + this.maxBufferCount = maxBufferCount; + } + + /** + * Returns the maximum size of this pool in byte unit. The returned value + * can be somewhat different from what was specified in the constructor. + */ + public int getMaxPoolSize() { + return maxBufferCount * MAX_PACKET_SIZE; + } + + /** + * Returns the number of bytes which were allocated but have not been + * acquired yet. You can estimate how optimal the specified maximum pool + * size is from this value. If it keeps returning {@code 0}, it means the + * pool is getting exhausted. If it keeps returns a unnecessarily big + * value, it means the pool is wasting the heap space. + */ + public synchronized int getUnacquiredPoolSize() { + return index * MAX_PACKET_SIZE; + } + + public ByteBuffer acquireBuffer() { + return acquire(); + } + + /** + * Will get removed. Please use {@link #acquireBuffer()} + * + */ + @Deprecated + synchronized ByteBuffer acquire() { + if (index == 0) { + return ByteBuffer.allocate(MAX_PACKET_SIZE); + } else { + return (ByteBuffer) pool[-- index].clear(); + } + } + + public void releaseBuffer(ByteBuffer buffer) { + release(buffer); + } + + /** + * Will get removed. Please use {@link #releaseBuffer(ByteBuffer)} + * + * @deprecated + * + */ + @Deprecated + synchronized void release(ByteBuffer buffer) { + if (index < maxBufferCount) { + pool[index ++] = buffer; + } + } +} diff --git a/src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java b/src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java index 05ba7b96a28..642aedaaade 100644 --- a/src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java +++ b/src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java @@ -17,15 +17,10 @@ import java.nio.ByteBuffer; -import javax.net.ssl.SSLEngine; - /** * A {@link ByteBuffer} pool dedicated for {@link SslHandler} performance * improvement. - * <p> - * In most cases, you won't need to create a new pool instance because - * {@link SslHandler} has a default pool instance internally. - * <p> + * * The reason why {@link SslHandler} requires a buffer pool is because the * current {@link SSLEngine} implementation always requires a 17KiB buffer for * every 'wrap' and 'unwrap' operation. In most cases, the actual size of the @@ -33,103 +28,21 @@ * buffer for every 'wrap' and 'unwrap' operation wastes a lot of memory * bandwidth, resulting in the application performance degradation. */ -public class SslBufferPool { - - // Add 1024 as a room for compressed data and another 1024 for Apache Harmony compatibility. - private static final int MAX_PACKET_SIZE = 16665 + 2048; - private static final int DEFAULT_POOL_SIZE = MAX_PACKET_SIZE * 1024; - - private final ByteBuffer[] pool; - private final int maxBufferCount; - private int index; - - /** - * Creates a new buffer pool whose size is {@code 18113536}, which can - * hold {@code 1024} buffers. - */ - public SslBufferPool() { - this(DEFAULT_POOL_SIZE); - } - - /** - * Creates a new buffer pool. - * - * @param maxPoolSize the maximum number of bytes that this pool can hold - */ - public SslBufferPool(int maxPoolSize) { - if (maxPoolSize <= 0) { - throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize); - } - - int maxBufferCount = maxPoolSize / MAX_PACKET_SIZE; - if (maxPoolSize % MAX_PACKET_SIZE != 0) { - maxBufferCount ++; - } +public interface SslBufferPool { - pool = new ByteBuffer[maxBufferCount]; - this.maxBufferCount = maxBufferCount; - } - - /** - * Returns the maximum size of this pool in byte unit. The returned value - * can be somewhat different from what was specified in the constructor. - */ - public int getMaxPoolSize() { - return maxBufferCount * MAX_PACKET_SIZE; - } - - /** - * Returns the number of bytes which were allocated but have not been - * acquired yet. You can estimate how optimal the specified maximum pool - * size is from this value. If it keeps returning {@code 0}, it means the - * pool is getting exhausted. If it keeps returns a unnecessarily big - * value, it means the pool is wasting the heap space. - */ - public synchronized int getUnacquiredPoolSize() { - return index * MAX_PACKET_SIZE; - } + // Returned buffers must be large enough to accomodate the maximum SSL record size. + // Header (5) + Data (2^14) + Compression (1024) + Encryption (1024) + MAC (20) + Padding (256) + int MAX_PACKET_SIZE = 18713; /** * Acquire a new {@link ByteBuffer} out of the {@link SslBufferPool} - * */ - public ByteBuffer acquireBuffer() { - return acquire(); - } - - /** - * Will get removed. Please use {@link #acquireBuffer()} - * - */ - @Deprecated - synchronized ByteBuffer acquire() { - if (index == 0) { - return ByteBuffer.allocate(MAX_PACKET_SIZE); - } else { - return (ByteBuffer) pool[-- index].clear(); - } - } - + ByteBuffer acquireBuffer(); /** - * Release a previous acquired {@link ByteBuffer} - * + * Release a previously acquired {@link ByteBuffer} + * * @param buffer */ - public void releaseBuffer(ByteBuffer buffer) { - release(buffer); - } - - /** - * Will get removed. Please use {@link #releaseBuffer(ByteBuffer)} - * - * @deprecated - * - */ - @Deprecated - synchronized void release(ByteBuffer buffer) { - if (index < maxBufferCount) { - pool[index ++] = buffer; - } - } + void releaseBuffer(ByteBuffer buffer); } diff --git a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java index e05f21a81f3..d040cd2b84c 100644 --- a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java +++ b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java @@ -171,7 +171,7 @@ public class SslHandler extends FrameDecoder */ public static synchronized SslBufferPool getDefaultBufferPool() { if (defaultBufferPool == null) { - defaultBufferPool = new SslBufferPool(); + defaultBufferPool = new DefaultSslBufferPool(); } return defaultBufferPool; }
null
train
train
2012-05-18T11:21:29
"2012-05-18T06:00:02Z"
normanmaurer
val
netty/netty/336_342
netty/netty
netty/netty/336
netty/netty/342
[ "timestamp(timedelta=102587.0, similarity=0.9171606088937482)" ]
3d49975a3cc87cd263d479b0e0b6281dcd51ae50
a82fd9cd5b13485913c45e2c8ba688f05f430b14
[]
[]
"2012-05-18T20:51:23Z"
[ "improvement" ]
Make SslBufferPool's methods public
We should make all Methods of SslBufferPool public so its easy to have a custom implementation in another package. For example a user may want to have a custom impl that use direct ByteBuffers.
[ "handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/DefaultSslBufferPool.java", "handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/DefaultSslBufferPool.java b/handler/src/main/java/io/netty/handler/ssl/DefaultSslBufferPool.java new file mode 100644 index 00000000000..6fe44d58943 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/ssl/DefaultSslBufferPool.java @@ -0,0 +1,93 @@ +/* + * Copyright 2011 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.ssl; + +import java.nio.ByteBuffer; + +import javax.net.ssl.SSLEngine; + +public class DefaultSslBufferPool implements SslBufferPool { + + private static final int DEFAULT_POOL_SIZE = MAX_PACKET_SIZE * 1024; + + private final ByteBuffer[] pool; + private final int maxBufferCount; + private int index; + + /** + * Creates a new buffer pool whose size is {@code 18113536}, which can + * hold {@code 1024} buffers. + */ + public DefaultSslBufferPool() { + this(DEFAULT_POOL_SIZE); + } + + /** + * Creates a new buffer pool. + * + * @param maxPoolSize the maximum number of bytes that this pool can hold + */ + public DefaultSslBufferPool(int maxPoolSize) { + if (maxPoolSize <= 0) { + throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize); + } + + int maxBufferCount = maxPoolSize / MAX_PACKET_SIZE; + if (maxPoolSize % MAX_PACKET_SIZE != 0) { + maxBufferCount ++; + } + + pool = new ByteBuffer[maxBufferCount]; + this.maxBufferCount = maxBufferCount; + } + + /** + * Returns the maximum size of this pool in byte unit. The returned value + * can be somewhat different from what was specified in the constructor. + */ + public int getMaxPoolSize() { + return maxBufferCount * MAX_PACKET_SIZE; + } + + /** + * Returns the number of bytes which were allocated but have not been + * acquired yet. You can estimate how optimal the specified maximum pool + * size is from this value. If it keeps returning {@code 0}, it means the + * pool is getting exhausted. If it keeps returns a unnecessarily big + * value, it means the pool is wasting the heap space. + */ + public synchronized int getUnacquiredPoolSize() { + return index * MAX_PACKET_SIZE; + } + + public ByteBuffer acquireBuffer() { + synchronized { + if (index == 0) { + return ByteBuffer.allocate(MAX_PACKET_SIZE); + } else { + return (ByteBuffer) pool[-- index].clear(); + } + } + } + + public void releaseBuffer(ByteBuffer buffer) { + synchronized { + if (index < maxBufferCount) { + pool[index ++] = buffer; + } + } + } +} diff --git a/handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java b/handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java index 164513a9683..6cd3e18de12 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslBufferPool.java @@ -17,15 +17,10 @@ import java.nio.ByteBuffer; -import javax.net.ssl.SSLEngine; - /** * A {@link ByteBuffer} pool dedicated for {@link SslHandler} performance * improvement. - * <p> - * In most cases, you won't need to create a new pool instance because - * {@link SslHandler} has a default pool instance internally. - * <p> + * * The reason why {@link SslHandler} requires a buffer pool is because the * current {@link SSLEngine} implementation always requires a 17KiB buffer for * every 'wrap' and 'unwrap' operation. In most cases, the actual size of the @@ -33,103 +28,21 @@ * buffer for every 'wrap' and 'unwrap' operation wastes a lot of memory * bandwidth, resulting in the application performance degradation. */ -public class SslBufferPool { - - // Add 1024 as a room for compressed data and another 1024 for Apache Harmony compatibility. - private static final int MAX_PACKET_SIZE = 16665 + 2048; - private static final int DEFAULT_POOL_SIZE = MAX_PACKET_SIZE * 1024; - - private final ByteBuffer[] pool; - private final int maxBufferCount; - private int index; - - /** - * Creates a new buffer pool whose size is {@code 18113536}, which can - * hold {@code 1024} buffers. - */ - public SslBufferPool() { - this(DEFAULT_POOL_SIZE); - } - - /** - * Creates a new buffer pool. - * - * @param maxPoolSize the maximum number of bytes that this pool can hold - */ - public SslBufferPool(int maxPoolSize) { - if (maxPoolSize <= 0) { - throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize); - } - - int maxBufferCount = maxPoolSize / MAX_PACKET_SIZE; - if (maxPoolSize % MAX_PACKET_SIZE != 0) { - maxBufferCount ++; - } +public interface SslBufferPool { - pool = new ByteBuffer[maxBufferCount]; - this.maxBufferCount = maxBufferCount; - } - - /** - * Returns the maximum size of this pool in byte unit. The returned value - * can be somewhat different from what was specified in the constructor. - */ - public int getMaxPoolSize() { - return maxBufferCount * MAX_PACKET_SIZE; - } - - /** - * Returns the number of bytes which were allocated but have not been - * acquired yet. You can estimate how optimal the specified maximum pool - * size is from this value. If it keeps returning {@code 0}, it means the - * pool is getting exhausted. If it keeps returns a unnecessarily big - * value, it means the pool is wasting the heap space. - */ - public synchronized int getUnacquiredPoolSize() { - return index * MAX_PACKET_SIZE; - } + // Returned buffers must be large enough to accomodate the maximum SSL record size. + // Header (5) + Data (2^14) + Compression (1024) + Encryption (1024) + MAC (20) + Padding (256) + int MAX_PACKET_SIZE = 18713; /** * Acquire a new {@link ByteBuffer} out of the {@link SslBufferPool} - * */ - public ByteBuffer acquireBuffer() { - return acquire(); - } - - /** - * Will get removed. Please use {@link #acquireBuffer()} - * - */ - @Deprecated - synchronized ByteBuffer acquire() { - if (index == 0) { - return ByteBuffer.allocate(MAX_PACKET_SIZE); - } else { - return (ByteBuffer) pool[-- index].clear(); - } - } - + ByteBuffer acquireBuffer(); /** - * Release a previous acquired {@link ByteBuffer} - * + * Release a previously acquired {@link ByteBuffer} + * * @param buffer */ - public void releaseBuffer(ByteBuffer buffer) { - release(buffer); - } - - /** - * Will get removed. Please use {@link #releaseBuffer(ByteBuffer)} - * - * @deprecated - * - */ - @Deprecated - synchronized void release(ByteBuffer buffer) { - if (index < maxBufferCount) { - pool[index ++] = buffer; - } - } + void releaseBuffer(ByteBuffer buffer); } diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index 3247d614a4c..5a550751889 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -170,7 +170,7 @@ public class SslHandler extends FrameDecoder */ public static synchronized SslBufferPool getDefaultBufferPool() { if (defaultBufferPool == null) { - defaultBufferPool = new SslBufferPool(); + defaultBufferPool = new DefaultSslBufferPool(); } return defaultBufferPool; }
null
train
train
2012-05-18T21:41:57
"2012-05-18T06:00:02Z"
normanmaurer
val
netty/netty/345_346
netty/netty
netty/netty/345
netty/netty/346
[ "keyword_pr_to_issue" ]
ed538209e588e8ba7e94371a801067d73eb2ab74
1af6e443ac864a5d1b1769478155e88b8d97e8b6
[ "PS: if desired I could provide these changes.\n", "Hi @rzorzorzo \n\nOn the first item, I was really unaware of this ! Thanks for spotting this !\n\nOn the second item, I could agree but the idea is to be able to change the timer... (traffic handler could changed during runtime due to special request).\nHow could we do this ? I suppose that using the Timer utilitye from Netty will bring us to assigning again and again a new thread at every check (which is probably worst than having one specific thread per counter making some sleep) ?\nOn Counter, we need to have such one thread per Handler (one unique for Global, but if needed, one per Channel).\n\nI would be please if you can propose both, but perhaps in 2 separates proposal to be able to accept one or the other ?\n", "@rzorzorzo \nSince I was on my way to check some other elements, I may have done the first point (see #346).\n\nSorry if you were on your way... ;-)\nI will try to make the same on release 3.5 immediately.\n\nHowever on second proposal, I let you make some proposals... ;-)\n", "Frederic,\n\nthnx for 1.\n\nconcerning 2:\nTrafficCounter sleeps practically 100% of the time. During sleep, the thread is not returned to the pool. With 100k connections, therefore 100k channels, we will need with the current solution 100k threads. Not feasible.\n\nNetty's HashedWheelTimer requires a single Thread. The same timer, and therefore thread can be shared by all TrafficCounters. The dynamic change of checkIntervall can be supported as with the current implementation.\n\nMaybe the following code sections will help:\n\nfields:\n\n``` java\n private Timer timer; // replace executor\n private TimerTask timerTask; // created once in start()\n volatile private Timeout timeout = null; // used in stop() to cancel the timer\n```\n\nConstructor:\n\n``` java\n public TrafficCounter(TrafficShapingHandler trafficShapingHandler,\n Timer timer, String name, long checkInterval) { \n this.timer = timer;\n ...\n }\n```\n\nstart method\n\n``` java\n public void start() {\n...\n timerTask = new TimerTask()\n {\n\n @Override\n public void run(Timeout timeout) throws Exception\n {\n if (!monitorActive.get()) {\n return;\n }\n trafficMonitoring.run();\n TrafficCounter.this.timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS); \n }\n\n };\n timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS);\n...\n```\n\nstop method\n\n``` java\n public void stop() {\n...\n if (timeout != null)\n timeout.cancel();\n```\n\n-- Ron\n", "@rzorzorzo @fredericBregier this makes a lot of sense\n", "@rzorzorzo I will spend some time to your proposal, see if I understand first, then if I can propose a new version once I had tested it.\nThank you !!\n", "@rzorzorzo and @normanmaurer \nI finally make the change as proposed. I tested it intensively. I find no issue (as for now of course).\nI even optimize a bit more the traffic handler:\n- there were one thread created to unlock traffic from time to time when needed => Timer\n- in the original proposal, 2 objects were created: the TimerTask and the internal TrafficCOunter object => only the timer task now\n\nI hope this is what you guess both of you !\n\nSee proposal in Issue #348\n", "Cool.. I will review later today.\n", "Thank you @normanmaurer !\nAnd thank you too @rzorzorzo for these proposals!\n\nI believe we can close this issue then.\n" ]
[]
"2012-05-19T12:06:45Z"
[]
Enhancements to AbstractTrafficShapingHandler / TrafficCounter
1. do not sleep 101 ms due to issues with java and windows see: http://www.javamex.com/tutorials/threads/sleep_issues.shtml in getTimeToWait change return wait; to: return (wait/10)*10; 1. do not "waste" a thread in TrafficCounter. use netty's Timer instead. -- Ron
[ "handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java", "handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java" ]
[ "handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java", "handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java index 7da4b29a96c..b0c6fcfda95 100644 --- a/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java +++ b/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java @@ -360,7 +360,7 @@ private long getTimeToWait(long limit, long bytes, long lastTime, // Time is too short, so just lets continue return 0; } - return bytes * 1000 / limit - interval; + return ((bytes * 1000 / limit - interval)/10)*10; } @Override diff --git a/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java b/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java index 6976ac08c53..d8cfdb3fb67 100644 --- a/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java +++ b/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java @@ -248,9 +248,10 @@ public TrafficCounter(AbstractTrafficShapingHandler trafficShapingHandler, * @param newcheckInterval */ public void configure(long newcheckInterval) { - if (checkInterval.get() != newcheckInterval) { - checkInterval.set(newcheckInterval); - if (newcheckInterval <= 0) { + long newInterval = (newcheckInterval/10)*10; + if (checkInterval.get() != newInterval) { + checkInterval.set(newInterval); + if (newInterval <= 0) { stop(); // No more active monitoring lastTime.set(System.currentTimeMillis());
null
train
train
2012-05-19T13:19:24
"2012-05-19T08:24:33Z"
rzorzorzo
val
netty/netty/345_347
netty/netty
netty/netty/345
netty/netty/347
[ "keyword_pr_to_issue" ]
2a05afd418a12f437391bf83f18c97700615019d
b241fca16c06916ac4f2c4a1f8b85e9baddd38a1
[ "PS: if desired I could provide these changes.\n", "Hi @rzorzorzo \n\nOn the first item, I was really unaware of this ! Thanks for spotting this !\n\nOn the second item, I could agree but the idea is to be able to change the timer... (traffic handler could changed during runtime due to special request).\nHow could we do this ? I suppose that using the Timer utilitye from Netty will bring us to assigning again and again a new thread at every check (which is probably worst than having one specific thread per counter making some sleep) ?\nOn Counter, we need to have such one thread per Handler (one unique for Global, but if needed, one per Channel).\n\nI would be please if you can propose both, but perhaps in 2 separates proposal to be able to accept one or the other ?\n", "@rzorzorzo \nSince I was on my way to check some other elements, I may have done the first point (see #346).\n\nSorry if you were on your way... ;-)\nI will try to make the same on release 3.5 immediately.\n\nHowever on second proposal, I let you make some proposals... ;-)\n", "Frederic,\n\nthnx for 1.\n\nconcerning 2:\nTrafficCounter sleeps practically 100% of the time. During sleep, the thread is not returned to the pool. With 100k connections, therefore 100k channels, we will need with the current solution 100k threads. Not feasible.\n\nNetty's HashedWheelTimer requires a single Thread. The same timer, and therefore thread can be shared by all TrafficCounters. The dynamic change of checkIntervall can be supported as with the current implementation.\n\nMaybe the following code sections will help:\n\nfields:\n\n``` java\n private Timer timer; // replace executor\n private TimerTask timerTask; // created once in start()\n volatile private Timeout timeout = null; // used in stop() to cancel the timer\n```\n\nConstructor:\n\n``` java\n public TrafficCounter(TrafficShapingHandler trafficShapingHandler,\n Timer timer, String name, long checkInterval) { \n this.timer = timer;\n ...\n }\n```\n\nstart method\n\n``` java\n public void start() {\n...\n timerTask = new TimerTask()\n {\n\n @Override\n public void run(Timeout timeout) throws Exception\n {\n if (!monitorActive.get()) {\n return;\n }\n trafficMonitoring.run();\n TrafficCounter.this.timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS); \n }\n\n };\n timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS);\n...\n```\n\nstop method\n\n``` java\n public void stop() {\n...\n if (timeout != null)\n timeout.cancel();\n```\n\n-- Ron\n", "@rzorzorzo @fredericBregier this makes a lot of sense\n", "@rzorzorzo I will spend some time to your proposal, see if I understand first, then if I can propose a new version once I had tested it.\nThank you !!\n", "@rzorzorzo and @normanmaurer \nI finally make the change as proposed. I tested it intensively. I find no issue (as for now of course).\nI even optimize a bit more the traffic handler:\n- there were one thread created to unlock traffic from time to time when needed => Timer\n- in the original proposal, 2 objects were created: the TimerTask and the internal TrafficCOunter object => only the timer task now\n\nI hope this is what you guess both of you !\n\nSee proposal in Issue #348\n", "Cool.. I will review later today.\n", "Thank you @normanmaurer !\nAnd thank you too @rzorzorzo for these proposals!\n\nI believe we can close this issue then.\n" ]
[]
"2012-05-19T15:19:54Z"
[]
Enhancements to AbstractTrafficShapingHandler / TrafficCounter
1. do not sleep 101 ms due to issues with java and windows see: http://www.javamex.com/tutorials/threads/sleep_issues.shtml in getTimeToWait change return wait; to: return (wait/10)*10; 1. do not "waste" a thread in TrafficCounter. use netty's Timer instead. -- Ron
[ "src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java" ]
[ "src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java b/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java index 3cfb28e3900..2ec65af93b4 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java +++ b/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java @@ -358,7 +358,7 @@ private long getTimeToWait(long limit, long bytes, long lastTime, // Time is too short, so just lets continue return 0; } - return bytes * 1000 / limit - interval; + return ((bytes * 1000 / limit - interval)/10)*10; } @Override diff --git a/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java b/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java index 2fc4f0f2e0e..32a0a236e02 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java +++ b/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java @@ -247,9 +247,10 @@ public TrafficCounter(AbstractTrafficShapingHandler trafficShapingHandler, * @param newcheckInterval */ public void configure(long newcheckInterval) { - if (checkInterval.get() != newcheckInterval) { - checkInterval.set(newcheckInterval); - if (newcheckInterval <= 0) { + long newInterval = (newcheckInterval/10)*10; + if (checkInterval.get() != newInterval) { + checkInterval.set(newInterval); + if (newInterval <= 0) { stop(); // No more active monitoring lastTime.set(System.currentTimeMillis());
null
train
train
2012-05-18T22:16:17
"2012-05-19T08:24:33Z"
rzorzorzo
val
netty/netty/345_348
netty/netty
netty/netty/345
netty/netty/348
[ "keyword_pr_to_issue" ]
4bf2257d1adcaea802b0a1ca8802272b756905cc
154e9f152139bd2c8dd4d658149b0721a56a3300
[ "PS: if desired I could provide these changes.\n", "Hi @rzorzorzo \n\nOn the first item, I was really unaware of this ! Thanks for spotting this !\n\nOn the second item, I could agree but the idea is to be able to change the timer... (traffic handler could changed during runtime due to special request).\nHow could we do this ? I suppose that using the Timer utilitye from Netty will bring us to assigning again and again a new thread at every check (which is probably worst than having one specific thread per counter making some sleep) ?\nOn Counter, we need to have such one thread per Handler (one unique for Global, but if needed, one per Channel).\n\nI would be please if you can propose both, but perhaps in 2 separates proposal to be able to accept one or the other ?\n", "@rzorzorzo \nSince I was on my way to check some other elements, I may have done the first point (see #346).\n\nSorry if you were on your way... ;-)\nI will try to make the same on release 3.5 immediately.\n\nHowever on second proposal, I let you make some proposals... ;-)\n", "Frederic,\n\nthnx for 1.\n\nconcerning 2:\nTrafficCounter sleeps practically 100% of the time. During sleep, the thread is not returned to the pool. With 100k connections, therefore 100k channels, we will need with the current solution 100k threads. Not feasible.\n\nNetty's HashedWheelTimer requires a single Thread. The same timer, and therefore thread can be shared by all TrafficCounters. The dynamic change of checkIntervall can be supported as with the current implementation.\n\nMaybe the following code sections will help:\n\nfields:\n\n``` java\n private Timer timer; // replace executor\n private TimerTask timerTask; // created once in start()\n volatile private Timeout timeout = null; // used in stop() to cancel the timer\n```\n\nConstructor:\n\n``` java\n public TrafficCounter(TrafficShapingHandler trafficShapingHandler,\n Timer timer, String name, long checkInterval) { \n this.timer = timer;\n ...\n }\n```\n\nstart method\n\n``` java\n public void start() {\n...\n timerTask = new TimerTask()\n {\n\n @Override\n public void run(Timeout timeout) throws Exception\n {\n if (!monitorActive.get()) {\n return;\n }\n trafficMonitoring.run();\n TrafficCounter.this.timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS); \n }\n\n };\n timeout = timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS);\n...\n```\n\nstop method\n\n``` java\n public void stop() {\n...\n if (timeout != null)\n timeout.cancel();\n```\n\n-- Ron\n", "@rzorzorzo @fredericBregier this makes a lot of sense\n", "@rzorzorzo I will spend some time to your proposal, see if I understand first, then if I can propose a new version once I had tested it.\nThank you !!\n", "@rzorzorzo and @normanmaurer \nI finally make the change as proposed. I tested it intensively. I find no issue (as for now of course).\nI even optimize a bit more the traffic handler:\n- there were one thread created to unlock traffic from time to time when needed => Timer\n- in the original proposal, 2 objects were created: the TimerTask and the internal TrafficCOunter object => only the timer task now\n\nI hope this is what you guess both of you !\n\nSee proposal in Issue #348\n", "Cool.. I will review later today.\n", "Thank you @normanmaurer !\nAnd thank you too @rzorzorzo for these proposals!\n\nI believe we can close this issue then.\n" ]
[]
"2012-05-20T08:42:22Z"
[]
Enhancements to AbstractTrafficShapingHandler / TrafficCounter
1. do not sleep 101 ms due to issues with java and windows see: http://www.javamex.com/tutorials/threads/sleep_issues.shtml in getTimeToWait change return wait; to: return (wait/10)*10; 1. do not "waste" a thread in TrafficCounter. use netty's Timer instead. -- Ron
[ "src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java", "src/main/java/org/jboss/netty/handler/traffic/package-info.java" ]
[ "src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java", "src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java", "src/main/java/org/jboss/netty/handler/traffic/package-info.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java b/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java index 2ec65af93b4..fe0fdd2ed30 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java +++ b/src/main/java/org/jboss/netty/handler/traffic/AbstractTrafficShapingHandler.java @@ -15,7 +15,7 @@ */ package org.jboss.netty.handler.traffic; -import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.netty.channel.Channel; @@ -30,7 +30,9 @@ import org.jboss.netty.util.DefaultObjectSizeEstimator; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.ObjectSizeEstimator; -import org.jboss.netty.util.internal.ExecutorUtil; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.TimerTask; /** * AbstractTrafficShapingHandler allows to limit the global bandwidth @@ -41,6 +43,10 @@ * the method doAccounting of this handler.<br> * <br> * + * An {@link ObjectSizeEstimator} can be passed at construction to specify what + * is the size of the object to be read or write accordingly to the type of + * object. If not specified, it will used the {@link DefaultObjectSizeEstimator} implementation.<br><br> + * * If you want for any particular reasons to stop the monitoring (accounting) or to change * the read/write limit or the check interval, several methods allow that for you:<br> * <ul> @@ -79,10 +85,14 @@ public abstract class AbstractTrafficShapingHandler extends private ObjectSizeEstimator objectSizeEstimator; /** - * Executor to associated to any TrafficCounter + * Timer to associated to any TrafficCounter */ - protected Executor executor; - + protected Timer timer; + /** + * used in releaseExternalResources() to cancel the timer + */ + volatile private Timeout timeout = null; + /** * Limit in B/s to apply to write */ @@ -105,15 +115,16 @@ public abstract class AbstractTrafficShapingHandler extends */ final AtomicBoolean release = new AtomicBoolean(false); - private void init(ObjectSizeEstimator newObjectSizeEstimator, - Executor newExecutor, long newWriteLimit, long newReadLimit, long newCheckInterval) { - objectSizeEstimator = newObjectSizeEstimator; - executor = newExecutor; - writeLimit = newWriteLimit; - readLimit = newReadLimit; - checkInterval = newCheckInterval; - //logger.info("TSH: "+writeLimit+":"+readLimit+":"+checkInterval+":"+isPerChannel()); - } + private void init(ObjectSizeEstimator newObjectSizeEstimator, + Timer newTimer, long newWriteLimit, long newReadLimit, + long newCheckInterval) { + objectSizeEstimator = newObjectSizeEstimator; + timer = newTimer; + writeLimit = newWriteLimit; + readLimit = newReadLimit; + checkInterval = newCheckInterval; + //logger.warn("TSH: "+writeLimit+":"+readLimit+":"+checkInterval); + } /** * @@ -126,8 +137,8 @@ void setTrafficCounter(TrafficCounter newTrafficCounter) { /** * Constructor using default {@link ObjectSizeEstimator} * - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param writeLimit * 0 or a limit in bytes/s * @param readLimit @@ -136,10 +147,9 @@ void setTrafficCounter(TrafficCounter newTrafficCounter) { * The delay between two computations of performances for * channels or 0 if no stats are to be computed */ - public AbstractTrafficShapingHandler(Executor executor, long writeLimit, + public AbstractTrafficShapingHandler(Timer timer, long writeLimit, long readLimit, long checkInterval) { - init(new DefaultObjectSizeEstimator(), executor, writeLimit, readLimit, - checkInterval); + init(new DefaultObjectSizeEstimator(), timer, writeLimit, readLimit, checkInterval); } /** @@ -148,8 +158,8 @@ public AbstractTrafficShapingHandler(Executor executor, long writeLimit, * @param objectSizeEstimator * the {@link ObjectSizeEstimator} that will be used to compute * the size of the message - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param writeLimit * 0 or a limit in bytes/s * @param readLimit @@ -159,26 +169,24 @@ public AbstractTrafficShapingHandler(Executor executor, long writeLimit, * channels or 0 if no stats are to be computed */ public AbstractTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long writeLimit, long readLimit, long checkInterval) { - init(objectSizeEstimator, executor, writeLimit, readLimit, - checkInterval); + init(objectSizeEstimator, timer, writeLimit, readLimit, checkInterval); } /** * Constructor using default {@link ObjectSizeEstimator} and using default Check Interval * - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param writeLimit * 0 or a limit in bytes/s * @param readLimit * 0 or a limit in bytes/s */ - public AbstractTrafficShapingHandler(Executor executor, long writeLimit, + public AbstractTrafficShapingHandler(Timer timer, long writeLimit, long readLimit) { - init(new DefaultObjectSizeEstimator(), executor, writeLimit, readLimit, - DEFAULT_CHECK_INTERVAL); + init(new DefaultObjectSizeEstimator(), timer, writeLimit, readLimit, DEFAULT_CHECK_INTERVAL); } /** @@ -187,29 +195,27 @@ public AbstractTrafficShapingHandler(Executor executor, long writeLimit, * @param objectSizeEstimator * the {@link ObjectSizeEstimator} that will be used to compute * the size of the message - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param writeLimit * 0 or a limit in bytes/s * @param readLimit * 0 or a limit in bytes/s */ public AbstractTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long writeLimit, long readLimit) { - init(objectSizeEstimator, executor, writeLimit, readLimit, - DEFAULT_CHECK_INTERVAL); + init(objectSizeEstimator, timer, writeLimit, readLimit, DEFAULT_CHECK_INTERVAL); } /** * Constructor using default {@link ObjectSizeEstimator} and using NO LIMIT and default Check Interval * - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) */ - public AbstractTrafficShapingHandler(Executor executor) { - init(new DefaultObjectSizeEstimator(), executor, 0, 0, - DEFAULT_CHECK_INTERVAL); + public AbstractTrafficShapingHandler(Timer timer) { + init(new DefaultObjectSizeEstimator(), timer, 0, 0, DEFAULT_CHECK_INTERVAL); } /** @@ -218,25 +224,25 @@ public AbstractTrafficShapingHandler(Executor executor) { * @param objectSizeEstimator * the {@link ObjectSizeEstimator} that will be used to compute * the size of the message - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) */ public AbstractTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor) { - init(objectSizeEstimator, executor, 0, 0, DEFAULT_CHECK_INTERVAL); + ObjectSizeEstimator objectSizeEstimator, Timer timer) { + init(objectSizeEstimator, timer, 0, 0, DEFAULT_CHECK_INTERVAL); } /** * Constructor using default {@link ObjectSizeEstimator} and using NO LIMIT * - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param checkInterval * The delay between two computations of performances for * channels or 0 if no stats are to be computed */ - public AbstractTrafficShapingHandler(Executor executor, long checkInterval) { - init(new DefaultObjectSizeEstimator(), executor, 0, 0, checkInterval); + public AbstractTrafficShapingHandler(Timer timer, long checkInterval) { + init(new DefaultObjectSizeEstimator(), timer, 0, 0, checkInterval); } /** @@ -245,20 +251,24 @@ public AbstractTrafficShapingHandler(Executor executor, long checkInterval) { * @param objectSizeEstimator * the {@link ObjectSizeEstimator} that will be used to compute * the size of the message - * @param executor - * created for instance like Executors.newCachedThreadPool + * @param timer + * created once for instance like HashedWheelTimer(10, TimeUnit.MILLISECONDS, 1024) * @param checkInterval * The delay between two computations of performances for * channels or 0 if no stats are to be computed */ public AbstractTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long checkInterval) { - init(objectSizeEstimator, executor, 0, 0, checkInterval); + init(objectSizeEstimator, timer, 0, 0, checkInterval); } /** * Change the underlying limitations and check interval. + * + * @param newWriteLimit + * @param newReadLimit + * @param newCheckInterval */ public void configure(long newWriteLimit, long newReadLimit, long newCheckInterval) { @@ -268,17 +278,22 @@ public void configure(long newWriteLimit, long newReadLimit, /** * Change the underlying limitations. + * + * @param newWriteLimit + * @param newReadLimit */ public void configure(long newWriteLimit, long newReadLimit) { writeLimit = newWriteLimit; readLimit = newReadLimit; if (trafficCounter != null) { - trafficCounter.resetAccounting(System.currentTimeMillis() + 1); + trafficCounter.resetAccounting(System.currentTimeMillis()+1); } } /** * Change the check interval. + * + * @param newCheckInterval */ public void configure(long newCheckInterval) { checkInterval = newCheckInterval; @@ -300,45 +315,25 @@ protected void doAccounting(TrafficCounter counter) { /** * Class to implement setReadable at fix time - */ - private class ReopenRead implements Runnable { - /** - * Associated ChannelHandlerContext - */ - private ChannelHandlerContext ctx; - - /** - * Time to wait before clearing the channel - */ - private long timeToWait; - - /** - * @param ctx - * the associated channelHandlerContext - * @param timeToWait - */ - protected ReopenRead(ChannelHandlerContext ctx, long timeToWait) { + */ + private class ReopenReadTimerTask implements TimerTask { + ChannelHandlerContext ctx; + ReopenReadTimerTask(ChannelHandlerContext ctx) { this.ctx = ctx; - this.timeToWait = timeToWait; } - - /** - * Truly run the waken up of the channel - */ - public void run() { - try { - if (release.get()) { - return; - } - Thread.sleep(timeToWait); - } catch (InterruptedException e) { - // interruption so exit + public void run(Timeout timeoutArg) throws Exception { + //logger.warn("Start RRTT: "+release.get()); + if (release.get()) { return; } - // logger.info("WAKEUP!"); + /* + logger.warn("WAKEUP! "+ + (ctx != null && ctx.getChannel() != null && + ctx.getChannel().isConnected())); + */ if (ctx != null && ctx.getChannel() != null && ctx.getChannel().isConnected()) { - //logger.info(" setReadable TRUE: "+timeToWait); + //logger.warn(" setReadable TRUE: "); // readSuspended = false; ctx.setAttachment(null); ctx.getChannel().setReadable(true); @@ -374,17 +369,18 @@ public void messageReceived(ChannelHandlerContext arg0, MessageEvent arg1) return; } // compute the number of ms to wait before reopening the channel - long wait = getTimeToWait(readLimit, trafficCounter - .getCurrentReadBytes(), trafficCounter.getLastTime(), - curtime); - if (wait > MINIMAL_WAIT) { // At least 10ms seems a minimal time in order to + long wait = getTimeToWait(readLimit, + trafficCounter.getCurrentReadBytes(), + trafficCounter.getLastTime(), curtime); + if (wait >= MINIMAL_WAIT) { // At least 10ms seems a minimal + // time in order to Channel channel = arg0.getChannel(); // try to limit the traffic if (channel != null && channel.isConnected()) { // Channel version - if (executor == null) { + if (timer == null) { // Sleep since no executor - //logger.info("Read sleep since no executor for "+wait+" ms for "+this); + // logger.warn("Read sleep since no timer for "+wait+" ms for "+this); if (release.get()) { return; } @@ -395,11 +391,14 @@ public void messageReceived(ChannelHandlerContext arg0, MessageEvent arg1) // readSuspended = true; arg0.setAttachment(Boolean.TRUE); channel.setReadable(false); - //logger.info("Read will wakeup after "+wait+" ms "+this); - executor.execute(new ReopenRead(arg0, wait)); + // logger.warn("Read will wakeup after "+wait+" ms "+this); + TimerTask timerTask = new ReopenReadTimerTask(arg0); + timeout = timer.newTimeout(timerTask, wait, + TimeUnit.MILLISECONDS); } else { - // should be waiting: but can occurs sometime so as a FIX - //logger.info("Read sleep ok but should not be here: "+wait+" "+this); + // should be waiting: but can occurs sometime so as + // a FIX + // logger.warn("Read sleep ok but should not be here: "+wait+" "+this); if (release.get()) { return; } @@ -407,7 +406,7 @@ public void messageReceived(ChannelHandlerContext arg0, MessageEvent arg1) } } else { // Not connected or no channel - //logger.info("Read sleep "+wait+" ms for "+this); + // logger.warn("Read sleep "+wait+" ms for "+this); if (release.get()) { return; } @@ -432,11 +431,12 @@ public void writeRequested(ChannelHandlerContext arg0, MessageEvent arg1) if (writeLimit == 0) { return; } - // compute the number of ms to wait before continue with the channel - long wait = getTimeToWait(writeLimit, trafficCounter - .getCurrentWrittenBytes(), trafficCounter.getLastTime(), - curtime); - if (wait > MINIMAL_WAIT) { + // compute the number of ms to wait before continue with the + // channel + long wait = getTimeToWait(writeLimit, + trafficCounter.getCurrentWrittenBytes(), + trafficCounter.getLastTime(), curtime); + if (wait >= MINIMAL_WAIT) { // Global or Channel if (release.get()) { return; @@ -449,7 +449,6 @@ public void writeRequested(ChannelHandlerContext arg0, MessageEvent arg1) super.writeRequested(arg0, arg1); } } - @Override public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { @@ -485,7 +484,9 @@ public void releaseExternalResources() { trafficCounter.stop(); } release.set(true); - ExecutorUtil.terminate(executor); + if (timeout != null) { + timeout.cancel(); + } } @Override diff --git a/src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java b/src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java index 9ec72afd5ac..28389693ab8 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java +++ b/src/main/java/org/jboss/netty/handler/traffic/ChannelTrafficShapingHandler.java @@ -15,8 +15,6 @@ */ package org.jboss.netty.handler.traffic; -import java.util.concurrent.Executor; - import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; @@ -24,6 +22,7 @@ import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.util.ObjectSizeEstimator; +import org.jboss.netty.util.Timer; /** * This implementation of the {@link AbstractTrafficShapingHandler} is for channel @@ -33,8 +32,8 @@ * <ul> * <li>Add in your pipeline a new ChannelTrafficShapingHandler, before a recommended {@link ExecutionHandler} (like * {@link OrderedMemoryAwareThreadPoolExecutor} or {@link MemoryAwareThreadPoolExecutor}).<br> - * <tt>ChannelTrafficShapingHandler myHandler = new ChannelTrafficShapingHandler(executor);</tt><br> - * executor could be created using <tt>Executors.newCachedThreadPool();</tt><br> + * <tt>ChannelTrafficShapingHandler myHandler = new ChannelTrafficShapingHandler(timer);</tt><br> + * timer could be created using <tt>HashedWheelTimer<tt><br> * <tt>pipeline.addLast("CHANNEL_TRAFFIC_SHAPING", myHandler);</tt><br><br> * * <b>Note that this handler has a Pipeline Coverage of "one" which means a new handler must be created @@ -52,7 +51,7 @@ * the less precise the traffic shaping will be. It is suggested as higher value something close * to 5 or 10 minutes.<br> * </li> - * <li>When you shutdown your application, release all the external resources like the executor + * <li>When you shutdown your application, release all the external resources (except the timer internal itself) * by calling:<br> * <tt>myHandler.releaseExternalResources();</tt><br> * </li> @@ -60,96 +59,53 @@ */ public class ChannelTrafficShapingHandler extends AbstractTrafficShapingHandler { - /** - * @param executor - * @param writeLimit - * @param readLimit - * @param checkInterval - */ - public ChannelTrafficShapingHandler(Executor executor, long writeLimit, + public ChannelTrafficShapingHandler(Timer timer, long writeLimit, long readLimit, long checkInterval) { - super(executor, writeLimit, readLimit, checkInterval); + super(timer, writeLimit, readLimit, checkInterval); } - /** - * @param executor - * @param writeLimit - * @param readLimit - */ - public ChannelTrafficShapingHandler(Executor executor, long writeLimit, + public ChannelTrafficShapingHandler(Timer timer, long writeLimit, long readLimit) { - super(executor, writeLimit, readLimit); + super(timer, writeLimit, readLimit); } - - - /** - * @param executor - * @param checkInterval - */ - public ChannelTrafficShapingHandler(Executor executor, long checkInterval) { - super(executor, checkInterval); + + public ChannelTrafficShapingHandler(Timer timer, long checkInterval) { + super(timer, checkInterval); } - /** - * @param executor - */ - public ChannelTrafficShapingHandler(Executor executor) { - super(executor); + public ChannelTrafficShapingHandler(Timer timer) { + super(timer); } - /** - * @param objectSizeEstimator - * @param executor - * @param writeLimit - * @param readLimit - * @param checkInterval - */ public ChannelTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long writeLimit, long readLimit, long checkInterval) { - super(objectSizeEstimator, executor, writeLimit, readLimit, + super(objectSizeEstimator, timer, writeLimit, readLimit, checkInterval); } - /** - * @param objectSizeEstimator - * @param executor - * @param writeLimit - * @param readLimit - */ public ChannelTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long writeLimit, long readLimit) { - super(objectSizeEstimator, executor, writeLimit, readLimit); + super(objectSizeEstimator, timer, writeLimit, readLimit); } - /** - * @param objectSizeEstimator - * @param executor - * @param checkInterval - */ public ChannelTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor, + ObjectSizeEstimator objectSizeEstimator, Timer timer, long checkInterval) { - super(objectSizeEstimator, executor, checkInterval); + super(objectSizeEstimator, timer, checkInterval); } - /** - * @param objectSizeEstimator - * @param executor - */ public ChannelTrafficShapingHandler( - ObjectSizeEstimator objectSizeEstimator, Executor executor) { - super(objectSizeEstimator, executor); + ObjectSizeEstimator objectSizeEstimator, Timer timer) { + super(objectSizeEstimator, timer); } - @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (trafficCounter != null) { trafficCounter.stop(); - trafficCounter = null; } super.channelClosed(ctx, e); } @@ -162,8 +118,10 @@ public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) ctx.getChannel().setReadable(false); if (trafficCounter == null) { // create a new counter now - trafficCounter = new TrafficCounter(this, executor, "ChannelTC" + - ctx.getChannel().getId(), checkInterval); + if (timer != null) { + trafficCounter = new TrafficCounter(this, timer, "ChannelTC" + + ctx.getChannel().getId(), checkInterval); + } } if (trafficCounter != null) { trafficCounter.start(); diff --git a/src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java b/src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java index 7f54e28f296..b6f3f708f8a 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java +++ b/src/main/java/org/jboss/netty/handler/traffic/GlobalTrafficShapingHandler.java @@ -15,13 +15,12 @@ */ package org.jboss.netty.handler.traffic; -import java.util.concurrent.Executor; - import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.util.ObjectSizeEstimator; +import org.jboss.netty.util.Timer; /** * This implementation of the {@link AbstractTrafficShapingHandler} is for global @@ -31,8 +30,8 @@ * The general use should be as follow:<br> * <ul> * <li>Create your unique GlobalTrafficShapingHandler like:<br><br> - * <tt>GlobalTrafficShapingHandler myHandler = new GlobalTrafficShapingHandler(executor);</tt><br><br> - * executor could be created using <tt>Executors.newCachedThreadPool();</tt><br> + * <tt>GlobalTrafficShapingHandler myHandler = new GlobalTrafficShapingHandler(timer);</tt><br><br> + * timer could be created using <tt>HashedWheelTimer<tt><br> * <tt>pipeline.addLast("GLOBAL_TRAFFIC_SHAPING", myHandler);</tt><br><br> * * <b>Note that this handler has a Pipeline Coverage of "all" which means only one such handler must be created @@ -52,7 +51,7 @@ * {@link OrderedMemoryAwareThreadPoolExecutor} or {@link MemoryAwareThreadPoolExecutor}).<br> * <tt>pipeline.addLast("GLOBAL_TRAFFIC_SHAPING", myHandler);</tt><br><br> * </li> - * <li>When you shutdown your application, release all the external resources like the executor + * <li>When you shutdown your application, release all the external resources (except the timer internal itself) * by calling:<br> * <tt>myHandler.releaseExternalResources();</tt><br> * </li> @@ -64,96 +63,61 @@ public class GlobalTrafficShapingHandler extends AbstractTrafficShapingHandler { * Create the global TrafficCounter */ void createGlobalTrafficCounter() { - TrafficCounter tc = new TrafficCounter(this, executor, "GlobalTC", - checkInterval); - setTrafficCounter(tc); - tc.start(); + TrafficCounter tc; + if (timer != null) { + tc = new TrafficCounter(this, timer, "GlobalTC", + checkInterval); + setTrafficCounter(tc); + tc.start(); + } } - /** - * @param executor - * @param writeLimit - * @param readLimit - * @param checkInterval - */ - public GlobalTrafficShapingHandler(Executor executor, long writeLimit, + public GlobalTrafficShapingHandler(Timer timer, long writeLimit, long readLimit, long checkInterval) { - super(executor, writeLimit, readLimit, checkInterval); + super(timer, writeLimit, readLimit, checkInterval); createGlobalTrafficCounter(); } - /** - * @param executor - * @param writeLimit - * @param readLimit - */ - public GlobalTrafficShapingHandler(Executor executor, long writeLimit, + public GlobalTrafficShapingHandler(Timer timer, long writeLimit, long readLimit) { - super(executor, writeLimit, readLimit); + super(timer, writeLimit, readLimit); createGlobalTrafficCounter(); } - /** - * @param executor - * @param checkInterval - */ - public GlobalTrafficShapingHandler(Executor executor, long checkInterval) { - super(executor, checkInterval); + + public GlobalTrafficShapingHandler(Timer timer, long checkInterval) { + super(timer, checkInterval); createGlobalTrafficCounter(); } - /** - * @param executor - */ - public GlobalTrafficShapingHandler(Executor executor) { - super(executor); + public GlobalTrafficShapingHandler(Timer timer) { + super(timer); createGlobalTrafficCounter(); } - /** - * @param objectSizeEstimator - * @param executor - * @param writeLimit - * @param readLimit - * @param checkInterval - */ public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator, - Executor executor, long writeLimit, long readLimit, + Timer timer, long writeLimit, long readLimit, long checkInterval) { - super(objectSizeEstimator, executor, writeLimit, readLimit, + super(objectSizeEstimator, timer, writeLimit, readLimit, checkInterval); createGlobalTrafficCounter(); } - /** - * @param objectSizeEstimator - * @param executor - * @param writeLimit - * @param readLimit - */ public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator, - Executor executor, long writeLimit, long readLimit) { - super(objectSizeEstimator, executor, writeLimit, readLimit); + Timer timer, long writeLimit, long readLimit) { + super(objectSizeEstimator, timer, writeLimit, readLimit); createGlobalTrafficCounter(); } - /** - * @param objectSizeEstimator - * @param executor - * @param checkInterval - */ public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator, - Executor executor, long checkInterval) { - super(objectSizeEstimator, executor, checkInterval); + Timer timer, long checkInterval) { + super(objectSizeEstimator, timer, checkInterval); createGlobalTrafficCounter(); } - /** - * @param objectSizeEstimator - * @param executor - */ public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator, - Executor executor) { - super(objectSizeEstimator, executor); + Timer timer) { + super(objectSizeEstimator, timer); createGlobalTrafficCounter(); } + } diff --git a/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java b/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java index 32a0a236e02..2a63e5bf9a1 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java +++ b/src/main/java/org/jboss/netty/handler/traffic/TrafficCounter.java @@ -15,11 +15,14 @@ */ package org.jboss.netty.handler.traffic; -import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.TimerTask; /** * TrafficCounter is associated with {@link AbstractTrafficShapingHandler}.<br> @@ -97,27 +100,31 @@ public class TrafficCounter { /** * The associated TrafficShapingHandler */ - private AbstractTrafficShapingHandler trafficShapingHandler; + private final AbstractTrafficShapingHandler trafficShapingHandler; /** - * Default Executor + * One Timer for all Counter */ - private Executor executor; - + private final Timer timer; // replace executor /** - * Is Monitor active + * Monitor created once in start() */ - AtomicBoolean monitorActive = new AtomicBoolean(); + private TimerTask timerTask; + /** + * used in stop() to cancel the timer + */ + volatile private Timeout timeout = null; /** - * Monitor + * Is Monitor active */ - private TrafficMonitoring trafficMonitoring; + AtomicBoolean monitorActive = new AtomicBoolean(); /** * Class to implement monitoring at fix delay - */ - private static class TrafficMonitoring implements Runnable { + * + */ + private static class TrafficMonitoringTask implements TimerTask { /** * The associated TrafficShapingHandler */ @@ -132,42 +139,30 @@ private static class TrafficMonitoring implements Runnable { * @param trafficShapingHandler * @param counter */ - protected TrafficMonitoring( + protected TrafficMonitoringTask( AbstractTrafficShapingHandler trafficShapingHandler, TrafficCounter counter) { trafficShapingHandler1 = trafficShapingHandler; this.counter = counter; } - /** - * Default run - */ - public void run() { - try { - Thread.currentThread().setName(counter.name); - for (; counter.monitorActive.get();) { - long check = counter.checkInterval.get(); - if (check > 0) { - Thread.sleep(check); - } else { - // Delay goes to 0, so exit - return; - } - long endTime = System.currentTimeMillis(); - counter.resetAccounting(endTime); - if (trafficShapingHandler1 != null) { - trafficShapingHandler1.doAccounting(counter); - } - } - } catch (InterruptedException e) { - // End of computations + public void run(Timeout timeout) throws Exception { + if (!counter.monitorActive.get()) { + return; } + long endTime = System.currentTimeMillis(); + counter.resetAccounting(endTime); + if (trafficShapingHandler1 != null) { + trafficShapingHandler1.doAccounting(counter); + } + timeout = + counter.timer.newTimeout(this, counter.checkInterval.get(), TimeUnit.MILLISECONDS); } } /** * Start the monitoring process - */ + */ public void start() { synchronized (lastTime) { if (monitorActive.get()) { @@ -176,16 +171,16 @@ public void start() { lastTime.set(System.currentTimeMillis()); if (checkInterval.get() > 0) { monitorActive.set(true); - trafficMonitoring = new TrafficMonitoring( - trafficShapingHandler, this); - executor.execute(trafficMonitoring); + timerTask = new TrafficMonitoringTask(trafficShapingHandler, this); + timeout = + timer.newTimeout(timerTask, checkInterval.get(), TimeUnit.MILLISECONDS); } } } /** * Stop the monitoring process - */ + */ public void stop() { synchronized (lastTime) { if (!monitorActive.get()) { @@ -196,6 +191,9 @@ public void stop() { if (trafficShapingHandler != null) { trafficShapingHandler.doAccounting(this); } + if (timeout != null) { + timeout.cancel(); + } } } @@ -221,20 +219,20 @@ void resetAccounting(long newLastTime) { } /** - * Constructor with the {@link AbstractTrafficShapingHandler} that hosts it, the executorService to use, its + * Constructor with the {@link AbstractTrafficShapingHandler} that hosts it, the Timer to use, its * name, the checkInterval between two computations in millisecond * @param trafficShapingHandler the associated AbstractTrafficShapingHandler - * @param executor - * Should be a CachedThreadPool for efficiency + * @param timer + * Could be a HashedWheelTimer * @param name * the name given to this monitor * @param checkInterval * the checkInterval in millisecond between two computations */ public TrafficCounter(AbstractTrafficShapingHandler trafficShapingHandler, - Executor executor, String name, long checkInterval) { + Timer timer, String name, long checkInterval) { this.trafficShapingHandler = trafficShapingHandler; - this.executor = executor; + this.timer = timer; this.name = name; lastCumulativeTime = System.currentTimeMillis(); configure(checkInterval); diff --git a/src/main/java/org/jboss/netty/handler/traffic/package-info.java b/src/main/java/org/jboss/netty/handler/traffic/package-info.java index 25321804cb0..50ed87d3d5a 100644 --- a/src/main/java/org/jboss/netty/handler/traffic/package-info.java +++ b/src/main/java/org/jboss/netty/handler/traffic/package-info.java @@ -17,26 +17,28 @@ /** * Implementation of a Traffic Shaping Handler and Dynamic Statistics.<br> * <br><br> + * + * * <P>The main goal of this package is to allow to shape the traffic (bandwidth limitation), * but also to get statistics on how many bytes are read or written. Both functions can * be active or inactive (traffic or statistics).</P> * * <P>Two classes implement this behavior:<br> * <ul> - * <li> <tt>{@link org.jboss.netty.handler.traffic.TrafficCounter}</tt>: this class implements the counters needed by the handlers. + * <li> <tt>{@link TrafficCounter}</tt>: this class implements the counters needed by the handlers. * It can be accessed to get some extra information like the read or write bytes since last check, the read and write * bandwidth from last check...</li><br><br> * - * <li> <tt>{@link org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler}</tt>: this abstract class implements the kernel + * <li> <tt>{@link AbstractTrafficShapingHandler}</tt>: this abstract class implements the kernel * of the traffic shaping. It could be extended to fit your needs. Two classes are proposed as default - * implementations: see {@link org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler} and see {@link org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler} + * implementations: see {@link ChannelTrafficShapingHandler} and see {@link GlobalTrafficShapingHandler} * respectively for Channel traffic shaping and Global traffic shaping.</li><br><br> * * The insertion in the pipeline of one of those handlers can be wherever you want, but - * <b>it must be placed before any <tt>{@link org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor}</tt> - * in your pipeline</b>.<br> - * <b><i>It is really recommended to have such a</i> <tt>{@link org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor}</tt> - * <i>(either non ordered or </i> <tt>{@link org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor}</tt> + * <b>it must be placed before any <tt>{@link MemoryAwareThreadPoolExecutor}</tt> + * in your pipeline</b>.</li><br> + * <b><i>It is really recommended to have such a</i> <tt>{@link MemoryAwareThreadPoolExecutor}</tt> + * <i>(either non ordered or </i> <tt>{@link OrderedMemoryAwareThreadPoolExecutor}</tt> * <i>) in your pipeline</i></b> * when you want to use this feature with some real traffic shaping, since it will allow to relax the constraint on * NioWorker to do other jobs if necessary.<br> @@ -48,9 +50,9 @@ * 60KB/s for each channel since NioWorkers are stopping by this handler.<br> * When it is used as a read traffic shaper, the handler will set the channel as not readable, so as to relax the * NioWorkers.<br><br> - * An {@link org.jboss.netty.util.ObjectSizeEstimator} can be passed at construction to specify what + * An {@link ObjectSizeEstimator} can be passed at construction to specify what * is the size of the object to be read or write accordingly to the type of - * object. If not specified, it will used the {@link org.jboss.netty.util.DefaultObjectSizeEstimator} implementation.<br><br> + * object. If not specified, it will used the {@link DefaultObjectSizeEstimator} implementation.<br><br> * </ul></P> * * <P>Standard use could be as follow:</P> @@ -60,27 +62,27 @@ * [Global or per Channel] [Write or Read] Limitation in byte/s.</li><br> * A value of <tt>0</tt> * stands for no limitation, so the traffic shaping is deactivate (on what you specified).<br> - * You can either change those values with the method <tt>configure</tt> in {@link org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler}.<br> + * You can either change those values with the method <tt>configure</tt> in {@link AbstractTrafficShapingHandler}.<br> * <br> * * <li>To activate or deactivate the statistics, you can adjust the delay to a low (suggested not less than 200ms * for efficiency reasons) or a high value (let say 24H in millisecond is huge enough to not get the problem) * or even using <tt>0</tt> which means no computation will be done.</li><br> * If you want to do anything with this statistics, just override the <tt>doAccounting</tt> method.<br> - * This interval can be changed either from the method <tt>configure</tt> in {@link org.jboss.netty.handler.traffic.AbstractTrafficShapingHandler} - * or directly using the method <tt>configure</tt> of {@link org.jboss.netty.handler.traffic.TrafficCounter}.<br><br> + * This interval can be changed either from the method <tt>configure</tt> in {@link AbstractTrafficShapingHandler} + * or directly using the method <tt>configure</tt> of {@link TrafficCounter}.<br><br> * * </ul></P><br><br> * * <P>So in your application you will create your own TrafficShapingHandler and set the values to fit your needs.</P> - * <tt>XXXXXTrafficShapingHandler myHandler = new XXXXXTrafficShapingHandler(executor);</tt><br><br> - * where executor could be created using <tt>Executors.newCachedThreadPool();</tt> and XXXXX could be either + * <tt>XXXXXTrafficShapingHandler myHandler = new XXXXXTrafficShapingHandler(timer);</tt><br><br> + * timer could be created using <tt>HashedWheelTimer<tt> and XXXXX could be either * Global or Channel<br> * <tt>pipeline.addLast("XXXXX_TRAFFIC_SHAPING", myHandler);</tt><br> * <tt>...</tt><br> * <tt>pipeline.addLast("MemoryExecutor",new ExecutionHandler(memoryAwareThreadPoolExecutor));</tt><br><br> - * <P>Note that a new {@link org.jboss.netty.handler.traffic.ChannelTrafficShapingHandler} must be created for each new channel, - * but only one {@link org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler} must be created for all channels.</P> + * <P>Note that a new {@link ChannelTrafficShapingHandler} must be created for each new channel, + * but only one {@link GlobalTrafficShapingHandler} must be created for all channels.</P> * * <P>Note also that you can create different GlobalTrafficShapingHandler if you want to separate classes of * channels (for instance either from business point of view or from bind address point of view).</P>
null
train
train
2012-05-19T20:51:25
"2012-05-19T08:24:33Z"
rzorzorzo
val
netty/netty/378_379
netty/netty
netty/netty/378
netty/netty/379
[ "timestamp(timedelta=148.0, similarity=0.8879426217002148)" ]
f34fc73e89e88da32c36786c8634afa9dc090207
40f4ee22fb7f9790d7ec936c692944b54f2c4337
[ "This bug has consequences on downstream projects depending on Netty:\n\nhttps://play.lighthouseapp.com/projects/82401-play-20/tickets/511-adding-a-cookie-twice-to-a-result-doesnt-override-the-old-cookie\n", "Pull request: https://github.com/netty/netty/pull/379\n", "Merged into '3' and 'master'. Thanks!\n" ]
[]
"2012-06-02T22:05:46Z"
[ "defect" ]
DefaultCookie equals and compareTo implementation wrong
The equals and compareTo implementations in DefaultCookie are wrong. Sample code from the equals method: ``` if (getPath() == null && that.getPath() != null) { return false; } else if (that.getPath() == null) { return false; } if (!getPath().equals(that.getPath())) { return false; } ``` If path on both this and that is null, then the above code returns false, even though the cookies may be equal. The problem is in the else if statement, it should also check if getPath() doesn't equal null. This affects both the equals and the compareTo methods, with the path and domain properties.
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java index e94e5dc145f..cb5d3c6eaeb 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultCookie.java @@ -273,7 +273,7 @@ public boolean equals(Object o) { if (getPath() == null && that.getPath() != null) { return false; - } else if (that.getPath() == null) { + } else if (that.getPath() == null && getPath() != null) { return false; } if (!getPath().equals(that.getPath())) { @@ -282,7 +282,7 @@ public boolean equals(Object o) { if (getDomain() == null && that.getDomain() != null) { return false; - } else if (that.getDomain() == null) { + } else if (that.getDomain() == null && getDomain() != null) { return false; } return getDomain().equalsIgnoreCase(that.getDomain()); @@ -298,7 +298,7 @@ public int compareTo(Cookie c) { if (getPath() == null && c.getPath() != null) { return -1; - } else if (c.getPath() == null) { + } else if (c.getPath() == null && getPath() != null) { return 1; } v = getPath().compareTo(c.getPath()); @@ -308,7 +308,7 @@ public int compareTo(Cookie c) { if (getDomain() == null && c.getDomain() != null) { return -1; - } else if (c.getDomain() == null) { + } else if (c.getDomain() == null && getDomain() != null) { return 1; } v = getDomain().compareToIgnoreCase(c.getDomain());
null
train
train
2012-06-02T20:13:58
"2012-06-02T21:49:37Z"
jroper
val
netty/netty/398_399
netty/netty
netty/netty/398
netty/netty/399
[ "keyword_pr_to_issue" ]
df11cfab255c376ed0f2482156b9a5dd35a9f2f4
472d0a3c4ece00b17b979e58f78fdb1293797607
[ "So the JVM implementation is buggy (not the Netty one), since the transferTo method on FileChannel should be optimized carefully in JVM, taking in consideration the memory footprint. If I'm correct, this method is system optimized, so the reason we used it.\nAnd for the record, the \"renameTo\" method of Netty first tries to use the simplest \"renameTo\" method on File directly, since it is the most efficient one, then if not possible (such as different FileSystem under the wood), then it must copy and delete manually.\n\nSo we need to make the second part fully manually and not using the FileChannel optimization... This is a sad news, as it will be less efficient than the native one.\nAm I correct ?\n\nNow the issue is the optimal chunk size. For nowadays, 8KB could be considered as a good tradeoff among all filesystems implementation...\n", "I meant we can call transferTo() multiple times with smaller length parameter, rather than completely falling back to old I/O.\n", "I update the proposal accordingly. Thank @trustin and @normanmaurer \n", "Should correct the issue...\nShould we ask the user to check first before to close this issue?\n", "Just close it and tell him that it will be part of 3.5.1.Final ;)\n\n2012/6/15 Frédéric Brégier\[email protected]:\n\n> Should correct the issue...\n> Should we ask the user to check first before to close this issue?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/398#issuecomment-6353273\n" ]
[]
"2012-06-15T06:18:25Z"
[ "defect" ]
AbstractDiskHttpData.renameTo() can fail when mmap'ing fails.
See: http://stackoverflow.com/questions/11006968/netty-file-upload-out-of-memory-error The current implementation of `renameTo` is not correct. It has to copy data chunk by chunk (e.g. 8KiB) instead of issuing full transfer at once.
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java index 0df3500de38..010bd1d55ff 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java @@ -289,10 +289,17 @@ public boolean renameTo(File dest) throws IOException { FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); - long destsize = in.transferTo(0, size, out); + int chunkSize = 8196; + long position = 0; + while (position < size) { + if (chunksize < size - position) { + chunksize = size - position; + } + position += in.transferTo(position, chunkSize , out); + } in.close(); out.close(); - if (destsize == size) { + if (position == size) { file.delete(); file = dest; isRenamed = true;
null
val
train
2012-06-13T11:22:37
"2012-06-15T02:05:03Z"
trustin
val
netty/netty/398_400
netty/netty
netty/netty/398
netty/netty/400
[ "keyword_pr_to_issue" ]
6d29d2feb193214b5e548f570f3b8e25a1e3637e
fe59cd1631d80542b908f4621000ee0d911131ae
[ "So the JVM implementation is buggy (not the Netty one), since the transferTo method on FileChannel should be optimized carefully in JVM, taking in consideration the memory footprint. If I'm correct, this method is system optimized, so the reason we used it.\nAnd for the record, the \"renameTo\" method of Netty first tries to use the simplest \"renameTo\" method on File directly, since it is the most efficient one, then if not possible (such as different FileSystem under the wood), then it must copy and delete manually.\n\nSo we need to make the second part fully manually and not using the FileChannel optimization... This is a sad news, as it will be less efficient than the native one.\nAm I correct ?\n\nNow the issue is the optimal chunk size. For nowadays, 8KB could be considered as a good tradeoff among all filesystems implementation...\n", "I meant we can call transferTo() multiple times with smaller length parameter, rather than completely falling back to old I/O.\n", "I update the proposal accordingly. Thank @trustin and @normanmaurer \n", "Should correct the issue...\nShould we ask the user to check first before to close this issue?\n", "Just close it and tell him that it will be part of 3.5.1.Final ;)\n\n2012/6/15 Frédéric Brégier\[email protected]:\n\n> Should correct the issue...\n> Should we ask the user to check first before to close this issue?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/398#issuecomment-6353273\n" ]
[]
"2012-06-15T17:42:24Z"
[ "defect" ]
AbstractDiskHttpData.renameTo() can fail when mmap'ing fails.
See: http://stackoverflow.com/questions/11006968/netty-file-upload-out-of-memory-error The current implementation of `renameTo` is not correct. It has to copy data chunk by chunk (e.g. 8KiB) instead of issuing full transfer at once.
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java b/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java index 010bd1d55ff..e1400cae675 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/multipart/AbstractDiskHttpData.java @@ -292,8 +292,8 @@ public boolean renameTo(File dest) throws IOException { int chunkSize = 8196; long position = 0; while (position < size) { - if (chunksize < size - position) { - chunksize = size - position; + if (chunkSize < size - position) { + chunkSize = (int) (size - position); } position += in.transferTo(position, chunkSize , out); }
null
train
train
2012-06-15T12:04:34
"2012-06-15T02:05:03Z"
trustin
val
netty/netty/414_415
netty/netty
netty/netty/414
netty/netty/415
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.8466891398433595)" ]
33c42bee6d2cbc1fadecbb82440ddff9e13e1692
a60db57faa54e475fbc776827ee7c3a0ee018ca5
[ "I understand the probable need.\nHere are some remarks on my side:\n\n1- a clear documentation must indicate that the returned ByteBuf is limited to the portion of bytes where the index given is physically located\n\n2- why do you make \n\n```\nreturn components[componentId].duplicate();\n```\n\ninstead of\n\n```\nreturn components[componentId];\n```\n\nSORRY: bad interpretation of duplicate, but still point 2 and 3 together are valid comments...\n\n> erroneous: This should even limitated the in-memory copy process... But if you do need a copy, then maybe you should explicitely duplicate it from the output, not from the method ? \n\n3- Moreover, I think duplicate() is changing the index of the duplicated ByteBuf (0, buf.capacity), instead of\n\n```\n ByteBuf buf = components[componentId];\n return buf.slice(buf.readerIndex(), buf.readableBytes());\n```\n\nWhat do you think ?\n", "Agreed on the documentation, it should be stated that this is an expert method. As such, btw, I don't see a reason to duplicate the buffer, if the \"expert\" in this case wishes to, he can do it.\n\nAs for the implementation, it an overhead something like this will work:\n\n```\n return components(componentId(index));\n```\n", "Thanks, guys! I've pushed up a new commit with your suggestions.\n", "I can't make the change for proposal from where I am now, but I do agree with @kimchy comment:\n\n```\nreturn components(componentId(index));\n```\n\nAnd for the comment, could be something like:\n\n```\n/**\n* Return the underlying ByteBuf region that contains the index element. Expert method only\n*\n* Modifying the content of the returned buffer or this buffer affects\n* each other's content. They do shared the same indexes and marks.\n* It is therefore recommended to use a slice() of the returned buffer except\n* if you know what you are doing.\n*\n* @param index the index that is included in the returned ByteBuf\n* @return the ByteBuf containing the index\n* \n* @throws IndexOutOfBoundsException\n* if the specified {@code index} is less than {@code this.readerIndex()} or\n* is greater than {@code this.readerIndex()+this.readableBytes()}\n*/\n```\n", "Also I come back with the initial test (that throws the exception).\n\nIs it ok to test from 0 to capacity or should it be between global readerIndex and global readableBytes ?\nI believe that you do want a piece of buffer that is valid (and no more sliced out of the composite buffer) ?\n", "@CruzBishop so according to me it is fine\n@trustin or @normanmaurer , are you ok with this proposal ?\n", "Seems to be fine - You know new code, it works until somebody abuses it :P\n", "Will review later today\n\nSent from my iPhone. Excuse any typos....\n\nAm 29.06.2012 um 10:15 schrieb Frédéric Bré[email protected]:\n\n> @CruzBishop so according to me it is fine\n> @trustin or @normanmaurer , are you ok with this proposal ?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/414#issuecomment-6654512\n", "Thanks, Norman!\n" ]
[]
"2012-06-28T00:26:00Z"
[]
CompositeChannelBuffer: Add expert method to return the ChannelBuffer for a specific index
It would be nice to add an expert method to CompositeChannelBuffer that allows to get the ChannelBuffer for a specific index. Pretty simple to add, would help a lot in my case when trying to optimize buffer copies when possible. If it makes sense, I can easily send a pull request.
[ "buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/AbstractCompositeChannelBufferTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java b/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java index 9329de90231..ca86eb3cd06 100644 --- a/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java @@ -575,6 +575,34 @@ private void copyTo(int index, int length, int componentId, ByteBuf dst) { dst.writerIndex(dst.capacity()); } + /** + * Returns the {@link ByteBuf} portion of this {@link CompositeByteBuf} that + * contains the specified {@code index}. This is an expert method! + * + * <p> + * Please note that since a {@link CompositeByteBuf} is made up of + * multiple {@link ByteBuf}s, this does <em>not</em> return the full buffer. + * Instead, it only returns a portion of the composite buffer where the + * index is located + * </p> + * + * @param index The {@code index} to search for and include in the returned {@link ByteBuf} + * @return The {@link ByteBuf} that contains the specified {@code index} + * @throws IndexOutOfBoundsException when the specified {@code index} is + * less than zero, or larger than {@code capacity()} + */ + public ByteBuf getBufferFor(int index) throws IndexOutOfBoundsException { + if (index < 0 || index >= capacity()) { + throw new IndexOutOfBoundsException("Invalid index: " + index + + " - Bytes needed: " + index + ", maximum is " + + capacity()); + } + + //Return the component byte buffer + return components[componentId(index)]; + + } + @Override public ByteBuf slice(int index, int length) { if (index == 0) {
diff --git a/buffer/src/test/java/io/netty/buffer/AbstractCompositeChannelBufferTest.java b/buffer/src/test/java/io/netty/buffer/AbstractCompositeChannelBufferTest.java index 2d68c5cd1d3..86fa2a50098 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractCompositeChannelBufferTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractCompositeChannelBufferTest.java @@ -16,6 +16,7 @@ package io.netty.buffer; import static io.netty.buffer.Unpooled.*; +import java.io.IOException; import static org.junit.Assert.*; import java.nio.ByteBuffer; @@ -89,6 +90,29 @@ protected ByteBuf[] components() { protected boolean discardReadBytesDoesNotMoveWritableBytes() { return false; } + + /** + * Tests the "getBufferFor" method + */ + @Test + public void testGetBufferFor() throws IOException { + CompositeByteBuf buf = (CompositeByteBuf) Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4, 5 }, new byte[] {4, 5, 6, 7, 8, 9, 26}); + + //Ensure that a random place will be fine + assertEquals(buf.getBufferFor(2).capacity(), 5); + + //Loop through each byte + + byte index = 0; + + while (index < buf.capacity()) { + ByteBuf _buf = buf.getBufferFor(index++); + assertNotNull(_buf); + assertTrue(_buf.capacity() > 0); + assertNotNull(_buf.getByte(0)); + assertNotNull(_buf.getByte(_buf.readableBytes() - 1)); + } + } @Test public void testDiscardReadBytes3() {
train
train
2012-06-28T14:08:01
"2012-06-27T23:44:44Z"
kimchy
val
netty/netty/434_436
netty/netty
netty/netty/434
netty/netty/436
[ "keyword_pr_to_issue" ]
f16c7472deac81ea54c29b84e07fc6756f8b608e
4936ac4dc481bc70c447fb667a8820cba77c73c9
[ "I understand your concern, but according to RFC 1867, chapter 5.9 :\n\n```\n5.9 CRLF used as line separator\n\n As with all MIME transmissions, CRLF is used as the separator for\n lines in a POST of the data in multipart/form-data.\n```\n\nSo my guess is that the Adobe Flash Uploader code is incorrect... ?\nThe issue is that if we look for only the last '--' then what happens with conforming upload where there is a 'crlf' after the last '--'... ? We will have then issues for all other clients/servers since those 2 caracters will not be ignored...\nI don't see yet a good way of doing...\n", "Perhaps look for the CRLF. If that's not found, back up a few characters and look for the -- as well?\n", "Of course, you'd have to log a warning stating that an application is not conforming to the standards ;)\n", "@CruzBishop +1\n", "OK, I will try later today to see what I can propose...\n", "I propose a fix for issue #434 to provide the ability to stop even if no CRLF is provided since some clients as Adobe Flash will not finish the closing delimiter with a CRLF.\n\nNote however that there is one \"hole\" in the proposal:\n- if one chunk is enough to fullfill the closing delimiter but not enough to get the CRLF\n- but the next chunk will provide this CRLF\n => the code may be wrong (while it should ignore the next CRLF from the next chunk).\n\nIf you have a better idea (the code shows 2 // FIXME as comments)\n", "I figured the problem would be the multipart upload implementation of the Flash Uploader. But I see you've finally found a solution. Great! Just in one day!\n\nI suppose it is not fair that servers have to fix client pitfalls.\n\nSo, thanks a lot.\n" ]
[]
"2012-07-03T13:05:44Z"
[]
HttpPostRequestDecoder doesn't work if last disposition delimiter doesn't end with CRLF
Some Adobe Flash based uploaders such as SWFUpload doesn't end the last disposition delimiter with CRLF. > SWFUpload sends this: > ------------ei4ae0GI3Ef1gL6Ij5gL6gL6ei4KM7-- > > instead of this: > ------------ei4ae0GI3Ef1gL6Ij5gL6gL6ei4KM7--\r\n So multipart uploads always fail with an "ErrorDataDecoderException: No Multipart delimiter found". We can make it work with some tricks, such as this: ``` java private static final HttpChunk CRLF = new DefaultHttpChunk(copiedBuffer("\r\n", Charset.forName("UTF-8"))); decoder.offer(CRLF); decoder.offer(HttpChunk.LAST_CHUNK); ``` Always offering the CRLF before the LAST_CHUNK, and we transform all HttpRequests in chunked requests to make this work. I found that the problem is in readline method (line 1247 of HttpPostRequestDecoder.java) "private String readLine() throws NotEnoughDataDecoderException": ``` java if (nextByte == HttpConstants.CR) { if (sao.pos < sao.limit) { nextByte = sao.bytes[sao.pos ++]; if (nextByte == HttpConstants.LF) { sao.setReadPosition(0); return sb.toString(); } } else { sb.append((char) nextByte); } } else .... ``` If the LF is not found, the end of the method runs: ``` java undecodedChunk.readerIndex(readerIndex); throw new NotEnoughDataDecoderException(); ``` Maybe it would be better to look for the last "--" after the delimiter "------------ei4ae0GI3Ef1gL6Ij5gL6gL6ei4KM7" instead of the CRLF.
[ "src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java", "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java" ]
[ "src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java", "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java index 4e844afdfbf..5a23e729f60 100644 --- a/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java +++ b/src/main/java/org/jboss/netty/example/http/upload/HttpUploadServerHandler.java @@ -360,9 +360,10 @@ private void writeResponse(Channel channel) { CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie: cookies) { cookieEncoder.addCookie(cookie); + response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder + .encode()); + cookieEncoder = new CookieEncoder(true); } - response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder - .encode()); } // Write the response. ChannelFuture future = channel.write(response); diff --git a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java index 30826d90f9f..324c9c6639a 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java @@ -894,7 +894,7 @@ private InterfaceHttpData findMultipartDelimiter(String delimiter, skipOneLine(); String newline; try { - newline = readLine(); + newline = readDelimiter(delimiter); } catch (NotEnoughDataDecoderException e) { undecodedChunk.readerIndex(readerIndex); return null; @@ -1281,6 +1281,202 @@ private String readLine() throws NotEnoughDataDecoderException { throw new NotEnoughDataDecoderException(); } + /** + * Read one line up to --delimiter or --delimiter-- and if existing the CRLF or LF + * Read one line up to --delimiter or --delimiter-- and if existing the CRLF or LF. + * Note that CRLF or LF are mandatory for opening delimiter (--delimiter) but not for + * closing delimiter (--delimiter--) since some clients does not include CRLF in this case. + * + * @param delimiter of the form --string, such that '--' is already included + * @return the String from one line as the delimiter searched (opening or closing) + * @throws NotEnoughDataDecoderException Need more chunks and + * reset the readerInder to the previous value + */ + private String readDelimiterStandard(String delimiter) throws NotEnoughDataDecoderException { + int readerIndex = undecodedChunk.readerIndex(); + try { + StringBuilder sb = new StringBuilder(64); + int delimiterPos = 0; + int len = delimiter.length(); + while (undecodedChunk.readable() && delimiterPos < len) { + byte nextByte = undecodedChunk.readByte(); + if (nextByte == delimiter.charAt(delimiterPos)) { + delimiterPos++; + sb.append((char) nextByte); + } else { + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } + // Now check if either opening delimiter or closing delimiter + if (undecodedChunk.readable()) { + byte nextByte = undecodedChunk.readByte(); + // first check for opening delimiter + if (nextByte == HttpConstants.CR) { + nextByte = undecodedChunk.readByte(); + if (nextByte == HttpConstants.LF) { + return sb.toString(); + } else { + // error since CR must be followed by LF + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } else if (nextByte == HttpConstants.LF) { + return sb.toString(); + } else if (nextByte == '-') { + sb.append((char) nextByte); + // second check for closing delimiter + nextByte = undecodedChunk.readByte(); + if (nextByte == '-') { + sb.append((char) nextByte); + // now try to find if CRLF or LF there + if (undecodedChunk.readable()) { + nextByte = undecodedChunk.readByte(); + if (nextByte == HttpConstants.CR) { + nextByte = undecodedChunk.readByte(); + if (nextByte == HttpConstants.LF) { + return sb.toString(); + } else { + // error CR without LF + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } else if (nextByte == HttpConstants.LF) { + return sb.toString(); + } else { + // No CRLF but ok however (Adobe Flash uploader) + // minus 1 since we read one char ahead but should not + undecodedChunk.readerIndex(undecodedChunk.readerIndex()-1); + return sb.toString(); + } + } + // FIXME what do we do here? + // either considering it is fine, either waiting for more data to come? + // lets try considering it is fine... + return sb.toString(); + } + // only one '-' => not enough + // whatever now => error since incomplete + } + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + /** + * Read one line up to --delimiter or --delimiter-- and if existing the CRLF or LF. + * Note that CRLF or LF are mandatory for opening delimiter (--delimiter) but not for + * closing delimiter (--delimiter--) since some clients does not include CRLF in this case. + * + * @param delimiter of the form --string, such that '--' is already included + * @return the String from one line as the delimiter searched (opening or closing) + * @throws NotEnoughDataDecoderException Need more chunks and + * reset the readerInder to the previous value + */ + private String readDelimiter(String delimiter) throws NotEnoughDataDecoderException { + SeekAheadOptimize sao = null; + try { + sao = new SeekAheadOptimize(undecodedChunk); + } catch (SeekAheadNoBackArrayException e1) { + return readDelimiterStandard(delimiter); + } + int readerIndex = undecodedChunk.readerIndex(); + int delimiterPos = 0; + int len = delimiter.length(); + try { + StringBuilder sb = new StringBuilder(64); + // check conformity with delimiter + while (sao.pos < sao.limit && delimiterPos < len) { + byte nextByte = sao.bytes[sao.pos ++]; + if (nextByte == delimiter.charAt(delimiterPos)) { + delimiterPos++; + sb.append((char) nextByte); + } else { + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } + // Now check if either opening delimiter or closing delimiter + if (sao.pos < sao.limit) { + byte nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpConstants.CR) { + // first check for opening delimiter + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpConstants.LF) { + sao.setReadPosition(0); + return sb.toString(); + } + } else { + // error since CR must be followed by LF + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } else if (nextByte == HttpConstants.LF) { + // same first check for opening delimiter where LF used with no CR + sao.setReadPosition(0); + return sb.toString(); + } else if (nextByte == '-') { + sb.append((char) nextByte); + // second check for closing delimiter + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == '-') { + sb.append((char) nextByte); + // now try to find if CRLF or LF there + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpConstants.CR) { + if (sao.pos < sao.limit) { + nextByte = sao.bytes[sao.pos ++]; + if (nextByte == HttpConstants.LF) { + sao.setReadPosition(0); + return sb.toString(); + } + } else { + // error CR without LF + // delimiter not found so break here ! + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + } else if (nextByte == HttpConstants.LF) { + sao.setReadPosition(0); + return sb.toString(); + } else { + // No CRLF but ok however (Adobe Flash uploader) + // minus 1 since we read one char ahead but should not + sao.setReadPosition(1); + return sb.toString(); + } + } + // FIXME what do we do here? + // either considering it is fine, either waiting for more data to come? + // lets try considering it is fine... + sao.setReadPosition(0); + return sb.toString(); + } + // whatever now => error since incomplete + // only one '-' => not enough or whatever not enough element + } + } + } + } catch (IndexOutOfBoundsException e) { + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(e); + } + undecodedChunk.readerIndex(readerIndex); + throw new NotEnoughDataDecoderException(); + } + + /** * Read a FileUpload data as Byte (Binary) and add the bytes directly to the * FileUpload. If the delimiter is found, the FileUpload is completed.
null
train
train
2012-07-03T10:40:49
"2012-07-02T15:29:02Z"
nitroduna
val
netty/netty/444_446
netty/netty
netty/netty/444
netty/netty/446
[ "timestamp(timedelta=6838.0, similarity=0.9016470800548596)" ]
f648aae747b4531d80ad3f4b86746c5d93d3821f
4b2010a7f8a2930007c16ab380230fe62ccb520e
[ "not necessary after calling 'deflater.finish()' on line 235\n\nOn Fri, Jul 6, 2012 at 8:00 AM, naude-r\[email protected]\nwrote:\n\n> Hi,\n> \n> Using netty-3.5.0.Final http compression works just fine. After upgrading to netty-3.5.2.Final I found that some resources do not compress completely.\n> \n> This is evident in the actual sizes of the files as well:\n> \n> > -rw-rw-r--. 1 roelof roelof 192628 Jul 6 16:14 netty-3.5.0.js\n> > -rw-rw-r--. 1 roelof roelof 167636 Jul 6 16:14 netty-3.5.2.js\n> \n> Entries from my access log also confirm this.\n> \n> netty-3.5.0.Final\n> \n> > 127.0.0.1 30.507 - 06/07/2012:16:12:42 +0200 \"GET /mtnusa_web/style/jquery/jquery-ui-1.7.2.custom.min.js HTTP/1.1\" 200 <b>46315</b> \"-\" \"curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7\"\n> \n> netty-3.5.2.Final\n> \n> > 127.0.0.1 31.547 - 06/07/2012:16:13:47 +0200 \"GET /mtnusa_web/style/jquery/jquery-ui-1.7.2.custom.min.js HTTP/1.1\" 200 <b>40978</b> \"-\" \"curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7\"\n> \n> Notice the difference in not only file sizes but also final response sizes.\n> \n> The only related changes I could find are the following two issues:\n> [#404](https://github.com/netty/netty/pull/404)\n> [#406](https://github.com/netty/netty/issues/406)\n> \n> The http server is running with jdk 7 and thus the <i>JdkZlibEncoder</i> would be used.\n> \n> Are there any known issues with using JdkZlibEncoder?\n> \n> Took a quick look at the code for JdkZlipEncoder. Lines 236 - 238:\n> \n> ``` java\n> if (!deflater.finished()) {\n> numBytes = deflater.deflate(out, 0, out.length);\n> }\n> ```\n> \n> Should the deflate not be called with <b>SYNC_FLUSH</b>?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/444\n", "@naude-r would it be possible to provide a unit test that shows the error ?\n", "hi,\n\nmanaged to find and fixed the bug. there could still be uncompressed data available when calling <i>deflater.deflate</i> after <i>deflater.finish</i>.\n\nthe fix is to loop on <i>deflater.finished()</i> and write all output to the channel. my attempt to fix is below. feel free to update as required ;-)\n\n```\n--- netty-3.5.2.Final/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java 2012-07-05 10:32:08.000000000 +0200\n+++ netty-3.5.2.Final.new/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java 2012-07-09 12:35:24.288543119 +0200\n@@ -232,14 +232,16 @@\n ChannelBuffer footer = ChannelBuffers.EMPTY_BUFFER;\n synchronized (deflater) {\n int numBytes = 0;\n+ int footerSize = gzip ? numBytes + 8 : numBytes;\n+ final int estimatedSize = footerSize + out.length;\n+ footer = ChannelBuffers.dynamicBuffer(estimatedSize, ctx.getChannel().getConfig().getBufferFactory());\n deflater.finish();\n- if (!deflater.finished()) {\n+ while (!deflater.finished()) {\n numBytes = deflater.deflate(out, 0, out.length);\n+ footer.writeBytes(out, 0, numBytes);\n+ footerSize += numBytes;\n }\n- int footerSize = gzip ? numBytes + 8 : numBytes;\n if (footerSize > 0) {\n- footer = ctx.getChannel().getConfig().getBufferFactory().getBuffer(footerSize);\n- footer.writeBytes(out, 0, numBytes);\n if (gzip) {\n int crcValue = (int) crc.getValue();\n int uncBytes = deflater.getTotalIn();\n\n```\n", "@jpinner sounds good.. wdyt ?\n", "issued pull request: https://github.com/netty/netty/pull/446\n", "@jpinner merged in.. thanks..\n\n@naude-r could you check if the changes which I just pulled in also fix it for you ?\n", "@normanmaurer thank you. that worked perfectly.\n" ]
[]
"2012-07-09T18:03:03Z"
[ "defect" ]
Http compression error
Hi, Using netty-3.5.0.Final http compression works just fine. After upgrading to netty-3.5.2.Final I found that some resources do not compress completely. This is evident in the actual sizes of the files as well: > -rw-rw-r--. 1 roelof roelof 192628 Jul 6 16:14 netty-3.5.0.js > -rw-rw-r--. 1 roelof roelof 167636 Jul 6 16:14 netty-3.5.2.js Entries from my access log also confirm this. netty-3.5.0.Final > 127.0.0.1 30.507 - 06/07/2012:16:12:42 +0200 "GET /mtnusa_web/style/jquery/jquery-ui-1.7.2.custom.min.js HTTP/1.1" 200 <b>46315</b> "-" "curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7" netty-3.5.2.Final > 127.0.0.1 31.547 - 06/07/2012:16:13:47 +0200 "GET /mtnusa_web/style/jquery/jquery-ui-1.7.2.custom.min.js HTTP/1.1" 200 <b>40978</b> "-" "curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7" Notice the difference in not only file sizes but also final response sizes. The only related changes I could find are the following two issues: [#404](https://github.com/netty/netty/pull/404) [#406](https://github.com/netty/netty/issues/406) The http server is running with jdk 7 and thus the <i>JdkZlibEncoder</i> would be used. Are there any known issues with using JdkZlibEncoder? Took a quick look at the code for JdkZlipEncoder. Lines 236 - 238: ``` java if (!deflater.finished()) { numBytes = deflater.deflate(out, 0, out.length); } ``` Should the deflate not be called with <b>SYNC_FLUSH</b>?
[ "src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java b/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java index cd7b161be10..59d78a67d33 100644 --- a/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/compression/JdkZlibEncoder.java @@ -222,42 +222,41 @@ public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) } private ChannelFuture finishEncode(final ChannelHandlerContext ctx, final ChannelEvent evt) { + ChannelFuture future = Channels.succeededFuture(ctx.getChannel()); + if (!finished.compareAndSet(false, true)) { if (evt != null) { ctx.sendDownstream(evt); } - return Channels.succeededFuture(ctx.getChannel()); + return future; } - ChannelBuffer footer = ChannelBuffers.EMPTY_BUFFER; + ChannelBuffer footer = ChannelBuffers.dynamicBuffer(ctx.getChannel().getConfig().getBufferFactory()); synchronized (deflater) { - int numBytes = 0; deflater.finish(); - if (!deflater.finished()) { - numBytes = deflater.deflate(out, 0, out.length); - } - int footerSize = gzip ? numBytes + 8 : numBytes; - if (footerSize > 0) { - footer = ctx.getChannel().getConfig().getBufferFactory().getBuffer(footerSize); + while (!deflater.finished()) { + int numBytes = deflater.deflate(out, 0, out.length); footer.writeBytes(out, 0, numBytes); - if (gzip) { - int crcValue = (int) crc.getValue(); - int uncBytes = deflater.getTotalIn(); - footer.writeByte(crcValue); - footer.writeByte(crcValue >>> 8); - footer.writeByte(crcValue >>> 16); - footer.writeByte(crcValue >>> 24); - footer.writeByte(uncBytes); - footer.writeByte(uncBytes >>> 8); - footer.writeByte(uncBytes >>> 16); - footer.writeByte(uncBytes >>> 24); - } + } + if (gzip) { + int crcValue = (int) crc.getValue(); + int uncBytes = deflater.getTotalIn(); + footer.writeByte(crcValue); + footer.writeByte(crcValue >>> 8); + footer.writeByte(crcValue >>> 16); + footer.writeByte(crcValue >>> 24); + footer.writeByte(uncBytes); + footer.writeByte(uncBytes >>> 8); + footer.writeByte(uncBytes >>> 16); + footer.writeByte(uncBytes >>> 24); } deflater.end(); } - ChannelFuture future = Channels.future(ctx.getChannel()); - Channels.write(ctx, future, footer); + if (footer.readable()) { + future = Channels.future(ctx.getChannel()); + Channels.write(ctx, future, footer); + } if (evt != null) { future.addListener(new ChannelFutureListener() {
null
train
train
2012-07-08T11:24:26
"2012-07-06T14:39:11Z"
naude-r
val
netty/netty/456_460
netty/netty
netty/netty/456
netty/netty/460
[ "timestamp(timedelta=74809.0, similarity=0.8526710381688708)", "keyword_pr_to_issue" ]
3447e8711227f83ff8d02a90078e376c3fbf5a0f
1134715697e30d9fa8f0637b79d05889c54d45f3
[ "@trustin @veebs @fredericBregier wdyt ?\n", "Sorry. Saw the issue but been a bit busy with work. Will make some time to look at it tomorrow. \n\nSent from my iPhone\n\nOn 18/07/2012, at 5:57 PM, Norman [email protected] wrote:\n\n> @trustin @veebs @fredericBregier wdyt ?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/456#issuecomment-7059069\n", "I looked at some RFC, and it seems that the proposal is correct.\nSee http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08 chapter 4.3.\nThe mask sent should be the same used in the next writes if payload is used.\nSo I propose to validate this fix.\n\nNB: in branch 3, the code is as proposed (create only one RANDOM and use it)\n", "Let's merge in. Thanks @spullara ! :-)\n", "By the way, the issue is referenced to 3.5.3 but it is related to 4...\n", "@fredericBregier so only 4 is effected atm ?\n", "Yes, in branch 3, we already have :\n\n```\n Integer random = (int) (Math.random() * Integer.MAX_VALUE);\n mask = ByteBuffer.allocate(4).putInt(random).array();\n header.writeBytes(mask);\n```\n\nAnd I just proposed a pull request for master...\nI changed the writeInt to writeBytes... and I justsee that I made a typo error while looking at source 3 to master... \n", "@fredericBregier Ok.. In the description of this issue he mention that the problem also exist in V13.. Did you check this too ?\n", "In fact v13 is just an extend of v08 with no additional code, so fixing v08 is enough.\n(Valid also in branch 3)\n", "@garypart Maybe you could try to download the last master branch version or applied the small fix and check if it fixes your issue correctly ?\n", "Thanks everyone.\n" ]
[]
"2012-07-18T08:48:11Z"
[ "defect" ]
Completely broken WebSocket08FrameEncoder (v13 broken too) (includes 1 line fix)
Bug exists in 4.0.0.Alpha1 AND verified it still exists in master. Didn't check previous to those. Symptom: - Other end will get an undecodable garbage payload from a netty WebSocket client. Cause: - Netty picks two random numbers. One random number is stored in the mask field in the WebSocket frame that is sent to the other end. The other random number is used as the mask in the code that masks the payload data. There is a very low chance of course that these two random numbers will be the same and thus a low chance that the other end will get anything but garbage when attempting to decode the payload. Solution: - Only generate one random number. Use that same random number as the mask value sent to the other end and as the mask value that the payload is actually encoded with. ## Diff: diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java index f32d01a..86862c2 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java @@ -166,7 +166,7 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame if (maskPayload) { int random = (int) (Math.random() \* Integer.MAX_VALUE); mask = ByteBuffer.allocate(4).putInt(random).array(); - out.writeInt((int) (Math.random() \* Integer.MAX_VALUE)); - ``` out.writeInt(random); int counter = 0; for (int i = data.readerIndex(); i < data.writerIndex(); i ++) { ``` --- - Sam Maloney [email protected]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java index f32d01a2d05..715123a311d 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java @@ -166,7 +166,7 @@ public void encode(ChannelHandlerContext ctx, if (maskPayload) { int random = (int) (Math.random() * Integer.MAX_VALUE); mask = ByteBuffer.allocate(4).putInt(random).array(); - out.writeInt((int) (Math.random() * Integer.MAX_VALUE)); + header.writeBytes(mask); int counter = 0; for (int i = data.readerIndex(); i < data.writerIndex(); i ++) {
null
train
train
2012-07-18T09:26:11
"2012-07-17T10:53:44Z"
garypart
val
netty/netty/456_461
netty/netty
netty/netty/456
netty/netty/461
[ "keyword_pr_to_issue" ]
b5412c956359200f66076c4f99da163fb1df6ed5
19eba3ec596151da63719929d0746479cdff13d7
[ "@trustin @veebs @fredericBregier wdyt ?\n", "Sorry. Saw the issue but been a bit busy with work. Will make some time to look at it tomorrow. \n\nSent from my iPhone\n\nOn 18/07/2012, at 5:57 PM, Norman [email protected] wrote:\n\n> @trustin @veebs @fredericBregier wdyt ?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/456#issuecomment-7059069\n", "I looked at some RFC, and it seems that the proposal is correct.\nSee http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08 chapter 4.3.\nThe mask sent should be the same used in the next writes if payload is used.\nSo I propose to validate this fix.\n\nNB: in branch 3, the code is as proposed (create only one RANDOM and use it)\n", "Let's merge in. Thanks @spullara ! :-)\n", "By the way, the issue is referenced to 3.5.3 but it is related to 4...\n", "@fredericBregier so only 4 is effected atm ?\n", "Yes, in branch 3, we already have :\n\n```\n Integer random = (int) (Math.random() * Integer.MAX_VALUE);\n mask = ByteBuffer.allocate(4).putInt(random).array();\n header.writeBytes(mask);\n```\n\nAnd I just proposed a pull request for master...\nI changed the writeInt to writeBytes... and I justsee that I made a typo error while looking at source 3 to master... \n", "@fredericBregier Ok.. In the description of this issue he mention that the problem also exist in V13.. Did you check this too ?\n", "In fact v13 is just an extend of v08 with no additional code, so fixing v08 is enough.\n(Valid also in branch 3)\n", "@garypart Maybe you could try to download the last master branch version or applied the small fix and check if it fixes your issue correctly ?\n", "Thanks everyone.\n" ]
[]
"2012-07-18T08:50:57Z"
[ "defect" ]
Completely broken WebSocket08FrameEncoder (v13 broken too) (includes 1 line fix)
Bug exists in 4.0.0.Alpha1 AND verified it still exists in master. Didn't check previous to those. Symptom: - Other end will get an undecodable garbage payload from a netty WebSocket client. Cause: - Netty picks two random numbers. One random number is stored in the mask field in the WebSocket frame that is sent to the other end. The other random number is used as the mask in the code that masks the payload data. There is a very low chance of course that these two random numbers will be the same and thus a low chance that the other end will get anything but garbage when attempting to decode the payload. Solution: - Only generate one random number. Use that same random number as the mask value sent to the other end and as the mask value that the payload is actually encoded with. ## Diff: diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java index f32d01a..86862c2 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java @@ -166,7 +166,7 @@ public class WebSocket08FrameEncoder extends MessageToByteEncoder<WebSocketFrame if (maskPayload) { int random = (int) (Math.random() \* Integer.MAX_VALUE); mask = ByteBuffer.allocate(4).putInt(random).array(); - out.writeInt((int) (Math.random() \* Integer.MAX_VALUE)); - ``` out.writeInt(random); int counter = 0; for (int i = data.readerIndex(); i < data.writerIndex(); i ++) { ``` --- - Sam Maloney [email protected]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java index 715123a311d..1d773852296 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket08FrameEncoder.java @@ -166,7 +166,7 @@ public void encode(ChannelHandlerContext ctx, if (maskPayload) { int random = (int) (Math.random() * Integer.MAX_VALUE); mask = ByteBuffer.allocate(4).putInt(random).array(); - header.writeBytes(mask); + out.writeBytes(mask); int counter = 0; for (int i = data.readerIndex(); i < data.writerIndex(); i ++) {
null
train
train
2012-07-18T10:50:23
"2012-07-17T10:53:44Z"
garypart
val
netty/netty/489_490
netty/netty
netty/netty/489
netty/netty/490
[ "timestamp(timedelta=29.0, similarity=0.9177840192781919)" ]
f2eeed77e0d1a850b9e77212191af457f05cbfbc
1a4bbc0f39eb0cd5062d873871c73d9d3925a3b0
[ "@jfallows merged your pull request.. Thanks again1\n", "Awesome. Thanks @jfallows!\n" ]
[]
"2012-08-05T22:26:13Z"
[ "defect" ]
Suspend-resume in AIO can cause a ReadPendingException
When a read completes in AioSocketChannel and the newly read buffer is advertised via fireInboundBufferUpdated(), user code can trigger a ChannelHandlerContext.readable(false), followed by a ChannelHandlerContext.readable(true). The ChannelHandlerContext.readable(true) causes a new AioSocketChannel.beginRead() call to occur, in this case immediately because we are on the event loop thread, then the fireInboundBufferUpdated() method returns, and the read completion handler calls AioSocketChannel.beginRead() again. This second call to beginRead() causes the java.nio.channels.ReadPendingException.
[ "transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java" ]
[ "transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java b/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java index 817cbc0af71..16a44c6c773 100755 --- a/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java +++ b/transport/src/main/java/io/netty/channel/socket/aio/AioSocketChannel.java @@ -54,6 +54,7 @@ private static AsynchronousSocketChannel newSocket(AsynchronousChannelGroup grou private boolean flushing; private final AtomicBoolean readSuspended = new AtomicBoolean(); + private final AtomicBoolean readInProgress = new AtomicBoolean(); private final Runnable readTask = new Runnable() { @Override @@ -191,6 +192,11 @@ private void beginRead() { return; } + // prevent ReadPendingException + if (!readInProgress.compareAndSet(false, true)) { + return; + } + ByteBuf byteBuf = pipeline().inboundByteBuffer(); if (!byteBuf.readable()) { byteBuf.discardReadBytes(); @@ -297,6 +303,9 @@ protected void completed0(Integer result, AioSocketChannel channel) { } } } finally { + // see beginRead + channel.readInProgress.set(false); + if (read) { if (!channel.readSuspended.get()) { pipeline.fireInboundBufferUpdated();
null
train
train
2012-08-05T11:43:32
"2012-08-05T21:58:26Z"
jfallows
val
netty/netty/497_498
netty/netty
netty/netty/497
netty/netty/498
[ "timestamp(timedelta=37.0, similarity=0.8947825777299173)" ]
e0a88a0f1596ca91a2d31c6d39936a54e102354f
5b48f8bc0daba1a740bba130a3a58fc0417aeaa7
[ "This will break the api. Its fixed in master already but should not\nget touched in 3\n\nSent from my iPhone. Excuse any typos....\n\nAm 09.08.2012 um 01:12 schrieb Cruz Bishop [email protected]:\n\n> As noted by a TODO note in line 505 (branch: 3)\n> \n> ```\n> public void cancel() {\n> if (!state.compareAndSet(ST_INIT, ST_CANCELLED)) {\n> // TODO return false\n> return;\n> }\n> \n> wheel[stopIndex].remove(this);\n> }\n> ```\n> \n> I'll make a pull request to fix this in a moment\n> \n> —\n> Reply to this email directly or view it on GitHub.\n" ]
[]
"2012-08-08T23:21:35Z"
[ "won't fix" ]
HashedWheelTimer.cancel() cannot report failure
As noted by a TODO note in line 505 (branch: 3) ``` public void cancel() { if (!state.compareAndSet(ST_INIT, ST_CANCELLED)) { // TODO return false return; } wheel[stopIndex].remove(this); } ``` I'll make a pull request to fix this in a moment
[ "src/main/java/org/jboss/netty/util/HashedWheelTimer.java", "src/main/java/org/jboss/netty/util/Timeout.java" ]
[ "src/main/java/org/jboss/netty/util/HashedWheelTimer.java", "src/main/java/org/jboss/netty/util/Timeout.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/util/HashedWheelTimer.java b/src/main/java/org/jboss/netty/util/HashedWheelTimer.java index 3b8d1d2ae22..fad43274e9a 100644 --- a/src/main/java/org/jboss/netty/util/HashedWheelTimer.java +++ b/src/main/java/org/jboss/netty/util/HashedWheelTimer.java @@ -500,13 +500,13 @@ public TimerTask getTask() { return task; } - public void cancel() { + public boolean cancel() { if (!state.compareAndSet(ST_INIT, ST_CANCELLED)) { - // TODO return false - return; + return false; } wheel[stopIndex].remove(this); + return true; } public boolean isCancelled() { diff --git a/src/main/java/org/jboss/netty/util/Timeout.java b/src/main/java/org/jboss/netty/util/Timeout.java index 162eff87375..bf3ce154ec6 100644 --- a/src/main/java/org/jboss/netty/util/Timeout.java +++ b/src/main/java/org/jboss/netty/util/Timeout.java @@ -44,9 +44,11 @@ public interface Timeout { boolean isCancelled(); /** - * Cancels the {@link TimerTask} associated with this handle. It the - * task has been executed or cancelled already, it will return with no - * side effect. + * Attempts to cancel the {@link TimerTask} associated with this handle. + * If the task has been executed or cancelled already, it will return with + * no side effect. + * + * @return True if the cancellation completed successfully, otherwise false */ - void cancel(); + boolean cancel(); }
null
train
train
2012-08-01T09:00:13
"2012-08-08T23:12:26Z"
CruzBishop
val
netty/netty/431_508
netty/netty
netty/netty/431
netty/netty/508
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.8819787003609638)" ]
b5aa2108ec06382a45f79f1876e6014baf836ee3
2d5896b30631d252d90646abfcaccf6805a7ff7a
[]
[]
"2012-08-14T05:46:13Z"
[]
No way to get a UniqueName's ID
There is currently no way to get a raw UniqueName's ID without subclassing. I'm already working on this, but I thought I should make a bug report anyway.
[ "common/src/main/java/io/netty/util/UniqueName.java" ]
[ "common/src/main/java/io/netty/util/UniqueName.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/UniqueName.java b/common/src/main/java/io/netty/util/UniqueName.java index dbdd47617d9..9eb3e8b4bab 100644 --- a/common/src/main/java/io/netty/util/UniqueName.java +++ b/common/src/main/java/io/netty/util/UniqueName.java @@ -55,6 +55,10 @@ public final String name() { return name; } + public final int id() { + return id; + } + @Override public final int hashCode() { return super.hashCode();
null
train
train
2012-08-14T07:10:40
"2012-07-02T08:50:15Z"
CruzBishop
val
netty/netty/510_512
netty/netty
netty/netty/510
netty/netty/512
[ "keyword_pr_to_issue", "timestamp(timedelta=1.0, similarity=0.8576154479389824)" ]
ad534efc58d8be5eb7f5b1a211639ce451bf2009
553b97f0a4d8f706ae687f728e30e8dea32413e2
[ "Looks like a copy/paste error :P\n\nI'll go fix that, thanks.\n" ]
[]
"2012-08-14T09:54:09Z"
[]
netty example: comment error in ObjectEchoClientHandler.java
@bobmcwhirter public void messageReceived(ChannelHandlerContext ctx, List<Integer> msg) throws Exception { // Echo back the received object to the client. ctx.write(msg); } does the "to client" in comment should be "to server" ?
[ "example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java" ]
[ "example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java" ]
[]
diff --git a/example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java b/example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java index c7b583d99e0..62acef8dddd 100644 --- a/example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java +++ b/example/src/main/java/io/netty/example/objectecho/ObjectEchoClientHandler.java @@ -57,7 +57,7 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { @Override public void messageReceived(ChannelHandlerContext ctx, List<Integer> msg) throws Exception { - // Echo back the received object to the client. + // Echo back the received object to the server. ctx.write(msg); }
null
test
train
2012-08-14T08:07:21
"2012-08-14T08:36:20Z"
tianyuanzhonglu
val
netty/netty/510_513
netty/netty
netty/netty/510
netty/netty/513
[ "timestamp(timedelta=110.0, similarity=0.8583523126024742)", "keyword_pr_to_issue" ]
3a3c5de76b11a15e91b223f3c0ebc1d744d5fa6d
f450dfd958c05e2a9a8ebc51fc0873b123b73741
[ "Looks like a copy/paste error :P\n\nI'll go fix that, thanks.\n" ]
[]
"2012-08-14T09:57:04Z"
[]
netty example: comment error in ObjectEchoClientHandler.java
@bobmcwhirter public void messageReceived(ChannelHandlerContext ctx, List<Integer> msg) throws Exception { // Echo back the received object to the client. ctx.write(msg); } does the "to client" in comment should be "to server" ?
[ "src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java" ]
[ "src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java index c70aea0590d..61b0ef6d26f 100644 --- a/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java +++ b/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClientHandler.java @@ -80,7 +80,7 @@ public void channelConnected( @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { - // Echo back the received object to the client. + // Echo back the received object to the server. transferredMessages.incrementAndGet(); e.getChannel().write(e.getMessage()); }
null
test
train
2012-08-12T10:59:04
"2012-08-14T08:36:20Z"
tianyuanzhonglu
val
netty/netty/514_515
netty/netty
netty/netty/514
netty/netty/515
[ "timestamp(timedelta=74.0, similarity=0.9100228567346533)" ]
1f1403697bdcb70de4bd4717cfcbb343e72b5804
5c9d13713141a756b6f38470baffae9c3755c5a7
[ "You are right.. Thanks for the report and fix!\n", "However, the accepted AioSocketChannel's AsynchronousChannelGroup is identical to that of AioServerSocketChannel. It means any async I/O events will be firstly handled by the parent AsyncChannelGroup and then forwarded to the child AsyncChannelGroup. Do you see any degradation in performance?\n", "Nevermind. AioEventLoop.execute() will try to avoid that problem using reflection. :-)\n" ]
[]
"2012-08-14T14:43:13Z"
[ "feature" ]
AIO server channel accepts channels onto server event loop group
When a parent `AioServerSocketChannel` accepts a new inbound connection, the child `AioSocketChannel` is created with the server event loop group instead of a separate child event loop group. Forcing both parent and child channels onto the same event loop group is still functionally correct, but can lead to connection timeout due to starvation at high throughput. The NIO transport keeps the parent and child event loop groups separate and does not suffer from starvation at high throughput.
[ "transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java" ]
[ "transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java b/transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java index d7eca8dc7a4..4a83008d7ba 100755 --- a/transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java +++ b/transport/src/main/java/io/netty/channel/socket/aio/AioServerSocketChannel.java @@ -40,6 +40,7 @@ public class AioServerSocketChannel extends AbstractAioChannel implements Server private static final InternalLogger logger = InternalLoggerFactory.getInstance(AioServerSocketChannel.class); + private final AioEventLoopGroup childGroup; private final AioServerSocketChannelConfig config; private boolean closed; private AtomicBoolean readSuspended = new AtomicBoolean(); @@ -60,9 +61,14 @@ private static AsynchronousServerSocketChannel newSocket(AsynchronousChannelGrou } } - public AioServerSocketChannel(AioEventLoopGroup eventLoop) { - super(null, null, eventLoop, newSocket(eventLoop.group)); - config = new AioServerSocketChannelConfig(javaChannel()); + public AioServerSocketChannel(AioEventLoopGroup group) { + this(group, group); + } + + public AioServerSocketChannel(AioEventLoopGroup parentGroup, AioEventLoopGroup childGroup) { + super(null, null, parentGroup, newSocket(parentGroup.group)); + this.childGroup = childGroup; + this.config = new AioServerSocketChannelConfig(javaChannel()); } @Override @@ -147,7 +153,7 @@ protected void completed0(AsynchronousSocketChannel ch, AioServerSocketChannel c // create the socket add it to the buffer and fire the event channel.pipeline().inboundMessageBuffer().add( - new AioSocketChannel(channel, null, channel.group, ch)); + new AioSocketChannel(channel, null, channel.childGroup, ch)); if (!channel.readSuspended.get()) { channel.pipeline().fireInboundBufferUpdated(); }
null
train
train
2012-08-14T11:58:33
"2012-08-14T14:37:49Z"
jfallows
val
netty/netty/521_522
netty/netty
netty/netty/521
netty/netty/522
[ "timestamp(timedelta=1.0, similarity=0.9007243028816602)" ]
b6264c02d98b7e0335460c393e46adc42039bd74
2eae71843268b3d065408a8f6dc8bc9eb008e3a8
[ "@jpinner makes sense.. I want to cut 3.5.4.Final tomorrow. Would be nice if you could \"fix it\" before that..\n" ]
[]
"2012-08-15T21:06:46Z"
[ "defect" ]
Encode URI using UTF-8 charset
Starting with IE7, all URLs are encoded using the UTF-8 character set (http://support.microsoft.com/kb/934279). Netty assumes that the request uri string is encoded as ASCII -- see HttpRequestEncoder: buf.writeBytes(request.getUri().getBytes("ASCII")) Requests that are generated by HttpMessageDecoder use StringBuilder to generate the URI and so will not preserve UTF-8 characters when encoded using HttpRequestEncoder. Since UTF-8 is a strict superset of ASCII, we should be able to encode the URI using UTF-8 without breaking any requests whose URI only contains ASCII characters.
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java index 43d4167af6e..6da12766335 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.java @@ -37,7 +37,7 @@ protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) throws HttpRequest request = (HttpRequest) message; buf.writeBytes(request.getMethod().toString().getBytes("ASCII")); buf.writeByte(SP); - buf.writeBytes(request.getUri().getBytes("ASCII")); + buf.writeBytes(request.getUri().getBytes("UTF-8")); buf.writeByte(SP); buf.writeBytes(request.getProtocolVersion().toString().getBytes("ASCII")); buf.writeByte(CR);
null
train
train
2012-08-15T22:39:40
"2012-08-15T20:47:03Z"
jpinner
val
netty/netty/521_523
netty/netty
netty/netty/521
netty/netty/523
[ "timestamp(timedelta=69770.0, similarity=0.9007243028816602)" ]
5787e2eac9c151f63055b9dd9d5b03dbaa38c3d2
44a2525687746b481f005386d0a61bfe11078519
[ "@jpinner makes sense.. I want to cut 3.5.4.Final tomorrow. Would be nice if you could \"fix it\" before that..\n" ]
[]
"2012-08-15T21:07:09Z"
[ "defect" ]
Encode URI using UTF-8 charset
Starting with IE7, all URLs are encoded using the UTF-8 character set (http://support.microsoft.com/kb/934279). Netty assumes that the request uri string is encoded as ASCII -- see HttpRequestEncoder: buf.writeBytes(request.getUri().getBytes("ASCII")) Requests that are generated by HttpMessageDecoder use StringBuilder to generate the URI and so will not preserve UTF-8 characters when encoded using HttpRequestEncoder. Since UTF-8 is a strict superset of ASCII, we should be able to encode the URI using UTF-8 without breaking any requests whose URI only contains ASCII characters.
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java index c83c1921904..b1c56222325 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpMessageEncoder.java @@ -150,10 +150,10 @@ private static void encodeTrailingHeaders(ByteBuf buf, HttpChunkTrailer trailer) private static void encodeHeader(ByteBuf buf, String header, String value) throws UnsupportedEncodingException { - buf.writeBytes(header.getBytes("ASCII")); + buf.writeBytes(header.getBytes(CharsetUtil.US_ASCII)); buf.writeByte(COLON); buf.writeByte(SP); - buf.writeBytes(value.getBytes("ASCII")); + buf.writeBytes(value.getBytes(CharsetUtil.US_ASCII)); buf.writeByte(CR); buf.writeByte(LF); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java index eda340707e7..f450c809da2 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java @@ -17,6 +17,7 @@ import static io.netty.handler.codec.http.HttpConstants.*; import io.netty.buffer.ByteBuf; +import io.netty.util.CharsetUtil; /** * Encodes an {@link HttpRequest} or an {@link HttpChunk} into @@ -33,11 +34,11 @@ public HttpRequestEncoder() { @Override protected void encodeInitialLine(ByteBuf buf, HttpMessage message) throws Exception { HttpRequest request = (HttpRequest) message; - buf.writeBytes(request.getMethod().toString().getBytes("ASCII")); + buf.writeBytes(request.getMethod().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte(SP); - buf.writeBytes(request.getUri().getBytes("ASCII")); + buf.writeBytes(request.getUri().getBytes(CharsetUtil.UTF_8)); buf.writeByte(SP); - buf.writeBytes(request.getProtocolVersion().toString().getBytes("ASCII")); + buf.writeBytes(request.getProtocolVersion().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte(CR); buf.writeByte(LF); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java index d897f680dd9..141b41d8e19 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java @@ -17,6 +17,7 @@ import static io.netty.handler.codec.http.HttpConstants.*; import io.netty.buffer.ByteBuf; +import io.netty.util.CharsetUtil; /** * Encodes an {@link HttpResponse} or an {@link HttpChunk} into @@ -33,11 +34,11 @@ public HttpResponseEncoder() { @Override protected void encodeInitialLine(ByteBuf buf, HttpMessage message) throws Exception { HttpResponse response = (HttpResponse) message; - buf.writeBytes(response.getProtocolVersion().toString().getBytes("ASCII")); + buf.writeBytes(response.getProtocolVersion().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte(SP); - buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes("ASCII")); + buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes(CharsetUtil.US_ASCII)); buf.writeByte(SP); - buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII")); + buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes(CharsetUtil.US_ASCII)); buf.writeByte(CR); buf.writeByte(LF); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java index 4a6815fb538..d968c3c88be 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspRequestEncoder.java @@ -18,6 +18,7 @@ import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.HttpRequest; +import io.netty.util.CharsetUtil; /** * Encodes an RTSP request represented in {@link HttpRequest} into @@ -30,11 +31,11 @@ public class RtspRequestEncoder extends RtspMessageEncoder { protected void encodeInitialLine(ByteBuf buf, HttpMessage message) throws Exception { HttpRequest request = (HttpRequest) message; - buf.writeBytes(request.getMethod().toString().getBytes("ASCII")); + buf.writeBytes(request.getMethod().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) ' '); - buf.writeBytes(request.getUri().getBytes("ASCII")); + buf.writeBytes(request.getUri().getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) ' '); - buf.writeBytes(request.getProtocolVersion().toString().getBytes("ASCII")); + buf.writeBytes(request.getProtocolVersion().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) '\r'); buf.writeByte((byte) '\n'); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java index 63b94c5df70..e5c2f719a46 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspResponseEncoder.java @@ -18,6 +18,7 @@ import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.HttpResponse; +import io.netty.util.CharsetUtil; /** * Encodes an RTSP response represented in {@link HttpResponse} into @@ -30,11 +31,11 @@ public class RtspResponseEncoder extends RtspMessageEncoder { protected void encodeInitialLine(ByteBuf buf, HttpMessage message) throws Exception { HttpResponse response = (HttpResponse) message; - buf.writeBytes(response.getProtocolVersion().toString().getBytes("ASCII")); + buf.writeBytes(response.getProtocolVersion().toString().getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) ' '); - buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes("ASCII")); + buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) ' '); - buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII")); + buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes(CharsetUtil.US_ASCII)); buf.writeByte((byte) '\r'); buf.writeByte((byte) '\n'); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java index 8d4059a399f..5458a9f77f2 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyCodecUtil.java @@ -16,6 +16,7 @@ package io.netty.handler.codec.spdy; import io.netty.buffer.ByteBuf; +import io.netty.util.CharsetUtil; final class SpdyCodecUtil { @@ -251,7 +252,7 @@ final class SpdyCodecUtil { byte[] SPDY2_DICT_; try { - SPDY2_DICT_ = SPDY2_DICT_S.getBytes("US-ASCII"); + SPDY2_DICT_ = SPDY2_DICT_S.getBytes(CharsetUtil.US_ASCII); // dictionary is null terminated SPDY2_DICT_[SPDY2_DICT_.length - 1] = (byte) 0; } catch (Exception e) { diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java index 350a12f20f8..f05b4c469ad 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyFrameEncoder.java @@ -23,6 +23,7 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.UnsupportedMessageTypeException; +import io.netty.util.CharsetUtil; import java.util.Set; @@ -302,14 +303,14 @@ private static ByteBuf encodeHeaderBlock(int version, SpdyHeaderBlock headerFram ByteBuf headerBlock = Unpooled.buffer(); writeLengthField(version, headerBlock, numHeaders); for (String name: names) { - byte[] nameBytes = name.getBytes("UTF-8"); + byte[] nameBytes = name.getBytes(CharsetUtil.UTF_8); writeLengthField(version, headerBlock, nameBytes.length); headerBlock.writeBytes(nameBytes); int savedIndex = headerBlock.writerIndex(); int valueLength = 0; writeLengthField(version, headerBlock, valueLength); for (String value: headerFrame.getHeaders(name)) { - byte[] valueBytes = value.getBytes("UTF-8"); + byte[] valueBytes = value.getBytes(CharsetUtil.UTF_8); headerBlock.writeBytes(valueBytes); headerBlock.writeByte(0); valueLength += valueBytes.length + 1;
null
val
train
2012-08-15T03:10:23
"2012-08-15T20:47:03Z"
jpinner
val
netty/netty/494_526
netty/netty
netty/netty/494
netty/netty/526
[ "timestamp(timedelta=1095.0, similarity=0.94711738258233)" ]
3f709efcea850ee352df4b88e4b759fa44a22569
bfe8d1a70fd120ba20ad6ac4662bfe83abddcf39
[ "The fix would be modifying `HttpMessageEncoder` so that it removes `Content-Length` when `Transfer-Encoding: chunked` is set. WDYT?\n", "@trustin makes sense.. should I make the change later today ?\n", "If you wish to do it by yourself, please go ahead. :-)\n\nOn Thu, Aug 9, 2012 at 5:39 PM, Norman Maurer [email protected]:\n\n> @trustin https://github.com/trustin makes sense.. should I make the\n> change later today ?\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/netty/netty/issues/494#issuecomment-7608522.\n", "Why not avoid adding the transfer-encoding header if content-length is already set?\nThat way you avoid sending the extra chunked encoding headers along with the message and send the message as it was intended.\n", "Preserving the Content-Length header rather than transforming to chunked encoding also allows the client to show a determinate download progress bar and immediately reject content that is too large.\n", "Agreed. So, the new behavior should be: if Content-Length is set,\nTransfer-Encoding header is cleared and HttpMessageEncoder.chunked is set\nto false. Does that make sense?\n\nOn Fri, Aug 10, 2012 at 1:43 AM, Michael Zampani\[email protected]:\n\n> Preserving the Content-Length header rather than transforming to chunked\n> encoding also allows the client to show a determinate download progress bar\n> and immediately reject content that is too large.\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/netty/netty/issues/494#issuecomment-7619551.\n", "@zampani what about issue a pull request ?\n", "@zampani Would you mind if I ask you to confirm the fix is working as you expected?\n" ]
[]
"2012-08-16T08:24:30Z"
[ "defect" ]
Automatically adding chunked encoding header breaks streaming
Previously, a change was committed to automatically add the Transfer-Encoding: chunk header to any HttpMessage for which isChunked() == true. https://github.com/netty/netty/issues/171 https://github.com/netty/netty/commit/01225b0a522720a7423390673581a0e48bf1d7c2 According to the javadoc https://github.com/netty/netty/blob/3/src/main/java/org/jboss/netty/handler/codec/http/HttpMessage.java#L133 isChunked isn't coupled to the transfer-encoding. It can also be used for streaming request/responses. "This means that the HttpMessageEncoder will add the chunked Transfer-Encoding header to the message and prepend each chunk with <chunksize>CRLF as it is encoded, even for messages that include a Content-Length header for streaming." This results in a larger than expected message due to the added bytes for the per-chunk size information. http://en.wikipedia.org/wiki/Chunked_transfer_encoding#Format which means that clients will think that they have the entire message when it has actually been corrupted by the inserted chunked encoding headers. The HTTP 1.1 spec specifies that no response should contain both a content-length header and a non-identity transfer-encoding header. http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4 While it is true that the HTTP 1.1 spec states that responses containing both content-length and transfer-encoding: chunked should be handled by ignoring the content-length field we have found that some clients do not respect this.
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java index 94c685f6f5b..8105f67fd96 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java @@ -118,6 +118,17 @@ static boolean isTransferEncodingChunked(HttpMessage m) { return false; } + static void removeTransferEncodingChunked(HttpMessage m) { + List<String> values = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); + values.remove(HttpHeaders.Values.CHUNKED); + m.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, values); + } + + static boolean isContentLengthSet(HttpMessage m) { + List<String> contentLength = m.getHeaders(HttpHeaders.Names.CONTENT_LENGTH); + return !contentLength.isEmpty(); + } + private HttpCodecUtil() { super(); } diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java index 0a29aaae4f8..6dcb3694bfa 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.java @@ -65,12 +65,18 @@ protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) HttpMessage m = (HttpMessage) msg; boolean chunked; if (m.isChunked()) { - // check if the Transfer-Encoding is set to chunked already. - // if not add the header to the message - if (!HttpCodecUtil.isTransferEncodingChunked(m)) { - m.addHeader(Names.TRANSFER_ENCODING, Values.CHUNKED); + // if Content-Length is set then the message can't be HTTP chunked + if (HttpCodecUtil.isContentLengthSet(m)) { + chunked = this.chunked = false; + HttpCodecUtil.removeTransferEncodingChunked(m); + } else { + // check if the Transfer-Encoding is set to chunked already. + // if not add the header to the message + if (!HttpCodecUtil.isTransferEncodingChunked(m)) { + m.addHeader(Names.TRANSFER_ENCODING, Values.CHUNKED); + } + chunked = this.chunked = true; } - chunked = this.chunked = true; } else { chunked = this.chunked = HttpCodecUtil.isTransferEncodingChunked(m); }
null
train
train
2012-08-16T09:22:19
"2012-08-08T16:55:59Z"
zampani
val
netty/netty/442_545
netty/netty
netty/netty/442
netty/netty/545
[ "keyword_pr_to_issue" ]
31a51b4937b782b542023ab92df2fcfb1c51c72c
6aa51e1496cd1212ee32329bf46cbb1b39acd70a
[ "hexdump of the frame causing the error would be helpful\n\nOn Fri, Jul 6, 2012 at 3:17 AM, naude-r\[email protected]\nwrote:\n\n> hi,\n> \n> I have added spdy support to a web server. The pipeline is fairly typical:\n> \n> ``` java\n> pipeline.addLast(\"decoder\", new SpdyFrameDecoder(spdyVersion));\n> pipeline.addLast(\"spdy_encoder\", new SpdyFrameEncoder(spdyVersion));\n> pipeline.addLast(\"spdy_session_handler\", new SpdySessionHandler(spdyVersion, true));\n> pipeline.addLast(\"spdy_http_encoder\", new SpdyHttpEncoder(spdyVersion));\n> pipeline.addLast(\"spdy_http_decoder\", new SpdyHttpDecoder(spdyVersion, config.getMaxContentSize()));\n> if (config != null && config.getProcessingExecutor() != null) {\n> pipeline.addLast(\"executor\", new ExecutionHandler(config.getProcessingExecutor()));\n> } //if\n> pipeline.addLast(\"handler\", new HttpServerHandler(channelGroup, handlers));\n> ```\n> \n> <i>spdyVersion</i> is set to either <b>2</b> or <b>3</b> depending on the outcome of NPN.\n> \n> Using chrome 20.0.1132.43 and netty 3.5.2.\n> \n> Every once in a while chome would return the error:\n> Error 337 (net::ERR_SPDY_PROTOCOL_ERROR): Unknown error\n> \n> Restarting chrome allows one to browse more before encountering the error again.\n> \n> Switching on packet tracing in chrome results in:\n> \n> > t=1341569010002 [st=58620] SPDY_SESSION_SEND_RST_STREAM\n> > --> description = \"Could not parse Spdy Control Frame Header.\"\n> > --> status = 1\n> > --> stream_id = 397\n> \n> This error can be triggered with and without the ExecutionHandler. Any idea where one can start looking for the problem?\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/442\n", "@jpinner \n\nhave created a gist with both the hex dump (from logginghandler) and the chrome trace:\nhttps://gist.github.com/720271be47ffd4b54a25\n\nplease let me know if you need anything else....\n", "Thanks for the gist. I've figured out the error -- it's a race condition:\n\nThe responses were compressed through the SpdyFrameDecoder in this order: 1, 3, 13, 15, 11, 9, 5, 17, 19\n\n17 was written by worker #5 and 19 was written by worker #6, however, worker #6 was able to write to the channel before worker #5 so the responses were written to the channel in this order: 1, 3, 13, 15, 11, 9, 5, 19, 17\n", "@trustin, @normanmaurer : how would you suggest addressing this for netty 3?\n\n(isn't this fixed automatically in netty 4 by having the channel be single threaded in both directions?)\n", "@jpinner sorry I guess you mean \"SpdyFrameDecoder\" right ? So you say the problem is that if you call:\n\nchannel.write(new ...);\nchannel.write(new ...); \n\nits possible that the second write will be faster then first if they are executed from different threads ? Thats correct as you would need to schedule the second in a ChannelFutureListener if you want to be sure that its executed after the first.\n", "Is that necessarily scalable? what's to prevent 3 threads from writing concurrently? or 16?\n\nI would need each write to be enqueued on a transfer queue that synchronized with the decoder state. And a dedicated thread to read from to transfer from that queue to the channel's write queue. Is there a way to schedule execution for the channel's worker thread?\n", "what you could do is this:\n\n``` java\nchannel.getChannelPipeline().execute(new Runnable() {\n public void run() {\n channel.write(..)\n }\n}\n```\n\nThis would execute the write request in the IO-Loop/Thread\n", "thanks! :)\n\nOn Tue, Jul 10, 2012 at 12:28 AM, Norman Maurer\[email protected]\nwrote:\n\n> what you could do is this:\n> \n> ``` java\n> channel.getChannelPipeline().execute(new Runnable() {\n> public void run() {\n> channel.write(..)\n> }\n> }\n> ```\n> \n> This would execute the write request in the IO-Loop/Thread\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/442#issuecomment-6868771\n", "I wonder if it would be a good idea todo this under-the-hood for the user. So on write it would schedule it in the event loop and so make sure that there can be no race. The downside would be that it will add some latency\n\n@trustin wdyt ?\n", "@jpinner thank you. quickly tested the patch and everything is now working as expected.\n", "I prefer to keep the current behavior because it might affect existing applications built on top of 3.\n", "@trustin, how so?\n\nThe sender's compression context and receiver's decompression context\nmust be kept in sync, so frames must be delivered to the socket in the\norder they are compressed.\n\nI think the existing race condition is a bug.\n\nOn Tue, Jul 10, 2012 at 6:02 AM, Trustin Lee\[email protected]\nwrote:\n\n> I prefer to keep the current behavior because it might affect existing applications built on top of 3.\n> \n> ---\n> \n> Reply to this email directly or view it on GitHub:\n> https://github.com/netty/netty/issues/442#issuecomment-6874734\n", "@jpinner I was talking about @normanmaurer 's proposal to force all downstream event invokcation to be run by an I/O thread. Your fix is great. :-)\n" ]
[]
"2012-08-21T12:33:20Z"
[ "defect" ]
Spdy error -> Error 337 (net::ERR_SPDY_PROTOCOL_ERROR): Unknown error
hi, I have added spdy support to a web server. The pipeline is fairly typical: ``` java pipeline.addLast("decoder", new SpdyFrameDecoder(spdyVersion)); pipeline.addLast("spdy_encoder", new SpdyFrameEncoder(spdyVersion)); pipeline.addLast("spdy_session_handler", new SpdySessionHandler(spdyVersion, true)); pipeline.addLast("spdy_http_encoder", new SpdyHttpEncoder(spdyVersion)); pipeline.addLast("spdy_http_decoder", new SpdyHttpDecoder(spdyVersion, config.getMaxContentSize())); if (config != null && config.getProcessingExecutor() != null) { pipeline.addLast("executor", new ExecutionHandler(config.getProcessingExecutor())); } //if pipeline.addLast("handler", new HttpServerHandler(channelGroup, handlers)); ``` <i>spdyVersion</i> is set to either <b>2</b> or <b>3</b> depending on the outcome of NPN. Using chrome 20.0.1132.43 and netty 3.5.2. Every once in a while chome would return the error: Error 337 (net::ERR_SPDY_PROTOCOL_ERROR): Unknown error Restarting chrome allows one to browse more before encountering the error again. Switching on packet tracing in chrome results in: > t=1341569010002 [st=58620] SPDY_SESSION_SEND_RST_STREAM > --> description = "Could not parse Spdy Control Frame Header." > --> status = 1 > --> stream_id = 397 This error can be triggered with and without the ExecutionHandler. Any idea where one can start looking for the problem?
[ "src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java b/src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java index d8bdd9b62c0..e6ed2ff325a 100644 --- a/src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/spdy/SpdyFrameEncoder.java @@ -159,11 +159,7 @@ public void handleDownstream( } // Writes of compressed data must occur in order final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(frame, data); - e.getChannel().getPipeline().execute(new Runnable() { - public void run() { - Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); - } - }); + Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); } return; @@ -197,11 +193,7 @@ public void run() { } // Writes of compressed data must occur in order final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(frame, data); - e.getChannel().getPipeline().execute(new Runnable() { - public void run() { - Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); - } - }); + Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); } return; @@ -323,11 +315,7 @@ public void run() { } // Writes of compressed data must occur in order final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(frame, data); - e.getChannel().getPipeline().execute(new Runnable() { - public void run() { - Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); - } - }); + Channels.write(ctx, e.getFuture(), buffer, e.getRemoteAddress()); } return;
null
val
train
2012-08-21T13:13:44
"2012-07-06T10:16:04Z"
naude-r
val
netty/netty/547_564
netty/netty
netty/netty/547
netty/netty/564
[ "timestamp(timedelta=38013.0, similarity=0.8614472946287012)" ]
573fbfa518dc7dbf38397e5b603a4cd2b0c79cc4
36a6a9ec2680dc7387e426bedfb88dfaf7f3ea39
[ "Ah, if only this was Launchpad - I'd assign myself to this \n\nI've made a patch to use Random, but it looks like the IDs have to be negative - To \"avoid conflicts with user-specified IDs\"\n\nI'll make this pull request and add some test cases later, then if required, I'll see if it's viable to use Long values instead :)\n", "Thank to @CruzBishop for the patches!\n", "Any time :)\n", "Have you considered using `ThreadLocalRandom` to reduce concurrent contendancy?\n", "@shpikat, sounds like a good idea\n" ]
[ "Please remove the public getter..\n", "Alright\n" ]
"2012-08-25T03:46:37Z"
[ "improvement" ]
Improved channel ID entropy
The Netty channel ID is an ideal key that can be used to help track and diagnose problems occurring within a server. For example I log the channel ID with all notable events that occur in my server. I also store usage and throughput statistic keyed on channel ID. These can then be queried and correlated when we have an issue to diagnose. I could create my own GUID for this but the existing channel ID is great for this as it is always available everywhere in your code that you need to log an IO event. Unfortunately, however, the current 32-bit channel ID which is based on System.identityHashCode(channel) has poor entropy making it less useful than it could be. On testing a server handling many thousands of connections over a long period of time I have never observed a channel ID greater than 0x01FFFFFF. Over time, as client connections come and go, repeat channel IDs are more common that you would expect from a 32-bit value. It would be helpful if either: 1. The algorithm in AbstractChannel could be changed to use a 32-bit random number, or 2. There was a mechanism to override the default algorithm (perhaps via the ChannelFactory).
[ "src/main/java/org/jboss/netty/channel/AbstractChannel.java" ]
[ "src/main/java/org/jboss/netty/channel/AbstractChannel.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/channel/AbstractChannel.java b/src/main/java/org/jboss/netty/channel/AbstractChannel.java index 6de954403ee..bf182668275 100644 --- a/src/main/java/org/jboss/netty/channel/AbstractChannel.java +++ b/src/main/java/org/jboss/netty/channel/AbstractChannel.java @@ -16,6 +16,7 @@ package org.jboss.netty.channel; import java.net.SocketAddress; +import java.util.Random; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.util.internal.ConcurrentHashMap; @@ -27,8 +28,10 @@ public abstract class AbstractChannel implements Channel { static final ConcurrentMap<Integer, Channel> allChannels = new ConcurrentHashMap<Integer, Channel>(); + private static final Random random = new Random(); + private static Integer allocateId(Channel channel) { - Integer id = System.identityHashCode(channel); + Integer id = random.nextInt(); for (;;) { // Loop until a unique ID is acquired. // It should be found in one loop practically. @@ -139,12 +142,11 @@ protected ChannelFuture getUnsupportedOperationFuture() { } /** - * Returns the {@linkplain System#identityHashCode(Object) identity hash code} - * of this channel. + * Returns the ID of this channel. */ @Override public final int hashCode() { - return System.identityHashCode(this); + return this.id; } /**
null
train
train
2012-08-24T08:34:04
"2012-08-22T16:32:31Z"
psweeny
val
netty/netty/569_572
netty/netty
netty/netty/569
netty/netty/572
[ "keyword_pr_to_issue" ]
dc56905630030364fd37cc1a1e1abe2b8ea4e36c
781a8e4dcd82a2cfab11d9b652367ce92e733e21
[ "@ngocdaothanh does this also happen with older versions ?\n", "1.\n\nYes, same problem with 3.5.3.Final.\n\n2.\n\nThis problem can be reproduced with the last form (no file is selected) at:\norg.jboss.netty.example.http.upload.HttpUploadServerHandler\nof the latest Netty 3 branch.\n\nI guess this problem may be related with cookie:\n\n2.1. Using Chrome with some cookies\n\nAfter posting the form about 3 times, this error will be printed in the console:\n\n```\nAug 27, 2012 2:59:07 PM org.jboss.netty.example.http.upload.HttpUploadServerHandler\nSEVERE: WELCOME TO THE WILD WILD WEB SERVER\n===================================\nVERSION: HTTP/1.1\nREQUEST_URI: /formpostmultipart\n\n\n\nHEADER: Host=localhost:8080\nHEADER: Connection=keep-alive\nHEADER: Content-Length=670\nHEADER: Cache-Control=max-age=0\nHEADER: Origin=http://localhost:8080\nHEADER: User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1\nHEADER: Content-Type=multipart/form-data; boundary=----WebKitFormBoundary3UbKLOfprY9gaKzo\nHEADER: Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nHEADER: Referer=http://localhost:8080/\nHEADER: Accept-Encoding=gzip,deflate,sdch\nHEADER: Accept-Language=en-US,en;q=0.8\nHEADER: Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.3\nHEADER: Cookie=_session=AAACQJAneGp2k3ib2OyAbItsVTmeqtcheBHiZx1aF2gXN4uoCBxlD8zMkKzlvEXKyQy8acAQGNBU6hfNt9XD5yywFmgZ72ZyFSHlYWVe7ha2xAhbNKI-5uxq7F0eLxVt-ks9_SJfPx1LAmMyY9SV42DOr9t8jl3UCbSJmKYFwi_JWMEvDNmruoUyaKBYMDwNbMnE2BZmsbWQ3IJt9AjrO3EVIwcNtoRRWgnpUQJNuA_N7fuDwrtsCQc0x4r4StAfgjfEThz2tFxNPyLzmqet5DM2p8yRzUme8QaNSlCDV0v5EFHqUWMbwUc9pcd9I73REOYbT4L8JaXzCM6f6epYmYEHyMs5rCzOGnWs3inxkTDKpRnun1w8dsF0UR_YtR42K8d9uCNvBdpau0XUSQ_ZSCAubUArnr9SL-FJzVTkyHazQItM40ubIUzjLe3TRyHntsFYHGp0wvhLVjVQz3aFCZiyXEOM-SjiiIMQcvzLy4mZ4I7XY9Fmrg7Ee9WmmCuTjRNunEfHMAjFFvbmRt06zk-fs2NircRGDLR_3X1xbaQJnMhxHA99N1-Ow_3U_tJv_Xte929LY7vwHArwFHJrx-ecWNlQqnGKSS3sHDQttAFUXCx7yXwP4oTaMJLsqHor0tDHZkTTKGhQtR8nRAw0dmhF_M76LE9NQJs47kN_6MjcI6QtELiVjti_ZeST-dIVKLP09jTlKkbMebeXq6UQCg8G6rgSdNofVb32m5geoVTtjKxKr4d2kaRoFcQ8kaThPnwYrGymzx6bShQUaEbs9fo3SghNi3OkgDzIhJvN5CFcEdk1; firstVisitorCookie=1; s_cc=true; s_nr=1345733923539; s_ppv=24; s_sq=%5B%5BB%5D%5D; ttc11=1353505852841\n\n\nCOOKIE: _session=AAACQJAneGp2k3ib2OyAbItsVTmeqtcheBHiZx1aF2gXN4uoCBxlD8zMkKzlvEXKyQy8acAQGNBU6hfNt9XD5yywFmgZ72ZyFSHlYWVe7ha2xAhbNKI-5uxq7F0eLxVt-ks9_SJfPx1LAmMyY9SV42DOr9t8jl3UCbSJmKYFwi_JWMEvDNmruoUyaKBYMDwNbMnE2BZmsbWQ3IJt9AjrO3EVIwcNtoRRWgnpUQJNuA_N7fuDwrtsCQc0x4r4StAfgjfEThz2tFxNPyLzmqet5DM2p8yRzUme8QaNSlCDV0v5EFHqUWMbwUc9pcd9I73REOYbT4L8JaXzCM6f6epYmYEHyMs5rCzOGnWs3inxkTDKpRnun1w8dsF0UR_YtR42K8d9uCNvBdpau0XUSQ_ZSCAubUArnr9SL-FJzVTkyHazQItM40ubIUzjLe3TRyHntsFYHGp0wvhLVjVQz3aFCZiyXEOM-SjiiIMQcvzLy4mZ4I7XY9Fmrg7Ee9WmmCuTjRNunEfHMAjFFvbmRt06zk-fs2NircRGDLR_3X1xbaQJnMhxHA99N1-Ow_3U_tJv_Xte929LY7vwHArwFHJrx-ecWNlQqnGKSS3sHDQttAFUXCx7yXwP4oTaMJLsqHor0tDHZkTTKGhQtR8nRAw0dmhF_M76LE9NQJs47kN_6MjcI6QtELiVjti_ZeST-dIVKLP09jTlKkbMebeXq6UQCg8G6rgSdNofVb32m5geoVTtjKxKr4d2kaRoFcQ8kaThPnwYrGymzx6bShQUaEbs9fo3SghNi3OkgDzIhJvN5CFcEdk1\nCOOKIE: firstVisitorCookie=1\nCOOKIE: s_cc=true\nCOOKIE: s_nr=1345733923539\nCOOKIE: s_ppv=24\nCOOKIE: s_sq=%5B%5BB%5D%5D\nCOOKIE: ttc11=1353505852841\n\n\n\n\n\njava.lang.IndexOutOfBoundsException\n at org.jboss.netty.buffer.AbstractChannelBuffer.readerIndex(AbstractChannelBuffer.java:44)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostBodyUtil$SeekAheadOptimize.setReadPosition(HttpPostBodyUtil.java:163)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.skipControlCharacters(HttpPostRequestDecoder.java:865)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.findMultipartDelimiter(HttpPostRequestDecoder.java:895)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.decodeMultipart(HttpPostRequestDecoder.java:766)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBodyMultipart(HttpPostRequestDecoder.java:727)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBody(HttpPostRequestDecoder.java:408)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.<init>(HttpPostRequestDecoder.java:191)\n at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.<init>(HttpPostRequestDecoder.java:148)\n at org.jboss.netty.example.http.upload.HttpUploadServerHandler.messageReceived(HttpUploadServerHandler.java:161)\n at org.jboss.netty.handler.codec.http.HttpContentEncoder.messageReceived(HttpContentEncoder.java:82)\n at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:296)\n at org.jboss.netty.handler.codec.frame.FrameDecoder.unfoldAndFireMessageReceived(FrameDecoder.java:455)\n at org.jboss.netty.handler.codec.replay.ReplayingDecoder.callDecode(ReplayingDecoder.java:538)\n at org.jboss.netty.handler.codec.replay.ReplayingDecoder.messageReceived(ReplayingDecoder.java:437)\n at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268)\n at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255)\n at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:94)\n at org.jboss.netty.channel.socket.nio.AbstractNioWorker.processSelectedKeys(AbstractNioWorker.java:390)\n at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:261)\n at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:35)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)\n at java.lang.Thread.run(Thread.java:722)\n```\n\n2.2. Using Firefox without cookie\n\nThere's no error.\n\nBut there's another problem: when posting the form the second time with \"1\", \"2\", and \"3\" as values for the first 3 parameters of the last form, the server side does not output the values.\n\n```\nWELCOME TO THE WILD WILD WEB SERVER\n===================================\nVERSION: HTTP/1.1\nREQUEST_URI: /formpostmultipart\n\n\n\nHEADER: Host=localhost:8080\nHEADER: User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1\nHEADER: Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nHEADER: Accept-Language=en-us,en;q=0.5\nHEADER: Accept-Encoding=gzip, deflate\nHEADER: Connection=keep-alive\nHEADER: Referer=http://localhost:8080/\nHEADER: Content-Type=multipart/form-data; boundary=---------------------------8006742647998229461524106849\nHEADER: Content-Length=789\n\n\n\n\n\n\nIs Chunked: false\nIsMultipart: true\n\n\nEND OF CONTENT AT FINAL END\n\n\nEND OF NOT CHUNKED CONTENT\n```\n", "@fredericBregier could you please have a look. I think the problem is that ChannelBuffer.readerIndex(-1) is called.\n", "@normanmaurer I will try this evening to take a look at this issue...\n", "Thanks!\n\nSent from my iPhone. Excuse any typos....\n\nAm 27.08.2012 um 18:08 schrieb Frédéric Brégier [email protected]:\n\n> @normanmaurer I will try this evening to take a look at this issue...\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Hi all,\n\nOK, I don't find yet the reason but I can reproduce and not reproduce it. I explain myself:\n\n1- If the file is specified with enough size (such that chunk is ON, so more than 8K), it is OK for all Browsers.\n\n2- Now with only 1, 2, 3 as parameter and no file (or a small one such that the global size is less than 8K):\n- IE 9 : no problem, always ok\n- Firefox 14.0.1 : \n OK first time\n KO next times, \n except if I do a CTRL-F5 (force reload) on the page (whatever the upload page or web menu page), \n but not OK if only simple F5\n- Chrome 23.0.1243.3\n OK first time\n KO next times, \n\nMoreover, if I wait a long time (such that the browser finish the connection that were pending due to persistent connection), the request is OK again (for all browsers).\n\nSo from those elements, I try to force \"close\" on each response (in writeResponse method, after computation of close boolean, I force close to be \"true\"), and then for all browser it is ok.\n\nSo I don't think right now it is related to the channelbuffer.readerIndex(-1).\nBut I do not know where the issue is...\nI suppose that a value is kept behind since the connection is not closed and therefore bringing wrong result... but which one ? I try to seek the value in the handler and see nothing. All variables seem new for each request, as if the connection where new.\n\nFrom some trace, what I've seen is that when not reloading, Firefox send the exact same \"boundary\".\nOK, I stop here for tonight, but if you have an idea I could check tomorrow...\n", "Hi all,\n\nFor your information, I've made another test by deactivating the SeekAheadOptimize optimization, and there is no more issue with Firefox. I didn't test yet with Chrome but will do...\nIf this is the root cause (and it seems so), then I will spend some time to understand why.\n\nEdit: I confirm that with Chrome this is OK too by deactivating SeekAheadOptimize... I'm starting to look for the reason.\n", "For all, I finally found the issue. This was introduced by a correction on arrayOffset usage in the optimization part, but not enough... So I test it under IE, Firefox and Chrome, it seems now correct whatever the size of the upload.\n\n@normanmaurer Sorry Norman, but I don't have access to all my tools to check the \"typo\" stuff.\nCould you check it before any merge ?\n", "@fredericBregier\nThanks a lot!\n\n@normanmaurer\nSorry because 3.5.5.Final was only released a few days ago, but should a new version be released soon?\n", "@ngocdaothanh Ok I think we are good now as @fredericBregier fixed the bug (yay)... Please retest with latest code out of the 3 branch and give us feedback..\n\nThanks!\n", "By the way, Thank you @normanmaurer to check my fix ;-) \nI was pretty sure of what I've done, but as I had only web access to publish, I was not 100% sure, and you did it well and quick ! \nSorry to have push this on your side and Thank you again !\n", "You are welcome... Thanks to find the time to investigate, I only did the dumb part\n\nSent from my iPhone. Excuse any typos....\n\nAm 28.08.2012 um 18:49 schrieb Frédéric Brégier [email protected]:\n\n> By the way, Thank you @normanmaurer to check my fix ;-) \n> I was pretty sure of what I've done, but as I had only web access to publish, I was not 100% sure, and you did it well and quick ! \n> Sorry to have push this on your side and Thank you again !\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "> Please retest with latest code out of the 3 branch and give us feedback..\n\nI confirm that there's no error now.\nThanks a lot.\n" ]
[]
"2012-08-28T13:48:06Z"
[ "defect" ]
[3.5.5.Final] Error when uploading nothing
I'm using Netty 3.5.5.Final and Firefox 14.0.1. When uploading a form like this: ``` <form class="well span6" method="post" action="/apps/573d3849f224f9f1a160b6feb2759967/markers/7ab50bf507ac9bd3cf08f2141b4e2158" enctype="multipart/form-data"> <input type="hidden" name="csrf-token" value="9d26ddeb-3b38-4a49-924e-9f3093f37cf7"/> <input type="hidden" name="_method" value="put"/> <label>Image</label> <input class="span6" type="file" name="image"/> <label>Description</label> <input class="span6" type="text" name="description" value="" /> <label>Return data</label> <input class="span6" type="text" name="return_data" value="" /> </form> ``` I sometimes (not always, about once every 5 times) get this error when not selecting any image file to upload: ``` java.lang.IndexOutOfBoundsException: null at org.jboss.netty.buffer.AbstractChannelBuffer.readerIndex(AbstractChannelBuffer.java:44) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostBodyUtil$SeekAheadOptimize.setReadPosition(HttpPostBodyUtil.java:163) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.skipControlCharacters(HttpPostRequestDecoder.java:865) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.findMultipartDelimiter(HttpPostRequestDecoder.java:895) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.decodeMultipart(HttpPostRequestDecoder.java:766) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBodyMultipart(HttpPostRequestDecoder.java:727) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBody(HttpPostRequestDecoder.java:408) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.<init>(HttpPostRequestDecoder.java:191) ~[netty-3.5.5.Final.jar:na] at org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.<init>(HttpPostRequestDecoder.java:148) ~[netty-3.5.5.Final.jar:na] at xitrum.handler.up.BodyParser.messageReceived(BodyParser.scala:55) ~[xitrum_2.9.2-1.9.4.jar:1.9.4] ``` BodyParser.scala:55 https://github.com/ngocdaothanh/xitrum/blob/master/src/main/scala/xitrum/handler/up/BodyParser.scala#L55 Data sent to server: ``` POST /apps/573d3849f224f9f1a160b6feb2759967/markers/7ab50bf507ac9bd3cf08f2141b4e2158 HTTP/1.1 Host: localhost:2218 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://localhost:2218/apps/573d3849f224f9f1a160b6feb2759967/markers/7ab50bf507ac9bd3cf08f2141b4e2158/edit Cookie: _session=AAACQJAneGp2k3ib2OyAbItsVTmeqtcheBHiZx1aF2gXN4uoCBxlD8zMkKzlvEXKyQy8acAQGNBU6hfNt9XD5yywFmgZ72ZyFSHlYWVe7ha2xAhbNKI-5uxq7F0eLxVt-ks9_SJfPx1LAmMyY9SV42DOr9t8jl3UCbSJmKYFwi_JWMEvDNmruoUyaKBYMDwNbMnE2BZmsbWQ3IJt9AjrO3EVIwdFFF-LUpKP_0AWhtAOcgDek1Xm627eg9qHSNyWHRzz-mb3ZaR3EjfNXqq-dxfRt89bglfn4xHI8pK9TrFXHhbctQJLUeFdK3GVPYv1zqshGdYPGjv2S1d6D36sunYZujl5lHQ0tnSwdEcU2KzEs04jNkXPGPqjVsQLdOUlWvIXcrOVEXrIV3cqctpNW0ofZR24Z4mEhjo2X5O7zN4FeYGBF371BzkSuexa6Ix3mIrNu4pO5aUidMAufyAwqUl44hUr0rgMjfSEaj9THWavvVwctw6GiATeqQnE7xZNw8VIA8dbMLnJhZ2Czumwzh0YumQK_qTeVKEuFRHUdoDgU5jXuuj7vn9BAJ2eSDebUvZs7M_cI159TLb4c_hfclbMVXD8WVXlVkbGL_0NxYHvwtCYYPYZPtS90-s7oZQ4xSgH0ewK-EmUl7et25e7pphsr13PV_OyLcxccU9UNseiIy8HGL0OM5c8dWCjTW45eHeDv0ZcK_NtQLEHjUxmik6izC2rpelzSyUPl7IRocLTn1HoW79oz2H3fTdhee2MwWdgR9Z2BZhOgNA6erb-lPrNZruy97sS7QdiGZGs-7DUlmdX Content-Type: multipart/form-data; boundary=---------------------------10903988221855041503514953775 Content-Length: 831 -----------------------------10903988221855041503514953775 Content-Disposition: form-data; name="csrf-token" 9d26ddeb-3b38-4a49-924e-9f3093f37cf7 -----------------------------10903988221855041503514953775 Content-Disposition: form-data; name="_method" put -----------------------------10903988221855041503514953775 Content-Disposition: form-data; name="image"; filename="" Content-Type: application/octet-stream -----------------------------10903988221855041503514953775 Content-Disposition: form-data; name="description" -----------------------------10903988221855041503514953775 Content-Disposition: form-data; name="return_data" http://169.254.47.225:2218/upload/file/f12a4df1da77a5c66ac8adaf42d3f28d/5ead9425a4571037e007c35186e452fb.mp4 -----------------------------10903988221855041503514953775-- ```
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java", "src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java index c0d923c83e4..12a4a0e5e1d 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostBodyUtil.java @@ -134,6 +134,8 @@ static class SeekAheadOptimize { int readerIndex; int pos; + + int origPos; int limit; @@ -148,7 +150,8 @@ static class SeekAheadOptimize { } this.buffer = buffer; bytes = buffer.array(); - pos = readerIndex = buffer.arrayOffset() + buffer.readerIndex(); + readerIndex = buffer.readerIndex(); + origPos = pos = buffer.arrayOffset() + readerIndex; limit = buffer.arrayOffset() + buffer.writerIndex(); } @@ -159,10 +162,19 @@ static class SeekAheadOptimize { */ void setReadPosition(int minus) { pos -= minus; - readerIndex = pos; + readerIndex = getReadPosition(pos); buffer.readerIndex(readerIndex); } + /** + * + * @param index raw index of the array (pos in general) + * @return the value equivalent of raw index to be used in readerIndex(value) + */ + int getReadPosition(int index) { + return index - origPos + readerIndex; + } + void clear() { buffer = null; bytes = null; diff --git a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java index 3b674280fed..0cf9837b23e 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java @@ -849,13 +849,18 @@ private InterfaceHttpData decodeMultipart(MultiPartStatus state) /** * Skip control Characters + * @throws NotEnoughDataDecoderException */ - void skipControlCharacters() { + void skipControlCharacters() throws NotEnoughDataDecoderException { SeekAheadOptimize sao = null; try { sao = new SeekAheadOptimize(undecodedChunk); } catch (SeekAheadNoBackArrayException e) { - skipControlCharactersStandard(undecodedChunk); + try { + skipControlCharactersStandard(undecodedChunk); + } catch (IndexOutOfBoundsException e1) { + throw new NotEnoughDataDecoderException(e1); + } return; } @@ -866,13 +871,13 @@ void skipControlCharacters() { return; } } - sao.setReadPosition(0); + throw new NotEnoughDataDecoderException("Access out of bounds"); } - static void skipControlCharactersStandard(ChannelBuffer buffer) { + void skipControlCharactersStandard() { for (;;) { - char c = (char) buffer.readUnsignedByte(); + char c = (char) undecodedChunk.readUnsignedByte(); if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { - buffer.readerIndex(buffer.readerIndex() - 1); + undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1); break; } } @@ -892,7 +897,12 @@ private InterfaceHttpData findMultipartDelimiter(String delimiter, throws ErrorDataDecoderException { // --AaB03x or --AaB03x-- int readerIndex = undecodedChunk.readerIndex(); - skipControlCharacters(); + try { + skipControlCharacters(); + } catch (NotEnoughDataDecoderException e1) { + undecodedChunk.readerIndex(readerIndex); + return null; + } skipOneLine(); String newline; try { @@ -933,9 +943,9 @@ private InterfaceHttpData findMultipartDisposition() } // read many lines until empty line with newline found! Store all data while (!skipOneLine()) { - skipControlCharacters(); String newline; try { + skipControlCharacters(); newline = readLine(); } catch (NotEnoughDataDecoderException e) { undecodedChunk.readerIndex(readerIndex); @@ -1594,8 +1604,8 @@ private void readFileUploadByteMultipart(String delimiter) // found the decoder limit boolean newLine = true; int index = 0; + int lastrealpos = sao.pos; int lastPosition = undecodedChunk.readerIndex(); - int setReadPosition = -1; boolean found = false; while (sao.pos < sao.limit) { @@ -1606,7 +1616,6 @@ private void readFileUploadByteMultipart(String delimiter) index ++; if (delimiter.length() == index) { found = true; - sao.setReadPosition(0); break; } continue; @@ -1620,23 +1629,16 @@ private void readFileUploadByteMultipart(String delimiter) if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - setReadPosition = sao.pos; - lastPosition = sao.pos - 2; + lastrealpos = sao.pos - 2; } - } else { - // save last valid position - setReadPosition = sao.pos; - lastPosition = sao.pos; } } else if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - setReadPosition = sao.pos; - lastPosition = sao.pos - 1; + lastrealpos = sao.pos - 1; } else { // save last valid position - setReadPosition = sao.pos; - lastPosition = sao.pos; + lastrealpos = sao.pos; } } } else { @@ -1647,30 +1649,20 @@ private void readFileUploadByteMultipart(String delimiter) if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - setReadPosition = sao.pos; - lastPosition = sao.pos - 2; + lastrealpos = sao.pos - 2; } - } else { - // save last valid position - setReadPosition = sao.pos; - lastPosition = sao.pos; } } else if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - setReadPosition = sao.pos; - lastPosition = sao.pos - 1; + lastrealpos = sao.pos - 1; } else { // save last valid position - setReadPosition = sao.pos; - lastPosition = sao.pos; + lastrealpos = sao.pos; } } } - if (setReadPosition > 0) { - sao.pos = setReadPosition; - sao.setReadPosition(0); - } + lastPosition = sao.getReadPosition(lastrealpos); ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex); if (found) { // found so lastPosition is correct and final @@ -1809,7 +1801,7 @@ private void loadFieldMultipart(String delimiter) boolean newLine = true; int index = 0; int lastPosition = undecodedChunk.readerIndex(); - int setReadPosition = -1; + int lastrealpos = sao.pos; boolean found = false; while (sao.pos < sao.limit) { @@ -1820,7 +1812,6 @@ private void loadFieldMultipart(String delimiter) index ++; if (delimiter.length() == index) { found = true; - sao.setReadPosition(0); break; } continue; @@ -1834,21 +1825,15 @@ private void loadFieldMultipart(String delimiter) if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - lastPosition = sao.pos - 2; - setReadPosition = sao.pos; + lastrealpos = sao.pos - 2; } - } else { - lastPosition = sao.pos; - setReadPosition = sao.pos; } } else if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - lastPosition = sao.pos - 1; - setReadPosition = sao.pos; + lastrealpos = sao.pos - 1; } else { - lastPosition = sao.pos; - setReadPosition = sao.pos; + lastrealpos = sao.pos; } } } else { @@ -1859,28 +1844,19 @@ private void loadFieldMultipart(String delimiter) if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - lastPosition = sao.pos - 2; - setReadPosition = sao.pos; + lastrealpos = sao.pos - 2; } - } else { - lastPosition = sao.pos; - setReadPosition = sao.pos; } } else if (nextByte == HttpConstants.LF) { newLine = true; index = 0; - lastPosition = sao.pos - 1; - setReadPosition = sao.pos; + lastrealpos = sao.pos - 1; } else { - lastPosition = sao.pos; - setReadPosition = sao.pos; + lastrealpos = sao.pos; } } } - if (setReadPosition > 0) { - sao.pos = setReadPosition; - sao.setReadPosition(0); - } + lastPosition = sao.getReadPosition(lastrealpos); if (found) { // found so lastPosition is correct // but position is just after the delimiter (either close delimiter or simple one)
null
val
train
2012-08-28T14:38:58
"2012-08-27T03:59:30Z"
ngocdaothanh
val
netty/netty/605_613
netty/netty
netty/netty/605
netty/netty/613
[ "keyword_issue_to_pr" ]
c3af4427bbb6118e60fdfd4e81e5f7c4b7d2efac
27c65199bd997d783deb31c89a8122a86e6834f5
[ "In 3.5.3, the context switching was high in websocket client connections but in 3.5.7 the context switching is high for both server and client connections.\n", "The main reason for I believe is lowering the select timeout from `500` to `10` milliseconds. @trustin / @normanmaurer, I think the solution of lowering it is problematic, since as explained here, and based on what I have seen, the overhead is quite big.\n", "@kimchy what I not get is that @gauravsri says that it was not in 3.5.3... The lowering of the timeout was done before that. The problem with have the timeout high is that you will \"delay\" events if you are \"lucky\" enough, and so harm throughput. What you can do now is that you adjust it via the \"org.jboss.netty.selectTimeout\" property to match your need... Anyway we may want to think about to make a higher default value better \"fit\" the average user.\n", "In 3.5.3, I only see high context switching when using it for client connections (@200-300 more context switches per second per client connection). In 3.5.7, the context switches are increasing for bother server and client connections.\n\nThis is definitely an issue for me as the issue was noted by a customer when they observed that the load average in 3.5.3 has suddenly increased by 4 on an idle system. I tried the latest version to see if that resolved the problem but it became even worse.\n\nI will try by adjusting it using the property mentioned and let you know of my observations.\n", "Changing the property to 500 doesn't seem to help. Following is output of vmstat when I launch with the new value.\n\nThere are no websocket connections at this time (only a websocket server listening on wss). As you can see the context switches still increases from 1500 to 3500.\n\n -Dorg.jboss.netty.selectTimeout=500 was set.\n\nprocs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------\n r b swpd free buff cache si so bi bo in cs us sy id wa st\n 0 0 1571720 122776 135748 224668 0 0 0 108 1043 1415 0 0 100 0 0\n 0 0 1571720 122776 135748 224668 0 0 0 0 1016 1538 0 0 100 0 0\n 1 0 1571720 122652 135748 224668 0 0 0 0 1012 1349 0 0 100 0 0\n 0 0 1571720 122156 135748 224668 0 0 0 0 1012 1419 0 0 100 0 0\n 1 0 1571720 113476 135748 224672 0 0 0 24 1017 1785 21 2 77 0 0\n 4 0 1571720 102936 135748 224672 0 0 0 316 1066 1658 32 3 66 0 0\n 1 0 1571720 82724 135748 224704 0 0 0 0 1021 2093 38 3 59 0 0\n 1 0 1571720 78384 135748 224704 0 0 0 0 1019 1611 37 1 62 0 0\n 1 0 1571720 75532 135748 224728 0 0 0 0 1017 1500 33 2 65 0 0\n 0 0 1571720 70820 135748 224728 0 0 0 184 1054 4324 11 1 88 0 0\n 1 0 1571720 70200 135748 224744 0 0 0 292 1042 4012 0 0 99 0 0\n 0 0 1571720 69952 135748 224712 32 0 32 28 1029 4542 4 1 95 0 0\n 0 0 1571720 69952 135748 224756 0 0 0 0 1012 3723 0 0 100 0 0\n 1 0 1571720 70004 135748 224756 0 0 0 0 1016 8358 18 2 80 0 0\n 1 0 1571720 69988 135748 224756 0 0 0 132 1036 5112 5 0 94 0 0\n 1 0 1571720 69988 135748 224756 0 0 0 0 1011 3852 5 0 94 0 0\n 0 0 1571720 69616 135748 224756 0 0 0 228 1048 3989 0 0 99 0 0\n 0 0 1571720 69616 135748 224756 0 0 0 0 1015 3701 0 0 100 0 0\n 0 0 1571720 67912 135748 224756 0 0 0 0 1014 3691 3 1 96 0 0\n 1 0 1571720 67912 135748 224756 0 0 0 0 1015 3412 0 0 100 0 0\n 2 0 1571720 68904 135748 224756 0 0 0 0 1013 3323 0 0 100 0 0\n 3 0 1571720 68904 135748 224756 0 0 0 188 1038 3373 0 0 100 0 0\n 1 0 1571720 68936 135748 224760 0 0 0 0 1013 3456 0 0 100 0 0\n 0 0 1571720 69060 135748 224760 0 0 0 0 1015 3740 0 0 99 0 0\n 2 0 1571720 69060 135748 224760 0 0 0 12 1027 3619 0 0 100 0 0\n 0 0 1571720 69060 135748 224760 0 0 0 0 1014 3935 1 0 99 0 0\n 0 0 1571720 69084 135748 224760 0 0 0 204 1038 3687 0 0 100 0 0\n 0 0 1571720 69084 135748 224760 0 0 0 0 1019 3531 0 0 100 0 0\n 1 0 1571720 69332 135748 224760 0 0 0 0 1015 3549 0 0 99 0 0\n 1 0 1571720 69212 135748 224760 0 0 0 24 1025 8637 19 2 80 0 0\n 0 0 1571720 69212 135748 224764 0 0 0 0 1016 4679 2 0 97 0 0\n 0 0 1571720 69212 135756 224756 0 0 0 96 1035 3861 0 0 100 0 0\n 1 0 1571720 69212 135756 224764 0 0 0 0 1016 3489 1 0 99 0 0\n 0 0 1571720 69212 135756 224764 0 0 0 0 1013 3486 0 1 99 0 0\n 0 0 1571720 69244 135756 224764 0 0 0 12 1018 3501 0 0 100 0 0\n 1 0 1571720 69196 135756 224764 0 0 0 0 1013 9309 21 2 77 0 0\n 0 0 1571720 69196 135764 224768 0 0 0 204 1035 3675 0 0 100 0 0\n 0 0 1571720 69196 135764 224768 0 0 0 0 1011 3417 0 0 100 0 0\n 0 0 1571720 69196 135764 224768 0 0 0 0 1014 3614 0 0 99 0 0\n 0 0 1571720 69196 135764 224768 0 0 0 56 1022 3798 1 0 99 0 0\n 1 1 1571720 68576 135764 224768 0 0 0 140 1014 3504 0 0 100 0 0\n", "I will see if I can find the cause of this..\n\nCan you share your code which you use to setup the ChannelPipeline etc ? It would be even better if you could submit a simple \"app\" that shows the problem ..\n\nAm 15.09.2012 um 16:37 schrieb gauravsri [email protected]:\n\n> Changing the property to 500 doesn't seem to help. Following is output of vmstat when I launch with the new value.\n> \n> There are no websocket connections at this time (only a websocket server listening on wss). As you can see the context switches still increases from 1500 to 3500.\n> \n> -Dorg.jboss.netty.selectTimeout=500 was set.\n> \n> procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------\n> r b swpd free buff cache si so bi bo in cs us sy id wa st\n> 0 0 1571720 122776 135748 224668 0 0 0 108 1043 1415 0 0 100 0 0\n> 0 0 1571720 122776 135748 224668 0 0 0 0 1016 1538 0 0 100 0 0\n> 1 0 1571720 122652 135748 224668 0 0 0 0 1012 1349 0 0 100 0 0\n> 0 0 1571720 122156 135748 224668 0 0 0 0 1012 1419 0 0 100 0 0\n> 1 0 1571720 113476 135748 224672 0 0 0 24 1017 1785 21 2 77 0 0\n> 4 0 1571720 102936 135748 224672 0 0 0 316 1066 1658 32 3 66 0 0\n> 1 0 1571720 82724 135748 224704 0 0 0 0 1021 2093 38 3 59 0 0\n> 1 0 1571720 78384 135748 224704 0 0 0 0 1019 1611 37 1 62 0 0\n> 1 0 1571720 75532 135748 224728 0 0 0 0 1017 1500 33 2 65 0 0\n> 0 0 1571720 70820 135748 224728 0 0 0 184 1054 4324 11 1 88 0 0\n> 1 0 1571720 70200 135748 224744 0 0 0 292 1042 4012 0 0 99 0 0\n> 0 0 1571720 69952 135748 224712 32 0 32 28 1029 4542 4 1 95 0 0\n> 0 0 1571720 69952 135748 224756 0 0 0 0 1012 3723 0 0 100 0 0\n> 1 0 1571720 70004 135748 224756 0 0 0 0 1016 8358 18 2 80 0 0\n> 1 0 1571720 69988 135748 224756 0 0 0 132 1036 5112 5 0 94 0 0\n> 1 0 1571720 69988 135748 224756 0 0 0 0 1011 3852 5 0 94 0 0\n> 0 0 1571720 69616 135748 224756 0 0 0 228 1048 3989 0 0 99 0 0\n> 0 0 1571720 69616 135748 224756 0 0 0 0 1015 3701 0 0 100 0 0\n> 0 0 1571720 67912 135748 224756 0 0 0 0 1014 3691 3 1 96 0 0\n> 1 0 1571720 67912 135748 224756 0 0 0 0 1015 3412 0 0 100 0 0\n> 2 0 1571720 68904 135748 224756 0 0 0 0 1013 3323 0 0 100 0 0\n> 3 0 1571720 68904 135748 224756 0 0 0 188 1038 3373 0 0 100 0 0\n> 1 0 1571720 68936 135748 224760 0 0 0 0 1013 3456 0 0 100 0 0\n> 0 0 1571720 69060 135748 224760 0 0 0 0 1015 3740 0 0 99 0 0\n> 2 0 1571720 69060 135748 224760 0 0 0 12 1027 3619 0 0 100 0 0\n> 0 0 1571720 69060 135748 224760 0 0 0 0 1014 3935 1 0 99 0 0\n> 0 0 1571720 69084 135748 224760 0 0 0 204 1038 3687 0 0 100 0 0\n> 0 0 1571720 69084 135748 224760 0 0 0 0 1019 3531 0 0 100 0 0\n> 1 0 1571720 69332 135748 224760 0 0 0 0 1015 3549 0 0 99 0 0\n> 1 0 1571720 69212 135748 224760 0 0 0 24 1025 8637 19 2 80 0 0\n> 0 0 1571720 69212 135748 224764 0 0 0 0 1016 4679 2 0 97 0 0\n> 0 0 1571720 69212 135756 224756 0 0 0 96 1035 3861 0 0 100 0 0\n> 1 0 1571720 69212 135756 224764 0 0 0 0 1016 3489 1 0 99 0 0\n> 0 0 1571720 69212 135756 224764 0 0 0 0 1013 3486 0 1 99 0 0\n> 0 0 1571720 69244 135756 224764 0 0 0 12 1018 3501 0 0 100 0 0\n> 1 0 1571720 69196 135756 224764 0 0 0 0 1013 9309 21 2 77 0 0\n> 0 0 1571720 69196 135764 224768 0 0 0 204 1035 3675 0 0 100 0 0\n> 0 0 1571720 69196 135764 224768 0 0 0 0 1011 3417 0 0 100 0 0\n> 0 0 1571720 69196 135764 224768 0 0 0 0 1014 3614 0 0 99 0 0\n> 0 0 1571720 69196 135764 224768 0 0 0 56 1022 3798 1 0 99 0 0\n> 1 1 1571720 68576 135764 224768 0 0 0 140 1014 3504 0 0 100 0 0\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "I can create a sample App if needed.\n\nAs for setting up server pipeline, \n\nhttps://gist.github.com/3728640\n", "@gauravsri thats all I need.. will investigate tomorrow ..\n", "@gauravsri changing the system property helps a lot in my case.. I don't understand why it not helps you..\n\n@kimchy @trustin do you think it worth it to change the timeout to higher number by default and just let it get tuned by the \"experience\" folks ? I think we should better just ship with something that the \"general\" user can use and let the \"experts\" tune their setup.\n\nWhat we also good do is have a select timeout of 500ms when the Worker is idle and when at least one channel is registered in the Worker we can adjust it to a smaller number. I think that could be done very easy and so we would safe a lot when idle.. WDYT ?\n", "@gauravsri @kimchy @trustin just committed the \"explained\" idea in the context_switching branch.. WDYT ?\n\nhttps://github.com/netty/netty/tree/context_switching\n", "@normanmaurer Its a good step forward, I don't fully understand why the timeout was needed to be reduced. Is there a chance for an example of a case where smaller timeout helps? I bet it has to do with work that is not select driven, but what is it? Wondering if there is a way to try and solve it in a different manner?\n", "@kimchy If I remember right it was driven by the handling of connection timeouts.. Let me recheck that..\n", "@normanmaurer I can't understand why the system property is not working for me in 3.5.7. I am using the following arg in the command line but don't see any reduction in context switches.\n\n/usr/j2se/bin/java -Dorg.jboss.netty.selectTimeout=500 \n", "@normanmaurer I tried with the sample websocket server provided by netty and the context switches appear reduced with that code. I'll investigate into my application as to why it is showing more context switches with new netty library. \n", "@normanmaurer This issue is fixed with the configuration change. The problem in my App was related to the fact that System properties were being reloaded by the App and getting ignored by netty.\n", "@normanmaurer This issue is fixed with the configuration change. The problem in my App was related to the fact that System properties were being reloaded by the App and getting ignored by netty.\n", "Let us reopen this to find a better way to fix this out-of-the-box..\n", "This should be fixed by #613\n" ]
[ "newTimeout() accepts 'delay', not 'dead line'.\n", "Doh.. Thanks\n\nSent from my iPhone. Excuse any typos....\n\nAm 18.09.2012 um 08:28 schrieb Trustin Lee [email protected]:\n\n> In src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java:\n> \n> > @@ -231,10 +246,16 @@ void register(NioClientSocketChannel channel) {\n> > boolean offered = registerTaskQueue.offer(registerTask);\n> > assert offered;\n> > \n> > ## }\n> > - if (channel.connectDeadlineNanos > 0) {\n> > - if (!channel.isConnected()) {\n> > - channel.timoutTimer = TIMER.newTimeout(wakeupTask,\n> > - channel.connectDeadlineNanos, TimeUnit.NANOSECONDS);\n> > newTimeout() accepts 'delay', not 'dead line'.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n" ]
"2012-09-18T06:23:01Z"
[]
very high context switching when using netty to establish websocket connection in 3.5.7
The context switching on centos 5 has almost doubled when I switched from netty 3.5.3 to netty 3.5.7 for creating websocket connections. Just upgrading netty jar caused context switches to jump from 2000 to 5000. Even 2000 were high especially when there was no websocket traffic and now it is just ridiculously high.
[ "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java", "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java", "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java", "src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java" ]
[ "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java", "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java", "src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java", "src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java index 2753f649730..b473c059289 100644 --- a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java +++ b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.java @@ -27,6 +27,7 @@ import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; +import org.jboss.netty.util.Timeout; final class NioClientSocketChannel extends NioSocketChannel { @@ -71,6 +72,8 @@ private static SocketChannel newSocket() { // Does not need to be volatile as it's accessed by only one thread. long connectDeadlineNanos; + volatile Timeout timoutTimer; + NioClientSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, NioWorker worker) { diff --git a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java index 5b0800ee48d..4a75ab6f94d 100644 --- a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java +++ b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.java @@ -26,6 +26,8 @@ import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.util.ExternalResourceReleasable; +import org.jboss.netty.util.HashedWheelTimer; +import org.jboss.netty.util.Timer; import org.jboss.netty.util.internal.ExecutorUtil; /** @@ -86,6 +88,7 @@ public class NioClientSocketChannelFactory implements ClientSocketChannelFactory private final Executor bossExecutor; private final WorkerPool<NioWorker> workerPool; private final NioClientSocketPipelineSink sink; + private final Timer timer; /** * Creates a new {@link NioClientSocketChannelFactory} which uses {@link Executors#newCachedThreadPool()} @@ -152,6 +155,12 @@ public NioClientSocketChannelFactory( public NioClientSocketChannelFactory( Executor bossExecutor, int bossCount, WorkerPool<NioWorker> workerPool) { + this(bossExecutor, bossCount, workerPool, new HashedWheelTimer()); + } + + public NioClientSocketChannelFactory( + Executor bossExecutor, int bossCount, + WorkerPool<NioWorker> workerPool, Timer timer) { if (bossExecutor == null) { throw new NullPointerException("bossExecutor"); @@ -168,8 +177,9 @@ public NioClientSocketChannelFactory( this.bossExecutor = bossExecutor; this.workerPool = workerPool; + this.timer = timer; sink = new NioClientSocketPipelineSink( - bossExecutor, bossCount, workerPool); + bossExecutor, bossCount, workerPool, timer); } public SocketChannel newChannel(ChannelPipeline pipeline) { @@ -178,6 +188,7 @@ public SocketChannel newChannel(ChannelPipeline pipeline) { public void releaseExternalResources() { ExecutorUtil.terminate(bossExecutor); + timer.stop(); if (workerPool instanceof ExternalResourceReleasable) { ((ExternalResourceReleasable) workerPool).releaseExternalResources(); } diff --git a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java index 12f08f4ae5a..3d79ce51fa5 100644 --- a/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java +++ b/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.java @@ -32,6 +32,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -45,6 +46,10 @@ import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; +import org.jboss.netty.util.HashedWheelTimer; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.TimerTask; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.DeadLockProofWorker; @@ -64,11 +69,13 @@ class NioClientSocketPipelineSink extends AbstractNioChannelSink { private final WorkerPool<NioWorker> workerPool; + private final Timer timer; + NioClientSocketPipelineSink( - Executor bossExecutor, int bossCount, WorkerPool<NioWorker> workerPool) { + Executor bossExecutor, int bossCount, WorkerPool<NioWorker> workerPool, Timer timer) { this.bossExecutor = bossExecutor; - + this.timer = timer; bosses = new Boss[bossCount]; for (int i = 0; i < bosses.length; i ++) { bosses[i] = new Boss(i); @@ -179,6 +186,15 @@ private final class Boss implements Runnable { private final Object startStopLock = new Object(); private final Queue<Runnable> registerTaskQueue = new ConcurrentLinkedQueue<Runnable>(); private final int subId; + private final TimerTask wakeupTask = new TimerTask() { + public void run(Timeout timeout) throws Exception { + if (selector != null) { + if (wakenUp.compareAndSet(false, true)) { + selector.wakeup(); + } + } + } + }; Boss(int subId) { this.subId = subId; @@ -231,10 +247,17 @@ void register(NioClientSocketChannel channel) { boolean offered = registerTaskQueue.offer(registerTask); assert offered; } - + int timeout = channel.getConfig().getConnectTimeoutMillis(); + if (timeout > 0) { + if (!channel.isConnected()) { + channel.timoutTimer = timer.newTimeout(wakeupTask, + timeout, TimeUnit.MILLISECONDS); + } + } if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } + } public void run() { @@ -339,10 +362,8 @@ public void run() { // Handle connection timeout every 10 milliseconds approximately. long currentTimeNanos = System.nanoTime(); - if (currentTimeNanos - lastConnectTimeoutCheckTimeNanos >= 10 * 1000000L) { - lastConnectTimeoutCheckTimeNanos = currentTimeNanos; - processConnectTimeout(selector.keys(), currentTimeNanos); - } + lastConnectTimeoutCheckTimeNanos = currentTimeNanos; + processConnectTimeout(selector.keys(), currentTimeNanos); // Exit the loop when there's nothing to handle. // The shutdown flag is used to delay the shutdown of this @@ -471,6 +492,9 @@ private void connect(SelectionKey k) throws IOException { NioClientSocketChannel ch = (NioClientSocketChannel) k.attachment(); if (ch.channel.finishConnect()) { k.cancel(); + if (ch.timoutTimer != null) { + ch.timoutTimer.cancel(); + } ch.worker.register(ch, ch.connectFuture); } } diff --git a/src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java b/src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java index a263f9e4b28..c2889e92c69 100644 --- a/src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java +++ b/src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java @@ -29,7 +29,7 @@ final class SelectorUtil { InternalLoggerFactory.getInstance(SelectorUtil.class); static final int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() * 2; - static final long DEFAULT_SELECT_TIMEOUT = 10; + static final long DEFAULT_SELECT_TIMEOUT = 500; static final long SELECT_TIMEOUT = SystemPropertyUtil.getLong("org.jboss.netty.selectTimeout", DEFAULT_SELECT_TIMEOUT); static final long SELECT_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(SELECT_TIMEOUT);
null
test
train
2012-09-14T14:00:16
"2012-09-14T22:27:03Z"
gauravsri
val
netty/netty/620_621
netty/netty
netty/netty/620
netty/netty/621
[ "timestamp(timedelta=923.0, similarity=0.8640943361991529)", "keyword_pr_to_issue" ]
a7d205075b59b0fd6eb37dbc47228881ed1bdb4e
16d73e247e4030d408892b40334ebb65e7e82dd1
[ "Thanks for the detailed analysis and also for the pull-request.. We love contributions :)\n\nI merged your patch in and it will be part of 3.5.8.Final\n" ]
[]
"2012-09-21T12:59:57Z"
[]
pipelining + suspended ChunkedInput triggers StackOverflowError in ChunkedWriteHandler.flush()
We encountered an issue with ChunkedWriteHandler (netty version 3.5.7). We get StackOverflowError in following scenario: - ChunkWriteHandler.queue is not empty - ChunkedWriteHandler.currentEvent is not null and it stores ChunkedInput as message - chunkedInput stored in currentEvent is in suspended mode (nextChunk returns null but isEndOfInput returns false). In such case break from while loop in line 248 is executed. But then immediately after that flush() is called again recursively in line 301, because condition in line 300 evaluates to true. If chunkedInput is in suspended mode long enough we get StackOverFlowException. As a fix I moved suspend variable above while loop and modified condition in line 300 to: ``` if (acquired && (!channel.isConnected() || channel.isWritable() && (!queue.isEmpty() && !suspend))) { ``` I am not exactly sure if it does not break something but it seems to fix an issue.
[ "src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java" ]
[ "src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java b/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java index 0cb6d4ef55c..e06c45b4608 100644 --- a/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java +++ b/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java @@ -186,6 +186,7 @@ private void discard(ChannelHandlerContext ctx, boolean fireNow) { private void flush(ChannelHandlerContext ctx, boolean fireNow) throws Exception { boolean acquired = false; final Channel channel = ctx.getChannel(); + boolean suspend = false; // use CAS to see if the have flush already running, if so we don't need to take futher actions if (acquired = flush.compareAndSet(false, true)) { @@ -216,7 +217,6 @@ private void flush(ChannelHandlerContext ctx, boolean fireNow) throws Exception final ChunkedInput chunks = (ChunkedInput) m; Object chunk; boolean endOfInput; - boolean suspend; try { chunk = chunks.nextChunk(); endOfInput = chunks.isEndOfInput(); @@ -297,7 +297,7 @@ public void operationComplete(ChannelFuture future) throws Exception { } - if (acquired && (!channel.isConnected() || channel.isWritable() && !queue.isEmpty())) { + if (acquired && (!channel.isConnected() || channel.isWritable() && !queue.isEmpty() && !suspend)) { flush(ctx, fireNow); } }
null
train
train
2012-09-19T21:22:36
"2012-09-21T12:43:22Z"
losipiuk
val
netty/netty/702_703
netty/netty
netty/netty/702
netty/netty/703
[ "timestamp(timedelta=40.0, similarity=0.9563708796915518)" ]
d9090ecb1bb884fd1cd856b985cfda925537cfb0
8b50af9163506e36bf4e9a8cbfade9b06ecfe93c
[ "Go ahead!\n\nSent from my iPhone. Excuse any typos....\n\nAm 02.11.2012 um 02:21 schrieb Jeff Pinner [email protected]:\n\n> According to the spec method should be case sensitive:\n> \n> http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1\n> \n> but the case is ignored in HttpMethod.java:\n> \n> name = name.trim().toUpperCase();\n> \n> If there are no objections, I'd like to drop the toUpperCase() in both 3.x and 4.0 in order to comply with the spec.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Both pull request merged... Thanks!\n" ]
[]
"2012-11-02T05:54:14Z"
[]
HTTP method should be case sensitive
According to the spec method should be case sensitive: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 but the case is ignored in HttpMethod.java: name = name.trim().toUpperCase(); If there are no objections, I'd like to drop the toUpperCase() in both 3.x and 4.0 in order to comply with the spec.
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java" ]
[ "src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java b/src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java index d8cf627d558..7c8c3b96de2 100644 --- a/src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java +++ b/src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java @@ -109,7 +109,7 @@ public static HttpMethod valueOf(String name) { throw new NullPointerException("name"); } - name = name.trim().toUpperCase(); + name = name.trim(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); } @@ -136,7 +136,7 @@ public HttpMethod(String name) { throw new NullPointerException("name"); } - name = name.trim().toUpperCase(); + name = name.trim(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); }
null
test
train
2012-10-30T08:49:11
"2012-11-02T01:21:41Z"
jpinner
val
netty/netty/702_704
netty/netty
netty/netty/702
netty/netty/704
[ "timestamp(timedelta=89.0, similarity=0.9563708796915518)" ]
a9814fbf9330d8f2e2dbdd570045876841e903d3
9529f66540fa1380c098b50b01a3a035a1573cbb
[ "Go ahead!\n\nSent from my iPhone. Excuse any typos....\n\nAm 02.11.2012 um 02:21 schrieb Jeff Pinner [email protected]:\n\n> According to the spec method should be case sensitive:\n> \n> http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1\n> \n> but the case is ignored in HttpMethod.java:\n> \n> name = name.trim().toUpperCase();\n> \n> If there are no objections, I'd like to drop the toUpperCase() in both 3.x and 4.0 in order to comply with the spec.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Both pull request merged... Thanks!\n" ]
[]
"2012-11-02T05:55:42Z"
[]
HTTP method should be case sensitive
According to the spec method should be case sensitive: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 but the case is ignored in HttpMethod.java: name = name.trim().toUpperCase(); If there are no objections, I'd like to drop the toUpperCase() in both 3.x and 4.0 in order to comply with the spec.
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java index 6a97242a566..166df645c49 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java @@ -109,7 +109,7 @@ public static HttpMethod valueOf(String name) { throw new NullPointerException("name"); } - name = name.trim().toUpperCase(); + name = name.trim(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); } @@ -136,7 +136,7 @@ public HttpMethod(String name) { throw new NullPointerException("name"); } - name = name.trim().toUpperCase(); + name = name.trim(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); }
null
val
train
2012-10-30T13:04:27
"2012-11-02T01:21:41Z"
jpinner
val
netty/netty/672_732
netty/netty
netty/netty/672
netty/netty/732
[ "timestamp(timedelta=23.0, similarity=0.891991349326418)" ]
2d5028bfd6872f551bf33b9fba9b0dd416c0dd8f
0773786b8a03c9aac8a0f9a98058ad16667a0769
[ "Sounds good.. We just need to make it safe to ensure the other does not mess-up something once we use pooled buffers.\n", "Hi, all. I'm still learning the Netty internals and would appreciate some opinions on my attempted solution to this issue:\n1. What should the behaviour be when replacing with a null value? My implementation throws an NPE. This might be related to question 2 if we assume a null replacement should be treated as empty.\n2. How should pending bytes in the old buffer be handled when the new buffer does not have enough space to store them? One idea is to create a composite buffer. I have not chosen how to handle this, other than to let the IndexOutOfBoundsException happen when I attempt a write from the old to new buffer. Note that when I transfer the data, I let the reader index advance from the old buffer.\n3. After transferring the bytes, should discardReadBytes() be called on the old buffer?\n4. Should the replacement operation be executed on the event loop? My implementation ensures this.\n", "I'm testing the following decision: A null parameter wraps the old buffer in a read-only buffer. The reason: we want to drain whatever's left and then shut down the buffer. i.e. 'null' means 'shut down'.\n", "My thoughts:\n\n1) I think throwing a NPE is preferable than accepting null as a value. If a user wants to replace with an empty buffer they could always use Unpooled.EMPTY_BUFFER.\n\n2) In order to avoid making the \"wrong decision\" for any particular use case, we could force the user to choose what to do with any unread bytes in the buffer. They could always drain into a new buffer before replacement, or handle them in whatever way is appropriate after returning the old buffer. This would allow users to do things like limit the capacity of the buffer (for say a length delimited frame decoder) then swap the buffer when it is full without having to have \"read\" the bytes first or worry that they would be transferred to the replacement buffer.\n\n3) If you don't transfer the bytes then nothing should be done on any buffer other than to swap the pointers.\n\n4) Yes -- it should.\n", "+1 to everything that @jpinner said\n", "Would an exception be appropriate, then, for the case where a user is trying to replace the buffer and there are still readable bytes?\n", "The operation could return the old buffer instance so that the user can append/prepend its content to the new buffer.\n", "this makes sense as it \"may\" be ok to replace the buffer even if it still has data left to read... The user may want to do exactly that \n", "Well, the implementation has just become a lot simpler...\n", "Being new to Netty development, where can I paste my git diff for this implementation to have it reviewed and discussed?\n", "The best would be to \"fork\" netty, commit and push your changes and then issue a pull-request..\n\nAm 12.11.2012 um 20:44 schrieb ssilverman [email protected]:\n\n> Being new to Netty development, where can I paste my git diff for this implementation to have it reviewed and discussed?\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Done.\n", "merged in.. See #732\n" ]
[ "please add \"newInboundMsgBuf\" as message of the NPE.\n", "please add \"newOutboundMsgBuf\" as message of the NPE.\n", "Just in case it's unclear, it should be:\n\n```\nthrow new NullPointerException(\"newInboundMsgBuf\");\n```\n\nto be consistent with all NPE messages in Netty.\n" ]
"2012-11-13T00:04:13Z"
[ "feature" ]
Allow replacing an inbound or outbound buffer of a handler.
Previous Netty 4 alphas did not allow replacing a handler's inbound/outbound buffer once it's created - it's final. Is there any reason to keep it final though? Just like a user can replace a decoder on the fly using `ByteToMessageDecoder.replace(..)`, what if a user can replace a handler's inbound (or outbound) buffer very easily? It will give a user an alternative way to implement a decoder (or encoder). For example, a `FixedLengthFrameDecoder` could prepare two inbound buffers and simply wait until the first inbound buffer is full, and replace the first buffer with the second buffer to continue reading the second message. There is no need to copy the frame from the buffer at all.
[ "transport/src/main/java/io/netty/channel/ChannelHandlerContext.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java", "transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java", "transport/src/main/java/io/netty/channel/DefaultChannelPipelineModificationTask.java" ]
[ "transport/src/main/java/io/netty/channel/ChannelHandlerContext.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java", "transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/ChannelHandlerContext.java b/transport/src/main/java/io/netty/channel/ChannelHandlerContext.java index 86172fb6e8c..a095f877c3b 100755 --- a/transport/src/main/java/io/netty/channel/ChannelHandlerContext.java +++ b/transport/src/main/java/io/netty/channel/ChannelHandlerContext.java @@ -212,6 +212,46 @@ public interface ChannelHandlerContext */ <T> MessageBuf<T> outboundMessageBuffer(); + /** + * Replaces the inbound byte buffer with the given buffer. This returns the + * old buffer, so any readable bytes can be handled appropriately by the caller. + * + * @param newInboundByteBuf the new inbound byte buffer + * @return the old buffer. + * @throws NullPointerException if the argument is {@code null}. + */ + ByteBuf replaceInboundByteBuffer(ByteBuf newInboundByteBuf); + + /** + * Replaces the inbound message buffer with the given buffer. This returns the + * old buffer, so any pending messages can be handled appropriately by the caller. + * + * @param newInboundMsgBuf the new inbound message buffer + * @return the old buffer. + * @throws NullPointerException if the argument is {@code null}. + */ + <T> MessageBuf<T> replaceInboundMessageBuffer(MessageBuf<T> newInboundMsgBuf); + + /** + * Replaces the outbound byte buffer with the given buffer. This returns the + * old buffer, so any readable bytes can be handled appropriately by the caller. + * + * @param newOutboundByteBuf the new inbound byte buffer + * @return the old buffer. + * @throws NullPointerException if the argument is {@code null}. + */ + ByteBuf replaceOutboundByteBuffer(ByteBuf newOutboundByteBuf); + + /** + * Replaces the outbound message buffer with the given buffer. This returns the + * old buffer, so any pending messages can be handled appropriately by the caller. + * + * @param newOutboundMsgBuf the new inbound message buffer + * @return the old buffer. + * @throws NullPointerException if the argument is {@code null}. + */ + <T> MessageBuf<T> replaceOutboundMessageBuffer(MessageBuf<T> newOutboundMsgBuf); + /** * Return {@code true} if the next {@link ChannelHandlerContext} has a {@link ByteBuf} for handling * inbound data. diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java index 4decd85b974..329a7be192f 100755 --- a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java @@ -27,7 +27,10 @@ import java.util.EnumSet; import java.util.Queue; import java.util.Set; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -48,10 +51,10 @@ final class DefaultChannelHandlerContext extends DefaultAttributeMap implements final int directions; private final ChannelHandler handler; - final MessageBuf<Object> inMsgBuf; - final ByteBuf inByteBuf; - final MessageBuf<Object> outMsgBuf; - final ByteBuf outByteBuf; + MessageBuf<Object> inMsgBuf; + ByteBuf inByteBuf; + MessageBuf<Object> outMsgBuf; + ByteBuf outByteBuf; // When the two handlers run in a different thread and they are next to each other, // each other's buffers can be accessed at the same time resulting in a race condition. @@ -447,6 +450,222 @@ public <T> MessageBuf<T> outboundMessageBuffer() { return (MessageBuf<T>) outMsgBuf; } + /** + * Executes a task on the event loop and waits for it to finish. If the task is interrupted, then the + * current thread will be interrupted and this will return {@code null}. It is expected that the task + * performs any appropriate locking. + * <p> + * If the {@link Callable#call()} call throws a {@link Throwable}, but it is not an instance of + * {@link Error}, {@link RuntimeException}, or {@link Exception}, then it is wrapped inside an + * {@link AssertionError} and that is thrown instead.</p> + * + * @param c execute this callable and return its value + * @param <T> the return value type + * @return the task's return value, or {@code null} if the task was interrupted. + * @see Callable#call() + * @see Future#get() + * @throws Error if the task threw this. + * @throws RuntimeException if the task threw this. + * @throws Exception if the task threw this. + * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of + * {@link Throwable}. + */ + <T> T executeOnEventLoop(Callable<T> c) throws Exception { + return getFromFuture(executor().submit(c)); + } + + /** + * Executes a task on the event loop and waits for it to finish. If the task is interrupted, then the + * current thread will be interrupted. It is expected that the task performs any appropriate locking. + * <p> + * If the {@link Runnable#run()} call throws a {@link Throwable}, but it is not an instance of + * {@link Error} or {@link RuntimeException}, then it is wrapped inside a + * {@link ChannelPipelineException} and that is thrown instead.</p> + * + * @param r execute this runnable + * @see Runnable#run() + * @see Future#get() + * @throws Error if the task threw this. + * @throws RuntimeException if the task threw this. + * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of + * {@link Throwable}. + */ + void executeOnEventLoop(Runnable r) { + waitForFuture(executor().submit(r)); + } + + /** + * Waits for a future to finish and gets the result. If the task is interrupted, then the current thread + * will be interrupted and this will return {@code null}. It is expected that the task performs any + * appropriate locking. + * <p> + * If the internal call throws a {@link Throwable}, but it is not an instance of {@link Error}, + * {@link RuntimeException}, or {@link Exception}, then it is wrapped inside an {@link AssertionError} + * and that is thrown instead.</p> + * + * @param future wait for this future + * @param <T> the return value type + * @return the task's return value, or {@code null} if the task was interrupted. + * @see Future#get() + * @throws Error if the task threw this. + * @throws RuntimeException if the task threw this. + * @throws Exception if the task threw this. + * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of + * {@link Throwable}. + */ + <T> T getFromFuture(Future<T> future) throws Exception { + try { + return future.get(); + } catch (ExecutionException ex) { + // In the arbitrary case, we can throw Error, RuntimeException, and Exception + + Throwable t = ex.getCause(); + if (t instanceof Error) { throw (Error) t; } + if (t instanceof RuntimeException) { throw (RuntimeException) t; } + if (t instanceof Exception) { throw (Exception) t; } + throw new ChannelPipelineException(t); + } catch (InterruptedException ex) { + // Interrupt the calling thread (note that this method is not called from the event loop) + + Thread.currentThread().interrupt(); + return null; + } + } + + /** + * Waits for a future to finish. If the task is interrupted, then the current thread will be interrupted. + * It is expected that the task performs any appropriate locking. + * <p> + * If the internal call throws a {@link Throwable}, but it is not an instance of {@link Error} or + * {@link RuntimeException}, then it is wrapped inside a {@link ChannelPipelineException} and that is + * thrown instead.</p> + * + * @param future wait for this future + * @see Future#get() + * @throws Error if the task threw this. + * @throws RuntimeException if the task threw this. + * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of + * {@link Throwable}. + */ + void waitForFuture(Future future) { + try { + future.get(); + } catch (ExecutionException ex) { + // In the arbitrary case, we can throw Error, RuntimeException, and Exception + + Throwable t = ex.getCause(); + if (t instanceof Error) { throw (Error) t; } + if (t instanceof RuntimeException) { throw (RuntimeException) t; } + throw new ChannelPipelineException(t); + } catch (InterruptedException ex) { + // Interrupt the calling thread (note that this method is not called from the event loop) + + Thread.currentThread().interrupt(); + } + } + + @Override + public ByteBuf replaceInboundByteBuffer(final ByteBuf newInboundByteBuf) { + if (newInboundByteBuf == null) { + throw new NullPointerException("newInboundByteBuf"); + } + + if (!executor().inEventLoop()) { + try { + return executeOnEventLoop(new Callable<ByteBuf>() { + @Override + public ByteBuf call() { + return replaceInboundByteBuffer(newInboundByteBuf); + } + }); + } catch (Exception ex) { + // Ignore because call() does not throw an Exception + } + } + + ByteBuf currentInboundByteBuf = inboundByteBuffer(); + + this.inByteBuf = newInboundByteBuf; + return currentInboundByteBuf; + } + + @Override + @SuppressWarnings("unchecked") + public <T> MessageBuf<T> replaceInboundMessageBuffer(final MessageBuf<T> newInboundMsgBuf) { + if (newInboundMsgBuf == null) { + throw new NullPointerException("newInboundMsgBuf"); + } + + if (!executor().inEventLoop()) { + try { + return executeOnEventLoop(new Callable<MessageBuf<T>>() { + @Override + public MessageBuf<T> call() { + return replaceInboundMessageBuffer(newInboundMsgBuf); + } + }); + } catch (Exception ex) { + // Ignore because call() does not throw an Exception + } + } + + MessageBuf<T> currentInboundMsgBuf = inboundMessageBuffer(); + + this.inMsgBuf = (MessageBuf<Object>) newInboundMsgBuf; + return currentInboundMsgBuf; + } + + @Override + public ByteBuf replaceOutboundByteBuffer(final ByteBuf newOutboundByteBuf) { + if (newOutboundByteBuf == null) { + throw new NullPointerException("newOutboundByteBuf"); + } + + if (!executor().inEventLoop()) { + try { + return executeOnEventLoop(new Callable<ByteBuf>() { + @Override + public ByteBuf call() { + return replaceOutboundByteBuffer(newOutboundByteBuf); + } + }); + } catch (Exception ex) { + // Ignore because call() does not throw an Exception + } + } + + ByteBuf currentOutboundByteBuf = outboundByteBuffer(); + + this.outByteBuf = newOutboundByteBuf; + return currentOutboundByteBuf; + } + + @Override + @SuppressWarnings("unchecked") + public <T> MessageBuf<T> replaceOutboundMessageBuffer(final MessageBuf<T> newOutboundMsgBuf) { + if (newOutboundMsgBuf == null) { + throw new NullPointerException("newOutboundMsgBuf"); + } + + if (!executor().inEventLoop()) { + try { + return executeOnEventLoop(new Callable<MessageBuf<T>>() { + @Override + public MessageBuf<T> call() { + return replaceOutboundMessageBuffer(newOutboundMsgBuf); + } + }); + } catch (Exception ex) { + // Ignore because call() does not throw an Exception + } + } + + MessageBuf<T> currentOutboundMsgBuf = outboundMessageBuffer(); + + this.outMsgBuf = (MessageBuf<Object>) newOutboundMsgBuf; + return currentOutboundMsgBuf; + } + @Override public boolean hasNextInboundByteBuffer() { DefaultChannelHandlerContext ctx = next; diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java index eb2c980b5f9..bdda8d8b8f3 100755 --- a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java @@ -82,44 +82,35 @@ public ChannelPipeline addFirst(String name, ChannelHandler handler) { } @Override - public ChannelPipeline addFirst(EventExecutorGroup group, final String name, final ChannelHandler handler) { - try { - Future<Throwable> future; + public ChannelPipeline addFirst(EventExecutorGroup group, final String name, ChannelHandler handler) { + final DefaultChannelHandlerContext nextCtx; + final DefaultChannelHandlerContext newCtx; - synchronized (this) { - checkDuplicateName(name); - final DefaultChannelHandlerContext nextCtx = head.next; - final DefaultChannelHandlerContext newCtx = - new DefaultChannelHandlerContext(this, group, head, nextCtx, name, handler); + synchronized (this) { + checkDuplicateName(name); + nextCtx = head.next; + newCtx = new DefaultChannelHandlerContext(this, group, head, nextCtx, name, handler); - if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { - addFirst0(name, nextCtx, newCtx); - return this; - } - future = newCtx.executor().submit(new DefaultChannelPipelineModificationTask(this) { - @Override - void doCall() { + if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { + addFirst0(name, nextCtx, newCtx); + return this; + } + } + + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + newCtx.executeOnEventLoop(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { checkDuplicateName(name); addFirst0(name, nextCtx, newCtx); } - }); - } - // Call Future.get() outside of the synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; - } - return this; - - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); - } + } + }); + return this; } private void addFirst0( @@ -141,46 +132,36 @@ public ChannelPipeline addLast(String name, ChannelHandler handler) { } @Override - public ChannelPipeline addLast(EventExecutorGroup group, final String name, final ChannelHandler handler) { - try { - Future<Throwable> future; + public ChannelPipeline addLast(EventExecutorGroup group, final String name, ChannelHandler handler) { + final DefaultChannelHandlerContext oldTail; + final DefaultChannelHandlerContext newTail; - synchronized (this) { - checkDuplicateName(name); + synchronized (this) { + checkDuplicateName(name); - final DefaultChannelHandlerContext oldTail = tail; - final DefaultChannelHandlerContext newTail = - new DefaultChannelHandlerContext(this, group, oldTail, null, name, handler); + oldTail = tail; + newTail = new DefaultChannelHandlerContext(this, group, oldTail, null, name, handler); - if (!newTail.channel().isRegistered() || newTail.executor().inEventLoop()) { - addLast0(name, oldTail, newTail); - return this; - } else { - future = newTail.executor().submit(new DefaultChannelPipelineModificationTask(this) { - @Override - void doCall() { - checkDuplicateName(name); - addLast0(name, oldTail, newTail); - } - }); - } + if (!newTail.channel().isRegistered() || newTail.executor().inEventLoop()) { + addLast0(name, oldTail, newTail); + return this; } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; - } - return this; - - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); } + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + newTail.executeOnEventLoop(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + checkDuplicateName(name); + addLast0(name, oldTail, newTail); + } + } + }); + + return this; } private void addLast0( @@ -201,46 +182,35 @@ public ChannelPipeline addBefore(String baseName, String name, ChannelHandler ha @Override public ChannelPipeline addBefore( - EventExecutorGroup group, String baseName, final String name, final ChannelHandler handler) { - try { - Future<Throwable> future; + EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { + final DefaultChannelHandlerContext ctx; + final DefaultChannelHandlerContext newCtx; - synchronized (this) { - final DefaultChannelHandlerContext ctx = getContextOrDie(baseName); - checkDuplicateName(name); - final DefaultChannelHandlerContext newCtx = - new DefaultChannelHandlerContext(this, group, ctx.prev, ctx, name, handler); + synchronized (this) { + ctx = getContextOrDie(baseName); + checkDuplicateName(name); + newCtx = new DefaultChannelHandlerContext(this, group, ctx.prev, ctx, name, handler); - if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { - addBefore0(name, ctx, newCtx); - return this; - } else { - future = newCtx.executor().submit(new DefaultChannelPipelineModificationTask(this) { - @Override - void doCall() { - checkDuplicateName(name); - addBefore0(name, ctx, newCtx); - } - }); - } + if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { + addBefore0(name, ctx, newCtx); + return this; } + } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; - } - return this; + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); - } + newCtx.executeOnEventLoop(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + checkDuplicateName(name); + addBefore0(name, ctx, newCtx); + } + } + }); + return this; } private void addBefore0(final String name, DefaultChannelHandlerContext ctx, DefaultChannelHandlerContext newCtx) { @@ -260,49 +230,38 @@ public ChannelPipeline addAfter(String baseName, String name, ChannelHandler han @Override public ChannelPipeline addAfter( - EventExecutorGroup group, String baseName, final String name, final ChannelHandler handler) { - - try { - Future<Throwable> future; - - synchronized (this) { - final DefaultChannelHandlerContext ctx = getContextOrDie(baseName); - if (ctx == tail) { - return addLast(name, handler); - } - checkDuplicateName(name); - final DefaultChannelHandlerContext newCtx = - new DefaultChannelHandlerContext(this, group, ctx, ctx.next, name, handler); + EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { + final DefaultChannelHandlerContext ctx; + final DefaultChannelHandlerContext newCtx; - if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { - addAfter0(name, ctx, newCtx); - return this; - } else { - future = newCtx.executor().submit(new DefaultChannelPipelineModificationTask(this) { - @Override - void doCall() { - checkDuplicateName(name); - addAfter0(name, ctx, newCtx); - } - }); - } - } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; + synchronized (this) { + ctx = getContextOrDie(baseName); + if (ctx == tail) { + return addLast(name, handler); } - return this; + checkDuplicateName(name); + newCtx = new DefaultChannelHandlerContext(this, group, ctx, ctx.next, name, handler); - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); + if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { + addAfter0(name, ctx, newCtx); + return this; + } } + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + newCtx.executeOnEventLoop(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + checkDuplicateName(name); + addAfter0(name, ctx, newCtx); + } + } + }); + + return this; } private void addAfter0(final String name, DefaultChannelHandlerContext ctx, DefaultChannelHandlerContext newCtx) { @@ -394,65 +353,59 @@ public <T extends ChannelHandler> T remove(Class<T> handlerType) { } private DefaultChannelHandlerContext remove(final DefaultChannelHandlerContext ctx) { - try { - DefaultChannelHandlerContext context; - Future<Throwable> future; - synchronized (this) { + DefaultChannelHandlerContext context; + Future future; + + synchronized (this) { + if (head == tail) { + return null; + } else if (ctx == head) { + throw new Error(); // Should never happen. + } else if (ctx == tail) { if (head == tail) { - return null; - } else if (ctx == head) { - throw new Error(); // Should never happen. - } else if (ctx == tail) { - if (head == tail) { - throw new NoSuchElementException(); - } + throw new NoSuchElementException(); + } - final DefaultChannelHandlerContext oldTail = tail; - if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { - removeLast0(oldTail); - return oldTail; - } else { - future = oldTail.executor().submit(new DefaultChannelPipelineModificationTask(this) { + final DefaultChannelHandlerContext oldTail = tail; + if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { + removeLast0(oldTail); + return oldTail; + } else { + future = oldTail.executor().submit(new Runnable() { @Override - void doCall() { - removeLast0(oldTail); + public void run() { + synchronized (DefaultChannelPipeline.this) { + removeLast0(oldTail); + } } }); - context = oldTail; - } + context = oldTail; + } + } else { + if (!ctx.channel().isRegistered() || ctx.executor().inEventLoop()) { + remove0(ctx); + return ctx; } else { - if (!ctx.channel().isRegistered() || ctx.executor().inEventLoop()) { - remove0(ctx); - return ctx; - } else { - future = ctx.executor().submit(new DefaultChannelPipelineModificationTask(this) { + future = ctx.executor().submit(new Runnable() { @Override - void doCall() { - remove0(ctx); + public void run() { + synchronized (DefaultChannelPipeline.this) { + remove0(ctx); + } } }); - context = ctx; - } + context = ctx; } } + } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; - } + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock - return context; - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); - } + context.waitForFuture(future); + return context; } private void remove0(DefaultChannelHandlerContext ctx) { @@ -480,43 +433,32 @@ public ChannelHandler removeFirst() { @Override public ChannelHandler removeLast() { - try { - Future<Throwable> future; - final DefaultChannelHandlerContext oldTail; - synchronized (this) { - if (head == tail) { - throw new NoSuchElementException(); - } - oldTail = tail; - if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { - removeLast0(oldTail); - return oldTail.handler(); - } else { - future = oldTail.executor().submit(new DefaultChannelPipelineModificationTask(this) { - @Override - void doCall() { - removeLast0(oldTail); - } - }); - } + final DefaultChannelHandlerContext oldTail; + + synchronized (this) { + if (head == tail) { + throw new NoSuchElementException(); } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; + oldTail = tail; + if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { + removeLast0(oldTail); + return oldTail.handler(); } - - return oldTail.handler(); - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); } + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + oldTail.executeOnEventLoop(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + removeLast0(oldTail); + } + } + }); + return oldTail.handler(); } private void removeLast0(DefaultChannelHandlerContext oldTail) { @@ -550,78 +492,76 @@ public <T extends ChannelHandler> T replace( } private ChannelHandler replace( - final DefaultChannelHandlerContext ctx, final String newName, final ChannelHandler newHandler) { - try { - Future<Throwable> future; - synchronized (this) { - if (ctx == head) { - throw new IllegalArgumentException(); - } else if (ctx == tail) { - if (head == tail) { - throw new NoSuchElementException(); - } - final DefaultChannelHandlerContext oldTail = tail; - final DefaultChannelHandlerContext newTail = - new DefaultChannelHandlerContext(this, null, oldTail, null, newName, newHandler); + final DefaultChannelHandlerContext ctx, final String newName, ChannelHandler newHandler) { + Future future; + DefaultChannelHandlerContext context; - if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { - removeLast0(oldTail); - checkDuplicateName(newName); - addLast0(newName, tail, newTail); - return ctx.handler(); + synchronized (this) { + if (ctx == head) { + throw new IllegalArgumentException(); + } else if (ctx == tail) { + if (head == tail) { + throw new NoSuchElementException(); + } + final DefaultChannelHandlerContext oldTail = tail; + final DefaultChannelHandlerContext newTail = + new DefaultChannelHandlerContext(this, null, oldTail, null, newName, newHandler); + + if (!oldTail.channel().isRegistered() || oldTail.executor().inEventLoop()) { + removeLast0(oldTail); + checkDuplicateName(newName); + addLast0(newName, tail, newTail); + return ctx.handler(); - } else { - future = oldTail.executor().submit(new DefaultChannelPipelineModificationTask(this) { + } else { + future = oldTail.executor().submit(new Runnable() { @Override - void doCall() { - removeLast0(oldTail); - checkDuplicateName(newName); - addLast0(newName, tail, newTail); + public void run() { + synchronized (DefaultChannelPipeline.this) { + removeLast0(oldTail); + checkDuplicateName(newName); + addLast0(newName, tail, newTail); + } } }); - } + context = oldTail; + } - } else { - boolean sameName = ctx.name().equals(newName); - if (!sameName) { - checkDuplicateName(newName); - } + } else { + boolean sameName = ctx.name().equals(newName); + if (!sameName) { + checkDuplicateName(newName); + } - DefaultChannelHandlerContext prev = ctx.prev; - DefaultChannelHandlerContext next = ctx.next; + DefaultChannelHandlerContext prev = ctx.prev; + DefaultChannelHandlerContext next = ctx.next; - final DefaultChannelHandlerContext newCtx = - new DefaultChannelHandlerContext(this, ctx.executor, prev, next, newName, newHandler); + final DefaultChannelHandlerContext newCtx = + new DefaultChannelHandlerContext(this, ctx.executor, prev, next, newName, newHandler); - if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { - replace0(ctx, newName, newCtx); - return ctx.handler(); - } else { - future = newCtx.executor().submit(new DefaultChannelPipelineModificationTask(this) { + if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { + replace0(ctx, newName, newCtx); + return ctx.handler(); + } else { + future = newCtx.executor().submit(new Runnable() { @Override - void doCall() { - replace0(ctx, newName, newCtx); + public void run() { + synchronized (DefaultChannelPipeline.this) { + replace0(ctx, newName, newCtx); + } } }); - } + context = newCtx; } } - // Call Future.get() outside of synchronized block to prevent dead-lock - Throwable result = future.get(); - if (result != null) { - // re-throw exception that was caught - throw result; - } + } - return ctx.handler(); + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock - } catch (RuntimeException e) { - throw e; - } catch (Error e) { - throw e; - } catch (Throwable t) { - throw new ChannelPipelineException(t); - } + context.waitForFuture(future); + + return ctx.handler(); } private void replace0(DefaultChannelHandlerContext ctx, String newName, DefaultChannelHandlerContext newCtx) { diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelPipelineModificationTask.java b/transport/src/main/java/io/netty/channel/DefaultChannelPipelineModificationTask.java deleted file mode 100644 index 7b6ce7d847e..00000000000 --- a/transport/src/main/java/io/netty/channel/DefaultChannelPipelineModificationTask.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package io.netty.channel; - -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -/** - * Custom {@link Callable} implementation which will catch all {@link Throwable} which happens - * during execution of {@link DefaultChannelPipelineModificationTask#doCall()} and return them in the - * {@link Future}. This allows to re-throw them later. - * - * It also handles the right synchronization of the {@link DefaultChannelPipelineModificationTask#doCall()} - * method. - * - * It was originally an inner class of {@link DefaultChannelPipeline}, but moved to a top level - * type to work around a compiler bug. - */ -abstract class DefaultChannelPipelineModificationTask implements Callable<Throwable> { - - private final ChannelPipeline lock; - - DefaultChannelPipelineModificationTask(ChannelPipeline lock) { - this.lock = lock; - } - - @Override - public Throwable call() { - try { - synchronized (lock) { - doCall(); - } - } catch (Throwable t) { - return t; - } - return null; - } - - /** - * Execute the modification - */ - abstract void doCall(); - -}
null
val
train
2012-11-12T15:29:02
"2012-10-22T22:09:03Z"
trustin
val
netty/netty/722_802
netty/netty
netty/netty/722
netty/netty/802
[ "timestamp(timedelta=32.0, similarity=0.9166131880386778)" ]
2903b91e66c6e6615b7ba67c8c6ff286e392ad95
63cadb22eb22c94c5d7e8b792eeccba69881aacc
[ "@trustin @normanmaurer Want me to tackle this one?\n", "Go ahead!\n\nSent from my iPhone. Excuse any typos....\n\nAm 09.12.2012 um 05:00 schrieb \"Vibul Imtarnasan @vibuli\" [email protected]:\n\n> @trustin @normanmaurer Want me to tackle this one?\n> \n> —\n> Reply to this email directly or view it on GitHub.\n" ]
[ "`return` is unnecessary.\n" ]
"2012-12-12T06:44:53Z"
[ "cleanup" ]
Make WebSocketClientHandshakerFactory a utility class
WebSocketClientHandshakerFactory does not need instantiation actually. Let's make the methods static and make it a utility class.
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java index baef4c6f5e1..06d768e5e77 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java @@ -23,7 +23,13 @@ /** * Instances the appropriate handshake class to use for clients */ -public class WebSocketClientHandshakerFactory { +public final class WebSocketClientHandshakerFactory { + + /** + * Private constructor so this static class cannot be instanced. + */ + private WebSocketClientHandshakerFactory() { + } /** * Creates a new handshaker. @@ -40,7 +46,7 @@ public class WebSocketClientHandshakerFactory { * @param customHeaders * Custom HTTP headers to send during the handshake */ - public WebSocketClientHandshaker newHandshaker( + public static WebSocketClientHandshaker newHandshaker( URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, Map<String, String> customHeaders) { return newHandshaker(webSocketURL, version, subprotocol, allowExtensions, customHeaders, 65536); @@ -64,7 +70,7 @@ public WebSocketClientHandshaker newHandshaker( * Maximum allowable frame payload length. Setting this value to your application's * requirement may reduce denial of service attacks using long data frames. */ - public WebSocketClientHandshaker newHandshaker( + public static WebSocketClientHandshaker newHandshaker( URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, Map<String, String> customHeaders, int maxFramePayloadLength) { if (version == V13) { diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java index 0454f2a1c24..c7c101f697c 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java @@ -79,7 +79,7 @@ public void run() throws Exception { // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler( - new WebSocketClientHandshakerFactory().newHandshaker( + WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, customHeaders)); b.group(new NioEventLoopGroup())
null
test
train
2012-12-10T20:12:59
"2012-11-09T22:50:42Z"
trustin
val
netty/netty/751_821
netty/netty
netty/netty/751
netty/netty/821
[ "timestamp(timedelta=1358.0, similarity=0.8458491573177721)" ]
ba3c795fdfbc03d5422107051000f218047f3d5b
a2afa3ea305d322c4f53422903f66282b6b579dd
[ "I think you will have to dig up the spec and compare. A change in web socket version typically means a change in the wire protocol so it may take a bit of work to support.\n\nHowever, which clients do u expect to use WebSocket 7? I'm not sure there are that many.\n\nFrom http://en.wikipedia.org/wiki/WebSocket#Browser_support, only FF6 supports it. \n", "I've passed about 95% of the SockJS protocol tests:\nhttps://github.com/sockjs/sockjs-protocol\n\nThere are only some minor tests left, so for completeness I want to add WebSocket 7 support to Xitrum or Netty.\n\nYou're right that FF6 is very old. But that's why SockJS exists. SockJS tries to support all browsers, even IE6!\n", "@ngocdaothanh @veebs If I remember right 07 is almost 100% identical to 08 so it should be easy. I think it only differs in the handshake.\n\n @ngocdaothanh feel free to implement it and issue a pull-req :)\n", "@ngocdaothanh can you give some \"details\" about how to run these tests ? I think I could add support for WebSocket 7 easily but would love to test it :)\n", "Oh thank you very much! You're my hero.\n\nYou use this server side project, which uses Xitrum 1.10 which uses Netty 3.5.11:\nhttps://github.com/ngocdaothanh/xitrum-sockjs-test\n\nStart the server on port 8081:\ngit clone git://github.com/ngocdaothanh/xitrum-sockjs-test.git\ncd xitrum-sockjs-test\nsbt/sbt run\n\nThen follow the instruction here to run the Python test client:\nhttps://github.com/sockjs/sockjs-protocol\n\nYou can specify only some specific tests to run:\n./venv/bin/python sockjs-protocol-0.3.3.py -v WebsocketHybi10\n./venv/bin/python sockjs-protocol-0.3.3.py -v WebsocketHixie76\n", "Was this resolved?\n", "nope… On my to-do-list, which keeps growing :/\n\nAm 13.12.2012 um 17:14 schrieb Trustin Lee [email protected]:\n\n> Was this resolved?\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Sent pull request https://github.com/netty/netty/pull/821\n\nPlease help test with SocksJS and let me know if it works.\n", "Thanks a lot!\nCan you add it to the 3.5 branch too?\nMy test is using the 3.5 stable branch.\n", "Can some one test on the master first before we port back? Thanks\n", "@ngocdaothanh can you join the #netty channel on irc.freenode.org. I think I'm to dumb to get the test running :/\n", "OK. I've joined the chat room.\n", "@ngocdaothanh the backported code is here: https://github.com/netty/netty/tree/websocket07\n\nIf you want to include it in 3.6.0.Final you need to hurry up as I want to cut it at latest tomorrow morning. :)\n", "Thanks a lot.\nAll the tests related to WebSocket 07 now passed.\nLooking forward to Netty 3.6.0.Final!\n" ]
[ "I think it would make \"more sense\" to let 08 extend from 07. At least it sounds more logic, even if it will not matter :)\n", "I think it would make \"more sense\" to let 08 extend from 07. At least it sounds more logic, even if it will not matter :)\n" ]
"2012-12-14T23:02:50Z"
[ "feature" ]
Support WebSocket 07
After reading the doc and doing some experiment, as I understand Netty currently only support WebSocket version 00, 08, and 13: http://static.netty.io/3.5/api/org/jboss/netty/handler/codec/http/websocketx/package-summary.html I am adding SockJS feature to my Xitrum web framework which is based on Netty. But SockJS requires that the server side supports WebSocket 07: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.3.html#section-71 What should I do to add WebSocket 07 to Netty?
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameDecoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameDecoder.java new file mode 100644 index 00000000000..55ef8d941bc --- /dev/null +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameDecoder.java @@ -0,0 +1,76 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +// (BSD License: http://www.opensource.org/licenses/bsd-license) +// +// Copyright (c) 2011, Joe Walnes and contributors +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or +// without modification, are permitted provided that the +// following conditions are met: +// +// * Redistributions of source code must retain the above +// copyright notice, this list of conditions and the +// following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the +// following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// * Neither the name of the Webbit nor the names of +// its contributors may be used to endorse or promote products +// derived from this software without specific prior written +// permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +package io.netty.handler.codec.http.websocketx; + +/** + * Decodes a web socket frame from wire protocol version 7 format. V7 is essentially the same as V8. + */ +public class WebSocket07FrameDecoder extends WebSocket08FrameDecoder { + + /** + * Constructor + * + * @param maskedPayload + * Web socket servers must set this to true processed incoming masked payload. Client implementations + * must set this to false. + * @param allowExtensions + * Flag to allow reserved extension bits to be used or not + * @param maxFramePayloadLength + * Maximum length of a frame's payload. Setting this to an appropriate value for you application + * helps check for denial of services attacks. + */ + public WebSocket07FrameDecoder(boolean maskedPayload, boolean allowExtensions, int maxFramePayloadLength) { + super(maskedPayload, allowExtensions, maxFramePayloadLength); + } +} diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameEncoder.java new file mode 100644 index 00000000000..b74d0130ac3 --- /dev/null +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocket07FrameEncoder.java @@ -0,0 +1,73 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +// (BSD License: http://www.opensource.org/licenses/bsd-license) +// +// Copyright (c) 2011, Joe Walnes and contributors +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or +// without modification, are permitted provided that the +// following conditions are met: +// +// * Redistributions of source code must retain the above +// copyright notice, this list of conditions and the +// following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the +// following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// * Neither the name of the Webbit nor the names of +// its contributors may be used to endorse or promote products +// derived from this software without specific prior written +// permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +package io.netty.handler.codec.http.websocketx; + +/** + * <p> + * Encodes a web socket frame into wire protocol version 7 format. V7 is essentially the same as V8. + * </p> + */ +public class WebSocket07FrameEncoder extends WebSocket08FrameEncoder { + + /** + * Constructor + * + * @param maskPayload + * Web socket clients must set this to true to mask payload. Server implementations must set this to + * false. + */ + public WebSocket07FrameEncoder(boolean maskPayload) { + super(maskPayload); + } +} diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java new file mode 100644 index 00000000000..46512cdda17 --- /dev/null +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java @@ -0,0 +1,230 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.http.websocketx; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.http.DefaultHttpRequest; +import io.netty.handler.codec.http.HttpHeaders.Names; +import io.netty.handler.codec.http.HttpHeaders.Values; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpRequestEncoder; +import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpResponseDecoder; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.logging.InternalLogger; +import io.netty.logging.InternalLoggerFactory; +import io.netty.util.CharsetUtil; + +import java.net.URI; +import java.util.Map; + +/** + * <p> + * Performs client side opening and closing handshakes for web socket specification version <a + * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07" >draft-ietf-hybi-thewebsocketprotocol- + * 10</a> + * </p> + */ +public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class); + + public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + + private String expectedChallengeResponseString; + + private final boolean allowExtensions; + + /** + * Creates a new instance. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + */ + public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol, + boolean allowExtensions, Map<String, String> customHeaders, int maxFramePayloadLength) { + super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength); + this.allowExtensions = allowExtensions; + } + + /** + * /** + * <p> + * Sends the opening request to the server: + * </p> + * + * <pre> + * GET /chat HTTP/1.1 + * Host: server.example.com + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== + * Sec-WebSocket-Origin: http://example.com + * Sec-WebSocket-Protocol: chat, superchat + * Sec-WebSocket-Version: 7 + * </pre> + * + * @param channel + * Channel into which we can write our request + */ + @Override + public ChannelFuture handshake(Channel channel, final ChannelFuture handshakeFuture) { + // Get path + URI wsURL = getWebSocketUrl(); + String path = wsURL.getPath(); + if (wsURL.getQuery() != null && !wsURL.getQuery().isEmpty()) { + path = wsURL.getPath() + '?' + wsURL.getQuery(); + } + + if (path == null || path.isEmpty()) { + path = "/"; + } + + // Get 16 bit nonce and base 64 encode it + byte[] nonce = WebSocketUtil.randomBytes(16); + String key = WebSocketUtil.base64(nonce); + + String acceptSeed = key + MAGIC_GUID; + byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII)); + expectedChallengeResponseString = WebSocketUtil.base64(sha1); + + if (logger.isDebugEnabled()) { + logger.debug(String.format("WS Version 07 Client Handshake key: %s. Expected response: %s.", key, + expectedChallengeResponseString)); + } + + // Format request + HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); + request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase()); + request.addHeader(Names.CONNECTION, Values.UPGRADE); + request.addHeader(Names.SEC_WEBSOCKET_KEY, key); + request.addHeader(Names.HOST, wsURL.getHost()); + + int wsPort = wsURL.getPort(); + String originValue = "http://" + wsURL.getHost(); + if (wsPort != 80 && wsPort != 443) { + // if the port is not standard (80/443) its needed to add the port to the header. + // See http://tools.ietf.org/html/rfc6454#section-6.2 + originValue = originValue + ':' + wsPort; + } + request.addHeader(Names.SEC_WEBSOCKET_ORIGIN, originValue); + + String expectedSubprotocol = getExpectedSubprotocol(); + if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { + request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); + } + + request.addHeader(Names.SEC_WEBSOCKET_VERSION, "7"); + + if (customHeaders != null) { + for (Map.Entry<String, String> e : customHeaders.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + } + + ChannelFuture future = channel.write(request); + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) { + ChannelPipeline p = future.channel().pipeline(); + p.addAfter( + p.context(HttpRequestEncoder.class).name(), + "ws-encoder", new WebSocket07FrameEncoder(true)); + + if (future.isSuccess()) { + handshakeFuture.setSuccess(); + } else { + handshakeFuture.setFailure(future.cause()); + } + } + }); + + return handshakeFuture; + } + + /** + * <p> + * Process server response: + * </p> + * + * <pre> + * HTTP/1.1 101 Switching Protocols + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= + * Sec-WebSocket-Protocol: chat + * </pre> + * + * @param channel + * Channel + * @param response + * HTTP response returned from the server for the request sent by beginOpeningHandshake00(). + * @throws WebSocketHandshakeException + */ + @Override + public void finishHandshake(Channel channel, HttpResponse response) { + final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS; + + if (!response.getStatus().equals(status)) { + throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus()); + } + + String upgrade = response.getHeader(Names.UPGRADE); + if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) { + throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + + response.getHeader(Names.UPGRADE)); + } + + String connection = response.getHeader(Names.CONNECTION); + if (!Values.UPGRADE.equalsIgnoreCase(connection)) { + throw new WebSocketHandshakeException("Invalid handshake response connection: " + + response.getHeader(Names.CONNECTION)); + } + + String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT); + if (accept == null || !accept.equals(expectedChallengeResponseString)) { + throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, + expectedChallengeResponseString)); + } + + String subprotocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL); + setActualSubprotocol(subprotocol); + + setHandshakeComplete(); + + ChannelPipeline p = channel.pipeline(); + p.remove(HttpRequestEncoder.class); + p.get(HttpResponseDecoder.class).replace( + "ws-decoder", + new WebSocket07FrameDecoder(false, allowExtensions, getMaxFramePayloadLength())); + } +} diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java index 06d768e5e77..d69b161cb54 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java @@ -81,6 +81,10 @@ public static WebSocketClientHandshaker newHandshaker( return new WebSocketClientHandshaker08( webSocketURL, V08, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength); } + if (version == V07) { + return new WebSocketClientHandshaker07( + webSocketURL, V07, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength); + } if (version == V00) { return new WebSocketClientHandshaker00( webSocketURL, V00, subprotocol, customHeaders, maxFramePayloadLength); diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker07.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker07.java new file mode 100644 index 00000000000..33a20fab360 --- /dev/null +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker07.java @@ -0,0 +1,179 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.http.websocketx; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.http.DefaultHttpResponse; +import io.netty.handler.codec.http.HttpChunkAggregator; +import io.netty.handler.codec.http.HttpHeaders.Names; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpRequestDecoder; +import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpResponseEncoder; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.logging.InternalLogger; +import io.netty.logging.InternalLoggerFactory; +import io.netty.util.CharsetUtil; + +import static io.netty.handler.codec.http.HttpHeaders.Values.*; +import static io.netty.handler.codec.http.HttpVersion.*; + +/** + * <p> + * Performs server side opening and closing handshakes for web socket specification version <a + * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" >draft-ietf-hybi-thewebsocketprotocol- + * 10</a> + * </p> + */ +public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandshaker07.class); + + public static final String WEBSOCKET_07_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + + private final boolean allowExtensions; + + /** + * Constructor specifying the destination web socket location + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". + * Subsequent web socket frames will be sent to this URL. + * @param subprotocols + * CSV of supported protocols + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param maxFramePayloadLength + * Maximum allowable frame payload length. Setting this value to your application's + * requirement may reduce denial of service attacks using long data frames. + */ + public WebSocketServerHandshaker07( + String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength) { + super(WebSocketVersion.V07, webSocketURL, subprotocols, maxFramePayloadLength); + this.allowExtensions = allowExtensions; + } + + /** + * <p> + * Handle the web socket handshake for the web socket specification <a href= + * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07">HyBi version 7</a>. + * </p> + * + * <p> + * Browser request to the server: + * </p> + * + * <pre> + * GET /chat HTTP/1.1 + * Host: server.example.com + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== + * Sec-WebSocket-Origin: http://example.com + * Sec-WebSocket-Protocol: chat, superchat + * Sec-WebSocket-Version: 7 + * </pre> + * + * <p> + * Server response: + * </p> + * + * <pre> + * HTTP/1.1 101 Switching Protocols + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= + * Sec-WebSocket-Protocol: chat + * </pre> + * + * @param channel + * Channel + * @param req + * HTTP request + */ + @Override + public ChannelFuture handshake(Channel channel, HttpRequest req, ChannelFuture future) { + + if (logger.isDebugEnabled()) { + logger.debug(String.format("Channel %s WS Version 7 server handshake", channel.id())); + } + + HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS); + + String key = req.getHeader(Names.SEC_WEBSOCKET_KEY); + if (key == null) { + throw new WebSocketHandshakeException("not a WebSocket request: missing key"); + } + String acceptSeed = key + WEBSOCKET_07_ACCEPT_GUID; + byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII)); + String accept = WebSocketUtil.base64(sha1); + + if (logger.isDebugEnabled()) { + logger.debug(String.format("WS Version 7 Server Handshake key: %s. Response: %s.", key, accept)); + } + + res.setStatus(HttpResponseStatus.SWITCHING_PROTOCOLS); + res.addHeader(Names.UPGRADE, WEBSOCKET.toLowerCase()); + res.addHeader(Names.CONNECTION, Names.UPGRADE); + res.addHeader(Names.SEC_WEBSOCKET_ACCEPT, accept); + String subprotocols = req.getHeader(Names.SEC_WEBSOCKET_PROTOCOL); + if (subprotocols != null) { + String selectedSubprotocol = selectSubprotocol(subprotocols); + if (selectedSubprotocol == null) { + throw new WebSocketHandshakeException("Requested subprotocol(s) not supported: " + subprotocols); + } else { + res.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol); + setSelectedSubprotocol(selectedSubprotocol); + } + } + + channel.write(res, future); + + // Upgrade the connection and send the handshake response. + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) { + ChannelPipeline p = future.channel().pipeline(); + if (p.get(HttpChunkAggregator.class) != null) { + p.remove(HttpChunkAggregator.class); + } + + p.get(HttpRequestDecoder.class).replace("wsdecoder", + new WebSocket07FrameDecoder(true, allowExtensions, getMaxFramePayloadLength())); + p.replace(HttpResponseEncoder.class, "wsencoder", new WebSocket07FrameEncoder(false)); + } + }); + + return future; + } + + /** + * Echo back the closing frame and close the connection + * + * @param channel + * Channel + * @param frame + * Web Socket frame that was received + */ + @Override + public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelFuture future) { + future.addListener(ChannelFutureListener.CLOSE); + return channel.write(frame, future); + } +} diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java index fe8a0794d83..a93b0fdfd4c 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java @@ -93,6 +93,10 @@ public WebSocketServerHandshaker newHandshaker(HttpRequest req) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength); + } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { + // Version 8 of the wire protocol - version 07 of the draft hybi specification. + return new WebSocketServerHandshaker07( + webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength); } else { return null; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java index 3c157c6c1ee..2cb1c195777 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketVersion.java @@ -33,6 +33,12 @@ public enum WebSocketVersion { */ V00, + /** + * <a href= "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07" + * >draft-ietf-hybi-thewebsocketprotocol- 07</a> + */ + V07, + /** * <a href= "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" * >draft-ietf-hybi-thewebsocketprotocol- 10</a> @@ -53,6 +59,9 @@ public String toHttpHeaderValue() { if (this == V00) { return "0"; } + if (this == V07) { + return "7"; + } if (this == V08) { return "8"; }
null
train
train
2012-12-14T17:06:31
"2012-11-18T23:58:42Z"
ngocdaothanh
val
netty/netty/829_830
netty/netty
netty/netty/829
netty/netty/830
[ "timestamp(timedelta=62.0, similarity=0.854182584804582)" ]
44938973b4d09608b655d32d0693dc1119e56da8
13a446aecc30bd534fbeb987552ec3b47061ac0d
[ "This was first discovered by a hornetq user. For more details:\n\nhttps://community.jboss.org/thread/214134?start=15&tstart=0\n", "Pull request #830 was merged in to fix it...\n", "The same issue was observed in 3.6.6 Release. Stacktrace is following:\n Exception caught in channel [id: 0x363a30c8, /192.168.1.69:55489 => /192.168.1.32:5012]. Closing channel.\njavax.net.ssl.SSLException: Algorithm missing: \n at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:554) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1051) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) ~[na:1.6]\n at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) ~[na:1.6]\n at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1225) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:913) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:88) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:109) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:312) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:90) ~[netty-3.6.6.Final.jar:na]\n at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) ~[netty-3.6.6.Final.jar:na]\n at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_32]\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_32]\n at java.lang.Thread.run(Thread.java:662) [na:1.6.0_32]\nCaused by: java.security.NoSuchAlgorithmException: Could not create cipher RC4/128\n at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:99) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.CipherBox.newCipherBox(CipherBox.java:119) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.CipherSuite$BulkCipher.newCipher(CipherSuite.java:369) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.Handshaker.newReadCipher(Handshaker.java:410) ~[na:1.6]\n at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:550) ~[na:1.6]\n ... 18 common frames omitted\nCaused by: java.security.InvalidKeyException: No installed provider supports this key: (null)\n at javax.crypto.Cipher.a(DashoA13_..) ~[na:na]\n at javax.crypto.Cipher.init(DashoA13_..) ~[na:na]\n at javax.crypto.Cipher.init(DashoA13*..) ~[na:na]\n at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:88) ~[na:1.6]\n ... 22 common frames omitted\n\nShould I provide some info?\n" ]
[]
"2012-12-17T12:55:01Z"
[]
Race in SslHandler which can lead to failing handshake and also other bad side-effects
Here is the related stack: UNKNOWN SERVER CERTIFICATE: CN=securechat.example.netty.gleamynode.net, OU=Contributors, O=The Netty Project, L=Seongnam-si, ST=Kyunggi-do, C=KR javax.net.ssl.SSLException: Algorithm missing: at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:554) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1051) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1127) at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:825) at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:560) at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:555) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) at org.jboss.netty.channel.socket.oio.OioWorker.process(OioWorker.java:71) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:73) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) Caused by: java.security.NoSuchAlgorithmException: Could not create cipher RC4/128 at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:99) at com.sun.net.ssl.internal.ssl.CipherBox.newCipherBox(CipherBox.java:119) at com.sun.net.ssl.internal.ssl.CipherSuite$BulkCipher.newCipher(CipherSuite.java:369) at com.sun.net.ssl.internal.ssl.Handshaker.newReadCipher(Handshaker.java:410) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:550) ... 21 more Caused by: java.security.InvalidKeyException: No installed provider supports this key: (null) at javax.crypto.Cipher.a(DashoA13_..) at javax.crypto.Cipher.init(DashoA13_..) at javax.crypto.Cipher.init(DashoA13_..) at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:88) ... 25 more javax.net.ssl.SSLException: Algorithm missing: at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:554) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1051) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1127) at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:825) at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) at org.jboss.netty.channel.socket.oio.OioWorker.process(OioWorker.java:71) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:73) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) Caused by: java.security.NoSuchAlgorithmException: Could not create cipher RC4/128 at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:99) at com.sun.net.ssl.internal.ssl.CipherBox.newCipherBox(CipherBox.java:119) at com.sun.net.ssl.internal.ssl.CipherSuite$BulkCipher.newCipher(CipherSuite.java:369) at com.sun.net.ssl.internal.ssl.Handshaker.newReadCipher(Handshaker.java:410) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.changeReadCiphers(SSLEngineImpl.java:550) ... 16 more Caused by: java.security.InvalidKeyException: No installed provider supports this key: (null) at javax.crypto.Cipher.a(DashoA13_..) at javax.crypto.Cipher.init(DashoA13_..) at javax.crypto.Cipher.init(DashoA13_..) at com.sun.net.ssl.internal.ssl.CipherBox.<init>(CipherBox.java:88) ... 20 more javax.net.ssl.SSLException: Received fatal alert: internal_error at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1467) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1435) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1601) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1031) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1127) at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:825) at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) at org.jboss.netty.channel.socket.oio.OioWorker.process(OioWorker.java:71) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:73) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) java.nio.channels.ClosedChannelException at org.jboss.netty.handler.ssl.SslHandler.channelClosed(SslHandler.java:1472) at org.jboss.netty.channel.Channels.fireChannelClosed(Channels.java:468) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.close(AbstractOioWorker.java:229) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:98) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) 17.12.2012 09:11:26 org.jboss.netty.handler.ssl.SslHandshakeTest SCHWERWIEGEND: Handshake failed javax.net.ssl.SSLException: Received fatal alert: internal_error at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1467) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1435) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1601) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1031) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1127) at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:825) at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) at org.jboss.netty.channel.socket.oio.OioWorker.process(OioWorker.java:71) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:73) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) [WARNING] java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297) at java.lang.Thread.run(Thread.java:680) Caused by: javax.net.ssl.SSLException: Received fatal alert: internal_error at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1467) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1435) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1601) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1031) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:845) at com.sun.net.ssl.internal.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:721) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:607) at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1127) at org.jboss.netty.handler.ssl.SslHandler.decode(SslHandler.java:825) at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:425) at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) at org.jboss.netty.channel.socket.oio.OioWorker.process(OioWorker.java:71) at org.jboss.netty.channel.socket.oio.AbstractOioWorker.run(AbstractOioWorker.java:73) at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:51) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) ... 1 more
[ "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[ "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[ "src/test/java/org/jboss/netty/handler/ssl/SslHandshakeRaceTester.java" ]
diff --git a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java index de66e562a71..2e7e494a726 100644 --- a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java +++ b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java @@ -54,7 +54,6 @@ import java.util.regex.Pattern; import static org.jboss.netty.channel.Channels.*; -import static org.jboss.netty.channel.Channels.fireExceptionCaught; /** * Adds <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">SSL @@ -870,76 +869,76 @@ private void wrap(ChannelHandlerContext context, Channel channel) channel.getRemoteAddress())); offered = true; } else { - SSLEngineResult result = null; - try { - synchronized (handshakeLock) { + synchronized (handshakeLock) { + SSLEngineResult result = null; + try { result = engine.wrap(outAppBuf, outNetBuf); - } - } finally { - if (!outAppBuf.hasRemaining()) { - pendingUnencryptedWrites.remove(); - } - } - - if (result.bytesProduced() > 0) { - outNetBuf.flip(); - int remaining = outNetBuf.remaining(); - msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(remaining); - - // Transfer the bytes to the new ChannelBuffer using some safe method that will also - // work with "non" heap buffers - // - // See https://github.com/netty/netty/issues/329 - msg.writeBytes(outNetBuf); - outNetBuf.clear(); - - ChannelFuture future; - if (pendingWrite.outAppBuf.hasRemaining()) { - // pendingWrite's future shouldn't be notified if - // only partial data is written. - future = succeededFuture(channel); - } else { - future = pendingWrite.future; + } finally { + if (!outAppBuf.hasRemaining()) { + pendingUnencryptedWrites.remove(); + } } - MessageEvent encryptedWrite = new DownstreamMessageEvent( - channel, future, msg, channel.getRemoteAddress()); - offerEncryptedWriteRequest(encryptedWrite); - offered = true; - } else if (result.getStatus() == Status.CLOSED) { - // SSLEngine has been closed already. - // Any further write attempts should be denied. - success = false; - break; - } else { - final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); - handleRenegotiation(handshakeStatus); - switch (handshakeStatus) { - case NEED_WRAP: - if (outAppBuf.hasRemaining()) { - break; + if (result.bytesProduced() > 0) { + outNetBuf.flip(); + int remaining = outNetBuf.remaining(); + msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(remaining); + + // Transfer the bytes to the new ChannelBuffer using some safe method that will also + // work with "non" heap buffers + // + // See https://github.com/netty/netty/issues/329 + msg.writeBytes(outNetBuf); + outNetBuf.clear(); + + ChannelFuture future; + if (pendingWrite.outAppBuf.hasRemaining()) { + // pendingWrite's future shouldn't be notified if + // only partial data is written. + future = succeededFuture(channel); } else { - break loop; + future = pendingWrite.future; } - case NEED_UNWRAP: - needsUnwrap = true; - break loop; - case NEED_TASK: - runDelegatedTasks(); + + MessageEvent encryptedWrite = new DownstreamMessageEvent( + channel, future, msg, channel.getRemoteAddress()); + offerEncryptedWriteRequest(encryptedWrite); + offered = true; + } else if (result.getStatus() == Status.CLOSED) { + // SSLEngine has been closed already. + // Any further write attempts should be denied. + success = false; break; - case FINISHED: - case NOT_HANDSHAKING: - if (handshakeStatus == HandshakeStatus.FINISHED) { - setHandshakeSuccess(channel); - } - if (result.getStatus() == Status.CLOSED) { - success = false; + } else { + final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); + handleRenegotiation(handshakeStatus); + switch (handshakeStatus) { + case NEED_WRAP: + if (outAppBuf.hasRemaining()) { + break; + } else { + break loop; + } + case NEED_UNWRAP: + needsUnwrap = true; + break loop; + case NEED_TASK: + runDelegatedTasks(); + break; + case FINISHED: + case NOT_HANDSHAKING: + if (handshakeStatus == HandshakeStatus.FINISHED) { + setHandshakeSuccess(channel); + } + if (result.getStatus() == Status.CLOSED) { + success = false; + } + break loop; + default: + throw new IllegalStateException( + "Unknown handshake status: " + + handshakeStatus); } - break loop; - default: - throw new IllegalStateException( - "Unknown handshake status: " + - handshakeStatus); } } } @@ -1125,56 +1124,55 @@ private ChannelBuffer unwrap( synchronized (handshakeLock) { result = engine.unwrap(inNetBuf, outAppBuf); - } - // notify about the CLOSED state of the SSLEngine. See #137 - if (result.getStatus() == Status.CLOSED) { - sslEngineCloseFuture.setClosed(); - } + // notify about the CLOSED state of the SSLEngine. See #137 + if (result.getStatus() == Status.CLOSED) { + sslEngineCloseFuture.setClosed(); + } - final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); - handleRenegotiation(handshakeStatus); - switch (handshakeStatus) { - case NEED_UNWRAP: - if (inNetBuf.hasRemaining() && !engine.isInboundDone()) { + final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); + handleRenegotiation(handshakeStatus); + switch (handshakeStatus) { + case NEED_UNWRAP: + if (inNetBuf.hasRemaining() && !engine.isInboundDone()) { + break; + } else { + break loop; + } + case NEED_WRAP: + wrapNonAppData(ctx, channel); break; - } else { + case NEED_TASK: + runDelegatedTasks(); + break; + case FINISHED: + setHandshakeSuccess(channel); + needsWrap = true; break loop; + case NOT_HANDSHAKING: + needsWrap = true; + break loop; + default: + throw new IllegalStateException( + "Unknown handshake status: " + handshakeStatus); } - case NEED_WRAP: - wrapNonAppData(ctx, channel); - break; - case NEED_TASK: - runDelegatedTasks(); - break; - case FINISHED: - setHandshakeSuccess(channel); - needsWrap = true; - break loop; - case NOT_HANDSHAKING: - needsWrap = true; - break loop; - default: - throw new IllegalStateException( - "Unknown handshake status: " + handshakeStatus); } - } - if (needsWrap) { - // wrap() acquires pendingUnencryptedWrites first and then - // handshakeLock. If handshakeLock is already hold by the - // current thread, calling wrap() will lead to a dead lock - // i.e. pendingUnencryptedWrites -> handshakeLock vs. - // handshakeLock -> pendingUnencryptedLock -> handshakeLock - // - // There is also a same issue between pendingEncryptedWrites - // and pendingUnencryptedWrites. - if (!Thread.holdsLock(handshakeLock) && - !pendingEncryptedWritesLock.isHeldByCurrentThread()) { - wrap(ctx, channel); + if (needsWrap) { + // wrap() acquires pendingUnencryptedWrites first and then + // handshakeLock. If handshakeLock is already hold by the + // current thread, calling wrap() will lead to a dead lock + // i.e. pendingUnencryptedWrites -> handshakeLock vs. + // handshakeLock -> pendingUnencryptedLock -> handshakeLock + // + // There is also a same issue between pendingEncryptedWrites + // and pendingUnencryptedWrites. + if (!Thread.holdsLock(handshakeLock) && + !pendingEncryptedWritesLock.isHeldByCurrentThread()) { + wrap(ctx, channel); + } } } - outAppBuf.flip(); if (outAppBuf.hasRemaining()) {
diff --git a/src/test/java/org/jboss/netty/handler/ssl/SslHandshakeRaceTester.java b/src/test/java/org/jboss/netty/handler/ssl/SslHandshakeRaceTester.java new file mode 100644 index 00000000000..fdf99d897e6 --- /dev/null +++ b/src/test/java/org/jboss/netty/handler/ssl/SslHandshakeRaceTester.java @@ -0,0 +1,197 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package org.jboss.netty.handler.ssl; + +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelFutureListener; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import org.jboss.netty.channel.socket.ClientSocketChannelFactory; +import org.jboss.netty.channel.socket.ServerSocketChannelFactory; +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; +import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; +import org.jboss.netty.example.securechat.SecureChatSslContextFactory; + +import javax.net.ssl.SSLEngine; +import java.net.InetSocketAddress; +import java.util.Random; +import java.util.concurrent.atomic.AtomicReference; + +public class SslHandshakeRaceTester { + + private static final Random random = new Random(); + static final byte[] data = new byte[1048576]; + private int count; + + static { + random.nextBytes(data); + } + + public void run(int rounds, boolean nio) throws Throwable { + ClientSocketChannelFactory clientFactory; + if (nio) { + clientFactory = new NioClientSocketChannelFactory(); + } else { + clientFactory = new OioClientSocketChannelFactory(); + } + ClientBootstrap cb = new ClientBootstrap(clientFactory); + cb.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() throws Exception { + ChannelPipeline cp = Channels.pipeline(); + + SSLEngine cse = SecureChatSslContextFactory.getClientContext().createSSLEngine(); + cse.setUseClientMode(true); + cp.addFirst("ssl", new SslHandler(cse)); + + cp.addLast("handler", new TestHandler()); + return cp; + } + }); + + ServerSocketChannelFactory serverFactory; + if (nio) { + serverFactory = new NioServerSocketChannelFactory(); + } else { + serverFactory = new OioServerSocketChannelFactory(); + } + ServerBootstrap sb = new ServerBootstrap(serverFactory); + + sb.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() throws Exception { + ChannelPipeline cp = Channels.pipeline(); + + cp.addFirst("counter", new SimpleChannelUpstreamHandler() { + @Override + public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { + ctx.getPipeline().get(SslHandler.class).handshake().addListener(new ChannelFutureListener() { + public void operationComplete(ChannelFuture future) throws Exception { + if (!future.isSuccess()) { + future.getCause().printStackTrace(); + future.getChannel().close(); + } + } + }); + + ++count; + System.out.println("Connection #" + count); + } + }); + + SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine(); + sse.setUseClientMode(false); + cp.addFirst("ssl", new SslHandler(sse)); + + cp.addLast("handler", new TestHandler()); + return cp; + } + }); + + Channel sc = sb.bind(new InetSocketAddress(0)); + int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); + + for (int i = 0; i < rounds; i++) { + connectAndSend(cb, port); + } + + cb.shutdown(); + cb.releaseExternalResources(); + sc.close().awaitUninterruptibly(); + sb.shutdown(); + sb.releaseExternalResources(); + } + + private static void connectAndSend(ClientBootstrap cb, int port) throws Throwable { + ChannelFuture ccf = cb.connect(new InetSocketAddress("127.0.0.1", port)); + ccf.awaitUninterruptibly(); + if (!ccf.isSuccess()) { + ccf.getCause().printStackTrace(); + throw ccf.getCause(); + } + TestHandler ch = ccf.getChannel().getPipeline().get(TestHandler.class); + + Channel cc = ccf.getChannel(); + ChannelFuture hf = cc.getPipeline().get(SslHandler.class).handshake(); + hf.awaitUninterruptibly(); + if (!hf.isSuccess()) { + hf.getCause().printStackTrace(); + ch.channel.close(); + throw hf.getCause(); + } + + for (int i = 0; i < data.length;) { + int length = Math.min(random.nextInt(1024 * 64), data.length - i); + ChannelFuture future = cc.write(ChannelBuffers.wrappedBuffer(data, i, length)); + i += length; + if (i >= data.length) { + future.awaitUninterruptibly(); + } + } + + ch.channel.close().awaitUninterruptibly(); + + if (ch.exception.get() != null) { + throw ch.exception.get(); + } + } + + private static class TestHandler extends SimpleChannelUpstreamHandler { + volatile Channel channel; + final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); + + @Override + public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) + throws Exception { + channel = e.getChannel(); + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) + throws Exception { + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) + throws Exception { + e.getCause().printStackTrace(); + + exception.compareAndSet(null, e.getCause()); + e.getChannel().close(); + } + } + + public static void main(String[] args) throws Throwable { + int count = 20000; + boolean nio = false; + if (args.length == 2) { + count = Integer.parseInt(args[0]); + nio = Boolean.parseBoolean(args[1]); + } + SslHandshakeRaceTester test = new SslHandshakeRaceTester(); + test.run(count, nio); + } +}
train
train
2012-12-14T10:35:39
"2012-12-17T11:40:53Z"
normanmaurer
val
netty/netty/799_835
netty/netty
netty/netty/799
netty/netty/835
[ "timestamp(timedelta=6.0, similarity=0.8830975234270076)" ]
44938973b4d09608b655d32d0693dc1119e56da8
[]
[ "Unnecessary empty line\n", "Unnecessary empty line\n", "How about adding a private method like this:\n\n```\nprivate void cancelHandshakeTimeout() {\n if (handshakeTimeout != null) { ... }\n}\n```\n\nto reduce duplicates\n", "good idea :)\n" ]
"2012-12-19T08:38:14Z"
[ "defect", "improvement", "feature" ]
Backport SslHandler.handshake() timeout
We have a "strong" need for SslHandler.handshake() timeout in HornetQ so I would like to backport it to 3.x
[ "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[ "src/main/java/org/jboss/netty/handler/ssl/SslHandler.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java index 6b4cec0470c..9e6fa600b11 100644 --- a/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java +++ b/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java @@ -33,6 +33,9 @@ import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.TimerTask; import org.jboss.netty.util.internal.DetectionUtil; import org.jboss.netty.util.internal.NonReentrantLock; @@ -50,6 +53,7 @@ import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; @@ -209,6 +213,10 @@ public static synchronized SslBufferPool getDefaultBufferPool() { private int packetLength = Integer.MIN_VALUE; + private final Timer timer; + private final long handshakeTimeoutInMillis; + private Timeout handshakeTimeout; + /** * Creates a new instance. * @@ -314,6 +322,33 @@ public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExec * that {@link SSLEngine#getDelegatedTask()} will return */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) { + this(engine, bufferPool, startTls, delegatedTaskExecutor, null, 0); + } + + /** + * Creates a new instance. + * + * @param engine + * the {@link SSLEngine} this handler will use + * @param bufferPool + * the {@link SslBufferPool} where this handler will acquire + * the buffers required by the {@link SSLEngine} + * @param startTls + * {@code true} if the first write request shouldn't be encrypted + * by the {@link SSLEngine} + * @param delegatedTaskExecutor + * the {@link Executor} which will execute the delegated task + * that {@link SSLEngine#getDelegatedTask()} will return + * @param timer + * the {@link Timer} which will be used to process the timeout of the {@link #handshake()}. + * Be aware that the given {@link Timer} will not get stopped automaticly, so it is up to you to cleanup + * once you not need it anymore + * @param handshakeTimeoutInMillis + * the time in milliseconds after whic the {@link #handshake()} will be failed, and so the future notified + * + */ + public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor, + Timer timer, long handshakeTimeoutInMillis) { if (engine == null) { throw new NullPointerException("engine"); } @@ -323,10 +358,16 @@ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, if (delegatedTaskExecutor == null) { throw new NullPointerException("delegatedTaskExecutor"); } + if (timer == null && handshakeTimeoutInMillis > 0) { + throw new IllegalArgumentException("No Timer was given but a handshakeTimeoutInMillis, need both or none"); + } + this.engine = engine; this.bufferPool = bufferPool; this.delegatedTaskExecutor = delegatedTaskExecutor; this.startTls = startTls; + this.timer = timer; + this.handshakeTimeoutInMillis = handshakeTimeoutInMillis; } /** @@ -348,7 +389,7 @@ public ChannelFuture handshake() { } ChannelHandlerContext ctx = this.ctx; - Channel channel = ctx.getChannel(); + final Channel channel = ctx.getChannel(); ChannelFuture handshakeFuture; Exception exception = null; @@ -361,6 +402,20 @@ public ChannelFuture handshake() { engine.beginHandshake(); runDelegatedTasks(); handshakeFuture = this.handshakeFuture = future(channel); + if (handshakeTimeoutInMillis > 0) { + handshakeTimeout = timer.newTimeout(new TimerTask() { + public void run(Timeout timeout) throws Exception { + ChannelFuture future = SslHandler.this.handshakeFuture; + if (future != null && future.isDone()) { + return; + } + + setHandshakeFailure(channel, new SSLException("Handshake did not complete within " + + handshakeTimeoutInMillis + "ms")); + } + }, handshakeTimeoutInMillis, TimeUnit.MILLISECONDS); + } + } catch (Exception e) { handshakeFuture = this.handshakeFuture = failedFuture(channel, e); exception = e; @@ -466,6 +521,15 @@ public ChannelFuture getSSLEngineInboundCloseFuture() { return sslEngineCloseFuture; } + /** + * Return the timeout (in ms) after which the {@link ChannelFuture} of {@link #handshake()} will be failed, while + * a handshake is in progress + * + */ + public long getHandshakeTimeout() { + return handshakeTimeoutInMillis; + } + /** * If set to {@code true}, the {@link Channel} will automatically get closed * one a {@link SSLException} was caught. This is most times what you want, as after this @@ -543,6 +607,10 @@ public void channelDisconnected(ChannelHandlerContext ctx, // been closed during handshake. synchronized (handshakeLock) { if (handshaking) { + if (handshakeTimeout != null) { + // cancel the task as we will fail the handshake future now + handshakeTimeout.cancel(); + } handshakeFuture.setFailure(new ClosedChannelException()); } } @@ -563,7 +631,6 @@ public void channelDisconnected(ChannelHandlerContext ctx, } } } - @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { @@ -1262,6 +1329,9 @@ private void setHandshakeSuccess(Channel channel) { if (handshakeFuture == null) { handshakeFuture = future(channel); } + if (handshakeTimeout != null) { + handshakeTimeout.cancel(); + } } handshakeFuture.setSuccess(); @@ -1279,6 +1349,11 @@ private void setHandshakeFailure(Channel channel, SSLException cause) { handshakeFuture = future(channel); } + // cancel the timeout now + if (handshakeTimeout != null) { + handshakeTimeout.cancel(); + } + // Release all resources such as internal buffers that SSLEngine // is managing.
null
train
train
2012-12-14T10:35:39
"2012-12-11T16:50:19Z"
normanmaurer
val
netty/netty/690_848
netty/netty
netty/netty/690
netty/netty/848
[ "timestamp(timedelta=68.0, similarity=0.9339016503041959)" ]
71b089cb3bf30706a9da17bd91f0a67146732059
6284fc3af315ba943fa99ba1597c9dbf3f315a26
[ "@phoenix we are currently try to \"port\" one \"piece\" after the other. But as you may realize we are quite busy at the moment to the the API rock stable. \n\nSo the best thing for you to get it add back in a quick manner is to chime in an port it by yourself.. After that a pull-request would be really welcome :)\n\nThe JMX stuff will hopefully get also some more attention in the near future. As we want to integrate our new metrics api in more parts of Netty. This could then be used to export the metrics via jmx. At the moment we have a default implementation which use yammer metrics, and as far as I can tell they support jmx out of the box\n", "I've ported this over to 4. I just need to fix up the javadoc and then will issue a pull request. Will likely be tomorrow evening before I can get a chance to commit the last bit.\n", "@lw346 thanks !!!\n", "Also see #851 \n", "Fixed by #851 \n" ]
[ "I think we don't need that anymore as the readable(..) flag is now per ChannelHandlerContext and so it should be enough to just use this method...\n", "See above...\n", "I know it is just the same as in 3 but this just is an anti-pattern as it will block the IO-Thread. Let us fix this.\n", "See above\n", "The reason I kept this attribute setting was in case there's another handler in the pipeline that will modify readable() on the ChannelHandlerContext. In this instance, we need to make sure that we're not overriding another handler's modifications - the attribute ensures that we will only make modifications if **this** handler needs to.\n\nI'm quite happy to swap it out as you suggest, but it feels cleaner to keep the handlers self-contained.\n", "The ChannelHandlerContext is \"bound\" to the ChannelHandler instance so only \"this instance\" can change it. In 3.x this was different as the readable(..) flag was modified on the Channel and so was not \"per\" ChannelHandlerContext. So we don't need it anymore..\n", "This should be \"true\" all the times r I'm wrong ?\n" ]
"2012-12-23T19:33:50Z"
[]
the traffic package need ported back to 4.0
We miss the traffic package so much,can you port it back to 4.0 please? And how about the JMX support plan in 4.0?
[]
[ "handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java", "handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java", "handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java", "handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java", "handler/src/main/java/io/netty/handler/traffic/package-info.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java new file mode 100644 index 00000000000..b061647b089 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/traffic/AbstractTrafficShapingHandler.java @@ -0,0 +1,364 @@ +/* + * Copyright 2011 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.traffic; + +import io.netty.buffer.Buf; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundByteHandler; +import io.netty.channel.ChannelOutboundByteHandler; +import io.netty.util.AttributeKey; + +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * AbstractTrafficShapingHandler allows to limit the global bandwidth + * (see {@link GlobalTrafficShapingHandler}) or per session + * bandwidth (see {@link ChannelTrafficShapingHandler}), as traffic shaping. + * It allows you to implement an almost real time monitoring of the bandwidth using + * the monitors from {@link TrafficCounter} that will call back every checkInterval + * the method doAccounting of this handler.<br> + * <br> + * + * If you want for any particular reasons to stop the monitoring (accounting) or to change + * the read/write limit or the check interval, several methods allow that for you:<br> + * <ul> + * <li><tt>configure</tt> allows you to change read or write limits, or the checkInterval</li> + * <li><tt>getTrafficCounter</tt> allows you to have access to the TrafficCounter and so to stop + * or start the monitoring, to change the checkInterval directly, or to have access to its values.</li> + * </ul> + */ +public abstract class AbstractTrafficShapingHandler extends ChannelHandlerAdapter + implements ChannelInboundByteHandler, ChannelOutboundByteHandler { + + /** + * Default delay between two checks: 1s + */ + public static final long DEFAULT_CHECK_INTERVAL = 1000; + + /** + * AttributeKey to indicate whether this handler has suspended read + * operations on the channel + */ + protected AttributeKey<Boolean> readSuspended; + + /** + * Default minimal time to wait + */ + private static final long MINIMAL_WAIT = 10; + + /** + * Traffic Counter + */ + protected TrafficCounter trafficCounter; + + /** + * used in releaseExternalResources() to cancel the timer + */ + private volatile ScheduledFuture<?> scheduledFuture; + + /** + * Limit in B/s to apply to write + */ + private long writeLimit; + + /** + * Limit in B/s to apply to read + */ + private long readLimit; + + /** + * Delay between two performance snapshots + */ + protected long checkInterval = DEFAULT_CHECK_INTERVAL; // default 1 s + + /** + * Boolean associated with the release of this TrafficShapingHandler. + * It will be true only once when the releaseExternalRessources is called + * to prevent waiting when shutdown. + */ + final AtomicBoolean release = new AtomicBoolean(false); + + /** + * + * @param newTrafficCounter the TrafficCounter to set + */ + void setTrafficCounter(TrafficCounter newTrafficCounter) { + trafficCounter = newTrafficCounter; + } + + /** + * @param writeLimit + * 0 or a limit in bytes/s + * @param readLimit + * 0 or a limit in bytes/s + * @param checkInterval + * The delay between two computations of performances for + * channels or 0 if no stats are to be computed + */ + protected AbstractTrafficShapingHandler(long writeLimit, long readLimit, + long checkInterval) { + this.writeLimit = writeLimit; + this.readLimit = readLimit; + this.checkInterval = checkInterval; + } + + /** + * Constructor using default Check Interval + * + * @param writeLimit + * 0 or a limit in bytes/s + * @param readLimit + * 0 or a limit in bytes/s + */ + protected AbstractTrafficShapingHandler(long writeLimit, long readLimit) { + this(writeLimit, readLimit, DEFAULT_CHECK_INTERVAL); + } + + /** + * Constructor using NO LIMIT and default Check Interval + */ + protected AbstractTrafficShapingHandler() { + this(0, 0, DEFAULT_CHECK_INTERVAL); + } + + /** + * Constructor using NO LIMIT + * + * @param checkInterval + * The delay between two computations of performances for + * channels or 0 if no stats are to be computed + */ + protected AbstractTrafficShapingHandler(long checkInterval) { + this(0, 0, checkInterval); + } + + /** + * Change the underlying limitations and check interval. + * + * @param newWriteLimit The new write limit (in bytes) + * @param newReadLimit The new read limit (in bytes) + * @param newCheckInterval The new check interval (in milliseconds) + */ + public void configure(long newWriteLimit, long newReadLimit, + long newCheckInterval) { + configure(newWriteLimit, newReadLimit); + configure(newCheckInterval); + } + + /** + * Change the underlying limitations. + * + * @param newWriteLimit The new write limit (in bytes) + * @param newReadLimit The new read limit (in bytes) + */ + public void configure(long newWriteLimit, long newReadLimit) { + writeLimit = newWriteLimit; + readLimit = newReadLimit; + if (trafficCounter != null) { + trafficCounter.resetAccounting(System.currentTimeMillis() + 1); + } + } + + /** + * Change the check interval. + * + * @param newCheckInterval The new check interval (in milliseconds) + */ + public void configure(long newCheckInterval) { + checkInterval = newCheckInterval; + if (trafficCounter != null) { + trafficCounter.configure(checkInterval); + } + } + + /** + * Called each time the accounting is computed from the TrafficCounters. + * This method could be used for instance to implement almost real time accounting. + * + * @param counter + * the TrafficCounter that computes its performance + */ + protected void doAccounting(TrafficCounter counter) { + // NOOP by default + } + + /** + * Class to implement setReadable at fix time + */ + private class ReopenReadTimerTask implements Runnable { + final ChannelHandlerContext ctx; + ReopenReadTimerTask(ChannelHandlerContext ctx) { + this.ctx = ctx; + } + + @Override + public void run() { + if (release.get()) { + return; + } + + if (ctx != null && ctx.channel() != null && + ctx.channel().isActive()) { + ctx.attr(readSuspended).set(null); + ctx.readable(true); + } + } + } + + /** + * + * @return the time that should be necessary to wait to respect limit. Can + * be negative time + */ + private static long getTimeToWait(long limit, long bytes, long lastTime, + long curtime) { + long interval = curtime - lastTime; + if (interval == 0) { + // Time is too short, so just lets continue + return 0; + } + return ((bytes * 1000 / limit - interval) / 10) * 10; + } + + @Override + public ByteBuf newInboundBuffer(ChannelHandlerContext ctx) throws Exception { + return ctx.alloc().buffer(); + } + + @Override + public void freeInboundBuffer(ChannelHandlerContext ctx, Buf buf) throws Exception { + buf.free(); + } + + @Override + public ByteBuf newOutboundBuffer(ChannelHandlerContext ctx) throws Exception { + return ctx.alloc().buffer(); + } + + @Override + public void freeOutboundBuffer(ChannelHandlerContext ctx, Buf buf) throws Exception { + buf.free(); + } + + @Override + public void inboundBufferUpdated(ChannelHandlerContext ctx) throws Exception { + ByteBuf buf = ctx.inboundByteBuffer(); + long curtime = System.currentTimeMillis(); + long size = buf.readableBytes(); + + if (trafficCounter != null) { + trafficCounter.bytesRecvFlowControl(size); + if (readLimit == 0) { + // no action + return; + } + + // compute the number of ms to wait before reopening the channel + long wait = getTimeToWait(readLimit, + trafficCounter.getCurrentReadBytes(), + trafficCounter.getLastTime(), curtime); + if (wait >= MINIMAL_WAIT) { // At least 10ms seems a minimal + // time in order to + Channel channel = ctx.channel(); + // try to limit the traffic + if (channel != null && channel.isActive()) { + if (ctx.attr(readSuspended).get() == null) { + ctx.attr(readSuspended).set(Boolean.TRUE); + ctx.readable(false); + Runnable timerTask = new ReopenReadTimerTask(ctx); + scheduledFuture = ctx.executor().schedule(timerTask, wait, + TimeUnit.MILLISECONDS); + } else { + // should be waiting: but can occurs sometime so as + // a FIX + if (release.get()) { + return; + } + Thread.sleep(wait); + } + } else { + // Not connected or no channel + if (release.get()) { + return; + } + Thread.sleep(wait); + } + } + } + } + + @Override + public void flush(ChannelHandlerContext ctx, ChannelFuture future) throws Exception { + long curtime = System.currentTimeMillis(); + long size = ctx.outboundByteBuffer().readableBytes(); + + try { + if (trafficCounter != null) { + trafficCounter.bytesWriteFlowControl(size); + if (writeLimit == 0) { + return; + } + // compute the number of ms to wait before continue with the + // channel + long wait = getTimeToWait(writeLimit, + trafficCounter.getCurrentWrittenBytes(), + trafficCounter.getLastTime(), curtime); + if (wait >= MINIMAL_WAIT) { + // Global or Channel + if (release.get()) { + return; + } + Thread.sleep(wait); + } + } + } finally { + ctx.flush(future); + } + } + + /** + * + * @return the current TrafficCounter (if + * channel is still connected) + */ + public TrafficCounter getTrafficCounter() { + return trafficCounter; + } + + @Override + public void beforeRemove(ChannelHandlerContext ctx) { + if (trafficCounter != null) { + trafficCounter.stop(); + } + release.set(true); + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + } + } + + @Override + public String toString() { + return "TrafficShaping with Write Limit: " + writeLimit + + " Read Limit: " + readLimit + " and Counter: " + + (trafficCounter != null? trafficCounter.toString() : "none"); + } +} diff --git a/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java new file mode 100644 index 00000000000..4158d867488 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/traffic/ChannelTrafficShapingHandler.java @@ -0,0 +1,93 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.traffic; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.util.AttributeKey; + +/** + * This implementation of the {@link AbstractTrafficShapingHandler} is for channel + * traffic shaping, that is to say a per channel limitation of the bandwidth.<br><br> + * + * The general use should be as follow:<br> + * <ul> + * <li>Add in your pipeline a new ChannelTrafficShapingHandler.<br> + * <tt>ChannelTrafficShapingHandler myHandler = new ChannelTrafficShapingHandler();</tt><br> + * <tt>pipeline.addLast(myHandler);</tt><br><br> + * + * <b>Note that this handler has a Pipeline Coverage of "one" which means a new handler must be created + * for each new channel as the counter cannot be shared among all channels.</b>.<br><br> + * + * Other arguments can be passed like write or read limitation (in bytes/s where 0 means no limitation) + * or the check interval (in millisecond) that represents the delay between two computations of the + * bandwidth and so the call back of the doAccounting method (0 means no accounting at all).<br><br> + * + * A value of 0 means no accounting for checkInterval. If you need traffic shaping but no such accounting, + * it is recommended to set a positive value, even if it is high since the precision of the + * Traffic Shaping depends on the period where the traffic is computed. The highest the interval, + * the less precise the traffic shaping will be. It is suggested as higher value something close + * to 5 or 10 minutes.<br> + * </li> + * </ul><br> + */ +public class ChannelTrafficShapingHandler extends AbstractTrafficShapingHandler { + + public ChannelTrafficShapingHandler(long writeLimit, + long readLimit, long checkInterval) { + super(writeLimit, readLimit, checkInterval); + } + + public ChannelTrafficShapingHandler(long writeLimit, + long readLimit) { + super(writeLimit, readLimit); + } + + public ChannelTrafficShapingHandler(long checkInterval) { + super(checkInterval); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) + throws Exception { + if (trafficCounter != null) { + trafficCounter.stop(); + } + + super.channelInactive(ctx); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + readSuspended = new AttributeKey<Boolean>("readSuspended-channel"); + ctx.attr(readSuspended).set(Boolean.TRUE); + ctx.readable(false); + if (trafficCounter == null) { + // create a new counter now + if (ctx.executor() != null) { + trafficCounter = new TrafficCounter(this, ctx.executor(), "ChannelTC" + + ctx.channel().id(), checkInterval); + } + } + if (trafficCounter != null) { + trafficCounter.start(); + } + super.channelActive(ctx); + + ctx.attr(readSuspended).set(null); + ctx.readable(true); + } + +} diff --git a/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java b/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java new file mode 100644 index 00000000000..4b817fc3a45 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/traffic/GlobalTrafficShapingHandler.java @@ -0,0 +1,85 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.traffic; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.EventExecutor; +import io.netty.util.AttributeKey; + +/** + * This implementation of the {@link AbstractTrafficShapingHandler} is for global + * traffic shaping, that is to say a global limitation of the bandwidth, whatever + * the number of opened channels.<br><br> + * + * The general use should be as follow:<br> + * <ul> + * <li>Create your unique GlobalTrafficShapingHandler like:<br><br> + * <tt>GlobalTrafficShapingHandler myHandler = new GlobalTrafficShapingHandler(executor);</tt><br><br> + * The executor could be the underlying IO worker pool<br> + * <tt>pipeline.addLast(myHandler);</tt><br><br> + * + * <b>Note that this handler has a Pipeline Coverage of "all" which means only one such handler must be created + * and shared among all channels as the counter must be shared among all channels.</b><br><br> + * + * Other arguments can be passed like write or read limitation (in bytes/s where 0 means no limitation) + * or the check interval (in millisecond) that represents the delay between two computations of the + * bandwidth and so the call back of the doAccounting method (0 means no accounting at all).<br><br> + * + * A value of 0 means no accounting for checkInterval. If you need traffic shaping but no such accounting, + * it is recommended to set a positive value, even if it is high since the precision of the + * Traffic Shaping depends on the period where the traffic is computed. The highest the interval, + * the less precise the traffic shaping will be. It is suggested as higher value something close + * to 5 or 10 minutes.<br> + * </li> + * </ul><br> + */ +@Sharable +public class GlobalTrafficShapingHandler extends AbstractTrafficShapingHandler { + /** + * Create the global TrafficCounter + */ + void createGlobalTrafficCounter(EventExecutor executor) { + readSuspended = new AttributeKey<Boolean>("readSuspended-global"); + TrafficCounter tc; + if (executor != null) { + tc = new TrafficCounter(this, executor, "GlobalTC", + checkInterval); + setTrafficCounter(tc); + tc.start(); + } + } + + public GlobalTrafficShapingHandler(EventExecutor executor, long writeLimit, + long readLimit, long checkInterval) { + super(writeLimit, readLimit, checkInterval); + createGlobalTrafficCounter(executor); + } + + public GlobalTrafficShapingHandler(EventExecutor executor, long writeLimit, + long readLimit) { + super(writeLimit, readLimit); + createGlobalTrafficCounter(executor); + } + + public GlobalTrafficShapingHandler(EventExecutor executor, long checkInterval) { + super(checkInterval); + createGlobalTrafficCounter(executor); + } + + public GlobalTrafficShapingHandler(EventExecutor executor) { + createGlobalTrafficCounter(executor); + } +} diff --git a/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java b/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java new file mode 100644 index 00000000000..95b47e96da2 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/traffic/TrafficCounter.java @@ -0,0 +1,394 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.traffic; + +import io.netty.channel.EventExecutor; + +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +/** + * TrafficCounter is associated with {@link AbstractTrafficShapingHandler}. + * + * <p>A <tt>TrafficCounter</tt> counts the read and written bytes such that the + * {@link AbstractTrafficShapingHandler} can limit the traffic, globally or per channel.</p> + * + * <p>It computes the statistics for both read and written every {@link #checkInterval}, and calls + * back to its parent {@link AbstractTrafficShapingHandler#doAccounting} method. If the checkInterval + * is set to 0, no accounting will be done and statistics will only be computed at each receive or + * write operation.</p> + */ +public class TrafficCounter { + /** + * Current written bytes + */ + private final AtomicLong currentWrittenBytes = new AtomicLong(); + + /** + * Current read bytes + */ + private final AtomicLong currentReadBytes = new AtomicLong(); + + /** + * Long life written bytes + */ + private final AtomicLong cumulativeWrittenBytes = new AtomicLong(); + + /** + * Long life read bytes + */ + private final AtomicLong cumulativeReadBytes = new AtomicLong(); + + /** + * Last Time where cumulative bytes where reset to zero + */ + private long lastCumulativeTime; + + /** + * Last writing bandwidth + */ + private long lastWriteThroughput; + + /** + * Last reading bandwidth + */ + private long lastReadThroughput; + + /** + * Last Time Check taken + */ + private final AtomicLong lastTime = new AtomicLong(); + + /** + * Last written bytes number during last check interval + */ + private long lastWrittenBytes; + + /** + * Last read bytes number during last check interval + */ + private long lastReadBytes; + + /** + * Delay between two captures + */ + AtomicLong checkInterval = new AtomicLong( + AbstractTrafficShapingHandler.DEFAULT_CHECK_INTERVAL); + + // default 1 s + + /** + * Name of this Monitor + */ + final String name; + + /** + * The associated TrafficShapingHandler + */ + private final AbstractTrafficShapingHandler trafficShapingHandler; + + /** + * Executor that will run the monitor + */ + private final EventExecutor executor; + /** + * Monitor created once in start() + */ + private Runnable monitor; + /** + * used in stop() to cancel the timer + */ + private volatile ScheduledFuture<?> scheduledFuture; + + /** + * Is Monitor active + */ + AtomicBoolean monitorActive = new AtomicBoolean(); + + /** + * Class to implement monitoring at fix delay + * + */ + private static class TrafficMonitoringTask implements Runnable { + /** + * The associated TrafficShapingHandler + */ + private final AbstractTrafficShapingHandler trafficShapingHandler1; + + /** + * The associated TrafficCounter + */ + private final TrafficCounter counter; + + /** + * @param trafficShapingHandler The parent handler to which this task needs to callback to for accounting + * @param counter The parent TrafficCounter that we need to reset the statistics for + */ + protected TrafficMonitoringTask( + AbstractTrafficShapingHandler trafficShapingHandler, + TrafficCounter counter) { + trafficShapingHandler1 = trafficShapingHandler; + this.counter = counter; + } + + @Override + public void run() { + if (!counter.monitorActive.get()) { + return; + } + long endTime = System.currentTimeMillis(); + counter.resetAccounting(endTime); + if (trafficShapingHandler1 != null) { + trafficShapingHandler1.doAccounting(counter); + } + counter.scheduledFuture = counter.executor.schedule(this, counter.checkInterval.get(), + TimeUnit.MILLISECONDS); + } + } + + /** + * Start the monitoring process + */ + public void start() { + synchronized (lastTime) { + if (monitorActive.get()) { + return; + } + lastTime.set(System.currentTimeMillis()); + if (checkInterval.get() > 0) { + monitorActive.set(true); + monitor = new TrafficMonitoringTask(trafficShapingHandler, this); + scheduledFuture = + executor.schedule(monitor, checkInterval.get(), TimeUnit.MILLISECONDS); + } + } + } + + /** + * Stop the monitoring process + */ + public void stop() { + synchronized (lastTime) { + if (!monitorActive.get()) { + return; + } + monitorActive.set(false); + resetAccounting(System.currentTimeMillis()); + if (trafficShapingHandler != null) { + trafficShapingHandler.doAccounting(this); + } + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + } + } + } + + /** + * Reset the accounting on Read and Write + * + * @param newLastTime the millisecond unix timestamp that we should be considered up-to-date for + */ + void resetAccounting(long newLastTime) { + synchronized (lastTime) { + long interval = newLastTime - lastTime.getAndSet(newLastTime); + if (interval == 0) { + // nothing to do + return; + } + lastReadBytes = currentReadBytes.getAndSet(0); + lastWrittenBytes = currentWrittenBytes.getAndSet(0); + lastReadThroughput = lastReadBytes / interval * 1000; + // nb byte / checkInterval in ms * 1000 (1s) + lastWriteThroughput = lastWrittenBytes / interval * 1000; + // nb byte / checkInterval in ms * 1000 (1s) + } + } + + /** + * Constructor with the {@link AbstractTrafficShapingHandler} that hosts it, the Timer to use, its + * name, the checkInterval between two computations in millisecond + * @param trafficShapingHandler the associated AbstractTrafficShapingHandler + * @param executor the underlying executor service for scheduling checks + * @param name the name given to this monitor + * @param checkInterval the checkInterval in millisecond between two computations + */ + public TrafficCounter(AbstractTrafficShapingHandler trafficShapingHandler, + EventExecutor executor, String name, long checkInterval) { + this.trafficShapingHandler = trafficShapingHandler; + this.executor = executor; + this.name = name; + lastCumulativeTime = System.currentTimeMillis(); + configure(checkInterval); + } + + /** + * Change checkInterval between two computations in millisecond + * + * @param newcheckInterval The new check interval (in milliseconds) + */ + public void configure(long newcheckInterval) { + long newInterval = (newcheckInterval / 10) * 10; + if (checkInterval.get() != newInterval) { + checkInterval.set(newInterval); + if (newInterval <= 0) { + stop(); + // No more active monitoring + lastTime.set(System.currentTimeMillis()); + } else { + // Start if necessary + start(); + } + } + } + + /** + * Computes counters for Read. + * + * @param recv + * the size in bytes to read + */ + void bytesRecvFlowControl(long recv) { + currentReadBytes.addAndGet(recv); + cumulativeReadBytes.addAndGet(recv); + } + + /** + * Computes counters for Write. + * + * @param write + * the size in bytes to write + */ + void bytesWriteFlowControl(long write) { + currentWrittenBytes.addAndGet(write); + cumulativeWrittenBytes.addAndGet(write); + } + + /** + * + * @return the current checkInterval between two computations of traffic counter + * in millisecond + */ + public long getCheckInterval() { + return checkInterval.get(); + } + + /** + * + * @return the Read Throughput in bytes/s computes in the last check interval + */ + public long getLastReadThroughput() { + return lastReadThroughput; + } + + /** + * + * @return the Write Throughput in bytes/s computes in the last check interval + */ + public long getLastWriteThroughput() { + return lastWriteThroughput; + } + + /** + * + * @return the number of bytes read during the last check Interval + */ + public long getLastReadBytes() { + return lastReadBytes; + } + + /** + * + * @return the number of bytes written during the last check Interval + */ + public long getLastWrittenBytes() { + return lastWrittenBytes; + } + + /** + * + * @return the current number of bytes read since the last checkInterval + */ + public long getCurrentReadBytes() { + return currentReadBytes.get(); + } + + /** + * + * @return the current number of bytes written since the last check Interval + */ + public long getCurrentWrittenBytes() { + return currentWrittenBytes.get(); + } + + /** + * @return the Time in millisecond of the last check as of System.currentTimeMillis() + */ + public long getLastTime() { + return lastTime.get(); + } + + /** + * @return the cumulativeWrittenBytes + */ + public long getCumulativeWrittenBytes() { + return cumulativeWrittenBytes.get(); + } + + /** + * @return the cumulativeReadBytes + */ + public long getCumulativeReadBytes() { + return cumulativeReadBytes.get(); + } + + /** + * @return the lastCumulativeTime in millisecond as of System.currentTimeMillis() + * when the cumulative counters were reset to 0. + */ + public long getLastCumulativeTime() { + return lastCumulativeTime; + } + + /** + * Reset both read and written cumulative bytes counters and the associated time. + */ + public void resetCumulativeTime() { + lastCumulativeTime = System.currentTimeMillis(); + cumulativeReadBytes.set(0); + cumulativeWrittenBytes.set(0); + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * String information + */ + @Override + public String toString() { + return "Monitor " + name + " Current Speed Read: " + + (lastReadThroughput >> 10) + " KB/s, Write: " + + (lastWriteThroughput >> 10) + " KB/s Current Read: " + + (currentReadBytes.get() >> 10) + " KB Current Write: " + + (currentWrittenBytes.get() >> 10) + " KB"; + } +} diff --git a/handler/src/main/java/io/netty/handler/traffic/package-info.java b/handler/src/main/java/io/netty/handler/traffic/package-info.java new file mode 100644 index 00000000000..44123fbb1d0 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/traffic/package-info.java @@ -0,0 +1,59 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +/** + * Implementation of a Traffic Shaping Handler and Dynamic Statistics. + * + * <p>The main goal of this package is to allow you to shape the traffic (bandwidth limitation), + * but also to get statistics on how many bytes are read or written. Both functions can + * be active or inactive (traffic or statistics).</p> + * + * <p>Two classes implement this behavior: + * <ul> + * <li> <tt>{@link TrafficCounter}</tt>: this class implements the counters needed by the handlers. + * It can be accessed to get some extra information like the read or write bytes since last check, the read and write + * bandwidth from last check...</li> + * + * <li> <tt>{@link AbstractTrafficShapingHandler}</tt>: this abstract class implements the kernel + * of traffic shaping. It could be extended to fit your needs. Two classes are proposed as default + * implementations: see {@link ChannelTrafficShapingHandler} and see {@link GlobalTrafficShapingHandler} + * respectively for Channel traffic shaping and Global traffic shaping.</li> + * </ul></p> + * + * <p>Both inbound and outbound traffic can be shaped independently. This is done by either passing in + * the desired limiting values to the constructors of both the Channel and Global traffic shaping handlers, + * or by calling the <tt>configure</tt> method on the {@link AbstractTrafficShapingHandler}. A value of + * 0 for either parameter indicates that there should be no limitation. This allows you to monitor the + * incoming and outgoing traffic without shaping.</p> + * + * <p>To activate or deactivate the statistics, you can adjust the delay to a low (suggested not less than 200ms + * for efficiency reasons) or a high value (let say 24H in millisecond is huge enough to not get the problem) + * or even using <tt>0</tt> which means no computation will be done.</p> + * + * <p>If you want to do anything with these statistics, just override the <tt>doAccounting</tt> method.<br> + * This interval can be changed either from the method <tt>configure</tt> in {@link AbstractTrafficShapingHandler} + * or directly using the method <tt>configure</tt> of {@link TrafficCounter}.</p> + * + * <p>Note that a new {@link ChannelTrafficShapingHandler} must be created for each new channel, + * but only one {@link GlobalTrafficShapingHandler} must be created for all channels.</p> + * + * <p>Note also that you can create different GlobalTrafficShapingHandler if you want to separate classes of + * channels (for instance either from business point of view or from bind address point of view).</p> + * + * @apiviz.exclude ^java\.lang\. + */ +package io.netty.handler.traffic; +
null
train
train
2012-12-23T19:24:20
"2012-10-29T05:55:57Z"
phoenix
val
netty/netty/561_912
netty/netty
netty/netty/561
netty/netty/912
[ "timestamp(timedelta=64.0, similarity=0.940854927279281)" ]
7755a8267415ab9d8b432e87dab4397e14553880
a2350718824d8badf227e178096ca0453211209f
[ "@danbim you are working on it ?\n", "\"Unfortunately\" I'm on holidays, so no. I'll try to do it next week. Is that fine with you guys?\n", "Sure!\n\nSent from my iPhone. Excuse any typos....\n\nAm 11.09.2012 um 11:57 schrieb Daniel Bimschas [email protected]:\n\n> \"Unfortunately\" I'm on holidays, so no. I'll try to do it next week. Is that fine with you guys?\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "@danbim Any help I could provide on this issue?\n", "Was done via c094abad7b14fb16827b13e5671665753be9ecad\n" ]
[ "Can you update to 2013 ?\n", "Can you update to 2013 ?\n", "Javadocs please :)\n", "Javadocs to all the methods following please :)\n", "These must be volatile ...\n", "Can you update to 2013 ?\n", "Can you update to 2013 ?\n", "Can you update to 2013 ?\n", "Can you update to 2013 ?\n", "I think this should be removed... no ?\n" ]
"2013-01-09T13:01:28Z"
[ "feature" ]
Port the RXTX transport
Now that the core API got pretty stable, it's good time to port the RXTX transport to the new API.
[ "example/pom.xml", "pom.xml" ]
[ "example/pom.xml", "example/src/main/java/io/netty/example/rxtx/RxtxClient.java", "example/src/main/java/io/netty/example/rxtx/RxtxClientHandler.java", "pom.xml", "transport-rxtx/pom.xml", "transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannel.java", "transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelConfig.java", "transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelOptions.java", "transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxDeviceAddress.java", "transport-rxtx/src/main/java/io/netty/transport/rxtx/package-info.java" ]
[]
diff --git a/example/pom.xml b/example/pom.xml index 24c22d7e502..8416c11ad66 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -75,6 +75,11 @@ <artifactId>netty-transport-udt</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>netty-transport-rxtx</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/example/src/main/java/io/netty/example/rxtx/RxtxClient.java b/example/src/main/java/io/netty/example/rxtx/RxtxClient.java new file mode 100644 index 00000000000..5ce89de457b --- /dev/null +++ b/example/src/main/java/io/netty/example/rxtx/RxtxClient.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.rxtx; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.socket.oio.OioEventLoopGroup; +import io.netty.handler.codec.LineBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; +import io.netty.handler.codec.string.StringEncoder; +import io.netty.transport.rxtx.RxtxChannel; +import io.netty.transport.rxtx.RxtxDeviceAddress; + +/** + * Sends one message to a serial device + */ +public class RxtxClient { + + public static void main(String[] args) throws Exception { + Bootstrap b = new Bootstrap(); + try { + b.group(new OioEventLoopGroup()) + .channel(RxtxChannel.class) + .remoteAddress(new RxtxDeviceAddress("/dev/ttyUSB0")) + .handler(new ChannelInitializer<RxtxChannel>() { + @Override + public void initChannel(RxtxChannel ch) throws Exception { + ch.pipeline().addLast( + new LineBasedFrameDecoder(32768), + new StringEncoder(), + new StringDecoder(), + new RxtxClientHandler() + ); + } + }); + + ChannelFuture f = b.connect().sync(); + + f.channel().closeFuture().sync(); + } finally { + b.shutdown(); + } + } +} diff --git a/example/src/main/java/io/netty/example/rxtx/RxtxClientHandler.java b/example/src/main/java/io/netty/example/rxtx/RxtxClientHandler.java new file mode 100644 index 00000000000..6cf07c77c09 --- /dev/null +++ b/example/src/main/java/io/netty/example/rxtx/RxtxClientHandler.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.rxtx; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundMessageHandlerAdapter; + +public class RxtxClientHandler extends ChannelInboundMessageHandlerAdapter<String> { + + @Override + public void channelActive(ChannelHandlerContext ctx) { + ctx.write("AT\n"); + } + + @Override + protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception { + if ("OK".equals(msg)) { + System.out.println("Serial port responded to AT"); + } + else { + System.out.println("Serial port responded with not-OK: " + msg); + } + ctx.close(); + } +} diff --git a/pom.xml b/pom.xml index ea635cef218..4651ba63d20 100644 --- a/pom.xml +++ b/pom.xml @@ -79,6 +79,7 @@ <module>codec-http</module> <module>codec-socks</module> <module>transport</module> + <module>transport-rxtx</module> <module>transport-sctp</module> <module>transport-udt</module> <module>handler</module> @@ -106,6 +107,12 @@ <version>2.4.1</version> </dependency> + <dependency> + <groupId>org.rxtx</groupId> + <artifactId>rxtx</artifactId> + <version>2.1.7</version> + </dependency> + <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> diff --git a/transport-rxtx/pom.xml b/transport-rxtx/pom.xml new file mode 100644 index 00000000000..71e46bec3f2 --- /dev/null +++ b/transport-rxtx/pom.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ Copyright 2013 The Netty Project + ~ + ~ The Netty Project licenses this file to you under the Apache License, + ~ version 2.0 (the "License"); you may not use this file except in compliance + ~ with the License. You may obtain a copy of the License at: + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, software + ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + ~ License for the specific language governing permissions and limitations + ~ under the License. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>io.netty</groupId> + <artifactId>netty-parent</artifactId> + <version>4.0.0.Beta1-SNAPSHOT</version> + </parent> + + <artifactId>netty-transport-rxtx</artifactId> + <packaging>jar</packaging> + + <name>Netty/RXTX Transport</name> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>netty-buffer</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>netty-codec</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>netty-transport</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.rxtx</groupId> + <artifactId>rxtx</artifactId> + </dependency> + </dependencies> + +</project> + diff --git a/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannel.java b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannel.java new file mode 100644 index 00000000000..263023697a4 --- /dev/null +++ b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannel.java @@ -0,0 +1,177 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.transport.rxtx; + +import static io.netty.transport.rxtx.RxtxChannelOptions.*; + +import io.netty.buffer.BufType; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelConfig; +import io.netty.channel.ChannelMetadata; +import io.netty.channel.socket.oio.AbstractOioByteChannel; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.nio.channels.NotYetConnectedException; + +import gnu.io.CommPort; +import gnu.io.CommPortIdentifier; +import gnu.io.SerialPort; + +/** + * A channel to a serial device using the RXTX library. + */ +public class RxtxChannel extends AbstractOioByteChannel { + private static final ChannelMetadata METADATA = new ChannelMetadata(BufType.BYTE, true); + + private final ChannelConfig config; + + private RxtxDeviceAddress deviceAddress; + private SerialPort serialPort; + private InputStream in; + private OutputStream out; + + public RxtxChannel() { + super(null, null); + + config = new RxtxChannelConfig(this); + } + + @Override + public ChannelConfig config() { + return config; + } + + @Override + public ChannelMetadata metadata() { + return METADATA; + } + + @Override + public boolean isOpen() { + return true; + } + + @Override + public boolean isActive() { + return in != null && out != null; + } + + @Override + protected int available() { + try { + return in.available(); + } catch (IOException e) { + return 0; + } + } + + @Override + protected int doReadBytes(ByteBuf buf) throws Exception { + try { + return buf.writeBytes(in, buf.writableBytes()); + } catch (SocketTimeoutException e) { + return 0; + } + } + + @Override + protected void doWriteBytes(ByteBuf buf) throws Exception { + if (out == null) { + throw new NotYetConnectedException(); + } + buf.readBytes(out, buf.readableBytes()); + } + + @Override + protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { + final CommPortIdentifier cpi = + CommPortIdentifier.getPortIdentifier(((RxtxDeviceAddress)remoteAddress).getDeviceAddress()); + final CommPort commPort = cpi.open(this.getClass().getName(), 1000); + + deviceAddress = (RxtxDeviceAddress) remoteAddress; + + serialPort = (SerialPort) commPort; + serialPort.setSerialPortParams( + config().getOption(BAUD_RATE), + config().getOption(DATA_BITS).getValue(), + config().getOption(STOP_BITS).getValue(), + config().getOption(PARITY_BIT).getValue() + ); + serialPort.setDTR(config().getOption(DTR)); + serialPort.setRTS(config().getOption(RTS)); + + out = serialPort.getOutputStream(); + in = serialPort.getInputStream(); + } + + @Override + protected SocketAddress localAddress0() { + return null; + } + + @Override + protected SocketAddress remoteAddress0() { + return deviceAddress; + } + + @Override + protected void doBind(SocketAddress localAddress) throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected void doDisconnect() throws Exception { + doClose(); + } + + @Override + protected void doClose() throws Exception { + IOException ex = null; + + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + ex = e; + } + + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + ex = e; + } + + if (serialPort != null) { + serialPort.removeEventListener(); + serialPort.close(); + } + + in = null; + out = null; + serialPort = null; + + if (ex != null) { + throw ex; + } + } +} diff --git a/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelConfig.java b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelConfig.java new file mode 100644 index 00000000000..44417198bf9 --- /dev/null +++ b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelConfig.java @@ -0,0 +1,319 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.transport.rxtx; + +import static io.netty.transport.rxtx.RxtxChannelOptions.*; + +import io.netty.channel.ChannelOption; +import io.netty.channel.DefaultChannelConfig; + +import java.util.Map; + +import gnu.io.SerialPort; + +/** + * A configuration class for RXTX device connections. + */ +public class RxtxChannelConfig extends DefaultChannelConfig { + + public enum Stopbits { + /** + * 1 stop bit will be sent at the end of every character + */ + STOPBITS_1(SerialPort.STOPBITS_1), + /** + * 2 stop bits will be sent at the end of every character + */ + STOPBITS_2(SerialPort.STOPBITS_2), + /** + * 1.5 stop bits will be sent at the end of every character + */ + STOPBITS_1_5(SerialPort.STOPBITS_1_5); + + private final int value; + + Stopbits(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static Stopbits ofValue(int value) { + for (Stopbits stopbit : Stopbits.values()) { + if (stopbit.value == value) { + return stopbit; + } + } + throw new IllegalArgumentException("Unknown value for Stopbits: " + value + "."); + } + } + + public enum Databits { + /** + * 5 data bits will be used for each character (ie. Baudot code) + */ + DATABITS_5(SerialPort.DATABITS_5), + /** + * 6 data bits will be used for each character + */ + DATABITS_6(SerialPort.DATABITS_6), + /** + * 7 data bits will be used for each character (ie. ASCII) + */ + DATABITS_7(SerialPort.DATABITS_7), + /** + * 8 data bits will be used for each character (ie. binary data) + */ + DATABITS_8(SerialPort.DATABITS_8); + + private final int value; + + Databits(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static Databits ofValue(int value) { + for (Databits databit : Databits.values()) { + if (databit.value == value) { + return databit; + } + } + throw new IllegalArgumentException("Unknown value for Databits: " + value + "."); + } + } + + public enum Paritybit { + /** + * No parity bit will be sent with each data character at all + */ + NONE(SerialPort.PARITY_NONE), + /** + * An odd parity bit will be sent with each data character, ie. will be set + * to 1 if the data character contains an even number of bits set to 1. + */ + ODD(SerialPort.PARITY_ODD), + /** + * An even parity bit will be sent with each data character, ie. will be set + * to 1 if the data character contains an odd number of bits set to 1. + */ + EVEN(SerialPort.PARITY_EVEN), + /** + * A mark parity bit (ie. always 1) will be sent with each data character + */ + MARK(SerialPort.PARITY_MARK), + /** + * A space parity bit (ie. always 0) will be sent with each data character + */ + SPACE(SerialPort.PARITY_SPACE); + + private final int value; + + Paritybit(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static Paritybit ofValue(int value) { + for (Paritybit paritybit : Paritybit.values()) { + if (paritybit.value == value) { + return paritybit; + } + } + throw new IllegalArgumentException("Unknown value for paritybit: " + value + "."); + } + } + + private volatile int baudrate = 115200; + + private volatile boolean dtr; + + private volatile boolean rts; + + private volatile Stopbits stopbits = Stopbits.STOPBITS_1; + + private volatile Databits databits = Databits.DATABITS_8; + + private volatile Paritybit paritybit = Paritybit.NONE; + + public RxtxChannelConfig(RxtxChannel channel) { + super(channel); + } + + @Override + public Map<ChannelOption<?>, Object> getOptions() { + return getOptions(super.getOptions(), + BAUD_RATE, DTR, RTS, STOP_BITS, DATA_BITS, PARITY_BIT); + } + + @SuppressWarnings("unchecked") + @Override + public <T> T getOption(ChannelOption<T> option) { + if (option == BAUD_RATE) { + return (T) Integer.valueOf(getBaudrate()); + } + if (option == DTR) { + return (T) Boolean.valueOf(isDtr()); + } + if (option == RTS) { + return (T) Boolean.valueOf(isRts()); + } + if (option == STOP_BITS) { + return (T) getStopbits(); + } + if (option == DATA_BITS) { + return (T) getDatabits(); + } + if (option == PARITY_BIT) { + return (T) getParitybit(); + } + + return super.getOption(option); + } + + @Override + public <T> boolean setOption(ChannelOption<T> option, T value) { + validate(option, value); + + if (option == BAUD_RATE) { + setBaudrate((Integer) value); + } else if (option == DTR) { + setDtr((Boolean) value); + } else if (option == RTS) { + setRts((Boolean) value); + } else if (option == STOP_BITS) { + setStopbits((Stopbits) value); + } else if (option == DATA_BITS) { + setDatabits((Databits) value); + } else if (option == PARITY_BIT) { + setParitybit((Paritybit) value); + } else { + return super.setOption(option, value); + } + + return true; + } + + /** + * Sets the baud rate (ie. bits per second) for communication with the serial device. + * The baud rate will include bits for framing (in the form of stop bits and parity), + * such that the effective data rate will be lower than this value. + * + * @param baudrate The baud rate (in bits per second) + */ + public void setBaudrate(final int baudrate) { + this.baudrate = baudrate; + } + + /** + * Sets the number of stop bits to include at the end of every character to aid the + * serial device in synchronising with the data. + * + * @param stopbits The number of stop bits to use + */ + public void setStopbits(final Stopbits stopbits) { + this.stopbits = stopbits; + } + + /** + * Sets the number of data bits to use to make up each character sent to the serial + * device. + * + * @param databits The number of data bits to use + */ + public void setDatabits(final Databits databits) { + this.databits = databits; + } + + /** + * Sets the type of parity bit to be used when communicating with the serial device. + * + * @param paritybit The type of parity bit to be used + */ + public void setParitybit(final Paritybit paritybit) { + this.paritybit = paritybit; + } + + /** + * @return The configured baud rate, defaulting to 115200 if unset + */ + public int getBaudrate() { + return baudrate; + } + + /** + * @return The configured stop bits, defaulting to {@link Stopbits#STOPBITS_1} if unset + */ + public Stopbits getStopbits() { + return stopbits; + } + + /** + * @return The configured data bits, defaulting to {@link Databits#DATABITS_8} if unset + */ + public Databits getDatabits() { + return databits; + } + + /** + * @return The configured parity bit, defaulting to {@link Paritybit#NONE} if unset + */ + public Paritybit getParitybit() { + return paritybit; + } + + /** + * @return true if the serial device should support the Data Terminal Ready signal + */ + public boolean isDtr() { + return dtr; + } + + /** + * Sets whether the serial device supports the Data Terminal Ready signal, used for + * flow control + * + * @param dtr true if DTR is supported, false otherwise + */ + public void setDtr(final boolean dtr) { + this.dtr = dtr; + } + + /** + * @return true if the serial device should support the Ready to Send signal + */ + public boolean isRts() { + return rts; + } + + /** + * Sets whether the serial device supports the Request To Send signal, used for flow + * control + * + * @param rts true if RTS is supported, false otherwise + */ + public void setRts(final boolean rts) { + this.rts = rts; + } +} diff --git a/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelOptions.java b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelOptions.java new file mode 100644 index 00000000000..ff2b928cd74 --- /dev/null +++ b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxChannelOptions.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.transport.rxtx; + +import io.netty.channel.ChannelOption; +import io.netty.transport.rxtx.RxtxChannelConfig.Databits; +import io.netty.transport.rxtx.RxtxChannelConfig.Paritybit; +import io.netty.transport.rxtx.RxtxChannelConfig.Stopbits; + +/** + * Options for configuring a serial port connection + */ +public final class RxtxChannelOptions { + public static final ChannelOption<Integer> BAUD_RATE = + new ChannelOption<Integer>("BAUD_RATE"); + + public static final ChannelOption<Boolean> DTR = + new ChannelOption<Boolean>("DTR"); + + public static final ChannelOption<Boolean> RTS = + new ChannelOption<Boolean>("RTS"); + + public static final ChannelOption<Stopbits> STOP_BITS = + new ChannelOption<Stopbits>("STOP_BITS"); + + public static final ChannelOption<Databits> DATA_BITS = + new ChannelOption<Databits>("DATA_BITS"); + + public static final ChannelOption<Paritybit> PARITY_BIT = + new ChannelOption<Paritybit>("PARITY_BIT"); + + private RxtxChannelOptions() {} +} diff --git a/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxDeviceAddress.java b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxDeviceAddress.java new file mode 100644 index 00000000000..d1db101436f --- /dev/null +++ b/transport-rxtx/src/main/java/io/netty/transport/rxtx/RxtxDeviceAddress.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.transport.rxtx; + +import java.net.SocketAddress; + +/** + * A {@link SocketAddress} subclass to wrap the serial port address of a RXTX + * device (e.g. COM1, /dev/ttyUSB0). + */ +public class RxtxDeviceAddress extends SocketAddress { + + private static final long serialVersionUID = -2907820090993709523L; + + private final String deviceAddress; + + /** + * Creates a RxtxDeviceAddress representing the address of the serial port. + * + * @param deviceAddress the address of the device (e.g. COM1, /dev/ttyUSB0, ...) + */ + public RxtxDeviceAddress(String deviceAddress) { + this.deviceAddress = deviceAddress; + } + + /** + * @return The serial port address of the device (e.g. COM1, /dev/ttyUSB0, ...) + */ + public String getDeviceAddress() { + return deviceAddress; + } +} diff --git a/transport-rxtx/src/main/java/io/netty/transport/rxtx/package-info.java b/transport-rxtx/src/main/java/io/netty/transport/rxtx/package-info.java new file mode 100644 index 00000000000..98223e759ea --- /dev/null +++ b/transport-rxtx/src/main/java/io/netty/transport/rxtx/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +/** + * A serial and parallel port communication transport based on <a href="http://rxtx.qbang.org/">RXTX</a>. + */ +package io.netty.transport.rxtx;
null
test
train
2013-01-09T13:29:41
"2012-08-24T09:00:21Z"
trustin
val
netty/netty/952_953
netty/netty
netty/netty/952
netty/netty/953
[ "timestamp(timedelta=62.0, similarity=0.8670852673075325)" ]
4dd462d0b501d15ec5b1adba2438d9d2a3c106cb
3c01f59fad61277491ee2d7853d98c3f0b917b17
[]
[]
"2013-01-18T07:22:16Z"
[ "improvement", "feature" ]
Allow to switch to single decoding mode
In our *Decoder implementation we always try to decode as many messages as possible. This is the best performance wise but is sometimes problematic. Especially when you are about to do a protocol upgrade and so will replace the decoder. To fix this we should provide a way to switch to only decode one message per inboundBuffferUpdated(..) call. This will also fix #864.
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java", "codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java", "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java", "codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java", "codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java", "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java", "codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java index 040399d3991..6cb8768e10d 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java @@ -173,6 +173,8 @@ public ChannelFuture handshake(Channel channel, final ChannelPromise promise) { headers.set(Names.CONTENT_LENGTH, key3.length); request.data().writeBytes(key3); + channel.pipeline().get(HttpResponseDecoder.class).setSingleDecode(true); + ChannelFuture future = channel.write(request); future.addListener(new ChannelFutureListener() { @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java index f2ce512e8d4..118a281ef40 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java @@ -152,6 +152,8 @@ public ChannelFuture handshake(Channel channel, final ChannelPromise promise) { headers.add(customHeaders); } + channel.pipeline().get(HttpResponseDecoder.class).setSingleDecode(true); + ChannelFuture future = channel.write(request); future.addListener(new ChannelFutureListener() { @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java index 21bf020744d..cb227a25b09 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java @@ -152,6 +152,8 @@ public ChannelFuture handshake(Channel channel, final ChannelPromise promise) { headers.add(customHeaders); } + channel.pipeline().get(HttpResponseDecoder.class).setSingleDecode(true); + ChannelFuture future = channel.write(request); future.addListener(new ChannelFutureListener() { @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java index 55ac1bf38e3..b5adbe6eb28 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java @@ -152,6 +152,8 @@ public ChannelFuture handshake(Channel channel, final ChannelPromise promise) { headers.add(customHeaders); } + channel.pipeline().get(HttpResponseDecoder.class).setSingleDecode(true); + ChannelFuture future = channel.write(request); future.addListener(new ChannelFutureListener() { @Override diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java b/codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java index 334bcb12e5b..31a3cf7e3ee 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToByteDecoder.java @@ -44,6 +44,28 @@ */ public abstract class ByteToByteDecoder extends ChannelInboundByteHandlerAdapter { + private volatile boolean singleDecode; + + /** + * If set then only one message is decoded on each {@link #inboundBufferUpdated(ChannelHandlerContext)} call. + * This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. + * + * Default is {@code false} as this has performance impacts. + */ + public void setSingleDecode(boolean singleDecode) { + this.singleDecode = singleDecode; + } + + /** + * If {@code true} then only one message is decoded on each + * {@link #inboundBufferUpdated(ChannelHandlerContext)} call. + * + * Default is {@code false} as this has performance impacts. + */ + public boolean isSingleDecode() { + return singleDecode; + } + @Override public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception { callDecode(ctx, in, ctx.nextInboundByteBuffer()); @@ -91,7 +113,7 @@ private void callDecode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) { ctx.fireExceptionCaught(new DecoderException(t)); } } - if (oldInSize == in.readableBytes()) { + if (oldInSize == in.readableBytes() || isSingleDecode()) { break; } } diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java index b32b095f572..d82e8c6b23e 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java @@ -44,6 +44,28 @@ public abstract class ByteToMessageDecoder private ChannelHandlerContext ctx; + private volatile boolean singleDecode; + + /** + * If set then only one message is decoded on each {@link #inboundBufferUpdated(ChannelHandlerContext)} call. + * This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. + * + * Default is {@code false} as this has performance impacts. + */ + public void setSingleDecode(boolean singleDecode) { + this.singleDecode = singleDecode; + } + + /** + * If {@code true} then only one message is decoded on each + * {@link #inboundBufferUpdated(ChannelHandlerContext)} call. + * + * Default is {@code false} as this has performance impacts. + */ + public boolean isSingleDecode() { + return singleDecode; + } + @Override public void beforeAdd(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; @@ -109,6 +131,9 @@ protected void callDecode(ChannelHandlerContext ctx) { if (ChannelHandlerUtil.unfoldAndAdd(ctx, o, true)) { decoded = true; + if (isSingleDecode()) { + break; + } } else { break; } diff --git a/codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java b/codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java index 02743758d42..76bc1a04003 100644 --- a/codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ReplayingDecoder.java @@ -432,6 +432,9 @@ protected void callDecode(ChannelHandlerContext ctx) { // A successful decode if (ChannelHandlerUtil.unfoldAndAdd(ctx, result, true)) { decoded = true; + if (isSingleDecode()) { + break; + } } } catch (Throwable t) { if (decoded) {
null
val
train
2013-01-18T07:08:11
"2013-01-18T07:19:45Z"
normanmaurer
val
netty/netty/1100_1102
netty/netty
netty/netty/1100
netty/netty/1102
[ "timestamp(timedelta=61.0, similarity=0.8802064381510787)" ]
d4d01ba52c8c4c57f53386ae6e6505f91349772d
23a098c1f8e3962ad5f198f437a67f7a824287d1
[ "@justinsb thanks again for your fix.. I did adjust it a bit and merged it + deployed it to the snapshot repository.\n\nCould you please test with the snapshot: \nhttps://oss.sonatype.org/content/repositories/snapshots/io/netty/netty-all/4.0.0.Beta3-SNAPSHOT/netty-all-4.0.0.Beta3-20130228.104616-2.jar\n", "Thanks; works. The commitset did \"break\" a lot of the JavaDocs etc, but that's merely a cosmetic issue.\n", "This issue has been fixed by #1102.\n" ]
[ "This change doesn't look right... Can you explain ?\n", "This change is not necessary..\n", "Obviously you know better than me, but here's my understanding...\n\nIn Netty 4, all HTTP transfers are \"chunked\" in the Netty 3 sense. They all comprise a HttpResponse, 0 or more HttpContent messages, then HttpLastContent.\n\nWe're trying to tell SPDY if it's the final frame of the stream; the correct way to do that is to check for instanceof HttpLastContent. That's done in the encode() function (which calls this function).\n\n(There is now a potentially missed optimization, in that we'll always send a SPDY data frame, even if it's empty, but I'm focusing on getting things working again first!)\n", "I think we can probably delete the call to release() entirely, but without the change I get this error thrown when the SPDY connection is closed:\n\nio.netty.channel.NoSuchBufferException: the handler 'spdySessionHandler' has no inbound byte buffer; it does not implement ChannelInboundByteHandler.\n at io.netty.channel.DefaultChannelHandlerContext.inboundByteBuffer(DefaultChannelHandlerContext.java:450)\n at io.netty.handler.codec.spdy.SpdySessionHandler.freeInboundBuffer(SpdySessionHandler.java:95)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer0(DefaultChannelHandlerContext.java:1473)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer(DefaultChannelHandlerContext.java:1456)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer0(DefaultChannelHandlerContext.java:1483)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer(DefaultChannelHandlerContext.java:1456)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer0(DefaultChannelHandlerContext.java:1483)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer(DefaultChannelHandlerContext.java:1456)\n at io.netty.channel.DefaultChannelHandlerContext.invokeFreeInboundBuffer0(DefaultChannelHandlerContext.java:1483)\n at io.netty.channel.DefaultChannelHandlerContext.access$3100(DefaultChannelHandlerContext.java:38)\n at io.netty.channel.DefaultChannelHandlerContext$21.run(DefaultChannelHandlerContext.java:1462)\n at io.netty.channel.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:259)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:305)\n at io.netty.channel.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:110)\n at java.lang.Thread.run(Thread.java:722)\n", "I have used this change and my spdyserver (using netty4) worked ! But without this change my spdyserver did not responded the request ,there is no SYN_REPLY. \n", "char1st: Glad it works for someone else as well!\n\nnormanmaurer: ...or if you're asking why currentStreamId wasn't getting set before, if the reply wasn't transfer-encoding chunked, then I don't know. I think that was a bug?\n", "ok know why.. it must be ctx.inboundMessageBuffer().release() ... I will incoperate this into the fix of you..\n" ]
"2013-02-27T23:39:10Z"
[ "defect" ]
SPDY codec broken in 4.0.0.Beta1
Commit 238e03f75bf7d73b22b475f6f070223857613cd2 broke SPDY; in that commit method() was renamed getMethod(). However, it looks like all occurences of method in strings were also changed to getMethod. This broke the METHOD constant in Spdy2HttpNames et al I think the refactoring also accidentally changed a bunch of javadocs which shouldn't have been changed.
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java index 7afa1555902..6ab424cf22a 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHeaders.java @@ -108,9 +108,9 @@ public static final class HttpNames { */ public static final String HOST = ":host"; /** - * {@code ":getMethod"} + * {@code ":method"} */ - public static final String METHOD = ":getMethod"; + public static final String METHOD = ":method"; /** * {@code ":path"} */ @@ -120,9 +120,9 @@ public static final class HttpNames { */ public static final String SCHEME = ":scheme"; /** - * {@code ":getStatus"} + * {@code ":status"} */ - public static final String STATUS = ":getStatus"; + public static final String STATUS = ":status"; /** * {@code ":version"} */ @@ -136,17 +136,17 @@ private HttpNames() { } */ public static final class Spdy2HttpNames { /** - * {@code "getMethod"} + * {@code "method"} */ - public static final String METHOD = "getMethod"; + public static final String METHOD = "method"; /** * {@code "scheme"} */ public static final String SCHEME = "scheme"; /** - * {@code "getStatus"} + * {@code "status"} */ - public static final String STATUS = "getStatus"; + public static final String STATUS = "status"; /** * {@code "url"} */ @@ -231,7 +231,7 @@ public static void setHost(SpdyHeaderBlock block, String host) { } /** - * Removes the HTTP getMethod header. + * Removes the HTTP method header. */ public static void removeMethod(int spdyVersion, SpdyHeaderBlock block) { if (spdyVersion < 3) { @@ -242,7 +242,7 @@ public static void removeMethod(int spdyVersion, SpdyHeaderBlock block) { } /** - * Returns the {@link HttpMethod} represented by the HTTP getMethod header. + * Returns the {@link HttpMethod} represented by the HTTP method header. */ public static HttpMethod getMethod(int spdyVersion, SpdyHeaderBlock block) { try { @@ -257,7 +257,7 @@ public static HttpMethod getMethod(int spdyVersion, SpdyHeaderBlock block) { } /** - * Sets the HTTP getMethod header. + * Sets the HTTP method header. */ public static void setMethod(int spdyVersion, SpdyHeaderBlock block, HttpMethod method) { if (spdyVersion < 3) { @@ -301,7 +301,7 @@ public static void setScheme(int spdyVersion, SpdyHeaderBlock block, String sche } /** - * Removes the HTTP response getStatus header. + * Removes the HTTP response status header. */ public static void removeStatus(int spdyVersion, SpdyHeaderBlock block) { if (spdyVersion < 3) { @@ -312,7 +312,7 @@ public static void removeStatus(int spdyVersion, SpdyHeaderBlock block) { } /** - * Returns the {@link HttpResponseStatus} represented by the HTTP response getStatus header. + * Returns the {@link HttpResponseStatus} represented by the HTTP response status header. */ public static HttpResponseStatus getStatus(int spdyVersion, SpdyHeaderBlock block) { try { @@ -341,7 +341,7 @@ public static HttpResponseStatus getStatus(int spdyVersion, SpdyHeaderBlock bloc } /** - * Sets the HTTP response getStatus header. + * Sets the HTTP response status header. */ public static void setStatus(int spdyVersion, SpdyHeaderBlock block, HttpResponseStatus status) { if (spdyVersion < 3) { diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java index 28d7acfecdd..6a00be5b823 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java @@ -142,11 +142,16 @@ public SpdyHttpEncoder(int version) { protected Object encode(ChannelHandlerContext ctx, HttpObject msg) throws Exception { List<Object> out = new ArrayList<Object>(); + + boolean valid = false; + if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpRequest); out.add(spdySynStreamFrame); + + valid = true; } if (msg instanceof HttpResponse) { @@ -158,6 +163,8 @@ protected Object encode(ChannelHandlerContext ctx, HttpObject msg) throws Except SpdySynReplyFrame spdySynReplyFrame = createSynReplyFrame(httpResponse); out.add(spdySynReplyFrame); } + + valid = true; } if (msg instanceof HttpContent) { @@ -185,7 +192,11 @@ protected Object encode(ChannelHandlerContext ctx, HttpObject msg) throws Except } else { out.add(spdyDataFrame); } - } else { + + valid = true; + } + + if (!valid) { throw new UnsupportedMessageTypeException(msg); } @@ -255,8 +266,6 @@ private SpdySynStreamFrame createSynStreamFrame(HttpMessage httpMessage) private SpdySynReplyFrame createSynReplyFrame(HttpResponse httpResponse) throws Exception { - boolean chunked = HttpHeaders.isTransferEncodingChunked(httpResponse); - // Get the Stream-ID from the headers int streamID = SpdyHttpHeaders.getStreamId(httpResponse); SpdyHttpHeaders.removeStreamId(httpResponse); @@ -279,10 +288,8 @@ private SpdySynReplyFrame createSynReplyFrame(HttpResponse httpResponse) spdySynReplyFrame.headers().add(entry.getKey(), entry.getValue()); } - if (chunked) { - currentStreamId = streamID; - spdySynReplyFrame.setLast(false); - } + currentStreamId = streamID; + spdySynReplyFrame.setLast(false); return spdySynReplyFrame; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java index 52e59a57c10..a57437c6e2a 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionHandler.java @@ -92,7 +92,9 @@ public MessageBuf<Object> newInboundBuffer(ChannelHandlerContext ctx) throws Exc @Override public void freeInboundBuffer(ChannelHandlerContext ctx) throws Exception { - ctx.inboundByteBuffer().release(); + if (ctx.hasInboundByteBuffer()) { + ctx.inboundByteBuffer().release(); + } } @Override
null
train
train
2013-02-28T00:19:25
"2013-02-27T22:06:34Z"
justinsb
val
netty/netty/1138_1146
netty/netty
netty/netty/1138
netty/netty/1146
[ "timestamp(timedelta=90374.0, similarity=0.9142520246612053)" ]
a49c1047f50f31c25d94392e1f4e902d7e808b0c
315493bfff83d4687ff8be929993e7aa22dcac80
[ "@kryptonics411 sounds nice.. pull-req welcome :)\n", "yeah,your are right,the decoder should be update,but I think they are so busy now~:P\n", "It's already fixed thanks to user contrubution.\n" ]
[]
"2013-03-12T13:03:31Z"
[]
ProtobufDecoder should be upgraded to take advantage of protobuf 2.5 features
From protobuf 2.5 release notes: "Added Parser to parse directly into messages without a Builder. For example, Foo foo = Foo.getParser().ParseFrom(input); Using Parser is ~25% faster than using Builder to parse messages." see FastProtobufDecoder: https://code.google.com/p/protobuf-rpc-pro/issues/detail?id=19#c4
[ "pom.xml", "src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java" ]
[ "pom.xml", "src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java" ]
[]
diff --git a/pom.xml b/pom.xml index f1ffa4bada2..a669eeda8c1 100644 --- a/pom.xml +++ b/pom.xml @@ -84,7 +84,7 @@ <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> - <version>2.4.1</version> + <version>2.5.0</version> <scope>compile</scope> <optional>true</optional> </dependency> diff --git a/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java b/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java index 257c33d9041..0f3d619b047 100644 --- a/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java +++ b/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.java @@ -66,7 +66,20 @@ */ @Sharable public class ProtobufDecoder extends OneToOneDecoder { + private static final boolean HAS_PARSER; + static { + boolean hasParser = false; + try { + // MessageLite.getParsetForType() is not available until protobuf 2.5.0. + MessageLite.class.getDeclaredMethod("getParserForType"); + hasParser = true; + } catch (Throwable t) { + // Ignore + } + + HAS_PARSER = hasParser; + } private final MessageLite prototype; private final ExtensionRegistry extensionRegistry; @@ -93,22 +106,30 @@ protected Object decode( } ChannelBuffer buf = (ChannelBuffer) msg; - if (buf.hasArray()) { - final int offset = buf.readerIndex(); - if (extensionRegistry == null) { - return prototype.newBuilderForType().mergeFrom( - buf.array(), buf.arrayOffset() + offset, buf.readableBytes()).build(); - } else { - return prototype.newBuilderForType().mergeFrom( - buf.array(), buf.arrayOffset() + offset, buf.readableBytes(), extensionRegistry).build(); + final byte[] array; + final int offset; + final int length = buf.readableBytes(); + + if (buf.hasArray()){ + array = buf.array(); + offset = buf.arrayOffset() + buf.readerIndex(); + }else { + array = new byte[length]; + buf.getBytes(buf.readerIndex(),array,0,length); + offset = 0; + } + + if (extensionRegistry == null){ + if(HAS_PARSER){ + return prototype.getParserForType().parseFrom(array,offset,length); + }else{ + return prototype.newBuilderForType().mergeFrom(array,offset,length).build(); } - } else { - if (extensionRegistry == null) { - return prototype.newBuilderForType().mergeFrom( - new ChannelBufferInputStream((ChannelBuffer) msg)).build(); - } else { - return prototype.newBuilderForType().mergeFrom( - new ChannelBufferInputStream((ChannelBuffer) msg), extensionRegistry).build(); + }else { + if(HAS_PARSER){ + return prototype.getParserForType().parseFrom(array,offset,length,extensionRegistry); + }else{ + return prototype.newBuilderForType().mergeFrom(array,offset,length,extensionRegistry).build(); } } }
null
train
train
2013-03-11T01:54:35
"2013-03-09T20:12:20Z"
kryptonics411
val
netty/netty/1186_1190
netty/netty
netty/netty/1186
netty/netty/1190
[ "timestamp(timedelta=8351.0, similarity=0.8516756070893446)" ]
8fb80e91796e8567aca5e2b8244f853f8631217b
240d8e246243cc13ec231fbb381c3b694959cd55
[ "`Unpooled.wrappedBuffer(ByteBuffer)` should not fail even if a user specified a read-only buffer. However, it should return a different `ByteBuf` implementation than `UnpooledUnsafeDirectByteBuf` because it will make the read-only buffer writable.\n", "@trustin will you take care ?\n", "working on it....\n", "Fixed via #1190 \n" ]
[]
"2013-03-21T15:47:03Z"
[ "defect" ]
Is there a way to create a ByteBuf backed by a read-only ByteBuffer?
I'm mmaping a file (read-only), and would like to send it using Netty. When I do Unpooled.wrappedBuffer(myByteBuffer) Netty throws because of these lines in UnpooledUnsafeDirectByteBuf: ``` if (initialBuffer.isReadOnly()) { throw new IllegalArgumentException("initialBuffer is a read-only buffer."); } ``` I presume there's a reason for the isReadOnly() test, but I can't really see why it is a problem to have a read-only ByteBuf as long as I don't try to write to it (?)
[ "buffer/src/main/java/io/netty/buffer/Unpooled.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/ReadOnlyDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/Unpooled.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufTest.java", "buffer/src/test/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBufTest.java", "buffer/src/test/java/io/netty/buffer/UnpooledTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/ReadOnlyDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/ReadOnlyDirectByteBuf.java new file mode 100644 index 00000000000..b1b4d8b2124 --- /dev/null +++ b/buffer/src/main/java/io/netty/buffer/ReadOnlyDirectByteBuf.java @@ -0,0 +1,327 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.buffer; + +import io.netty.util.ResourceLeak; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + + +/** + * Read-only ByteBuf which wraps a read-only direct ByteBuffer. + */ +class ReadOnlyDirectByteBuf extends AbstractReferenceCountedByteBuf { + private final ResourceLeak leak = leakDetector.open(this); + + protected final ByteBuffer buffer; + private final ByteBufAllocator allocator; + private ByteBuffer tmpNioBuf; + + public ReadOnlyDirectByteBuf(ByteBufAllocator allocator, ByteBuffer buffer) { + super(buffer.remaining()); + if (!buffer.isDirect()) { + throw new IllegalArgumentException("buffer must be readOnly"); + } + this.allocator = allocator; + this.buffer = buffer.slice().order(ByteOrder.BIG_ENDIAN); + writerIndex(buffer.limit()); + } + + @Override + protected void deallocate() { + leak.close(); + } + + @Override + public byte getByte(int index) { + ensureAccessible(); + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return buffer.get(index); + } + + @Override + public short getShort(int index) { + ensureAccessible(); + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getUnsignedMedium(int index) { + ensureAccessible(); + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | getByte(index + 2) & 0xff; + } + + @Override + public int getInt(int index) { + ensureAccessible(); + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + ensureAccessible(); + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else if (dst.nioBufferCount() > 0) { + for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { + int bbLen = bb.remaining(); + getBytes(index, bb); + index += bbLen; + } + } else { + dst.setBytes(dstIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.length); + if (dst == null) { + throw new NullPointerException("dst"); + } + if (dstIndex < 0 || dstIndex > dst.length - length) { + throw new IndexOutOfBoundsException(String.format( + "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); + } + + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.get(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + checkIndex(index); + if (dst == null) { + throw new NullPointerException("dst"); + } + + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + bytesToCopy); + dst.put(tmpBuf); + return this; + } + + @Override + protected void _setByte(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setShort(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setMedium(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setInt(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setLong(int index, long value) { + throw new ReadOnlyBufferException(); + } + + @Override + public int capacity() { + return maxCapacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBufAllocator alloc() { + return allocator; + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public ByteBuf unwrap() { + return null; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + protected final ByteBuffer internalNioBuffer() { + ByteBuffer tmpNioBuf = this.tmpNioBuf; + if (tmpNioBuf == null) { + this.tmpNioBuf = tmpNioBuf = buffer.duplicate(); + } + return tmpNioBuf; + } + + @Override + public ByteBuf copy(int index, int length) { + ensureAccessible(); + ByteBuffer src; + try { + src = (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } catch (IllegalArgumentException e) { + throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); + } + + ByteBuffer dst = ByteBuffer.allocateDirect(length); + dst.put(src); + dst.order(order()); + dst.clear(); + return new UnpooledDirectByteBuf(alloc(), dst, maxCapacity()); + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + ensureAccessible(); + if (index == 0 && length == capacity()) { + return buffer.duplicate(); + } else { + return ((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)).slice(); + } + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public byte[] array() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + public int arrayOffset() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + public boolean hasMemoryAddress() { + return false; + } + + @Override + public long memoryAddress() { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuf suspendIntermediaryDeallocations() { + return this; + } + + @Override + public ByteBuf resumeIntermediaryDeallocations() { + return this; + } +} diff --git a/buffer/src/main/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBuf.java new file mode 100644 index 00000000000..1607a6006bd --- /dev/null +++ b/buffer/src/main/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBuf.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.buffer; + + +import io.netty.util.internal.PlatformDependent; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + + + +/** + * Read-only ByteBuf which wraps a read-only direct ByteBuffer and use unsafe for best performance. + */ +final class ReadOnlyUnsafeDirectByteBuf extends ReadOnlyDirectByteBuf { + private static final boolean NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + private final long memoryAddress; + + public ReadOnlyUnsafeDirectByteBuf(ByteBufAllocator allocator, ByteBuffer buffer) { + super(allocator, buffer); + memoryAddress = PlatformDependent.directBufferAddress(buffer); + } + + @Override + protected byte _getByte(int index) { + return PlatformDependent.getByte(addr(index)); + } + + @Override + protected short _getShort(int index) { + short v = PlatformDependent.getShort(addr(index)); + return NATIVE_ORDER? v : Short.reverseBytes(v); + } + + @Override + protected int _getUnsignedMedium(int index) { + long addr = addr(index); + return (PlatformDependent.getByte(addr) & 0xff) << 16 | + (PlatformDependent.getByte(addr + 1) & 0xff) << 8 | + PlatformDependent.getByte(addr + 2) & 0xff; + } + + @Override + protected int _getInt(int index) { + int v = PlatformDependent.getInt(addr(index)); + return NATIVE_ORDER? v : Integer.reverseBytes(v); + } + + @Override + protected long _getLong(int index) { + long v = PlatformDependent.getLong(addr(index)); + return NATIVE_ORDER? v : Long.reverseBytes(v); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkIndex(index, length); + if (dst == null) { + throw new NullPointerException("dst"); + } + if (dstIndex < 0 || dstIndex > dst.capacity() - length) { + throw new IndexOutOfBoundsException("dstIndex: " + dstIndex); + } + + if (dst.hasMemoryAddress()) { + PlatformDependent.copyMemory(addr(index), dst.memoryAddress() + dstIndex, length); + } else if (dst.hasArray()) { + PlatformDependent.copyMemory(addr(index), dst.array(), dst.arrayOffset() + dstIndex, length); + } else { + dst.setBytes(dstIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkIndex(index, length); + if (dst == null) { + throw new NullPointerException("dst"); + } + if (dstIndex < 0 || dstIndex > dst.length - length) { + throw new IndexOutOfBoundsException(String.format( + "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); + } + + if (length != 0) { + PlatformDependent.copyMemory(addr(index), dst, dstIndex, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + checkIndex(index); + if (dst == null) { + throw new NullPointerException("dst"); + } + + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + bytesToCopy); + dst.put(tmpBuf); + return this; + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + UnpooledUnsafeDirectByteBuf copy = (UnpooledUnsafeDirectByteBuf) alloc().directBuffer(length, maxCapacity()); + if (length != 0) { + PlatformDependent.copyMemory(addr(index), copy.addr(0), length); + copy.setIndex(0, length); + } + return copy; + } + + private long addr(int index) { + return memoryAddress + index; + } +} diff --git a/buffer/src/main/java/io/netty/buffer/Unpooled.java b/buffer/src/main/java/io/netty/buffer/Unpooled.java index 77303d4eb93..8a0f7d9565b 100644 --- a/buffer/src/main/java/io/netty/buffer/Unpooled.java +++ b/buffer/src/main/java/io/netty/buffer/Unpooled.java @@ -223,9 +223,17 @@ public static ByteBuf wrappedBuffer(ByteBuffer buffer) { buffer.arrayOffset() + buffer.position(), buffer.remaining()).order(buffer.order()); } else if (PlatformDependent.hasUnsafe()) { - return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining()); + if (buffer.isReadOnly()) { + return new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer); + } else { + return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining()); + } } else { - return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); + if (buffer.isReadOnly()) { + return new ReadOnlyDirectByteBuf(ALLOC, buffer); + } else { + return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); + } } } diff --git a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java index a0510dbf20f..815922dfc04 100644 --- a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java @@ -493,7 +493,7 @@ public ByteBuf unwrap() { return null; } - private long addr(int index) { + long addr(int index) { return memoryAddress + index; } }
diff --git a/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufTest.java b/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufTest.java new file mode 100644 index 00000000000..5c8fc9d7c08 --- /dev/null +++ b/buffer/src/test/java/io/netty/buffer/ReadOnlyDirectByteBufTest.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.buffer; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ReadOnlyBufferException; + +public class ReadOnlyDirectByteBufTest { + + protected ByteBuf buffer(ByteBuffer buffer) { + return new ReadOnlyDirectByteBuf(UnpooledByteBufAllocator.DEFAULT, buffer.asReadOnlyBuffer()); + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructWithNotDirectBuffer() { + buffer(ByteBuffer.allocate(1)); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetByte() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setByte(0, 1); + } + + + @Test(expected = ReadOnlyBufferException.class) + public void testSetInt() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setInt(0, 1); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetShort() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setShort(0, 1); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetMedium() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setMedium(0, 1); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetLong() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setLong(0, 1); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaArray() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setBytes(0, "test".getBytes()); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaBuffer() { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setBytes(0, Unpooled.copyInt(1)); + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaStream() throws IOException { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2); + } + + @Test + public void testGetReadByte() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(2).put(new byte[]{(byte) 1, (byte) 2}).flip()).asReadOnlyBuffer()); + Assert.assertEquals(1, buf.getByte(0)); + Assert.assertEquals(2, buf.getByte(1)); + + Assert.assertEquals(1, buf.readByte()); + Assert.assertEquals(2, buf.readByte()); + Assert.assertFalse(buf.isReadable()); + } + + @Test + public void testGetReadInt() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); + Assert.assertEquals(1, buf.getInt(0)); + Assert.assertEquals(2, buf.getInt(4)); + + Assert.assertEquals(1, buf.readInt()); + Assert.assertEquals(2, buf.readInt()); + Assert.assertFalse(buf.isReadable()); + } + + + @Test + public void testGetReadShort() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(8).putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer()); + Assert.assertEquals(1, buf.getShort(0)); + Assert.assertEquals(2, buf.getShort(2)); + + Assert.assertEquals(1, buf.readShort()); + Assert.assertEquals(2, buf.readShort()); + Assert.assertFalse(buf.isReadable()); + } + + @Test + public void testGetReadLong() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + Assert.assertEquals(1, buf.getLong(0)); + Assert.assertEquals(2, buf.getLong(8)); + + Assert.assertEquals(1, buf.readLong()); + Assert.assertEquals(2, buf.readLong()); + Assert.assertFalse(buf.isReadable()); + } + + @Test + public void testCopy() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + Assert.assertEquals(buf, buf.copy()); + } + + @Test + public void testCopyWithOffset() { + ByteBuf buf = buffer(((ByteBuffer) ByteBuffer.allocateDirect(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + Assert.assertEquals(buf.slice(1, 9), buf.copy(1, 9)); + } +} diff --git a/buffer/src/test/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBufTest.java b/buffer/src/test/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBufTest.java new file mode 100644 index 00000000000..4ce322660ca --- /dev/null +++ b/buffer/src/test/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBufTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.buffer; + +import io.netty.util.internal.PlatformDependent; +import org.junit.BeforeClass; + +import java.nio.ByteBuffer; + +import static org.junit.Assume.assumeTrue; + +public class ReadOnlyUnsafeDirectByteBufTest extends ReadOnlyDirectByteBufTest { + + /** + * Needs unsafe to run + */ + @BeforeClass + public static void assumeConditions(){ + assumeTrue(PlatformDependent.hasUnsafe()); + } + + @Override + protected ByteBuf buffer(ByteBuffer buffer) { + return new ReadOnlyUnsafeDirectByteBuf(UnpooledByteBufAllocator.DEFAULT, buffer); + } +} diff --git a/buffer/src/test/java/io/netty/buffer/UnpooledTest.java b/buffer/src/test/java/io/netty/buffer/UnpooledTest.java index e53f2b33ef9..9f61c6533e2 100644 --- a/buffer/src/test/java/io/netty/buffer/UnpooledTest.java +++ b/buffer/src/test/java/io/netty/buffer/UnpooledTest.java @@ -570,4 +570,17 @@ public void testWrapBoolean() { assertEquals(0, Unpooled.copyBoolean(new boolean[0]).capacity()); } + + @Test + public void wrappedReadOnlyDirectBuffer() { + ByteBuffer buffer = ByteBuffer.allocateDirect(12); + for (int i = 0; i < 12; i++) { + buffer.put((byte) i); + } + buffer.flip(); + ByteBuf wrapped = wrappedBuffer(buffer.asReadOnlyBuffer()); + for (int i = 0; i < 12; i++) { + assertEquals((byte) i, wrapped.readByte()); + } + } }
train
train
2013-03-21T13:34:13
"2013-03-21T00:35:00Z"
justinsb
val
netty/netty/1202_1217
netty/netty
netty/netty/1202
netty/netty/1217
[ "timestamp(timedelta=100013.0, similarity=0.8897228510456948)" ]
c2cd99d90cde91d2dc91c21b8006fc947c4f5a67
a43f5349ad72abb12728eece77ec62784ae15b61
[ "@openaphid fixed.. thanks!\n" ]
[]
"2013-03-28T22:50:28Z"
[]
Minor issue in javadoc of ByteBuf
Inside the section of **NIO Buffers** (generated from master branch), I found it states following: ``` To determine if a buffer can be converted into an NIO buffer, use nioBuffer(). ``` Should `nioBufferCount()` be used here instead of `nioBuffer()`?
[ "buffer/src/main/java/io/netty/buffer/BufType.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java" ]
[ "buffer/src/main/java/io/netty/buffer/BufType.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java" ]
[]
diff --git a/buffer/src/main/java/io/netty/buffer/BufType.java b/buffer/src/main/java/io/netty/buffer/BufType.java index 2a82223a7e9..8b9ffd06740 100644 --- a/buffer/src/main/java/io/netty/buffer/BufType.java +++ b/buffer/src/main/java/io/netty/buffer/BufType.java @@ -20,7 +20,7 @@ */ public enum BufType { /** - * Operates one bytes. + * Operates on bytes. */ BYTE, diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java index b70c9e527ef..9987dc1f014 100755 --- a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java @@ -64,7 +64,7 @@ final class DefaultChannelHandlerContext extends DefaultAttributeMap implements // 'bridge' so that the two handlers access each other's buffer only via the bridges. // The content written into a bridge is flushed into the actual buffer by flushBridge(). // - // Note we use an AtomicReferenceFieldUpdater for atomic operations on these to safe memory. This will safe us + // Note we use an AtomicReferenceFieldUpdater for atomic operations on these to save memory. This will save us // 64 bytes per Bridge. @SuppressWarnings("UnusedDeclaration") private volatile MessageBridge inMsgBridge;
null
test
train
2013-03-28T21:49:36
"2013-03-24T03:22:43Z"
openaphid
val
netty/netty/1234_1235
netty/netty
netty/netty/1234
netty/netty/1235
[ "timestamp(timedelta=16.0, similarity=0.9477986483800093)" ]
7ee2adb5878b7261abf8ce5f3e7e977627ff8c84
a72d1bc2fc014edcc9b96d43caf68c8ed658885c
[ "If you kill `package-info.java` from tests, build will fail because of existing check style rule.\n", "well, this rule was not there before. lets kill it too :-)\n", "Or may be modify https://github.com/netty/netty-build/blob/master/src/main/resources/io/netty/checkstyle.xml#L25 to ignore `package-info.java` and remove them after that? \n", "one more idea: change test name space so there is no package split.\n\nthis is also required if we want run same tests in osgi.\n\nfor example: I needed to use different name space here:\n\nhttps://github.com/netty/netty/tree/master/transport-udt/src/main/java/io/netty/channel/udt\n\nhttps://github.com/netty/netty/tree/master/transport-udt/src/test/java/io/netty/test/udt\n\nin order to run these tests\n\nhttps://github.com/netty/netty/tree/master/testsuite-osgi/testsuite-osgi-exam\n", "re:\n\n```\nOr may be modify https://github.com/netty/netty-build/blob/master/src/main/resources/io/netty/checkstyle.xml#L25 to ignore package-info.java and remove them after that?\n```\n\nremoving is the easiest solution. do we need to keep them? \n\n@trustin @normanmaurer please comment.\n", "Another solution:\n\nCreate `suppressions.xml` in netty-build with content: https://gist.github.com/infynyxx/5303333\n\nAnd in parent pom.xml, under plugin `maven-checkstyle-plugin` enable:\n\n```\n<suppressionsLocation>io/netty/suppressions.xml</suppressionsLocation>\n```\n", "yes, this takes care of ckeckstyle. \n\nbut the underlying reason is still there: eclipse does not tolerate same class name in same package.\n\nexample:\n\nhttp://jira.codehaus.org/browse/SONAR-2444\n", "Once checkstyle is ignoring package-info.java in tests directory, we can\nremove them.\n\nOn Wed, Apr 3, 2013 at 1:46 PM, Andrei Pozolotin\[email protected]:\n\n> yes, this takes care of ckeckstyle.\n> \n> but the underlying reason is still there: eclipse does not tolerate same\n> class name in same package.\n> \n> example:\n> \n> http://jira.codehaus.org/browse/SONAR-2444\n> \n> —\n> Reply to this email directly or view it on GitHubhttps://github.com/netty/netty/issues/1234#issuecomment-15852145\n> .\n\n## \n\n-- Praj\n", "unless @trustin really needs them to be happy :-)\n", "That's true :)\n", "I think remove them in test packages is a no-brainer… so go for it!\n\nAm 03.04.2013 um 20:00 schrieb Prajwal Tuladhar [email protected]:\n\n> That's true :)\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "@normanmaurer please review\n" ]
[]
"2013-04-04T03:20:01Z"
[]
duplicate package-info.java errors in eclipse
see below possible work around 1) kill these files from *_/test/_ path 2) try to use package-info.html 3) try to use both package-info.html and package-info.java ``` Description Resource Path Location Type The type package-info is already defined package-info.java /netty-buffer/src/test/java/io/netty/buffer line 1 Java Problem The type package-info is already defined package-info.java /netty-codec-http/src/test/java/io/netty/handler/codec/http line 1 Java Problem The type package-info is already defined package-info.java /netty-codec-http/src/test/java/io/netty/handler/codec/http/multipart line 1 Java Problem The type package-info is already defined package-info.java /netty-codec-http/src/test/java/io/netty/handler/codec/http/websocketx line 1 Java Problem The type package-info is already defined package-info.java /netty-codec-http/src/test/java/io/netty/handler/codec/spdy line 1 Java Problem The type package-info is already defined package-info.java /netty-codec-socks/src/test/java/io/netty/handler/codec/socks line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec/bytes line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec/compression line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec/marshalling line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec/protobuf line 1 Java Problem The type package-info is already defined package-info.java /netty-codec/src/test/java/io/netty/handler/codec/serialization line 1 Java Problem The type package-info is already defined package-info.java /netty-common/src/test/java/io/netty/util line 1 Java Problem The type package-info is already defined package-info.java /netty-common/src/test/java/io/netty/util/internal line 1 Java Problem The type package-info is already defined package-info.java /netty-common/src/test/java/io/netty/util/internal/logging line 1 Java Problem The type package-info is already defined package-info.java /netty-handler/src/test/java/io/netty/handler/stream line 1 Java Problem The type package-info is already defined package-info.java /netty-testsuite-osgi-exam/src/test/java/io/netty/verify/osgi line 1 Java Problem The type package-info is already defined package-info.java /netty-testsuite-osgi-split/src/test/java/io/netty/verify/osgi line 1 Java Problem The type package-info is already defined package-info.java /netty-transport/src/test/java/io/netty/bootstrap line 1 Java Problem The type package-info is already defined package-info.java /netty-transport/src/test/java/io/netty/channel line 1 Java Problem The type package-info is already defined package-info.java /netty-transport/src/test/java/io/netty/channel/group line 1 Java Problem The type package-info is already defined package-info.java /netty-transport/src/test/java/io/netty/channel/local line 1 Java Problem The type package-info is already defined package-info.java /netty-transport/src/test/java/io/netty/channel/nio line 1 Java Problem ```
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index b1aab0aba36..be97bb753d8 100644 --- a/pom.xml +++ b/pom.xml @@ -369,7 +369,7 @@ <dependency> <groupId>${project.groupId}</groupId> <artifactId>netty-build</artifactId> - <version>18</version> + <version>19-SNAPSHOT</version> </dependency> </dependencies> </plugin>
diff --git a/buffer/src/test/java/io/netty/buffer/package-info.java b/buffer/src/test/java/io/netty/buffer/package-info.java deleted file mode 100644 index 4271c3f5c91..00000000000 --- a/buffer/src/test/java/io/netty/buffer/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Byte Buffer test classes - **/ - -package io.netty.buffer; diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/package-info.java b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/package-info.java deleted file mode 100644 index ef01b481477..00000000000 --- a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for HTTP multipart codec. - */ -package io.netty.handler.codec.http.multipart; diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/package-info.java b/codec-http/src/test/java/io/netty/handler/codec/http/package-info.java deleted file mode 100644 index f3545575a77..00000000000 --- a/codec-http/src/test/java/io/netty/handler/codec/http/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder, decoder and their related message types for HTTP. - */ -package io.netty.handler.codec.http; diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/package-info.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/package-info.java deleted file mode 100644 index 9fc5800a678..00000000000 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder, decoder, handshakers and their related message types for - * <a href="http://en.wikipedia.org/wiki/Web_Sockets">Web Socket</a> data frames. - */ -package io.netty.handler.codec.http.websocketx; diff --git a/codec-http/src/test/java/io/netty/handler/codec/spdy/package-info.java b/codec-http/src/test/java/io/netty/handler/codec/spdy/package-info.java deleted file mode 100644 index 966486d3f2a..00000000000 --- a/codec-http/src/test/java/io/netty/handler/codec/spdy/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder, decoder, session handler and their related message types for the SPDY protocol. - */ -package io.netty.handler.codec.spdy; diff --git a/codec-socks/src/test/java/io/netty/handler/codec/socks/package-info.java b/codec-socks/src/test/java/io/netty/handler/codec/socks/package-info.java deleted file mode 100644 index df685f46f31..00000000000 --- a/codec-socks/src/test/java/io/netty/handler/codec/socks/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder, decoder and their related message types for Socks. - */ -package io.netty.handler.codec.socks; diff --git a/codec/src/test/java/io/netty/handler/codec/bytes/package-info.java b/codec/src/test/java/io/netty/handler/codec/bytes/package-info.java deleted file mode 100644 index ca530361259..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/bytes/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder and decoder which transform an array of bytes into a - * {@link io.netty.buffer.ByteBuf} and vice versa. - */ -package io.netty.handler.codec.bytes; diff --git a/codec/src/test/java/io/netty/handler/codec/compression/package-info.java b/codec/src/test/java/io/netty/handler/codec/compression/package-info.java deleted file mode 100644 index af11948b60a..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/compression/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes encoder and decoder which compresses and decompresses {@link io.netty.buffer.ByteBuf}s - * in a compression format - */ -package io.netty.handler.codec.compression; diff --git a/codec/src/test/java/io/netty/handler/codec/marshalling/package-info.java b/codec/src/test/java/io/netty/handler/codec/marshalling/package-info.java deleted file mode 100644 index e7e08938cc1..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/marshalling/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for decoder and encoder which uses - * <a href="http://www.jboss.org/jbossmarshalling">JBoss Marshalling</a>. - */ -package io.netty.handler.codec.marshalling; diff --git a/codec/src/test/java/io/netty/handler/codec/package-info.java b/codec/src/test/java/io/netty/handler/codec/package-info.java deleted file mode 100644 index f7cf92edaf7..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for extensible decoder and its common implementations - */ -package io.netty.handler.codec; diff --git a/codec/src/test/java/io/netty/handler/codec/protobuf/package-info.java b/codec/src/test/java/io/netty/handler/codec/protobuf/package-info.java deleted file mode 100644 index b561895216e..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/protobuf/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder and decoder which transform a - * <a href="http://code.google.com/p/protobuf/">Google Protocol Buffers</a> - * {@link com.google.protobuf.Message} into a {@link io.netty.buffer.ByteBuf} - * and vice versa. - */ -package io.netty.handler.codec.protobuf; diff --git a/codec/src/test/java/io/netty/handler/codec/serialization/package-info.java b/codec/src/test/java/io/netty/handler/codec/serialization/package-info.java deleted file mode 100644 index 389f6dbebb3..00000000000 --- a/codec/src/test/java/io/netty/handler/codec/serialization/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for encoder, decoder and their compatibility stream implementations which - * transform a {@link java.io.Serializable} object into a byte buffer and - * vice versa. - */ -package io.netty.handler.codec.serialization; diff --git a/common/src/test/java/io/netty/util/internal/logging/package-info.java b/common/src/test/java/io/netty/util/internal/logging/package-info.java deleted file mode 100644 index 3538aad14a0..00000000000 --- a/common/src/test/java/io/netty/util/internal/logging/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Internal logging utility test classes - */ -package io.netty.util.internal.logging; diff --git a/common/src/test/java/io/netty/util/internal/package-info.java b/common/src/test/java/io/netty/util/internal/package-info.java deleted file mode 100644 index 1a63153f416..00000000000 --- a/common/src/test/java/io/netty/util/internal/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Utility internal test classes - */ -package io.netty.util.internal; diff --git a/common/src/test/java/io/netty/util/package-info.java b/common/src/test/java/io/netty/util/package-info.java deleted file mode 100644 index 371ab4c4c01..00000000000 --- a/common/src/test/java/io/netty/util/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Utility test classes - */ -package io.netty.util; diff --git a/handler/src/test/java/io/netty/handler/stream/package-info.java b/handler/src/test/java/io/netty/handler/stream/package-info.java deleted file mode 100644 index 72c2f2a4109..00000000000 --- a/handler/src/test/java/io/netty/handler/stream/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for stream package - */ -package io.netty.handler.stream; diff --git a/testsuite-osgi/testsuite-osgi-exam/src/test/java/io/netty/verify/osgi/package-info.java b/testsuite-osgi/testsuite-osgi-exam/src/test/java/io/netty/verify/osgi/package-info.java deleted file mode 100644 index 6ef91550a4c..00000000000 --- a/testsuite-osgi/testsuite-osgi-exam/src/test/java/io/netty/verify/osgi/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * OSGI verify compliance tests - */ -package io.netty.verify.osgi; diff --git a/testsuite-osgi/testsuite-osgi-split/src/test/java/io/netty/verify/osgi/package-info.java b/testsuite-osgi/testsuite-osgi-split/src/test/java/io/netty/verify/osgi/package-info.java deleted file mode 100644 index 57b701f6001..00000000000 --- a/testsuite-osgi/testsuite-osgi-split/src/test/java/io/netty/verify/osgi/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * OSGI placeholder - */ -package io.netty.verify.osgi; diff --git a/transport/src/test/java/io/netty/bootstrap/package-info.java b/transport/src/test/java/io/netty/bootstrap/package-info.java deleted file mode 100644 index 670d2ac62dd..00000000000 --- a/transport/src/test/java/io/netty/bootstrap/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for transport bootstrap - */ -package io.netty.bootstrap; diff --git a/transport/src/test/java/io/netty/channel/group/package-info.java b/transport/src/test/java/io/netty/channel/group/package-info.java deleted file mode 100644 index 84818504716..00000000000 --- a/transport/src/test/java/io/netty/channel/group/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for transport channel group - */ -package io.netty.channel.group; diff --git a/transport/src/test/java/io/netty/channel/local/package-info.java b/transport/src/test/java/io/netty/channel/local/package-info.java deleted file mode 100644 index 9cd900034b3..00000000000 --- a/transport/src/test/java/io/netty/channel/local/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for local transport channel - */ -package io.netty.channel.local; diff --git a/transport/src/test/java/io/netty/channel/nio/package-info.java b/transport/src/test/java/io/netty/channel/nio/package-info.java deleted file mode 100644 index cf80654c3e1..00000000000 --- a/transport/src/test/java/io/netty/channel/nio/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for NIO transport channel - */ -package io.netty.channel.nio; diff --git a/transport/src/test/java/io/netty/channel/package-info.java b/transport/src/test/java/io/netty/channel/package-info.java deleted file mode 100644 index ea5aea35bb7..00000000000 --- a/transport/src/test/java/io/netty/channel/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2013 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * Test classes for transport channel - */ -package io.netty.channel;
test
train
2013-04-03T18:52:57
"2013-04-03T17:11:15Z"
Andrei-Pozolotin
val
netty/netty/1228_1255
netty/netty
netty/netty/1228
netty/netty/1255
[ "timestamp(timedelta=129.0, similarity=0.8571149236625287)" ]
067a2af700b1cfa476a4bcf1f55071ccb178e25e
19fd684a2cc3e92f91a3239f3601fad3ee67aa7f
[ "Could anyone take a look a this one? It causes lots of web site to fail\n", "Sorry I'm quite busy… maybe you could issue a pull-req with a fix ?\n\nAm 08.04.2013 um 18:45 schrieb xhh11 [email protected]:\n\n> Could anyone take a look a this one? It causes lots of web site to fail\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Sorry but you point to XHTML, which is not HTML...\nSee http://www.w3.org/TR/REC-html40/types.html where name is expressed as:\n\n```\nID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (\"-\"), underscores (\"_\"), colons (\":\"), and periods (\".\").\n```\n\nAnd in http://www.w3.org/TR/xhtml1/diffs.html#diffs\nThere is the following indication:\n\n```\nDue to the fact that XHTML is an XML application, certain practices that were perfectly legal in SGML-based HTML 4 [HTML4] must be changed.\n```\n\nAnd for name and id:\n\n```\n4.2. Element and attribute names must be in lower case\nXHTML documents must use lower case for all HTML element and attribute names. This difference is necessary because XML is case-sensitive e.g. <li> and <LI> are different tags.\n```\n\nand\n\n```\n4.10. The elements with 'id' and 'name' attributes\n\nHTML 4 defined the name attribute for the elements a, applet, form, frame, iframe, img, and map. HTML 4 also introduced the id attribute. Both of these attributes are designed to be used as fragment identifiers.\n\nIn XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.\n\nNote that in XHTML 1.0, the name attribute of these elements is formally deprecated, and will be removed in a subsequent version of XHTML.\n```\n\nSo, if I am reading correctly, no \"space\" are allowed in name attribute.\n\nAm I wrong?\n", "You are right on HTML 4 spec. HTML 5 actually specifies: Attribute names must consist of one or more characters other than the space characters, U+0000 NULL, \"\"\", \"'\", \">\", \"/\", \"=\", the control characters, and any characters that are not defined by Unicode.\n\nBut the reality is that the specs are different and people are not strictly following specs. When Netty lib parses a form submission, the current strict implementation cannot handle some web sites that are not following the strict implementation. IMO, the Netty lib should leave the restriction to the apps that using Netty instead of making handling of those \"mis-formed\" web pages impossible.\n", "Hi Norman,\n\nThe fix is easy, just remove the name check code. I just want to make sure you guys agree on this.\n", "I'm not so happy to remove all those checks.\nBut anyway, maybe removing some could be useful as you said.\nAmong all items, are they some that really need to be out (taking into account that it will allow some bad things and could have some side effects on other code, not in Netty, but in application side since non conforment to HTML rules).\n\nI believe you asked at least for ' ' to be removed. Is there any other ?\nI would feel strange for instance if we removed the following ones (using (*) to note them):\n\n```\nswitch (c) {\n case '=': (*)\n case ',': (*)\n case ';': (*)\n case ' ':\n case '\\t':\n case '\\r': (*)\n case '\\n': (*)\n case '\\f': (*)\n case 0x0b: // Vertical tab\n throw new IllegalArgumentException(\n \"name contains one of the following prohibited characters: \" +\n \"=,; \\\\t\\\\r\\\\n\\\\v\\\\f: \" + name);\n```\n", "Another way would be to add a property to the configuration of the Http driver, in order to say: ignore bad characters in attribute name. WDYT ?\nHowever the difficulty would be to find where could be the best place for that configuration ?\nPutting it in HttpDataFactory could be the right solution but will force to create new constructors for all items with an extra argument to say: ignore those name checking.\n\nMy 2 cents ;-)\n", "As far as the application can decide what to do with the atypical names, it would be fine.\n\nThe options can be put into constructor of HttpPostRequestDecoder. An application either handle those strange names itself or just fail if the names don't follow specs. I don't think an application would need both.\n", "I've made a proposal to fix that issue.\nBut note however that I did not check it intensively (and I had to do this one through web since I've got some serious issues on my PC configuration). So please, before accepting it, someone has to check it.\nThe very same could be done for the other stream (3 ? ).\n", "I leave one comment that we feel from \"first at a glance\" fix proposal (not final one):\n- do you confirm that if disabled, all checking must be ignored (whatever ',', '=', ';', '\\n', ...) ?\n", "Yes. I see no reason why a web app just wants to get an Exception instead of the name/value pair that is inside the content. Maybe the checking functionality can be pull into a helper class/method. \n", "I don't see what you mean by helper class/method?\n=> Could you explain that point?\n\nI don't want to reopen the discussion, but for the reason for a web app to get an Exception, I think that in normal situation, it is preferable to get an exception than accepting wrong HTTP request/answer, in order to enforce the security, since most of the time, non conforming client/server should be considered as potential attacks.\n\nWhat we can propose, is all OR nothing, in a property to set within the DefaultHttpDataFactory. If disabled (not by default), then all checking MUST be done by the application, while it should have been done in the HTTP codec.\n\nTake for instance that someone implements badly SSL, would you accept that the codec will allow you to continue with the SSL connection, while it is not conform to the rules? I think not.\n\nHowever, if one have real need for that (and that the non conform client/server are out of control), then the application will have to handle all cases itself.\n\nMaybe we could also put the check code in a separate method in order to allow someone to check manually the correctness (while still done by default), but then useful for the application that disable this automatic checking.\n=> Is that the helper class/method you were talking about?\n", "Yes, I meant that user can get the name/value pair and then call something like isValidHTML4Name(String name) to verify if name is valid.\n\nThe situation I saw was that the existing browser and web server can all live with the \"bad\" names. As a network lib, we definitely want user to have the flexibility to do the same thing. \n\nAnyway, what you did is perfect for all needs. Thanks\n", "@trustin I think we can move this to CR3 ?\n", "I had a chance to read the specification today, and I guess you guys are confusing the name of types from the 'NAME' attribute in INPUT. The type of INPUT.NAME attribute is CDATA, which means the validation logic should be:\n\n> CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows:\n> - Replace character entities with characters,\n> - Ignore line feeds,\n> - Replace each carriage return or tab with a single space.\n> \n> User agents may ignore leading and trailing white space in CDATA attribute values (e.g., \" myval \" may be interpreted as \"myval\"). Authors should not declare attribute values with leading or trailing white space.\n> \n> For some HTML 4 attributes with CDATA attribute values, the specification imposes further constraints on the set of legal values for the attribute that may not be expressed by the DTD.\n> \n> Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence \"</\" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.\n", "Fixed both in 3 and master.\n", "Sorry Trustin but:\n\nIn chapter [6.2 SGML basic types] of http://www.w3.org/TR/REC-html40/types.html, the CDATA is restricted for ID and NAME as follow:\n\n> ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits \n> ([0-9]), hyphens (\"-\"), underscores (\"_\"), colons (\":\"), and periods (\".\").\n\nSo it might be not so simple... my 2 cents.\nCheers, \n", "No. The `ID` and `NAME` tokens here refers to the DTD types, not attributes. Also, I don't see anything that says `CDATA` must conform to `ID`/`NAME` rules.\n", "Yes, you're right! My misunderstanding... Thank you Trustin!\n" ]
[ "Do we have to disable the check code completely? Shouldn't the characters like `\\t`, `\\r`, `\\n`, `\\f`, `0x0b` be prohibited yet?\n", "Please keep the old signature and add a new one. We should probably set the default less strict.\n", "Please fill the Javadoc correctly or just leave it empty.\n", "The description of this method is not very informative. Please revise.\n", "Same applies to the subtypes.\n", "Why pass `false` rather than `this.checkBadName`?\n", "There are many similar issues in this pull request. Please fix them, too.\n", "On all others I am totally agree. I was doing it just to show what can be done, not really a final step (I should say it).\nOn this point, (and in other part of the code wher I put false also):\n- the checkBadName is only visible in DefaultHttpDataFactory, and I fell like unuseful to push this variable into each and every Data created.\n- since those \"copy\" methods will be called after the constructor was already called, we have the 2 following cases:\n a) checkBadName was true then checking it again on the very same name (getName() is called) is not useful\n b) checkBadName was false, then we must not check it (since it could break the checking rules)\n\nSo I believe that put false in \"copy\" methods is correct.\n", "On this one, I really would like that the user that asked this change specifies what to remove or not.\nAs I said in the ticket, I don't feel confortable with not checkink '=', ',', ';' and maybe '\\n', '\\r'.\nSo without answer, maybe we could make this by unchecking all, leaving the application with the responsability to check itself.\nBy default, all checking should be done, since it is the official way, even in HTML5.\n", "Could we ever make this pluggable so that a user can choose whatever naming rule he wants to enforce? Perhaps a user could pass a matcher when creating `HttpPostRequestDecoder`? The default could be the strictly RFC-conforming one.\n", "Yes it is still possible, but note that both HttpPostRequestDecoder and HttpPostRequestEncoder have the HattpDataFactory as argument, which should be setup to use (or not use) this RFC conforming rule, since this is where (HttpDataFactory) this rule has to be setup.\n\nWhen I wrote this helper method, I feel like a specific class should be setup (a new class helper) such that it can easily be reused, maybe in the DefaultHttpDataFactory class, or a new one (which name ?).\nNote that I'm not so happy that someone could implement a \"bad\" conforming service (contrary to any good practices in IT), so the reason to not make it \"so\" easy, and in particular not the default one. So putting this as an argument to the Encoder/Decoder as explicit argument is somehow not particularly intended.\n\nMoreovern put it in Encoder/Decoder will break the underlying implementation where the factory is responsible of the constructor (factory), while the encoder/decoder is not. It could lead to an heavy change (I did not take time however to see if it is particularly difficult or not).\n\nSo let me know what is your preference...\nCheers\n", "I prefer to:\n1. Add a matcher interface\n2. Add the matcher as a constructor parameter of `DefaultHttpDataFactory`\n3. Keep the old constructors of `DefaultHttpDataFactory` which conforms to the RFC strictly.\n", "OK, I agree since it is more \"adaptable\" then than just all or nothing.\nJust to ensure I have correctly understood (I'm so busy that I need to someone recheck, sorry ;-(\nYou want to have:\n1. the user can define his own Pattern p = Pattern.compile(\"xxx\");\n2. Then giving this Pattern p as argument to DefaultHttpDataFactory new constructor (keeping the one without extra argument, but removing the extra set methods and in particular this isValidHtml4Name method)\n3. By default, if no argument is given, the following Pattern will be compiled\n \n Pattern.compile(\"\\p{ASCII}&&[^=,;\\s]\");\n\nIs that correct?\nAlso, if you could check the pattern, since 4 eyes are better than one when playing with regex...\n(note that there is double '\\' but git show only one)\nIf I'm correct: \n- \\p{ASCII} => [\\x00-\\x7F] = c <= 127\n- &&[^=,;\\s] => substract '=', ',', ';', any \"space character\"\n\nCheers\n", "One more comment, while I tried to implement this option, I found out that I need to be able to pass this Pattern in every cases, and in particular in copy mode.\nWhile I don't think it is a good idea to \"copy\" the pattern in each and every item (data), due to memory overhead that it could imply, the only solution I figure out right now is to put this Pattern in a static variable.\n\nBut as it must be accessed by all and every part of the code, the change should then be as the following:\n1. Create an abstract class of the interface HttpDataFactory that will host this static Pattern variable, and nothing more.\n2. Change all access or definition to HttpDataFactory to the new AbstractHttpDataFactory, in order that this variable is visible, and moreover that someone implementing a new Factory will have to start from this abstract.\n\nIs that correct? Or do you have a better idea?\nI don't really like the \"static\" way, but I don't find a clear way to do that.\nOnce again, this is the \"copy\" function that brings the issue...\n", "Instead of a Pattern argument can't you just define an interface that has a function to match an individual character? something like:\n\nboolean isValidCharacter(char c)\n\nthat can be called by the loop and the exception thrown if it return false.\n", "I add one answer and one comment:\n1. isValidCharacter(char c) will be very very expensive in term of computation. In this codec various items are made to try to be as much as possible optimized (in particular, we allow mixed types of variable, in memory or on disk according to a size, and we try when possible to check arrays directly without getting bytes one by one). So putting this will lead to obviously a slow down in the overall process. So I feel like this is not a good idea. The pattern, even if costly too, should be faster than one by one check.\n2. On my \"pre\" test to make this Abstract class with static property Pattern, I must admit that, even if it is not as clean as I would like, it is really helpful, since:\n3. no more constructor with or without argument on each \"data\" to specify if we want to check and how the name W3C rule\n4. only the factory has those constructors (and those without a specific pattern will cause the pattern to be the standard one)\n5. In more than 90%, I feel like once someone decides to use a specific pattern (or the default one), he/she probably stick with this one for every implementation in one VM.\n\nSo while answering 90% of the case (one way used to verify the W3C conformity), there is still some cases where perhaps some people could want to have several web services in the same VM using different patterns. In this case, what could be done is to specify the \"less\" restrictive pattern for all, and then explicitely call an helper class (put on Data classes) that could check the name with a specific (maybe one shot) pattern given as parameter, thus allowing to check various levels of conformance.\n\nWDYT?\n", "Slightly confused as to the expense of a character at a time check given the for loop in the code below at line 46 which is already doing a character at a time check. Or are you suggesting that the function call itself is expensive?\n", "Ah, ok, I understand the confusion.\nCurrently yes, the code is one by one character, but however in the same \"method\" which tends to be optimized, compared to a method called each and every time (compare getByte() to getBytes(byte[]) then looping on array).\n\nHowever the remarks on going are more on the request from Trustin about using a Pattern instead of a method as currently implemented. Therefore, the code will look like:\n\n```\nif (! pattern.matcher(name).matches())\n```\n\ninstead of\n\n```\nif (! isValidHtml4Name(name)) \n```\n\nso replacing the method isValidHtml4Name by a call to a \"supposed to be\" more efficient way (pattern.matcher) and moreover more flexible for the user (he/she can implement the pattern he wants instead of the current logic which is all or nothing).\n\nSorry for the confusion...\n", "Which method is \"faster\" is hard to say as the JIT of course is very magical :)\n\nBut I'm not too concerned about that -- I'm more curious about your comment above:\n\n\"Change all access or definition to HttpDataFactory to the new AbstractHttpDataFactory, in order that this variable is visible, and moreover that someone implementing a new Factory will have to start from this abstract.\"\n\nsince wouldn't this break the existing API?\n", "To the breaking of API, the answer is yes and no:\n- yes: it will introduce a new Abstract class that is the first level of the Interface HttpDataFactory as the factory will have to include a \"static\" member : the pattern\n- no : except that, no other change (even less than in the current example which is fully compatible with the prior API already)\n\nSo from a strict point of view, yes, there is potential break. The only way I see to not introduce this change is to replace the interface HttpDataFactory by the Abstract class directly (keeping the very same name), but then lead to a change of \"implements\" to \"extends\".\n\nSo far, I'm not so happy about this change (as you understand, I try to find the best way, taking all advices).\nSo to resume;\n1. The current proposition does not change the API, but lack of \"control\" for the programmer, since the method is then \"all or nothing\".\n2. The next proposition (abstract class) allows more flexibility but could lead to an API change (minor but still).\n3. The next-next proposition would be to \"duplicate\" the pattern in each and every \"data\", by constructor addition, but in fact will lead to the very same kind of API break, since each \"data\" will have to extend their own constructor to accept such a pattern, and if none specified (default current constructor), they will have to rely on the \"static default pattern\" (especially the \"copy\" operation), which could lead to 2 optional issues:\n- either the default pattern is different to the default one specified by the user in the factory, and then could lead to misbehaviour\n- either we introduce again the abstract class (proposition 2) to host the current pattern (whatever the one from the user if specified, or the default one) and then we came back to the API issue of (2) (and moreover no interest of solution 3).\n\nI must admit that it is like the chicken and egg issue...\n" ]
"2013-04-08T23:08:18Z"
[ "defect" ]
AbstractHttpData is too restrict in name
When a html form input name includes space, an IllegalArgumentException will be thrown. However, in the specification, name is actually defined as CDATA. See http://www.w3.org/TR/xhtml1/dtds.html#dtdentry_xhtml1-transitional.dtd_input ``` protected AbstractHttpData(String name, Charset charset, long size) { if (name == null) { throw new NullPointerException("name"); } name = name.trim(); if (name.isEmpty()) { throw new IllegalArgumentException("empty name"); } for (int i = 0; i < name.length(); i ++) { char c = name.charAt(i); if (c > 127) { throw new IllegalArgumentException( "name contains non-ascii character: " + name); } // Check prohibited characters. switch (c) { case '=': case ',': case ';': case ' ': case '\t': case '\r': case '\n': case '\f': case 0x0b: // Vertical tab throw new IllegalArgumentException( "name contains one of the following prohibited characters: " + "=,; \\t\\r\\n\\v\\f: " + name); } } this.name = name; if (charset != null) { setCharset(charset); } definedSize = size; } ```
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpDataTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java index c854a719d23..6199b676f32 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractDiskHttpData.java @@ -38,8 +38,12 @@ public abstract class AbstractDiskHttpData extends AbstractHttpData { private boolean isRenamed; private FileChannel fileChannel; + protected AbstractDiskHttpData(String name, Charset charset, long size, boolean checkBadName) { + super(name, charset, size, checkBadName); + } + protected AbstractDiskHttpData(String name, Charset charset, long size) { - super(name, charset, size); + this(name, charset, size, false); } /** diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java index d80b57f735f..0066de9d743 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractHttpData.java @@ -35,19 +35,20 @@ public abstract class AbstractHttpData extends AbstractReferenceCounted implemen protected boolean completed; protected AbstractHttpData(String name, Charset charset, long size) { - if (name == null) { - throw new NullPointerException("name"); - } - name = name.trim(); - if (name.isEmpty()) { - throw new IllegalArgumentException("empty name"); - } + this(name, charset, size, false); + } + /** + * Convenient method to check if an attribute name respects the W3C rules + * (character are ASCII (less than 127) and no characters from "=,; \t\r\n\v\f:") + * @param name the attribute name to check + * @return True if the name is conform with the W3C rules + */ + public static boolean isValidHtml4Name(String name) { for (int i = 0; i < name.length(); i ++) { char c = name.charAt(i); if (c > 127) { - throw new IllegalArgumentException( - "name contains non-ascii character: " + name); + return false; } // Check prohibited characters. @@ -61,11 +62,25 @@ protected AbstractHttpData(String name, Charset charset, long size) { case '\n': case '\f': case 0x0b: // Vertical tab - throw new IllegalArgumentException( - "name contains one of the following prohibited characters: " + - "=,; \\t\\r\\n\\v\\f: " + name); + return false; } } + return true; + } + + protected AbstractHttpData(String name, Charset charset, long size, boolean checkBadName) { + if (name == null) { + throw new NullPointerException("name"); + } + name = name.trim(); + if (name.isEmpty()) { + throw new IllegalArgumentException("empty name"); + } + if (checkBadName && ! isValidHtml4Name(name)) { + throw new IllegalArgumentException( + "name contains non-ascii character or one of the following prohibited characters: " + + "=,; \\t\\r\\n\\v\\f: " + name); + } this.name = name; if (charset != null) { setCharset(charset); diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java index f3461d8f883..1c12a2269f5 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpData.java @@ -39,7 +39,11 @@ public abstract class AbstractMemoryHttpData extends AbstractHttpData { protected boolean isRenamed; protected AbstractMemoryHttpData(String name, Charset charset, long size) { - super(name, charset, size); + this(name, charset, size, false); + } + + protected AbstractMemoryHttpData(String name, Charset charset, long size, boolean checkBadName) { + super(name, charset, size, checkBadName); } @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java index 8f6f68e18b5..0ad8b01b6af 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java @@ -44,6 +44,11 @@ public class DefaultHttpDataFactory implements HttpDataFactory { private long minSize; + /** + * Default should check the correctness with W3c rules on attribute names + */ + private boolean checkBadName = true; + /** * Keep all HttpDatas until cleanAllHttpDatas() is called. */ @@ -78,6 +83,26 @@ public DefaultHttpDataFactory(long minSize) { this.minSize = minSize; } + /** + * @return True if the current Factory is checking the correctness of the attribute names regarding W3c rules + * which say character are ASCII (less than 127) and no characters from "=,; \t\r\n\v\f:" + */ + public boolean isCheckBadName() { + return checkBadName; + } + + /** + * Note that it is still possible to check later on manually using + * {@link AbstractHttpData}.isValidHtml4Name(String name) method + * + * @param checkBadName True to check if names conform to HTML definition ASCII (less than 127) + * and no characters from "=,; \t\r\n\v\f:", and False to ignore this check. + * + */ + public void setCheckBadName(boolean checkBadName) { + this.checkBadName = checkBadName; + } + /** * @return the associated list of Files for the request */ @@ -93,18 +118,18 @@ private List<HttpData> getList(HttpRequest request) { @Override public Attribute createAttribute(HttpRequest request, String name) { if (useDisk) { - Attribute attribute = new DiskAttribute(name); + Attribute attribute = new DiskAttribute(name, checkBadName); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } if (checkSize) { - Attribute attribute = new MixedAttribute(name, minSize); + Attribute attribute = new MixedAttribute(name, minSize, checkBadName); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } - return new MemoryAttribute(name); + return new MemoryAttribute(name, checkBadName); } @Override @@ -112,23 +137,23 @@ public Attribute createAttribute(HttpRequest request, String name, String value) if (useDisk) { Attribute attribute; try { - attribute = new DiskAttribute(name, value); + attribute = new DiskAttribute(name, value, checkBadName); } catch (IOException e) { // revert to Mixed mode - attribute = new MixedAttribute(name, value, minSize); + attribute = new MixedAttribute(name, value, minSize, checkBadName); } List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } if (checkSize) { - Attribute attribute = new MixedAttribute(name, value, minSize); + Attribute attribute = new MixedAttribute(name, value, minSize, checkBadName); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } try { - return new MemoryAttribute(name, value); + return new MemoryAttribute(name, value, checkBadName); } catch (IOException e) { throw new IllegalArgumentException(e); } @@ -140,20 +165,20 @@ public FileUpload createFileUpload(HttpRequest request, String name, String file long size) { if (useDisk) { FileUpload fileUpload = new DiskFileUpload(name, filename, contentType, - contentTransferEncoding, charset, size); + contentTransferEncoding, charset, size, checkBadName); List<HttpData> fileToDelete = getList(request); fileToDelete.add(fileUpload); return fileUpload; } if (checkSize) { FileUpload fileUpload = new MixedFileUpload(name, filename, contentType, - contentTransferEncoding, charset, size, minSize); + contentTransferEncoding, charset, size, minSize, checkBadName); List<HttpData> fileToDelete = getList(request); fileToDelete.add(fileUpload); return fileUpload; } return new MemoryFileUpload(name, filename, contentType, - contentTransferEncoding, charset, size); + contentTransferEncoding, charset, size, checkBadName); } @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java index ccb59bdfa3b..8b37e6b5d58 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java @@ -39,11 +39,19 @@ public class DiskAttribute extends AbstractDiskHttpData implements Attribute { * Constructor used for huge Attribute */ public DiskAttribute(String name) { - super(name, HttpConstants.DEFAULT_CHARSET, 0); + this(name, false); + } + + public DiskAttribute(String name, boolean checkBadName) { + super(name, HttpConstants.DEFAULT_CHARSET, 0, checkBadName); // Attribute have no default size } public DiskAttribute(String name, String value) throws IOException { - super(name, HttpConstants.DEFAULT_CHARSET, 0); // Attribute have no default size + this(name, value, false); + } + + public DiskAttribute(String name, String value, boolean checkBadName) throws IOException { + this(name, checkBadName); setValue(value); } @@ -142,7 +150,7 @@ protected String getPrefix() { @Override public Attribute copy() { - DiskAttribute attr = new DiskAttribute(getName()); + DiskAttribute attr = new DiskAttribute(getName(), false); attr.setCharset(getCharset()); ByteBuf content = data(); if (content != null) { diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java index 988bf955ede..df9c2d74255 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskFileUpload.java @@ -43,7 +43,12 @@ public class DiskFileUpload extends AbstractDiskHttpData implements FileUpload { public DiskFileUpload(String name, String filename, String contentType, String contentTransferEncoding, Charset charset, long size) { - super(name, charset, size); + this(name, filename, contentType, contentTransferEncoding, charset, size, false); + } + + public DiskFileUpload(String name, String filename, String contentType, + String contentTransferEncoding, Charset charset, long size, boolean checkBadName) { + super(name, charset, size, checkBadName); setFilename(filename); setContentType(contentType); setContentTransferEncoding(contentTransferEncoding); @@ -166,7 +171,7 @@ protected String getPrefix() { @Override public FileUpload copy() { DiskFileUpload upload = new DiskFileUpload(getName(), - getFilename(), getContentType(), getContentTransferEncoding(), getCharset(), size); + getFilename(), getContentType(), getContentTransferEncoding(), getCharset(), size, false); ByteBuf buf = data(); if (buf != null) { try { diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java index c22c26e5681..ed32a5ee713 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java @@ -29,11 +29,19 @@ public class MemoryAttribute extends AbstractMemoryHttpData implements Attribute { public MemoryAttribute(String name) { - super(name, HttpConstants.DEFAULT_CHARSET, 0); + this(name, false); + } + + public MemoryAttribute(String name, boolean checkBadName) { + super(name, HttpConstants.DEFAULT_CHARSET, 0, checkBadName); // Attribute have no default size } public MemoryAttribute(String name, String value) throws IOException { - super(name, HttpConstants.DEFAULT_CHARSET, 0); // Attribute have no default size + this(name, value, false); + } + + public MemoryAttribute(String name, String value, boolean checkBadName) throws IOException { + this(name, checkBadName); setValue(value); } @@ -103,7 +111,7 @@ public String toString() { @Override public Attribute copy() { - MemoryAttribute attr = new MemoryAttribute(getName()); + MemoryAttribute attr = new MemoryAttribute(getName(), false); attr.setCharset(getCharset()); ByteBuf content = data(); if (content != null) { diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java index d31d4e88ce1..e639f49e61f 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryFileUpload.java @@ -37,7 +37,12 @@ public class MemoryFileUpload extends AbstractMemoryHttpData implements FileUplo public MemoryFileUpload(String name, String filename, String contentType, String contentTransferEncoding, Charset charset, long size) { - super(name, charset, size); + this(name, filename, contentType, contentTransferEncoding, charset, size, false); + } + + public MemoryFileUpload(String name, String filename, String contentType, + String contentTransferEncoding, Charset charset, long size, boolean checkBadName) { + super(name, charset, size, checkBadName); setFilename(filename); setContentType(contentType); setContentTransferEncoding(contentTransferEncoding); @@ -132,7 +137,7 @@ public String toString() { @Override public FileUpload copy() { MemoryFileUpload upload = new MemoryFileUpload(getName(), getFilename(), getContentType(), - getContentTransferEncoding(), getCharset(), size); + getContentTransferEncoding(), getCharset(), size, false); ByteBuf buf = data(); if (buf != null) { try { diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java index f15a1ba4448..b173508fbf1 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java @@ -31,26 +31,34 @@ public class MixedAttribute implements Attribute { private final long limitSize; public MixedAttribute(String name, long limitSize) { + this(name, limitSize, false); + } + + public MixedAttribute(String name, long limitSize, boolean checkBadName) { this.limitSize = limitSize; - attribute = new MemoryAttribute(name); + attribute = new MemoryAttribute(name, checkBadName); } public MixedAttribute(String name, String value, long limitSize) { + this(name, value, limitSize, false); + } + + public MixedAttribute(String name, String value, long limitSize, boolean checkBadName) { this.limitSize = limitSize; if (value.length() > this.limitSize) { try { - attribute = new DiskAttribute(name, value); + attribute = new DiskAttribute(name, value, checkBadName); } catch (IOException e) { // revert to Memory mode try { - attribute = new MemoryAttribute(name, value); + attribute = new MemoryAttribute(name, value, checkBadName); } catch (IOException e1) { throw new IllegalArgumentException(e); } } } else { try { - attribute = new MemoryAttribute(name, value); + attribute = new MemoryAttribute(name, value, checkBadName); } catch (IOException e) { throw new IllegalArgumentException(e); } @@ -62,7 +70,7 @@ public void addContent(ByteBuf buffer, boolean last) throws IOException { if (attribute instanceof MemoryAttribute) { if (attribute.length() + buffer.readableBytes() > limitSize) { DiskAttribute diskAttribute = new DiskAttribute(attribute - .getName()); + .getName(), false); if (((MemoryAttribute) attribute).getByteBuf() != null) { diskAttribute.addContent(((MemoryAttribute) attribute) .getByteBuf(), false); @@ -133,7 +141,7 @@ public void setContent(ByteBuf buffer) throws IOException { if (buffer.readableBytes() > limitSize) { if (attribute instanceof MemoryAttribute) { // change to Disk - attribute = new DiskAttribute(attribute.getName()); + attribute = new DiskAttribute(attribute.getName(), false); } } attribute.setContent(buffer); @@ -144,7 +152,7 @@ public void setContent(File file) throws IOException { if (file.length() > limitSize) { if (attribute instanceof MemoryAttribute) { // change to Disk - attribute = new DiskAttribute(attribute.getName()); + attribute = new DiskAttribute(attribute.getName(), false); } } attribute.setContent(file); @@ -154,7 +162,7 @@ public void setContent(File file) throws IOException { public void setContent(InputStream inputStream) throws IOException { if (attribute instanceof MemoryAttribute) { // change to Disk even if we don't know the size - attribute = new DiskAttribute(attribute.getName()); + attribute = new DiskAttribute(attribute.getName(), false); } attribute.setContent(inputStream); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java index ee554df5b6e..bbaf58bff2b 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedFileUpload.java @@ -36,13 +36,20 @@ public class MixedFileUpload implements FileUpload { public MixedFileUpload(String name, String filename, String contentType, String contentTransferEncoding, Charset charset, long size, long limitSize) { + this(name, filename, contentType, contentTransferEncoding, charset, size, + limitSize, false); + } + + public MixedFileUpload(String name, String filename, String contentType, + String contentTransferEncoding, Charset charset, long size, + long limitSize, boolean checkBadName) { this.limitSize = limitSize; if (size > this.limitSize) { fileUpload = new DiskFileUpload(name, filename, contentType, - contentTransferEncoding, charset, size); + contentTransferEncoding, charset, size, checkBadName); } else { fileUpload = new MemoryFileUpload(name, filename, contentType, - contentTransferEncoding, charset, size); + contentTransferEncoding, charset, size, checkBadName); } definedSize = size; } @@ -56,7 +63,7 @@ public void addContent(ByteBuf buffer, boolean last) .getName(), fileUpload.getFilename(), fileUpload .getContentType(), fileUpload .getContentTransferEncoding(), fileUpload.getCharset(), - definedSize); + definedSize, false); if (((MemoryFileUpload) fileUpload).getByteBuf() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload) .getByteBuf(), false); @@ -146,7 +153,7 @@ public void setContent(ByteBuf buffer) throws IOException { .getName(), fileUpload.getFilename(), fileUpload .getContentType(), fileUpload .getContentTransferEncoding(), fileUpload.getCharset(), - definedSize); + definedSize, false); } } fileUpload.setContent(buffer); @@ -161,7 +168,7 @@ public void setContent(File file) throws IOException { .getName(), fileUpload.getFilename(), fileUpload .getContentType(), fileUpload .getContentTransferEncoding(), fileUpload.getCharset(), - definedSize); + definedSize, false); } } fileUpload.setContent(file); @@ -175,7 +182,7 @@ public void setContent(InputStream inputStream) throws IOException { .getName(), fileUpload.getFilename(), fileUpload .getContentType(), fileUpload .getContentTransferEncoding(), fileUpload.getCharset(), - definedSize); + definedSize, false); } fileUpload.setContent(inputStream); }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpDataTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpDataTest.java index 0334ba612df..82c14bf7c9c 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpDataTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/AbstractMemoryHttpDataTest.java @@ -69,7 +69,7 @@ private static final class TestHttpData extends AbstractMemoryHttpData { * @param size Expected data block size. */ protected TestHttpData(String name, Charset charset, long size) { - super(name, charset, size); + super(name, charset, size, true); } @Override
val
train
2013-04-08T21:23:53
"2013-04-02T16:54:21Z"
xhh11
val
netty/netty/1426_1429
netty/netty
netty/netty/1426
netty/netty/1429
[ "timestamp(timedelta=52.0, similarity=0.9419155171733438)" ]
dbab41cc50f4ddb71a153df342748ca1d85ab8e7
a094341c566ddfe82d44bbbcbc2adabc7ddbdc50
[ "@menacher I wonder why you not can just pass the thread count in by your own ? The problem is that there is not a good \"default\" value as it really depends on how many NioEventLoopGroups you create and what they do.\n", "@normanmaurer Agreed. But normally when you pass in 0 or -ve to such api it goes for a default silently rather than throwing back an exception. The one use I could see is that when using different machines to deploy same code, sending in 0 automatically ends up using the right number of threads, without me having to tweak them on each machine (for production I will need to tweak for sure, am talking about dev and test).\n", "@menacher I think the problem is that there is no good default as it depends on how many NioEventLoopGroup you create..\n", "Although I agree with @normanmaurer that there's no sane default in most cases, but I accepted @menacher's suggestion because it's also sometimes pretty useful.\n" ]
[]
"2013-06-07T04:13:05Z"
[ "defect" ]
Spring instantiation of NioEventLoopGroup with 0 number of threads is now complicated
I used to use the following constructor while instantiating `NioEventLoopGroup` boss and worker threads. ``` java /** * Create a new instance using nThreads number of threads, the given {@link ThreadFactory} and the * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. */ public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) { this(nThreads, threadFactory, SelectorProvider.provider()); } ``` The issue is that when instantiating from spring, earlier I used to give nThreads = 0 and it would take the default number. But now its throwing `IllegalArgumentException`. Reason I instantiate via spring is so that I can pass in my own `ThreadFactory`. It would be good if a condition is kept inside this constructor checking for 0 and then passing the default value of threads. Or have another constructor which takes `ThreadFactory` alone and does the same logic.
[ "transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java" ]
[ "transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java b/transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java index 04d89b68fac..d11bb12865f 100644 --- a/transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java +++ b/transport/src/main/java/io/netty/channel/nio/NioEventLoopGroup.java @@ -58,7 +58,7 @@ public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) { */ public NioEventLoopGroup( int nThreads, ThreadFactory threadFactory, final SelectorProvider selectorProvider) { - super(nThreads, threadFactory, selectorProvider); + super((nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads), threadFactory, selectorProvider); } /**
null
train
train
2013-06-25T04:07:15
"2013-06-06T03:06:56Z"
menacher
val
netty/netty/1508_1510
netty/netty
netty/netty/1508
netty/netty/1510
[ "timestamp(timedelta=120917.0, similarity=0.8648559196228794)" ]
a4ee2841be0be8e69d624f0543ab9d0ebb4b9567
b632e26bea7f9615ba74808b9a89d21dc21078a9
[ "@fbettag I get the following exception when run latest code from master:\n\n[info] Running io.wasted.netty.websocket.bench.Client ws://localhost:5555 50\n21:19:49.042 DEBUG i.n.u.i.l.InternalLoggerFactory - Using SLF4J as the default logging framework\n21:19:49.046 DEBUG i.n.c.MultithreadEventLoopGroup - io.netty.eventLoopThreads: 8\n21:19:49.059 DEBUG i.n.util.internal.PlatformDependent - UID: 501\n21:19:49.060 DEBUG i.n.util.internal.PlatformDependent - Java version: 7\n21:19:49.062 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.ByteBuffer.cleaner: available\n21:19:49.062 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Buffer.address: available\n21:19:49.062 DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available\n21:19:49.063 DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available\n21:19:49.063 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: true\n21:19:49.063 DEBUG i.n.util.internal.PlatformDependent - sun.misc.Unsafe: available\n21:19:49.188 DEBUG i.n.util.internal.PlatformDependent - Javassist: available\n21:19:49.188 DEBUG i.n.util.internal.PlatformDependent - io.netty.noPreferDirect: false\n21:19:49.292 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.numHeapArenas: 4\n21:19:49.292 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.numDirectArenas: 4\n21:19:49.292 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.pageSize: 8192\n21:19:49.292 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.maxOrder: 11\n21:19:49.292 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.chunkSize: 16777216\n21:19:49.337 DEBUG io.netty.util.ResourceLeakDetector - io.netty.noResourceLeakDetection: false\n21:19:49.345 DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.**matchers**.io.netty.handler.codec.http.HttpObjectMatcher\n21:19:49.411 DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.**matchers**.io.netty.handler.codec.http.websocketx.WebSocketFrameMatcher\n21:19:49.488 INFO Client$ - All 50 launched\n21:19:50.569 WARN io.netty.util.HashedWheelTimer - An exception was thrown by TimerTask.\njava.lang.NullPointerException: null\n at io.wasted.netty.websocket.bench.Client$$anonfun$start$1.apply$mcV$sp(Client.scala:55) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anonfun$io$wasted$netty$websocket$bench$Schedule$$repeatFunc$1.apply$mcV$sp(Schedule.scala:26) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anon$1.run(Schedule.scala:20) ~[classes/:na]\n at io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:535) ~[netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.notifyExpiredTimeouts(HashedWheelTimer.java:433) [netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:374) [netty-all-4.0.0.CR7.jar:na]\n at java.lang.Thread.run(Thread.java:722) [na:1.7.0_17]\n21:19:51.663 WARN io.netty.util.HashedWheelTimer - An exception was thrown by TimerTask.\njava.lang.NullPointerException: null\n at io.wasted.netty.websocket.bench.Client$$anonfun$start$1.apply$mcV$sp(Client.scala:55) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anonfun$io$wasted$netty$websocket$bench$Schedule$$repeatFunc$1.apply$mcV$sp(Schedule.scala:26) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anon$1.run(Schedule.scala:20) ~[classes/:na]\n at io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:535) ~[netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.notifyExpiredTimeouts(HashedWheelTimer.java:433) [netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:374) [netty-all-4.0.0.CR7.jar:na]\n at java.lang.Thread.run(Thread.java:722) [na:1.7.0_17]\n21:19:52.763 WARN io.netty.util.HashedWheelTimer - An exception was thrown by TimerTask.\njava.lang.NullPointerException: null\n at io.wasted.netty.websocket.bench.Client$$anonfun$start$1.apply$mcV$sp(Client.scala:55) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anonfun$io$wasted$netty$websocket$bench$Schedule$$repeatFunc$1.apply$mcV$sp(Schedule.scala:26) ~[classes/:na]\n at io.wasted.netty.websocket.bench.Schedule$$anon$1.run(Schedule.scala:20) ~[classes/:na]\n at io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:535) ~[netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.notifyExpiredTimeouts(HashedWheelTimer.java:433) [netty-all-4.0.0.CR7.jar:na]\n at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:374) [netty-all-4.0.0.CR7.jar:na]\n at java.lang.Thread.run(Thread.java:722) [na:1.7.0_17]\n", "Dont pay attention to the client, i wanted to output stats but decided otherwise. Will cean it up, doesnt have impact tho.\n", "@fbettag don't call retain on the request when pass it to the handshakeer. This will fix it. I have added some explanation to the javadocs to make this clear.\n" ]
[]
"2013-07-02T15:51:48Z"
[ "defect" ]
ResourceLeakException in CR7
During our tests with our benchmark, we saw a Leak which according to us and norman did not make sense. Test-Case can be found at https://github.com/wasted/netty-websocket-bench Output from Server: fbettag@committers:~/netty-bench$ ./sbt 'run-main io.wasted.netty.websocket.bench.Server' [info] Loading project definition from /home/fbettag/netty-bench/project [info] Set current project to netty-bench (in build file:/home/fbettag/netty-bench/) [info] Running io.wasted.netty.websocket.bench.Server 22:19:23.818 DEBUG i.n.u.i.l.InternalLoggerFactory - Using SLF4J as the default logging framework 22:19:23.823 DEBUG i.n.c.MultithreadEventLoopGroup - io.netty.eventLoopThreads: 12 22:19:23.835 DEBUG i.n.util.internal.PlatformDependent - UID: 1001 22:19:23.835 DEBUG i.n.util.internal.PlatformDependent - Java version: 7 22:19:23.838 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.ByteBuffer.cleaner: available 22:19:23.839 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Buffer.address: available 22:19:23.839 DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available 22:19:23.839 DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available 22:19:23.839 DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: true 22:19:23.840 DEBUG i.n.util.internal.PlatformDependent - sun.misc.Unsafe: available 22:19:23.967 DEBUG i.n.util.internal.PlatformDependent - Javassist: available 22:19:23.967 DEBUG i.n.util.internal.PlatformDependent - io.netty.noPreferDirect: false 22:19:24.088 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.numHeapArenas: 6 22:19:24.088 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.numDirectArenas: 6 22:19:24.088 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.pageSize: 8192 22:19:24.088 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.maxOrder: 11 22:19:24.088 DEBUG i.n.buffer.PooledByteBufAllocator - io.netty.allocator.chunkSize: 16777216 22:19:24.104 DEBUG io.netty.util.NetUtil - Loopback interface: lo 22:19:24.104 DEBUG io.netty.util.NetUtil - Loopback address: /0:0:0:0:0:0:0:1%1 (primary) 22:19:24.104 DEBUG io.netty.util.NetUtil - Loopback address: /127.0.0.1 22:19:24.104 DEBUG io.netty.util.NetUtil - /proc/sys/net/core/somaxconn: 128 22:19:24.129 DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.**matchers**.io.netty.channel.ChannelMatcher 22:19:24.141 INFO Server$ - Listening on 0.0.0.0:5555 22:19:24.142 INFO Server$ - Ready 22:19:24.147 DEBUG io.netty.util.ResourceLeakDetector - io.netty.noResourceLeakDetection: false 22:19:25.200 INFO Server$ - -- Stats -- connected: 0 22:19:26.294 INFO Server$ - -- Stats -- connected: 0 22:19:27.394 INFO Server$ - -- Stats -- connected: 0 22:19:28.395 INFO Server$ - -- Stats -- connected: 0 22:19:29.395 INFO Server$ - -- Stats -- connected: 0 22:19:30.495 INFO Server$ - -- Stats -- connected: 0 22:19:31.168 DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.**matchers**.io.netty.handler.codec.http.HttpObjectMatcher 22:19:31.398 DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.**matchers**.io.netty.handler.codec.http.websocketx.WebSocketFrameMatcher 22:19:31.594 INFO Server$ - -- Stats -- connected: 382 22:19:32.594 INFO Server$ - -- Stats -- connected: 1629 22:19:32.887 WARN io.netty.util.ResourceLeakDetector - LEAK: ByteBuf was GC'd before being released correctly. io.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@7572e7e5 at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:60) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.buffer.Unpooled.compositeBuffer(Unpooled.java:353) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.handler.codec.http.HttpObjectAggregator.decode(HttpObjectAggregator.java:137) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.handler.codec.http.HttpObjectAggregator.decode(HttpObjectAggregator.java:49) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:82) ~[netty-all-4.0.0.CR7.jar:na] at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364) [netty-all-4.0.0.CR7.jar:na] at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464) [netty-all-4.0.0.CR7.jar:na] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358) [netty-all-4.0.0.CR7.jar:na] at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101) [netty-all-4.0.0.CR7.jar:na] at java.lang.Thread.run(Thread.java:722) [na:1.7.0_03] 22:19:33.694 INFO Server$ - -- Stats -- connected: 3293 22:19:34.794 INFO Server$ - -- Stats -- connected: 4434 22:19:35.895 INFO Server$ - -- Stats -- connected: 4434 22:19:36.995 INFO Server$ - -- Stats -- connected: 4496 22:19:38.094 INFO Server$ - -- Stats -- connected: 6172 22:19:39.095 INFO Server$ - -- Stats -- connected: 8256 22:19:40.195 INFO Server$ - -- Stats -- connected: 10637 22:19:41.328 INFO Server$ - -- Stats -- connected: 13811 22:19:42.394 INFO Server$ - -- Stats -- connected: 14053 22:19:43.494 INFO Server$ - -- Stats -- connected: 14169 22:19:44.594 INFO Server$ - -- Stats -- connected: 15114 22:19:45.695 INFO Server$ - -- Stats -- connected: 15116 22:19:46.795 INFO Server$ - -- Stats -- connected: 15116 22:19:47.895 INFO Server$ - -- Stats -- connected: 16018 22:19:48.995 INFO Server$ - -- Stats -- connected: 16020 22:19:50.095 INFO Server$ - -- Stats -- connected: 16020 22:19:51.194 INFO Server$ - -- Stats -- connected: 17850 22:19:52.195 INFO Server$ - -- Stats -- connected: 18120 22:19:53.294 INFO Server$ - -- Stats -- connected: 18145 22:19:54.395 INFO Server$ - -- Stats -- connected: 18752 22:19:55.495 INFO Server$ - -- Stats -- connected: 20156 22:19:56.595 INFO Server$ - -- Stats -- connected: 20174 22:19:57.695 INFO Server$ - -- Stats -- connected: 20198 22:19:58.794 INFO Server$ - -- Stats -- connected: 23409 22:19:59.894 INFO Server$ - -- Stats -- connected: 26831 22:20:00.894 INFO Server$ - -- Stats -- connected: 29504 22:20:01.994 INFO Server$ - -- Stats -- connected: 30593 22:20:03.094 INFO Server$ - -- Stats -- connected: 30735 22:20:04.194 INFO Server$ - -- Stats -- connected: 31655 22:20:05.294 INFO Server$ - -- Stats -- connected: 32179 22:20:06.395 INFO Server$ - -- Stats -- connected: 32322 22:20:07.494 INFO Server$ - -- Stats -- connected: 32612 22:20:08.594 INFO Server$ - -- Stats -- connected: 32619 22:20:09.595 INFO Server$ - -- Stats -- connected: 32639 22:20:10.695 INFO Server$ - -- Stats -- connected: 33241 22:20:11.794 INFO Server$ - -- Stats -- connected: 33250 22:20:12.894 INFO Server$ - -- Stats -- connected: 33273 22:20:13.994 INFO Server$ - -- Stats -- connected: 34017 22:20:15.094 INFO Server$ - -- Stats -- connected: 34160 22:20:16.194 INFO Server$ - -- Stats -- connected: 34303 22:20:17.195 INFO Server$ - -- Stats -- connected: 34696 22:20:18.295 INFO Server$ - -- Stats -- connected: 34712 22:20:19.395 INFO Server$ - -- Stats -- connected: 34735 22:20:20.395 INFO Server$ - -- Stats -- connected: 35236 22:20:21.495 INFO Server$ - -- Stats -- connected: 35378 22:20:22.595 INFO Server$ - -- Stats -- connected: 35716 22:20:23.694 INFO Server$ - -- Stats -- connected: 37473 22:20:24.694 INFO Server$ - -- Stats -- connected: 37494 22:20:25.794 INFO Server$ - -- Stats -- connected: 37908 22:20:26.894 INFO Server$ - -- Stats -- connected: 38825 22:20:27.994 INFO Server$ - -- Stats -- connected: 38848 22:20:29.094 INFO Server$ - -- Stats -- connected: 39202 22:20:30.194 INFO Server$ - -- Stats -- connected: 39346 22:20:31.295 INFO Server$ - -- Stats -- connected: 39489 22:20:32.395 INFO Server$ - -- Stats -- connected: 39890 22:20:33.495 INFO Server$ - -- Stats -- connected: 40032 22:20:34.594 INFO Server$ - -- Stats -- connected: 40176 22:20:35.694 INFO Server$ - -- Stats -- connected: 40589 22:20:36.695 INFO Server$ - -- Stats -- connected: 40721 22:20:37.795 INFO Server$ - -- Stats -- connected: 40865 22:20:38.895 INFO Server$ - -- Stats -- connected: 41689 22:20:39.995 INFO Server$ - -- Stats -- connected: 41712 22:20:41.094 INFO Server$ - -- Stats -- connected: 41734 22:20:42.194 INFO Server$ - -- Stats -- connected: 42118 22:20:43.194 INFO Server$ - -- Stats -- connected: 42249 22:20:44.294 INFO Server$ - -- Stats -- connected: 42477 22:20:45.394 INFO Server$ - -- Stats -- connected: 42778 22:20:46.494 INFO Server$ - -- Stats -- connected: 42923 22:20:47.595 INFO Server$ - -- Stats -- connected: 43975 22:20:48.695 INFO Server$ - -- Stats -- connected: 43983 22:20:49.794 INFO Server$ - -- Stats -- connected: 44006 22:20:50.795 INFO Server$ - -- Stats -- connected: 44377 22:20:51.894 INFO Server$ - -- Stats -- connected: 44521 22:20:52.895 INFO Server$ - -- Stats -- connected: 44649 22:20:53.995 INFO Server$ - -- Stats -- connected: 45068 22:20:55.095 INFO Server$ - -- Stats -- connected: 45213 22:20:56.195 INFO Server$ - -- Stats -- connected: 45360 22:20:57.295 INFO Server$ - -- Stats -- connected: 45756 22:20:58.394 INFO Server$ - -- Stats -- connected: 45900 22:20:59.395 INFO Server$ - -- Stats -- connected: 46033 22:21:00.494 INFO Server$ - -- Stats -- connected: 48850 22:21:01.594 INFO Server$ - -- Stats -- connected: 51145 22:21:02.694 INFO Server$ - -- Stats -- connected: 51674 22:21:03.794 INFO Server$ - -- Stats -- connected: 52088 22:21:04.895 INFO Server$ - -- Stats -- connected: 52111 22:21:06.027 INFO Server$ - -- Stats -- connected: 53118 22:21:07.094 INFO Server$ - -- Stats -- connected: 57462 22:21:08.094 INFO Server$ - -- Stats -- connected: 57595 22:21:09.194 INFO Server$ - -- Stats -- connected: 57740 22:21:10.295 INFO Server$ - -- Stats -- connected: 57887 22:21:11.395 INFO Server$ - -- Stats -- connected: 58033 22:21:12.494 INFO Server$ - -- Stats -- connected: 58178 22:21:13.595 INFO Server$ - -- Stats -- connected: 58322 22:21:14.695 INFO Server$ - -- Stats -- connected: 58468 22:21:15.795 INFO Server$ - -- Stats -- connected: 58614 22:21:16.895 INFO Server$ - -- Stats -- connected: 58759 22:21:17.995 INFO Server$ - -- Stats -- connected: 58906 22:21:19.095 INFO Server$ - -- Stats -- connected: 59053 22:21:20.195 INFO Server$ - -- Stats -- connected: 59199 22:21:21.294 INFO Server$ - -- Stats -- connected: 59345 22:21:22.394 INFO Server$ - -- Stats -- connected: 59487 22:21:23.494 INFO Server$ - -- Stats -- connected: 59634 22:21:24.594 INFO Server$ - -- Stats -- connected: 59780 22:21:25.694 INFO Server$ - -- Stats -- connected: 59927 22:21:26.794 INFO Server$ - -- Stats -- connected: 60072 22:21:27.894 INFO Server$ - -- Stats -- connected: 60219 22:21:28.994 INFO Server$ - -- Stats -- connected: 60366 22:21:30.095 INFO Server$ - -- Stats -- connected: 60512 22:21:31.195 INFO Server$ - -- Stats -- connected: 60658 22:21:32.295 INFO Server$ - -- Stats -- connected: 60801 22:21:33.395 INFO Server$ - -- Stats -- connected: 60948 22:21:34.495 INFO Server$ - -- Stats -- connected: 61095 22:21:35.594 INFO Server$ - -- Stats -- connected: 61241 22:21:36.595 INFO Server$ - -- Stats -- connected: 61375 22:21:37.694 INFO Server$ - -- Stats -- connected: 61521 22:21:38.794 INFO Server$ - -- Stats -- connected: 61667 22:21:39.894 INFO Server$ - -- Stats -- connected: 61814 22:21:40.994 INFO Server$ - -- Stats -- connected: 61958 22:21:42.095 INFO Server$ - -- Stats -- connected: 62105 22:21:43.195 INFO Server$ - -- Stats -- connected: 62252 22:21:44.294 INFO Server$ - -- Stats -- connected: 62399 22:21:45.395 INFO Server$ - -- Stats -- connected: 62547 22:21:46.495 INFO Server$ - -- Stats -- connected: 62696 22:21:47.595 INFO Server$ - -- Stats -- connected: 62844 22:21:48.695 INFO Server$ - -- Stats -- connected: 62993 22:21:49.794 INFO Server$ - -- Stats -- connected: 63137 22:21:50.795 INFO Server$ - -- Stats -- connected: 63272 22:21:51.895 INFO Server$ - -- Stats -- connected: 63421 22:21:52.995 INFO Server$ - -- Stats -- connected: 63569 22:21:54.095 INFO Server$ - -- Stats -- connected: 63718 22:21:55.194 INFO Server$ - -- Stats -- connected: 63866 22:21:56.195 INFO Server$ - -- Stats -- connected: 64001 22:21:57.294 INFO Server$ - -- Stats -- connected: 64149 22:21:58.295 INFO Server$ - -- Stats -- connected: 64285 22:21:59.395 INFO Server$ - -- Stats -- connected: 64429 22:22:00.494 INFO Server$ - -- Stats -- connected: 64579 22:22:01.495 INFO Server$ - -- Stats -- connected: 64715 22:22:02.594 INFO Server$ - -- Stats -- connected: 64863 22:22:03.595 INFO Server$ - -- Stats -- connected: 64997 22:22:04.695 INFO Server$ - -- Stats -- connected: 65146 22:22:05.794 INFO Server$ - -- Stats -- connected: 65296 22:22:06.894 INFO Server$ - -- Stats -- connected: 65445 22:22:07.994 INFO Server$ - -- Stats -- connected: 65594 22:22:09.095 INFO Server$ - -- Stats -- connected: 65738 22:22:10.195 INFO Server$ - -- Stats -- connected: 65887 22:22:11.294 INFO Server$ - -- Stats -- connected: 66036 22:22:12.295 INFO Server$ - -- Stats -- connected: 66172 22:22:13.395 INFO Server$ - -- Stats -- connected: 66320 22:22:14.494 INFO Server$ - -- Stats -- connected: 66470 22:22:15.495 INFO Server$ - -- Stats -- connected: 66606 22:22:16.594 INFO Server$ - -- Stats -- connected: 66756 22:22:17.694 INFO Server$ - -- Stats -- connected: 66901 22:22:18.794 INFO Server$ - -- Stats -- connected: 67051 22:22:19.894 INFO Server$ - -- Stats -- connected: 67200 22:22:20.994 INFO Server$ - -- Stats -- connected: 67350 22:22:22.095 INFO Server$ - -- Stats -- connected: 67499 22:22:23.195 INFO Server$ - -- Stats -- connected: 67648 22:22:24.294 INFO Server$ - -- Stats -- connected: 67799 22:22:25.394 INFO Server$ - -- Stats -- connected: 67948 22:22:26.495 INFO Server$ - -- Stats -- connected: 68097 22:22:27.595 INFO Server$ - -- Stats -- connected: 68243 22:22:28.695 INFO Server$ - -- Stats -- connected: 68393 22:22:29.795 INFO Server$ - -- Stats -- connected: 68542 22:22:30.795 INFO Server$ - -- Stats -- connected: 68679 22:22:31.894 INFO Server$ - -- Stats -- connected: 68829 22:22:32.895 INFO Server$ - -- Stats -- connected: 68964 22:22:33.994 INFO Server$ - -- Stats -- connected: 69114 22:22:34.995 INFO Server$ - -- Stats -- connected: 69251 22:22:36.095 INFO Server$ - -- Stats -- connected: 69398 22:22:37.195 INFO Server$ - -- Stats -- connected: 69546 22:22:38.295 INFO Server$ - -- Stats -- connected: 69694 22:22:39.395 INFO Server$ - -- Stats -- connected: 69844 22:22:40.494 INFO Server$ - -- Stats -- connected: 69994 22:22:41.594 INFO Server$ - -- Stats -- connected: 70142 22:22:42.694 INFO Server$ - -- Stats -- connected: 70292 22:22:43.794 INFO Server$ - -- Stats -- connected: 70441 22:22:44.895 INFO Server$ - -- Stats -- connected: 70591 22:22:45.995 INFO Server$ - -- Stats -- connected: 70732 22:22:47.095 INFO Server$ - -- Stats -- connected: 70874 22:22:48.195 INFO Server$ - -- Stats -- connected: 71023 22:22:49.295 INFO Server$ - -- Stats -- connected: 71172 22:22:50.395 INFO Server$ - -- Stats -- connected: 71322 22:22:51.495 INFO Server$ - -- Stats -- connected: 71472 22:22:52.595 INFO Server$ - -- Stats -- connected: 71621 22:22:53.695 INFO Server$ - -- Stats -- connected: 71770 22:22:54.794 INFO Server$ - -- Stats -- connected: 71920 22:22:55.894 INFO Server$ - -- Stats -- connected: 72066 22:22:56.994 INFO Server$ - -- Stats -- connected: 72216 22:22:58.094 INFO Server$ - -- Stats -- connected: 72365 22:22:59.194 INFO Server$ - -- Stats -- connected: 72515 22:23:00.294 INFO Server$ - -- Stats -- connected: 72665 22:23:01.395 INFO Server$ - -- Stats -- connected: 72815 22:23:02.495 INFO Server$ - -- Stats -- connected: 72963 22:23:03.595 INFO Server$ - -- Stats -- connected: 73113 22:23:04.695 INFO Server$ - -- Stats -- connected: 73264 22:23:05.794 INFO Server$ - -- Stats -- connected: 73411 22:23:06.894 INFO Server$ - -- Stats -- connected: 73560 22:23:07.994 INFO Server$ - -- Stats -- connected: 73689 22:23:09.094 INFO Server$ - -- Stats -- connected: 73816 22:23:10.195 INFO Server$ - -- Stats -- connected: 73945 22:23:11.295 INFO Server$ - -- Stats -- connected: 74088 22:23:12.394 INFO Server$ - -- Stats -- connected: 74215 22:23:13.395 INFO Server$ - -- Stats -- connected: 74330 22:23:14.495 INFO Server$ - -- Stats -- connected: 74452 22:23:15.595 INFO Server$ - -- Stats -- connected: 74579 22:23:16.695 INFO Server$ - -- Stats -- connected: 74706 22:23:17.794 INFO Server$ - -- Stats -- connected: 74833 22:23:18.795 INFO Server$ - -- Stats -- connected: 74948 22:23:19.894 INFO Server$ - -- Stats -- connected: 75075 22:23:20.895 INFO Server$ - -- Stats -- connected: 75190 22:23:21.995 INFO Server$ - -- Stats -- connected: 75317 22:23:23.094 INFO Server$ - -- Stats -- connected: 75443 22:23:24.095 INFO Server$ - -- Stats -- connected: 75556 22:23:25.194 INFO Server$ - -- Stats -- connected: 75683 22:23:26.195 INFO Server$ - -- Stats -- connected: 75799 22:23:27.294 INFO Server$ - -- Stats -- connected: 75925 22:23:28.394 INFO Server$ - -- Stats -- connected: 76052 22:23:29.494 INFO Server$ - -- Stats -- connected: 76178 22:23:30.594 INFO Server$ - -- Stats -- connected: 76305 22:23:31.694 INFO Server$ - -- Stats -- connected: 76432 22:23:32.794 INFO Server$ - -- Stats -- connected: 76555 22:23:33.895 INFO Server$ - -- Stats -- connected: 76682 22:23:34.995 INFO Server$ - -- Stats -- connected: 76809 22:23:36.095 INFO Server$ - -- Stats -- connected: 76936 22:23:37.195 INFO Server$ - -- Stats -- connected: 77063 22:23:38.295 INFO Server$ - -- Stats -- connected: 77189 22:23:39.395 INFO Server$ - -- Stats -- connected: 77316 22:23:40.495 INFO Server$ - -- Stats -- connected: 77443 22:23:41.594 INFO Server$ - -- Stats -- connected: 77570 22:23:42.595 INFO Server$ - -- Stats -- connected: 77685 22:23:43.695 INFO Server$ - -- Stats -- connected: 77807 22:23:44.795 INFO Server$ - -- Stats -- connected: 77934 22:23:45.895 INFO Server$ - -- Stats -- connected: 78061 22:23:46.995 INFO Server$ - -- Stats -- connected: 78188 22:23:48.095 INFO Server$ - -- Stats -- connected: 78315 22:23:49.195 INFO Server$ - -- Stats -- connected: 78441 22:23:50.294 INFO Server$ - -- Stats -- connected: 78568 22:23:51.394 INFO Server$ - -- Stats -- connected: 78695 22:23:52.494 INFO Server$ - -- Stats -- connected: 78818 22:23:53.594 INFO Server$ - -- Stats -- connected: 78945 22:23:54.694 INFO Server$ - -- Stats -- connected: 78992 22:23:55.794 INFO Server$ - -- Stats -- connected: 78992 22:23:56.894 INFO Server$ - -- Stats -- connected: 78992 22:23:57.994 INFO Server$ - -- Stats -- connected: 78992 22:23:59.094 INFO Server$ - -- Stats -- connected: 78992 22:24:00.194 INFO Server$ - -- Stats -- connected: 78992 ^C22:24:00.729 INFO Server$ - Shutting down 22:24:00.733 INFO Server$ - Shutdown complete
[ "common/src/main/java/io/netty/util/ResourceLeakException.java" ]
[ "common/src/main/java/io/netty/util/ResourceLeakException.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/ResourceLeakException.java b/common/src/main/java/io/netty/util/ResourceLeakException.java index a69238884bf..d1bdec0c4ff 100644 --- a/common/src/main/java/io/netty/util/ResourceLeakException.java +++ b/common/src/main/java/io/netty/util/ResourceLeakException.java @@ -16,6 +16,8 @@ package io.netty.util; +import io.netty.util.internal.StringUtil; + import java.util.Arrays; public class ResourceLeakException extends RuntimeException { @@ -64,4 +66,15 @@ public boolean equals(Object o) { return Arrays.equals(cachedStackTrace, ((ResourceLeakException) o).cachedStackTrace); } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getCanonicalName()).append(": ").append(getMessage()); + for (StackTraceElement element : cachedStackTrace) { + builder.append(StringUtil.NEWLINE).append(" at ").append(element); + } + + return builder.toString(); + } }
null
train
train
2013-07-02T13:46:09
"2013-07-02T12:57:29Z"
fbettag
val
netty/netty/1469_1510
netty/netty
netty/netty/1469
netty/netty/1510
[ "timestamp(timedelta=61230.0, similarity=0.8410950705895608)" ]
a4ee2841be0be8e69d624f0543ab9d0ebb4b9567
b632e26bea7f9615ba74808b9a89d21dc21078a9
[ "It is for netty-4.0.0.CR5\n", "What are the types of the handlers in the pipeline?\n\nWhen extending `ChannelInboundHandler(Adapter)`, you have to call `MessageList.releaseAllAndRecycle()` on the incoming message lists after processing them.\n\n(some utilities for this being worked in #1446)\n", "Hello,\n\nI extends ChannelInboundHandlerAdapter. I call MessageList.releaseAllAndRecycle() after processing them.\n\nMy method:\n\n```\n@Override\npublic void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception {\n for (int i = 0; i < msgs.size(); i++) \n {\n Object msg = msgs.get(i);\n\n if (msg instanceof HttpRequest) \n {\n HttpRequest request = this.request = (HttpRequest) msg;\n\n // if GET Method: should not try to create a HttpPostRequestDecoder\n try {\n decoder = new HttpPostRequestDecoder(factory, request);\n } catch (ErrorDataDecoderException e1) {\n e1.printStackTrace();\n responseContent.append(\"RECEIVED_FAIL\");\n writeResponse(ctx.channel());\n ctx.channel().close();\n return;\n } catch (IncompatibleDataDecoderException e1) {\n // GET Method: should not try to create a HttpPostRequestDecoder\n // So OK but stop here\n //responseContent.append(e1.getMessage());\n responseContent.append(\"RECEIVED_FAIL\");\n writeResponse(ctx.channel());\n return;\n }\n }//if\n\n // check if the decoder was constructed before\n // if not it handles the form get\n if (decoder != null) \n {\n if (msg instanceof HttpContent) \n {\n // New chunk is received\n HttpContent chunk = (HttpContent) msg;\n try \n {\n decoder.offer(chunk);\n } \n catch (ErrorDataDecoderException e1) \n {\n e1.printStackTrace();\n responseContent.append(\"RECEIVED_FAIL\");\n writeResponse(ctx.channel());\n ctx.channel().close();\n return;\n }\n\n if (chunk instanceof LastHttpContent) \n {\n responseContent.setLength(0);\n isReceivedOK = false;\n\n readHttpDataAllReceive(ctx.channel());\n\n if(isReceivedOK)\n responseContent.append(\"RECEIVED_OK\");\n else\n responseContent.append(\"RECEIVED_FAIL\");\n\n writeResponse(ctx.channel());\n readingChunks = false;\n reset();\n }\n }\n }//decoder\n }//for\n\n msgs.releaseAllAndRecycle();\n}\n```\n", "The `releaseAllAndRecycle()` is not in a finally block, and there are `return` statements in the error handling paths. Were there any exceptions handled before you got the leak?\n", "I have print screen from my test machine where I see only this exception. I used this example (https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/http/upload/HttpUploadServerHandler.java) (there isn't \"finally\" block too). I see, you have right. I think, I must add releaseAllAndRecycle(). I'll let report if throw exception.\n", "Thanks @jaens!\n", "@rostaocenasek any news here ?\n", "Let us close this as its most likely a user error ... @rostaocenasek please reopen if you still think its a bug\n", "Hello,\nI have the test server back. I tested netty. After 2 minutes what I start up the server, I see first exception:\n\nWARN ResourceLeakDetector:151 - LEAK: ByteBuf was GC'd before being released correctly.\nio.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@501f2f6a\n at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158)\n at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103)\n at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:80)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:301)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:238)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:363)\n at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:150)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96)\n at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786)\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120)\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489)\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358)\n at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)\n at java.lang.Thread.run(Thread.java:724)\n\nAfter 7 minutes:\n\nWARN ResourceLeakDetector:151 - LEAK: ByteBuf was GC'd before being released correctly.\nio.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@3a1c5252\n at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158)\n at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103)\n at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:60)\n at io.netty.buffer.Unpooled.compositeBuffer(Unpooled.java:353)\n at io.netty.buffer.Unpooled.compositeBuffer(Unpooled.java:346)\n at io.netty.handler.codec.http.multipart.AbstractMemoryHttpData.addContent(AbstractMemoryHttpData.java:100)\n at io.netty.handler.codec.http.multipart.MixedFileUpload.addContent(MixedFileUpload.java:67)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.readFileUploadByteMultipart(HttpPostRequestDecoder.java:1698)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.getFileUpload(HttpPostRequestDecoder.java:1149)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.decodeMultipart(HttpPostRequestDecoder.java:817)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBodyMultipart(HttpPostRequestDecoder.java:725)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBody(HttpPostRequestDecoder.java:423)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:368)\n at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:150)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96)\n at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786)\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120)\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489)\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358)\n at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)\n at java.lang.Thread.run(Thread.java:724)\n", "@rostaocenasek I think I just fixed it today in master... could you please verify ?\n", "I have problem build project from master :(.\n", "whats the problem ? It builds here without problems…\n\nAm 04.07.2013 um 15:46 schrieb Rostislav Ocenasek [email protected]:\n\n> I have problem build project from master :(.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Builded netty-all-4.0.0.CR10-SNAPSHOT.jar . Tested. Still Exception:\n\nWARN ResourceLeakDetector:151 - LEAK: ByteBuf was GC'd before being released correctly.\nio.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@445551c5\n at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158)\n at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103)\n at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:80)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:301)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:238)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:363)\n at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:150)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96)\n at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786)\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120)\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489)\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358)\n at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)\n at java.lang.Thread.run(Thread.java:724)\n", "Can you share your full code ao Ican reproduce?\n\nAm 04.07.2013 um 16:35 schrieb Rostislav Ocenasek [email protected]:\n\n> Builded. Tested. Still Exception:\n> \n> WARN ResourceLeakDetector:151 - LEAK: ByteBuf was GC'd before being released correctly.\n> io.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@445551c\n> at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.(ResourceLeakDetector.java:158)\n> at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103)\n> at io.netty.buffer.DefaultCompositeByteBuf.(DefaultCompositeByteBuf.java:80)\n> at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:301)\n> at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:238)\n> at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:363)\n> at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:150)\n> at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n> at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n> at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96)\n> at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100)\n> at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n> at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n> at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187)\n> at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n> at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n> at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786)\n> at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120)\n> at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489)\n> at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)\n> at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358)\n> at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)\n> at java.lang.Thread.run(Thread.java:724)\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "I sent you mail.\n", "Let me check tomorrow..\n\nAm 04.07.2013 um 19:34 schrieb Rostislav Ocenasek [email protected]:\n\n> I sent you mail.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "@rostaocenasek it seems like you not release all resources. Check again the example provided by netty which does exactly this.\n", "Hello,\n\nI repair code according to your example and use today build of netty. Still I see Exception:\n\n15:16:09,642 WARN ResourceLeakDetector:151 - LEAK: ByteBuf was GC'd before being released correctly.\nio.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@7dfcc4fc\n at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158)\n at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103)\n at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:80)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:301)\n at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:238)\n at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:382)\n at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:155)\n at main.java.sportsdata.spocosy.SpocosyUploadServerHandler.messageReceived(SpocosyUploadServerHandler.java:1)\n at io.netty.channel.SimpleChannelInboundHandler.messageReceived(SimpleChannelInboundHandler.java:84)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96)\n at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:187)\n at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379)\n at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364)\n at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:786)\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:120)\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:497)\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:465)\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:359)\n at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)\n at java.lang.Thread.run(Thread.java:724)\n", "I also see the Exception for 4.0.0.CR10-SNAPSHOT/netty-all-4.0.0.CR10-20130709, why? is a bug or has fixed?\n", "I don't know, but sometimes I see this exception 5 min start server after, sometimes 6-10 hours after.\n" ]
[]
"2013-07-02T15:51:48Z"
[]
io.netty.util.ResourceLeakDetector reportLeak
``` Jun 18, 2013 7:05:31 PM io.netty.util.ResourceLeakDetector reportLeak WARNING: LEAK: ByteBuf was GC'd before being released correctly. io.netty.util.ResourceLeakException: io.netty.buffer.DefaultCompositeByteBuf@32f5627f at io.netty.util.ResourceLeakDetector$DefaultResourceLeak.<init>(ResourceLeakDetector.java:158) at io.netty.util.ResourceLeakDetector.open(ResourceLeakDetector.java:103) at io.netty.buffer.DefaultCompositeByteBuf.<init>(DefaultCompositeByteBuf.java:80) at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:301) at io.netty.buffer.Unpooled.wrappedBuffer(Unpooled.java:238) at io.netty.handler.codec.http.multipart.AbstractMemoryHttpData.addContent(AbstractMemoryHttpData.java:95) at io.netty.handler.codec.http.multipart.MemoryAttribute.addContent(MemoryAttribute.java:69) at io.netty.handler.codec.http.multipart.MixedAttribute.addContent(MixedAttribute.java:73) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.loadFieldMultipartStandard(HttpPostRequestDecoder.java:1792) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.loadFieldMultipart(HttpPostRequestDecoder.java:1826) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.decodeMultipart(HttpPostRequestDecoder.java:804) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBodyMultipart(HttpPostRequestDecoder.java:725) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.parseBody(HttpPostRequestDecoder.java:423) at io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.offer(HttpPostRequestDecoder.java:368) at com.sportsdata.spocosy.server.HttpUploadServerHandler.messageReceived(HttpUploadServerHandler.java:198) at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379) at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364) at io.netty.handler.codec.MessageToMessageDecoder.messageReceived(MessageToMessageDecoder.java:96) at io.netty.handler.codec.MessageToMessageCodec.messageReceived(MessageToMessageCodec.java:100) at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379) at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364) at io.netty.handler.codec.ByteToMessageDecoder.messageReceived(ByteToMessageDecoder.java:178) at io.netty.channel.DefaultChannelHandlerContext.invokeMessageReceived(DefaultChannelHandlerContext.java:379) at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:364) at io.netty.channel.DefaultChannelHandlerContext.fireMessageReceived(DefaultChannelHandlerContext.java:347) at io.netty.channel.DefaultChannelPipeline.fireMessageReceived(DefaultChannelPipeline.java:780) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:92) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:489) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101) at java.lang.Thread.run(Thread.java:722) ```
[ "common/src/main/java/io/netty/util/ResourceLeakException.java" ]
[ "common/src/main/java/io/netty/util/ResourceLeakException.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/ResourceLeakException.java b/common/src/main/java/io/netty/util/ResourceLeakException.java index a69238884bf..d1bdec0c4ff 100644 --- a/common/src/main/java/io/netty/util/ResourceLeakException.java +++ b/common/src/main/java/io/netty/util/ResourceLeakException.java @@ -16,6 +16,8 @@ package io.netty.util; +import io.netty.util.internal.StringUtil; + import java.util.Arrays; public class ResourceLeakException extends RuntimeException { @@ -64,4 +66,15 @@ public boolean equals(Object o) { return Arrays.equals(cachedStackTrace, ((ResourceLeakException) o).cachedStackTrace); } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getCanonicalName()).append(": ").append(getMessage()); + for (StackTraceElement element : cachedStackTrace) { + builder.append(StringUtil.NEWLINE).append(" at ").append(element); + } + + return builder.toString(); + } }
null
val
train
2013-07-02T13:46:09
"2013-06-19T09:29:05Z"
rostaocenasek
val
netty/netty/1534_1541
netty/netty
netty/netty/1534
netty/netty/1541
[ "timestamp(timedelta=138586.0, similarity=0.8643002822383684)" ]
75229e145a8a593c6058938eb78c3b6dacdf9315
7663149e7373fdce308f99e3df6988078b531b47
[ "Tested with netty-handler-4.0.0.CR10-20130707.150539-39.jar -- still occurs but with much less frequency.\n", "Hmm.. Maybe a way to reproduce?\n\nAm 07.07.2013 um 18:14 schrieb Jeff Pinner [email protected]:\n\n> Tested with netty-handler-4.0.0.CR10-20130707.150539-39.jar -- still occurs but with much less frequency.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Trying to get a reproducible case -- strangely enough it appears to always happen on split packets, after reading the first 57 bytes of the split packet -- no idea where 57 comes from.\n", "My guess is that the fix doesn't handle the case where the buffer contains multiple TLS records whose last record is truncated. I didn't have a chance to confirm this by myself though.\n", "Maybe I can check this in a few.. Just time for dinner first\n\nAm 07.07.2013 um 18:39 schrieb Trustin Lee [email protected]:\n\n> My guess is that the fix doesn't handle the case where the buffer contains multiple TLS records whose last record is truncated. I didn't have a chance to confirm this by myself though.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "In each case, the first packet contained a 32-byte TLS record (not including header) and then the first 314-bytes of the second TLS record (also not including header) -- so the first packet was 356 bytes total. Then the second packet consumed the first 57 bytes and the next time through caused the exception.\n", "@trustin, just took a look at your fix, you're right -- you shouldn't just reset packetLength to 0 in the finally block, you need to add:\n\npacketLength -= result.bytesConsumed()\n\nafter the unwrap call and read the next header once it reaches 0.\n", "Not necessarily related but looks like another bug: `decode0()` calls `ctx.fireMessageReceived()` where `out.add(...)` should be called. i.e. we should not extend ByteToMessageDecoder really.\n\nI'll take a closer look in the morning.\n", "Hmm... We used FrameDecoder in 3.x so I think it should be ok to use ByteToMessageDecoder in 4.x\n\nAm 07.07.2013 um 19:03 schrieb Trustin Lee [email protected]:\n\n> Not necessarily related but looks like another bug: decode0() calls ctx.fireMessageReceived() where out.add(...) should be called. i.e. we should not extend ByteToMessageDecoder really.\n> \n> I'll take a closer look in the morning.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "I need to have a deeper look but at least in 3.x we do the same (reset the packetLength)\n\nAm 07.07.2013 um 18:59 schrieb Jeff Pinner [email protected]:\n\n> @trustin, just took a look at your fix, you're right -- you shouldn't just reset packetLength to 0 in the finally block, you need to add:\n> \n> packetLength -= result.bytesConsumed()\n> \n> after the unwrap call and read the next header once it reaches 0.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "@trustin now I see.. I think you are right we should better not extend ByteToMessageDecoder at all and just handle it by ourself. \n", "@normanmaurer In Netty 3.x we skipped the decoded packet length and returned the unwrapped buffer. So we never processed more than 1 frame at a time.\n", "@trustin how did you generate your ssl test data ? just capture it via wireshark ?\n", "@jpinner I did think about this again and I don't see why we need to \"update\" the packetLength as we also skip the bytes here too. This is done in the \"unwrap(...)\" method.\n\nI create a pull-req to make it easier to follow the fix #1541 of this problem.\n\nI already fixed there some issues which could I think can lead do \"corrupt\" data. Unfortunally I was not able to write a test-case yet. \n\n@trustin please also review\n", "@jpinner nevermind... Now I see it. Let me fix it in a few\n", "> @trustin how did you generate your ssl test data ? just capture it via wireshark ?\n\nJust wrote a dummy packet based on the RFC. You could just add LoggingHandler to the pipeline of SecureChatHandler to get some?\n", "@trustin good idea... will take a stab on this after swimming to \"re-gather\" some energy.\n", "@normanmaurer let me know if you need any help with this\n", "@jpinner @trustin fixed... I was able to reproduce it with niosmtp and so finally fixed it.. yay!\n" ]
[ "Why was this moved before the instantiation of the exception?\n", "Isn't `this.packetLength` already `0`?\n" ]
"2013-07-08T13:35:41Z"
[ "defect" ]
SSLHandler throws NotSslRecordException on partial data
In Netty 3, SSLHandler read the SSL packet length and aggregated the data until the entire packet had been received: if (buffer.readableBytes() < packetLength) { return null; } In Netty 4, SSLHandler computes the packet length, but then calls unwrap without aggregating the data. If the engine reads the available data and aggregates internally, it will consume the header, and on receiving the rest of the packet, SSLHandler will try to compute the packet length again and throw an exception. SSLHandler should either aggregate the data as it did in Netty 3, or track the packetLength and the bytesConsumed and only try to compute the packet length after completely consuming the previous packet.
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index 01ef75131a2..ee8ae7554a1 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -19,6 +19,7 @@ import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; +import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; @@ -183,6 +184,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH private final Queue<PendingWrite> pendingUnencryptedWrites = new ArrayDeque<PendingWrite>(); private int packetLength; + private ByteBuf decodeOut; private volatile long handshakeTimeoutMillis = 10000; private volatile long closeNotifyTimeoutMillis = 3000; @@ -343,9 +345,17 @@ public Future<Channel> sslCloseFuture() { } @Override - protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { + public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { if (decodeOut != null) { decodeOut.release(); + decodeOut = null; + } + for (;;) { + PendingWrite write = pendingUnencryptedWrites.poll(); + if (write == null) { + break; + } + write.fail(new ChannelException("Pending write on removal of SslHandler")); } } @@ -495,7 +505,7 @@ private void flush0(ChannelHandlerContext ctx) throws SSLException { } if (unwrapLater) { - decode0(ctx); + unwrapLater(ctx); } } catch (SSLException e) { setHandshakeFailure(e); @@ -517,6 +527,16 @@ private void flush0(ChannelHandlerContext ctx) throws SSLException { } } + private void unwrapLater(ChannelHandlerContext ctx) throws SSLException { + MessageList<Object> messageList = MessageList.newInstance(); + decode(ctx, internalBuffer(), messageList); + if (messageList.isEmpty()) { + messageList.recycle(); + } else { + ctx.fireMessageReceived(messageList); + } + } + private void flushNonAppData0(ChannelHandlerContext ctx) throws SSLException { boolean unwrapLater = false; ByteBuf out = null; @@ -567,7 +587,7 @@ private void flushNonAppData0(ChannelHandlerContext ctx) throws SSLException { } if (unwrapLater) { - decode0(ctx); + unwrapLater(ctx); } } catch (SSLException e) { setHandshakeFailure(e); @@ -782,26 +802,19 @@ private static int getEncryptedPacketLength(ByteBuf buffer) { } @Override - public void decode(final ChannelHandlerContext ctx, ByteBuf in, MessageList<Object> out) throws Exception { - decode0(ctx); - } - - private ByteBuf decodeOut; - - private void decode0(final ChannelHandlerContext ctx) throws SSLException { - final ByteBuf in = internalBuffer(); - - // Check if the packet length was parsed yet, if so we can skip the parsing - final int readableBytes = in.readableBytes(); + protected void decode(ChannelHandlerContext ctx, ByteBuf in, MessageList<Object> out) throws SSLException { int packetLength = this.packetLength; if (packetLength == 0) { + // the previous packet was consumed so try to read the length of the next packet + final int readableBytes = in.readableBytes(); if (readableBytes < 5) { + // not enough bytes readable to read the packet length return; } packetLength = getEncryptedPacketLength(in); if (packetLength == -1) { - // Bad data - discard the buffer and raise an exception. + // Not an SSL/TLS packet NotSslRecordException e = new NotSslRecordException( "not an SSL/TLS record: " + ByteBufUtil.hexDump(in)); in.skipBytes(readableBytes); @@ -814,10 +827,22 @@ private void decode0(final ChannelHandlerContext ctx) throws SSLException { this.packetLength = packetLength; } - if (readableBytes < packetLength) { + if (in.readableBytes() < packetLength) { + // wait until the whole packet can be read return; } + try { + // slice out the whole packet so unwrap will only be called with complete packets + int readerIndex = in.readerIndex(); + in.skipBytes(packetLength); + unwrap(ctx, in.nioBuffer(readerIndex, packetLength), out); + } finally { + this.packetLength = 0; + } + } + + private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, MessageList<Object> out) throws SSLException { boolean wrapLater = false; int bytesProduced = 0; try { @@ -826,9 +851,8 @@ private void decode0(final ChannelHandlerContext ctx) throws SSLException { if (decodeOut == null) { decodeOut = ctx.alloc().buffer(); } - SSLEngineResult result = unwrap(engine, in, decodeOut); + SSLEngineResult result = unwrap(engine, packet, decodeOut); bytesProduced += result.bytesProduced(); - switch (result.getStatus()) { case CLOSED: // notify about the CLOSED state of the SSLEngine. See #137 @@ -870,23 +894,18 @@ private void decode0(final ChannelHandlerContext ctx) throws SSLException { setHandshakeFailure(e); throw e; } finally { - // reset the packet length so it will be parsed again on the next call - this.packetLength = 0; - if (bytesProduced > 0) { ByteBuf decodeOut = this.decodeOut; this.decodeOut = null; - ctx.fireMessageReceived(decodeOut); + out.add(decodeOut); } } } - private static SSLEngineResult unwrap(SSLEngine engine, ByteBuf in, ByteBuf out) throws SSLException { - ByteBuffer in0 = in.nioBuffer(); + private static SSLEngineResult unwrap(SSLEngine engine, ByteBuffer in, ByteBuf out) throws SSLException { for (;;) { ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes()); - SSLEngineResult result = engine.unwrap(in0, out0); - in.skipBytes(result.bytesConsumed()); + SSLEngineResult result = engine.unwrap(in, out0); out.writerIndex(out.writerIndex() + result.bytesProduced()); switch (result.getStatus()) { case BUFFER_OVERFLOW:
null
test
train
2013-07-09T07:53:05
"2013-07-06T23:33:48Z"
jpinner
val
netty/netty/1545_1546
netty/netty
netty/netty/1545
netty/netty/1546
[ "timestamp(timedelta=83676.0, similarity=0.8647030483939786)" ]
7bedd8f28ef52a0c825133bc5926764444d7b3a9
4ab35bfa512c107ecbb0f1ddeabddb1691c78816
[ "@jestan after more thoughts I wonder why you not use InitMaxStreams.create(...) directly... Can you provide more info ?\n", "@jestan reverted this fix again as after more review I think the current impl is correct.\n", "@normanmaurer I think there is a problem. SctpChannelOption validates for List<Integer>. Thats why I have fixed the ClassCastException. Can we change SctpChannelOption back to InitMaxStream?\n\nI can not remember why InitMaxStream changed to List https://github.com/netty/netty/blob/master/transport-sctp/src/main/java/io/netty/channel/sctp/SctpChannelOption.java#L33\n", "@jestan yeah.. I will take care :)\n", "@jestan done! Thanks for reporting\n" ]
[]
"2013-07-09T18:38:39Z"
[]
ClassCastException while setting Sctp Inbound/Outbound streams in ChannelConfig in CR10-SNAPSHOT
In Netty CR-10 SNAPSHOT ``` Java final int MAX_INBOUND_STREAMS = 10; final int MAX_OUTBOUND_STREAMS = 10; List<Integer> streamConfig = new ArrayList<Integer>(2); streamConfig.add(MAX_INBOUND_STREAMS); streamConfig.add(MAX_OUTBOUND_STREAMS); Bootstrap cb = new Bootstrap(); cb.group(new NioEventLoopGroup()). handler(new ChannelInitializer() { @Override public void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(clientMeter); } }). option(SctpChannelOption.SCTP_NODELAY, true). option(SctpChannelOption.SCTP_INIT_MAXSTREAMS, streamConfig). option(SctpChannelOption.SO_RCVBUF, 1024 * 1024 * 1024). option(SctpChannelOption.SO_SNDBUF, 1024 * 1024 * 1024); ``` Jul 09, 2013 11:44:46 PM io.netty.bootstrap.Bootstrap init WARNING: Failed to set a channel option: [id: 0x2a71a639] java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.sun.nio.sctp.SctpStandardSocketOptions$InitMaxStreams at io.netty.channel.sctp.DefaultSctpChannelConfig.setOption(DefaultSctpChannelConfig.java:90) at io.netty.bootstrap.Bootstrap.init(Bootstrap.java:187) at io.netty.bootstrap.AbstractBootstrap.initAndRegister(AbstractBootstrap.java:280) at io.netty.bootstrap.Bootstrap.doConnect(Bootstrap.java:133) at io.netty.bootstrap.Bootstrap.connect(Bootstrap.java:89)
[ "transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java" ]
[ "transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java" ]
[]
diff --git a/transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java b/transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java index 8e7c2ffb222..37ec6ee79fc 100644 --- a/transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java +++ b/transport-sctp/src/main/java/io/netty/channel/sctp/DefaultSctpChannelConfig.java @@ -26,6 +26,7 @@ import io.netty.util.internal.PlatformDependent; import java.io.IOException; +import java.util.List; import java.util.Map; import static io.netty.channel.sctp.SctpChannelOption.*; @@ -87,7 +88,8 @@ public <T> boolean setOption(ChannelOption<T> option, T value) { } else if (option == SCTP_NODELAY) { setSctpNoDelay((Boolean) value); } else if (option == SCTP_INIT_MAXSTREAMS) { - setInitMaxStreams((SctpStandardSocketOptions.InitMaxStreams) value); + List<Integer> streams = (List<Integer>) value; + setInitMaxStreams(SctpStandardSocketOptions.InitMaxStreams.create(streams.get(0), streams.get(1))); } else { return super.setOption(option, value); }
null
train
train
2013-07-09T17:36:47
"2013-07-09T18:24:18Z"
jestan
val
netty/netty/1551_1552
netty/netty
netty/netty/1551
netty/netty/1552
[ "timestamp(timedelta=21.0, similarity=0.9527485477144009)" ]
4d44b379394f0ce82c5b0cfa610d8ba5a0d5d4e3
84846ab56110b61af15c43bace1d1cc095e067cb
[ "Issued pull request #1552.\n", "Will you provide a fix?\n\nAm 10.07.2013 um 20:00 schrieb Jeff Pinner [email protected]:\n\n> —\n> Reply to this email directly or view it on GitHub.\n", "Yep -- see #1552 :)\n", "@jpinner merged your pullreq in.. Thanks\n" ]
[]
"2013-07-10T18:17:58Z"
[ "defect" ]
HttpContentEncoder should not remove Content-Length when acting as a passthrough.
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java index fb8ec835cab..106e37233a1 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java @@ -123,15 +123,13 @@ protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou // If unable to encode, pass through. if (result == null) { if (isFull) { - // As an unchunked response + // Set the content length. res.headers().remove(Names.TRANSFER_ENCODING); res.headers().set(Names.CONTENT_LENGTH, ((ByteBufHolder) res).content().readableBytes()); out.add(ReferenceCountUtil.retain(res)); } else { - // As a chunked response - res.headers().remove(Names.CONTENT_LENGTH); - res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); out.add(res); + // Pass through all following contents. state = State.PASS_THROUGH; } break;
null
val
train
2013-07-10T18:10:52
"2013-07-10T18:00:43Z"
jpinner
val
netty/netty/1550_1554
netty/netty
netty/netty/1550
netty/netty/1554
[ "timestamp(timedelta=25.0, similarity=0.8970638251443727)" ]
cf9ee928b012bb2af24372ab180bacdb02cf7c74
60e00f27e922ab6a979714c82e3733bf17422448
[ "I will try to go through the codec carefully and see if anything else is broken.\n", "So you will issue a pullreq?\n\nAm 10.07.2013 um 19:34 schrieb Jeff Pinner [email protected]:\n\n> I will try to go through the codec carefully and see if anything else is broken.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Working on it now.\n", "Alright thanks... will review pullreq once you issued it\n", "ups sorry... closed it by mistake\n", "Issued pull request #1554. \n", "@jpinner merged #1554 ... Thanks!\n" ]
[]
"2013-07-10T19:22:16Z"
[ "defect" ]
SpdyHttpDecoder broken
At some point in the porting to netty 4 the SpdyHttpDecoder stopped writing RstStreams. As an example, the following code: // If a client receives a response with a truncated header block, // reply with a RST_STREAM with error code INTERNAL_ERROR. if (spdySynStreamFrame.isTruncated()) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INTERNAL_ERROR); out.add(spdyRstStreamFrame); } should have been // If a client receives a response with a truncated header block, // reply with a RST_STREAM with error code INTERNAL_ERROR. if (spdySynStreamFrame.isTruncated()) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INTERNAL_ERROR); ctx.write(spdyRstStreamFrame); // and possibly ctx.flush() also now }
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java index f9a991916eb..7041cfda79a 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpDecoder.java @@ -108,7 +108,8 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out if (associatedToStreamId == 0) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INVALID_STREAM); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); + return; } String URL = SpdyHeaders.getUrl(spdyVersion, spdySynStreamFrame); @@ -118,7 +119,8 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out if (URL == null) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.PROTOCOL_ERROR); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); + return; } // If a client receives a response with a truncated header block, @@ -126,7 +128,8 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out if (spdySynStreamFrame.isTruncated()) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INTERNAL_ERROR); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); + return; } try { @@ -149,7 +152,7 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out } catch (Exception e) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.PROTOCOL_ERROR); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); } } else { // SYN_STREAM frames initiated by the client are HTTP requests @@ -163,7 +166,8 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out spdySynReplyFrame, HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE); SpdyHeaders.setVersion(spdyVersion, spdySynReplyFrame, HttpVersion.HTTP_1_0); - out.add(spdySynReplyFrame); + ctx.writeAndFlush(spdySynReplyFrame); + return; } try { @@ -186,7 +190,7 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out spdySynReplyFrame.setLast(true); SpdyHeaders.setStatus(spdyVersion, spdySynReplyFrame, HttpResponseStatus.BAD_REQUEST); SpdyHeaders.setVersion(spdyVersion, spdySynReplyFrame, HttpVersion.HTTP_1_0); - out.add(spdySynReplyFrame); + ctx.writeAndFlush(spdySynReplyFrame); } } @@ -200,7 +204,8 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out if (spdySynReplyFrame.isTruncated()) { SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INTERNAL_ERROR); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); + return; } try { @@ -221,7 +226,7 @@ protected void decode(ChannelHandlerContext ctx, SpdyFrame msg, List<Object> out // the client must reply with a RST_STREAM frame indicating a PROTOCOL_ERROR SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.PROTOCOL_ERROR); - out.add(spdyRstStreamFrame); + ctx.writeAndFlush(spdyRstStreamFrame); } } else if (msg instanceof SpdyHeadersFrame) {
null
test
train
2013-07-10T21:02:00
"2013-07-10T17:33:28Z"
jpinner
val
netty/netty/1616_1617
netty/netty
netty/netty/1616
netty/netty/1617
[ "timestamp(timedelta=55.0, similarity=0.8490939366657063)" ]
a4d0341ea11140b1cfed2414f5292dffd3445dc8
0891c024d092f89f8790d0c0f8b1e99dc09b530c
[ "fixed with 80f92f90cbc9a8267cad3f338641982b53478e8a\n" ]
[]
"2013-07-19T20:19:57Z"
[ "defect" ]
SpdyHttpEncoder does not correctly set isLast() when sending a FullHttpMessage
For a FullHttpMessage with no content, two SPDY frames are sent, one SpdySynStreamFrame(last=false) plus one SpdyDataFrame with content and last=true. For known empty messages, last should be set to true in the SpdySynStreamFrame.
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java index 3862e2aedb3..a8e3eefd262 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpEncoder.java @@ -18,6 +18,7 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import io.netty.handler.codec.UnsupportedMessageTypeException; +import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; @@ -141,6 +142,7 @@ public SpdyHttpEncoder(int version) { protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { boolean valid = false; + boolean last = false; if (msg instanceof HttpRequest) { @@ -148,6 +150,7 @@ protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpRequest); out.add(spdySynStreamFrame); + last = spdySynStreamFrame.isLast(); valid = true; } if (msg instanceof HttpResponse) { @@ -155,15 +158,17 @@ protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou HttpResponse httpResponse = (HttpResponse) msg; if (httpResponse.headers().contains(SpdyHttpHeaders.Names.ASSOCIATED_TO_STREAM_ID)) { SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpResponse); + last = spdySynStreamFrame.isLast(); out.add(spdySynStreamFrame); } else { SpdySynReplyFrame spdySynReplyFrame = createSynReplyFrame(httpResponse); + last = spdySynReplyFrame.isLast(); out.add(spdySynReplyFrame); } valid = true; } - if (msg instanceof HttpContent) { + if (msg instanceof HttpContent && !last) { HttpContent chunk = (HttpContent) msg; @@ -255,6 +260,7 @@ private SpdySynStreamFrame createSynStreamFrame(HttpMessage httpMessage) spdySynStreamFrame.headers().add(entry.getKey(), entry.getValue()); } currentStreamId = spdySynStreamFrame.getStreamId(); + spdySynStreamFrame.setLast(isLast(httpMessage)); return spdySynStreamFrame; } @@ -284,8 +290,25 @@ private SpdySynReplyFrame createSynReplyFrame(HttpResponse httpResponse) } currentStreamId = streamID; - spdySynReplyFrame.setLast(false); + spdySynReplyFrame.setLast(isLast(httpResponse)); return spdySynReplyFrame; } + + /** + * Checks if the given HTTP message should be considered as a last SPDY frame. + * + * @param httpMessage check this HTTP message + * @return whether the given HTTP message should generate a <em>last</em> SPDY frame. + */ + private static boolean isLast(HttpMessage httpMessage) { + if (httpMessage instanceof FullHttpMessage) { + FullHttpMessage fullMessage = (FullHttpMessage) httpMessage; + if (fullMessage.trailingHeaders().isEmpty() && !fullMessage.content().isReadable()) { + return true; + } + } + + return false; + } }
null
train
train
2013-07-19T12:30:40
"2013-07-19T18:29:37Z"
ssilverman
val
netty/netty/1597_1618
netty/netty
netty/netty/1597
netty/netty/1618
[ "timestamp(timedelta=521.0, similarity=0.8774795595937743)" ]
a4d0341ea11140b1cfed2414f5292dffd3445dc8
d3f59be0b0270c0094a1fba9058504a1d2adfcb8
[ "This is also broken in Netty 3.6, line 188.\n", "Thanks.. Let me look into it\n\nAm 17.07.2013 um 18:04 schrieb ssilverman [email protected]:\n\n> The problem is on line 188. This will fail with a StringIndexOutOfBoundsException if the line contains just \"\\r\\n\". The length() check for > 0 needs to be done each time through the loop.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "Not really sure what that loop is for -- if I send the string \\r\\r\\r\\n -- why wouldn't the result be \\r\\r?\n", "If one subscribes to the \"\\r\"|\"\\n\"|\"\\r\\n\" linefeed model, I would expect \"\\r\\r\\r\\n\" to have three lines.\n", "I just wrote this quickly (it's untested). It should be close to what is needed.\n\n```\npublic String readLine() {\n StringBuilder lineBuf = new StringBuilder();\n\n loop: while (true) {\n if (!buffer.readable()) {\n return (lineBuf.length() > 0) ? lineBuf.toString() : null;\n }\n\n int c = buffer.readUnsignedByte();\n switch (c) {\n case '\\n':\n break loop;\n\n case '\\r':\n if (buffer.readable() && buffer.getUnsignedByte(buffer.readerIndex()) == '\\n') {\n buffer.skipBytes(1);\n }\n break loop;\n\n default:\n lineBuf.append((char)c);\n }\n }\n\n return lineBuf.toString();\n }\n```\n", "fixed via 674f4bce51047a19000ac1074bb934414511e9aa\n" ]
[]
"2013-07-20T00:50:09Z"
[ "defect" ]
Bug in ByteBufInputStream.readLine()
The problem is on lines 201-202. This will fail with a StringIndexOutOfBoundsException if the line contains just "\r\n". The length() check for > 0 needs to be done each time through the loop.
[ "buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java" ]
[ "buffer/src/test/java/io/netty/buffer/ByteBufStreamTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java b/buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java index f99e4c6444b..46b11b090c4 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufInputStream.java @@ -186,21 +186,25 @@ public int readInt() throws IOException { @Override public String readLine() throws IOException { lineBuf.setLength(0); - for (;;) { - int b = read(); - if (b == -1 && lineBuf.length() == 0) { - return null; - } - if (b < 0 || b == '\n') { - break; + + loop: while (true) { + if (!buffer.isReadable()) { + return (lineBuf.length() > 0) ? lineBuf.toString() : null; } - lineBuf.append((char) b); - } + int c = buffer.readUnsignedByte(); + switch (c) { + case '\n': + break loop; + + case '\r': + if (buffer.isReadable() && buffer.getUnsignedByte(buffer.readerIndex()) == '\n') { + buffer.skipBytes(1); + } + break loop; - if (lineBuf.length() > 0) { - while (lineBuf.charAt(lineBuf.length() - 1) == '\r') { - lineBuf.setLength(lineBuf.length() - 1); + default: + lineBuf.append((char) c); } }
diff --git a/buffer/src/test/java/io/netty/buffer/ByteBufStreamTest.java b/buffer/src/test/java/io/netty/buffer/ByteBufStreamTest.java index 430df8ff5dd..7f2d180061f 100644 --- a/buffer/src/test/java/io/netty/buffer/ByteBufStreamTest.java +++ b/buffer/src/test/java/io/netty/buffer/ByteBufStreamTest.java @@ -134,6 +134,7 @@ public void testAll() throws Exception { assertEquals("Hello, World!", in.readUTF()); assertEquals("The first line", in.readLine()); + assertEquals("", in.readLine()); assertEquals(4, in.read(tmp)); assertEquals(1, tmp[0]);
test
train
2013-07-19T12:30:40
"2013-07-17T16:04:44Z"
ssilverman
val
netty/netty/1654_1655
netty/netty
netty/netty/1654
netty/netty/1655
[ "timestamp(timedelta=53224.0, similarity=0.9381250108264462)" ]
fabefba79185ce7ec143d911ae86f5ab8bb08845
a09d6f95fa2c9f371588a62182cc0605c66174d2
[ "@jpinner what you mean with \"local sockets\" ?\n", "@normanmaurer i mean LocalChannel.java LocalServerChannel.java\n", "I'm happy to take a stab at this tonight and try to get you a pull req if you want.\n", "Sure thing! Thanks a lot :)\n\nAm 26.07.2013 um 07:45 schrieb Jeff Pinner [email protected]:\n\n> I'm happy to take a stab at this tonight and try to get you a pull req if you want.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n" ]
[]
"2013-07-26T06:23:27Z"
[ "defect", "cleanup" ]
Remove AbstractChannel#doPreClose()
tl;dr this is broken and should be removed instead of fixed doPreClose is currently called in closeFuture.setClosed(): 1) During registration failure closeForcily() calls doClose before setting the closeFuture -- so doPreClose() is called after doClose(). 2) During early registration failure (unable to schedule run loop) closeFuture is never set so doPreClose() is never called. 3) Exceptions in doPreClose are logged but the caller's promise is not notified. 4) doPreClose is only implemented in the local channels and that logic can be moved to close. 5) close() uses the closeFuture to determine if the socket is closed (via closeFuture.trySuccess) which calls out to user code listening to the closeFuture BEFORE closing the socket! We should do the following: 1) Move doPreClose to doClose for local sockets. 2) Remove doPreClose and have setClosed() only call trySuccces 3) don't use closeFuture to detect if the socket is closed (use !isOpen) and call closeFuture.setClosed only after calling doClose (which now we can do because we don't have to worry about the doPreClose ordering).
[ "transport/src/main/java/io/netty/channel/AbstractChannel.java", "transport/src/main/java/io/netty/channel/local/LocalChannel.java", "transport/src/main/java/io/netty/channel/local/LocalServerChannel.java" ]
[ "transport/src/main/java/io/netty/channel/AbstractChannel.java", "transport/src/main/java/io/netty/channel/local/LocalChannel.java", "transport/src/main/java/io/netty/channel/local/LocalServerChannel.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/AbstractChannel.java b/transport/src/main/java/io/netty/channel/AbstractChannel.java index 4f544bc67ac..638207b5b3a 100644 --- a/transport/src/main/java/io/netty/channel/AbstractChannel.java +++ b/transport/src/main/java/io/netty/channel/AbstractChannel.java @@ -415,6 +415,7 @@ public void run() { "Force-closing a channel whose registration task was unaccepted by an event loop: {}", AbstractChannel.this, t); closeForcibly(); + closeFuture.setClosed(); promise.setFailure(t); } } @@ -440,12 +441,12 @@ private void register0(ChannelPromise promise) { } catch (Throwable t) { // Close the channel directly to avoid FD leak. closeForcibly(); + closeFuture.setClosed(); if (!promise.tryFailure(t)) { logger.warn( "Tried to fail the registration promise, but it is complete already. " + "Swallowing the cause of the registration failure:", t); } - closeFuture.setClosed(); } } @@ -514,38 +515,39 @@ public void run() { return; } - boolean wasActive = isActive(); - if (closeFuture.setClosed()) { - ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; - this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. + if (closeFuture.isSuccess()) { + // Closed already. + promise.setSuccess(); + } - try { - doClose(); - promise.setSuccess(); - } catch (Throwable t) { - promise.setFailure(t); - } + boolean wasActive = isActive(); + ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; + this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. - // Fail all the queued messages - try { - outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); - outboundBuffer.close(CLOSED_CHANNEL_EXCEPTION); - } finally { + try { + doClose(); + closeFuture.setClosed(); + promise.setSuccess(); + } catch (Throwable t) { + promise.setFailure(t); + } - if (wasActive && !isActive()) { - invokeLater(new Runnable() { - @Override - public void run() { - pipeline.fireChannelInactive(); - } - }); - } + // Fail all the queued messages + try { + outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); + outboundBuffer.close(CLOSED_CHANNEL_EXCEPTION); + } finally { - deregister(voidPromise()); + if (wasActive && !isActive()) { + invokeLater(new Runnable() { + @Override + public void run() { + pipeline.fireChannelInactive(); + } + }); } - } else { - // Closed already. - promise.setSuccess(); + + deregister(voidPromise()); } } @@ -750,14 +752,6 @@ protected Runnable doRegister() throws Exception { */ protected abstract void doDisconnect() throws Exception; - /** - * Will be called before the actual close operation will be performed. Sub-classes may override this as the default - * is to do nothing. - */ - protected void doPreClose() throws Exception { - // NOOP by default - } - /** * Close the {@link Channel} */ @@ -834,11 +828,6 @@ public boolean tryFailure(Throwable cause) { } boolean setClosed() { - try { - doPreClose(); - } catch (Exception e) { - logger.warn("doPreClose() raised an exception.", e); - } return super.trySuccess(); } } diff --git a/transport/src/main/java/io/netty/channel/local/LocalChannel.java b/transport/src/main/java/io/netty/channel/local/LocalChannel.java index cc4acb20500..13b3c57abb1 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalChannel.java +++ b/transport/src/main/java/io/netty/channel/local/LocalChannel.java @@ -199,13 +199,12 @@ protected void doDisconnect() throws Exception { } @Override - protected void doPreClose() throws Exception { + protected void doClose() throws Exception { if (state > 2) { // Closed already return; } - // Update all internal state before the closeFuture is notified. if (localAddress != null) { if (parent() == null) { LocalChannelRegistry.unregister(localAddress); @@ -213,10 +212,7 @@ protected void doPreClose() throws Exception { localAddress = null; } state = 3; - } - @Override - protected void doClose() throws Exception { LocalChannel peer = this.peer; if (peer != null && peer.isActive()) { peer.unsafe().close(unsafe().voidPromise()); diff --git a/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java b/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java index 7f279cf4409..fc6c2d031ed 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java +++ b/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java @@ -94,23 +94,17 @@ protected void doBind(SocketAddress localAddress) throws Exception { } @Override - protected void doPreClose() throws Exception { + protected void doClose() throws Exception { if (state > 1) { // Closed already. return; } - // Update all internal state before the closeFuture is notified. LocalChannelRegistry.unregister(localAddress); localAddress = null; state = 2; } - @Override - protected void doClose() throws Exception { - // All internal state was updated already at doPreClose(). - } - @Override protected Runnable doDeregister() throws Exception { ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook);
null
val
train
2013-07-25T20:24:27
"2013-07-26T01:44:08Z"
jpinner
val
netty/netty/1720_1721
netty/netty
netty/netty/1720
netty/netty/1721
[ "timestamp(timedelta=53.0, similarity=0.9601021091043038)" ]
0b4adc0889e638f474f5876668cda0851ee3cfd7
cdd000e8551cc6bbe4dfeb81973c8ba5df5168f0
[ "duplicate of #1721 \n" ]
[ "You should move the setSuccess() call before the fireWriteComplete as we always notify the future first before fire this event in other transports\n" ]
"2013-08-09T16:03:45Z"
[]
intermittent: local channel sometimes sends messages after close (3.6)
A local channel can receive messages after it has been closed. This is the result of a race condition in DefaultLocalChannel.flushWriteBuffer: ``` e.getFuture().setSuccess(); fireMessageReceived(pairedChannel, e.getMessage()); fireWriteComplete(this, 1); ``` The future listener in this case is HttpConnectionHandler.ClosingChannelFutureListener. The problem is that the future.setSuccess() races with the fireMessageReceived. Moving the setSuccess to happen after the message is sent helps but doesn't completely remove the race: ``` fireMessageReceived(pairedChannel, e.getMessage()); fireWriteComplete(this, 1); e.getFuture().setSuccess(); ```
[ "src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java" ]
[ "src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java" ]
[]
diff --git a/src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java b/src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java index da02be3ece8..d127cd4d0a1 100644 --- a/src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java +++ b/src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java @@ -171,8 +171,8 @@ void flushWriteBuffer() { break; } - e.getFuture().setSuccess(); fireMessageReceived(pairedChannel, e.getMessage()); + e.getFuture().setSuccess(); fireWriteComplete(this, 1); } } finally { @@ -198,8 +198,8 @@ void flushWriteBuffer() { break; } - e.getFuture().setFailure(cause); fireExceptionCaught(this, cause); + e.getFuture().setFailure(cause); } } }
null
train
train
2013-06-05T08:52:56
"2013-08-09T15:59:39Z"
wgallagher
val
netty/netty/1481_1735
netty/netty
netty/netty/1481
netty/netty/1735
[ "timestamp(timedelta=40.0, similarity=0.8580937807760761)" ]
cc12e40065a0a27d81266cda863a4d24b4487a59
8c6520212206543f199a73a006469a4f1c51031a
[ "I found [this example ](http://www.jcraft.com/jsch/examples/CompressionJUZ.java) which explains how to \n**solely** use JDK for compression/decompression of a byte array as opposed to relying on external library JZlib.\n\nThe example is actually made by the author of JZlib. \n", "Let us try to do this for 4.1\n", "@phansson pull-req welcome ;)\n", "@phansson can you please test latest master, it now ship the requested decoder :)\n", "Made a simple test. No errors. Looks good.\n", "Thanks for testing\n\nAm 19.08.2013 um 08:43 schrieb phansson [email protected]:\n\n> Made a simple test. No errors. Looks good.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n" ]
[ "`Unpooled.copiedBuffer()`?\n", "Same for similar `wrapperBuffer()` calls\n", "Better use do-while because we already know `in` is readable at this point. Same applies for similar loops.\n" ]
"2013-08-12T18:33:59Z"
[ "improvement", "feature" ]
JDK zlib decompression support
With the changes implemented in JDK 7 I'm a bit uncertain as to whether a dependency on JZLib is still required. Currently Netty implements `JdkZlibEncoder` but doesn't implement a corresponding `JdkZlibDecoder`. I believe this is a historical omission based on the inability of previous versions of the JDK. Source code for [ZlibCodecFactory](http://netty.io/4.0/xref/io/netty/handler/codec/compression/ZlibCodecFactory.html) gives some idea as to what is currently going on but no comments as to why there's no `JdkZlibDecoder`. In other words: The proposal here is to implement `JdkZlibDecoder` in Netty and make it the default for decoding when using Java 7.
[ "codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java" ]
[ "codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java", "codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java" ]
[ "codec/src/test/java/io/netty/handler/codec/compression/JdkZlibTest.java" ]
diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java new file mode 100644 index 00000000000..5d860a15202 --- /dev/null +++ b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java @@ -0,0 +1,339 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.compression; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; + +import java.util.List; +import java.util.zip.CRC32; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + + +/** + * Decompress a {@link ByteBuf} using the inflate algorithm. + */ +public class JdkZlibDecoder extends ZlibDecoder { + private static final int FHCRC = 0x02; + private static final int FEXTRA = 0x04; + private static final int FNAME = 0x08; + private static final int FCOMMENT = 0x10; + private static final int FRESERVED = 0xE0; + + private final Inflater inflater; + private final byte[] dictionary; + + // GZIP related + private final CRC32 crc; + + private enum GzipState { + HEADER_START, + HEADER_END, + FLG_READ, + XLEN_READ, + SKIP_FNAME, + SKIP_COMMENT, + PROCESS_FHCRC, + FOOTER_START, + } + + private GzipState gzipState = GzipState.HEADER_START; + private int flags = -1; + private int xlen = -1; + + private volatile boolean finished; + + /** + * Creates a new instance with the default wrapper ({@link ZlibWrapper#ZLIB}). + */ + public JdkZlibDecoder() { + this(ZlibWrapper.ZLIB, null); + } + + /** + * Creates a new instance with the specified preset dictionary. The wrapper + * is always {@link ZlibWrapper#ZLIB} because it is the only format that + * supports the preset dictionary. + */ + public JdkZlibDecoder(byte[] dictionary) { + this(ZlibWrapper.ZLIB, dictionary); + } + + /** + * Creates a new instance with the specified wrapper. + * Be aware that only {@link ZlibWrapper#GZIP}, {@link ZlibWrapper#ZLIB} and {@link ZlibWrapper#NONE} are + * supported atm. + */ + public JdkZlibDecoder(ZlibWrapper wrapper) { + this(wrapper, null); + } + + private JdkZlibDecoder(ZlibWrapper wrapper, byte[] dictionary) { + if (wrapper == null) { + throw new NullPointerException("wrapper"); + } + switch (wrapper) { + case GZIP: + inflater = new Inflater(true); + crc = new CRC32(); + break; + case NONE: + inflater = new Inflater(true); + crc = null; + break; + case ZLIB: + inflater = new Inflater(); + crc = null; + break; + default: + throw new IllegalArgumentException("Only GZIP or ZLIB is supported, but you used " + wrapper); + } + this.dictionary = dictionary; + } + + @Override + public boolean isClosed() { + return finished; + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { + if (!in.isReadable() && finished) { + return; + } + + if (crc != null) { + switch (gzipState) { + case FOOTER_START: + if (readGZIPFooter(in)) { + finished = true; + } + return; + default: + if (gzipState != GzipState.HEADER_END) { + if (!readGZIPHeader(in)) { + return; + } + } + } + } + + int readableBytes = in.readableBytes(); + if (in.hasArray()) { + inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), in.readableBytes()); + } else { + byte[] array = new byte[in.readableBytes()]; + in.getBytes(in.readerIndex(), array); + inflater.setInput(array); + } + + int maxOutputLength = inflater.getRemaining() << 1; + ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength); + try { + boolean readFooter = false; + while (!inflater.needsInput()) { + byte[] outArray = decompressed.array(); + int outIndex = decompressed.arrayOffset() + decompressed.writerIndex(); + int length = outArray.length - outIndex; + + int outputLength = inflater.inflate(outArray, outIndex, length); + + if (outputLength > 0) { + decompressed.writerIndex(decompressed.writerIndex() + outputLength); + if (crc != null) { + crc.update(outArray, outIndex, length); + } + } else { + if (inflater.needsDictionary()) { + if (dictionary == null) { + throw new DecompressionException( + "decompression failure, unable to set dictionary as non was specified"); + } + inflater.setDictionary(dictionary); + } + } + + if (inflater.finished()) { + if (crc == null) { + finished = true; // Do not decode anymore. + } else { + readFooter = true; + } + break; + } + } + + in.skipBytes(readableBytes - inflater.getRemaining()); + + if (readFooter) { + gzipState = GzipState.FOOTER_START; + if (readGZIPFooter(in)) { + finished = true; + } + } + } catch (DataFormatException e) { + throw new DecompressionException("decompression failure", e); + } finally { + + if (decompressed.isReadable()) { + out.add(decompressed); + } else { + decompressed.release(); + } + } + } + + @Override + protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { + super.handlerRemoved0(ctx); + inflater.end(); + } + + private boolean readGZIPHeader(ByteBuf in) { + switch (gzipState) { + case HEADER_START: + if (in.readableBytes() < 10) { + return false; + } + // read magic numbers + int magic0 = in.readByte(); + int magic1 = in.readByte(); + + if (magic0 != 31) { + throw new CompressionException("Input is not in the GZIP format"); + } + crc.update(magic0); + crc.update(magic1); + + int method = in.readUnsignedByte(); + if (method != Deflater.DEFLATED) { + throw new CompressionException("Unsupported compression method " + + method + " in the GZIP header"); + } + crc.update(method); + + flags = in.readUnsignedByte(); + crc.update(flags); + + if ((flags & FRESERVED) != 0) { + throw new CompressionException( + "Reserved flags are set in the GZIP header"); + } + + // mtime (int) + crc.update(in.readByte()); + crc.update(in.readByte()); + crc.update(in.readByte()); + crc.update(in.readByte()); + + crc.update(in.readUnsignedByte()); // extra flags + crc.update(in.readUnsignedByte()); // operating system + + gzipState = GzipState.FLG_READ; + case FLG_READ: + if ((flags & FEXTRA) != 0) { + if (in.readableBytes() < 2) { + return false; + } + int xlen1 = in.readUnsignedByte(); + int xlen2 = in.readUnsignedByte(); + crc.update(xlen1); + crc.update(xlen2); + + xlen |= xlen1 << 8 | xlen2; + } + gzipState = GzipState.XLEN_READ; + case XLEN_READ: + if (xlen != -1) { + if (in.readableBytes() < xlen) { + return false; + } + byte[] xtra = new byte[xlen]; + in.readBytes(xtra); + crc.update(xtra); + } + gzipState = GzipState.SKIP_FNAME; + case SKIP_FNAME: + if ((flags & FNAME) != 0) { + if (!in.isReadable()) { + return false; + } + while (in.isReadable()) { + int b = in.readUnsignedByte(); + crc.update(b); + if (b == 0x00) { + break; + } + } + } + gzipState = GzipState.SKIP_COMMENT; + case SKIP_COMMENT: + if ((flags & FCOMMENT) != 0) { + if (!in.isReadable()) { + return false; + } + while (in.isReadable()) { + int b = in.readUnsignedByte(); + crc.update(b); + if (b == 0x00) { + break; + } + } + } + gzipState = GzipState.PROCESS_FHCRC; + case PROCESS_FHCRC: + if ((flags & FHCRC) != 0) { + if (!in.isReadable()) { + return false; + } + int headerCrc = in.readShort(); + int readCrc = (int) crc.getValue() & 0xffff; + if (headerCrc != readCrc) { + throw new CompressionException( + "Header CRC value missmatch. Expected: " + headerCrc + ", Got: " + readCrc); + } + } + crc.reset(); + gzipState = GzipState.HEADER_END; + case HEADER_END: + return true; + default: + throw new IllegalStateException(); + } + } + + private boolean readGZIPFooter(ByteBuf buf) { + if (buf.readableBytes() < 8) { + return false; + } + int dataCrc = buf.readInt(); + int readCrc = (int) crc.getValue() & 0xffff; + if (dataCrc != readCrc) { + throw new CompressionException( + "Data CRC value missmatch. Expected: " + dataCrc + ", Got: " + readCrc); + } + + int dataLength = buf.readInt(); + int readLength = inflater.getTotalOut(); + if (dataLength != readLength) { + throw new CompressionException( + "Number of bytes missmatch. Expected: " + dataLength + ", Got: " + readLength); + } + return true; + } +} diff --git a/codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java b/codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java index 979a124694d..60f51073b02 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/ZlibCodecFactory.java @@ -79,15 +79,32 @@ public static ZlibEncoder newZlibEncoder(int compressionLevel, int windowBits, i } public static ZlibDecoder newZlibDecoder() { - return new JZlibDecoder(); + if (PlatformDependent.javaVersion() < 7) { + return new JZlibDecoder(); + } else { + return new JdkZlibDecoder(); + } } public static ZlibDecoder newZlibDecoder(ZlibWrapper wrapper) { - return new JZlibDecoder(wrapper); + switch (wrapper) { + case ZLIB_OR_NONE: + return new JZlibDecoder(wrapper); + default: + if (PlatformDependent.javaVersion() < 7) { + return new JZlibDecoder(wrapper); + } else { + return new JdkZlibDecoder(wrapper); + } + } } public static ZlibDecoder newZlibDecoder(byte[] dictionary) { - return new JZlibDecoder(dictionary); + if (PlatformDependent.javaVersion() < 7) { + return new JZlibDecoder(dictionary); + } else { + return new JdkZlibDecoder(dictionary); + } } private ZlibCodecFactory() {
diff --git a/codec/src/test/java/io/netty/handler/codec/compression/JdkZlibTest.java b/codec/src/test/java/io/netty/handler/codec/compression/JdkZlibTest.java new file mode 100644 index 00000000000..9a93aa8fb2f --- /dev/null +++ b/codec/src/test/java/io/netty/handler/codec/compression/JdkZlibTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.compression; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JdkZlibTest { + + @Test + public void testZLIB() throws Exception { + ByteBuf data = Unpooled.wrappedBuffer("test".getBytes()); + + EmbeddedChannel chEncoder = new EmbeddedChannel(new JdkZlibEncoder(ZlibWrapper.ZLIB)); + + chEncoder.writeOutbound(data.copy()); + assertTrue(chEncoder.finish()); + + ByteBuf deflatedData = (ByteBuf) chEncoder.readOutbound(); + + EmbeddedChannel chDecoderZlib = new EmbeddedChannel(new JdkZlibDecoder(ZlibWrapper.ZLIB)); + + chDecoderZlib.writeInbound(deflatedData.copy()); + assertTrue(chDecoderZlib.finish()); + + assertEquals(data, chDecoderZlib.readInbound()); + } + + @Test + public void testNONE() throws Exception { + ByteBuf data = Unpooled.wrappedBuffer("test".getBytes()); + + EmbeddedChannel chEncoder = new EmbeddedChannel(new JdkZlibEncoder(ZlibWrapper.NONE)); + + chEncoder.writeOutbound(data.copy()); + assertTrue(chEncoder.finish()); + + ByteBuf deflatedData = (ByteBuf) chEncoder.readOutbound(); + + EmbeddedChannel chDecoderZlibNone = new EmbeddedChannel(new JdkZlibDecoder(ZlibWrapper.NONE)); + + chDecoderZlibNone.writeInbound(deflatedData.copy()); + assertTrue(chDecoderZlibNone.finish()); + + assertEquals(data, chDecoderZlibNone.readInbound()); + } + + @Test(expected = IllegalArgumentException.class) + public void testZLIB_OR_NONE() throws Exception { + new JdkZlibDecoder(ZlibWrapper.ZLIB_OR_NONE); + } + + @Test + public void testGZIP() throws Exception { + ByteBuf data = Unpooled.wrappedBuffer("test".getBytes()); + + EmbeddedChannel chEncoder = new EmbeddedChannel(new JdkZlibEncoder(ZlibWrapper.GZIP)); + + chEncoder.writeOutbound(data.copy()); + assertTrue(chEncoder.finish()); + + ByteBuf deflatedData = (ByteBuf) chEncoder.readOutbound(); + + EmbeddedChannel chDecoderGZip = new EmbeddedChannel(new JdkZlibDecoder(ZlibWrapper.GZIP)); + + chDecoderGZip.writeInbound(deflatedData.copy()); + assertTrue(chDecoderGZip.finish()); + + assertEquals(data, chDecoderGZip.readInbound()); + } +}
train
train
2013-08-12T07:23:00
"2013-06-23T11:25:26Z"
phansson
val
netty/netty/1765_1767
netty/netty
netty/netty/1765
netty/netty/1767
[ "timestamp(timedelta=16622.0, similarity=0.8519716299467585)" ]
fb619f23947aab158a11730e00f4dbd490093669
be70d42a340f4cba19069b1c5d194c0d02930425
[ "adding `buf.append(Long.toHexString(ThreadLocalRandom.current().nextLong() & 0xFFFFFFFFL | 0x100000000L));` in the LocalAddress constructor makes the collision less likely, although I don't think it removes it altogether. Perhaps using something like `java.util.UUID` would be more appropriate, ala `buf.append(UUID.randomUUID().toString().replace('-', ':'));`\n", "[This](https://gist.github.com/mhgrove/6295318) is a modified version of LocalEcho which creates and runs clients their own thread. On my machine, this reproduces the name collision every single time. If I apply either of the modifications to `LocalAddress` then it does not seem to occur.\n", "It is interesting that this issue is always reproducible for you. I can't reproduce it at all. Looking from the source code of ThreadLocalRandom and Random, I think it is pretty difficult for two different channels to get the same hashCode() because each ThreadLocalRandom is supposed to have different seeds. What JDK do you use?\n", "Yeah, I also found it interesting that the only explanation seemed to be that two different Randoms produced the same nextLong, which I assume would really only happen if they had the same seed, and that also seemed unlikely.\n\nIn any case, I'm on OSX 10.8.3 w/ Java 1.6.0_45-b06-451-11M4406\n", "Java 6 does a sloppy job in generating seeds, so I overrode it to make `ThreadLocalRandom` work better. Please feel free to reopen if you find the fix does not work.\n" ]
[]
"2013-08-21T15:52:16Z"
[ "defect" ]
LocalAddress's can collide in a multi-client setup
Using Netty 4.0.7, I'm randomly running into this exception when connecting many clients to the server over a LocalChannel: ``` io.netty.channel.ChannelException: address already in use by: [id: 0x65219647, local:E:65219647 => local:stardog] at io.netty.channel.local.LocalChannelRegistry.register(LocalChannelRegistry.java:46) at io.netty.channel.local.LocalChannel.doBind(LocalChannel.java:177) at io.netty.channel.local.LocalChannel$LocalUnsafe.connect(LocalChannel.java:338) at io.netty.channel.DefaultChannelPipeline$HeadHandler.connect(DefaultChannelPipeline.java:1008) at io.netty.channel.DefaultChannelHandlerContext.invokeConnect(DefaultChannelHandlerContext.java:491) at io.netty.channel.DefaultChannelHandlerContext.connect(DefaultChannelHandlerContext.java:476) at io.netty.channel.DefaultChannelHandlerContext.connect(DefaultChannelHandlerContext.java:461) at io.netty.channel.DefaultChannelPipeline.connect(DefaultChannelPipeline.java:847) at io.netty.channel.AbstractChannel.connect(AbstractChannel.java:198) at io.netty.bootstrap.Bootstrap$2.run(Bootstrap.java:165) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:354) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:366) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101) ``` It looks like the ID of the LocalAddress is created from the hashCode of the LocalChannel its connected to. It's entirely possible that two LocalChannels which are not == to get the same hashCode, which means their LocalAddresses will collide and you'll get the aforementioned stacktrace. This greatly hampers a multi-client use case w/ LocalChannel/LocalAddress.
[ "transport/src/main/java/io/netty/channel/local/LocalAddress.java" ]
[ "transport/src/main/java/io/netty/channel/local/LocalAddress.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/local/LocalAddress.java b/transport/src/main/java/io/netty/channel/local/LocalAddress.java index 6098cca470e..511f012b65c 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalAddress.java +++ b/transport/src/main/java/io/netty/channel/local/LocalAddress.java @@ -18,6 +18,7 @@ import io.netty.channel.Channel; import java.net.SocketAddress; +import java.util.UUID; /** * An endpoint in the local transport. Each endpoint is identified by a unique @@ -40,7 +41,7 @@ public final class LocalAddress extends SocketAddress implements Comparable<Loca LocalAddress(Channel channel) { StringBuilder buf = new StringBuilder(16); buf.append("local:E"); - buf.append(Long.toHexString(channel.hashCode() & 0xFFFFFFFFL | 0x100000000L)); + buf.append(UUID.randomUUID().toString().replace('-', ':')); buf.setCharAt(7, ':'); id = buf.substring(6); strVal = buf.toString();
null
test
train
2013-08-21T16:39:50
"2013-08-21T13:47:36Z"
mhgrove
val
netty/netty/1833_1834
netty/netty
netty/netty/1833
netty/netty/1834
[ "timestamp(timedelta=37.0, similarity=0.8890629724375693)" ]
87a6a68059f27b3118d56f76f0d98621f4a618be
c38ef2c4c86396b8c9521a8eb6312cfde414b56c
[ "@jianjin can you give some details on what not work and what you expect it to do ?\n", "If an url like this : http://foo.com/images;num=10?query=name;value=123\nthe first \";\" should not be replaced by &, because it is part of path but NOT query.\nHost:foo.com\nPath:/images\nPath Parameter:num=10\nQueryParameters:query=name and value=123\n\nThe getPath() should be /images;num=10 but not /images&num=10\n", "https://github.com/netty/netty/blob/master/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java#L117\n\n^ that should probably only be applied to the query string instead of the whole URI\n", "Yep. Or we could change the code @ https://github.com/netty/netty/blob/master/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java#L225\n\nto (c == '&' || c == ';') {\n", "Could you submit a pull-req ?\nAm 12.09.2013 um 12:05 schrieb jian jin [email protected]:\n\n> Yep. Or we could change the code @ https://github.com/netty/netty/blob/master/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java#L225\n> \n> to (c == '&' || c == ';') {\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "@jianjin @normanmaurer ,the ;in URL is just like &\n\nsee this:\n\n```\nAccording to the W3C: http://www.w3.org/TR/html401/appendix/notes.html#h-B.2.2\n\nWe recommend that HTTP server implementors, and in particular, CGI implementors support the use of \";\" in place of \"&\" to save authors the trouble of escaping \"&\" characters in this manner.\nThe query string decoder that Netty provides follows this recommendation, which I think is reasonable. The best thing to do is probably to use a separator other than ; or URL-encode your data.\n```\n", "so \nlocalhost/get?key=a;b;c \nwill make key=a ,and treat b and c as keys which will be null.\nkey=a\na=null\nc=null\n", "@jianjin I am wandering ,why you make you url pattern like that?\n", "@hepin1989 Netty's decoder does it wrong at the moment, that's the issue here. Netty replaces ; with & in the whole URI instead of just the query string.\n", "@quickwango really?okay,just send a pull request.\n", "just did it via the browser, I don't expect anything to break though\n", "cool. Would we fix it in 3.x also?\n", "Sure. the fix should go to both 3.x and 4.x.\n", "Fixed in branches 3, 4.0 and master\n" ]
[]
"2013-09-12T12:10:02Z"
[ "defect" ]
QueryStringDecoder replace all ; using &
If the url is /hello;pathparameter Then System.out.println(decoder.getPath()); will replace ; to & : /hello&pathparameter Simply replace ; use & does not work.
[ "codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java index 792452f44e3..4075efa25b1 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java @@ -113,8 +113,7 @@ public QueryStringDecoder(String uri, Charset charset, boolean hasPath, int maxP "maxParams: " + maxParams + " (expected: a positive integer)"); } - // http://en.wikipedia.org/wiki/Query_string - this.uri = uri.replace(';', '&'); + this.uri = uri; this.charset = charset; this.maxParams = maxParams; this.hasPath = hasPath; @@ -160,10 +159,8 @@ public QueryStringDecoder(URI uri, Charset charset, int maxParams) { hasPath = false; } // Also take care of cut of things like "http://localhost" - String newUri = rawPath + '?' + uri.getRawQuery(); + this.uri = rawPath + '?' + uri.getRawQuery(); - // http://en.wikipedia.org/wiki/Query_string - this.uri = newUri.replace(';', '&'); this.charset = charset; this.maxParams = maxParams; } @@ -222,7 +219,8 @@ private void decodeParams(String s) { name = decodeComponent(s.substring(pos, i), charset); } pos = i + 1; - } else if (c == '&') { + // http://www.w3.org/TR/html401/appendix/notes.html#h-B.2.2 + } else if (c == '&' || c == ';') { if (name == null && pos != i) { // We haven't seen an `=' so far but moved forward. // Must be a param of the form '&a&' so add it with
null
test
train
2013-09-12T09:29:40
"2013-09-12T03:35:43Z"
jianjin
val
netty/netty/1844_1856
netty/netty
netty/netty/1844
netty/netty/1856
[ "timestamp(timedelta=23.0, similarity=0.8510320016967471)" ]
a855f19ad6fd79a3b6034bff3fdeab710d5563d1
92433c31fcb845052ec51c35126a0c15dfe41311
[ "The following fix should work:\n\n``` java\n String uri = request.getUri();\n\n if (uri.length() == 0) {\n uri += SLASH;\n } else {\n int start = uri.indexOf(\"://\");\n if (start != -1 && uri.charAt(0) != SLASH) {\n int startIndex = start + 3;\n if (uri.lastIndexOf(SLASH) <= startIndex) {\n uri += SLASH;\n }\n }\n }\n```\n\n I will try to submit a pull request for this later; I don't have a working full netty build and should write tests.\n" ]
[]
"2013-09-19T15:49:40Z"
[]
HttpRequestEncoder erroneously appending '/' to absolute path requests that contain '://' in the path, query, or fragment
`io.netty.handler.codec.http.HttpRequestEncoder` contains the following code: ``` java // Add / as absolute path if no is present. // See http://tools.ietf.org/html/rfc2616#section-5.1.2 String uri = request.getUri(); int start = uri.indexOf("://"); if (start != -1) { int startIndex = start + 3; if (uri.lastIndexOf(SLASH) <= startIndex) { uri += SLASH; } } ``` In the case where the Http Request line is in the absolute path format (that is, it does not contain 'http://', this will find other possible occurrences of '://' in the request path. If there are no other backslashes after this in the request line, then a trailing backslash will be appended to the request. For example, the request: `GET /example?uri=http://example.com&size=3` will be transformed into: `GET /example?uri=http://example.com&size=3/` URLs containing `://` in the query or fragment are valid by RFC 3986, and I don't think netty should be modifying them.
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java index c7aa051596e..3dc959bd1d1 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpRequestEncoder.java @@ -41,13 +41,19 @@ protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Except // Add / as absolute path if no is present. // See http://tools.ietf.org/html/rfc2616#section-5.1.2 String uri = request.getUri(); - int start = uri.indexOf("://"); - if (start != -1) { - int startIndex = start + 3; - if (uri.lastIndexOf(SLASH) <= startIndex) { - uri += SLASH; + + if (uri.length() == 0) { + uri += SLASH; + } else { + int start = uri.indexOf("://"); + if (start != -1 && uri.charAt(0) != SLASH) { + int startIndex = start + 3; + if (uri.lastIndexOf(SLASH) <= startIndex) { + uri += SLASH; + } } } + buf.writeBytes(uri.getBytes(CharsetUtil.UTF_8)); buf.writeByte(SP);
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java index 3d13cf9faef..6ed9b95ff62 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java @@ -46,4 +46,34 @@ public void testUriWithPath() throws Exception { String req = buffer.toString(Charset.forName("US-ASCII")); assertEquals("GET http://localhost/ HTTP/1.1\r\n", req); } + + @Test + public void testAbsPath() throws Exception { + HttpRequestEncoder encoder = new HttpRequestEncoder(); + ByteBuf buffer = Unpooled.buffer(64); + encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, + HttpMethod.GET, "/")); + String req = buffer.toString(Charset.forName("US-ASCII")); + assertEquals("GET / HTTP/1.1\r\n", req); + } + + @Test + public void testEmptyAbsPath() throws Exception { + HttpRequestEncoder encoder = new HttpRequestEncoder(); + ByteBuf buffer = Unpooled.buffer(64); + encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, + HttpMethod.GET, "")); + String req = buffer.toString(Charset.forName("US-ASCII")); + assertEquals("GET / HTTP/1.1\r\n", req); + } + + @Test + public void testQueryStringPath() throws Exception { + HttpRequestEncoder encoder = new HttpRequestEncoder(); + ByteBuf buffer = Unpooled.buffer(64); + encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, + HttpMethod.GET, "/?url=http://example.com")); + String req = buffer.toString(Charset.forName("US-ASCII")); + assertEquals("GET /?url=http://example.com HTTP/1.1\r\n", req); + } }
val
train
2013-09-19T07:29:21
"2013-09-16T14:57:23Z"
ANorwell
val
netty/netty/1832_1877
netty/netty
netty/netty/1832
netty/netty/1877
[ "timestamp(timedelta=47.0, similarity=0.9259862956779858)" ]
512908f993d183cc2a7d8f8f9ebec44d174b7488
474672b120d25ddb95d5ff2ad3a202b8b645f6e3
[ "@wgallagher and assigned to you... have fun ;)\n", "@wgallagher ping ;)\n", "@wgallagher any news here ? I would love to cut 4.0.10.Final early next week.\n", "@oxtoacart was fixed... please retest with latest snapshot.\n", "@wgallagher I tried `4.1.0.Alpha1-SNAPSHOT` and this seems to be working fine for me now. Thanks for fixing it!\n" ]
[]
"2013-09-30T15:35:58Z"
[]
Channel writability change notifications sometimes fail to fire
As of the changes made for #1766, sometimes channel writability notifications are lost. In particular, I've noticed this when writing from a thread other than the channel's EventLoop. I believe that there's a logic error in `ChannelOutboundBuffer` in the `incrementPendingOutboundBytes` and `decrementPendingOutboundBytes` methods. In particular, each method does something like this: ``` java if (newWriteBufferSize > highWaterMark) { if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { if (fireEvent) { channel.pipeline().fireChannelWritabilityChanged(); } } } ``` `WRITABLE_UPDATER.compareAndSet(this, 1, 0)` handles updating the writability flag. However, we only notify if `fireEvent` is true. The problem is that if the writability flag happens to change inside of a call where `fireEvent` is false, then the pipeline will never be notified about the fact that the writability changed. I don't actually quite understand the need for the `fireEvent` flag, but assuming it's necessary, there seem to be a couple of parsimonious solutions available. ## Solution 1 Reverse the calls: ``` java if (newWriteBufferSize > highWaterMark) { if (fireEvent) { if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { channel.pipeline().fireChannelWritabilityChanged(); } } } ``` In this implementation, the result from Channel.isWritable() is always in sync with whatever notifications have been made. ## Solution 2 Use a second writable status: ``` java if (newWriteBufferSize > highWaterMark) { if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { if (fireEvent) { if (LAST_NOTIFIED_WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { channel.pipeline().fireChannelWritabilityChanged(); } } } } ``` In this implementation, the result from Channel.isWritable() is always super up-to-date and the notification can lag, but you will get notified at some point.
[ "transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java" ]
[ "transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java", "transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java" ]
[ "transport/src/test/java/io/netty/channel/ReentrantChannelTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java b/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java index 48a8c31aa78..393aad82463 100644 --- a/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java +++ b/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java @@ -129,7 +129,7 @@ void addMessage(Object msg, ChannelPromise promise) { // increment pending bytes after adding message to the unflushed arrays. // See https://github.com/netty/netty/issues/1619 - incrementPendingOutboundBytes(size, true); + incrementPendingOutboundBytes(size); } private void addCapacity() { @@ -164,7 +164,7 @@ void addFlush() { * Increment the pending bytes which will be written at some point. * This method is thread-safe! */ - void incrementPendingOutboundBytes(int size, boolean fireEvent) { + void incrementPendingOutboundBytes(int size) { // Cache the channel and check for null to make sure we not produce a NPE in case of the Channel gets // recycled while process this method. Channel channel = this.channel; @@ -183,9 +183,7 @@ void incrementPendingOutboundBytes(int size, boolean fireEvent) { if (newWriteBufferSize > highWaterMark) { if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { - if (fireEvent) { - channel.pipeline().fireChannelWritabilityChanged(); - } + channel.pipeline().fireChannelWritabilityChanged(); } } } @@ -194,7 +192,7 @@ void incrementPendingOutboundBytes(int size, boolean fireEvent) { * Decrement the pending bytes which will be written at some point. * This method is thread-safe! */ - void decrementPendingOutboundBytes(int size, boolean fireEvent) { + void decrementPendingOutboundBytes(int size) { // Cache the channel and check for null to make sure we not produce a NPE in case of the Channel gets // recycled while process this method. Channel channel = this.channel; @@ -213,9 +211,7 @@ void decrementPendingOutboundBytes(int size, boolean fireEvent) { if (newWriteBufferSize == 0 || newWriteBufferSize < lowWaterMark) { if (WRITABLE_UPDATER.compareAndSet(this, 0, 1)) { - if (fireEvent) { - channel.pipeline().fireChannelWritabilityChanged(); - } + channel.pipeline().fireChannelWritabilityChanged(); } } } @@ -316,7 +312,7 @@ public boolean remove() { safeRelease(msg); promise.trySuccess(); - decrementPendingOutboundBytes(size, true); + decrementPendingOutboundBytes(size); return true; } @@ -342,7 +338,7 @@ public boolean remove(Throwable cause) { safeRelease(msg); safeFail(promise, cause); - decrementPendingOutboundBytes(size, true); + decrementPendingOutboundBytes(size); return true; } diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java index 38eab413988..352aa6426d8 100644 --- a/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelHandlerContext.java @@ -642,7 +642,7 @@ private void write(Object msg, boolean flush, ChannelPromise promise) { ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); // Check for null as it may be set to null if the channel is closed already if (buffer != null) { - buffer.incrementPendingOutboundBytes(size, false); + buffer.incrementPendingOutboundBytes(size); } } executor.execute(WriteTask.newInstance(next, msg, size, flush, promise)); @@ -822,7 +822,7 @@ public void run() { ChannelOutboundBuffer buffer = ctx.channel.unsafe().outboundBuffer(); // Check for null as it may be set to null if the channel is closed already if (buffer != null) { - buffer.decrementPendingOutboundBytes(size, false); + buffer.decrementPendingOutboundBytes(size); } } ctx.invokeWrite(msg, promise);
diff --git a/transport/src/test/java/io/netty/channel/ReentrantChannelTest.java b/transport/src/test/java/io/netty/channel/ReentrantChannelTest.java index 67cd5fbe177..f0bf9bb308d 100644 --- a/transport/src/test/java/io/netty/channel/ReentrantChannelTest.java +++ b/transport/src/test/java/io/netty/channel/ReentrantChannelTest.java @@ -54,6 +54,8 @@ public void testWritabilityChanged() throws Exception { clientChannel.close().sync(); assertLog( + "WRITABILITY: writable=false\n" + + "WRITABILITY: writable=true\n" + "WRITE\n" + "WRITABILITY: writable=false\n" + "FLUSH\n" + @@ -91,6 +93,9 @@ public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exceptio clientChannel.close().sync(); assertLog( + "WRITABILITY: writable=false\n" + + "FLUSH\n" + + "WRITABILITY: writable=true\n" + "WRITE\n" + "WRITABILITY: writable=false\n" + "FLUSH\n" +
test
train
2013-09-30T14:49:03
"2013-09-11T15:20:29Z"
oxtoacart
val
netty/netty/1958_1963
netty/netty
netty/netty/1958
netty/netty/1963
[ "timestamp(timedelta=26.0, similarity=0.936257143643118)" ]
285dd79a10ac5363ed0e579005c97af76aac7592
d52986be214f1bce4ce6b1251084bfb65b24d2de
[ "@nxmbriggs404 I don't think there is any \"real\" reason for this.... @lw346 could you have a look ?\n", "Sure - I think it's just me failing to read the spec properly. Will sort out by tomorrow.\n", "This has been slightly hampered by the fact that java doesn't have unsigned types, but I think I've got this now. I'm going to open a pull request as I'd like my bit-wrangling logic verifying.\n", "@lw346 thanks for fixed.. cherry picked into 4.0 and master.\n" ]
[]
"2013-11-01T17:20:50Z"
[]
Use CRC32-C in Snappy Framing Format Implementation
I have recently been researching Java Snappy implementations and came across a curiosity in netty's implementation. Specifically, it looks like the code in: https://github.com/netty/netty/blob/master/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java is using CRC32 rather than CRC32-C for its masked checksum computations. The "Snappy framing format description" at: https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt metions in section 3, "Checksum format", that: "The checksums are always masked CRC-32Cs. A description of CRC-32C can be found in RFC 3720, section 12.1, with examples in section B.4." Other Java implementations I've come across take pains to use CRC-32C, typically defining the code themselves as in: https://github.com/dain/snappy/blob/master/src/main/java/org/iq80/snappy/Crc32C.java I didn't immediately find anything in the git history or the issues tracker that suggested this was an intentional choice, or if it might just be an oversight. Please note it's not impacting me in any way, it's just something I came across and wanted to bring up in case it actually was an oversight. Thanks, Matt
[ "codec/src/main/java/io/netty/handler/codec/compression/Snappy.java" ]
[ "codec/src/main/java/io/netty/handler/codec/compression/Crc32c.java", "codec/src/main/java/io/netty/handler/codec/compression/Snappy.java" ]
[ "codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedDecoderTest.java", "codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedEncoderTest.java", "codec/src/test/java/io/netty/handler/codec/compression/SnappyTest.java" ]
diff --git a/codec/src/main/java/io/netty/handler/codec/compression/Crc32c.java b/codec/src/main/java/io/netty/handler/codec/compression/Crc32c.java new file mode 100644 index 00000000000..b67c20004ae --- /dev/null +++ b/codec/src/main/java/io/netty/handler/codec/compression/Crc32c.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.compression; + +import java.util.zip.Checksum; + +/** + * Implements CRC32-C as defined in: + * "Optimization of Cyclic Redundancy-CHeck Codes with 24 and 32 Parity Bits", + * IEEE Transactions on Communications 41(6): 883-892 (1993). + * + * The implementation of this class has been sourced from the Appendix of RFC 3309, + * but with masking due to Java not being able to support unsigned types. + */ +class Crc32c implements Checksum { + private static final int[] CRC_TABLE = { + 0x00000000, 0xF26B8303, 0xE13B70F7, 0x1350F3F4, + 0xC79A971F, 0x35F1141C, 0x26A1E7E8, 0xD4CA64EB, + 0x8AD958CF, 0x78B2DBCC, 0x6BE22838, 0x9989AB3B, + 0x4D43CFD0, 0xBF284CD3, 0xAC78BF27, 0x5E133C24, + 0x105EC76F, 0xE235446C, 0xF165B798, 0x030E349B, + 0xD7C45070, 0x25AFD373, 0x36FF2087, 0xC494A384, + 0x9A879FA0, 0x68EC1CA3, 0x7BBCEF57, 0x89D76C54, + 0x5D1D08BF, 0xAF768BBC, 0xBC267848, 0x4E4DFB4B, + 0x20BD8EDE, 0xD2D60DDD, 0xC186FE29, 0x33ED7D2A, + 0xE72719C1, 0x154C9AC2, 0x061C6936, 0xF477EA35, + 0xAA64D611, 0x580F5512, 0x4B5FA6E6, 0xB93425E5, + 0x6DFE410E, 0x9F95C20D, 0x8CC531F9, 0x7EAEB2FA, + 0x30E349B1, 0xC288CAB2, 0xD1D83946, 0x23B3BA45, + 0xF779DEAE, 0x05125DAD, 0x1642AE59, 0xE4292D5A, + 0xBA3A117E, 0x4851927D, 0x5B016189, 0xA96AE28A, + 0x7DA08661, 0x8FCB0562, 0x9C9BF696, 0x6EF07595, + 0x417B1DBC, 0xB3109EBF, 0xA0406D4B, 0x522BEE48, + 0x86E18AA3, 0x748A09A0, 0x67DAFA54, 0x95B17957, + 0xCBA24573, 0x39C9C670, 0x2A993584, 0xD8F2B687, + 0x0C38D26C, 0xFE53516F, 0xED03A29B, 0x1F682198, + 0x5125DAD3, 0xA34E59D0, 0xB01EAA24, 0x42752927, + 0x96BF4DCC, 0x64D4CECF, 0x77843D3B, 0x85EFBE38, + 0xDBFC821C, 0x2997011F, 0x3AC7F2EB, 0xC8AC71E8, + 0x1C661503, 0xEE0D9600, 0xFD5D65F4, 0x0F36E6F7, + 0x61C69362, 0x93AD1061, 0x80FDE395, 0x72966096, + 0xA65C047D, 0x5437877E, 0x4767748A, 0xB50CF789, + 0xEB1FCBAD, 0x197448AE, 0x0A24BB5A, 0xF84F3859, + 0x2C855CB2, 0xDEEEDFB1, 0xCDBE2C45, 0x3FD5AF46, + 0x7198540D, 0x83F3D70E, 0x90A324FA, 0x62C8A7F9, + 0xB602C312, 0x44694011, 0x5739B3E5, 0xA55230E6, + 0xFB410CC2, 0x092A8FC1, 0x1A7A7C35, 0xE811FF36, + 0x3CDB9BDD, 0xCEB018DE, 0xDDE0EB2A, 0x2F8B6829, + 0x82F63B78, 0x709DB87B, 0x63CD4B8F, 0x91A6C88C, + 0x456CAC67, 0xB7072F64, 0xA457DC90, 0x563C5F93, + 0x082F63B7, 0xFA44E0B4, 0xE9141340, 0x1B7F9043, + 0xCFB5F4A8, 0x3DDE77AB, 0x2E8E845F, 0xDCE5075C, + 0x92A8FC17, 0x60C37F14, 0x73938CE0, 0x81F80FE3, + 0x55326B08, 0xA759E80B, 0xB4091BFF, 0x466298FC, + 0x1871A4D8, 0xEA1A27DB, 0xF94AD42F, 0x0B21572C, + 0xDFEB33C7, 0x2D80B0C4, 0x3ED04330, 0xCCBBC033, + 0xA24BB5A6, 0x502036A5, 0x4370C551, 0xB11B4652, + 0x65D122B9, 0x97BAA1BA, 0x84EA524E, 0x7681D14D, + 0x2892ED69, 0xDAF96E6A, 0xC9A99D9E, 0x3BC21E9D, + 0xEF087A76, 0x1D63F975, 0x0E330A81, 0xFC588982, + 0xB21572C9, 0x407EF1CA, 0x532E023E, 0xA145813D, + 0x758FE5D6, 0x87E466D5, 0x94B49521, 0x66DF1622, + 0x38CC2A06, 0xCAA7A905, 0xD9F75AF1, 0x2B9CD9F2, + 0xFF56BD19, 0x0D3D3E1A, 0x1E6DCDEE, 0xEC064EED, + 0xC38D26C4, 0x31E6A5C7, 0x22B65633, 0xD0DDD530, + 0x0417B1DB, 0xF67C32D8, 0xE52CC12C, 0x1747422F, + 0x49547E0B, 0xBB3FFD08, 0xA86F0EFC, 0x5A048DFF, + 0x8ECEE914, 0x7CA56A17, 0x6FF599E3, 0x9D9E1AE0, + 0xD3D3E1AB, 0x21B862A8, 0x32E8915C, 0xC083125F, + 0x144976B4, 0xE622F5B7, 0xF5720643, 0x07198540, + 0x590AB964, 0xAB613A67, 0xB831C993, 0x4A5A4A90, + 0x9E902E7B, 0x6CFBAD78, 0x7FAB5E8C, 0x8DC0DD8F, + 0xE330A81A, 0x115B2B19, 0x020BD8ED, 0xF0605BEE, + 0x24AA3F05, 0xD6C1BC06, 0xC5914FF2, 0x37FACCF1, + 0x69E9F0D5, 0x9B8273D6, 0x88D28022, 0x7AB90321, + 0xAE7367CA, 0x5C18E4C9, 0x4F48173D, 0xBD23943E, + 0xF36E6F75, 0x0105EC76, 0x12551F82, 0xE03E9C81, + 0x34F4F86A, 0xC69F7B69, 0xD5CF889D, 0x27A40B9E, + 0x79B737BA, 0x8BDCB4B9, 0x988C474D, 0x6AE7C44E, + 0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351, + }; + + private static final int LONG_MASK = 0xFFFFFFFF; + private static final int BYTE_MASK = 0xFF; + + private int crc = ~0; + + @Override + public void update(int b) { + crc = crc32c(crc, b); + } + + @Override + public void update(byte[] buffer, int offset, int length) { + for (int i = offset; i < offset + length; i++) { + crc = crc32c(crc, buffer[i]); + } + } + + @Override + public long getValue() { + return (crc ^ LONG_MASK) & LONG_MASK; + } + + @Override + public void reset() { + crc = ~0; + } + + private static int crc32c(int crc, int b) { + return (crc >>> 8) ^ CRC_TABLE[(crc ^ (b & BYTE_MASK)) & BYTE_MASK]; + } +} diff --git a/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java b/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java index 3219f0b3ce5..c521c7bd3e5 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java @@ -18,8 +18,6 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; -import java.util.zip.CRC32; - /** * Uncompresses an input {@link ByteBuf} encoded with Snappy compression into an * output {@link ByteBuf}. @@ -597,30 +595,30 @@ private static void validateOffset(int offset, int chunkSizeSoFar) { } /** - * Computes the CRC32 checksum of the supplied data and performs the "mask" operation + * Computes the CRC32C checksum of the supplied data and performs the "mask" operation * on the computed checksum * - * @param data The input data to calculate the CRC32 checksum of + * @param data The input data to calculate the CRC32C checksum of */ public static int calculateChecksum(ByteBuf data) { return calculateChecksum(data, data.readerIndex(), data.readableBytes()); } /** - * Computes the CRC32 checksum of the supplied data and performs the "mask" operation + * Computes the CRC32C checksum of the supplied data and performs the "mask" operation * on the computed checksum * - * @param data The input data to calculate the CRC32 checksum of + * @param data The input data to calculate the CRC32C checksum of */ public static int calculateChecksum(ByteBuf data, int offset, int length) { - CRC32 crc32 = new CRC32(); + Crc32c crc32 = new Crc32c(); try { if (data.hasArray()) { crc32.update(data.array(), data.arrayOffset() + offset, length); } else { byte[] array = new byte[length]; data.getBytes(offset, array); - crc32.update(array); + crc32.update(array, 0, length); } return maskChecksum((int) crc32.getValue()); @@ -630,12 +628,12 @@ public static int calculateChecksum(ByteBuf data, int offset, int length) { } /** - * Computes the CRC32 checksum of the supplied data, performs the "mask" operation + * Computes the CRC32C checksum of the supplied data, performs the "mask" operation * on the computed checksum, and then compares the resulting masked checksum to the * supplied checksum. * * @param expectedChecksum The checksum decoded from the stream to compare against - * @param data The input data to calculate the CRC32 checksum of + * @param data The input data to calculate the CRC32C checksum of * @throws DecompressionException If the calculated and supplied checksums do not match */ static void validateChecksum(int expectedChecksum, ByteBuf data) { @@ -643,12 +641,12 @@ static void validateChecksum(int expectedChecksum, ByteBuf data) { } /** - * Computes the CRC32 checksum of the supplied data, performs the "mask" operation + * Computes the CRC32C checksum of the supplied data, performs the "mask" operation * on the computed checksum, and then compares the resulting masked checksum to the * supplied checksum. * * @param expectedChecksum The checksum decoded from the stream to compare against - * @param data The input data to calculate the CRC32 checksum of + * @param data The input data to calculate the CRC32C checksum of * @throws DecompressionException If the calculated and supplied checksums do not match */ static void validateChecksum(int expectedChecksum, ByteBuf data, int offset, int length) {
diff --git a/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedDecoderTest.java b/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedDecoderTest.java index 2b255443090..625ac1f1e05 100644 --- a/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedDecoderTest.java +++ b/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedDecoderTest.java @@ -147,10 +147,10 @@ public void testInvalidChecksumThrowsException() throws Exception { public void testInvalidChecksumDoesNotThrowException() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(new SnappyFramedDecoder(true)); - // checksum here is presented as -1568496083 (little endian) + // checksum here is presented as a282986f (little endian) ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x80, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, - 0x01, 0x09, 0x00, 0x00, 0x2d, -0x5a, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y' + 0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y' }); channel.writeInbound(in); diff --git a/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedEncoderTest.java b/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedEncoderTest.java index 52edb9a67ba..3cc65ef5431 100644 --- a/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedEncoderTest.java +++ b/codec/src/test/java/io/netty/handler/codec/compression/SnappyFramedEncoderTest.java @@ -43,8 +43,9 @@ public void testSmallAmountOfDataIsUncompressed() throws Exception { ByteBuf expected = Unpooled.wrappedBuffer(new byte[] { -0x80, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, - 0x01, 0x09, 0x00, 0x00, 0x2d, -0x5a, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y' + 0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y' }); + assertEquals(expected, channel.readOutbound()); } @@ -60,11 +61,12 @@ public void testLargeAmountOfDataIsCompressed() throws Exception { ByteBuf expected = Unpooled.wrappedBuffer(new byte[] { -0x80, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, - 0x00, 0x0E, 0x00, 0x00, 0x7b, 0x1f, 0x65, 0x64, + 0x00, 0x0E, 0x00, 0x00, 0x3b, 0x36, -0x7f, 0x37, 0x14, 0x10, 'n', 'e', 't', 't', 'y', 0x3a, 0x05, 0x00 }); + assertEquals(expected, channel.readOutbound()); } @@ -81,8 +83,8 @@ public void testStreamStartIsOnlyWrittenOnce() throws Exception { ByteBuf expected = Unpooled.wrappedBuffer(new byte[] { -0x80, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, - 0x01, 0x09, 0x00, 0x00, 0x2d, -0x5a, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y', - 0x01, 0x09, 0x00, 0x00, 0x2d, -0x5a, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y', + 0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y', + 0x01, 0x09, 0x00, 0x00, 0x6f, -0x68, -0x7e, -0x5e, 'n', 'e', 't', 't', 'y', }); CompositeByteBuf actual = Unpooled.compositeBuffer(); diff --git a/codec/src/test/java/io/netty/handler/codec/compression/SnappyTest.java b/codec/src/test/java/io/netty/handler/codec/compression/SnappyTest.java index c7122d1913d..0ac3d6574c9 100644 --- a/codec/src/test/java/io/netty/handler/codec/compression/SnappyTest.java +++ b/codec/src/test/java/io/netty/handler/codec/compression/SnappyTest.java @@ -175,7 +175,7 @@ public void testCalculateChecksum() { ByteBuf input = Unpooled.wrappedBuffer(new byte[] { 'n', 'e', 't', 't', 'y' }); - assertEquals(maskChecksum(0xddaa8ce6), calculateChecksum(input)); + assertEquals(maskChecksum(0xd6cb8b55), calculateChecksum(input)); } @Test @@ -184,7 +184,7 @@ public void testValidateChecksumMatches() { 'y', 't', 't', 'e', 'n' }); - validateChecksum(maskChecksum(0x37c55159), input); + validateChecksum(maskChecksum(0x2d4d3535), input); } @Test(expected = DecompressionException.class) @@ -193,6 +193,6 @@ public void testValidateChecksumFails() { 'y', 't', 't', 'e', 'n' }); - validateChecksum(maskChecksum(0xddaa8ce6), input); + validateChecksum(maskChecksum(0xd6cb8b55), input); } }
train
train
2013-10-31T06:26:41
"2013-10-28T15:46:34Z"
nxmbriggs404
val
netty/netty/1810_1983
netty/netty
netty/netty/1810
netty/netty/1983
[ "timestamp(timedelta=18.0, similarity=0.9503122391605027)" ]
6ba1a85c4b4a317136eac237a1490de4d6c73ac7
a2a0fb52f974d3e2a925ecee88ebebcad1d21232
[ "@trustin good idea... will you work on this ?\n", "Just a proposal : why not using uuid (real one) such that unicity is provable ?\n", "Note: not uuid from jvm but another implementation...\n", "Yeah, we can do that, too. 3.x had to work with Java 5 which did not have access to the hardware address of the network interface, but the minimum requirement of 4.x is Java 6, so we can definitely do that.\n", "I think we can even use the UUID from JDK as long as we feed all the fields by ourselves.\n", "@trustin you will take care?\n", "the id can be everything,Long or String ,I think there is no need to insist it as an Integer\n", "From my own research, what I've found on various implementation as probably the best is the following combination in UUID:\n- partial MAC address (to ensure difference between 2 hosts), set statically at the beginning of the JVM\n- a JVM PID (to ensure difference between 2 JVM on the same host), set statically at the beginning of the JVM\n- partial timestamp in ms (since nano is not always implemented and so last bytes are just 0, and since most of the front bytes are 0)\n- and finally a counter to prevent 2 same values on the same ms (as AtomicLong) (this is the tricker part I've found that ensures that 2 immediate consecutive or simultaneous demands of UUID are still different)\n\nMy 2 cents...\n", "like hepin1989 said, id should be anything,\n\nto me:\n- channel.id() should return an java.lang.Object (or maybe a <T> T to avoid cast ?)\n- it should be allowed for user to provide a certain implementation for a \"ChannelIdGenerator\" interface with a given \"public Object generateId(Channel channel)\" method to implements\n- the default proposed netty channel id strategy should implement this interface\n\nAs for the implementation detail of the id, I think fredericBregier have a good point.\nMaybe also looking on how jgroups and/or infinispan generate their unique cluster id could be helpful ?\n", "@trustin @normanmaurer \n\nUUID maybe human unreadable .....\n", "I think there is no need for make it human readable\n\nAm 21.09.2013 um 18:06 schrieb yaphet [email protected]:\n\n> @trustin @normanmaurer\n> \n> UUID maybe human unreadable .....\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "mostly,we using the channel as a key for the map<channelId,channel>,why should it be human readable?\n" ]
[ "Could you commit this as a separate thing as it's not related ?\n", "I find this naming a bit confusing as from the naming I would expect to have a short returned. Same goes for the user where I would expect long\n", "why transient ?\n", "Serialization.\n", "Ah missed that it extends Serializable... makes sense.\n", "Renamed to `asShort/LongText()`\n", "Done.\n" ]
"2013-11-15T13:52:28Z"
[ "feature" ]
Resurrect Channel.id()
If we don't insist the type of `Channel.id()` to be an integer, I think we might be able to make it unique for sure. For example, it could be `hashCode` + `identityHashCode` + `nanoTime` + `sequence`. Practically, this should never collide.
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "transport/src/main/java/io/netty/channel/AbstractChannel.java", "transport/src/main/java/io/netty/channel/Channel.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "transport/src/main/java/io/netty/channel/AbstractChannel.java", "transport/src/main/java/io/netty/channel/Channel.java", "transport/src/main/java/io/netty/channel/ChannelId.java", "transport/src/main/java/io/netty/channel/DefaultChannelId.java" ]
[]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index 8860cbae740..f501ed13ca1 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -75,6 +75,38 @@ public static String hexDump(ByteBuf buffer, int fromIndex, int length) { return new String(buf); } + /** + * Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> + * of the specified byte array. + */ + public static String hexDump(byte[] array) { + return hexDump(array, 0, array.length); + } + + /** + * Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> + * of the specified byte array's sub-region. + */ + public static String hexDump(byte[] array, int fromIndex, int length) { + if (length < 0) { + throw new IllegalArgumentException("length: " + length); + } + if (length == 0) { + return ""; + } + + int endIndex = fromIndex + length; + char[] buf = new char[length << 1]; + + int srcIdx = fromIndex; + int dstIdx = 0; + for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { + System.arraycopy(HEXDUMP_TABLE, (array[srcIdx] & 0xFF) << 1, buf, dstIdx, 2); + } + + return new String(buf); + } + /** * Calculates the hash code of the specified buffer. This method is * useful when implementing a new buffer type. diff --git a/transport/src/main/java/io/netty/channel/AbstractChannel.java b/transport/src/main/java/io/netty/channel/AbstractChannel.java index c04f67aa7ba..f8c6de8a2dc 100644 --- a/transport/src/main/java/io/netty/channel/AbstractChannel.java +++ b/transport/src/main/java/io/netty/channel/AbstractChannel.java @@ -20,7 +20,6 @@ import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; -import io.netty.util.internal.ThreadLocalRandom; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -49,7 +48,7 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha private MessageSizeEstimator.Handle estimatorHandle; private final Channel parent; - private final long hashCode = ThreadLocalRandom.current().nextLong(); + private final ChannelId id = DefaultChannelId.newInstance(); private final Unsafe unsafe; private final DefaultChannelPipeline pipeline; private final ChannelFuture succeededFuture = new SucceededChannelFuture(this, null); @@ -79,6 +78,11 @@ protected AbstractChannel(Channel parent, EventLoop eventLoop) { pipeline = new DefaultChannelPipeline(this); } + @Override + public final ChannelId id() { + return id; + } + @Override public boolean isWritable() { ChannelOutboundBuffer buf = unsafe.outboundBuffer(); @@ -271,7 +275,7 @@ public Unsafe unsafe() { */ @Override public final int hashCode() { - return (int) hashCode; + return id.hashCode(); } /** @@ -289,21 +293,7 @@ public final int compareTo(Channel o) { return 0; } - long ret = hashCode - o.hashCode(); - if (ret > 0) { - return 1; - } - if (ret < 0) { - return -1; - } - - ret = System.identityHashCode(this) - System.identityHashCode(o); - if (ret != 0) { - return (int) ret; - } - - // Jackpot! - different objects with same hashes - throw new Error(); + return id().compareTo(o.id()); } /** @@ -331,11 +321,30 @@ public String toString() { srcAddr = remoteAddr; dstAddr = localAddr; } - strVal = String.format("[id: 0x%08x, %s %s %s]", (int) hashCode, srcAddr, active? "=>" : ":>", dstAddr); + + StringBuilder buf = new StringBuilder(96); + buf.append("[id: 0x"); + buf.append(id.asShortText()); + buf.append(", "); + buf.append(srcAddr); + buf.append(active? " => " : " :> "); + buf.append(dstAddr); + buf.append(']'); + strVal = buf.toString(); } else if (localAddr != null) { - strVal = String.format("[id: 0x%08x, %s]", (int) hashCode, localAddr); + StringBuilder buf = new StringBuilder(64); + buf.append("[id: 0x"); + buf.append(id.asShortText()); + buf.append(", "); + buf.append(localAddr); + buf.append(']'); + strVal = buf.toString(); } else { - strVal = String.format("[id: 0x%08x]", (int) hashCode); + StringBuilder buf = new StringBuilder(16); + buf.append("[id: 0x"); + buf.append(id.asShortText()); + buf.append(']'); + strVal = buf.toString(); } strValActive = active; diff --git a/transport/src/main/java/io/netty/channel/Channel.java b/transport/src/main/java/io/netty/channel/Channel.java index 28e364f7e81..6a6adaa06a7 100644 --- a/transport/src/main/java/io/netty/channel/Channel.java +++ b/transport/src/main/java/io/netty/channel/Channel.java @@ -68,6 +68,11 @@ */ public interface Channel extends AttributeMap, ChannelOutboundInvoker, ChannelPropertyAccess, Comparable<Channel> { + /** + * Returns the globally unique identifier of this {@link Channel}. + */ + ChannelId id(); + /** * Return the {@link EventLoop} this {@link Channel} was registered too. */ diff --git a/transport/src/main/java/io/netty/channel/ChannelId.java b/transport/src/main/java/io/netty/channel/ChannelId.java new file mode 100644 index 00000000000..b62fff88812 --- /dev/null +++ b/transport/src/main/java/io/netty/channel/ChannelId.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package io.netty.channel; + +import java.io.Serializable; + +/** + * Represents the globally unique identifier of a {@link Channel}. + * <p> + * The identifier is generated from various sources listed in the following: + * <ul> + * <li>MAC address (EUI-48 or EUI-64) or the network adapter, preferrably a globally unique one,</li> + * <li>the current process ID,</li> + * <li>{@link System#currentTimeMillis()},</li> + * <li>{@link System#nanoTime()},</li> + * <li>a random 32-bit integer, and</li> + * <li>a sequentially incremented 32-bit integer.</li> + * </ul> + * </p> + * <p> + * The global uniqueness of the generated identifier mostly depends on the MAC address and the current process ID, + * which are auto-detected at the class-loading time in best-effort manner. If all attempts to acquire them fail, + * a warning message is logged, and random values will be used instead. Alternatively, you can specify them manually + * via system properties: + * <ul> + * <li>{@code io.netty.machineId} - hexadecimal representation of 48 (or 64) bit integer, + * optionally separated by colon or hyphen.</li> + * <li>{@code io.netty.processId} - an integer between 0 and 65535</li> + * </ul> + * </p> + */ +public interface ChannelId extends Serializable, Comparable<ChannelId> { + /** + * Returns the short but globally non-unique string representation of the {@link ChannelId}. + */ + String asShortText(); + + /** + * Returns the long yet globally unique string representation of the {@link ChannelId}. + */ + String asLongText(); +} diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelId.java b/transport/src/main/java/io/netty/channel/DefaultChannelId.java new file mode 100644 index 00000000000..2f3ae26a002 --- /dev/null +++ b/transport/src/main/java/io/netty/channel/DefaultChannelId.java @@ -0,0 +1,375 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package io.netty.channel; + +import io.netty.buffer.ByteBufUtil; +import io.netty.util.internal.SystemPropertyUtil; +import io.netty.util.internal.ThreadLocalRandom; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; + +import java.lang.management.ManagementFactory; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; + +/** + * The default {@link ChannelId} implementation. + */ +final class DefaultChannelId implements ChannelId { + + private static final long serialVersionUID = 3884076183504074063L; + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class); + + private static final Pattern MACHINE_ID_PATTERN = Pattern.compile("^(?:[0-9a-fA-F][:-]?){6,8}$"); + private static final int MACHINE_ID_LEN = 8; + private static final byte[] MACHINE_ID; + private static final int PROCESS_ID_LEN = 2; + private static final int MAX_PROCESS_ID = 65535; + private static final int PROCESS_ID; + private static final int SEQUENCE_LEN = 4; + private static final int TIMESTAMP_LEN = 8; + private static final int RANDOM_LEN = 4; + + private static final AtomicInteger nextSequence = new AtomicInteger(); + + static ChannelId newInstance() { + DefaultChannelId id = new DefaultChannelId(); + id.init(); + return id; + } + + static { + byte[] machineId = null; + String customMachineId = SystemPropertyUtil.get("io.netty.machineId"); + if (customMachineId != null) { + if (MACHINE_ID_PATTERN.matcher(customMachineId).matches()) { + machineId = parseMachineId(customMachineId); + logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId); + } else { + logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId); + } + } + + if (machineId == null) { + machineId = defaultMachineId(); + if (logger.isDebugEnabled()) { + logger.debug("-Dio.netty.machineId: {} (auto-detected)", formatAddress(machineId)); + } + } + + MACHINE_ID = machineId; + + int processId = -1; + String customProcessId = SystemPropertyUtil.get("io.netty.processId"); + if (customProcessId != null) { + try { + processId = Integer.parseInt(customProcessId); + } catch (NumberFormatException e) { + // Malformed input. + } + + if (processId < 0 || processId > MAX_PROCESS_ID) { + processId = -1; + logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId); + } else if (logger.isDebugEnabled()) { + logger.debug("-Dio.netty.processId: {} (user-set)", processId); + } + } + + if (processId < 0) { + processId = defaultProcessId(); + if (logger.isDebugEnabled()) { + logger.debug("-Dio.netty.processId: {} (auto-detected)", processId); + } + } + + PROCESS_ID = processId; + } + + @SuppressWarnings("DynamicRegexReplaceableByCompiledPattern") + private static byte[] parseMachineId(String value) { + // Strip separators. + value = value.replaceAll("[:-]", ""); + + byte[] machineId = new byte[MACHINE_ID_LEN]; + for (int i = 0; i < value.length(); i += 2) { + machineId[i] = (byte) Integer.parseInt(value.substring(i, i + 2), 16); + } + + return machineId; + } + + private static byte[] defaultMachineId() { + // Find the best MAC address available. + final byte[] NOT_FOUND = { -1 }; + byte[] bestMacAddr = NOT_FOUND; + + Enumeration<NetworkInterface> ifaces = null; + try { + ifaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + logger.warn("Failed to find the loopback interface", e); + } + + if (ifaces != null) { + while (ifaces.hasMoreElements()) { + NetworkInterface iface = ifaces.nextElement(); + try { + if (iface.isLoopback() || iface.isPointToPoint() || iface.isVirtual()) { + continue; + } + } catch (SocketException e) { + logger.debug("Failed to determine the type of a network interface: {}", iface, e); + continue; + } + + byte[] macAddr; + try { + macAddr = iface.getHardwareAddress(); + } catch (SocketException e) { + logger.debug("Failed to get the hardware address of a network interface: {}", iface, e); + continue; + } + + if (isBetterAddress(bestMacAddr, macAddr)) { + bestMacAddr = macAddr; + } + } + } + + if (bestMacAddr == NOT_FOUND) { + bestMacAddr = new byte[MACHINE_ID_LEN]; + ThreadLocalRandom.current().nextBytes(bestMacAddr); + logger.warn( + "Failed to find a usable hardware address from the network interfaces; using random bytes: {}", + formatAddress(bestMacAddr)); + } + + if (bestMacAddr.length != MACHINE_ID_LEN) { + bestMacAddr = Arrays.copyOf(bestMacAddr, MACHINE_ID_LEN); + } + + return bestMacAddr; + } + + private static boolean isBetterAddress(byte[] current, byte[] candidate) { + if (candidate == null) { + return false; + } + + // Must be EUI-48 or longer. + if (candidate.length < 6) { + return false; + } + + // Must not be filled with only 0 or 1. + boolean onlyZero = true; + boolean onlyOne = true; + for (byte b: candidate) { + if (b != 0) { + onlyZero = false; + } + + if (b != -1) { + onlyOne = false; + } + } + + if (onlyZero || onlyOne) { + return false; + } + + // Must not be a multicast address + if ((candidate[0] & 1) != 0) { + return false; + } + + // Prefer longer globally unique addresses. + if ((current[0] & 2) == 0) { + if ((candidate[0] & 2) == 0) { + return candidate.length > current.length; + } else { + return false; + } + } else { + if ((candidate[0] & 2) == 0) { + return true; + } else { + return candidate.length > current.length; + } + } + } + + private static String formatAddress(byte[] addr) { + StringBuilder buf = new StringBuilder(24); + for (byte b: addr) { + buf.append(String.format("%02x:", b & 0xff)); + } + return buf.substring(0, buf.length() - 1); + } + + private static int defaultProcessId() { + String value = ManagementFactory.getRuntimeMXBean().getName(); + int atIndex = value.indexOf('@'); + if (atIndex >= 0) { + value = value.substring(0, atIndex); + } + + int pid; + try { + pid = Integer.parseInt(value); + } catch (NumberFormatException e) { + pid = -1; + } + + if (pid < 0 || pid > MAX_PROCESS_ID) { + pid = ThreadLocalRandom.current().nextInt(MAX_PROCESS_ID + 1); + logger.warn("Failed to find the current process ID; using a random value: {}", pid); + } + + return pid; + } + + private final byte[] data = new byte[MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN]; + private int hashCode; + + private transient String shortValue; + private transient String longValue; + + public DefaultChannelId() { } + + private void init() { + int i = 0; + + // machineId + System.arraycopy(MACHINE_ID, 0, data, i, MACHINE_ID_LEN); + i += MACHINE_ID_LEN; + + // processId + i = writeShort(i, PROCESS_ID); + + // sequence + i = writeInt(i, nextSequence.getAndIncrement()); + + // timestamp (kind of) + i = writeLong(i, Long.reverse(System.nanoTime()) ^ System.currentTimeMillis()); + + // random + int random = ThreadLocalRandom.current().nextInt(); + hashCode = random; + i = writeInt(i, random); + + assert i == data.length; + } + + private int writeShort(int i, int value) { + data[i ++] = (byte) (value >>> 8); + data[i ++] = (byte) value; + return i; + } + + private int writeInt(int i, int value) { + data[i ++] = (byte) (value >>> 24); + data[i ++] = (byte) (value >>> 16); + data[i ++] = (byte) (value >>> 8); + data[i ++] = (byte) value; + return i; + } + + private int writeLong(int i, long value) { + data[i ++] = (byte) (value >>> 56); + data[i ++] = (byte) (value >>> 48); + data[i ++] = (byte) (value >>> 40); + data[i ++] = (byte) (value >>> 32); + data[i ++] = (byte) (value >>> 24); + data[i ++] = (byte) (value >>> 16); + data[i ++] = (byte) (value >>> 8); + data[i ++] = (byte) value; + return i; + } + + @Override + public String asShortText() { + String shortValue = this.shortValue; + if (shortValue == null) { + this.shortValue = shortValue = ByteBufUtil.hexDump( + data, MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN, RANDOM_LEN); + } + return shortValue; + } + + @Override + public String asLongText() { + String longValue = this.longValue; + if (longValue == null) { + this.longValue = longValue = newLongValue(); + } + return longValue; + } + + private String newLongValue() { + StringBuilder buf = new StringBuilder(data.length + 4); + int i = 0; + i = appendHexDumpField(buf, i, MACHINE_ID_LEN); + i = appendHexDumpField(buf, i, PROCESS_ID_LEN); + i = appendHexDumpField(buf, i, SEQUENCE_LEN); + i = appendHexDumpField(buf, i, TIMESTAMP_LEN); + i = appendHexDumpField(buf, i, RANDOM_LEN); + assert i == data.length; + return buf.substring(0, buf.length() - 1); + } + + private int appendHexDumpField(StringBuilder buf, int i, int length) { + buf.append(ByteBufUtil.hexDump(data, i, length)); + buf.append('-'); + i += length; + return i; + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + public int compareTo(ChannelId o) { + return 0; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof DefaultChannelId)) { + return false; + } + + return Arrays.equals(data, ((DefaultChannelId) obj).data); + } + + @Override + public String toString() { + return asShortText(); + } +}
null
train
train
2013-11-15T15:08:25
"2013-09-04T00:17:30Z"
trustin
val
netty/netty/1988_1995
netty/netty
netty/netty/1988
netty/netty/1995
[ "timestamp(timedelta=20413.0, similarity=0.8800867546478833)" ]
d0e928db707460e00bb1269dc042401246c76324
cf13bf6ec1068702f949013b8531e486efc3f38e
[ "Checked against examples & submitted PR #1995 \n", "That one can be closed, #1995 is pulled :)\n", "@ifesdjeen true.. thanks!\n" ]
[]
"2013-11-20T09:13:46Z"
[]
The Javadoc example of IdleStateHandler is incorrect
The second param in userEventTriggered() should be converted to IdleStateEvent instead of IdleState. The following two lines should be changed: if (evt instanceof IdleState} { IdleState e = (IdleState) evt;
[ "handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java" ]
[ "handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java b/handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java index 19b8b9c8d90..c69aa7b38e5 100644 --- a/handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java +++ b/handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java @@ -74,8 +74,8 @@ * public class MyHandler extends {@link ChannelDuplexHandler} { * {@code @Override} * public void userEventTriggered({@link ChannelHandlerContext} ctx, {@link Object} evt) throws {@link Exception} { - * if (evt instanceof {@link IdleState}} { - * {@link IdleState} e = ({@link IdleState}) evt; + * if (evt instanceof {@link IdleStateEvent}} { + * {@link IdleStateEvent} e = ({@link IdleStateEvent}) evt; * if (e.state() == {@link IdleState}.READER_IDLE) { * ctx.close(); * } else if (e.state() == {@link IdleState}.WRITER_IDLE) {
null
val
train
2013-11-18T09:00:23
"2013-11-18T09:48:42Z"
iridium77
val
netty/netty/2014_2015
netty/netty
netty/netty/2014
netty/netty/2015
[ "timestamp(timedelta=23123.0, similarity=0.9999999999999998)" ]
4ea39aa9df93003f51a304adadc4adffa296d5be
eaee981c4571f08d8d8a86abd0b6e041e795db26
[ "Fixed via 8b495bb6e14becb5bda5e8b80257d5d186e18181\n" ]
[]
"2013-11-29T02:38:52Z"
[ "defect" ]
JDKZlibEncoder hangs (fails to flush) on large messages
If the message is great than 8k the message is not flushed.
[ "codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java index d0fa3f0b0c7..be806f65210 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java @@ -212,8 +212,11 @@ protected void encode(ChannelHandlerContext ctx, ByteBuf uncompressed, ByteBuf o deflater.setInput(inAry); while (!deflater.needsInput()) { - int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length, Deflater.SYNC_FLUSH); - out.writeBytes(encodeBuf, 0, numBytes); + int numBytes = encodeBuf.length; + while (numBytes == encodeBuf.length) { + numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length, Deflater.SYNC_FLUSH); + out.writeBytes(encodeBuf, 0, numBytes); + } } }
null
test
train
2013-11-28T13:50:08
"2013-11-29T02:19:06Z"
craigday
val
netty/netty/2025_2031
netty/netty
netty/netty/2025
netty/netty/2031
[ "timestamp(timedelta=18.0, similarity=0.85295617730554)" ]
053c512f6de708f1bb3f402cf6d911f88b1d38aa
82112699a79b18fe8bee0e6f0b90002c9eeecc13
[ "@BabyDuncan would you mind do the changes and submit a pullreq ?\n", "ok , i will do that .\n", "hi @normanmaurer ,netty 4.x is build under jdk 1.7 , but the applications base on netty 4.x can be build under jdk 1.6 , why ? \n", "If your application runs on Java 7, Netty will make use of the new classes in Java 7. Otherwise, it will only use the classes in Java 6 for maximum compatibility.\n", "@trustin wow,it is cool !\n" ]
[ "Should it be?\n\n attribute = new DiskAttribute(name, value, charset);\n", "yes it should be . i will fix that .\n", "Not sure it is better, but we could call the very same constructor inside. Something like:\n\n```\npublic DefaultHttpDataFactory(long minSize, Charset charset) {\n this(minSize);\n this.charset = charset;\n}\n```\n\nBut really not mandatory\n", "Agree @BabyDuncan please do the changes @fredericBregier suggested\n", "yes , \n\n```\npublic DefaultHttpDataFactory(long minSize, Charset charset) {\n this(minSize);\n this.charset = charset;\n}\n```\n\nis better .\n" ]
"2013-12-03T02:38:22Z"
[ "feature" ]
Wish MixedAttribute support user defined charset
MemoryAttribute 's constructor has no i can defined charset . > public MemoryAttribute(String name) { > super(name, HttpConstants.DEFAULT_CHARSET, 0); > } when i send a utf-8 request ,the gbk encoded server can never decode it correctly !!! i hope there is a MemoryAttribute constructor > public MemoryAttribute(String name, Charset charset ) so when i want yo use HttpPostRequestDecoder > new HttpPostRequestDecoder(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), httpRequest, user_define_charset); i can use this : > new HttpPostRequestDecoder(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE,user_define_charset), httpRequest, user_define_charset); then > Attribute attribute = new MixedAttribute(name, minSize,user_define_charset); then i got what i want .
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java", "codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java index 8f6f68e18b5..24873fa4279 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DefaultHttpDataFactory.java @@ -15,6 +15,7 @@ */ package io.netty.handler.codec.http.multipart; +import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.HttpRequest; import io.netty.util.internal.PlatformDependent; @@ -44,6 +45,8 @@ public class DefaultHttpDataFactory implements HttpDataFactory { private long minSize; + private Charset charset = HttpConstants.DEFAULT_CHARSET; + /** * Keep all HttpDatas until cleanAllHttpDatas() is called. */ @@ -78,6 +81,11 @@ public DefaultHttpDataFactory(long minSize) { this.minSize = minSize; } + public DefaultHttpDataFactory(long minSize, Charset charset) { + this(minSize); + this.charset = charset; + } + /** * @return the associated list of Files for the request */ @@ -93,13 +101,13 @@ private List<HttpData> getList(HttpRequest request) { @Override public Attribute createAttribute(HttpRequest request, String name) { if (useDisk) { - Attribute attribute = new DiskAttribute(name); + Attribute attribute = new DiskAttribute(name, charset); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } if (checkSize) { - Attribute attribute = new MixedAttribute(name, minSize); + Attribute attribute = new MixedAttribute(name, minSize, charset); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; @@ -112,23 +120,23 @@ public Attribute createAttribute(HttpRequest request, String name, String value) if (useDisk) { Attribute attribute; try { - attribute = new DiskAttribute(name, value); + attribute = new DiskAttribute(name, value, charset); } catch (IOException e) { // revert to Mixed mode - attribute = new MixedAttribute(name, value, minSize); + attribute = new MixedAttribute(name, value, minSize, charset); } List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } if (checkSize) { - Attribute attribute = new MixedAttribute(name, value, minSize); + Attribute attribute = new MixedAttribute(name, value, minSize, charset); List<HttpData> fileToDelete = getList(request); fileToDelete.add(attribute); return attribute; } try { - return new MemoryAttribute(name, value); + return new MemoryAttribute(name, value, charset); } catch (IOException e) { throw new IllegalArgumentException(e); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java index 28ac87044bd..d1bbd9c43b6 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/DiskAttribute.java @@ -20,8 +20,9 @@ import io.netty.handler.codec.http.HttpConstants; import java.io.IOException; +import java.nio.charset.Charset; -import static io.netty.buffer.Unpooled.*; +import static io.netty.buffer.Unpooled.wrappedBuffer; /** * Disk implementation of Attributes @@ -42,11 +43,20 @@ public DiskAttribute(String name) { super(name, HttpConstants.DEFAULT_CHARSET, 0); } + public DiskAttribute(String name, Charset charset) { + super(name, charset, 0); + } + public DiskAttribute(String name, String value) throws IOException { super(name, HttpConstants.DEFAULT_CHARSET, 0); // Attribute have no default size setValue(value); } + public DiskAttribute(String name, String value, Charset charset) throws IOException { + super(name, charset, 0); // Attribute have no default size + setValue(value); + } + @Override public HttpDataType getHttpDataType() { return HttpDataType.Attribute; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java index e174ac91f40..9cbb9068d25 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MemoryAttribute.java @@ -20,8 +20,9 @@ import io.netty.handler.codec.http.HttpConstants; import java.io.IOException; +import java.nio.charset.Charset; -import static io.netty.buffer.Unpooled.*; +import static io.netty.buffer.Unpooled.wrappedBuffer; /** * Memory implementation of Attributes @@ -32,11 +33,20 @@ public MemoryAttribute(String name) { super(name, HttpConstants.DEFAULT_CHARSET, 0); } + public MemoryAttribute(String name, Charset charset) { + super(name, charset, 0); + } + public MemoryAttribute(String name, String value) throws IOException { super(name, HttpConstants.DEFAULT_CHARSET, 0); // Attribute have no default size setValue(value); } + public MemoryAttribute(String name, String value, Charset charset) throws IOException { + super(name, charset, 0); // Attribute have no default size + setValue(value); + } + @Override public HttpDataType getHttpDataType() { return HttpDataType.Attribute; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java index e47e5486939..6bcf74c0156 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/MixedAttribute.java @@ -35,6 +35,11 @@ public MixedAttribute(String name, long limitSize) { attribute = new MemoryAttribute(name); } + public MixedAttribute(String name, long limitSize, Charset charset) { + this.limitSize = limitSize; + attribute = new MemoryAttribute(name, charset); + } + public MixedAttribute(String name, String value, long limitSize) { this.limitSize = limitSize; if (value.length() > this.limitSize) { @@ -57,6 +62,28 @@ public MixedAttribute(String name, String value, long limitSize) { } } + public MixedAttribute(String name, String value, long limitSize, Charset charset) { + this.limitSize = limitSize; + if (value.length() > this.limitSize) { + try { + attribute = new DiskAttribute(name, value, charset); + } catch (IOException e) { + // revert to Memory mode + try { + attribute = new MemoryAttribute(name, value, charset); + } catch (IOException e1) { + throw new IllegalArgumentException(e); + } + } + } else { + try { + attribute = new MemoryAttribute(name, value, charset); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + } + @Override public void addContent(ByteBuf buffer, boolean last) throws IOException { if (attribute instanceof MemoryAttribute) {
null
test
train
2013-12-02T08:23:57
"2013-12-02T10:31:12Z"
BabyDuncan
val
netty/netty/2040_2118
netty/netty
netty/netty/2040
netty/netty/2118
[ "timestamp(timedelta=85079.0, similarity=0.8540695487194159)" ]
a88584976d89ef6c93cbd48a422ef12bc06f5cbb
346c9cd96170067f4d417c49efc2ba5fbbf53e0b
[ "Google only supports SPDY over https with NPN. Which protocol version did you negotiate?\n", "I have try both spdy3 & spdy3.1 with NPN extension. It works few days ago, but failed in recent days.\n", "@jpinner anything we can do here ?\n", "What did you send in your settings frame? Google's servers send a GO_AWAY if they receive any setting they do not recognize.\n", "I didn't send setting frame manually, do you need me to capture the setting frame?\n", "@jpinner could you chime in ?\n", "If you could post a frame level / wire level dump of the session that would be helpful.\n", "Please reopen with the information requested.\n" ]
[ "Why not use Unpooled.copiedBuffer(...) ?\n", "I think you can use SelectedProtocol.protocolForName(...) ?\n", "`@Override` annotations ?\n", "You should add it to the parent pom version with version number ...\n", "Not from the current code.\n\n```\npublic enum SelectedProtocol {\n SPDY_3,\n SPDY_3_1,\n HTTP_1_1,\n HTTP_1_0,\n UNKNOWN\n}\n```\n", "Hmm what is the problem with using SelectedProtocol.protocol(String) \n", "From what I can see, `SelectedProtocol` is just a simple enum \n\n```\npublic enum SelectedProtocol {\n SPDY_3,\n SPDY_3_1,\n HTTP_1_1,\n HTTP_1_0,\n UNKNOWN\n}\n```\n\nAre you suggesting we change the enum?\n", "@veebs maybe you are not on latest 4.0 branch ?\n\nhttps://github.com/netty/netty/blob/4.0/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyOrHttpChooser.java#L66\n", "OK - makes sense now. I forked and worked on the SPDY example before Jan 11th when that change was pulled in. \n\nThanks @normanmaurer. I'll merge and make the change.\n" ]
"2014-01-15T11:30:54Z"
[ "needs info" ]
SPDY receive "PROTOCOL_ERROR" error
Recently connecting to http://www.google.com with spdy is broken. After two setting frame, I got a GoAwayFrame with "PROTOCOL_ERROR" status. It works just few days ago. Maybe google just update his protocol?? Version: both 3.8.3 and 4.0.13
[ "example/pom.xml", "pom.xml" ]
[ "example/pom.xml", "example/src/main/java/io/netty/example/spdy/SpdyOrHttpHandler.java", "example/src/main/java/io/netty/example/spdy/SpdyServer.java", "example/src/main/java/io/netty/example/spdy/SpdyServerHandler.java", "example/src/main/java/io/netty/example/spdy/SpdyServerInitializer.java", "example/src/main/java/io/netty/example/spdy/SpdyServerProvider.java", "example/src/main/java/io/netty/example/spdy/package-info.java", "pom.xml" ]
[]
diff --git a/example/pom.xml b/example/pom.xml index eed48abf9bf..0dcff3cd82a 100644 --- a/example/pom.xml +++ b/example/pom.xml @@ -68,6 +68,10 @@ <artifactId>javassist</artifactId> <scope>runtime</scope> </dependency> + <dependency> + <groupId>org.eclipse.jetty.npn</groupId> + <artifactId>npn-api</artifactId> + </dependency> <!-- see https://github.com/netty/netty/issues/874 --> <dependency> diff --git a/example/src/main/java/io/netty/example/spdy/SpdyOrHttpHandler.java b/example/src/main/java/io/netty/example/spdy/SpdyOrHttpHandler.java new file mode 100644 index 00000000000..dc394747515 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/SpdyOrHttpHandler.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.spdy; + +import javax.net.ssl.SSLEngine; + +import org.eclipse.jetty.npn.NextProtoNego; + +import io.netty.channel.ChannelHandler; +import io.netty.handler.codec.spdy.SpdyOrHttpChooser; + +/** + * Negotiates with the browser if SPDY or HTTP is going to be used. Once decided, the Netty pipeline is setup with + * the correct handlers for the selected protocol. + */ +public class SpdyOrHttpHandler extends SpdyOrHttpChooser { + private static final int MAX_CONTENT_LENGTH = 1024 * 100; + + public SpdyOrHttpHandler() { + this(MAX_CONTENT_LENGTH, MAX_CONTENT_LENGTH); + } + + public SpdyOrHttpHandler(int maxSpdyContentLength, int maxHttpContentLength) { + super(maxSpdyContentLength, maxHttpContentLength); + } + + @Override + protected SelectedProtocol getProtocol(SSLEngine engine) { + SpdyServerProvider provider = (SpdyServerProvider) NextProtoNego.get(engine); + String selectedProtocol = provider.getSelectedProtocol(); + + System.out.println("Selected Protocol is " + (selectedProtocol == null ? "Unknown" : selectedProtocol)); + + if (selectedProtocol == null) { + return SpdyOrHttpChooser.SelectedProtocol.UNKNOWN; + } else if (selectedProtocol.equalsIgnoreCase("spdy/3.1")) { + return SpdyOrHttpChooser.SelectedProtocol.SPDY_3_1; + } else if (selectedProtocol.equalsIgnoreCase("spdy/3")) { + return SpdyOrHttpChooser.SelectedProtocol.SPDY_3; + } else if (selectedProtocol.equalsIgnoreCase("http/1.1")) { + return SpdyOrHttpChooser.SelectedProtocol.HTTP_1_1; + } else if (selectedProtocol.equalsIgnoreCase("http/1.0")) { + return SpdyOrHttpChooser.SelectedProtocol.HTTP_1_0; + } else { + return SpdyOrHttpChooser.SelectedProtocol.UNKNOWN; + } + } + + @Override + protected ChannelHandler createHttpRequestHandlerForHttp() { + return new SpdyServerHandler(); + } + +} diff --git a/example/src/main/java/io/netty/example/spdy/SpdyServer.java b/example/src/main/java/io/netty/example/spdy/SpdyServer.java new file mode 100644 index 00000000000..0de13d04818 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/SpdyServer.java @@ -0,0 +1,77 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.spdy; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; + +/** + * A SPDY Server that responds to a GET request with a Hello World. + * <p> + * This class must be run with the JVM parameter: {@code java -Xbootclasspath/p:<path_to_npn_boot_jar> ...}. + * The "path_to_npn_boot_jar" is the path on the file system for the NPN Boot Jar file which can be downloaded from + * Maven at coordinates org.mortbay.jetty.npn:npn-boot. Different versions applies to different OpenJDK versions. + * See {@link http://www.eclipse.org/jetty/documentation/current/npn-chapter.html Jetty docs} for more information. + * <p> + * Once started, you can test the server with your + * {@link http://en.wikipedia.org/wiki/SPDY#Browser_support_and_usage SPDY enabled web browser} by navigating + * to https://localhost:8443/. + */ +public class SpdyServer { + + private final int port; + + public SpdyServer(int port) { + this.port = port; + } + + public void run() throws Exception { + // Configure the server. + EventLoopGroup bossGroup = new NioEventLoopGroup(); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 1024); + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) + .childHandler(new SpdyServerInitializer()); + + Channel ch = b.bind(port).sync().channel(); + ch.closeFuture().sync(); + } finally { + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8443; + } + + System.out.println("SPDY web server started at port " + port + '.'); + System.out.println("Open your SPDY enabled browser and navigate to https://localhost:" + port + '/'); + System.out.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy"); + + new SpdyServer(port).run(); + } +} diff --git a/example/src/main/java/io/netty/example/spdy/SpdyServerHandler.java b/example/src/main/java/io/netty/example/spdy/SpdyServerHandler.java new file mode 100644 index 00000000000..889796fb317 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/SpdyServerHandler.java @@ -0,0 +1,74 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.spdy; + +import java.util.Date; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.util.CharsetUtil; + +import static io.netty.handler.codec.http.HttpHeaders.Names.*; +import static io.netty.handler.codec.http.HttpHeaders.*; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.*; + +/** + * HTTP handler that responds with a "Hello World" + */ +public class SpdyServerHandler extends ChannelHandlerAdapter { + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof HttpRequest) { + HttpRequest req = (HttpRequest) msg; + + if (is100ContinueExpected(req)) { + ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); + } + boolean keepAlive = isKeepAlive(req); + + ByteBuf content = Unpooled.copiedBuffer("Hello World " + (new Date()).toString(), CharsetUtil.UTF_8); + + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); + response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); + response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); + + if (!keepAlive) { + ctx.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + response.headers().set(CONNECTION, Values.KEEP_ALIVE); + ctx.write(response); + } + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/example/src/main/java/io/netty/example/spdy/SpdyServerInitializer.java b/example/src/main/java/io/netty/example/spdy/SpdyServerInitializer.java new file mode 100644 index 00000000000..f9412055a62 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/SpdyServerInitializer.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.spdy; + +import javax.net.ssl.SSLEngine; + +import org.eclipse.jetty.npn.NextProtoNego; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.example.securechat.SecureChatSslContextFactory; +import io.netty.handler.ssl.SslHandler; + +/** + * Sets up the Netty pipeline + */ +public class SpdyServerInitializer extends ChannelInitializer<SocketChannel> { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline p = ch.pipeline(); + + SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); + engine.setUseClientMode(false); + p.addLast("ssl", new SslHandler(engine)); + + // Setup NextProtoNego with our server provider + NextProtoNego.put(engine, new SpdyServerProvider()); + NextProtoNego.debug = true; + + // Negotiates with the browser if SPDY or HTTP is going to be used + p.addLast("handler", new SpdyOrHttpHandler()); + } +} diff --git a/example/src/main/java/io/netty/example/spdy/SpdyServerProvider.java b/example/src/main/java/io/netty/example/spdy/SpdyServerProvider.java new file mode 100644 index 00000000000..250d7eedcc5 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/SpdyServerProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.spdy; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.jetty.npn.NextProtoNego.ServerProvider; + +/** + * The Jetty project provides an implementation of the Transport Layer Security (TLS) extension for Next + * Protocol Negotiation (NPN) for OpenJDK 7 or greater. NPN allows the application layer to negotiate which + * protocol to use over the secure connection. + * <p> + * This NPN service provider negotiates using SPDY. + * <p> + * To enable NPN support, start the JVM with: {@code java -Xbootclasspath/p:<path_to_npn_boot_jar> ...}. The + * "path_to_npn_boot_jar" is the path on the file system for the NPN Boot Jar file which can be downloaded from + * Maven at coordinates org.mortbay.jetty.npn:npn-boot. Different versions applies to different OpenJDK versions. + * + * @see http://www.eclipse.org/jetty/documentation/current/npn-chapter.html + */ +public class SpdyServerProvider implements ServerProvider { + + private String selectedProtocol; + + @Override + public void unsupported() { + // if unsupported, default to http/1.1 + selectedProtocol = "http/1.1"; + } + + @Override + public List<String> protocols() { + return Arrays.asList("spdy/3.1", "spdy/3", "http/1.1"); + } + + @Override + public void protocolSelected(String protocol) { + selectedProtocol = protocol; + } + + public String getSelectedProtocol() { + return selectedProtocol; + } +} diff --git a/example/src/main/java/io/netty/example/spdy/package-info.java b/example/src/main/java/io/netty/example/spdy/package-info.java new file mode 100644 index 00000000000..5155ee2e859 --- /dev/null +++ b/example/src/main/java/io/netty/example/spdy/package-info.java @@ -0,0 +1,33 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +/** + * This package contains an example SPDY HTTP web server. + * <p> + * This package relies on the Jetty project's implementation of the Transport Layer Security (TLS) extension for Next + * Protocol Negotiation (NPN) for OpenJDK 7 is required. NPN allows the application layer to negotiate which + * protocol, SPDY or HTTP, to use. + * <p> + * To start, run {@link SpdyServer} with the JVM parameter: {@code java -Xbootclasspath/p:<path_to_npn_boot_jar> ...}. + * The "path_to_npn_boot_jar" is the path on the file system for the NPN Boot Jar file which can be downloaded from + * Maven at coordinates org.mortbay.jetty.npn:npn-boot. Different versions applies to different OpenJDK versions. + * See {@link http://www.eclipse.org/jetty/documentation/current/npn-chapter.html Jetty docs} for more information. + * <p> + * Once started, you can test the server with your + * {@link http://en.wikipedia.org/wiki/SPDY#Browser_support_and_usage SPDY enabled web browser} by navigating + * to https://localhost:8443/. + */ +package io.netty.example.spdy; diff --git a/pom.xml b/pom.xml index 7803018efec..e64fc4d14ee 100644 --- a/pom.xml +++ b/pom.xml @@ -143,6 +143,13 @@ <optional>true</optional> </dependency> + <!-- SPDY Example - completely optional --> + <dependency> + <groupId>org.eclipse.jetty.npn</groupId> + <artifactId>npn-api</artifactId> + <version>1.1.0.v20120525</version> + </dependency> + <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId>
null
test
train
2014-01-15T08:00:18
"2013-12-05T14:14:56Z"
carck
val
netty/netty/2170_2171
netty/netty
netty/netty/2170
netty/netty/2171
[ "timestamp(timedelta=121.0, similarity=0.8772450393794907)" ]
f7f808c7e0e354e3d468e31e609d8c538fac67e1
e1213677a2d4d2ef2c54efb9c20c98cabcb5161b
[ "Suggested fix:\n\ninstead of ignoring\n\n> catch (InterruptedException ignore) {\n> // Ignore\n> }\n\nrestore interrupt status\n\n> catch (InterruptedException ignore) {\n> Thread.currentThread().interrupt();\n> }\n\nPull request with the suggested fix: https://github.com/netty/netty/pull/2171\n", "Was fixed in 4.0 and master.. Thanks!\n" ]
[]
"2014-01-31T11:23:43Z"
[ "defect" ]
[netty-5.0.0.Alpha1] ThreadLocalRandom.current() clears thread's interrupt status
API method _io.netty.util.internal.ThreadLocalRandom.current()_ clears thread's interrupt status because _ThreadLocalRandom.getInitialSeedUniquifier()_ swallows _InterruptedException_ without restoring interrupt status (see https://github.com/netty/netty/blob/netty-5.0.0.Alpha1/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java#L114). Note that such behavior isn't specified neither in class _ThreadLocalRandom_ specification nor in method _ThreadLocalRandom.getInitialSeedUniquifier()_ specification. This bug was introduced in netty-4.0.8.Final. This bug also causes unexpected behavior of other netty API methods which invoke _ThreadLocalRandom.getInitialSeedUniquifier()_ (e.g. because of _ThreadLocalRandom.current()_ method invocation). One of such affected methods is _io.netty.bootstrap.AbstractBootstrap.bind(SocketAddress)_: > Thread.currentThread().interrupt(); > assert Thread.currentThread().isInterrupted() == true; // OK > ChannelFuture serverSocketChannelBindFuture = serverBootstrap.bind(address); > assert Thread.currentThread().isInterrupted() == true; // FAIL > serverSocketChannelBindFuture.await(); > assert serverSocketChannelBindFuture.isSuccess() == true; // OK if we comment out FAIL assert above
[ "common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java" ]
[ "common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java" ]
[ "common/src/test/java/io/netty/util/internal/ThreadLocalRandomTest.java" ]
diff --git a/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java b/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java index 22ff7e47e18..3049e48274c 100644 --- a/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java +++ b/common/src/main/java/io/netty/util/internal/ThreadLocalRandom.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 The Netty Project + * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance @@ -110,8 +110,9 @@ public void run() { initialSeedUniquifier = result; break; } - } catch (InterruptedException ignore) { - // Ignore + } catch (InterruptedException e) { + // restore interrupt status because we don't know how to/don't need to handle it here + Thread.currentThread().interrupt(); } }
diff --git a/common/src/test/java/io/netty/util/internal/ThreadLocalRandomTest.java b/common/src/test/java/io/netty/util/internal/ThreadLocalRandomTest.java new file mode 100644 index 00000000000..8f584d7f52d --- /dev/null +++ b/common/src/test/java/io/netty/util/internal/ThreadLocalRandomTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.util.internal; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ThreadLocalRandomTest { + + @Test + public void getInitialSeedUniquifierPreservesInterrupt() { + try { + Thread.currentThread().interrupt(); + assertTrue("Assert that thread is interrupted before invocation of getInitialSeedUniquifier()", + Thread.currentThread().isInterrupted()); + ThreadLocalRandom.getInitialSeedUniquifier(); + assertTrue("Assert that thread is interrupted after invocation of getInitialSeedUniquifier()", + Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); // clear interrupted status in order to not affect other tests + } + } +}
train
train
2014-01-30T07:00:53
"2014-01-30T21:07:28Z"
stIncMale
val
netty/netty/2177_2178
netty/netty
netty/netty/2177
netty/netty/2178
[ "timestamp(timedelta=19.0, similarity=0.8764695546904817)" ]
ce053205021a55686d5484fe4f219db0261564f2
f7c7cf8ad3f6e1fd0f6afe3efeb7634940cd1043
[ "PR welcome :)\n\n> Am 02.02.2014 um 20:29 schrieb Vladimír Schäfer [email protected]:\n> \n> SOCKS5 protocol defines that response to CONNECT command can contain host and port the proxy server connects to the target from. Current implementation fills these fields with zeroes and doesn't support customization.\n> \n> The support for bound fields should be added to io.netty.handler.codec.socks.SocksCmdResponse class.\n> \n> —\n> Reply to this email directly or view it on GitHub.\n", "On the way, back in few minutes :)\n", "Provided you'd decide to accept the pull - do you think I could send another one for the 4.0.x branch? It's essentially an improvement, not a bug fix, but perhaps it's not against your policies of merging to fix releases?\n", "@vschafer don't worry I will cherry pick your change to 4.0 once it was merged ;)\n", "@vschafer thanks for your work.\nbtw where did this feature is used ?\n", "You should add checks in SocksCmdResponse constructor for provided boundHost and boundPort just like it is done in SocksCmdRequest\n", "@normanmaurer Thank you Norman :)\n\n@bk1te No problem, I'll add the checks later today. My worry was that this could break backwards compatibility - someone was sending invalid data for e.g. IPv4 earlier (100.100.1), but as it was essentially ignored (except for a length check) it didn't fail the decoding process. Now someone updates to 4.0.x and boom there's a regression as the constructor will reject the data. Not very likely, but possible. So what if we'd add the constructor check for 5.0, but skip it in 4.x?\n\nI'm prototyping a custom proxy for a cloud application and using Netty (SOCKS5+WebSocket) as part of it. When testing with Putty (configured to use SOCKS5) I ran into an issue when Putty interpreted the zeroed host+port incorrectly and added an extra 0x00 into the actual data stream.\n", "@vschafer yeah I think adding the check only in master is ok :)\n", "@vschafer @normanmaurer I think this checks would not break comptability, because you just add new constructor with additional data and didn`t remove the old one without bounded address. For IPv4 and IPv6 address types your point with invalid address is not an issue, cause you convert bytes to address. Your example is for domain address type and for it it is not an issue, in socks rfc there is nothing written about domain address type validation, so you would return SocksCmdResponse with address type DOMAIN and requested address and port.\nSo I vote for checks everywhere! \n", "@bk1te @vschafer true... so checks everywhere ;)\n", "@bk1te @normanmaurer Yes, the old constructor stays, but the SocksCmdResponseDecoder has changed - it now calls the new constructor and that's the place where (imho) you could now get an IllegalArgumentException when receiving a SocksResponse (while e.g. writing an application which acts as a SOCKS5 client). This could happen in case you receive an invalid IPv4 or IPv6 address in the incoming stream (e.g. correct amount of bytes resulting in string \"127.000000.000\" with subsequent fail in NetUtil.isValidIpV4Address). I agree that there's no issue with the domain address types.\n\nThis is really marginal and I'm just trying to convey any possible risks related to the patch :) The implementation of checks will follow later today.\n", "Why do you think that if you pass 4 bytes you would receive incorrect IPv4 address and same for IPv6 address\n", "My bad, I lived in a world where the whole string, dots included, gets sent over the wire. Just disregard it, aka so checks everywhere.\n" ]
[ "maybe move this after the switch so we not convert an invalid address ?\n", "could be static\n" ]
"2014-02-02T19:57:53Z"
[]
SOCKS5 Response command does not support bound host and port
SOCKS5 protocol defines that response to CONNECT command can contain host and port the proxy server connects to the target from. Current implementation fills these fields with zeroes and doesn't support customization. The support for bound fields should be added to io.netty.handler.codec.socks.SocksCmdResponse class.
[ "codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java", "codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java" ]
[ "codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java", "codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java" ]
[ "codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseDecoderTest.java", "codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseTest.java" ]
diff --git a/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java b/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java index 03218b69213..567ceb63fff 100644 --- a/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java +++ b/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponse.java @@ -16,9 +16,13 @@ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; +import io.netty.util.CharsetUtil; +import io.netty.util.NetUtil; + +import java.net.IDN; /** - * An socks cmd response. + * A socks cmd response. * * @see SocksCmdRequest * @see SocksCmdResponseDecoder @@ -27,7 +31,11 @@ public final class SocksCmdResponse extends SocksResponse { private final SocksCmdStatus cmdStatus; private final SocksAddressType addressType; + private final String host; + private final int port; + // All arrays are initialized on construction time to 0/false/null remove array Initialization + private static final byte[] DOMAIN_ZEROED = {0x00}; private static final byte[] IPv4_HOSTNAME_ZEROED = {0x00, 0x00, 0x00, 0x00}; private static final byte[] IPv6_HOSTNAME_ZEROED = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -35,6 +43,23 @@ public final class SocksCmdResponse extends SocksResponse { 0x00, 0x00, 0x00, 0x00}; public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType) { + this(cmdStatus, addressType, null, 0); + } + + /** + * Constructs new response and includes provided host and port as part of it. + * + * @param cmdStatus status of the response + * @param addressType type of host parameter + * @param host host (BND.ADDR field) is address that server used when connecting to the target host. + * When null a value of 4/8 0x00 octets will be used for IPv4/IPv6 and a single 0x00 byte will be + * used for domain addressType. Value is converted to ASCII using {@link IDN#toASCII(String)}. + * @param port port (BND.PORT field) that the server assigned to connect to the target host + * @throws NullPointerException in case cmdStatus or addressType are missing + * @throws IllegalArgumentException in case host or port cannot be validated + * @see IDN#toASCII(String) + */ + public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) { super(SocksResponseType.CMD); if (cmdStatus == null) { throw new NullPointerException("cmdStatus"); @@ -42,8 +67,36 @@ public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType) if (addressType == null) { throw new NullPointerException("addressType"); } + if (host != null) { + switch (addressType) { + case IPv4: + if (!NetUtil.isValidIpV4Address(host)) { + throw new IllegalArgumentException(host + " is not a valid IPv4 address"); + } + break; + case DOMAIN: + if (IDN.toASCII(host).length() > 255) { + throw new IllegalArgumentException(host + " IDN: " + + IDN.toASCII(host) + " exceeds 255 char limit"); + } + break; + case IPv6: + if (!NetUtil.isValidIpV6Address(host)) { + throw new IllegalArgumentException(host + " is not a valid IPv6 address"); + } + break; + case UNKNOWN: + break; + } + host = IDN.toASCII(host); + } + if (port < 0 && port >= 65535) { + throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536"); + } this.cmdStatus = cmdStatus; this.addressType = addressType; + this.host = host; + this.port = port; } /** @@ -64,6 +117,32 @@ public SocksAddressType addressType() { return addressType; } + /** + * Returns host that is used as a parameter in {@link io.netty.handler.codec.socks.SocksCmdType}. + * Host (BND.ADDR field in response) is address that server used when connecting to the target host. + * This is typically different from address which client uses to connect to the SOCKS server. + * + * @return host that is used as a parameter in {@link io.netty.handler.codec.socks.SocksCmdType} + * or null when there was no host specified during response construction + */ + public String host() { + if (host != null) { + return IDN.toUnicode(host); + } else { + return null; + } + } + + /** + * Returns port that is used as a parameter in {@link io.netty.handler.codec.socks.SocksCmdType}. + * Port (BND.PORT field in response) is port that the server assigned to connect to the target host. + * + * @return port that is used as a parameter in {@link io.netty.handler.codec.socks.SocksCmdType} + */ + public int port() { + return port; + } + @Override public void encodeAsByteBuf(ByteBuf byteBuf) { byteBuf.writeByte(protocolVersion().byteValue()); @@ -72,19 +151,25 @@ public void encodeAsByteBuf(ByteBuf byteBuf) { byteBuf.writeByte(addressType.byteValue()); switch (addressType) { case IPv4: { - byteBuf.writeBytes(IPv4_HOSTNAME_ZEROED); - byteBuf.writeShort(0); + byte[] hostContent = host == null ? + IPv4_HOSTNAME_ZEROED : NetUtil.createByteArrayFromIpAddressString(host); + byteBuf.writeBytes(hostContent); + byteBuf.writeShort(port); break; } case DOMAIN: { - byteBuf.writeByte(1); // domain length - byteBuf.writeByte(0); // domain value - byteBuf.writeShort(0); // port value + byte[] hostContent = host == null ? + DOMAIN_ZEROED : host.getBytes(CharsetUtil.US_ASCII); + byteBuf.writeByte(hostContent.length); // domain length + byteBuf.writeBytes(hostContent); // domain value + byteBuf.writeShort(port); // port value break; } case IPv6: { - byteBuf.writeBytes(IPv6_HOSTNAME_ZEROED); - byteBuf.writeShort(0); + byte[] hostContent = host == null + ? IPv6_HOSTNAME_ZEROED : NetUtil.createByteArrayFromIpAddressString(host); + byteBuf.writeBytes(hostContent); + byteBuf.writeShort(port); break; } } diff --git a/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java b/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java index e313128be49..d93674b752d 100644 --- a/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java +++ b/codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java @@ -67,20 +67,20 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> o case IPv4: { host = SocksCommonUtils.intToIp(byteBuf.readInt()); port = byteBuf.readUnsignedShort(); - msg = new SocksCmdResponse(cmdStatus, addressType); + msg = new SocksCmdResponse(cmdStatus, addressType, host, port); break; } case DOMAIN: { fieldLength = byteBuf.readByte(); host = byteBuf.readBytes(fieldLength).toString(CharsetUtil.US_ASCII); port = byteBuf.readUnsignedShort(); - msg = new SocksCmdResponse(cmdStatus, addressType); + msg = new SocksCmdResponse(cmdStatus, addressType, host, port); break; } case IPv6: { host = SocksCommonUtils.ipv6toStr(byteBuf.readBytes(16).array()); port = byteBuf.readUnsignedShort(); - msg = new SocksCmdResponse(cmdStatus, addressType); + msg = new SocksCmdResponse(cmdStatus, addressType, host, port); break; } case UNKNOWN:
diff --git a/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseDecoderTest.java b/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseDecoderTest.java index 62af41aa7cf..1a98a8f765e 100644 --- a/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseDecoderTest.java +++ b/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseDecoderTest.java @@ -26,27 +26,58 @@ public class SocksCmdResponseDecoderTest { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdResponseDecoderTest.class); private static void testSocksCmdResponseDecoderWithDifferentParams( - SocksCmdStatus cmdStatus, SocksAddressType addressType) { + SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) { logger.debug("Testing cmdStatus: " + cmdStatus + " addressType: " + addressType); - SocksResponse msg = new SocksCmdResponse(cmdStatus, addressType); + SocksResponse msg = new SocksCmdResponse(cmdStatus, addressType, host, port); SocksCmdResponseDecoder decoder = new SocksCmdResponseDecoder(); EmbeddedChannel embedder = new EmbeddedChannel(decoder); SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg); if (addressType == SocksAddressType.UNKNOWN) { assertTrue(embedder.readInbound() instanceof UnknownSocksResponse); } else { - msg = embedder.readInbound(); + msg = (SocksResponse) embedder.readInbound(); assertEquals(((SocksCmdResponse) msg).cmdStatus(), cmdStatus); + if (host != null) { + assertEquals(((SocksCmdResponse) msg).host(), host); + } + assertEquals(((SocksCmdResponse) msg).port(), port); } assertNull(embedder.readInbound()); } + /** + * Verifies that sent socks messages are decoded correctly. + */ @Test public void testSocksCmdResponseDecoder() { - for (SocksCmdStatus cmdStatus: SocksCmdStatus.values()) { - for (SocksAddressType addressType: SocksAddressType.values()) { - testSocksCmdResponseDecoderWithDifferentParams(cmdStatus, addressType); + for (SocksCmdStatus cmdStatus : SocksCmdStatus.values()) { + for (SocksAddressType addressType : SocksAddressType.values()) { + testSocksCmdResponseDecoderWithDifferentParams(cmdStatus, addressType, null, 0); } } } + + /** + * Verifies that invalid bound host will fail with IllegalArgumentException during encoding. + */ + @Test(expected = IllegalArgumentException.class) + public void testInvalidAddress() { + testSocksCmdResponseDecoderWithDifferentParams(SocksCmdStatus.SUCCESS, SocksAddressType.IPv4, "1", 80); + } + + /** + * Verifies that send socks messages are decoded correctly when bound host and port are set. + */ + @Test + public void testSocksCmdResponseDecoderIncludingHost() { + for (SocksCmdStatus cmdStatus : SocksCmdStatus.values()) { + testSocksCmdResponseDecoderWithDifferentParams(cmdStatus, SocksAddressType.IPv4, + "127.0.0.1", 80); + testSocksCmdResponseDecoderWithDifferentParams(cmdStatus, SocksAddressType.DOMAIN, + "testDomain.com", 80); + testSocksCmdResponseDecoderWithDifferentParams(cmdStatus, SocksAddressType.IPv6, + "2001:db8:85a3:42:1000:8a2e:370:7334", 80); + } + } + } diff --git a/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseTest.java b/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseTest.java index 319db95f14e..f8d69f138f4 100644 --- a/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseTest.java +++ b/codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdResponseTest.java @@ -15,6 +15,8 @@ */ package io.netty.handler.codec.socks; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import org.junit.Test; import static org.junit.Assert.*; @@ -33,4 +35,92 @@ public void testConstructorParamsAreNotNull() { assertTrue(e instanceof NullPointerException); } } + + /** + * Verifies content of the response when domain is not specified. + */ + @Test + public void testEmptyDomain() { + SocksCmdResponse socksCmdResponse = new SocksCmdResponse(SocksCmdStatus.SUCCESS, SocksAddressType.DOMAIN); + assertNull(socksCmdResponse.host()); + assertEquals(0, socksCmdResponse.port()); + ByteBuf buffer = Unpooled.buffer(20); + socksCmdResponse.encodeAsByteBuf(buffer); + byte[] expected = { + 0x05, // version + 0x00, // success reply + 0x00, // reserved + 0x03, // address type domain + 0x01, // length of domain + 0x00, // domain value + 0x00, // port value + 0x00 + }; + assertByteBufEquals(expected, buffer); + } + + /** + * Verifies content of the response when IPv4 address is specified. + */ + @Test + public void testIPv4Host() { + SocksCmdResponse socksCmdResponse = new SocksCmdResponse(SocksCmdStatus.SUCCESS, SocksAddressType.IPv4, + "127.0.0.1", 80); + assertEquals("127.0.0.1", socksCmdResponse.host()); + assertEquals(80, socksCmdResponse.port()); + ByteBuf buffer = Unpooled.buffer(20); + socksCmdResponse.encodeAsByteBuf(buffer); + byte[] expected = { + 0x05, // version + 0x00, // success reply + 0x00, // reserved + 0x01, // address type IPv4 + 0x7F, // address 127.0.0.1 + 0x00, + 0x00, + 0x01, + 0x00, // port + 0x50 + }; + assertByteBufEquals(expected, buffer); + } + + /** + * Verifies that empty domain is allowed Response. + */ + @Test + public void testEmptyBoundAddress() { + SocksCmdResponse socksCmdResponse = new SocksCmdResponse(SocksCmdStatus.SUCCESS, SocksAddressType.DOMAIN, + "", 80); + assertEquals("", socksCmdResponse.host()); + assertEquals(80, socksCmdResponse.port()); + ByteBuf buffer = Unpooled.buffer(20); + socksCmdResponse.encodeAsByteBuf(buffer); + byte[] expected = { + 0x05, // version + 0x00, // success reply + 0x00, // reserved + 0x03, // address type domain + 0x00, // domain length + 0x00, // port + 0x50 + }; + assertByteBufEquals(expected, buffer); + } + + /** + * Verifies that Response cannot be constructed with invalid IP. + */ + @Test(expected = IllegalArgumentException.class) + public void testInvalidBoundAddress() { + new SocksCmdResponse(SocksCmdStatus.SUCCESS, SocksAddressType.IPv4, "127.0.0", 1000); + } + + private static void assertByteBufEquals(byte[] expected, ByteBuf actual) { + byte[] actualBytes = new byte[actual.readableBytes()]; + actual.readBytes(actualBytes); + assertEquals("Generated response has incorrect length", expected.length, actualBytes.length); + assertArrayEquals("Generated response differs from expected", expected, actualBytes); + } + }
val
train
2014-02-01T18:35:09
"2014-02-02T19:29:50Z"
vschafer
val
netty/netty/2183_2184
netty/netty
netty/netty/2183
netty/netty/2184
[ "timestamp(timedelta=46.0, similarity=0.853477353555016)" ]
ff771c0fcbae09eab1d511995f32dfab0cf32ee2
7b55ad099981951e4194965d9dbd66099a53a32e
[ "@vschafer good catch! Thanks for the tests and fix!\n" ]
[]
"2014-02-06T18:44:04Z"
[]
ByteToMessageDecoder doesn't release cumulation buffer
ByteToMessageDecoder doesn't correctly release internal "cumulation" ByteBuf in case decoder is removed from pipeline during decode operation and all bytes of the buffer were already read (i.e. buf.isReadable() == false). Buffer is typically released in method handlerRemoved, but only in case it still has content to be read. In case buffer was fully read, it causes leaks detectable by ResourceLeakDetector (LEAK: ByteBuf.release() was not called before it's garbage-collected). Detection can be speeded up with setting -Dio.netty.leakDetectionLevel=PARANOID. The pull request which follows contains two test cases which demonstrate the problem. Test ByteToMessageDecoderTest#testInternalBufferClearReadPart correctly clears the buffer, while ByteToMessageDecoderTest#testInternalBufferClearReadAll fails. The issue is fixed by a change in handlerRemoved method of ByteToMessageDecoder. Issue was reproduced in the latest 4.0.16-snapshot
[ "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java" ]
[ "codec/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java" ]
diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java index 50dc125886a..637f4cd9d02 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java @@ -109,6 +109,8 @@ public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { ByteBuf bytes = buf.readBytes(readable); buf.release(); ctx.fireChannelRead(bytes); + } else { + buf.release(); } cumulation = null; ctx.fireChannelReadComplete();
diff --git a/codec/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java b/codec/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java index 09d5020073a..082ac8a2fca 100644 --- a/codec/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java +++ b/codec/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java @@ -72,4 +72,50 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t buf.release(); b.release(); } + + /** + * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In + * this case input is read fully. + */ + @Test + public void testInternalBufferClearReadAll() { + + final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[]{'a'}); + EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() { + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { + ByteBuf byteBuf = internalBuffer(); + Assert.assertEquals(1, byteBuf.refCnt()); + in.readByte(); + // Removal from pipeline should clear internal buffer + ctx.pipeline().remove(this); + Assert.assertEquals(0, byteBuf.refCnt()); + } + }); + channel.writeInbound(buf.copy()); + + } + + /** + * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In + * this case input was not fully read. + */ + @Test + public void testInternalBufferClearReadPartly() { + + final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[]{'a', 'b'}); + EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() { + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { + ByteBuf byteBuf = internalBuffer(); + Assert.assertEquals(1, byteBuf.refCnt()); + in.readByte(); + // Removal from pipeline should clear internal buffer + ctx.pipeline().remove(this); + Assert.assertEquals(0, byteBuf.refCnt()); + } + }); + channel.writeInbound(buf.copy()); + + } }
test
train
2014-02-06T10:48:56
"2014-02-06T18:38:56Z"
vschafer
val
netty/netty/1831_2266
netty/netty
netty/netty/1831
netty/netty/2266
[ "timestamp(timedelta=2633.0, similarity=0.9032205947505163)" ]
3e11c0c39e10be1410f6267a2857ffeb1dab76a3
96074dcc29758a25c629e6e5cbb0a3836516e605
[ "Was fixed by #2266\n" ]
[ "Why this license header ?\n", "why copied at all and not reused ?\n", "maybe some javadocs how to use it ?\n", "Should be final\n" ]
"2014-02-27T02:19:18Z"
[ "feature", "help wanted" ]
Feature request: Websocket SSL client example
It would be nice if a working SSL websocket client example could be added to the examples.
[ "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java", "example/src/main/java/io/netty/example/http/websocketx/client/package-info.java" ]
[ "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientRunner.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClient.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientContextFactory.java", "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientTrustManagerFactory.java" ]
[]
diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java index 5e6095167f3..6224c45ad17 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 The Netty Project + * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance @@ -13,123 +13,35 @@ * License for the specific language governing permissions and limitations * under the License. */ -//The MIT License -// -//Copyright (c) 2009 Carl Bystršm -// -//Permission is hereby granted, free of charge, to any person obtaining a copy -//of this software and associated documentation files (the "Software"), to deal -//in the Software without restriction, including without limitation the rights -//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -//copies of the Software, and to permit persons to whom the Software is -//furnished to do so, subject to the following conditions: -// -//The above copyright notice and this permission notice shall be included in -//all copies or substantial portions of the Software. -// -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -//THE SOFTWARE. package io.netty.example.http.websocketx.client; -import io.netty.bootstrap.Bootstrap; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.http.DefaultHttpHeaders; -import io.netty.handler.codec.http.HttpClientCodec; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; -import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; -import io.netty.handler.codec.http.websocketx.WebSocketVersion; - import java.net.URI; -public class WebSocketClient { - - private final URI uri; - - public WebSocketClient(URI uri) { - this.uri = uri; - } - - public void run() throws Exception { - EventLoopGroup group = new NioEventLoopGroup(); - try { - Bootstrap b = new Bootstrap(); - String protocol = uri.getScheme(); - if (!"ws".equals(protocol)) { - throw new IllegalArgumentException("Unsupported protocol: " + protocol); - } - - HttpHeaders customHeaders = new DefaultHttpHeaders(); - customHeaders.add("MyHeader", "MyValue"); - - // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. - // If you change it to V00, ping is not supported and remember to change - // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. - final WebSocketClientHandler handler = - new WebSocketClientHandler( - WebSocketClientHandshakerFactory.newHandshaker( - uri, WebSocketVersion.V13, null, false, customHeaders)); - - b.group(group) - .channel(NioSocketChannel.class) - .handler(new ChannelInitializer<SocketChannel>() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast("http-codec", new HttpClientCodec()); - pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); - pipeline.addLast("ws-handler", handler); - } - }); - - System.out.println("WebSocket Client connecting"); - Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel(); - handler.handshakeFuture().sync(); - - // Send 10 messages and wait for responses - System.out.println("WebSocket Client sending message"); - for (int i = 0; i < 10; i++) { - ch.writeAndFlush(new TextWebSocketFrame("Message #" + i)); - } - - // Ping - System.out.println("WebSocket Client sending ping"); - ch.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6}))); - - // Close - System.out.println("WebSocket Client sending close"); - ch.writeAndFlush(new CloseWebSocketFrame()); - - // WebSocketClientHandler will close the connection when the server - // responds to the CloseWebSocketFrame. - ch.closeFuture().sync(); - } finally { - group.shutdownGracefully(); - } +/** + * This is an example of a WebSocket client. + * <p> + * In order to run this example you need a compatible WebSocket server. + * Therefore you can either start the WebSocket server from the examples + * by running {@link io.netty.example.http.websocketx.server.WebSocketServer} + * or connect to an existing WebSocket server such as + * <a href="http://www.websocket.org/echo.html">ws://echo.websocket.org</a>. + * <p> + * The client will attempt to connect to the URI passed to it as the first argument. + * You don't have to specify any arguments if you want to connect to the example WebSocket server, + * as this is the default. + */ +public final class WebSocketClient { + private WebSocketClient() { } - public static void main(String[] args) throws Exception { + public static void main(String... args) throws Exception { URI uri; if (args.length > 0) { uri = new URI(args[0]); } else { uri = new URI("ws://localhost:8080/websocket"); } - new WebSocketClient(uri).run(); + + new WebSocketClientRunner(uri).run(); } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientRunner.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientRunner.java new file mode 100644 index 00000000000..211a71dcdd3 --- /dev/null +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientRunner.java @@ -0,0 +1,134 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.http.websocketx.client; + +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.DefaultHttpHeaders; +import io.netty.handler.codec.http.HttpClientCodec; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; +import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketVersion; +import io.netty.handler.ssl.SslHandler; + +import javax.net.ssl.SSLEngine; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URI; + +public final class WebSocketClientRunner { + + private URI uri; + + public WebSocketClientRunner(URI uri) { + this.uri = uri; + } + + public void run() throws Exception { + EventLoopGroup group = new NioEventLoopGroup(); + try { + // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. + // If you change it to V00, ping is not supported and remember to change + // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. + final WebSocketClientHandler handler = + new WebSocketClientHandler( + WebSocketClientHandshakerFactory.newHandshaker( + uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); + + final String protocol = uri.getScheme(); + int defaultPort; + ChannelInitializer<SocketChannel> initializer; + + // Normal WebSocket + if ("ws".equals(protocol)) { + initializer = new ChannelInitializer<SocketChannel>() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ch.pipeline() + .addLast("http-codec", new HttpClientCodec()) + .addLast("aggregator", new HttpObjectAggregator(8192)) + .addLast("ws-handler", handler); + } + }; + + defaultPort = 80; + // Secure WebSocket + } else if ("wss".equals(protocol)) { + initializer = new ChannelInitializer<SocketChannel>() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine(); + engine.setUseClientMode(true); + + ch.pipeline() + .addFirst("ssl", new SslHandler(engine)) + .addLast("http-codec", new HttpClientCodec()) + .addLast("aggregator", new HttpObjectAggregator(8192)) + .addLast("ws-handler", handler); + } + }; + + defaultPort = 443; + } else { + throw new IllegalArgumentException("Unsupported protocol: " + protocol); + } + + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioSocketChannel.class) + .handler(initializer); + + int port = uri.getPort(); + // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7 + if (uri.getPort() == -1) { + port = defaultPort; + } + + Channel ch = b.connect(uri.getHost(), port).sync().channel(); + handler.handshakeFuture().sync(); + + BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + String msg = console.readLine(); + if (msg == null) { + break; + } else if ("bye".equals(msg.toLowerCase())) { + ch.writeAndFlush(new CloseWebSocketFrame()); + ch.closeFuture().sync(); + break; + } else if ("ping".equals(msg.toLowerCase())) { + WebSocketFrame frame = new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[]{8, 1, 8, 1})); + ch.writeAndFlush(frame); + } else { + WebSocketFrame frame = new TextWebSocketFrame(msg); + ch.writeAndFlush(frame); + } + } + } finally { + group.shutdownGracefully(); + } + } +} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClient.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClient.java new file mode 100644 index 00000000000..7cc1ff6d0be --- /dev/null +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClient.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.http.websocketx.client; + +import java.net.URI; + +/** + * This is an example of a secure WebSocket client. + * <p> + * In order to run this example you need a compatible secure WebSocket server. + * Therefore you can either start the secure WebSocket server from the examples + * by running {@link io.netty.example.http.websocketx.sslserver.WebSocketSslServer} + * or connect to an existing secure WebSocket server such as + * <a href="http://www.websocket.org/echo.html">wss://echo.websocket.org</a>. + * <p> + * The client will attempt to connect to the URI passed to it as the first argument. + * You don't have to specify any arguments if you want to connect to the example secure WebSocket server, + * as this is the default. + */ +public final class WebSocketSslClient { + private WebSocketSslClient() { + } + + public static void main(String... args) throws Exception { + URI uri; + if (args.length > 0) { + uri = new URI(args[0]); + } else { + uri = new URI("wss://localhost:8443/websocket"); + } + + new WebSocketClientRunner(uri).run(); + } +} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientContextFactory.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientContextFactory.java new file mode 100644 index 00000000000..faa17f704ae --- /dev/null +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientContextFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.http.websocketx.client; + +import javax.net.ssl.SSLContext; + +/** + * Creates a bogus {@link javax.net.ssl.SSLContext}. A client-side context created by this + * factory accepts any certificate even if it is invalid. + * <p> + * You will have to create your context differently in a real world application. + * <p> + * Modified from {@link io.netty.example.securechat.SecureChatSslContextFactory} + */ +public final class WebSocketSslClientContextFactory { + + private static final String PROTOCOL = "TLS"; + private static final SSLContext CONTEXT; + + static { + SSLContext clientContext; + try { + clientContext = SSLContext.getInstance(PROTOCOL); + clientContext.init(null, WebSocketSslClientTrustManagerFactory.getTrustManagers(), null); + } catch (Exception e) { + throw new Error( + "Failed to initialize the client-side SSLContext", e); + } + + CONTEXT = clientContext; + } + + public static SSLContext getContext() { + return CONTEXT; + } + + private WebSocketSslClientContextFactory() { + // Unused + } +} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientTrustManagerFactory.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientTrustManagerFactory.java new file mode 100644 index 00000000000..2c5f71d0701 --- /dev/null +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketSslClientTrustManagerFactory.java @@ -0,0 +1,79 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.example.http.websocketx.client; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509TrustManager; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.X509Certificate; + +/** + * Bogus {@link javax.net.ssl.TrustManagerFactorySpi} which accepts any certificate + * even if it is invalid. + * <p> + * Copied from {@link io.netty.example.securechat.SecureChatTrustManagerFactory} + */ +public class WebSocketSslClientTrustManagerFactory extends TrustManagerFactorySpi { + + private static final TrustManager DUMMY_TRUST_MANAGER = new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + // Always trust - it is an example. + // You should do something in the real world. + // You will reach here only if you enabled client certificate auth, + // as described in WebSocketSslClientContextFactory. + System.err.println( + "UNKNOWN CLIENT CERTIFICATE: " + chain[0].getSubjectDN()); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + // Always trust - it is an example. + // You should do something in the real world. + System.err.println( + "UNKNOWN SERVER CERTIFICATE: " + chain[0].getSubjectDN()); + } + }; + + public static TrustManager[] getTrustManagers() { + return new TrustManager[]{DUMMY_TRUST_MANAGER}; + } + + @Override + protected TrustManager[] engineGetTrustManagers() { + return getTrustManagers(); + } + + @Override + protected void engineInit(KeyStore keystore) throws KeyStoreException { + // Unused + } + + @Override + protected void engineInit(ManagerFactoryParameters managerFactoryParameters) + throws InvalidAlgorithmParameterException { + // Unused + } +} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java b/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java deleted file mode 100644 index f009016a0d1..00000000000 --- a/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2012 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -/** - * <p>This is an example web service client. - * <p>To run this example, you must first start - * {@link io.netty.example.http.websocketx.server.WebSocketServer} and - * then {@link io.netty.example.http.websocketx.client.WebSocketClient}. - */ -package io.netty.example.http.websocketx.client;
null
val
train
2014-03-01T16:26:39
"2013-09-11T14:21:55Z"
mantesat
val