├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── c_src ├── Makefile ├── enm.h ├── enm_drv.c ├── enm_opts.c ├── enm_utils.c └── nanomsg-1.1.2.tar.gz ├── examples ├── bus.erl ├── pair.erl ├── pipeline.erl ├── pubsub.erl ├── request_reply.erl └── survey.erl ├── include └── enm.hrl ├── rebar.config ├── rebar.lock ├── src ├── enm.app.src ├── enm.erl ├── enm_app.erl └── enm_sup.erl ├── test ├── enm_bind_connect.erl ├── enm_bus.erl ├── enm_eqc.erl ├── enm_opts.erl ├── enm_pair.erl ├── enm_pipeline.erl ├── enm_pubsub.erl ├── enm_recv.erl ├── enm_reqrep.erl ├── enm_send.erl ├── enm_start_stop.erl └── enm_survey.erl └── tools.mk /.gitignore: -------------------------------------------------------------------------------- 1 | .eunit/* 2 | .rebar/* 3 | priv/* 4 | *.o 5 | *.beam 6 | doc 7 | test.*-temp-data 8 | ebin 9 | c_src/bin/* 10 | c_src/include/* 11 | c_src/lib/* 12 | c_src/lib64/* 13 | c_src/nanomsg-*/* 14 | c_src/*.d 15 | /.eqc-info 16 | /current_counterexample.eqc 17 | .local_dialyzer_plt 18 | dialyzer_unhandled_warnings 19 | dialyzer_warnings 20 | tags 21 | *~ 22 | _build 23 | rebar3 24 | rebar3.crashdump 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | REBAR := $(shell command -v rebar3 2>/dev/null) 2 | ifndef REBAR 3 | $(error "rebar3 not found, please install it from https://www.rebar3.org") 4 | endif 5 | 6 | all: compile 7 | 8 | compile: 9 | $(REBAR) compile 10 | 11 | clean: 12 | $(REBAR) clean 13 | rm -rf test.*-temp-data 14 | 15 | DIALYZER_APPS = kernel stdlib erts compiler crypto 16 | 17 | include tools.mk 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | `enm` is an 2 | [Erlang port driver](http://www.erlang.org/doc/tutorial/c_portdriver.html) 3 | that wraps the [nanomsg](http://nanomsg.org) C library, allowing Erlang 4 | systems to communicate with other nanomsg endpoints. `enm` supports 5 | idioms and approaches common to standard Erlang networking facilities such 6 | as `gen_tcp` and `gen_udp`. 7 | 8 | `enm` is currently based on version 1.0.0 of nanomsg, and `enm` itself 9 | is new, so its features are experimental and subject to change. 10 | 11 | ## Starting and Stopping 12 | 13 | You can start `enm` as a normal application, using 14 | `application:start(enm)` and `application:stop(enm)`. You can also call 15 | `enm:start_link/0` or `enm:start/0`, and call `enm:stop/0` to stop it. 16 | 17 | ## Just Open a Socket 18 | 19 | `enm` supports all nanomsg scalability protocols and transports. You can 20 | open a socket providing a particular scalability protocol using functions 21 | named for each protocol. For example, the `enm:pair/0` function opens a 22 | pair-type socket for one-to-one communication, and the `enm:req/0` and 23 | `enm:rep/0` functions open the request and reply ends, respectively, of the 24 | `reqrep` scalability protocol. The arity 0 versions of the `enm` 25 | scalability protocol functions listed below use default settings for the 26 | open sockets, while the arity 1 versions allow a list of [socket 27 | options](#socket-options) to be passed in order to control socket settings. 28 | 29 | * `req`: open the request end of the `reqrep` protocol 30 | * `rep`: open the reply end of the `reqrep` protocol 31 | * `pair`: open a pair socket for one-to-one communications 32 | * `bus`: open a bus socket for many-to-many communications 33 | * `pub`: open the publication end of the `pubsub` protocol 34 | * `sub`: open the subscriber end of the `pubsub` protocol 35 | * `push`: open the pushing end of the `pipeline` protocol 36 | * `pull`: open the pulling end of the `pipeline` protocol 37 | * `surveyor`: open the query end of the `survey` protocol 38 | * `respondent`: open the response end of the `survey` protocol 39 | 40 | If successful, these functions — both their arity 0 and arity 1 41 | versions — all return `{ok,Socket}`. 42 | 43 | Once opened, sockets can be bound or connected using the `enm:bind/2` or 44 | `enm:connect/2` functions respectively. Bind and connect information can 45 | alternatively be provided via [socket options](#socket-options) when 46 | sockets are first opened via the functions listed above. 47 | 48 | ## Functions 49 | 50 | In addition to the [scalability protocol functions](#just-open-a-socket), 51 | `enm` supports the following functions: 52 | 53 | * `send(Socket, Data)`: send `Data` on `Socket`. `Data` is an Erlang 54 | `iolist`, thus allowing lists of binaries and characters, or nested lists 55 | thereof, to be sent. 56 | * `recv(Socket)`: receive data from `Socket`. This function blocks 57 | indefinitely until data arrive. Returns `{ok,Data}` on success, or an 58 | error tuple on failure. `Data` defaults to a binary unless the socket was 59 | opened in `list` mode or was set into `list` mode via `setopts/2`. 60 | * `recv(Socket, Timeout)`: same as `recv/1` but if no data arrive within 61 | `Timeout` milliseconds, return `{error,etimedout}`. 62 | * `bind(Socket, Address)`: bind `Socket` to `Address`, where `Address` 63 | supports one of the nanomsg transport types: 64 | [inproc](http://nanomsg.org/v0.4/nn_inproc.7.html), 65 | [ipc](http://nanomsg.org/v0.4/nn_ipc.7.html), or 66 | [TCP](http://nanomsg.org/v0.4/nn_tcp.7.html). `Address` can be either a 67 | string or binary using the nanomsg URL address format, such as 68 | `"inproc://foo"` to bind to an intraprocess address or `"tcp://*:12345"` 69 | to listen on all your host's network interfaces on port 12345, or it can 70 | be one of the `enm` [address record types](#address-record-types). 71 | * `getopts(Socket, Options)`: return the current setting on `Socket` for 72 | each of the option names listed in `Options`. If successful, returns 73 | `{ok, OptionList}` where each element of the list provides the name and 74 | setting of one of the requested options. If `getopts` fails it return an 75 | error tuple. 76 | * `setopts(Socket, OptionList)`: apply each of the option settings in 77 | `OptionList` to `Socket`. Returns `ok` if successful or an error tuple on 78 | failure. 79 | * `controlling_process(Socket, Pid)`: the current controlling process for 80 | `Socket` can call this function to transfer its control to the process 81 | represented by `Pid`. The controlling process of a `Socket` is initially 82 | the one that opens it, and it's the one that receives data messages as 83 | Erlang messages if the socket is in an active mode. 84 | * `shutdown(Socket, EndpointId)`: removes the endpoint associated with 85 | `EndpointId`, created via `bind/2` or `connect/2`, from `Socket`. 86 | * `close(Socket)`: closes `Socket`. 87 | 88 | If you're already familiar with standard Erlang networking capabilities, 89 | you'll find these functions similar to functions supplied by standard 90 | modules such as `gen_tcp`, `gen_udp` and `inet`. 91 | 92 | ## Address Record Types 93 | 94 | To help avoid errors with mistyped string and binary address URLs, `enm` 95 | provides three record types you can use for addresses instead: 96 | 97 | * `#nn_inproc{addr=Address}`: for intra-process addresses. `Address` is a 98 | name in either string or binary form. 99 | * `#nn_ipc{path=Path}`: for IPC addresses. `Path` can be either an absolute 100 | pathname or a pathname relative to the current working directory, in 101 | either string or binary form. 102 | * `#nn_tcp{interface=Interface, addr=Address, port=Port}`: for TCP 103 | addresses. `Interface` can be the atom `any`, a network address in string 104 | or tuple form, or a string representing a network interface 105 | name. `Address` can be a hostname or a network address in either string 106 | or binary form. `Port` is a port number. 107 | 108 | Using these types, which is completely optional, requires including the 109 | `enm.hrl` file. 110 | 111 | ## Socket Options 112 | 113 | `enm` supports several socket options that can be set either when the 114 | socket is opened, or modified later during operation. Most socket options 115 | can also be read from `enm` sockets. `enm` supports the following options: 116 | 117 | * `type`: indicates the type of socket. For example, the `nnreq` type 118 | indicates a socket opened via the `req` function, and `nnsurveyor` 119 | indicates a socket implementing the query end of the `survey` 120 | protocol. This option can only be read from an `enm` socket and cannot 121 | be set. 122 | * `active`: this controls how messages are delivered from an `enm` socket 123 | to its controlling Erlang process. 124 | * The default setting, `{active,true}`, means that the driver reads 125 | data from the socket as soon as they arrive and sends them as Erlang 126 | messages to the controlling process. 127 | * The `{active,false}` setting puts an `enm` socket in passive mode; 128 | data from such a socket are retrieved only via the `enm:recv/{1,2}` 129 | functions. 130 | * The `{active,once}` setting allows the driver to deliver one message 131 | from the socket to the controlling process, after which the socket 132 | flips automatically to `{active,false}` mode. This allows the 133 | application to receive nanomsg messages as Erlang messages only when 134 | it's ready to handle them. 135 | * The `{active,N}` mode, where `N` represents an integer, is similar to 136 | `{active,once}` mode except that it allows the driver to receive `N` 137 | messages on the socket and deliver them as Erlang messages to the 138 | controlling process before flipping the socket into `{active,false}` 139 | mode. When the socket flips to passive mode, `enm` sends a 140 | `{X_passive,Socket}` message to the controlling process, with the 141 | socket's actual type name substituted for "X" (for example, 142 | `{nnpair_passive, Socket}` if `Socket` is a `pair` socket). 143 | * `raw`: this option, which defaults to false, controls whether the 144 | underlying nanomsg socket is opened with the `AF_SP` domain (the default, 145 | or set via `{raw,false}`) or the `AF_SP_RAW` domain (set via 146 | `{raw,true}`). Using the atom `raw` by itself is equivalent to 147 | `{raw,true}`. See the 148 | [nanomsg nn_socket man page](http://nanomsg.org/v0.4/nn_socket.3.html) 149 | for more details on the `AF_SP` and `AF_SP_RAW` socket domains. 150 | * `mode`: this controls the form of the data delivered or retrieved from 151 | the socket. The default, `binary`, means that data from the socket are 152 | delivered to the application as Erlang binaries, whereas the `list` 153 | setting means socket data are delivered as Erlang lists. Using the atom 154 | `binary` by itself is equivalent to `{mode,binary}`, and `list` by itself 155 | is equivalent to `{mode,list}`. 156 | * `bind`: this option allows you to open a socket and then immediately bind 157 | it to the given address. See the `bind` 158 | [function description](#functions) for more details on the allowable 159 | forms for the bind address. Note, however, that the bind endpoint 160 | identifier is thrown away in this case. If you need to later manage the 161 | endpoint via `shutdown`, use the `bind` function instead. 162 | * `connect`: this option allows you open a socket and then immediately 163 | connect it to the given address. See the `connect` 164 | [function description](#functions) for more details on the allowable 165 | forms for the connect address. Note, however, that the connect endpoint 166 | identifier is thrown away in this case. If you need to later manage the 167 | endpoint via `shutdown`, use the `connect` function instead. 168 | * `deadline`: for `surveyor` sockets, set the surveyor deadline to specify 169 | how long, in milliseconds, to wait for responses to arrive. 170 | * `subscribe`: for `sub` sockets, subscribe to the named topic, specified 171 | either as a string or a binary. Topic names must be less than 256 172 | characters in length (this is an `enm` limit, not a nanomsg 173 | limit). Applying the `subscribe` option to a socket type other than `sub` 174 | results in a `badarg` exception. 175 | * `unsubscribe`: for `sub` sockets, unsubscribe from the named topic, 176 | specified either as a string or a binary. As for the `subscribe` option, 177 | topic names must be less than 256 characters in length. Applying the 178 | `unsubscribe` option to a socket type other than `sub` results in a 179 | `badarg` exception. 180 | * `resend_ivl`: for `req` sockets, set the request resend interval to 181 | specify how long, in milliseconds, to wait for a reply before resending 182 | the request. The default is 60000. Applying the `resend_ivl` option to a 183 | socket type other than `req` results in a `badarg` exception. 184 | * `sndbuf`: set the send buffer size to the specified number of 185 | bytes. Applying this option to a socket that doesn't allow sending, 186 | specifically a `pull` or `sub` socket, results in a `badarg` exception. 187 | * `rcvbuf`: set the receive buffer size to the specified number of 188 | bytes. Applying this option to a socket that doesn't allow receiving, 189 | specifically a `push` or `pub` socket, results in a `badarg` exception. 190 | * `nodelay`: if true, set the `TCP_NODELAY` option on TCP sockets, or if 191 | false, clear it. 192 | * `reconnect_ivl`: set the reconnect interval to specify how long, in 193 | milliseconds, to wait before attempting to reconnect a broken socket 194 | connection. The supplied value must be greater than 0, otherwise a 195 | `badarg` exception results. The default is 100. 196 | * `reconnect_ivl_max`: set the maximum reconnect interval in 197 | milliseconds. If this value is greater than the default of 0, socket 198 | reconnection attempts will use exponential backoff starting with the 199 | socket's `reconnect_ivl` value and doubling it on each reconnection 200 | attempt, but will ensure the backoff value never exceeds the specified 201 | `reconnect_ivl_max` value. With the default value of 0, no exponential 202 | backoff is used, and only the `reconnect_ivl` setting controls 203 | reconnection wait time. 204 | 205 | Currently, most but not all nanomsg socket options are implemented. Please 206 | file an issue or submit a pull request if an option you need is missing. 207 | 208 | ## Examples 209 | 210 | These following examples are based on 211 | [Tim Dysinger's C examples](https://github.com/dysinger/nanomsg-examples), 212 | but they produce somewhat different output. They are all run with `inproc` 213 | addresses, thereby taking advantage of Erlang's lightweight processes 214 | rather than using separate OS processes as for Tim's examples (though we 215 | could easily do that with Erlang too). 216 | 217 | Note also that each example explicitly starts and stops `enm` — 218 | this is for exposition only, and is not something you'd do explicitly in an 219 | actual Erlang application. The output shown comes from an interactive 220 | Erlang shell, and it assumes `enm` beam files are on the shell's load 221 | path. 222 | 223 | You can find the code for these examples in the repository `examples` 224 | directory. 225 | 226 | ### Pipeline 227 | 228 | -module(pipeline). 229 | -export([start/0]). 230 | 231 | start() -> 232 | enm:start_link(), 233 | Url = "inproc://pipeline", 234 | {ok,Pull} = enm:pull([{bind,Url},list]), 235 | {ok,Push} = enm:push([{connect,Url},list]), 236 | Send1 = "Hello, World!", 237 | io:format("pushing message \"~s\"~n", [Send1]), 238 | ok = enm:send(Push, Send1), 239 | receive 240 | {nnpull,Pull,Send1} -> 241 | io:format("pulling message \"~s\"~n", [Send1]) 242 | end, 243 | Send2 = "Goodbye.", 244 | io:format("pushing message \"~s\"~n", [Send2]), 245 | ok = enm:send(Push, Send2), 246 | receive 247 | {nnpull,Pull,Send2} -> 248 | io:format("pulling message \"~s\"~n", [Send2]) 249 | end, 250 | enm:close(Push), 251 | enm:close(Pull), 252 | enm:stop(). 253 | 254 | Here, note the pattern matching in the `receive` statements where we use 255 | the data variables set for the sent messages as the data to be expected to 256 | be received. We put each socket into `list` mode to ensure these pattern 257 | matches succeed, given that `Send1` and `Send2` are strings. Note also that 258 | both the type of the socket and the socket itself are part of the received 259 | messages, allowing us to use matching to easily distinguish between what 260 | each socket is receiving. If these expected patterns did not match what was 261 | being sent, the `receive` statements would wait forever. 262 | 263 | #### Pipeline Results 264 | 265 | 1> c("examples/pipeline.erl", [{o,"examples"}]). 266 | {ok,pipeline} 267 | 2> pipeline:start(). 268 | pushing message "Hello, World!" 269 | pulling message "Hello, World!" 270 | pushing message "Goodbye." 271 | pulling message "Goodbye." 272 | ok 273 | 274 | ### Request/Reply 275 | 276 | -module(request_reply). 277 | -export([start/0]). 278 | 279 | start() -> 280 | enm:start_link(), 281 | Url = "inproc://request_reply", 282 | {ok,Rep} = enm:rep([{bind,Url}]), 283 | {ok,Req} = enm:req([{connect,Url}]), 284 | DateReq = <<"DATE">>, 285 | io:format("sending date request~n"), 286 | ok = enm:send(Req, DateReq), 287 | receive 288 | {nnrep,Rep,DateReq} -> 289 | io:format("received date request~n"), 290 | Now = httpd_util:rfc1123_date(), 291 | io:format("sending date ~s~n", [Now]), 292 | ok = enm:send(Rep, Now) 293 | end, 294 | receive 295 | {nnreq,Req,Date} -> 296 | io:format("received date ~s~n", [Date]) 297 | end, 298 | enm:close(Req), 299 | enm:close(Rep), 300 | enm:stop(). 301 | 302 | This is similar to the [pipeline example](#pipeline) except that data flows 303 | in both directions, and both sockets default to binary mode. 304 | 305 | #### Request/Reply Results 306 | 307 | 1> c("examples/request_reply.erl", [{o,"examples"}]). 308 | {ok,request_reply} 309 | 2> request_reply:start(). 310 | sending date request 311 | received date request 312 | sending date Tue, 09 Sep 2014 23:05:26 GMT 313 | received date Tue, 09 Sep 2014 23:05:26 GMT 314 | ok 315 | 316 | ### Pair 317 | 318 | -module(pair). 319 | -export([start/0, node/4]). 320 | 321 | start() -> 322 | enm:start_link(), 323 | Self = self(), 324 | Url = "inproc://pair", 325 | spawn(?MODULE, node, [Self, Url, bind, "Node0"]), 326 | spawn(?MODULE, node, [Self, Url, connect, "Node1"]), 327 | collect(["Node0","Node1"]). 328 | 329 | node(Parent, Url, F, Name) -> 330 | {ok,P} = enm:pair([{active,3}]), 331 | {ok,Id} = enm:F(P,Url), 332 | send_recv(P, Name), 333 | enm:shutdown(P, Id), 334 | Parent ! {done,Name}. 335 | 336 | send_recv(Sock, Name) -> 337 | receive 338 | {_,Sock,Buf} -> 339 | io:format("~s received \"~s\"~n", [Name, Buf]) 340 | after 341 | 100 -> 342 | ok 343 | end, 344 | case enm:getopts(Sock, [active]) of 345 | {ok, [{active,false}]} -> 346 | ok; 347 | {error, Error} -> 348 | error(Error); 349 | _ -> 350 | timer:sleep(1000), 351 | io:format("~s sending \"~s\"~n", [Name, Name]), 352 | ok = enm:send(Sock, Name), 353 | send_recv(Sock, Name) 354 | end. 355 | 356 | collect([]) -> 357 | ok; 358 | collect([Name|Names]) -> 359 | receive 360 | {done,Name} -> 361 | collect(Names) 362 | end. 363 | 364 | This code is a little more involved than previous examples because we spawn 365 | two child processes that receive and send messages. Note how we use the 366 | `{active,N}` socket mode for each end of the pair to eventually break out 367 | of the recursive `send_recv/2` function, by using `enm:getopts/2` to 368 | check for when each socket flips into `{active,false}` mode. 369 | 370 | #### Pair Results 371 | 372 | 1> c("examples/pair.erl",[{o,"examples"}]). 373 | {ok,pair} 374 | 2> pair:start(). 375 | Node0 sending "Node0" 376 | Node1 sending "Node1" 377 | Node0 received "Node1" 378 | Node1 received "Node0" 379 | Node1 sending "Node1" 380 | Node0 sending "Node0" 381 | Node0 received "Node1" 382 | Node1 received "Node0" 383 | Node1 sending "Node1" 384 | Node0 sending "Node0" 385 | Node0 received "Node1" 386 | Node1 received "Node0" 387 | ok 388 | 389 | ### Pub/Sub 390 | 391 | -module(pubsub). 392 | -export([start/0]). 393 | 394 | -define(COUNT, 3). 395 | 396 | start() -> 397 | enm:start_link(), 398 | Url = "inproc://pubsub", 399 | Pub = pub(Url), 400 | collect(subs(Url, self())), 401 | enm:close(Pub), 402 | enm:stop(). 403 | 404 | pub(Url) -> 405 | {ok,Pub} = enm:pub([{bind,Url}]), 406 | spawn_link(fun() -> pub(Pub, ?COUNT) end), 407 | Pub. 408 | pub(_, 0) -> 409 | ok; 410 | pub(Pub, Count) -> 411 | Now = httpd_util:rfc1123_date(), 412 | io:format("publishing date \"~s\"~n", [Now]), 413 | ok = enm:send(Pub, ["DATE: ", Now]), 414 | timer:sleep(1000), 415 | pub(Pub, Count-1). 416 | 417 | subs(Url, Parent) -> 418 | subs(Url, Parent, ?COUNT, []). 419 | subs(_, _, 0, Acc) -> 420 | Acc; 421 | subs(Url, Parent, Count, Acc) -> 422 | {ok, Sub} = enm:sub([{connect,Url},{subscribe,"DATE:"},{active,false}]), 423 | Name = "Subscriber" ++ integer_to_list(Count), 424 | spawn_link(fun() -> sub(Sub, Parent, Name) end), 425 | subs(Url, Parent, Count-1, [Name|Acc]). 426 | sub(Sub, Parent, Name) -> 427 | case enm:recv(Sub, 2000) of 428 | {ok,Data} -> 429 | io:format("~s received \"~s\"~n", [Name, Data]), 430 | sub(Sub, Parent, Name); 431 | {error,etimedout} -> 432 | enm:close(Sub), 433 | Parent ! {done, Name}, 434 | ok 435 | end. 436 | 437 | collect([Sub|Subs]) -> 438 | receive 439 | {done,Sub} -> 440 | collect(Subs) 441 | end; 442 | collect([]) -> 443 | ok. 444 | 445 | This code sets up a publisher and 3 subscribers, and the publisher 446 | publishes dates to the subscribers. It includes the text "DATE:" in each 447 | message, and messages containing that text are what the subscribers are 448 | looking to receive. Note the use of `{active,false}` mode for the 449 | subscriber sockets; this is done because the Erlang process that creates 450 | the sockets, known as the *controlling process* for the socket, is not the 451 | same process that receives the messages. Only the controlling process can 452 | receive messages in an active mode from a socket. 453 | 454 | #### Pub/Sub Results 455 | 456 | 1> c("examples/pubsub.erl", [{o,"examples"}]). 457 | {ok,pubsub} 458 | 2> pubsub:start(). 459 | publishing date "Tue, 09 Sep 2014 23:08:10 GMT" 460 | Subscriber3 received "DATE: Tue, 09 Sep 2014 23:08:10 GMT" 461 | Subscriber2 received "DATE: Tue, 09 Sep 2014 23:08:10 GMT" 462 | Subscriber1 received "DATE: Tue, 09 Sep 2014 23:08:10 GMT" 463 | publishing date "Tue, 09 Sep 2014 23:08:11 GMT" 464 | Subscriber3 received "DATE: Tue, 09 Sep 2014 23:08:11 GMT" 465 | Subscriber2 received "DATE: Tue, 09 Sep 2014 23:08:11 GMT" 466 | Subscriber1 received "DATE: Tue, 09 Sep 2014 23:08:11 GMT" 467 | publishing date "Tue, 09 Sep 2014 23:08:12 GMT" 468 | Subscriber3 received "DATE: Tue, 09 Sep 2014 23:08:12 GMT" 469 | Subscriber2 received "DATE: Tue, 09 Sep 2014 23:08:12 GMT" 470 | Subscriber1 received "DATE: Tue, 09 Sep 2014 23:08:12 GMT" 471 | ok 472 | 473 | ### Survey 474 | 475 | -module(survey). 476 | -export([start/0]). 477 | 478 | -define(COUNT, 3). 479 | 480 | start() -> 481 | enm:start_link(), 482 | Url = "inproc://survey", 483 | Self = self(), 484 | {ok,Survey} = enm:surveyor([{bind,Url},{deadline,3000}]), 485 | Clients = clients(Url, Self), 486 | ok = enm:send(Survey, httpd_util:rfc1123_date()), 487 | get_responses(Survey), 488 | wait_for_clients(Clients), 489 | enm:close(Survey), 490 | enm:stop(). 491 | 492 | clients(Url, Parent) -> 493 | clients(Url, Parent, ?COUNT, []). 494 | clients(_, _, 0, Acc) -> 495 | Acc; 496 | clients(Url, Parent, Count, Acc) -> 497 | {ok, Respondent} = enm:respondent([{connect,Url},{active,false},list]), 498 | Name = "Respondent" ++ integer_to_list(Count), 499 | Pid = spawn_link(fun() -> client(Respondent, Name, Parent) end), 500 | clients(Url, Parent, Count-1, [Pid|Acc]). 501 | 502 | client(Respondent, Name, Parent) -> 503 | {ok,Msg} = enm:recv(Respondent, 5000), 504 | Date = httpd_util:convert_request_date(Msg), 505 | ok = enm:send(Respondent, term_to_binary(Date)), 506 | io:format("~s got \"~s\"~n", [Name, Msg]), 507 | Parent ! {done, self(), Respondent}. 508 | 509 | get_responses(Survey) -> 510 | get_responses(Survey, ?COUNT+1). 511 | get_responses(_, 0) -> 512 | ok; 513 | get_responses(Survey, Count) -> 514 | receive 515 | {nnsurveyor,Survey,BinResp} -> 516 | Response = binary_to_term(BinResp), 517 | io:format("received survey response ~p~n", [Response]); 518 | {nnsurveyor_deadline,Survey} -> 519 | io:format("survey has expired~n") 520 | end, 521 | get_responses(Survey, Count-1). 522 | 523 | wait_for_clients([Client|Clients]) -> 524 | receive 525 | {done,Client,Respondent} -> 526 | enm:close(Respondent), 527 | wait_for_clients(Clients) 528 | end; 529 | wait_for_clients([]) -> 530 | ok. 531 | 532 | This example creates a surveyor, and several respondents connect to it. The 533 | `{deadline,3000}` option used when creating the surveyor socket means 534 | respondents have a maximum of 3 seconds to respond to any survey. The 535 | surveyor sends out the survey, and then collects responses from each of the 536 | respondents. When we hit the survey deadline, the controlling process for 537 | the surveyor socket gets a `{nnsurveyor_deadline,Socket}` message. 538 | 539 | #### Survey Results 540 | 541 | 1> c("examples/survey.erl", [{o,"examples"}]). 542 | {ok,survey} 543 | 2> survey:start(). 544 | Respondent3 got "Tue, 09 Sep 2014 23:09:34 GMT" 545 | Respondent2 got "Tue, 09 Sep 2014 23:09:34 GMT" 546 | Respondent1 got "Tue, 09 Sep 2014 23:09:34 GMT" 547 | received survey response {{2014,9,9},{23,9,34}} 548 | received survey response {{2014,9,9},{23,9,34}} 549 | received survey response {{2014,9,9},{23,9,34}} 550 | survey has expired 551 | ok 552 | 553 | ### Bus 554 | 555 | -module(bus). 556 | -export([start/0]). 557 | 558 | -define(COUNT, 4). 559 | 560 | start() -> 561 | enm:start_link(), 562 | UrlBase = "inproc://bus", 563 | Buses = connect_buses(UrlBase), 564 | Pids = send_and_receive(Buses, self()), 565 | wait_for_pids(Pids), 566 | enm:stop(). 567 | 568 | connect_buses(UrlBase) -> 569 | connect_buses(UrlBase, lists:seq(1,?COUNT), []). 570 | connect_buses(UrlBase, [1=Node|Nodes], Buses) -> 571 | Url = make_url(UrlBase, Node), 572 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 573 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 2)), 574 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 3)), 575 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 576 | connect_buses(UrlBase, [?COUNT=Node|Nodes], Buses) -> 577 | Url = make_url(UrlBase, Node), 578 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 579 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 1)), 580 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 581 | connect_buses(UrlBase, [Node|Nodes], Buses) -> 582 | Url = make_url(UrlBase, Node), 583 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 584 | Urls = [make_url(UrlBase,N) || N <- lists:seq(Node+1,?COUNT)], 585 | [{ok,_} = enm:connect(Bus,U) || U <- Urls], 586 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 587 | connect_buses(_, [], Buses) -> 588 | Buses. 589 | 590 | send_and_receive(Buses, Parent) -> 591 | send_and_receive(Buses, Parent, []). 592 | send_and_receive([{Bus,Id}|Buses], Parent, Acc) -> 593 | Pid = spawn_link(fun() -> bus(Bus, Id, Parent) end), 594 | send_and_receive(Buses, Parent, [Pid|Acc]); 595 | send_and_receive([], _, Acc) -> 596 | Acc. 597 | 598 | bus(Bus, Id, Parent) -> 599 | Name = "node"++integer_to_list(Id), 600 | io:format("node ~w sending \"~s\"~n", [Id, Name]), 601 | ok = enm:send(Bus, Name), 602 | collect(Bus, Id, Parent). 603 | 604 | collect(Bus, Id, Parent) -> 605 | case enm:recv(Bus, 1000) of 606 | {ok,Data} -> 607 | io:format("node ~w received \"~s\"~n", [Id, Data]), 608 | collect(Bus, Id, Parent); 609 | {error,etimedout} -> 610 | Parent ! {done, self(), Bus} 611 | end. 612 | 613 | wait_for_pids([Pid|Pids]) -> 614 | receive 615 | {done,Pid,Bus} -> 616 | enm:close(Bus), 617 | wait_for_pids(Pids) 618 | end; 619 | wait_for_pids([]) -> 620 | ok. 621 | 622 | make_url(Base,N) -> 623 | Base++integer_to_list(N). 624 | 625 | In this example consisting of four nodes, each node is connected such that 626 | it receives one message from each of the other nodes. Each node binds to 627 | one bus address and connects to one or more of the other bus addresses 628 | — for example, node 1 connects to nodes 2 and 3, and node 4 connects 629 | only to node 1. This example uses `{active,false}` mode since the Erlang 630 | processes calling `enm:recv/2` are not the controlling processes for the 631 | receiving sockets. 632 | 633 | #### Bus Results 634 | 635 | 1> c("examples/bus", [{o,"examples"}]). 636 | {ok,bus} 637 | 2> bus:start(). 638 | node 4 sending "node4" 639 | node 3 sending "node3" 640 | node 2 sending "node2" 641 | node 1 sending "node1" 642 | node 3 received "node4" 643 | node 2 received "node4" 644 | node 1 received "node4" 645 | node 4 received "node3" 646 | node 3 received "node2" 647 | node 2 received "node3" 648 | node 1 received "node3" 649 | node 4 received "node2" 650 | node 3 received "node1" 651 | node 2 received "node1" 652 | node 1 received "node2" 653 | node 4 received "node1" 654 | ok 655 | -------------------------------------------------------------------------------- /c_src/Makefile: -------------------------------------------------------------------------------- 1 | NANOMSG := ./nanomsg-1.1.2 2 | NANOMSG_LIB := lib/libnanomsg.a 3 | NANOMSG_TARBALL := $(NANOMSG).tar.gz 4 | CLEAN := rm -rf $(NANOMSG) bin include lib lib64 share 5 | 6 | all: $(NANOMSG_LIB) 7 | 8 | $(NANOMSG_LIB): $(NANOMSG_TARBALL) 9 | set -e ; \ 10 | $(CLEAN) ; \ 11 | tar zxf $(NANOMSG_TARBALL) ; \ 12 | cur=`pwd` ; \ 13 | cd $(NANOMSG) ; \ 14 | mkdir build ; \ 15 | cd build ; \ 16 | cmake .. -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DCMAKE_INSTALL_PREFIX=$$cur -DNN_STATIC_LIB=ON ; \ 17 | cmake --build . ; \ 18 | cmake --build . --target install 19 | 20 | .PHONY: clean 21 | clean: 22 | $(CLEAN) 23 | -------------------------------------------------------------------------------- /c_src/enm.h: -------------------------------------------------------------------------------- 1 | #ifndef ENM_C_SRC_ENM_H 2 | #define ENM_C_SRC_ENM_H 3 | 4 | // ------------------------------------------------------------------- 5 | // 6 | // enm.h: common definitions for nanomsg Erlang language binding 7 | // 8 | // Copyright (c) 2014-2016 Basho Technologies, Inc. All Rights Reserved. 9 | // 10 | // This file is provided to you under the Apache License, 11 | // Version 2.0 (the "License"); you may not use this file 12 | // except in compliance with the License. You may obtain 13 | // a copy of the License at 14 | // 15 | // http://www.apache.org/licenses/LICENSE-2.0 16 | // 17 | // Unless required by applicable law or agreed to in writing, 18 | // software distributed under the License is distributed on an 19 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 20 | // KIND, either express or implied. See the License for the 21 | // specific language governing permissions and limitations 22 | // under the License. 23 | // 24 | // ------------------------------------------------------------------- 25 | 26 | #include "nanomsg/nn.h" 27 | #include "nanomsg/reqrep.h" 28 | #include "nanomsg/bus.h" 29 | #include "nanomsg/pubsub.h" 30 | #include "nanomsg/pipeline.h" 31 | #include "nanomsg/survey.h" 32 | #include "nanomsg/pair.h" 33 | #include "erl_driver.h" 34 | #include "ei.h" 35 | 36 | #define ENM_CLOSE 1 37 | #define ENM_BIND 2 38 | #define ENM_CONNECT 3 39 | #define ENM_SHUTDOWN 4 40 | #define ENM_TERM 5 41 | #define ENM_RECV 10 42 | #define ENM_CANCEL_RECV 11 43 | #define ENM_GETOPTS 12 44 | #define ENM_SETOPTS 13 45 | #define ENM_REQ 20 46 | #define ENM_REP 21 47 | #define ENM_BUS 22 48 | #define ENM_PUB 23 49 | #define ENM_SUB 24 50 | #define ENM_PUSH 25 51 | #define ENM_PULL 26 52 | #define ENM_SVYR 27 53 | #define ENM_RESP 28 54 | #define ENM_PAIR 29 55 | 56 | #define ENM_FALSE 0 57 | #define ENM_TRUE 1 58 | #define ENM_ONCE 2 59 | #define ENM_N 3 60 | #define ENM_ACTIVE 10 61 | #define ENM_TYPE 11 62 | #define ENM_RAW 12 63 | #define ENM_DEADLINE 13 64 | #define ENM_SUBSCRIBE 14 65 | #define ENM_UNSUBSCRIBE 15 66 | #define ENM_RESEND_IVL 16 67 | #define ENM_BINARY 17 68 | #define ENM_SNDBUF 18 69 | #define ENM_RCVBUF 19 70 | #define ENM_NODELAY 20 71 | #define ENM_IPV4ONLY 21 72 | #define ENM_RECONNECT_IVL 22 73 | #define ENM_RECONNECT_IVL_MAX 23 74 | 75 | #define IDXSHFT(P,I,SH) ((int)(((unsigned char)((P)[I]))<<(SH))) 76 | #define GETINT16(P) (IDXSHFT(P,0,8) | IDXSHFT(P,1,0)) 77 | #define GETINT32(P) (IDXSHFT(P,0,24) | IDXSHFT(P,1,16) | \ 78 | IDXSHFT(P,2,8) | IDXSHFT(P,3,0)) 79 | 80 | typedef struct EnmRecv { 81 | ErlDrvMonitor monitor; 82 | erlang_ref ref; 83 | ErlDrvTermData rcvr; 84 | struct EnmRecv* next; 85 | } EnmRecv; 86 | 87 | typedef struct { 88 | ErlDrvPort port; 89 | EnmRecv* waiting_recvs; 90 | size_t busy_limit; 91 | int protocol; 92 | int fd; 93 | int sfd; 94 | int rfd; 95 | short n_count; 96 | struct { 97 | unsigned active: 2; 98 | unsigned raw: 1; 99 | unsigned listmode: 1; 100 | unsigned writable: 1; 101 | unsigned write_poll: 1; 102 | unsigned read_poll: 1; 103 | unsigned busy: 1; 104 | } b; 105 | } EnmData; 106 | 107 | #define ENM_MAX_TOPIC 256 108 | 109 | typedef struct { 110 | char topic[ENM_MAX_TOPIC]; 111 | char* buf; 112 | char** rbuf; 113 | int len; 114 | int index; 115 | int rlen; 116 | int deadline; 117 | int resend_ivl; 118 | int sndbuf; 119 | int rcvbuf; 120 | int reconnect_ivl; 121 | int reconnect_ivl_max; 122 | struct { 123 | unsigned topic_seen: 1; 124 | } b; 125 | } EnmArgs; 126 | 127 | typedef enum { 128 | ENM_NANOMSG_ERROR, 129 | ENM_POSIX_ERROR, 130 | ENM_UNKNOWN_ERROR 131 | } EnmErrorType; 132 | 133 | extern int enm_write_select(EnmData* d, int start); 134 | extern int enm_read_select(EnmData* d, int start); 135 | extern ErlDrvSSizeT enm_getopts(EnmData* d, EnmArgs* args); 136 | extern ErlDrvSSizeT enm_setopts_priv(EnmData* d, int opt, EnmArgs* args); 137 | extern ErlDrvSSizeT enm_setopts(EnmData* d, EnmArgs* args); 138 | extern ErlDrvSSizeT enm_ok(char* buf); 139 | extern EnmErrorType enm_errno_str(int err, char* errstr); 140 | extern ErlDrvSSizeT enm_errno_tuple(char* buf, int err); 141 | extern ErlDrvTermData enm_errno_atom(int err); 142 | extern const char* enm_protocol_name(int protocol); 143 | 144 | #endif 145 | -------------------------------------------------------------------------------- /c_src/enm_drv.c: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------- 2 | // 3 | // enm_drv.c: driver entry points for nanomsg Erlang language binding 4 | // 5 | // Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | // 7 | // This file is provided to you under the Apache License, 8 | // Version 2.0 (the "License"); you may not use this file 9 | // except in compliance with the License. You may obtain 10 | // a copy of the License at 11 | // 12 | // http://www.apache.org/licenses/LICENSE-2.0 13 | // 14 | // Unless required by applicable law or agreed to in writing, 15 | // software distributed under the License is distributed on an 16 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | // KIND, either express or implied. See the License for the 18 | // specific language governing permissions and limitations 19 | // under the License. 20 | // 21 | // ------------------------------------------------------------------- 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "enm.h" 28 | 29 | #define ENM_REFS_EQUAL(R1,R2) \ 30 | (strcmp((R1).node, (R2).node) == 0 && \ 31 | (R1).len == (R2).len && memcmp((R1).n, (R2).n, (R1).len) == 0) 32 | 33 | static EnmData** enm_sockets; 34 | 35 | static int 36 | enm_cmd_to_protocol(int cmd) 37 | { 38 | switch (cmd) { 39 | case ENM_REQ: 40 | return NN_REQ; 41 | case ENM_REP: 42 | return NN_REP; 43 | case ENM_BUS: 44 | return NN_BUS; 45 | case ENM_PUB: 46 | return NN_PUB; 47 | case ENM_SUB: 48 | return NN_SUB; 49 | case ENM_PUSH: 50 | return NN_PUSH; 51 | case ENM_PULL: 52 | return NN_PULL; 53 | case ENM_SVYR: 54 | return NN_SURVEYOR; 55 | case ENM_RESP: 56 | return NN_RESPONDENT; 57 | case ENM_PAIR: 58 | return NN_PAIR; 59 | default: 60 | errno = ENOPROTOOPT; 61 | return -1; 62 | } 63 | } 64 | 65 | static ErlDrvTermData 66 | enm_protocol_atom(int protocol) 67 | { 68 | return driver_mk_atom((char*)enm_protocol_name(protocol)); 69 | } 70 | 71 | int 72 | enm_write_select(EnmData* d, int start) 73 | { 74 | ErlDrvEvent event; 75 | int rc; 76 | size_t optlen = sizeof d->sfd; 77 | 78 | if (start) { 79 | if (d->b.write_poll) 80 | return 0; 81 | if (d->sfd == -1) { 82 | if (d->protocol == NN_PULL || d->protocol == NN_SUB) { 83 | errno = EINVAL; 84 | return -1; 85 | } 86 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_SNDFD, &d->sfd, &optlen); 87 | if (rc < 0) 88 | return -1; 89 | enm_sockets[d->sfd] = d; 90 | } 91 | event = (ErlDrvEvent)(long)d->sfd; 92 | driver_select(d->port, event, ERL_DRV_WRITE|ERL_DRV_USE, 1); 93 | d->b.write_poll = 1; 94 | } else { 95 | if (!d->b.write_poll) 96 | return 0; 97 | assert(d->sfd != -1); 98 | event = (ErlDrvEvent)(long)d->sfd; 99 | driver_select(d->port, event, ERL_DRV_WRITE|ERL_DRV_USE, 0); 100 | d->b.write_poll = 0; 101 | } 102 | return 0; 103 | } 104 | 105 | int 106 | enm_read_select(EnmData* d, int start) 107 | { 108 | ErlDrvEvent event; 109 | int rc; 110 | size_t optlen = sizeof d->rfd; 111 | 112 | if (start) { 113 | if (d->b.read_poll) 114 | return 0; 115 | if (d->rfd == -1) { 116 | if (d->protocol == NN_PUSH) { 117 | errno = EINVAL; 118 | return -1; 119 | } 120 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_RCVFD, &d->rfd, &optlen); 121 | if (rc < 0) 122 | return -1; 123 | enm_sockets[d->rfd] = d; 124 | } 125 | event = (ErlDrvEvent)(long)d->rfd; 126 | driver_select(d->port, event, ERL_DRV_READ|ERL_DRV_USE, 1); 127 | d->b.read_poll = 1; 128 | } else { 129 | if (!d->b.read_poll) 130 | return 0; 131 | assert(d->rfd != -1); 132 | event = (ErlDrvEvent)(long)d->rfd; 133 | driver_select(d->port, event, ERL_DRV_READ|ERL_DRV_USE, 0); 134 | d->b.read_poll = 0; 135 | } 136 | return 0; 137 | } 138 | 139 | static void 140 | enm_add_waiter(EnmData* d, erlang_ref* ref) 141 | { 142 | EnmRecv *rcv, *cur; 143 | 144 | rcv = driver_alloc(sizeof(EnmRecv)); 145 | if (rcv == 0) { 146 | driver_failure_posix(d->port, ENOMEM); 147 | return; 148 | } 149 | memcpy(&rcv->ref, ref, sizeof *ref); 150 | rcv->rcvr = driver_caller(d->port); 151 | rcv->next = 0; 152 | driver_monitor_process(d->port, rcv->rcvr, &rcv->monitor); 153 | cur = d->waiting_recvs; 154 | if (cur == 0) 155 | d->waiting_recvs = rcv; 156 | else { 157 | while (cur) { 158 | if (cur->next != 0) 159 | cur = cur->next; 160 | else { 161 | cur->next = rcv; 162 | break; 163 | } 164 | } 165 | } 166 | } 167 | 168 | static int 169 | enm_init() 170 | { 171 | struct rlimit rl; 172 | 173 | if (getrlimit(RLIMIT_NOFILE, &rl) < 0) 174 | return -1; 175 | enm_sockets = (EnmData**)driver_alloc(rl.rlim_cur * sizeof(EnmData*)); 176 | if (enm_sockets == 0) 177 | return -1; 178 | return 0; 179 | } 180 | 181 | static void 182 | enm_finish() 183 | { 184 | driver_free(enm_sockets); 185 | } 186 | 187 | static ErlDrvData 188 | enm_start(ErlDrvPort port, char* command) 189 | { 190 | EnmData* d = (EnmData*)driver_alloc(sizeof(EnmData)); 191 | memset(d, 0, sizeof *d); 192 | d->port = port; 193 | d->waiting_recvs = 0; 194 | set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY); 195 | return (ErlDrvData)d; 196 | } 197 | 198 | static void 199 | enm_stop(ErlDrvData drv_data) 200 | { 201 | EnmData* d = (EnmData*)drv_data; 202 | EnmRecv* rcv = d->waiting_recvs; 203 | ErlDrvTermData port = driver_mk_port(d->port); 204 | char refbuf[64]; 205 | int index; 206 | 207 | enm_write_select(d, 0); 208 | enm_read_select(d, 0); 209 | while (rcv != 0) { 210 | EnmRecv* p = rcv; 211 | if (driver_demonitor_process(d->port, &rcv->monitor) == 0) { 212 | index = 0; 213 | ei_encode_version(refbuf, &index); 214 | ei_encode_ref(refbuf, &index, &rcv->ref); 215 | { 216 | ErlDrvTermData term[] = { 217 | ERL_DRV_EXT2TERM, (ErlDrvTermData)refbuf, index+1, 218 | ERL_DRV_ATOM, driver_mk_atom("error"), 219 | ERL_DRV_ATOM, enm_errno_atom(ETERM), 220 | ERL_DRV_TUPLE, 2, 221 | ERL_DRV_TUPLE, 2, 222 | }; 223 | erl_drv_send_term(port, rcv->rcvr, term, 224 | sizeof term/sizeof *term); 225 | } 226 | } 227 | rcv = rcv->next; 228 | driver_free(p); 229 | } 230 | if (d->fd != -1) 231 | nn_close(d->fd); 232 | d->fd = d->sfd = d->rfd = -1; 233 | driver_free(d); 234 | } 235 | 236 | static int 237 | enm_do_send(EnmData* d, const struct nn_msghdr* msghdr, int* err) 238 | { 239 | int rc; 240 | 241 | if (msghdr->msg_iovlen == 0) 242 | return 0; 243 | *err = 0; 244 | do { 245 | rc = nn_sendmsg(d->fd, msghdr, NN_DONTWAIT); 246 | if (rc < 0) { 247 | *err = errno; 248 | switch (*err) { 249 | case EINTR: 250 | case EFSM: 251 | /* do nothing */ 252 | break; 253 | case EAGAIN: 254 | d->b.writable = 0; 255 | break; 256 | default: 257 | enm_write_select(d, 0); 258 | enm_read_select(d, 0); 259 | driver_failure(d->port, *err); 260 | } 261 | } 262 | } while (*err == EINTR); 263 | return rc; 264 | } 265 | 266 | static void 267 | enm_outputv(ErlDrvData drv_data, ErlIOVec *ev) 268 | { 269 | EnmData* d = (EnmData*)drv_data; 270 | ErlIOVec qev; 271 | ErlDrvSizeT qtotal; 272 | struct nn_msghdr msghdr; 273 | int i, rc = -1, err; 274 | 275 | if (d->fd == -1 || d->protocol == NN_PULL || d->protocol == NN_SUB) 276 | return; 277 | qtotal = driver_peekqv(d->port, &qev); 278 | if (qtotal > 0) { 279 | memset(&msghdr, 0, sizeof msghdr); 280 | msghdr.msg_iov = (struct nn_iovec*)qev.iov; 281 | msghdr.msg_iovlen = qev.vsize; 282 | msghdr.msg_control = 0; 283 | err = 0; 284 | do { 285 | rc = enm_do_send(d, &msghdr, &err); 286 | if (rc < 0) { 287 | if (err == EAGAIN) { 288 | d->b.writable = 0; 289 | break; 290 | } else if (err != EINTR) { 291 | char errstr[32]; 292 | switch (enm_errno_str(err, errstr)) { 293 | case ENM_NANOMSG_ERROR: 294 | driver_failure_atom(d->port, errstr); 295 | break; 296 | case ENM_POSIX_ERROR: 297 | driver_failure_posix(d->port, err); 298 | break; 299 | case ENM_UNKNOWN_ERROR: 300 | driver_failure(d->port, err); 301 | break; 302 | } 303 | return; 304 | } 305 | } 306 | } while (err == EINTR); 307 | } 308 | /* 309 | * Do nothing if the message has no data 310 | */ 311 | if (ev->size == 0 || ev->vsize == 0 || 312 | (ev->vsize == 1 && *ev->binv == 0 && ev->iov->iov_len == 0)) 313 | return; 314 | if (d->b.writable) { 315 | memset(&msghdr, 0, sizeof msghdr); 316 | msghdr.msg_iov = (struct nn_iovec*)ev->iov; 317 | msghdr.msg_iovlen = ev->vsize; 318 | msghdr.msg_control = 0; 319 | err = 0; 320 | do { 321 | rc = enm_do_send(d, &msghdr, &err); 322 | if (rc < 0) { 323 | if (err == EAGAIN) { 324 | d->b.writable = 0; 325 | break; 326 | } else if (err != EINTR) { 327 | char errstr[32]; 328 | switch (enm_errno_str(err, errstr)) { 329 | case ENM_NANOMSG_ERROR: 330 | driver_failure_atom(d->port, errstr); 331 | break; 332 | case ENM_POSIX_ERROR: 333 | driver_failure_posix(d->port, err); 334 | break; 335 | case ENM_UNKNOWN_ERROR: 336 | driver_failure(d->port, err); 337 | break; 338 | } 339 | return; 340 | } 341 | } 342 | } while (err == EINTR); 343 | } 344 | if (rc < 0 && !d->b.writable) { 345 | rc = 0; 346 | d->b.busy = 1; 347 | set_busy_port(d->port, d->b.busy); 348 | for (i = 0; i < ev->vsize; i++) { 349 | ErlDrvBinary* bin = 0; 350 | if (ev->binv[i] != 0) { 351 | bin = ev->binv[i]; 352 | driver_binary_inc_refc(bin); 353 | } else if (ev->iov[i].iov_len > 0) { 354 | SysIOVec* vec = &ev->iov[i]; 355 | bin = driver_alloc_binary(vec->iov_len); 356 | memcpy(bin->orig_bytes, vec->iov_base, vec->iov_len); 357 | } 358 | if (bin != 0) 359 | driver_enq_bin(d->port, bin, 0, bin->orig_size); 360 | } 361 | if (!d->b.write_poll) 362 | enm_write_select(d, 1); 363 | } 364 | if (rc > 0 && d->protocol == NN_SURVEYOR && d->b.active != ENM_FALSE) 365 | enm_read_select(d, 1); 366 | } 367 | 368 | static ErlDrvSSizeT 369 | enm_create_socket(EnmData* d, EnmArgs* args) 370 | { 371 | ErlDrvSSizeT res; 372 | int rc, domain, err, opt; 373 | size_t optlen = sizeof d->sfd; 374 | 375 | d->fd = d->sfd = d->rfd = -1; 376 | d->b.active = ENM_TRUE; 377 | while (args->index < args->len) { 378 | opt = *args->buf++; 379 | args->index++; 380 | switch (opt) { 381 | case ENM_ACTIVE: 382 | case ENM_RAW: 383 | case ENM_BINARY: 384 | case ENM_DEADLINE: 385 | case ENM_SUBSCRIBE: 386 | case ENM_RESEND_IVL: 387 | case ENM_SNDBUF: 388 | case ENM_RCVBUF: 389 | case ENM_NODELAY: 390 | case ENM_IPV4ONLY: 391 | if ((res = enm_setopts_priv(d, opt, args)) != 0) 392 | return res; 393 | break; 394 | default: 395 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 396 | } 397 | } 398 | domain = d->b.raw ? AF_SP_RAW : AF_SP; 399 | d->fd = nn_socket(domain, d->protocol); 400 | if (d->fd < 0) 401 | return enm_errno_tuple(*args->rbuf, errno); 402 | if (args->deadline != 0) { 403 | rc = nn_setsockopt(d->fd, NN_SURVEYOR, NN_SURVEYOR_DEADLINE, 404 | &args->deadline, sizeof args->deadline); 405 | if (rc < 0) { 406 | err = errno; 407 | nn_close(d->fd); 408 | d->fd = -1; 409 | return enm_errno_tuple(*args->rbuf, err); 410 | } 411 | } 412 | if (args->resend_ivl != 0) { 413 | rc = nn_setsockopt(d->fd, NN_REQ, NN_REQ_RESEND_IVL, 414 | &args->resend_ivl, sizeof args->resend_ivl); 415 | if (rc < 0) { 416 | err = errno; 417 | nn_close(d->fd); 418 | d->fd = -1; 419 | return enm_errno_tuple(*args->rbuf, err); 420 | } 421 | } 422 | if (args->b.topic_seen) { 423 | rc = nn_setsockopt(d->fd, NN_SUB, NN_SUB_SUBSCRIBE, 424 | args->topic, strlen(args->topic)); 425 | if (rc < 0) { 426 | err = errno; 427 | nn_close(d->fd); 428 | d->fd = -1; 429 | return enm_errno_tuple(*args->rbuf, err); 430 | } 431 | } 432 | if (d->protocol != NN_PULL && d->protocol != NN_SUB) { 433 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_SNDFD, &d->sfd, &optlen); 434 | if (rc < 0) { 435 | err = errno; 436 | nn_close(d->fd); 437 | d->fd = -1; 438 | return enm_errno_tuple(*args->rbuf, err); 439 | } 440 | enm_sockets[d->sfd] = d; 441 | d->b.writable = 1; 442 | if (args->sndbuf != 0) { 443 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_SNDBUF, 444 | &args->sndbuf, sizeof args->sndbuf); 445 | if (rc < 0) { 446 | err = errno; 447 | nn_close(d->fd); 448 | d->fd = -1; 449 | d->sfd = -1; 450 | return enm_errno_tuple(*args->rbuf, err); 451 | } 452 | } else { 453 | optlen = sizeof args->sndbuf; 454 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_SNDBUF, 455 | &args->sndbuf, &optlen); 456 | if (rc < 0) { 457 | err = errno; 458 | nn_close(d->fd); 459 | d->fd = -1; 460 | d->sfd = -1; 461 | return enm_errno_tuple(*args->rbuf, err); 462 | } 463 | } 464 | if (args->sndbuf != 0) { 465 | ErlDrvSizeT low = args->sndbuf >> 1, high = args->sndbuf; 466 | erl_drv_busy_msgq_limits(d->port, &low, &high); 467 | } 468 | } 469 | if (d->b.active) { 470 | if (d->protocol != NN_PUSH && d->protocol != NN_PUB) { 471 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_RCVFD, &d->rfd, &optlen); 472 | if (rc < 0) { 473 | err = errno; 474 | nn_close(d->fd); 475 | d->fd = -1; 476 | d->sfd = -1; 477 | return enm_errno_tuple(*args->rbuf, err); 478 | } 479 | enm_sockets[d->rfd] = d; 480 | if (d->protocol != NN_SURVEYOR) 481 | enm_read_select(d, 1); 482 | } 483 | if (args->rcvbuf != 0) { 484 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_RCVBUF, 485 | &args->rcvbuf, sizeof args->rcvbuf); 486 | if (rc < 0) { 487 | err = errno; 488 | enm_read_select(d, 0); 489 | nn_close(d->fd); 490 | d->fd = -1; 491 | d->sfd = -1; 492 | return enm_errno_tuple(*args->rbuf, err); 493 | } 494 | } 495 | } 496 | return enm_ok(*args->rbuf); 497 | } 498 | 499 | static ErlDrvSSizeT 500 | enm_control(ErlDrvData drv_data, unsigned int command, 501 | char* buf, ErlDrvSizeT len, char** rbuf, ErlDrvSizeT rlen) 502 | { 503 | EnmData* d = (EnmData*)drv_data; 504 | ErlDrvSSizeT result; 505 | ErlDrvSizeT qsize; 506 | EnmRecv *cur, *prev; 507 | EnmArgs args; 508 | int rc, err, index, how, vsn; 509 | void* bf; 510 | char* outbuf; 511 | ei_x_buff xb; 512 | erlang_ref ref; 513 | ErlDrvBinary* bin; 514 | 515 | memset(&args, 0, sizeof args); 516 | args.buf = buf; 517 | args.len = len; 518 | args.rbuf = rbuf; 519 | args.rlen = rlen; 520 | 521 | switch (command) { 522 | case ENM_REQ: 523 | case ENM_REP: 524 | case ENM_BUS: 525 | case ENM_PUB: 526 | case ENM_SUB: 527 | case ENM_PUSH: 528 | case ENM_PULL: 529 | case ENM_SVYR: 530 | case ENM_RESP: 531 | case ENM_PAIR: 532 | d->protocol = enm_cmd_to_protocol(command); 533 | if (d->protocol < 0) 534 | return enm_errno_tuple(*rbuf, errno); 535 | return enm_create_socket(d, &args); 536 | break; 537 | 538 | case ENM_CONNECT: 539 | case ENM_BIND: 540 | if (d->fd == -1) 541 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 542 | rc = (command == ENM_CONNECT) ? 543 | nn_connect(d->fd, buf) : 544 | nn_bind(d->fd, buf); 545 | if (rc < 0) { 546 | err = errno; 547 | enm_write_select(d, 0); 548 | enm_read_select(d, 0); 549 | if (err == EBADF) 550 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 551 | else 552 | return enm_errno_tuple(*rbuf, err); 553 | } 554 | index = 0; 555 | ei_encode_version(*rbuf, &index); 556 | ei_encode_tuple_header(*rbuf, &index, 2); 557 | ei_encode_atom(*rbuf, &index, "ok"); 558 | ei_encode_long(*rbuf, &index, rc); 559 | return index; 560 | break; 561 | 562 | case ENM_CLOSE: 563 | enm_write_select(d, 0); 564 | enm_read_select(d, 0); 565 | qsize = driver_sizeq(d->port); 566 | if (qsize > 0) 567 | driver_deq(d->port, qsize); 568 | result = 0; 569 | err = 0; 570 | if (d->fd != -1) { 571 | do { 572 | rc = nn_close(d->fd); 573 | if (rc < 0 ) { 574 | err = errno; 575 | if (err == EBADF) 576 | result = (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 577 | } 578 | } while (err == EINTR); 579 | } 580 | d->fd = d->sfd = d->rfd = -1; 581 | if (result != 0) return result; 582 | break; 583 | 584 | case ENM_SHUTDOWN: 585 | if (d->fd == -1) 586 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 587 | how = GETINT32(buf); 588 | for (;;) { 589 | rc = nn_shutdown(d->fd, how); 590 | if (rc < 0) { 591 | err = errno; 592 | if (err != EINTR) { 593 | enm_write_select(d, 0); 594 | enm_read_select(d, 0); 595 | if (err == EBADF) 596 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 597 | else 598 | return enm_errno_tuple(*rbuf, err); 599 | } 600 | } else 601 | break; 602 | } 603 | break; 604 | 605 | case ENM_TERM: 606 | /* Ideally here we should call nn_term() but it has problems, as 607 | discussed at the github nanomsg repository in issues such as 608 | #854 (https://github.com/nanomsg/nanomsg/issues/854), so this is 609 | a no-op instead. */ 610 | break; 611 | 612 | case ENM_GETOPTS: 613 | return enm_getopts(d, &args); 614 | break; 615 | 616 | case ENM_SETOPTS: 617 | return enm_setopts(d, &args); 618 | break; 619 | 620 | case ENM_RECV: 621 | if (d->fd == -1 || d->protocol == NN_PUSH) 622 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 623 | index = 0; 624 | ei_decode_version(buf, &index, &vsn); 625 | ei_decode_ref(buf, &index, &ref); 626 | xb.index = 0; 627 | /* 628 | * If there are already waiting receivers, just add this recv to 629 | * the queue to preserve recv order. 630 | */ 631 | if (d->waiting_recvs) { 632 | enm_add_waiter(d, &ref); 633 | ei_x_new_with_version(&xb); 634 | ei_x_encode_tuple_header(&xb, 2); 635 | ei_x_encode_ref(&xb, &ref); 636 | ei_x_encode_atom(&xb, "wait"); 637 | enm_read_select(d, 1); 638 | } 639 | while (xb.index == 0) { 640 | rc = nn_recv(d->fd, &bf, NN_MSG, NN_DONTWAIT); 641 | if (rc < 0) { 642 | err = errno; 643 | if (err == EINTR) 644 | continue; 645 | else if (err == EAGAIN) { 646 | enm_add_waiter(d, &ref); 647 | ei_x_new_with_version(&xb); 648 | ei_x_encode_tuple_header(&xb, 2); 649 | ei_x_encode_ref(&xb, &ref); 650 | ei_x_encode_atom(&xb, "wait"); 651 | enm_read_select(d, 1); 652 | } else { 653 | char errstr[64]; 654 | enm_write_select(d, 0); 655 | enm_read_select(d, 0); 656 | ei_x_new_with_version(&xb); 657 | ei_x_encode_tuple_header(&xb, 2); 658 | ei_x_encode_ref(&xb, &ref); 659 | ei_x_encode_tuple_header(&xb, 2); 660 | ei_x_encode_atom(&xb, "error"); 661 | if (enm_errno_str(err, errstr) != ENM_UNKNOWN_ERROR) 662 | ei_x_encode_atom(&xb, errstr); 663 | else 664 | ei_x_encode_long(&xb, err); 665 | } 666 | } else 667 | break; 668 | } 669 | bin = 0; 670 | if (xb.index == 0) { 671 | /* 672 | * We assume we need 40 bytes at the front of the encoded term 673 | * buffer for the version, tuple header, and ref. If that plus 674 | * the received data length is greater than rlen, it won't fit 675 | * into *rbuf, so we encode directly into a binary instead. 676 | */ 677 | if (40+rc > rlen) { 678 | bin = driver_alloc_binary(40+rc); 679 | *rbuf = (char*)bin; 680 | outbuf = bin->orig_bytes; 681 | } else 682 | outbuf = *rbuf; 683 | index = 0; 684 | ei_encode_version(outbuf, &index); 685 | ei_encode_tuple_header(outbuf, &index, 2); 686 | ei_encode_ref(outbuf, &index, &ref); 687 | if (d->b.listmode) 688 | ei_encode_string_len(outbuf, &index, bf, rc); 689 | else 690 | ei_encode_binary(outbuf, &index, bf, rc); 691 | nn_freemsg(bf); 692 | if (*rbuf == (char*)bin) 693 | bin->orig_size = index; 694 | rlen = index; 695 | } else { 696 | if (xb.index <= rlen) 697 | outbuf = *rbuf; 698 | else { 699 | bin = driver_alloc_binary(xb.index); 700 | *rbuf = (char*)bin; 701 | outbuf = bin->orig_bytes; 702 | } 703 | memcpy(outbuf, xb.buff, xb.index); 704 | ei_x_free(&xb); 705 | rlen = xb.index; 706 | } 707 | return rlen; 708 | break; 709 | 710 | case ENM_CANCEL_RECV: 711 | index = 0; 712 | ei_decode_version(buf, &index, &vsn); 713 | ei_decode_ref(buf, &index, &ref); 714 | cur = d->waiting_recvs; 715 | prev = 0; 716 | while (cur) { 717 | if (ENM_REFS_EQUAL(cur->ref, ref)) { 718 | if (prev != 0) 719 | prev->next = cur->next; 720 | else 721 | d->waiting_recvs = cur->next; 722 | driver_demonitor_process(d->port, &cur->monitor); 723 | driver_free(cur); 724 | break; 725 | } 726 | prev = cur; 727 | cur = cur->next; 728 | } 729 | if (!d->b.active) 730 | enm_read_select(d, 0); 731 | break; 732 | 733 | default: 734 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 735 | } 736 | return enm_ok(*rbuf); 737 | } 738 | 739 | static void 740 | enm_ready_input(ErlDrvData drv_data, ErlDrvEvent event) 741 | { 742 | EnmData* d = enm_sockets[(long)event]; 743 | ErlDrvTermData port = driver_mk_port(d->port); 744 | void* buf; 745 | char pktname[64]; 746 | int rc, err; 747 | 748 | rc = nn_recv(d->fd, &buf, NN_MSG, NN_DONTWAIT); 749 | if (rc < 0) { 750 | err = errno; 751 | if (err == EAGAIN) 752 | return; 753 | strcpy(pktname, enm_protocol_name(d->protocol)); 754 | if (d->protocol == NN_SURVEYOR && err == EFSM) { 755 | /* 756 | * TODO: nanomsg documentation for nn_survey says that when the 757 | * surveyor deadline expires, recv returns ETIMEDOUT, but that 758 | * doesn't seem to be the case. Instead, we seem to get 759 | * EFSM. The nanomsg 0.4-beta survey.c test file also checks 760 | * for EFSM when the deadline hits. Unclear whether the doc or 761 | * the code is correct. 762 | */ 763 | strcat(pktname, "_deadline"); 764 | { 765 | ErlDrvTermData term[] = { 766 | ERL_DRV_ATOM, driver_mk_atom(pktname), 767 | ERL_DRV_PORT, port, 768 | ERL_DRV_TUPLE, 2, 769 | }; 770 | erl_drv_output_term(port, term, sizeof term/sizeof *term); 771 | } 772 | d->b.active = ENM_FALSE; 773 | enm_read_select(d, 0); 774 | } else { 775 | strcat(pktname, "_error"); 776 | { 777 | ErlDrvTermData term[] = { 778 | ERL_DRV_ATOM, driver_mk_atom(pktname), 779 | ERL_DRV_PORT, port, 780 | ERL_DRV_ATOM, enm_errno_atom(err), 781 | ERL_DRV_TUPLE, 3, 782 | }; 783 | erl_drv_output_term(port, term, sizeof term/sizeof *term); 784 | } 785 | } 786 | if (err == ETERM) { 787 | enm_read_select(d, 0); 788 | enm_write_select(d, 0); 789 | nn_close(d->fd); 790 | d->fd = -1; 791 | } 792 | } else { 793 | if (d->waiting_recvs != 0) { 794 | EnmRecv* rcv = d->waiting_recvs; 795 | int index = 0; 796 | char refbuf[64]; 797 | ei_encode_version(refbuf, &index); 798 | ei_encode_ref(refbuf, &index, &rcv->ref); 799 | { 800 | ErlDrvTermData t[] = { 801 | ERL_DRV_EXT2TERM, (ErlDrvTermData)refbuf, index+1, 802 | d->b.listmode ? ERL_DRV_STRING : ERL_DRV_BUF2BINARY, 803 | (ErlDrvTermData)buf, rc, 804 | ERL_DRV_TUPLE, 2, 805 | }; 806 | erl_drv_send_term(port, rcv->rcvr, t, sizeof t/sizeof *t); 807 | } 808 | driver_demonitor_process(d->port, &rcv->monitor); 809 | d->waiting_recvs = rcv->next; 810 | driver_free(rcv); 811 | if (!d->b.active && d->waiting_recvs == 0) 812 | enm_read_select(d, 0); 813 | } else { 814 | ErlDrvTermData term[] = { 815 | ERL_DRV_ATOM, enm_protocol_atom(d->protocol), 816 | ERL_DRV_PORT, port, 817 | d->b.listmode ? ERL_DRV_STRING : ERL_DRV_BUF2BINARY, 818 | (ErlDrvTermData)buf, rc, 819 | ERL_DRV_TUPLE, 3, 820 | }; 821 | erl_drv_output_term(port, term, sizeof term/sizeof *term); 822 | if (d->b.active == ENM_N && --d->n_count == 0) { 823 | strcpy(pktname, enm_protocol_name(d->protocol)); 824 | strcat(pktname, "_passive"); 825 | { 826 | ErlDrvTermData t[] = { 827 | ERL_DRV_ATOM, driver_mk_atom(pktname), 828 | ERL_DRV_PORT, port, 829 | ERL_DRV_TUPLE, 2, 830 | }; 831 | erl_drv_output_term(port, t, sizeof t/sizeof *t); 832 | } 833 | d->b.active = ENM_FALSE; 834 | enm_read_select(d, 0); 835 | } else if (d->b.active == ENM_ONCE) { 836 | d->b.active = ENM_FALSE; 837 | enm_read_select(d, 0); 838 | } 839 | } 840 | nn_freemsg(buf); 841 | } 842 | } 843 | 844 | static void 845 | enm_ready_output(ErlDrvData drv_data, ErlDrvEvent event) 846 | { 847 | EnmData* d = enm_sockets[(long)event]; 848 | struct nn_msghdr msghdr; 849 | ErlIOVec ev; 850 | ErlDrvSizeT total; 851 | int rc, err; 852 | 853 | d->b.writable = 1; 854 | total = driver_peekqv(d->port, &ev); 855 | if (total == 0) 856 | return; 857 | memset(&msghdr, 0, sizeof msghdr); 858 | msghdr.msg_iov = (struct nn_iovec*)ev.iov; 859 | msghdr.msg_iovlen = ev.vsize; 860 | msghdr.msg_control = 0; 861 | rc = enm_do_send(d, &msghdr, &err); 862 | if (rc < 0 && err == EAGAIN) { 863 | /* enm_ready_output (this function) is called when the VM's 864 | select/poll/etc. indicates the socket has become writable, but 865 | if we get here, it means we tried to write but it failed with 866 | EAGAIN, indicating that the socket isn't writable after all. So 867 | we assume things are broken in this case, and signal eof. */ 868 | enm_write_select(d, 0); 869 | enm_read_select(d, 0); 870 | nn_close(d->fd); 871 | d->fd = d->sfd = d->rfd = -1; 872 | driver_failure_eof(d->port); 873 | return; 874 | } 875 | if (rc > 0) 876 | driver_deq(d->port, rc); 877 | if (rc == total && d->b.writable) { 878 | if (d->b.busy) { 879 | d->b.busy = 0; 880 | set_busy_port(d->port, d->b.busy); 881 | } 882 | enm_write_select(d, 0); 883 | } 884 | } 885 | 886 | static void 887 | enm_process_exit(ErlDrvData drv_data, ErlDrvMonitor* monitor) 888 | { 889 | EnmData* d = (EnmData*)drv_data; 890 | EnmRecv* cur = d->waiting_recvs; 891 | EnmRecv* prev = 0; 892 | 893 | while (cur) { 894 | if (driver_compare_monitors(monitor, &cur->monitor) == 0) { 895 | if (prev != 0) 896 | prev->next = cur->next; 897 | else 898 | d->waiting_recvs = cur->next; 899 | driver_free(cur); 900 | break; 901 | } 902 | prev = cur; 903 | cur = cur->next; 904 | } 905 | } 906 | 907 | static void 908 | enm_stop_select(ErlDrvEvent event, void* arg) 909 | { 910 | /* do nothing */ 911 | } 912 | 913 | static ErlDrvEntry drv_entry = { 914 | enm_init, 915 | enm_start, 916 | enm_stop, 917 | 0, 918 | enm_ready_input, 919 | enm_ready_output, 920 | "enm_drv", 921 | enm_finish, 922 | 0, 923 | enm_control, 924 | 0, 925 | enm_outputv, 926 | 0, 927 | 0, 928 | 0, 929 | 0, 930 | ERL_DRV_EXTENDED_MARKER, 931 | ERL_DRV_EXTENDED_MAJOR_VERSION, 932 | ERL_DRV_EXTENDED_MINOR_VERSION, 933 | ERL_DRV_FLAG_USE_PORT_LOCKING, 934 | 0, 935 | enm_process_exit, 936 | enm_stop_select, 937 | }; 938 | 939 | DRIVER_INIT(enm_drv) 940 | { 941 | return &drv_entry; 942 | } 943 | -------------------------------------------------------------------------------- /c_src/enm_opts.c: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------- 2 | // 3 | // enm_opts.c: option handling for nanomsg Erlang language binding 4 | // 5 | // Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | // 7 | // This file is provided to you under the Apache License, 8 | // Version 2.0 (the "License"); you may not use this file 9 | // except in compliance with the License. You may obtain 10 | // a copy of the License at 11 | // 12 | // http://www.apache.org/licenses/LICENSE-2.0 13 | // 14 | // Unless required by applicable law or agreed to in writing, 15 | // software distributed under the License is distributed on an 16 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | // KIND, either express or implied. See the License for the 18 | // specific language governing permissions and limitations 19 | // under the License. 20 | // 21 | // ------------------------------------------------------------------- 22 | 23 | #include 24 | #include "enm.h" 25 | #include 26 | 27 | 28 | static const char* typeopt = "type"; 29 | static const char* activeopt = "active"; 30 | static const char* rawopt = "raw"; 31 | static const char* modeopt = "mode"; 32 | static const char* deadlineopt = "deadline"; 33 | static const char* subscribeopt = "subscribe"; 34 | static const char* unsubscribeopt = "unsubscribe"; 35 | static const char* resend_ivl = "resend_ivl"; 36 | static const char* sndbuf = "sndbuf"; 37 | static const char* rcvbuf = "rcvbuf"; 38 | static const char* nodelay = "nodelay"; 39 | static const char* ipv4only = "ipv4only"; 40 | static const char* reconnect_ivl = "reconnect_ivl"; 41 | static const char* reconnect_ivl_max = "reconnect_ivl_max"; 42 | 43 | static const char* 44 | enm_optname(int opt) 45 | { 46 | switch (opt) { 47 | case ENM_TYPE: 48 | return typeopt; 49 | case ENM_ACTIVE: 50 | return activeopt; 51 | case ENM_RAW: 52 | return rawopt; 53 | case ENM_BINARY: 54 | return modeopt; 55 | case ENM_DEADLINE: 56 | return deadlineopt; 57 | case ENM_SUBSCRIBE: 58 | return subscribeopt; 59 | case ENM_UNSUBSCRIBE: 60 | return unsubscribeopt; 61 | case ENM_RESEND_IVL: 62 | return resend_ivl; 63 | case ENM_SNDBUF: 64 | return sndbuf; 65 | case ENM_RCVBUF: 66 | return rcvbuf; 67 | case ENM_NODELAY: 68 | return nodelay; 69 | case ENM_IPV4ONLY: 70 | return ipv4only; 71 | case ENM_RECONNECT_IVL: 72 | return reconnect_ivl; 73 | case ENM_RECONNECT_IVL_MAX: 74 | return reconnect_ivl_max; 75 | default: 76 | break; 77 | } 78 | return 0; 79 | } 80 | 81 | ErlDrvSSizeT 82 | enm_getopts(EnmData* d, EnmArgs* args) 83 | { 84 | ei_x_buff xb; 85 | int err, optval, rc; 86 | size_t optlen = sizeof optval; 87 | const char* optname; 88 | 89 | if (d->fd == -1) 90 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 91 | ei_x_new_with_version(&xb); 92 | ei_x_encode_tuple_header(&xb, 2); 93 | ei_x_encode_atom(&xb, "ok"); 94 | ei_x_encode_list_header(&xb, args->len); 95 | for (; args->index < args->len; args->index++, args->buf++) { 96 | if ((optname = enm_optname(*args->buf)) == 0) 97 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 98 | ei_x_encode_tuple_header(&xb, 2); 99 | ei_x_encode_atom(&xb, optname); 100 | switch (*args->buf) { 101 | case ENM_TYPE: 102 | ei_x_encode_atom(&xb, enm_protocol_name(d->protocol)); 103 | break; 104 | case ENM_ACTIVE: 105 | switch (d->b.active) { 106 | case ENM_TRUE: 107 | ei_x_encode_atom(&xb, "true"); 108 | break; 109 | case ENM_FALSE: 110 | ei_x_encode_atom(&xb, "false"); 111 | break; 112 | case ENM_ONCE: 113 | ei_x_encode_atom(&xb, "once"); 114 | break; 115 | case ENM_N: 116 | ei_x_encode_long(&xb, d->n_count); 117 | break; 118 | } 119 | break; 120 | case ENM_RAW: 121 | ei_x_encode_boolean(&xb, d->b.raw); 122 | break; 123 | case ENM_BINARY: 124 | ei_x_encode_atom(&xb, d->b.listmode ? "list" : "binary"); 125 | break; 126 | case ENM_DEADLINE: 127 | if (d->protocol != NN_SURVEYOR) { 128 | ei_x_free(&xb); 129 | return enm_errno_tuple(*args->rbuf, EINVAL); 130 | } 131 | optlen = sizeof optval; 132 | rc = nn_getsockopt(d->fd, NN_SURVEYOR, NN_SURVEYOR_DEADLINE, 133 | &optval, &optlen); 134 | if (rc < 0) { 135 | err = errno; 136 | ei_x_free(&xb); 137 | return enm_errno_tuple(*args->rbuf, err); 138 | } 139 | ei_x_encode_long(&xb, optval); 140 | break; 141 | case ENM_RESEND_IVL: 142 | if (d->protocol != NN_REQ) { 143 | ei_x_free(&xb); 144 | return enm_errno_tuple(*args->rbuf, EINVAL); 145 | } 146 | optlen = sizeof args->resend_ivl; 147 | rc = nn_getsockopt(d->fd, NN_REQ, NN_REQ_RESEND_IVL, 148 | &args->resend_ivl, &optlen); 149 | if (rc < 0) { 150 | err = errno; 151 | ei_x_free(&xb); 152 | return enm_errno_tuple(*args->rbuf, err); 153 | } 154 | ei_x_encode_ulong(&xb, args->resend_ivl); 155 | break; 156 | case ENM_SNDBUF: 157 | if (d->protocol == NN_PULL || d->protocol == NN_SUB) { 158 | ei_x_free(&xb); 159 | return enm_errno_tuple(*args->rbuf, EINVAL); 160 | } 161 | optlen = sizeof args->sndbuf; 162 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_SNDBUF, 163 | &args->sndbuf, &optlen); 164 | if (rc < 0) { 165 | err = errno; 166 | ei_x_free(&xb); 167 | return enm_errno_tuple(*args->rbuf, err); 168 | } 169 | ei_x_encode_ulong(&xb, args->sndbuf); 170 | break; 171 | case ENM_RCVBUF: 172 | if (d->protocol == NN_PUSH || d->protocol == NN_PUB) { 173 | ei_x_free(&xb); 174 | return enm_errno_tuple(*args->rbuf, EINVAL); 175 | } 176 | optlen = sizeof args->rcvbuf; 177 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_RCVBUF, 178 | &args->rcvbuf, &optlen); 179 | if (rc < 0) { 180 | err = errno; 181 | ei_x_free(&xb); 182 | return enm_errno_tuple(*args->rbuf, err); 183 | } 184 | ei_x_encode_ulong(&xb, args->rcvbuf); 185 | break; 186 | case ENM_NODELAY: 187 | optlen = sizeof optval; 188 | rc = nn_getsockopt(d->fd, NN_TCP, NN_TCP_NODELAY, 189 | &optval, &optlen); 190 | if (rc < 0) { 191 | err = errno; 192 | ei_x_free(&xb); 193 | return enm_errno_tuple(*args->rbuf, err); 194 | } 195 | ei_x_encode_boolean(&xb, optval); 196 | break; 197 | case ENM_IPV4ONLY: 198 | optlen = sizeof optval; 199 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_IPV4ONLY, 200 | &optval, &optlen); 201 | if (rc < 0) { 202 | err = errno; 203 | ei_x_free(&xb); 204 | return enm_errno_tuple(*args->rbuf, err); 205 | } 206 | ei_x_encode_boolean(&xb, optval); 207 | break; 208 | case ENM_RECONNECT_IVL: 209 | optlen = sizeof args->reconnect_ivl; 210 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_RECONNECT_IVL, 211 | &args->reconnect_ivl, &optlen); 212 | if (rc < 0) { 213 | err = errno; 214 | ei_x_free(&xb); 215 | return enm_errno_tuple(*args->rbuf, err); 216 | } 217 | ei_x_encode_ulong(&xb, args->reconnect_ivl); 218 | break; 219 | case ENM_RECONNECT_IVL_MAX: 220 | optlen = sizeof args->reconnect_ivl_max; 221 | rc = nn_getsockopt(d->fd, NN_SOL_SOCKET, NN_RECONNECT_IVL_MAX, 222 | &args->reconnect_ivl_max, &optlen); 223 | if (rc < 0) { 224 | err = errno; 225 | ei_x_free(&xb); 226 | return enm_errno_tuple(*args->rbuf, err); 227 | } 228 | ei_x_encode_ulong(&xb, args->reconnect_ivl_max); 229 | break; 230 | default: 231 | ei_x_free(&xb); 232 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 233 | } 234 | } 235 | ei_x_encode_empty_list(&xb); 236 | xb.index++; 237 | if (xb.index <= args->rlen) { 238 | memcpy(*args->rbuf, xb.buff, xb.index); 239 | } else { 240 | ErlDrvBinary* bin = driver_alloc_binary(xb.index); 241 | memcpy(bin->orig_bytes, xb.buff, xb.index); 242 | *args->rbuf = (char*)bin; 243 | } 244 | args->rlen = xb.index; 245 | ei_x_free(&xb); 246 | return args->rlen; 247 | } 248 | 249 | ErlDrvSSizeT 250 | enm_setopts_priv(EnmData* d, int opt, EnmArgs* args) 251 | { 252 | int old_active, rc, optval; 253 | size_t optlen; 254 | 255 | switch (opt) { 256 | case ENM_ACTIVE: 257 | old_active = d->b.active; 258 | switch (*args->buf) { 259 | case ENM_TRUE: 260 | case ENM_FALSE: 261 | case ENM_ONCE: 262 | d->b.active = *args->buf++; 263 | args->index++; 264 | break; 265 | case ENM_N: 266 | d->b.active = *args->buf++; 267 | d->n_count += (short)GETINT16(args->buf); 268 | args->buf += 2; 269 | args->index += 3; 270 | break; 271 | default: 272 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 273 | } 274 | if (d->fd != -1 && d->b.active != old_active) { 275 | if (old_active == ENM_N && d->b.active != ENM_N) 276 | d->n_count = 0; 277 | if (old_active && !d->b.active && d->rfd != -1) 278 | enm_read_select(d, 0); 279 | else if (!old_active && d->b.active && d->fd != -1) { 280 | rc = enm_read_select(d, 1); 281 | if (rc < 0) 282 | return enm_errno_tuple(*args->rbuf, errno); 283 | } 284 | } 285 | if (d->b.active == ENM_N && d->n_count <= 0) { 286 | ErlDrvTermData port = driver_mk_port(d->port); 287 | char pktname[64]; 288 | enm_read_select(d, 0); 289 | d->b.active = ENM_FALSE; 290 | d->n_count = 0; 291 | strcpy(pktname, enm_protocol_name(d->protocol)); 292 | strcat(pktname, "_passive"); 293 | { 294 | ErlDrvTermData t[] = { 295 | ERL_DRV_ATOM, driver_mk_atom(pktname), 296 | ERL_DRV_PORT, port, 297 | ERL_DRV_TUPLE, 2, 298 | }; 299 | erl_drv_output_term(port, t, sizeof t/sizeof *t); 300 | } 301 | } 302 | break; 303 | case ENM_RAW: 304 | d->b.raw = *args->buf++; 305 | args->index++; 306 | break; 307 | case ENM_BINARY: 308 | d->b.listmode = (*args->buf++ == ENM_FALSE); 309 | args->index++; 310 | break; 311 | case ENM_DEADLINE: 312 | if (d->protocol != NN_SURVEYOR) 313 | return enm_errno_tuple(*args->rbuf, EINVAL); 314 | args->deadline = (int)GETINT32(args->buf); 315 | if (args->deadline <= 0) 316 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 317 | if (d->fd != -1) { 318 | rc = nn_setsockopt(d->fd, NN_SURVEYOR, NN_SURVEYOR_DEADLINE, 319 | &args->deadline, sizeof args->deadline); 320 | if (rc < 0) 321 | return enm_errno_tuple(*args->rbuf, errno); 322 | } 323 | args->buf += 4; 324 | args->index += 4; 325 | break; 326 | case ENM_SUBSCRIBE: 327 | if (d->protocol != NN_SUB) 328 | return enm_errno_tuple(*args->rbuf, EINVAL); 329 | args->b.topic_seen = 1; 330 | strcpy(args->topic, args->buf); 331 | optlen = strlen(args->topic); 332 | if (d->fd != -1) { 333 | rc = nn_setsockopt(d->fd, NN_SUB, NN_SUB_SUBSCRIBE, 334 | args->topic, optlen); 335 | if (rc < 0) 336 | return enm_errno_tuple(*args->rbuf, errno); 337 | } 338 | args->buf += optlen+1; 339 | args->index += optlen+1; 340 | break; 341 | case ENM_UNSUBSCRIBE: 342 | if (d->protocol != NN_SUB) 343 | return enm_errno_tuple(*args->rbuf, EINVAL); 344 | strcpy(args->topic, args->buf); 345 | optlen = strlen(args->topic); 346 | if (d->fd != -1) { 347 | rc = nn_setsockopt(d->fd, NN_SUB, NN_SUB_UNSUBSCRIBE, 348 | args->topic, optlen); 349 | if (rc < 0) 350 | return enm_errno_tuple(*args->rbuf, errno); 351 | } 352 | args->buf += optlen+1; 353 | args->index += optlen+1; 354 | break; 355 | case ENM_RESEND_IVL: 356 | if (d->protocol != NN_REQ) 357 | return enm_errno_tuple(*args->rbuf, EINVAL); 358 | args->resend_ivl = (int)GETINT32(args->buf); 359 | if (args->resend_ivl <= 0) 360 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 361 | if (d->fd != -1) { 362 | rc = nn_setsockopt(d->fd, NN_REQ, NN_REQ_RESEND_IVL, 363 | &args->resend_ivl, sizeof args->resend_ivl); 364 | if (rc < 0) 365 | return enm_errno_tuple(*args->rbuf, errno); 366 | } 367 | args->buf += 4; 368 | args->index += 4; 369 | break; 370 | case ENM_SNDBUF: 371 | if (d->protocol == NN_PULL || d->protocol == NN_SUB) 372 | return enm_errno_tuple(*args->rbuf, EINVAL); 373 | args->sndbuf = (int)GETINT32(args->buf); 374 | if (args->sndbuf <= 0) 375 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 376 | if (d->fd != -1) { 377 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_SNDBUF, 378 | &args->sndbuf, sizeof args->sndbuf); 379 | if (rc < 0) 380 | return enm_errno_tuple(*args->rbuf, errno); 381 | } 382 | args->buf += 4; 383 | args->index += 4; 384 | break; 385 | case ENM_RCVBUF: 386 | if (d->protocol == NN_PUSH || d->protocol == NN_PUB) 387 | return enm_errno_tuple(*args->rbuf, EINVAL); 388 | args->rcvbuf = (int)GETINT32(args->buf); 389 | if (args->rcvbuf <= 0) 390 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 391 | if (d->fd != -1) { 392 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_RCVBUF, 393 | &args->rcvbuf, sizeof args->rcvbuf); 394 | if (rc < 0) 395 | return enm_errno_tuple(*args->rbuf, errno); 396 | } 397 | args->buf += 4; 398 | args->index += 4; 399 | break; 400 | case ENM_NODELAY: 401 | optval = *args->buf; 402 | if (d->fd != -1) { 403 | rc = nn_setsockopt(d->fd, NN_TCP, NN_TCP_NODELAY, 404 | &optval, sizeof optval); 405 | if (rc < 0) 406 | return enm_errno_tuple(*args->rbuf, errno); 407 | } 408 | args->buf++; 409 | args->index++; 410 | break; 411 | case ENM_IPV4ONLY: 412 | optval = *args->buf; 413 | if (d->fd != -1) { 414 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_IPV4ONLY, 415 | &optval, sizeof optval); 416 | if (rc < 0) 417 | return enm_errno_tuple(*args->rbuf, errno); 418 | } 419 | args->buf++; 420 | args->index++; 421 | break; 422 | case ENM_RECONNECT_IVL: 423 | args->reconnect_ivl = (int)GETINT32(args->buf); 424 | if (args->reconnect_ivl <= 0) 425 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 426 | if (d->fd != -1) { 427 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_RECONNECT_IVL, 428 | &args->reconnect_ivl, 429 | sizeof args->reconnect_ivl); 430 | if (rc < 0) 431 | return enm_errno_tuple(*args->rbuf, errno); 432 | } 433 | args->buf += 4; 434 | args->index += 4; 435 | break; 436 | case ENM_RECONNECT_IVL_MAX: 437 | args->reconnect_ivl_max = (int)GETINT32(args->buf); 438 | if (args->reconnect_ivl_max < 0) 439 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 440 | if (d->fd != -1) { 441 | rc = nn_setsockopt(d->fd, NN_SOL_SOCKET, NN_RECONNECT_IVL_MAX, 442 | &args->reconnect_ivl_max, 443 | sizeof args->reconnect_ivl_max); 444 | if (rc < 0) 445 | return enm_errno_tuple(*args->rbuf, errno); 446 | } 447 | args->buf += 4; 448 | args->index += 4; 449 | break; 450 | default: 451 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 452 | } 453 | return 0; 454 | } 455 | 456 | ErlDrvSSizeT 457 | enm_setopts(EnmData* d, EnmArgs* args) 458 | { 459 | ErlDrvSSizeT res; 460 | int opt; 461 | 462 | if (d->fd == -1) 463 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 464 | while (args->index < args->len) { 465 | opt = *args->buf++; 466 | args->index++; 467 | switch (opt) { 468 | case ENM_ACTIVE: 469 | case ENM_BINARY: 470 | case ENM_DEADLINE: 471 | case ENM_SUBSCRIBE: 472 | case ENM_UNSUBSCRIBE: 473 | case ENM_RESEND_IVL: 474 | case ENM_SNDBUF: 475 | case ENM_RCVBUF: 476 | case ENM_NODELAY: 477 | case ENM_IPV4ONLY: 478 | case ENM_RECONNECT_IVL: 479 | case ENM_RECONNECT_IVL_MAX: 480 | if ((res = enm_setopts_priv(d, opt, args)) != 0) 481 | return res; 482 | break; 483 | default: 484 | return (ErlDrvSSizeT)ERL_DRV_ERROR_BADARG; 485 | } 486 | } 487 | return enm_ok(*args->rbuf); 488 | } 489 | -------------------------------------------------------------------------------- /c_src/enm_utils.c: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------- 2 | // 3 | // enm_utils.c: misc utilities for nanomsg Erlang language binding 4 | // 5 | // Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | // 7 | // This file is provided to you under the Apache License, 8 | // Version 2.0 (the "License"); you may not use this file 9 | // except in compliance with the License. You may obtain 10 | // a copy of the License at 11 | // 12 | // http://www.apache.org/licenses/LICENSE-2.0 13 | // 14 | // Unless required by applicable law or agreed to in writing, 15 | // software distributed under the License is distributed on an 16 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | // KIND, either express or implied. See the License for the 18 | // specific language governing permissions and limitations 19 | // under the License. 20 | // 21 | // ------------------------------------------------------------------- 22 | 23 | #include 24 | #include "enm.h" 25 | #include "ei.h" 26 | 27 | ErlDrvSSizeT 28 | enm_ok(char* buf) 29 | { 30 | int index = 0; 31 | ei_encode_version(buf, &index); 32 | ei_encode_atom(buf, &index, "ok"); 33 | return index; 34 | } 35 | 36 | EnmErrorType 37 | enm_errno_str(int err, char* errstr) 38 | { 39 | EnmErrorType errtype = ENM_UNKNOWN_ERROR; 40 | errstr[0] = '\0'; 41 | strcpy(errstr, erl_errno_id(err)); 42 | if (strcmp(errstr, "unknown") != 0) 43 | return ENM_POSIX_ERROR; 44 | else { 45 | switch (err) { 46 | case EFSM: 47 | strcpy(errstr, "efsm"); 48 | errtype = ENM_NANOMSG_ERROR; 49 | break; 50 | case ETERM: 51 | strcpy(errstr, "eterm"); 52 | errtype = ENM_NANOMSG_ERROR; 53 | break; 54 | default: 55 | /* default in case nanomsg adds new errno values 56 | * not accounted for here */ 57 | break; 58 | } 59 | } 60 | return errtype; 61 | } 62 | 63 | ErlDrvSSizeT 64 | enm_errno_tuple(char* buf, int err) 65 | { 66 | int index = 0; 67 | char errstr[64]; 68 | 69 | ei_encode_version(buf, &index); 70 | ei_encode_tuple_header(buf, &index, 2); 71 | ei_encode_atom(buf, &index, "error"); 72 | enm_errno_str(err, errstr); 73 | ei_encode_atom(buf, &index, errstr); 74 | return ++index; 75 | } 76 | 77 | ErlDrvTermData 78 | enm_errno_atom(int err) 79 | { 80 | char errstr[64]; 81 | enm_errno_str(err, errstr); 82 | return driver_mk_atom(errstr); 83 | } 84 | 85 | static const char* enm_pair = "nnpair"; 86 | static const char* enm_req = "nnreq"; 87 | static const char* enm_rep = "nnrep"; 88 | static const char* enm_bus = "nnbus"; 89 | static const char* enm_pub = "nnpub"; 90 | static const char* enm_sub = "nnsub"; 91 | static const char* enm_push = "nnpush"; 92 | static const char* enm_pull = "nnpull"; 93 | static const char* enm_svyr = "nnsurveyor"; 94 | static const char* enm_resp = "nnrespondent"; 95 | 96 | const char* 97 | enm_protocol_name(int protocol) 98 | { 99 | const char* s; 100 | 101 | switch (protocol) { 102 | case NN_REQ: 103 | case ENM_REQ: 104 | s = enm_req; 105 | break; 106 | case NN_REP: 107 | case ENM_REP: 108 | s = enm_rep; 109 | break; 110 | case NN_BUS: 111 | case ENM_BUS: 112 | s = enm_bus; 113 | break; 114 | case NN_PUB: 115 | case ENM_PUB: 116 | s = enm_pub; 117 | break; 118 | case NN_SUB: 119 | case ENM_SUB: 120 | s = enm_sub; 121 | break; 122 | case NN_PUSH: 123 | case ENM_PUSH: 124 | s = enm_push; 125 | break; 126 | case NN_PULL: 127 | case ENM_PULL: 128 | s = enm_pull; 129 | break; 130 | case NN_SURVEYOR: 131 | case ENM_SVYR: 132 | s = enm_svyr; 133 | break; 134 | case NN_RESPONDENT: 135 | case ENM_RESP: 136 | s = enm_resp; 137 | break; 138 | case NN_PAIR: 139 | case ENM_PAIR: 140 | s = enm_pair; 141 | break; 142 | } 143 | return s; 144 | } 145 | -------------------------------------------------------------------------------- /c_src/nanomsg-1.1.2.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/basho/enm/0c8a047ebda77e35fc9c514585e7a523a3fc8cfa/c_src/nanomsg-1.1.2.tar.gz -------------------------------------------------------------------------------- /examples/bus.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% bus: example of enm bus support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(bus). 23 | -export([start/0]). 24 | 25 | -define(COUNT, 4). 26 | 27 | start() -> 28 | enm:start_link(), 29 | UrlBase = "inproc://bus", 30 | Buses = connect_buses(UrlBase), 31 | Pids = send_and_receive(Buses, self()), 32 | wait_for_pids(Pids), 33 | enm:stop(). 34 | 35 | connect_buses(UrlBase) -> 36 | connect_buses(UrlBase, lists:seq(1,?COUNT), []). 37 | connect_buses(UrlBase, [1=Node|Nodes], Buses) -> 38 | Url = make_url(UrlBase, Node), 39 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 40 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 2)), 41 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 3)), 42 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 43 | connect_buses(UrlBase, [?COUNT=Node|Nodes], Buses) -> 44 | Url = make_url(UrlBase, Node), 45 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 46 | {ok,_} = enm:connect(Bus, make_url(UrlBase, 1)), 47 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 48 | connect_buses(UrlBase, [Node|Nodes], Buses) -> 49 | Url = make_url(UrlBase, Node), 50 | {ok,Bus} = enm:bus([{bind,Url},{active,false}]), 51 | Urls = [make_url(UrlBase,N) || N <- lists:seq(Node+1,?COUNT)], 52 | [{ok,_} = enm:connect(Bus,U) || U <- Urls], 53 | connect_buses(UrlBase, Nodes, [{Bus,Node}|Buses]); 54 | connect_buses(_, [], Buses) -> 55 | Buses. 56 | 57 | send_and_receive(Buses, Parent) -> 58 | send_and_receive(Buses, Parent, []). 59 | send_and_receive([{Bus,Id}|Buses], Parent, Acc) -> 60 | Pid = spawn_link(fun() -> bus(Bus, Id, Parent) end), 61 | send_and_receive(Buses, Parent, [Pid|Acc]); 62 | send_and_receive([], _, Acc) -> 63 | Acc. 64 | 65 | bus(Bus, Id, Parent) -> 66 | Name = "node"++integer_to_list(Id), 67 | io:format("node ~w sending \"~s\"~n", [Id, Name]), 68 | ok = enm:send(Bus, Name), 69 | collect(Bus, Id, Parent). 70 | 71 | collect(Bus, Id, Parent) -> 72 | case enm:recv(Bus, 1000) of 73 | {ok,Data} -> 74 | io:format("node ~w received \"~s\"~n", [Id, Data]), 75 | collect(Bus, Id, Parent); 76 | {error,etimedout} -> 77 | Parent ! {done, self(), Bus} 78 | end. 79 | 80 | wait_for_pids([Pid|Pids]) -> 81 | receive 82 | {done,Pid,Bus} -> 83 | enm:close(Bus), 84 | wait_for_pids(Pids) 85 | end; 86 | wait_for_pids([]) -> 87 | ok. 88 | 89 | make_url(Base,N) -> 90 | Base++integer_to_list(N). 91 | -------------------------------------------------------------------------------- /examples/pair.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% pair: example of enm pair support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(pair). 23 | -export([start/0, node/4]). 24 | 25 | start() -> 26 | enm:start_link(), 27 | Self = self(), 28 | Url = "inproc://pair", 29 | spawn(?MODULE, node, [Self, Url, bind, "Node0"]), 30 | spawn(?MODULE, node, [Self, Url, connect, "Node1"]), 31 | collect(["Node0","Node1"]). 32 | 33 | node(Parent, Url, F, Name) -> 34 | {ok,P} = enm:pair([{active,3}]), 35 | {ok,Id} = enm:F(P,Url), 36 | send_recv(P, Name), 37 | enm:shutdown(P, Id), 38 | Parent ! {done,Name}. 39 | 40 | send_recv(Sock, Name) -> 41 | receive 42 | {_,Sock,Buf} -> 43 | io:format("~s received \"~s\"~n", [Name, Buf]) 44 | after 45 | 100 -> 46 | ok 47 | end, 48 | case enm:getopts(Sock, [active]) of 49 | {ok, [{active,false}]} -> 50 | ok; 51 | {error, Error} -> 52 | error(Error); 53 | _ -> 54 | timer:sleep(1000), 55 | io:format("~s sending \"~s\"~n", [Name, Name]), 56 | ok = enm:send(Sock, Name), 57 | send_recv(Sock, Name) 58 | end. 59 | 60 | collect([]) -> 61 | ok; 62 | collect([Name|Names]) -> 63 | receive 64 | {done,Name} -> 65 | collect(Names) 66 | end. 67 | -------------------------------------------------------------------------------- /examples/pipeline.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% pipeline: example of enm pipeline support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(pipeline). 23 | -export([start/0]). 24 | 25 | start() -> 26 | enm:start_link(), 27 | Url = "inproc://pipeline", 28 | {ok,Pull} = enm:pull([{bind,Url},list]), 29 | {ok,Push} = enm:push([{connect,Url},list]), 30 | Send1 = "Hello, World!", 31 | io:format("pushing message \"~s\"~n", [Send1]), 32 | ok = enm:send(Push, Send1), 33 | receive 34 | {nnpull,Pull,Send1} -> 35 | io:format("pulling message \"~s\"~n", [Send1]) 36 | end, 37 | Send2 = "Goodbye.", 38 | io:format("pushing message \"~s\"~n", [Send2]), 39 | ok = enm:send(Push, Send2), 40 | receive 41 | {nnpull,Pull,Send2} -> 42 | io:format("pulling message \"~s\"~n", [Send2]) 43 | end, 44 | enm:close(Push), 45 | enm:close(Pull), 46 | enm:stop(). 47 | -------------------------------------------------------------------------------- /examples/pubsub.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% pubsub: example of enm pub/sub support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(pubsub). 23 | -export([start/0]). 24 | 25 | -define(COUNT, 3). 26 | 27 | start() -> 28 | enm:start_link(), 29 | Url = "inproc://pubsub", 30 | Pub = pub(Url), 31 | collect(subs(Url, self())), 32 | enm:close(Pub), 33 | enm:stop(). 34 | 35 | pub(Url) -> 36 | {ok,Pub} = enm:pub([{bind,Url}]), 37 | spawn_link(fun() -> pub(Pub, ?COUNT) end), 38 | Pub. 39 | pub(_, 0) -> 40 | ok; 41 | pub(Pub, Count) -> 42 | Now = httpd_util:rfc1123_date(), 43 | io:format("publishing date \"~s\"~n", [Now]), 44 | ok = enm:send(Pub, ["DATE: ", Now]), 45 | timer:sleep(1000), 46 | pub(Pub, Count-1). 47 | 48 | subs(Url, Parent) -> 49 | subs(Url, Parent, ?COUNT, []). 50 | subs(_, _, 0, Acc) -> 51 | Acc; 52 | subs(Url, Parent, Count, Acc) -> 53 | {ok, Sub} = enm:sub([{connect,Url},{subscribe,"DATE:"},{active,false}]), 54 | Name = "Subscriber" ++ integer_to_list(Count), 55 | spawn_link(fun() -> sub(Sub, Parent, Name) end), 56 | subs(Url, Parent, Count-1, [Name|Acc]). 57 | sub(Sub, Parent, Name) -> 58 | case enm:recv(Sub, 2000) of 59 | {ok,Data} -> 60 | io:format("~s received \"~s\"~n", [Name, Data]), 61 | sub(Sub, Parent, Name); 62 | {error,etimedout} -> 63 | enm:close(Sub), 64 | Parent ! {done, Name}, 65 | ok 66 | end. 67 | 68 | collect([Sub|Subs]) -> 69 | receive 70 | {done,Sub} -> 71 | collect(Subs) 72 | end; 73 | collect([]) -> 74 | ok. 75 | -------------------------------------------------------------------------------- /examples/request_reply.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% request_reply: example of enm request/reply support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(request_reply). 23 | -export([start/0]). 24 | 25 | start() -> 26 | enm:start_link(), 27 | Url = "inproc://request_reply", 28 | {ok,Rep} = enm:rep([{bind,Url}]), 29 | {ok,Req} = enm:req([{connect,Url}]), 30 | DateReq = <<"DATE">>, 31 | io:format("sending date request~n"), 32 | ok = enm:send(Req, DateReq), 33 | receive 34 | {nnrep,Rep,DateReq} -> 35 | io:format("received date request~n"), 36 | Now = httpd_util:rfc1123_date(), 37 | io:format("sending date ~s~n", [Now]), 38 | ok = enm:send(Rep, Now) 39 | end, 40 | receive 41 | {nnreq,Req,Date} -> 42 | io:format("received date ~s~n", [Date]) 43 | end, 44 | enm:close(Req), 45 | enm:close(Rep), 46 | enm:stop(). 47 | -------------------------------------------------------------------------------- /examples/survey.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% survey: example of enm survey support 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(survey). 23 | -export([start/0]). 24 | 25 | -define(COUNT, 3). 26 | 27 | start() -> 28 | enm:start_link(), 29 | Url = "inproc://survey", 30 | Self = self(), 31 | {ok,Survey} = enm:surveyor([{bind,Url},{deadline,3000}]), 32 | Clients = clients(Url, Self), 33 | ok = enm:send(Survey, httpd_util:rfc1123_date()), 34 | get_responses(Survey), 35 | wait_for_clients(Clients), 36 | enm:close(Survey), 37 | enm:stop(). 38 | 39 | clients(Url, Parent) -> 40 | clients(Url, Parent, ?COUNT, []). 41 | clients(_, _, 0, Acc) -> 42 | Acc; 43 | clients(Url, Parent, Count, Acc) -> 44 | {ok, Respondent} = enm:respondent([{connect,Url},{active,false},list]), 45 | Name = "Respondent" ++ integer_to_list(Count), 46 | Pid = spawn_link(fun() -> client(Respondent, Name, Parent) end), 47 | clients(Url, Parent, Count-1, [Pid|Acc]). 48 | 49 | client(Respondent, Name, Parent) -> 50 | {ok,Msg} = enm:recv(Respondent, 5000), 51 | Date = httpd_util:convert_request_date(Msg), 52 | ok = enm:send(Respondent, term_to_binary(Date)), 53 | io:format("~s got \"~s\"~n", [Name, Msg]), 54 | Parent ! {done, self(), Respondent}. 55 | 56 | get_responses(Survey) -> 57 | get_responses(Survey, ?COUNT+1). 58 | get_responses(_, 0) -> 59 | ok; 60 | get_responses(Survey, Count) -> 61 | receive 62 | {nnsurveyor,Survey,BinResp} -> 63 | Response = binary_to_term(BinResp), 64 | io:format("received survey response ~p~n", [Response]); 65 | {nnsurveyor_deadline,Survey} -> 66 | io:format("survey has expired~n") 67 | end, 68 | get_responses(Survey, Count-1). 69 | 70 | wait_for_clients([Client|Clients]) -> 71 | receive 72 | {done,Client,Respondent} -> 73 | enm:close(Respondent), 74 | wait_for_clients(Clients) 75 | end; 76 | wait_for_clients([]) -> 77 | ok. 78 | -------------------------------------------------------------------------------- /include/enm.hrl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm.hrl: data types for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | 23 | -record(nn_inproc, { 24 | addr :: string() | binary() 25 | }). 26 | 27 | -record(nn_ipc, { 28 | path :: string() | binary() 29 | }). 30 | 31 | -record(nn_tcp, { 32 | interface :: any | inet:ip_address() | string() | undefined, 33 | addr :: inet:ip_address() | inet:hostname() | undefined, 34 | port :: inet:port_number() 35 | }). 36 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | %%-*- mode: erlang -*- 2 | {require_min_otp_vsn, "R16B"}. 3 | {eunit_opts, [verbose]}. 4 | {so_name, "enm_drv.so"}. 5 | 6 | {plugins, [pc]}. 7 | 8 | {port_sources, ["c_src/*.c"]}. 9 | 10 | {port_env, [{"DRV_CFLAGS", "$DRV_CFLAGS -Wall -fPIC -Ic_src/include"}, 11 | {"DRV_LDFLAGS", "$DRV_LDFLAGS -Lc_src/lib64 -Lc_src/lib -lnanomsg"}, 12 | {"linux.*", "DRV_LDFLAGS", "$DRV_LDFLAGS -lanl"}]}. 13 | 14 | {pre_hooks, [{"(linux|darwin|solaris)", compile, "make -C c_src"}, 15 | {"(freebsd)", compile, "gmake -C c_src"}, 16 | {"(linux|darwin|solaris)", clean, "make -C c_src clean"}, 17 | {"(freebsd)", clean, "gmake -C c_src clean"}]}. 18 | 19 | {provider_hooks, [{post, [{compile, {pc, compile}}, 20 | {clean, {pc, clean}}]}]}. 21 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | []. 2 | -------------------------------------------------------------------------------- /src/enm.app.src: -------------------------------------------------------------------------------- 1 | {application, enm, 2 | [ 3 | {description, "nanomsg Erlang driver"}, 4 | {vsn, "0.2"}, 5 | {registered, [enm]}, 6 | {applications, [ 7 | kernel, 8 | stdlib 9 | ]}, 10 | {mod, {enm_app,[]}}, 11 | {env, [ 12 | ]} 13 | ]}. 14 | -------------------------------------------------------------------------------- /src/enm.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm: Erlang driver-based binding for nanomsg 4 | %% 5 | %% Copyright (c) 2014-2016 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm). 23 | -behaviour(gen_server). 24 | 25 | -include("enm.hrl"). 26 | 27 | -export([close/1, shutdown/2, 28 | connect/2, bind/2, 29 | req/0, req/1, rep/0, rep/1, 30 | pair/0, pair/1, 31 | bus/0, bus/1, 32 | push/0, push/1, pull/0, pull/1, 33 | pub/0, pub/1, sub/0, sub/1, 34 | surveyor/0, surveyor/1, respondent/0, respondent/1, 35 | send/2, recv/1, recv/2, 36 | getopts/2, setopts/2, 37 | controlling_process/2]). 38 | 39 | -export([start_link/0, start/0, stop/0]). 40 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 41 | terminate/2, code_change/3]). 42 | 43 | -record(state, { 44 | drvmonref :: reference() | undefined 45 | }). 46 | 47 | %% driver command IDs and arguments 48 | -define(ENM_CLOSE, 1). 49 | -define(ENM_BIND, 2). 50 | -define(ENM_CONNECT, 3). 51 | -define(ENM_SHUTDOWN, 4). 52 | -define(ENM_TERM, 5). 53 | -define(ENM_RECV, 10). 54 | -define(ENM_CANCEL_RECV, 11). 55 | -define(ENM_GETOPTS, 12). 56 | -define(ENM_SETOPTS, 13). 57 | -define(ENM_REQ, 20). 58 | -define(ENM_REP, 21). 59 | -define(ENM_BUS, 22). 60 | -define(ENM_PUB, 23). 61 | -define(ENM_SUB, 24). 62 | -define(ENM_PUSH, 25). 63 | -define(ENM_PULL, 26). 64 | -define(ENM_SVYR, 27). 65 | -define(ENM_RESP, 28). 66 | -define(ENM_PAIR, 29). 67 | 68 | -define(ENM_FALSE, 0). 69 | -define(ENM_TRUE, 1). 70 | -define(ENM_ONCE, 2). 71 | -define(ENM_N, 3). 72 | -define(ENM_ACTIVE, 10). 73 | -define(ENM_TYPE, 11). 74 | -define(ENM_RAW, 12). 75 | -define(ENM_DEADLINE, 13). 76 | -define(ENM_SUBSCRIBE, 14). 77 | -define(ENM_UNSUBSCRIBE, 15). 78 | -define(ENM_RESEND_IVL, 16). 79 | -define(ENM_BINARY, 17). 80 | -define(ENM_SNDBUF, 18). 81 | -define(ENM_RCVBUF, 19). 82 | -define(ENM_NODELAY, 20). 83 | -define(ENM_IPV4ONLY, 21). 84 | -define(ENM_RECONNECT_IVL, 22). 85 | -define(ENM_RECONNECT_IVL_MAX, 23). 86 | 87 | -type nnstate() :: #state{}. 88 | -type nnsocket() :: port(). 89 | -type nndata() :: binary() | list(). 90 | -type nnurl() :: #nn_inproc{} | #nn_ipc{} | #nn_tcp{} | 91 | binary() | string(). 92 | -type nnid() :: integer(). 93 | -type nnoptname() :: type | active | raw | mode | 94 | deadline | subscribe | unsubscribe | resend_ivl | 95 | sndbuf | rcvbuf | reconnect_ivl | reconnect_ivl_max. 96 | -type nnoptnames() :: [nnoptname()]. 97 | -type nntypename() :: nnreq | nnrep | nnbus | nnpub | nnsub | nnpush | nnpull | 98 | nnsurveyor | nnrespondent | nnpair. 99 | -type nntypeopt() :: {type, nntypename()}. 100 | -type nnbindopt() :: {bind, nnurl()}. 101 | -type nnconnectopt() :: {connect, nnurl()}. 102 | -type nnactiveopt() :: {active, boolean() | once | -32768..32767}. 103 | -type nnrawopt() :: raw | {raw, boolean()}. 104 | -type nnmodeopt() :: {mode, binary | list} | binary | list. 105 | -type nndeadlineopt() :: {deadline, pos_integer()}. 106 | -type nnsubscribeopt() :: {subscribe, string() | binary()}. 107 | -type nnunsubscribeopt() :: {unsubscribe, string() | binary()}. 108 | -type nnresendivlopt() :: {resend_ivl, pos_integer()}. 109 | -type nnsndbufopt() :: {sndbuf, pos_integer()}. 110 | -type nnrcvbufopt() :: {rcvbuf, pos_integer()}. 111 | -type nnnodelayopt() :: {nodelay, boolean()}. 112 | -type nnipv4only() :: {ipv4only, boolean()}. 113 | -type nnreconnectivl() :: {reconnect_ivl, pos_integer()}. 114 | -type nnreconnectivlmax() :: {reconnect_ivl_max, non_neg_integer()}. 115 | -type nngetopt() :: nntypeopt() | nnactiveopt() | nnmodeopt() | 116 | nndeadlineopt() | nnresendivlopt() | 117 | nnsndbufopt() | nnrcvbufopt() | nnnodelayopt(). 118 | -type nngetopts() :: [nngetopt()]. 119 | -type nnsetopt() :: nnactiveopt() | nnmodeopt() | 120 | nndeadlineopt() | nnsubscribeopt() | nnunsubscribeopt() | 121 | nnresendivlopt() | nnsndbufopt() | nnrcvbufopt() | 122 | nnnodelayopt() | nnipv4only() | 123 | nnreconnectivl() | nnreconnectivlmax(). 124 | -type nnsetopts() :: [nnsetopt()]. 125 | -type nnopenopt() :: nnbindopt() | nnconnectopt() | nnrawopt() | 126 | nnactiveopt() | nnmodeopt() | 127 | nndeadlineopt() | nnsubscribeopt() | nnunsubscribeopt() | 128 | nnresendivlopt() | nnsndbufopt() | nnrcvbufopt() | 129 | nnnodelayopt() | nnreconnectivl() | nnreconnectivlmax(). 130 | -type nnopenopts() :: [nnopenopt()]. 131 | 132 | -export_type([ 133 | nndata/0, 134 | nngetopts/0, 135 | nnid/0, 136 | nnopenopts/0, 137 | nnoptnames/0, 138 | nnsetopts/0, 139 | nnsocket/0, 140 | nnurl/0 141 | ]). 142 | 143 | -spec start_link() -> {ok, pid()}. 144 | start_link() -> 145 | gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). 146 | 147 | -spec start() -> {ok, pid()}. 148 | start() -> 149 | gen_server:start({local, ?MODULE}, ?MODULE, [], []). 150 | 151 | -spec stop() -> ok. 152 | stop() -> 153 | gen_server:cast(?MODULE, stop), 154 | wait_for_stop(). 155 | 156 | -spec close(nnsocket()) -> ok. 157 | close(Sock) when is_port(Sock) -> 158 | try 159 | _ = port_control(Sock, ?ENM_CLOSE, <<>>), 160 | _ = erlang:port_close(Sock) 161 | catch 162 | error:badarg -> 163 | ok 164 | end, 165 | ok. 166 | 167 | -spec shutdown(nnsocket(), nnid()) -> ok | {error, any()}. 168 | shutdown(Sock, Id) when is_port(Sock) -> 169 | call_control(Sock, ?ENM_SHUTDOWN, <>). 170 | 171 | -spec connect(nnsocket(), nnurl()) -> {ok, nnid()} | {error, any()}. 172 | connect(Sock, Url) when is_port(Sock) -> 173 | call_control(Sock, ?ENM_CONNECT, url(Url)). 174 | 175 | -spec bind(nnsocket(), nnurl()) -> {ok, nnid()} | {error, any()}. 176 | bind(Sock, Url) when is_port(Sock) -> 177 | call_control(Sock, ?ENM_BIND, url(Url)). 178 | 179 | -spec getopts(nnsocket(), nnoptnames()) -> {ok, nngetopts()} | {error, any()}. 180 | getopts(Sock, OptNames) when is_port(Sock) -> 181 | OptBin = validate_opt_names(OptNames), 182 | call_control(Sock, ?ENM_GETOPTS, OptBin). 183 | 184 | -spec setopts(nnsocket(), nnsetopts()) -> ok | {error, any()}. 185 | setopts(Sock, Opts) when is_port(Sock) -> 186 | case getopts(Sock, [type]) of 187 | {ok, [{type,Type}]} -> 188 | case validate_opts(normalize_opts(Opts), Type) of 189 | OptBin when is_binary(OptBin) -> 190 | call_control(Sock, ?ENM_SETOPTS, OptBin); 191 | Error -> 192 | Error 193 | end; 194 | Error -> 195 | Error 196 | end. 197 | 198 | -spec controlling_process(nnsocket(), pid()) -> ok | {error, any()}. 199 | controlling_process(Sock, NewOwner) when is_port(Sock) -> 200 | case erlang:port_info(Sock, connected) of 201 | {connected, NewOwner} -> 202 | ok; 203 | {connected, Owner} when Owner /= self() -> 204 | {error, not_owner}; 205 | undefined -> 206 | {error, closed}; 207 | _ -> 208 | {ok, Opts} = getopts(Sock, [active,type]), 209 | {active,A} = lists:keyfind(active,1,Opts), 210 | {type,Type} = lists:keyfind(type,1,Opts), 211 | ok = case A of 212 | false -> ok; 213 | _ -> setopts(Sock, [{active,false}]) 214 | end, 215 | ok = transfer_unreceived_msgs(Sock, Type, NewOwner), 216 | try erlang:port_connect(Sock, NewOwner) of 217 | true -> 218 | unlink(Sock), 219 | ok = case A of 220 | false -> ok; 221 | _ -> setopts(Sock, [{active,A}]) 222 | end, 223 | ok 224 | catch 225 | error:Reason -> 226 | {error, Reason} 227 | end 228 | end. 229 | 230 | -spec req() -> {ok, nnsocket()} | {error, any()}. 231 | -spec req(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 232 | req() -> 233 | socket(nnreq, [], [], []). 234 | req(Opts) -> 235 | socket(nnreq, [], [], Opts). 236 | 237 | -spec rep() -> {ok, nnsocket()} | {error, any()}. 238 | -spec rep(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 239 | rep() -> 240 | socket(nnrep, [], [], []). 241 | rep(Opts) -> 242 | socket(nnrep, [], [], Opts). 243 | 244 | -spec pair() -> {ok, nnsocket()} | {error, any()}. 245 | -spec pair(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 246 | pair() -> 247 | socket(nnpair, [], [], []). 248 | pair(Opts) -> 249 | socket(nnpair, [], [], Opts). 250 | 251 | -spec bus() -> {ok, nnsocket()} | {error, any()}. 252 | -spec bus(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 253 | bus() -> 254 | socket(nnbus, [], [], []). 255 | bus(Opts) -> 256 | socket(nnbus, [], [], Opts). 257 | 258 | -spec push() -> {ok, nnsocket()} | {error, any()}. 259 | -spec push(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 260 | push() -> 261 | socket(nnpush, [], [], []). 262 | push(Opts) -> 263 | socket(nnpush, [], [], Opts). 264 | 265 | -spec pull() -> {ok, nnsocket()} | {error, any()}. 266 | -spec pull(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 267 | pull() -> 268 | socket(nnpull, [], [], []). 269 | pull(Opts) -> 270 | socket(nnpull, [], [], Opts). 271 | 272 | -spec pub() -> {ok, nnsocket()} | {error, any()}. 273 | -spec pub(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 274 | pub() -> 275 | socket(nnpub, [], [], []). 276 | pub(Opts) -> 277 | socket(nnpub, [], [], Opts). 278 | 279 | -spec sub() -> {ok, nnsocket()} | {error, any()}. 280 | -spec sub(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 281 | sub() -> 282 | socket(nnsub, [], [], []). 283 | sub(Opts) -> 284 | socket(nnsub, [], [], Opts). 285 | 286 | -spec surveyor() -> {ok, nnsocket()} | {error, any()}. 287 | -spec surveyor(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 288 | surveyor() -> 289 | socket(nnsurveyor, [], [], []). 290 | surveyor(Opts) -> 291 | socket(nnsurveyor, [], [], Opts). 292 | 293 | -spec respondent() -> {ok, nnsocket()} | {error, any()}. 294 | -spec respondent(nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 295 | respondent() -> 296 | socket(nnrespondent, [], [], []). 297 | respondent(Opts) -> 298 | socket(nnrespondent, [], [], Opts). 299 | 300 | -spec send(nnsocket(), iodata()) -> ok | {error, any()}. 301 | send(Sock, Data) when is_port(Sock) -> 302 | try 303 | true = port_command(Sock, Data), 304 | ok 305 | catch 306 | error:badarg -> 307 | {error, closed} 308 | end. 309 | 310 | -spec recv(nnsocket()) -> {ok, nndata()} | {error, any()}. 311 | -spec recv(nnsocket(), timeout()) -> {ok, nndata()} | {error, any()}. 312 | recv(Sock) when is_port(Sock) -> 313 | recv(Sock, infinity). 314 | recv(Sock, Timeout) when is_port(Sock) -> 315 | Ref = make_ref(), 316 | Bin = term_to_binary(Ref), 317 | try binary_to_term(port_control(Sock, ?ENM_RECV, Bin)) of 318 | {Ref, wait} -> 319 | receive 320 | {Ref, Reply} when is_tuple(Reply) -> 321 | Reply; 322 | {Ref, Reply} -> 323 | {ok, Reply} 324 | after 325 | Timeout -> 326 | ok = binary_to_term(port_control(Sock, ?ENM_CANCEL_RECV, Bin)), 327 | receive 328 | {Ref, Reply} when is_tuple(Reply) -> 329 | Reply; 330 | {Ref, Reply} -> 331 | {ok, Reply} 332 | after 333 | 0 -> 334 | {error, etimedout} 335 | end 336 | end; 337 | {Ref, Reply} when is_tuple(Reply) -> 338 | Reply; 339 | {Ref, Reply} -> 340 | {ok, Reply} 341 | catch 342 | error:badarg -> 343 | {error, closed} 344 | end. 345 | 346 | -define(SHLIB, "enm_drv"). 347 | 348 | -spec init([]) -> ignore | {ok, nnstate()} | {stop, any()}. 349 | init([]) -> 350 | process_flag(trap_exit, true), 351 | PrivDir = case code:priv_dir(?MODULE) of 352 | {error, bad_name} -> 353 | EbinDir = filename:dirname(code:which(?MODULE)), 354 | AppPath = filename:dirname(EbinDir), 355 | filename:join(AppPath, "priv"); 356 | Path -> 357 | Path 358 | end, 359 | Opts = [{driver_options, [kill_ports]}], 360 | LoadResult = case erl_ddll:try_load(PrivDir, ?SHLIB, Opts) of 361 | {ok, loaded} -> ok; 362 | {ok, already_loaded} -> ok; 363 | {error, LoadError} -> 364 | LoadErrorStr = erl_ddll:format_error(LoadError), 365 | EStr = lists:flatten( 366 | io_lib:format("could not load driver ~s: ~p", 367 | [?SHLIB, LoadErrorStr])), 368 | {stop, EStr} 369 | end, 370 | case LoadResult of 371 | ok -> 372 | {ok, #state{}}; 373 | Error -> 374 | Error 375 | end. 376 | 377 | handle_call(_Request, _From, State) -> 378 | {reply, ok, State}. 379 | 380 | handle_cast(stop, State) -> 381 | ok = nn_term(), 382 | case erl_ddll:try_unload(?SHLIB, [{monitor, pending_driver}]) of 383 | {ok, unloaded} -> 384 | {stop, normal, State}; 385 | {ok, pending_driver} -> 386 | {noreply, State}; 387 | {ok, pending_driver, Ref} -> 388 | {noreply, State#state{drvmonref=Ref}} 389 | end; 390 | handle_cast(_Msg, State) -> 391 | {noreply, State}. 392 | 393 | handle_info({'DOWN', Ref, driver, _, unloaded}, #state{drvmonref=Ref}=State) -> 394 | {stop, normal, State}; 395 | handle_info({'DOWN', _, driver, _, unloaded}, State) -> 396 | {stop, normal, State}; 397 | handle_info(_Info, State) -> 398 | {noreply, State}. 399 | 400 | terminate(_Reason, _State) -> 401 | ok. 402 | 403 | code_change(_OldVsn, State, _Extra) -> 404 | {ok, State}. 405 | 406 | %% internal functions 407 | -spec socket(nntypename(), [nnurl()], [nnurl()], nnopenopts()) -> 408 | {ok, nnsocket()} | {error, any()}. 409 | socket(Type, [], [], Opts0) -> 410 | {Bind, Connect, Opts} = lists:foldl(fun({bind,_}=B, {Bind0, C, Opt}) -> 411 | {[B|Bind0], C, Opt}; 412 | ({connect,_}=C, {B, Connect0, Opt}) -> 413 | {B, [C|Connect0], Opt}; 414 | (Other, {B, C, Opt}) -> 415 | {B, C, [Other|Opt]} 416 | end, {[],[],[]}, Opts0), 417 | case {Bind, Connect} of 418 | {[],[]} -> 419 | open_socket(Type, Opts0); 420 | _ -> 421 | socket(Type, Bind, Connect, lists:reverse(Opts)) 422 | end; 423 | socket(Type, [{bind,Url}|_], [], Opts) -> 424 | case open_socket(Type, Opts) of 425 | {ok, Sock} -> 426 | case bind(Sock, Url) of 427 | {ok, _} -> 428 | {ok, Sock}; 429 | Error -> 430 | close(Sock), 431 | Error 432 | end; 433 | Error -> 434 | Error 435 | end; 436 | socket(Type, [], [{connect,Url}|_], Opts) -> 437 | case open_socket(Type, Opts) of 438 | {ok, Sock} -> 439 | case connect(Sock, Url) of 440 | {ok, _} -> 441 | {ok, Sock}; 442 | Error -> 443 | close(Sock), 444 | Error 445 | end; 446 | Error -> 447 | Error 448 | end; 449 | socket(Type, _, _, Opts) -> 450 | error(badarg, [Type, Opts]). 451 | 452 | -spec call_control(nnsocket(), non_neg_integer(), binary()) -> {error, closed} | term(). 453 | call_control(Sock, Cmd, Bin) -> 454 | try 455 | binary_to_term(port_control(Sock, Cmd, Bin)) 456 | catch 457 | error:badarg -> 458 | {error, closed} 459 | end. 460 | 461 | -spec open_socket(nntypename(), nnopenopts()) -> {ok, nnsocket()} | {error, any()}. 462 | open_socket(Type, Opts) -> 463 | Sock = erlang:open_port({spawn_driver, ?SHLIB}, [binary]), 464 | try 465 | case validate_opts(normalize_opts(Opts), Type) of 466 | OptBin when is_binary(OptBin) -> 467 | Protocol = protocol(Type), 468 | case binary_to_term(port_control(Sock, Protocol, OptBin)) of 469 | ok -> 470 | erlang:port_set_data(Sock, ?MODULE), 471 | {ok, Sock}; 472 | Error -> 473 | erlang:port_close(Sock), 474 | Error 475 | end; 476 | Error -> 477 | erlang:port_close(Sock), 478 | Error 479 | end 480 | catch 481 | error:badarg -> 482 | erlang:port_close(Sock), 483 | error(badarg) 484 | end. 485 | 486 | -spec protocol(nntypename()) -> non_neg_integer(). 487 | protocol(nnpair) -> ?ENM_PAIR; 488 | protocol(nnreq) -> ?ENM_REQ; 489 | protocol(nnrep) -> ?ENM_REP; 490 | protocol(nnbus) -> ?ENM_BUS; 491 | protocol(nnpub) -> ?ENM_PUB; 492 | protocol(nnsub) -> ?ENM_SUB; 493 | protocol(nnpush) -> ?ENM_PUSH; 494 | protocol(nnpull) -> ?ENM_PULL; 495 | protocol(nnsurveyor) -> ?ENM_SVYR; 496 | protocol(nnrespondent) -> ?ENM_RESP. 497 | 498 | -spec validate_opt_names(nnoptnames()) -> binary(). 499 | validate_opt_names(Opts) -> 500 | validate_opt_names(Opts, <<>>). 501 | validate_opt_names([], Bin) -> 502 | Bin; 503 | validate_opt_names([mode|Opts], Bin) -> 504 | validate_opt_names(Opts, <>); 505 | validate_opt_names([active|Opts], Bin) -> 506 | validate_opt_names(Opts, <>); 507 | validate_opt_names([type|Opts], Bin) -> 508 | validate_opt_names(Opts, <>); 509 | validate_opt_names([raw|Opts], Bin) -> 510 | validate_opt_names(Opts, <>); 511 | validate_opt_names([deadline|Opts], Bin) -> 512 | validate_opt_names(Opts, <>); 513 | validate_opt_names([subscribe|Opts], Bin) -> 514 | validate_opt_names(Opts, <>); 515 | validate_opt_names([unsubscribe|Opts], Bin) -> 516 | validate_opt_names(Opts, <>); 517 | validate_opt_names([resend_ivl|Opts], Bin) -> 518 | validate_opt_names(Opts, <>); 519 | validate_opt_names([sndbuf|Opts], Bin) -> 520 | validate_opt_names(Opts, <>); 521 | validate_opt_names([rcvbuf|Opts], Bin) -> 522 | validate_opt_names(Opts, <>); 523 | validate_opt_names([nodelay|Opts], Bin) -> 524 | validate_opt_names(Opts, <>); 525 | validate_opt_names([ipv4only|Opts], Bin) -> 526 | validate_opt_names(Opts, <>); 527 | validate_opt_names([reconnect_ivl|Opts], Bin) -> 528 | validate_opt_names(Opts, <>); 529 | validate_opt_names([reconnect_ivl_max|Opts], Bin) -> 530 | validate_opt_names(Opts, <>); 531 | validate_opt_names([Opt|_], _) -> 532 | error(badarg, [Opt]). 533 | 534 | -spec validate_opts(nnopenopts() | nnsetopts(), nntypename()) -> 535 | binary() | {error, any()}. 536 | validate_opts(Opts, Type) -> 537 | validate_opts(Opts, Type, <<>>). 538 | validate_opts([], _, Bin) -> 539 | Bin; 540 | validate_opts([{mode,binary}|Opts], Type, Bin) -> 541 | validate_opts(Opts, Type, <>); 542 | validate_opts([{mode,list}|Opts], Type, Bin) -> 543 | validate_opts(Opts, Type, <>); 544 | validate_opts([{active,_}|_]=Opts, nnpush, Bin) -> 545 | error(badarg, [Opts, nnpush, Bin]); 546 | validate_opts([{active,true}|Opts], Type, Bin) -> 547 | validate_opts(Opts, Type, <>); 548 | validate_opts([{active,false}|Opts], Type, Bin) -> 549 | validate_opts(Opts, Type, <>); 550 | validate_opts([{active,once}|Opts], Type, Bin) -> 551 | validate_opts(Opts, Type, <>); 552 | validate_opts([{active,N}|Opts], Type, Bin) when N >= -32768, N =< 32767 -> 553 | validate_opts(Opts, Type, <>); 554 | validate_opts([{raw,true}|Opts], Type, Bin) -> 555 | validate_opts(Opts, Type, <>); 556 | validate_opts([{raw,false}|Opts], Type, Bin) -> 557 | validate_opts(Opts, Type, <>); 558 | validate_opts([{deadline,Ddline}|Opts], nnsurveyor, Bin) when is_integer(Ddline) -> 559 | validate_opts(Opts, nnsurveyor, <>); 560 | validate_opts([{SubOrUnsub,Topic}|Opts]=AllOpts, nnsub, Bin) 561 | when (SubOrUnsub == subscribe orelse SubOrUnsub == unsubscribe) andalso 562 | (is_list(Topic) orelse is_binary(Topic)) -> 563 | Cmd = case SubOrUnsub of 564 | subscribe -> ?ENM_SUBSCRIBE; 565 | unsubscribe -> ?ENM_UNSUBSCRIBE 566 | end, 567 | case iolist_size(Topic) of 568 | Len when Len >= 256 -> 569 | error(badarg, [AllOpts, nnsub, Bin]); 570 | _ -> 571 | NewBin = list_to_binary([<>, Topic, <<0>>]), 572 | validate_opts(Opts, nnsub, NewBin) 573 | end; 574 | validate_opts([{resend_ivl,RI}|Opts], nnreq, Bin) when is_integer(RI), RI > 0 -> 575 | validate_opts(Opts, nnreq, <>); 576 | validate_opts([{sndbuf,_}|_], Type, _Bin) when Type == nnpull; Type == nnsub -> 577 | {error,einval}; 578 | validate_opts([{sndbuf,Sndbuf}|Opts], Type, Bin) when is_integer(Sndbuf) -> 579 | validate_opts(Opts, Type, <>); 580 | validate_opts([{rcvbuf,_}|_], Type, _Bin) when Type == nnpush; Type == nnpub -> 581 | {error, einval}; 582 | validate_opts([{rcvbuf,Rcvbuf}|Opts], Type, Bin) when is_integer(Rcvbuf) -> 583 | validate_opts(Opts, Type, <>); 584 | validate_opts([{nodelay,NoDelay}|Opts], Type, Bin) when is_boolean(NoDelay) -> 585 | Bool = case NoDelay of 586 | true -> ?ENM_TRUE; 587 | false -> ?ENM_FALSE 588 | end, 589 | validate_opts(Opts, Type, <>); 590 | validate_opts([{ipv4only, IPv4Only}|Opts], Type, Bin) when is_boolean(IPv4Only) -> 591 | Bool = case IPv4Only of 592 | true -> ?ENM_TRUE; 593 | false -> ?ENM_FALSE 594 | end, 595 | validate_opts(Opts, Type, <>); 596 | validate_opts([{reconnect_ivl,RCI}|Opts], Type, Bin) 597 | when is_integer(RCI), RCI > 0 -> 598 | validate_opts(Opts, Type, <>); 599 | validate_opts([{reconnect_ivl_max,RCI}|Opts], Type, Bin) 600 | when is_integer(RCI), RCI >= 0 -> 601 | validate_opts(Opts, Type, <>); 602 | validate_opts(Opts, Type, Bin) -> 603 | error(badarg, [Opts, Type, Bin]). 604 | 605 | normalize_opts(Opts) -> 606 | lists:map(fun(raw) -> {raw, true}; 607 | (binary) -> {mode, binary}; 608 | (list) -> {mode, list}; 609 | (Other) -> Other end, Opts). 610 | 611 | wait_for_stop() -> 612 | timer:sleep(5), 613 | case whereis(?MODULE) of 614 | undefined -> 615 | ok; 616 | _ -> 617 | wait_for_stop() 618 | end. 619 | 620 | nn_term() -> 621 | %% Ideally here we should call nn_term() in the driver but it has 622 | %% problems, as discussed at the github nanomsg repository in issues 623 | %% such as #854 (https://github.com/nanomsg/nanomsg/issues/854), so 624 | %% this is a no-op instead. 625 | ok. 626 | 627 | transfer_unreceived_msgs(Sock, Type, Owner) -> 628 | receive 629 | {Type, Sock, _}=Msg -> 630 | Owner ! Msg, 631 | transfer_unreceived_msgs(Sock, Type, Owner) 632 | after 633 | 0 -> 634 | ok 635 | end. 636 | 637 | -spec url(nnurl()) -> binary(). 638 | url(Url) when Url == <<>>; Url == [] -> 639 | error(badarg, [Url]); 640 | url(Url0) when is_binary(Url0); is_list(Url0) -> 641 | list_to_binary([Url0, <<0>>]); 642 | url(#nn_inproc{addr=Addr}) when is_binary(Addr); is_list(Addr) -> 643 | list_to_binary([<<"inproc://">>, Addr, <<0>>]); 644 | url(#nn_ipc{path=Path}) when is_binary(Path); is_list(Path) -> 645 | list_to_binary([<<"ipc://">>, Path, <<0>>]); 646 | url(#nn_tcp{interface=undefined, addr=undefined, port=Port}) -> 647 | list_to_binary([<<"tcp://:">>, integer_to_list(Port), <<0>>]); 648 | url(#nn_tcp{interface=any, addr=undefined, port=Port}) -> 649 | list_to_binary([<<"tcp://*:">>, integer_to_list(Port), <<0>>]); 650 | url(#nn_tcp{interface=Intf}=Url) when is_tuple(Intf) -> 651 | try inet_parse:ntoa(Intf) of 652 | ListIntf -> 653 | url(Url#nn_tcp{interface=ListIntf}) 654 | catch 655 | _:_ -> 656 | error(badarg, [Url]) 657 | end; 658 | url(#nn_tcp{interface=Intf0, addr=undefined, port=Port}) -> 659 | Intf = getintf(Intf0), 660 | list_to_binary([<<"tcp://">>, Intf, $:, integer_to_list(Port), <<0>>]); 661 | url(#nn_tcp{addr=Addr}=Url) when is_tuple(Addr) -> 662 | try inet_parse:ntoa(Addr) of 663 | ListAddr -> 664 | url(Url#nn_tcp{addr=ListAddr}) 665 | catch 666 | _:_ -> 667 | error(badarg, [Url]) 668 | end; 669 | url(#nn_tcp{interface=undefined, addr=Addr0, port=Port}) -> 670 | Addr = getaddr(Addr0), 671 | list_to_binary([<<"tcp://">>, Addr, $:, integer_to_list(Port), <<0>>]); 672 | url(#nn_tcp{interface=Intf0, addr=Addr0, port=Port}) -> 673 | Intf = getintf(Intf0), 674 | Addr = getaddr(Addr0), 675 | list_to_binary([<<"tcp://[">>, Intf, <<"]:">>, 676 | Addr, $:, integer_to_list(Port), <<0>>]). 677 | 678 | getintf(Intf) when is_list(Intf) -> 679 | try 680 | getaddr(Intf) 681 | catch 682 | error:badarg -> 683 | {ok, Intfs} = inet:getifaddrs(), 684 | case lists:member(Intf, [IfNm || {IfNm, _} <- Intfs]) of 685 | true -> 686 | Intf; 687 | false -> 688 | error(badarg, [Intf]) 689 | end 690 | end; 691 | getintf(Intf) -> 692 | error(badarg, [Intf]). 693 | 694 | getaddr(Addr) when is_list(Addr) -> 695 | case inet:getaddr(Addr, inet) of 696 | {ok, TupleV4} -> 697 | inet_parse:ntoa(TupleV4); 698 | _ -> 699 | case inet:getaddr(Addr, inet6) of 700 | {ok, TupleV6} -> 701 | inet_parse:ntoa(TupleV6); 702 | _ -> 703 | %% check if Addr is an interface name 704 | error(badarg, [Addr]) 705 | end 706 | end; 707 | getaddr(Addr) -> 708 | error(badarg, [Addr]). 709 | 710 | %% Internal tests 711 | -ifdef(TEST). 712 | -include_lib("eunit/include/eunit.hrl"). 713 | 714 | url_test() -> 715 | ?assertMatch(<<"inproc://foo",0>>, url(#nn_inproc{addr="foo"})), 716 | ?assertMatch(<<"ipc:///tmp/file",0>>, url(#nn_ipc{path= <<"/tmp/file">>})), 717 | ?assertMatch(<<"tcp://*:1234",0>>, url(#nn_tcp{interface=any, port=1234})), 718 | ?assertMatch(<<"tcp://127.0.0.1:1234",0>>, 719 | url(#nn_tcp{interface={127,0,0,1}, port=1234})), 720 | ?assertMatch(<<"tcp://192.168.1.1:1234",0>>, 721 | url(#nn_tcp{addr={192,168,1,1}, port=1234})), 722 | ?assertMatch(<<"tcp://::1:1234",0>>, 723 | url(#nn_tcp{addr={0,0,0,0,0,0,0,1}, port=1234})), 724 | ?assertMatch(<<"tcp://:1234",0>>, url(#nn_tcp{port=1234})), 725 | ?assertMatch(<<"tcp://[127.0.0.1]:127.0.0.1:4321",0>>, 726 | url(#nn_tcp{interface="127.0.0.1", addr={127,0,0,1}, port=4321})), 727 | ok = try url(#nn_tcp{interface=any}) 728 | catch 729 | error:badarg -> ok 730 | end, 731 | ok = try url(#nn_tcp{addr={192,168,1,1}}) 732 | catch 733 | error:badarg -> ok 734 | end, 735 | ok. 736 | 737 | close_test_() -> 738 | {setup, 739 | fun start_link/0, 740 | fun(_) -> stop() end, 741 | [fun close_twice/0, 742 | fun close_send/0, 743 | fun close_recv/0, 744 | fun close_bind/0, 745 | fun close_connect/0, 746 | fun close_shutdown/0, 747 | fun close_getopts/0, 748 | fun close_setopts/0, 749 | fun close_ctrlproc/0]}. 750 | 751 | close_twice() -> 752 | {ok,Sock} = enm:pair(), 753 | %% verify multiple calls to close just return ok 754 | ok = enm:close(Sock), 755 | ok = enm:close(Sock), 756 | ok. 757 | 758 | close_send() -> 759 | {ok,Sock} = enm:pair(), 760 | ok = enm:close(Sock), 761 | {error, closed} = enm:send(Sock, "foo"), 762 | ok. 763 | 764 | close_recv() -> 765 | {ok,Sock} = enm:pair(), 766 | ok = enm:close(Sock), 767 | {error, closed} = enm:recv(Sock), 768 | ok. 769 | 770 | close_bind() -> 771 | {ok,Sock} = enm:pair(), 772 | ok = enm:close(Sock), 773 | {error, closed} = enm:bind(Sock, "inproc://foo"), 774 | ok. 775 | 776 | close_connect() -> 777 | {ok,Sock} = enm:pair(), 778 | ok = enm:close(Sock), 779 | {error, closed} = enm:connect(Sock, "inproc://foo"), 780 | ok. 781 | 782 | close_shutdown() -> 783 | {ok,Sock} = enm:pair(), 784 | {ok,Id} = enm:bind(Sock, "inproc://foo"), 785 | ok = enm:close(Sock), 786 | {error, closed} = enm:shutdown(Sock, Id), 787 | ok. 788 | 789 | close_getopts() -> 790 | {ok,Sock} = enm:pair(), 791 | ok = enm:close(Sock), 792 | {error, closed} = enm:getopts(Sock, [active]), 793 | ok. 794 | 795 | close_setopts() -> 796 | {ok,Sock} = enm:pair(), 797 | ok = enm:close(Sock), 798 | {error, closed} = enm:setopts(Sock, [{active,false}]), 799 | ok. 800 | 801 | close_ctrlproc() -> 802 | {ok,Sock} = enm:pair(), 803 | ok = enm:close(Sock), 804 | {error, closed} = enm:controlling_process(Sock, self()), 805 | ok. 806 | 807 | -endif. 808 | -------------------------------------------------------------------------------- /src/enm_app.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_app: Erlang driver-based binding for nanomsg 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_app). 23 | -behaviour(application). 24 | -export([start/2, stop/1]). 25 | 26 | start(_StartType, _StartArgs) -> 27 | enm_sup:start_link(). 28 | 29 | stop(_State) -> 30 | ok. 31 | -------------------------------------------------------------------------------- /src/enm_sup.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_sup: Erlang driver-based binding for nanomsg 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_sup). 23 | -behaviour(supervisor). 24 | -export([start_link/0]). 25 | 26 | -export([init/1]). 27 | 28 | start_link() -> 29 | supervisor:start_link({local, ?MODULE}, ?MODULE, []). 30 | 31 | init([]) -> 32 | Child = {enm, {enm, start_link, []}, 33 | permanent, 2000, worker, [enm]}, 34 | {ok, {{one_for_one, 10, 30}, [Child]}}. 35 | -------------------------------------------------------------------------------- /test/enm_bind_connect.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_bind_connect: bind & connect tests for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_bind_connect). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | bind_test_() -> 29 | {setup, 30 | fun enm:start_link/0, 31 | fun(_) -> enm:stop() end, 32 | fun() -> 33 | {ok,P} = enm:pair(), 34 | {ok,BI1} = enm:bind(P, #nn_inproc{addr="foo"}), 35 | ?assert(is_integer(BI1)), 36 | ok = enm:shutdown(P, BI1), 37 | {error, einval} = enm:shutdown(P, BI1), 38 | {ok,BI2} = enm:bind(P, #nn_inproc{addr="foo2"}), 39 | ?assert(is_integer(BI2)), 40 | {ok,BI3} = enm:bind(P, #nn_inproc{addr="foo3"}), 41 | ?assert(is_integer(BI3)), 42 | ok = enm:close(P), 43 | ok 44 | end}. 45 | 46 | connect_test_() -> 47 | {setup, 48 | fun enm:start_link/0, 49 | fun(_) -> enm:stop() end, 50 | fun() -> 51 | {ok,P1} = enm:pair(), 52 | {ok,_} = enm:bind(P1, #nn_inproc{addr="foo"}), 53 | {ok,P2} = enm:pair(), 54 | {ok,CI} = enm:connect(P2, #nn_inproc{addr="foo"}), 55 | ?assert(is_integer(CI)), 56 | ok = enm:shutdown(P2, CI), 57 | ?assertMatch({error, einval}, enm:shutdown(P2, CI)), 58 | ok = enm:close(P2), 59 | ok = enm:close(P1), 60 | ok 61 | end}. 62 | -------------------------------------------------------------------------------- /test/enm_bus.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_bus: test bus protocol for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_bus). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | -define(URLA, #nn_inproc{addr="a"}). 29 | -define(URLB, #nn_inproc{addr="b"}). 30 | 31 | bus_test_() -> 32 | {setup, 33 | fun enm:start_link/0, 34 | fun(_) -> enm:stop() end, 35 | fun bus/0}. 36 | 37 | bus() -> 38 | {ok, Bus1} = enm:bus([{bind, ?URLA}]), 39 | {ok, Bus2} = enm:bus([{bind, ?URLB}]), 40 | {ok, _} = enm:connect(Bus2, ?URLA), 41 | {ok, Bus3} = enm:bus(), 42 | {ok, _} = enm:connect(Bus3, ?URLA), 43 | {ok, _} = enm:connect(Bus3, ?URLB), 44 | ok = bus_active_true(Bus1, Bus2, Bus3), 45 | ok = bus_active_once(Bus1, Bus2, Bus3), 46 | ok = bus_passive(Bus1, Bus2, Bus3), 47 | ok = enm:close(Bus1), 48 | ok = enm:close(Bus2), 49 | ok = enm:close(Bus3), 50 | ok. 51 | 52 | bus_active_true(Bus1, Bus2, Bus3) -> 53 | ok = enm:setopts(Bus1, [{active,true}]), 54 | ok = enm:setopts(Bus2, [{active,true}]), 55 | ok = enm:setopts(Bus3, [{active,true}]), 56 | ok = bus_active(Bus1, Bus2, Bus3), 57 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Bus1, [active])), 58 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Bus2, [active])), 59 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Bus3, [active])), 60 | ok. 61 | 62 | bus_active_once(Bus1, Bus2, Bus3) -> 63 | ok = enm:setopts(Bus1, [{active,true}]), 64 | ok = enm:setopts(Bus2, [{active,true}]), 65 | ok = enm:setopts(Bus3, [{active,true}]), 66 | FBus1 = fun() -> ok = enm:setopts(Bus1, [{active,once}]), Bus1 end, 67 | FBus2 = fun() -> ok = enm:setopts(Bus2, [{active,once}]), Bus2 end, 68 | FBus3 = fun() -> ok = enm:setopts(Bus3, [{active,once}]), Bus3 end, 69 | ok = bus_active(FBus1, FBus2, FBus3), 70 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Bus1, [active])), 71 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Bus2, [active])), 72 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Bus3, [active])), 73 | ok. 74 | 75 | bus_active(Bus1, Bus2, Bus3) -> 76 | Data1 = <<"data packet 1">>, 77 | Data2 = <<"data packet 2">>, 78 | Data3 = <<"data packet 3">>, 79 | Buses = [Bus1,Bus2,Bus3], 80 | [B1,B2,B3] = [if is_function(B) -> B(); true -> B end || B <- Buses], 81 | ok = enm:send(B1, Data1), 82 | ok = enm:send(B2, Data2), 83 | ok = enm:send(B3, Data3), 84 | Seq = [{Bus1,[Data2,Data3]}, {Bus2,[Data1,Data3]}, {Bus3,[Data1,Data2]}], 85 | Results = do_send_recv(Seq), 86 | ?assertMatch(6, length(Results)), 87 | true = lists:all(fun(ok) -> true end, Results), 88 | ok. 89 | 90 | bus_passive(Bus1, Bus2, Bus3) -> 91 | ok = enm:setopts(Bus1, [{active,false}]), 92 | ok = enm:setopts(Bus2, [{active,false}]), 93 | ok = enm:setopts(Bus3, [{active,false}]), 94 | Data1 = <<"passive data packet 1">>, 95 | Data2 = <<"passive data packet 2">>, 96 | Data3 = <<"passive data packet 3">>, 97 | ok = enm:send(Bus1, Data1), 98 | ok = enm:send(Bus2, Data2), 99 | ok = enm:send(Bus3, Data3), 100 | ?assertMatch({ok, Data2}, enm:recv(Bus1)), 101 | ?assertMatch({ok, Data3}, enm:recv(Bus1)), 102 | ?assertMatch({ok, Data1}, enm:recv(Bus2)), 103 | ?assertMatch({ok, Data3}, enm:recv(Bus2)), 104 | ?assertMatch({ok, Data1}, enm:recv(Bus3)), 105 | ?assertMatch({ok, Data2}, enm:recv(Bus3)), 106 | ok. 107 | 108 | do_send_recv(Seq) -> 109 | do_send_recv(Seq, []). 110 | do_send_recv([], Acc) -> 111 | lists:flatten(Acc); 112 | do_send_recv([{Bus,Packets}|Seq], Acc) -> 113 | Res = [begin 114 | B = if 115 | is_function(Bus) -> Bus(); 116 | true -> Bus 117 | end, 118 | receive 119 | {nnbus, B, Data} -> 120 | ok 121 | after 122 | 1000 -> 123 | error(bus_timeout) 124 | end 125 | end || Data <- Packets], 126 | do_send_recv(Seq, [Res|Acc]). 127 | -------------------------------------------------------------------------------- /test/enm_eqc.erl: -------------------------------------------------------------------------------- 1 | -module(enm_eqc). 2 | 3 | %% --------------------------------------------------------------------- 4 | %% 5 | %% Copyright (c) 2007-2013 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% --------------------------------------------------------------------- 22 | 23 | %% @doc Quickcheck test module for `enm_eqc'. 24 | %% Ideas: 25 | %% * Use eqc_fsm to model states of socket 26 | %% * `init' state: Open random type of socket 27 | %% * `send' state: send message 28 | %% * `recv' state: receive message 29 | %% * `close' state: close socket 30 | %% * Permit any transition from `init' state 31 | %% 32 | %% * Other interesting things to do 33 | %% * Random selection of address record type 34 | %% * Combination of different socket options 35 | 36 | -ifdef(TEST). 37 | 38 | -ifdef(EQC). 39 | 40 | -include_lib("eqc/include/eqc.hrl"). 41 | -include_lib("eqc/include/eqc_fsm.hrl"). 42 | -include_lib("eunit/include/eunit.hrl"). 43 | 44 | %% eqc properties 45 | -export([prop_enm/0]). 46 | 47 | %% States 48 | -export([init/1, 49 | msg_sent/1, 50 | msg_received/1, 51 | closed/1]). 52 | 53 | %% eqc_fsm callbacks 54 | -export([initial_state/0, 55 | initial_state_data/0, 56 | next_state_data/5, 57 | precondition/4, 58 | postcondition/5]). 59 | 60 | -export([recv/1, 61 | close/2, 62 | test/0, 63 | test/1]). 64 | 65 | -define(QC_OUT(P), 66 | eqc:on_output(fun(Str, Args) -> 67 | io:format(user, Str, Args) end, P)). 68 | 69 | -define(ENM_MODULE, enm). 70 | -define(TEST_ITERATIONS, 100). 71 | 72 | -define(P(EXPR), PPP = (EXPR), 73 | case PPP of 74 | true -> ok; 75 | _ -> io:format(user, "PPP=~p at line ~p: ~s~n", [PPP, ?LINE, ??EXPR]) 76 | end, 77 | PPP). 78 | 79 | -record(state, {sent_messages=[] :: [term()], 80 | write_socket :: term(), 81 | read_socket :: term(), 82 | socket_closed=false :: boolean() 83 | }). 84 | 85 | %% ==================================================================== 86 | %% EQC Properties 87 | %% ==================================================================== 88 | 89 | prop_enm() -> 90 | ?FORALL(Cmds, 91 | commands(?MODULE), 92 | begin 93 | {Read, Write} = sockets(), 94 | {H, {_F, _S}, Res} = 95 | run_commands(?MODULE, Cmds, [{read_socket, Read}, 96 | {write_socket, Write}]), 97 | close(Read, Write), 98 | aggregate(zip(state_names(H), command_names(Cmds)), 99 | ?WHENFAIL( 100 | begin 101 | eqc:format("Cmds: ~p~n~n", 102 | [zip(state_names(H), 103 | command_names(Cmds))]), 104 | eqc:format("Result: ~p~n~n", [Res]), 105 | eqc:format("History: ~p~n~n", [H]) 106 | end, 107 | equals(ok, Res))) 108 | end). 109 | 110 | %%==================================================================== 111 | %% Eunit shite 112 | %%==================================================================== 113 | 114 | eqc_test_() -> 115 | {spawn, 116 | [{setup, 117 | fun setup/0, 118 | fun cleanup/1, 119 | [%% Run the quickcheck tests 120 | {timeout, 600, 121 | ?_assertEqual(true, eqc:quickcheck( 122 | eqc:numtests(?TEST_ITERATIONS, 123 | ?QC_OUT(prop_enm()))))} 124 | ]} 125 | ]}. 126 | 127 | setup() -> 128 | error_logger:tty(false), 129 | error_logger:logfile({open, "enm_eqc.log"}), 130 | enm:start(). 131 | 132 | cleanup(_) -> 133 | enm:stop(). 134 | 135 | %%==================================================================== 136 | %% eqc_fsm callbacks 137 | %%==================================================================== 138 | 139 | %% TODO: Test other protocol types 140 | %% Just testing pipeline initially 141 | %% Protocols: [reqrep, pair, pubsub, pipeline, survey] 142 | %% Open question whether or not each protocol should 143 | %% have it's own eqc module or they should be rolled into 144 | %% one. 145 | 146 | init(S) -> 147 | %% TODO: shutdown state? 148 | [ 149 | {msg_sent, {call, ?ENM_MODULE, send, [S#state.write_socket, eqc_gen:binary(10)]}}, 150 | {msg_received, {call, ?MODULE, recv, [S#state.read_socket]}}, 151 | {closed, {call, ?MODULE, close, [S#state.read_socket, S#state.write_socket]}} 152 | ]. 153 | 154 | msg_sent(S) -> 155 | [ 156 | {msg_received, {call, ?MODULE, recv, [S#state.read_socket]}}, 157 | {closed, {call, ?MODULE, close, [S#state.read_socket, S#state.write_socket]}}, 158 | {history, {call, ?ENM_MODULE, send, [S#state.write_socket, eqc_gen:binary(10)]}} 159 | ]. 160 | 161 | msg_received(S) -> 162 | [ 163 | {msg_sent, {call, ?ENM_MODULE, send, [S#state.write_socket, eqc_gen:binary(10)]}}, 164 | {closed, {call, ?MODULE, close, [S#state.read_socket, S#state.write_socket]}}, 165 | {history, {call, ?MODULE, recv, [S#state.read_socket]}} 166 | ]. 167 | 168 | closed(S) -> 169 | [ 170 | {msg_sent, {call, ?ENM_MODULE, send, [S#state.write_socket, eqc_gen:binary()]}}, 171 | {msg_received, {call, ?MODULE, recv, [S#state.read_socket]}}, 172 | {history, {call, ?MODULE, close, [S#state.read_socket, S#state.write_socket]}} 173 | ]. 174 | 175 | 176 | initial_state() -> 177 | init. 178 | 179 | initial_state_data() -> 180 | #state{read_socket={var, read_socket}, 181 | write_socket={var, write_socket}}. 182 | 183 | next_state_data(_, msg_received, S, _Res, _C) -> 184 | Messages = lists:reverse(S#state.sent_messages), 185 | case Messages of 186 | [] -> 187 | S; 188 | [_Head | RestMessages] -> 189 | S#state{sent_messages=lists:reverse(RestMessages)} 190 | end; 191 | next_state_data(closed, _, S, _Res, _C) -> 192 | S; 193 | next_state_data(_, closed, S, _Res, _C) -> 194 | S#state{socket_closed=true}; 195 | next_state_data(_, msg_sent, S, _Res, {call, _M, _F, [_, SentMsg]}) -> 196 | SentMessages = S#state.sent_messages, 197 | S#state{sent_messages=[SentMsg | SentMessages]}; 198 | 199 | next_state_data(_From, _To, S, _R, _C) -> 200 | S. 201 | 202 | precondition(_From, _To, _S, _C) -> 203 | true. 204 | 205 | postcondition(_, closed, _S, _C, ok) -> 206 | true; 207 | postcondition(closed, msg_received, S , _C, {ok, Msg}) 208 | when S#state.sent_messages =/= [] -> 209 | ExpectedMsg = lists:last(S#state.sent_messages), 210 | ?P(ExpectedMsg =:= Msg); 211 | postcondition(closed, msg_received, _S , _C, {error, timeout}) -> 212 | true; 213 | postcondition(closed, _, _S , _C, {error, closed}) -> 214 | true; 215 | postcondition(closed, _, _S , _C, R) -> 216 | ?debugFmt("Res: ~p", [R]), 217 | ?P(false); 218 | postcondition(_, msg_received, S , _C, {ok, Msg}) 219 | when S#state.socket_closed =:= true, 220 | S#state.sent_messages =/= [] -> 221 | ExpectedMsg = lists:last(S#state.sent_messages), 222 | ?P(ExpectedMsg =:= Msg); 223 | postcondition(_, msg_received, S, _C, {error, timeout}) 224 | when S#state.socket_closed =:= true -> 225 | true; 226 | postcondition(_, _, S, _C, {error, closed}) 227 | when S#state.socket_closed =:= true -> 228 | true; 229 | postcondition(_, _, S, _C, R) 230 | when S#state.socket_closed =:= true -> 231 | ?debugFmt("Res2: ~p", [R]), 232 | ?P(false); 233 | postcondition(_, msg_sent, _S , _C, ok) -> 234 | true; 235 | postcondition(_, msg_sent, _S , _C, _R) -> 236 | ?P(false); 237 | postcondition(_, msg_received, S , _C, {ok, Msg}) -> 238 | ExpectedMsg = lists:last(S#state.sent_messages), 239 | ?P(ExpectedMsg =:= Msg); 240 | postcondition(_, msg_received, S , _C, {error, timeout}) -> 241 | case S#state.sent_messages of 242 | [] -> 243 | true; 244 | _ -> 245 | ?P(false) 246 | end; 247 | postcondition(_, msg_received, _S , _C, _R) -> 248 | ?P(false); 249 | postcondition(_From, _To, _S, _C, _R) -> 250 | true. 251 | 252 | %%==================================================================== 253 | %% Helpers 254 | %%==================================================================== 255 | 256 | sockets() -> 257 | Url = "inproc://pipeline", 258 | {ok, Read} = enm:pull([{bind, Url}]), 259 | {ok, Write} = enm:push([{connect, Url}]), 260 | {Read, Write}. 261 | 262 | close(Read, Write) -> 263 | enm:close(Read), 264 | enm:close(Write). 265 | 266 | recv(Socket) -> 267 | receive 268 | {nnpull, Socket, Msg} -> 269 | {ok, Msg} 270 | after 271 | 1000 -> 272 | {error, timeout} 273 | end. 274 | 275 | test() -> 276 | test(500). 277 | 278 | test(Iterations) -> 279 | setup(), 280 | Res = eqc:quickcheck(eqc:numtests(Iterations, prop_enm())), 281 | cleanup(ok), 282 | Res. 283 | 284 | 285 | -endif. 286 | -endif. 287 | -------------------------------------------------------------------------------- /test/enm_opts.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_opts: option tests for enm 4 | %% 5 | %% Copyright (c) 2014-2016 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_opts). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | opt_test_() -> 29 | {setup, 30 | fun enm:start_link/0, 31 | fun(_) -> enm:stop() end, 32 | [fun getopts/0, 33 | fun active/0, 34 | fun mode/0, 35 | fun misc/0]}. 36 | 37 | getopts() -> 38 | {ok,P} = enm:pair(), 39 | {ok,Opts} = enm:getopts(P, [type,active]), 40 | ?assertMatch({type,nnpair}, lists:keyfind(type,1,Opts)), 41 | ?assertMatch({active,true}, lists:keyfind(active,1,Opts)), 42 | ?assertMatch({ok,[{mode,binary}]}, enm:getopts(P, [mode])), 43 | ok = enm:close(P), 44 | ok. 45 | 46 | active() -> 47 | Url = #nn_inproc{addr="active"}, 48 | Req = <<"123456789">>, 49 | {ok, P1} = enm:pair([{active,false}]), 50 | {ok, _} = enm:bind(P1, Url), 51 | {ok, P2} = enm:pair(), 52 | {ok, _} = enm:connect(P2, Url), 53 | ok = enm:send(P2, Req), 54 | ok = receive 55 | Reply1 -> 56 | error({unexpected_reply, Reply1}) 57 | after 58 | 0 -> 59 | ok 60 | end, 61 | {ok, Req} = enm:recv(P1), 62 | ok = enm:setopts(P1, [{active,once}]), 63 | ok = receive 64 | Reply2 -> 65 | error({unexpected_reply, Reply2}) 66 | after 67 | 0 -> 68 | ok 69 | end, 70 | ok = enm:send(P2, Req), 71 | ok = receive 72 | {nnpair,P1,Req} -> 73 | ok; 74 | Reply3 -> 75 | error({unexpected_reply, Reply3}) 76 | after 77 | 1000 -> 78 | error(reply_timeout) 79 | end, 80 | ok = enm:send(P2, Req), 81 | ok = receive 82 | Reply4 -> 83 | error({unexpected_reply, Reply4}) 84 | after 85 | 0 -> 86 | ok 87 | end, 88 | {ok, [{active,false}]} = enm:getopts(P1, [active]), 89 | ok = enm:setopts(P1, [{active,once}]), 90 | ok = receive 91 | {nnpair,P1,Req} -> 92 | ok; 93 | Reply5 -> 94 | error({unexpected_reply, Reply5}) 95 | after 96 | 1000 -> 97 | error(reply_timeout) 98 | end, 99 | ok = enm:setopts(P1,[{active,1}]), 100 | ?assertMatch({ok,[{active,1}]}, enm:getopts(P1,[active])), 101 | ok = enm:setopts(P1,[{active,-1}]), 102 | ok = receive 103 | {nnpair_passive,P1} -> 104 | ok; 105 | Reply6 -> 106 | error({unexpected_reply, Reply6}) 107 | after 108 | 1000 -> 109 | error(reply_timeout) 110 | end, 111 | ?assertMatch({ok, [{active,false}]}, enm:getopts(P1, [active])), 112 | ok = enm:setopts(P1,[{active,-1}]), 113 | ok = receive 114 | {nnpair_passive,P1} -> 115 | ok; 116 | Reply7 -> 117 | error({unexpected_reply, Reply7}) 118 | after 119 | 1000 -> 120 | error(reply_timeout) 121 | end, 122 | ?assertMatch({ok, [{active,false}]}, enm:getopts(P1, [active])), 123 | ok = enm:setopts(P1,[{active,2}]), 124 | ok = enm:send(P2, Req), 125 | ok = receive 126 | {nnpair,P1,Req} -> 127 | ok; 128 | Reply8 -> 129 | error({unexpected_reply, Reply8}) 130 | after 131 | 1000 -> 132 | error(reply_timeout) 133 | end, 134 | ?assertMatch({ok,[{active,1}]}, enm:getopts(P1,[active])), 135 | ok = enm:send(P2, Req), 136 | ok = receive 137 | {nnpair,P1,Req} -> 138 | ok; 139 | Reply9 -> 140 | error({unexpected_reply, Reply9}) 141 | after 142 | 1000 -> 143 | error(reply_timeout) 144 | end, 145 | ok = receive 146 | {nnpair_passive,P1} -> 147 | ok; 148 | Reply10 -> 149 | error({unexpected_reply, Reply10}) 150 | after 151 | 1000 -> 152 | error(reply_timeout) 153 | end, 154 | ?assertMatch({ok, [{active,false}]}, enm:getopts(P1, [active])), 155 | ok = enm:close(P2), 156 | ok = enm:close(P1), 157 | ok. 158 | 159 | mode() -> 160 | Url = <<"inproc://mode">>, 161 | {ok,Rep} = enm:rep([{bind,Url},{mode,list}]), 162 | {ok,Req} = enm:req([{connect,Url},{active,false}]), 163 | Data = <<"data data data data">>, 164 | DataList = binary_to_list(Data), 165 | ok = enm:send(Req, Data), 166 | ok = receive 167 | {nnrep,Rep,DataList} -> 168 | ok = enm:send(Rep, "ok"); 169 | Reply1 -> 170 | error({unexpected_reply,Reply1}) 171 | end, 172 | ok = enm:setopts(Rep,[{mode,binary}]), 173 | ok = enm:send(Req, Data), 174 | ok = receive 175 | {nnrep,Rep,Data} -> 176 | ok = enm:send(Rep, "ok"); 177 | Reply2 -> 178 | error({unexpected_reply,Reply2}) 179 | end, 180 | ok = enm:setopts(Rep,[{active,false}]), 181 | ok = enm:send(Req, Data), 182 | ?assertMatch({ok, Data}, enm:recv(Rep, 2000)), 183 | ok = enm:send(Rep, "ok"), 184 | ok = enm:setopts(Rep,[{mode,list}]), 185 | ok = enm:send(Req, Data), 186 | ?assertMatch({ok, DataList}, enm:recv(Rep, 2000)), 187 | ok = enm:setopts(Rep,[binary]), 188 | {ok, [{mode,binary}]} = enm:getopts(Rep, [mode]), 189 | ok = enm:setopts(Rep,[list]), 190 | ?assertMatch({ok, [{mode,list}]}, enm:getopts(Rep, [mode])), 191 | ok = enm:close(Req), 192 | ok = enm:close(Rep), 193 | ok. 194 | 195 | misc() -> 196 | {ok,Req} = enm:req([{resend_ivl,5000}]), 197 | ?assertMatch({ok,[{resend_ivl,5000}]}, enm:getopts(Req, [resend_ivl])), 198 | ok = enm:setopts(Req, [{ipv4only,false}]), 199 | ?assertMatch({ok,[{ipv4only,false}]}, enm:getopts(Req, [ipv4only])), 200 | ok = enm:setopts(Req, [{sndbuf,345678}]), 201 | ?assertMatch({ok,[{sndbuf,345678}]}, enm:getopts(Req, [sndbuf])), 202 | ok = enm:setopts(Req, [{rcvbuf,456789}]), 203 | ?assertMatch({ok,[{rcvbuf,456789}]}, enm:getopts(Req, [rcvbuf])), 204 | ok = enm:setopts(Req, [{reconnect_ivl,2000}]), 205 | ?assertMatch({ok,[{reconnect_ivl,2000}]}, 206 | enm:getopts(Req, [reconnect_ivl])), 207 | ok = enm:setopts(Req, [{reconnect_ivl_max,5000}]), 208 | ?assertMatch({ok,[{reconnect_ivl_max,5000}]}, 209 | enm:getopts(Req, [reconnect_ivl_max])), 210 | ?assertMatch({error,einval}, enm:pull([{sndbuf,12345678}])), 211 | ?assertMatch({error,einval}, enm:sub([{sndbuf,12345678}])), 212 | ?assertMatch({error,einval}, enm:push([{rcvbuf,12345678}])), 213 | ?assertMatch({error,einval}, enm:pub([{rcvbuf,12345678}])), 214 | ok = enm:close(Req), 215 | ok. 216 | -------------------------------------------------------------------------------- /test/enm_pair.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_pair: test pair protocol for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_pair). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | pair_test_() -> 29 | {setup, 30 | fun enm:start_link/0, 31 | fun(_) -> enm:stop() end, 32 | fun pair/0}. 33 | 34 | pair() -> 35 | Url = #nn_inproc{addr="a"}, 36 | {ok, SB} = enm:pair([{bind, Url}]), 37 | {ok, SC} = enm:pair([{connect, Url}]), 38 | ok = active_true_pair(SB, SC), 39 | ok = active_once_pair(SB, SC), 40 | ok = passive_pair(SB, SC), 41 | ok. 42 | 43 | active_true_pair(SB, SC) -> 44 | ok = enm:setopts(SB, [{active,true}]), 45 | ok = enm:setopts(SC, [{active,true}]), 46 | ok = active_req_rep(SB, SC), 47 | ?assertMatch({ok, [{active,true}]}, enm:getopts(SB, [active])), 48 | ?assertMatch({ok, [{active,true}]}, enm:getopts(SC, [active])), 49 | ok. 50 | 51 | active_once_pair(SB, SC) -> 52 | ok = enm:setopts(SB, [{active,once}]), 53 | ok = enm:setopts(SC, [{active,once}]), 54 | ok = active_req_rep(SB, SC), 55 | ?assertMatch({ok, [{active,false}]}, enm:getopts(SB, [active])), 56 | ?assertMatch({ok, [{active,false}]}, enm:getopts(SC, [active])), 57 | ok. 58 | 59 | passive_pair(SB, SC) -> 60 | Req = <<"passive request">>, 61 | Rep = <<"passive reply">>, 62 | ok = enm:setopts(SB, [{active,false}]), 63 | ok = enm:setopts(SC, [{active,false}]), 64 | ok = enm:send(SC, Req), 65 | ?assertMatch({ok, Req}, enm:recv(SB)), 66 | ok = enm:send(SB, Rep), 67 | ?assertMatch({ok, Rep}, enm:recv(SC)), 68 | ok. 69 | 70 | active_req_rep(SB, SC) -> 71 | Req = <<"active request">>, 72 | Rep = <<"active reply">>, 73 | ok = enm:send(SC, Req), 74 | ok = receive 75 | {nnpair, SB, Req} -> 76 | ok = enm:send(SB, Rep); 77 | BadReq -> 78 | error({unexpected_request, BadReq}) 79 | after 80 | 2000 -> 81 | error(request_timeout) 82 | end, 83 | ok = receive 84 | {nnpair, SC, Rep} -> 85 | ok; 86 | BadRep -> 87 | error({unexpected_reply, BadRep}) 88 | after 89 | 2000 -> 90 | error(reply_timeout) 91 | end, 92 | ok. 93 | -------------------------------------------------------------------------------- /test/enm_pipeline.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_pipeline: test pipeline protocol for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_pipeline). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | -define(URL, #nn_inproc{addr="a"}). 29 | 30 | pipeline_test_() -> 31 | {setup, 32 | fun enm:start_link/0, 33 | fun(_) -> enm:stop() end, 34 | [fun fan_out/0, 35 | fun fan_in/0, 36 | fun no_server/0]}. 37 | 38 | fan_out() -> 39 | {ok, Push1} = enm:push(), 40 | {ok, _} = enm:bind(Push1, ?URL), 41 | {ok, Pull1} = enm:pull(), 42 | {ok, _} = enm:connect(Pull1, ?URL), 43 | {ok, Pull2} = enm:pull(), 44 | {ok, _} = enm:connect(Pull2, ?URL), 45 | ok = out_active_true_pipeline(Push1, Pull1, Pull2), 46 | ok = out_active_once_pipeline(Push1, Pull1, Pull2), 47 | ok = out_passive_pipeline(Push1, Pull1, Pull2), 48 | [ok,ok,ok] = [try enm:setopts(Push1, [{active,Active}]) 49 | catch error:badarg -> ok end || Active <- [true,false,once]], 50 | ok = enm:close(Push1), 51 | ok = enm:close(Pull1), 52 | ok = enm:close(Pull2), 53 | ok. 54 | 55 | fan_in() -> 56 | {ok, Pull1} = enm:pull(), 57 | {ok, _} = enm:bind(Pull1, ?URL), 58 | {ok, Push1} = enm:push(), 59 | {ok, _} = enm:connect(Push1, ?URL), 60 | {ok, Push2} = enm:push(), 61 | {ok, _} = enm:connect(Push2, ?URL), 62 | ok = in_active_true_pipeline(Pull1, Push1, Push2), 63 | ok = in_active_once_pipeline(Pull1, Push1, Push2), 64 | ok = in_passive_pipeline(Pull1, Push1, Push2), 65 | ok = enm:close(Pull1), 66 | ok = enm:close(Push1), 67 | ok = enm:close(Push2), 68 | ok. 69 | 70 | out_active_true_pipeline(Push1, Pull1, Pull2) -> 71 | ok = enm:setopts(Pull1, [{active,true}]), 72 | ok = enm:setopts(Pull2, [{active,true}]), 73 | ok = out_active_push_pull(Push1, Pull1, Pull2), 74 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Pull1, [active])), 75 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Pull2, [active])), 76 | ok. 77 | 78 | out_active_once_pipeline(Push1, Pull1, Pull2) -> 79 | ok = enm:setopts(Pull1, [{active,once}]), 80 | ok = enm:setopts(Pull2, [{active,once}]), 81 | ok = out_active_push_pull(Push1, Pull1, Pull2), 82 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Pull1, [active])), 83 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Pull2, [active])), 84 | ok. 85 | 86 | out_passive_pipeline(Push1, Pull1, Pull2) -> 87 | Data = <<"passive request">>, 88 | ok = enm:setopts(Pull1, [{active,false}]), 89 | ok = enm:setopts(Pull2, [{active,false}]), 90 | ok = enm:send(Push1, Data), 91 | ok = enm:send(Push1, Data), 92 | ?assertMatch({ok, Data}, enm:recv(Pull1)), 93 | ?assertMatch({ok, Data}, enm:recv(Pull2)), 94 | ok. 95 | 96 | out_active_push_pull(Push1, Pull1, Pull2) -> 97 | Data = <<"active pushpull">>, 98 | ok = enm:send(Push1, Data), 99 | ok = enm:send(Push1, Data), 100 | true = lists:all(fun(ok) -> true end, do_pull([Pull1, Pull2], Data)), 101 | ok. 102 | 103 | in_active_true_pipeline(Pull1, Push1, Push2) -> 104 | ok = enm:setopts(Pull1, [{active,true}]), 105 | ok = in_active_push_pull(Pull1, Push1, Push2), 106 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Pull1, [active])), 107 | ok. 108 | 109 | in_active_once_pipeline(Pull1, Push1, Push2) -> 110 | F = fun() -> ok = enm:setopts(Pull1, [{active,once}]), Pull1 end, 111 | ok = in_active_push_pull(F, Push1, Push2), 112 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Pull1, [active])), 113 | ok. 114 | 115 | in_passive_pipeline(Pull1, Push1, Push2) -> 116 | Data = <<"passive request">>, 117 | ok = enm:setopts(Pull1, [{active,false}]), 118 | ok = enm:send(Push1, Data), 119 | ok = enm:send(Push2, Data), 120 | ?assertMatch({ok, Data}, enm:recv(Pull1)), 121 | ?assertMatch({ok, Data}, enm:recv(Pull1)), 122 | ok. 123 | 124 | in_active_push_pull(Pull1, Push1, Push2) -> 125 | Data = <<"active pushpull">>, 126 | ok = enm:send(Push1, Data), 127 | ok = enm:send(Push2, Data), 128 | true = lists:all(fun(ok) -> true end, do_pull([Pull1, Pull1], Data)), 129 | ok. 130 | 131 | do_pull(Pulls, Data) -> 132 | do_pull(Pulls, Data, []). 133 | do_pull([], _, Acc) -> 134 | Acc; 135 | do_pull([Pull|Pulls], Data, Acc) when is_function(Pull) -> 136 | do_pull([Pull()|Pulls], Data, Acc); 137 | do_pull([_|Pulls], Data, Acc) -> 138 | receive 139 | {nnpull, _, Data} -> 140 | do_pull(Pulls, Data, [ok|Acc]); 141 | BadPull -> 142 | error({unexpected_push, BadPull}) 143 | after 144 | 2000 -> 145 | error(pull_timeout) 146 | end. 147 | 148 | no_server() -> 149 | %% This test checks that attempts to push to a TCP endpoint that's not 150 | %% there fails (github enm issue #7). The test requires the remote 151 | %% endpoint to not have anything listening and accepting, so the 152 | %% following fold attempts to find such an endpoint. The test won't 153 | %% work if something actually answers at the endpoint the fold chooses. 154 | Port = (catch lists:foldl( 155 | fun(P, _) -> 156 | case gen_tcp:connect("localhost", P, []) of 157 | {error, econnrefused} -> 158 | throw(P); 159 | {ok, S} -> 160 | gen_tcp:close(S), 161 | P; 162 | _ -> 163 | P 164 | end 165 | end, ok, lists:seq(47000,60000))), 166 | Url = "tcp://localhost:"++integer_to_list(Port), 167 | {ok,Push} = enm:push([{connect,Url},list]), 168 | enm:send(Push, "sending the first message"), 169 | ?assertMatch({error,closed}, enm:send(Push, "sending the second message")), 170 | ok. 171 | -------------------------------------------------------------------------------- /test/enm_pubsub.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_pubsub: test pub/sub protocol for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_pubsub). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | -define(URL, #nn_inproc{addr="a"}). 29 | 30 | pubsub_test_() -> 31 | {setup, 32 | fun enm:start_link/0, 33 | fun(_) -> enm:stop() end, 34 | [fun one_pub/0, 35 | fun two_pub/0, 36 | fun check_sub_filter/0]}. 37 | 38 | one_pub() -> 39 | {ok, Pub1} = enm:pub(), 40 | {ok, _} = enm:bind(Pub1, ?URL), 41 | {ok, Sub1} = enm:sub(), 42 | ok = enm:setopts(Sub1, [{subscribe, ""}]), 43 | {ok, _} = enm:connect(Sub1, ?URL), 44 | {ok, Sub2} = enm:sub(), 45 | ok = enm:setopts(Sub2, [{subscribe, ""}]), 46 | {ok, _} = enm:connect(Sub2, ?URL), 47 | ok = one_pub_active_true(Pub1, Sub1, Sub2), 48 | ok = one_pub_active_once(Pub1, Sub1, Sub2), 49 | ok = one_pub_passive(Pub1, Sub1, Sub2), 50 | ok = enm:setopts(Sub2, [{unsubscribe, ""}]), 51 | ok = enm:close(Sub2), 52 | ok = enm:close(Sub1), 53 | ok = enm:close(Pub1), 54 | ok. 55 | 56 | one_pub_active_true(Pub1, Sub1, Sub2) -> 57 | ok = enm:setopts(Sub1, [{active,true}]), 58 | ok = enm:setopts(Sub2, [{active,true}]), 59 | ok = one_pub_active(Pub1, Sub1, Sub2), 60 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Sub1, [active])), 61 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Sub2, [active])), 62 | ok. 63 | 64 | one_pub_active_once(Pub1, Sub1, Sub2) -> 65 | ok = enm:setopts(Sub1, [{active,once}]), 66 | ok = enm:setopts(Sub2, [{active,once}]), 67 | ok = one_pub_active(Pub1, Sub1, Sub2), 68 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Sub1, [active])), 69 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Sub2, [active])), 70 | ok. 71 | 72 | one_pub_active(Pub1, Sub1, Sub2) -> 73 | Data = <<"some important information for subscribers">>, 74 | ok = enm:send(Pub1, Data), 75 | true = lists:all(fun(ok) -> true end, do_sub([Sub1, Sub2], Data)), 76 | ok. 77 | 78 | one_pub_passive(Pub1, Sub1, Sub2) -> 79 | ok = enm:setopts(Sub1, [{active,false}]), 80 | ok = enm:setopts(Sub2, [{active,false}]), 81 | Data = <<"some important information for subscribers">>, 82 | ok = enm:send(Pub1, Data), 83 | {ok, Data} = enm:recv(Sub1), 84 | {ok, Data} = enm:recv(Sub2), 85 | ok. 86 | 87 | two_pub() -> 88 | {ok,Sub1} = enm:sub(), 89 | ok = enm:setopts(Sub1, [{subscribe,""}]), 90 | {ok,_} = enm:bind(Sub1, ?URL), 91 | {ok,Pub1} = enm:pub(), 92 | {ok,_} = enm:connect(Pub1, ?URL), 93 | {ok,Pub2} = enm:pub(), 94 | {ok,_} = enm:connect(Pub2, ?URL), 95 | ok = two_pub_active_true(Pub1, Pub2, Sub1), 96 | ok = two_pub_active_once(Pub1, Pub2, Sub1), 97 | ok = two_pub_passive(Pub1, Pub2, Sub1), 98 | ok = enm:close(Sub1), 99 | ok = enm:close(Pub1), 100 | ok = enm:close(Pub2), 101 | ok. 102 | 103 | two_pub_active_true(Pub1, Pub2, Sub1) -> 104 | ok = enm:setopts(Sub1, [{active,true}]), 105 | ok = two_pub_active(Pub1, Pub2, Sub1), 106 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Sub1, [active])), 107 | ok. 108 | 109 | two_pub_active_once(Pub1, Pub2, Sub1) -> 110 | F = fun() -> ok = enm:setopts(Sub1, [{active,once}]), Sub1 end, 111 | ok = two_pub_active(Pub1, Pub2, F), 112 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Sub1, [active])), 113 | ok. 114 | 115 | two_pub_active(Pub1, Pub2, Sub1) -> 116 | Data = <<"some important information for subscribers">>, 117 | ok = enm:send(Pub1, Data), 118 | ok = enm:send(Pub2, Data), 119 | true = lists:all(fun(ok) -> true end, do_sub([Sub1, Sub1], Data)), 120 | ok. 121 | 122 | two_pub_passive(Pub1, Pub2, Sub1) -> 123 | ok = enm:setopts(Sub1, [{active,false}]), 124 | Data = <<"some important information for subscribers">>, 125 | ok = enm:send(Pub1, Data), 126 | ok = enm:send(Pub2, Data), 127 | {ok, Data} = enm:recv(Sub1), 128 | {ok, Data} = enm:recv(Sub1), 129 | ok. 130 | 131 | check_sub_filter() -> 132 | {ok, Pub} = enm:pub([{bind, ?URL}]), 133 | {ok, Sub} = enm:sub([{connect, ?URL}, {subscribe, "good"}]), 134 | ok = enm:send(Pub, "bad"), 135 | ok = receive 136 | Bad -> error({should_be_filtered, Bad}) 137 | after 138 | 2000 -> 139 | ok 140 | end, 141 | Good = <<"good">>, 142 | ok = enm:send(Pub, Good), 143 | ok = receive 144 | {nnsub,Sub,Good} -> ok; 145 | Msg -> error({unexpected_data, Msg}) 146 | after 147 | 2000 -> 148 | error(subscriber_timeout) 149 | end, 150 | ok = enm:close(Sub), 151 | ok = enm:close(Pub), 152 | ok. 153 | 154 | do_sub(Subs, Data) -> 155 | do_sub(Subs, Data, []). 156 | do_sub([], _, Acc) -> 157 | Acc; 158 | do_sub([Sub|Subs], Data, Acc) when is_function(Sub) -> 159 | do_sub([Sub()|Subs], Data, Acc); 160 | do_sub([Sub|Subs], Data, Acc) -> 161 | receive 162 | {nnsub,Sub,Data} -> 163 | do_sub(Subs, Data, [ok|Acc]); 164 | Msg -> error({unexpected_data, Msg}) 165 | after 166 | 2000 -> 167 | error(subscriber_timeout) 168 | end. 169 | -------------------------------------------------------------------------------- /test/enm_recv.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_recv: recv tests for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_recv). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | -define(URL, #nn_inproc{addr="foo"}). 29 | 30 | recv_test_() -> 31 | {setup, 32 | fun enm:start_link/0, 33 | fun(_) -> enm:stop() end, 34 | fun() -> 35 | {ok,S} = enm:pair([{active, false}, {bind, ?URL}]), 36 | {ok,R} = enm:pair([{active, false}, {connect, ?URL}]), 37 | Self = self(), 38 | Data1 = <<"this is for receiver 1">>, 39 | Rcv1 = spawn_link(fun() -> receiver(R, Data1, Self) end), 40 | Data2 = <<"this is for receiver 2">>, 41 | Rcv2 = spawn_link(fun() -> receiver(R, Data2, Self) end), 42 | timer:sleep(500), 43 | ok = enm:send(S, Data1), 44 | ok = enm:send(S, Data2), 45 | ?assertMatch([ok,ok], [receive 46 | {Rcv1, Data1} -> ok; 47 | {Rcv2, Data2} -> ok; 48 | _ -> fail 49 | after 50 | 3000 -> timeout 51 | end || _ <- [Data1, Data2]]), 52 | ok = enm:close(R), 53 | ok = enm:close(S), 54 | ok 55 | end}. 56 | 57 | receiver(R, Data, Pid) -> 58 | ?assertMatch({ok, Data}, enm:recv(R, 2000)), 59 | Pid ! {self(), Data}, 60 | ok. 61 | -------------------------------------------------------------------------------- /test/enm_reqrep.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_reqrep: test request/reply protocol for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_reqrep). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | -define(URL, #nn_inproc{addr="test"}). 29 | 30 | reqrep_test_() -> 31 | {setup, 32 | fun enm:start_link/0, 33 | fun(_) -> enm:stop() end, 34 | [fun queuing/0, 35 | fun loadbal/0, 36 | fun resend/0, 37 | fun peer_unavailable/0, 38 | fun switch_to_peer/0]}. 39 | 40 | queuing() -> 41 | {ok, Rep1} = enm:rep([{bind, ?URL}]), 42 | {ok, Req1} = enm:req([{active,false}, {connect,?URL}]), 43 | {ok, Req2} = enm:req([{connect, ?URL}]), 44 | ?assertMatch({error, efsm}, enm:recv(Req1)), 45 | ok = reqrep_active_true(Rep1, Req1, Req2), 46 | ok = reqrep_active_once(Rep1, Req1, Req2), 47 | ok = reqrep_passive(Rep1, Req1, Req2), 48 | ok = enm:close(Rep1), 49 | ok = enm:close(Req1), 50 | ok = enm:close(Req2), 51 | ok. 52 | 53 | reqrep_active_true(Rep1, Req1, Req2) -> 54 | ok = enm:setopts(Rep1, [{active,true}]), 55 | ok = enm:setopts(Req1, [{active,true}]), 56 | ok = enm:setopts(Req2, [{active,true}]), 57 | ok = reqrep_active(Rep1, Req1, Req2), 58 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Rep1, [active])), 59 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Req1, [active])), 60 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Req2, [active])), 61 | ok. 62 | 63 | reqrep_active_once(Rep1, Req1, Req2) -> 64 | ok = enm:setopts(Rep1, [{active,true}]), 65 | ok = enm:setopts(Req1, [{active,true}]), 66 | ok = enm:setopts(Req2, [{active,true}]), 67 | FRep1 = fun() -> ok = enm:setopts(Rep1, [{active,once}]), Rep1 end, 68 | FReq1 = fun() -> ok = enm:setopts(Req1, [{active,once}]), Req1 end, 69 | FReq2 = fun() -> ok = enm:setopts(Req2, [{active,once}]), Req2 end, 70 | ok = reqrep_active(FRep1, FReq1, FReq2), 71 | ?assertMatch({ok, [{active,once}]}, enm:getopts(Rep1, [active])), 72 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Req1, [active])), 73 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Req2, [active])), 74 | ok. 75 | 76 | reqrep_active(Rep1, _Req1, Req2) -> 77 | Data = <<"reqrep active data">>, 78 | Seq = [{send,Req2}, {recv,Rep1}, {send,Rep1}, {recv,Req2}], 79 | true = lists:all(fun(ok) -> true end, do_send_recv(Seq, Data)), 80 | ok. 81 | 82 | reqrep_passive(Rep1, Req1, Req2) -> 83 | ok = enm:setopts(Rep1, [{active,false}]), 84 | ok = enm:setopts(Req1, [{active,false}]), 85 | ok = enm:setopts(Req2, [{active,false}]), 86 | Data = <<"reqrep passive data">>, 87 | ok = enm:send(Req2, Data), 88 | ?assertMatch({ok, Data}, enm:recv(Rep1)), 89 | ok = enm:send(Rep1, Data), 90 | ?assertMatch({ok, Data}, enm:recv(Req2)), 91 | ok. 92 | 93 | loadbal() -> 94 | {ok, Req1} = enm:req([{bind, ?URL}]), 95 | {ok, Rep1} = enm:rep([{connect, ?URL}]), 96 | {ok, Rep2} = enm:rep([{connect, ?URL}]), 97 | ok = loadbal_active_true(Req1, Rep1, Rep2), 98 | ok = loadbal_active_once(Req1, Rep1, Rep2), 99 | ok = loadbal_passive(Req1, Rep1, Rep2), 100 | ok = enm:close(Rep2), 101 | ok = enm:close(Rep1), 102 | ok = enm:close(Req1), 103 | ok. 104 | 105 | loadbal_active_true(Req1, Rep1, Rep2) -> 106 | ok = enm:setopts(Req1, [{active,true}]), 107 | ok = enm:setopts(Rep1, [{active,true}]), 108 | ok = enm:setopts(Rep2, [{active,true}]), 109 | ok = loadbal_active(Req1, Rep1, Rep2), 110 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Req1, [active])), 111 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Rep1, [active])), 112 | ?assertMatch({ok, [{active,true}]}, enm:getopts(Rep2, [active])), 113 | ok. 114 | 115 | loadbal_active_once(Req1, Rep1, Rep2) -> 116 | ok = enm:setopts(Req1, [{active,true}]), 117 | ok = enm:setopts(Rep1, [{active,true}]), 118 | ok = enm:setopts(Rep2, [{active,true}]), 119 | FReq1 = fun() -> ok = enm:setopts(Req1, [{active,once}]), Req1 end, 120 | FRep1 = fun() -> ok = enm:setopts(Rep1, [{active,once}]), Rep1 end, 121 | FRep2 = fun() -> ok = enm:setopts(Rep2, [{active,once}]), Rep2 end, 122 | ok = loadbal_active(FReq1, FRep1, FRep2), 123 | ?assertMatch({ok, [{active,false}]}, enm:getopts(Req1, [active])), 124 | ?assertMatch({ok, [{active,once}]}, enm:getopts(Rep1, [active])), 125 | ?assertMatch({ok, [{active,once}]}, enm:getopts(Rep2, [active])), 126 | ok. 127 | 128 | loadbal_active(Req1, Rep1, Rep2) -> 129 | Data = <<"reqrep active data">>, 130 | Seq = [{send,Req1}, {recv,Rep1}, {send,Rep1}, {recv,Req1}, 131 | {send,Req1}, {recv,Rep2}, {send,Rep2}, {recv,Req1}], 132 | true = lists:all(fun(ok) -> true end, do_send_recv(Seq, Data)), 133 | ok. 134 | 135 | loadbal_passive(Req1, Rep1, Rep2) -> 136 | ok = enm:setopts(Req1, [{active,false}]), 137 | ok = enm:setopts(Rep1, [{active,false}]), 138 | ok = enm:setopts(Rep2, [{active,false}]), 139 | Data = <<"reqrep passive data">>, 140 | ok = enm:send(Req1, Data), 141 | ?assertMatch({ok, Data}, enm:recv(Rep1)), 142 | ok = enm:send(Rep1, Data), 143 | ?assertMatch({ok, Data}, enm:recv(Req1)), 144 | ok = enm:send(Req1, Data), 145 | ?assertMatch({ok, Data}, enm:recv(Rep2)), 146 | ok = enm:send(Rep2, Data), 147 | ?assertMatch({ok, Data}, enm:recv(Req1)), 148 | ok. 149 | 150 | do_send_recv(ReqReps, Data) -> 151 | do_send_recv(ReqReps, Data, []). 152 | do_send_recv([], _, Acc) -> 153 | Acc; 154 | do_send_recv([{SR,ReqRep}|ReqReps], Data, Acc) when is_function(ReqRep) -> 155 | do_send_recv([{SR,ReqRep()}|ReqReps], Data, Acc); 156 | do_send_recv([{send,ReqRep}|ReqReps], Data, Acc) -> 157 | do_send_recv(ReqReps, Data, [enm:send(ReqRep, Data)|Acc]); 158 | do_send_recv([{recv,ReqRep}|ReqReps], Data, Acc) -> 159 | {ok, [{type,Type}]} = enm:getopts(ReqRep, [type]), 160 | receive 161 | {Type,ReqRep,Data} -> 162 | do_send_recv(ReqReps, Data, [ok|Acc]); 163 | Msg -> error({unexpected_data, Msg}) 164 | after 165 | 2000 -> 166 | error(reqrep_timeout) 167 | end. 168 | 169 | resend() -> 170 | {ok, Rep1} = enm:rep([{active,false}, {bind,?URL}]), 171 | {ok, Req1} = enm:req([{connect, ?URL}]), 172 | ResendIvl = 100, 173 | ok = enm:setopts(Req1, [{resend_ivl, ResendIvl}]), 174 | Data = <<"resend">>, 175 | ok = enm:send(Req1, Data), 176 | ?assertMatch({ok, Data}, enm:recv(Rep1)), 177 | ?assertMatch({ok, Data}, enm:recv(Rep1)), 178 | ok = enm:close(Req1), 179 | ok = enm:close(Rep1), 180 | ok. 181 | 182 | peer_unavailable() -> 183 | {ok, Req1} = enm:req([{connect, ?URL}]), 184 | Data = <<"peer unavailable">>, 185 | ok = enm:send(Req1, Data), 186 | {ok, Rep1} = enm:rep([{active,false}]), 187 | {ok, _} = enm:bind(Rep1, ?URL), 188 | Timeout = 200, 189 | ?assertMatch({ok, Data}, enm:recv(Rep1, Timeout)), 190 | ok = enm:close(Rep1), 191 | ok = enm:close(Req1), 192 | ok. 193 | 194 | switch_to_peer() -> 195 | {ok, Req1} = enm:req([{bind, ?URL}]), 196 | {ok, Rep1} = enm:rep([{active,false}, {connect, ?URL}]), 197 | {ok, Rep2} = enm:rep([{active,false}, {connect, ?URL}]), 198 | Timeout = 200, 199 | Data = <<"switch to other peer">>, 200 | ok = enm:send(Req1, Data), 201 | ?assertMatch({ok, Data}, enm:recv(Rep1, Timeout)), 202 | ok = enm:close(Rep1), 203 | ?assertMatch({ok, Data}, enm:recv(Rep2, Timeout)), 204 | ok = enm:send(Rep2, "reply"), 205 | ok = receive 206 | {nnreq, Req1, <<"reply">>} -> 207 | ok; 208 | Msg -> 209 | error({unexpected_reply, Msg}) 210 | after 211 | 1000 -> 212 | error(reply_timeout) 213 | end, 214 | ok. 215 | -------------------------------------------------------------------------------- /test/enm_send.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_send: send tests for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_send). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | %% 29 | %% TODO: nanomsg currently ignores the sndbuf option for the inproc 30 | %% transport, and it defaults the send buffer size to 128k even though 31 | %% setting sndbuf appears to work. This test therefore won't pass with the 32 | %% inproc transport unless we send chunks larger than 128k and set the 33 | %% receiver's rcvbuf to a small value. 34 | %% 35 | %% Using the TCP transport instead of inproc makes this test work as 36 | %% expected, since sndbuf works for that transport, but because nanomsg 37 | %% requires fixed ports and doesn't support ephemeral ports, using TCP for 38 | %% any test is problematic given the chance of port clashes. 39 | %% 40 | -define(URL, #nn_inproc{addr="foo"}). 41 | -define(SNDBUF, 1024*128). 42 | 43 | suspend_test_() -> 44 | {setup, 45 | fun enm:start_link/0, 46 | fun(_) -> enm:stop() end, 47 | fun() -> 48 | {ok,S} = enm:pair([{active,false},{bind,?URL},{rcvbuf,1}]), 49 | {ok,R} = enm:pair([{sndbuf,?SNDBUF},{connect,?URL}]), 50 | Data = lists:duplicate(?SNDBUF*2, $X), 51 | ok = enm:send(R, Data), 52 | ok = enm:send(R, Data), 53 | ok = enm:send(R, Data), 54 | ?assertMatch(false,port_command(R,Data,[nosuspend])), 55 | ok = enm:setopts(S, [{rcvbuf,?SNDBUF}]), 56 | clear_receiver(S), 57 | ?assertMatch(true,port_command(R,Data,[nosuspend])), 58 | ok = enm:close(R), 59 | ok = enm:close(S), 60 | ok 61 | end}. 62 | 63 | clear_receiver(S) -> 64 | case enm:recv(S, 500) of 65 | {ok,_} -> 66 | clear_receiver(S); 67 | {error,etimedout} -> 68 | ok 69 | end. 70 | 71 | empty_send_test_() -> 72 | {setup, 73 | fun enm:start_link/0, 74 | fun(_) -> enm:stop() end, 75 | fun() -> 76 | {ok,S} = enm:pair([{bind,?URL},{active,false}]), 77 | {ok,R} = enm:pair([{connect,?URL}]), 78 | %% sending an empty iolist should result in no data arriving 79 | %% at the receiver 80 | ok = enm:send(R, <<>>), 81 | ?assertMatch({error,etimedout},enm:recv(S,100)), 82 | ok = enm:close(R), 83 | ok = enm:close(S), 84 | ok 85 | end}. 86 | -------------------------------------------------------------------------------- /test/enm_start_stop.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_start_stop: start/stop tests for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_start_stop). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | 27 | start_stop_test() -> 28 | {ok,_} = enm:start(), 29 | ok = enm:stop(), 30 | {ok,_} = enm:start_link(), 31 | ok = enm:stop(), 32 | ok. 33 | -------------------------------------------------------------------------------- /test/enm_survey.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% enm_survey: test surveyor/respondent protocols for enm 4 | %% 5 | %% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. 6 | %% 7 | %% This file is provided to you under the Apache License, 8 | %% Version 2.0 (the "License"); you may not use this file 9 | %% except in compliance with the License. You may obtain 10 | %% a copy of the License at 11 | %% 12 | %% http://www.apache.org/licenses/LICENSE-2.0 13 | %% 14 | %% Unless required by applicable law or agreed to in writing, 15 | %% software distributed under the License is distributed on an 16 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | %% KIND, either express or implied. See the License for the 18 | %% specific language governing permissions and limitations 19 | %% under the License. 20 | %% 21 | %% ------------------------------------------------------------------- 22 | -module(enm_survey). 23 | -compile(export_all). 24 | 25 | -include_lib("eunit/include/eunit.hrl"). 26 | -include("../include/enm.hrl"). 27 | 28 | surveyor_test_() -> 29 | {setup, 30 | fun enm:start_link/0, 31 | fun(_) -> enm:stop() end, 32 | fun surveyor/0}. 33 | 34 | surveyor() -> 35 | Url = #nn_inproc{addr="foo"}, 36 | Req = <<"abcdefghijklm">>, 37 | Rep = <<"nopqrstuvwxyz">>, 38 | Deadline = 5000, 39 | {ok, S} = enm:surveyor([{deadline,Deadline}]), 40 | {ok, [{deadline,Deadline}]} = enm:getopts(S, [deadline]), 41 | {ok, _} = enm:bind(S, Url), 42 | Resp = lists:seq(1,3), 43 | Self = self(), 44 | [spawn_link(?MODULE,respondent,[Url,Req,Rep,Self]) || _ <- Resp], 45 | [receive respondent_ready -> ok end || _ <- Resp], 46 | ok = enm:send(S, Req), 47 | ok = enm:setopts(S, [{active,true}]), 48 | true = lists:all(fun(ok) -> true end, collect(S, Rep, length(Resp))), 49 | ok = enm:close(S), 50 | ok. 51 | 52 | respondent(Url, Req, Rep, Pid) -> 53 | {ok, R} = enm:respondent(), 54 | {ok, _} = enm:connect(R, Url), 55 | Pid ! respondent_ready, 56 | ok = receive 57 | {nnrespondent, R, Req} -> 58 | ok = enm:send(R, Rep), 59 | timer:sleep(1000), 60 | enm:close(R); 61 | Request -> 62 | error({unexpected_request, Request}) 63 | after 64 | 2000 -> 65 | error(respondent_timeout) 66 | end. 67 | 68 | collect(S, Rep, Count) -> 69 | collect(S, Rep, Count, []). 70 | collect(_, _, 0, Acc) -> 71 | Acc; 72 | collect(S, Rep, Count, Acc) -> 73 | ok = receive 74 | {nnsurveyor,S,Rep} -> 75 | ok; 76 | {nnsurveyor_deadline,S} -> 77 | ok; 78 | Reply -> 79 | error({unexpected_reply,Reply}) 80 | after 81 | 3500 -> 82 | error(surveyor_timeout) 83 | end, 84 | collect(S, Rep, Count-1, [ok|Acc]). 85 | -------------------------------------------------------------------------------- /tools.mk: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------- 2 | # 3 | # Copyright (c) 2014 Basho Technologies, Inc. 4 | # 5 | # This file is provided to you under the Apache License, 6 | # Version 2.0 (the "License"); you may not use this file 7 | # except in compliance with the License. You may obtain 8 | # a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, 13 | # software distributed under the License is distributed on an 14 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | # KIND, either express or implied. See the License for the 16 | # specific language governing permissions and limitations 17 | # under the License. 18 | # 19 | # ------------------------------------------------------------------- 20 | 21 | # ------------------------------------------------------------------- 22 | # NOTE: This file is is from https://github.com/basho/tools.mk. 23 | # It should not be edited in a project. It should simply be updated 24 | # wholesale when a new version of tools.mk is released. 25 | # ------------------------------------------------------------------- 26 | 27 | REBAR ?= $(shell command -v rebar3 2>/dev/null) 28 | REVISION ?= $(shell git rev-parse --short HEAD) 29 | PROJECT ?= $(shell basename `find src -name "*.app.src"` .app.src) 30 | 31 | .PHONY: compile-no-deps test docs xref dialyzer-run dialyzer-quick dialyzer \ 32 | cleanplt upload-docs 33 | 34 | compile-no-deps: 35 | $(REBAR) compile skip_deps=true 36 | 37 | test: compile 38 | $(REBAR) eunit skip_deps=true 39 | 40 | upload-docs: docs 41 | @if [ -z "${BUCKET}" -o -z "${PROJECT}" -o -z "${REVISION}" ]; then \ 42 | echo "Set BUCKET, PROJECT, and REVISION env vars to upload docs"; \ 43 | exit 1; fi 44 | @cd doc; s3cmd put -P * "s3://${BUCKET}/${PROJECT}/${REVISION}/" > /dev/null 45 | @echo "Docs built at: http://${BUCKET}.s3-website-us-east-1.amazonaws.com/${PROJECT}/${REVISION}" 46 | 47 | docs: 48 | $(REBAR) doc skip_deps=true 49 | 50 | xref: compile 51 | $(REBAR) xref skip_deps=true 52 | 53 | PLT ?= $(HOME)/.combo_dialyzer_plt 54 | LOCAL_PLT = .local_dialyzer_plt 55 | DIALYZER_FLAGS ?= -Wunmatched_returns 56 | 57 | $(PLT): compile 58 | @if [ -f $(PLT) ]; then \ 59 | dialyzer --check_plt --plt $(PLT) --apps $(DIALYZER_APPS) && \ 60 | dialyzer --add_to_plt --plt $(PLT) --output_plt $(PLT) --apps $(DIALYZER_APPS) ; test $$? -ne 1; \ 61 | else \ 62 | dialyzer --build_plt --output_plt $(PLT) --apps $(DIALYZER_APPS); test $$? -ne 1; \ 63 | fi 64 | 65 | $(LOCAL_PLT): compile 66 | @if [ -d deps ]; then \ 67 | if [ -f $(LOCAL_PLT) ]; then \ 68 | dialyzer --check_plt --plt $(LOCAL_PLT) _build/default/plugins/*/ebin && \ 69 | dialyzer --add_to_plt --plt $(LOCAL_PLT) --output_plt $(LOCAL_PLT) _build/default/plugins/*/ebin ; \ 70 | test $$? -ne 1; \ 71 | else \ 72 | dialyzer --build_plt --output_plt $(LOCAL_PLT) _build/default/plugins/*/ebin ; test $$? -ne 1; \ 73 | fi \ 74 | fi 75 | 76 | dialyzer-run: 77 | @echo "==> $(shell basename $(shell pwd)) (dialyzer)" 78 | # The bulk of the code below deals with the dialyzer.ignore-warnings file 79 | # which contains strings to ignore if output by dialyzer. 80 | # Typically the strings include line numbers. Using them exactly is hard 81 | # to maintain as the code changes. This approach instead ignores the line 82 | # numbers, but takes into account the number of times a string is listed 83 | # for a given file. So if one string is listed once, for example, and it 84 | # appears twice in the warnings, the user is alerted. It is possible but 85 | # unlikely that this approach could mask a warning if one ignored warning 86 | # is removed and two warnings of the same kind appear in the file, for 87 | # example. But it is a trade-off that seems worth it. 88 | # Details of the cryptic commands: 89 | # - Remove line numbers from dialyzer.ignore-warnings 90 | # - Pre-pend duplicate count to each warning with sort | uniq -c 91 | # - Remove annoying white space around duplicate count 92 | # - Save in dialyer.ignore-warnings.tmp 93 | # - Do the same to dialyzer_warnings 94 | # - Remove matches from dialyzer.ignore-warnings.tmp from output 95 | # - Remove duplicate count 96 | # - Escape regex special chars to use lines as regex patterns 97 | # - Add pattern to match any line number (file.erl:\d+:) 98 | # - Anchor to match the entire line (^entire line$) 99 | # - Save in dialyzer_unhandled_warnings 100 | # - Output matches for those patterns found in the original warnings 101 | @if [ -f $(LOCAL_PLT) ]; then \ 102 | PLTS="$(PLT) $(LOCAL_PLT)"; \ 103 | else \ 104 | PLTS=$(PLT); \ 105 | fi; \ 106 | if [ -f dialyzer.ignore-warnings ]; then \ 107 | if [ $$(grep -cvE '[^[:space:]]' dialyzer.ignore-warnings) -ne 0 ]; then \ 108 | echo "ERROR: dialyzer.ignore-warnings contains a blank/empty line, this will match all messages!"; \ 109 | exit 1; \ 110 | fi; \ 111 | dialyzer $(DIALYZER_FLAGS) --plts $${PLTS} -c _build/default/lib/enm/ebin > dialyzer_warnings ; \ 112 | cat dialyzer.ignore-warnings \ 113 | | sed -E 's/^([^:]+:)[^:]+:/\1/' \ 114 | | sort \ 115 | | uniq -c \ 116 | | sed -E '/.*\.erl: /!s/^[[:space:]]*[0-9]+[[:space:]]*//' \ 117 | > dialyzer.ignore-warnings.tmp ; \ 118 | egrep -v "^[[:space:]]*(done|Checking|Proceeding|Compiling)" dialyzer_warnings \ 119 | | sed -E 's/^([^:]+:)[^:]+:/\1/' \ 120 | | sort \ 121 | | uniq -c \ 122 | | sed -E '/.*\.erl: /!s/^[[:space:]]*[0-9]+[[:space:]]*//' \ 123 | | grep -F -f dialyzer.ignore-warnings.tmp -v \ 124 | | sed -E 's/^[[:space:]]*[0-9]+[[:space:]]*//' \ 125 | | sed -E 's/([]\^:+?|()*.$${}\[])/\\\1/g' \ 126 | | sed -E 's/(\\\.erl\\\:)/\1\\d+:/g' \ 127 | | sed -E 's/^(.*)$$/^\1$$/g' \ 128 | > dialyzer_unhandled_warnings ; \ 129 | rm dialyzer.ignore-warnings.tmp; \ 130 | if [ $$(cat dialyzer_unhandled_warnings | wc -l) -gt 0 ]; then \ 131 | egrep -f dialyzer_unhandled_warnings dialyzer_warnings ; \ 132 | found_warnings=1; \ 133 | fi; \ 134 | [ "$$found_warnings" != 1 ] ; \ 135 | else \ 136 | dialyzer $(DIALYZER_FLAGS) --plts $${PLTS} -c _build/default/lib/enm/ebin; \ 137 | fi 138 | 139 | dialyzer-quick: compile-no-deps dialyzer-run 140 | 141 | dialyzer: $(PLT) $(LOCAL_PLT) dialyzer-run 142 | 143 | cleanplt: 144 | @echo 145 | @echo "Are you sure? It takes several minutes to re-build." 146 | @echo Deleting $(PLT) and $(LOCAL_PLT) in 5 seconds. 147 | @echo 148 | sleep 5 149 | rm $(PLT) 150 | rm $(LOCAL_PLT) 151 | --------------------------------------------------------------------------------