diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d5f2fd7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: erlang +otp_release: + - 18.1 +script: "./rebar3 eunit" +notifications: + slack: cytoscape:jnbsb3KMMTjJtFBGKWYPPn6t diff --git a/DATABASE/.gitkeep b/DATABASE/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c8b1453 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM erlang + +ADD . /elsa +WORKDIR /elsa + +RUN mv /elsa/config/sys.config.docker /elsa/config/sys.config + +RUN /elsa/rebar3 release + +ENTRYPOINT ["/elsa/_build/default/rel/elsa/bin/elsa"] + +EXPOSE 8080 +CMD ["foreground"] diff --git a/Dockerfile.develop b/Dockerfile.develop new file mode 100644 index 0000000..6e18043 --- /dev/null +++ b/Dockerfile.develop @@ -0,0 +1,13 @@ +FROM erlang + +ADD . /elsa +WORKDIR /elsa + +RUN mv /elsa/config/sys.config.docker /elsa/config/sys.config + +RUN /elsa/rebar3 compile + +ENTRYPOINT ["/elsa/rebar3"] + +EXPOSE 8080 +CMD ["shell'] diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..02bbb60 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..700be38 --- /dev/null +++ b/README.md @@ -0,0 +1,109 @@ +ELSA: The ErLang Submit Agent +===== + +[![Build Status](https://travis-ci.org/cytoscape-ci/elsa.svg)](https://travis-ci.org/cytoscape-ci/elsa) [![GitHub version](https://badge.fury.io/gh/cytoscape-ci%2Felsa.svg)](https://badge.fury.io/gh/cytoscape-ci%2Felsa) + +This node connects clients and services running across a network, and provides a mechanism for handling long running services. Elsa nodes connect together to form a relay network, where client calls route to agents that have the required services to fufill their request. For services that take longer than the tolerated time of the client, responses enter a buffer that the agent handles, and await client pickup at a later time. Please see below for instructions on how to deploy an agent, make calls through the agent as a client, and register with an agent as a service. + +Getting Started +----- + +Elsa uses Docker Hub automated builds for production use: [Elsa on Docker Hub](https://hub.docker.com/r/cytoscape/elsa). + +You will need a Docker daemon to deploy the agent. Once you have docker installed, run: + +``` docker run -p 8080:8080 cytoscape/elsa #Runs elsa in a container on port 8080 ``` + +This will bring up the agent on port 8080. Services and clients can now use the agent. + +Releases and Production Deployments +----- +Releases are built automatically using Docker Hub automated builds. Images follow a master and tag scheme: + +``` +docker run cytoscape/elsa:latest #Run the container built off of master's last commit. Same as cytoscape/elsa with no tag. +docker run cytoscape/elsa:tag #Where tag is a release tag such as cytoscape/elsa:v0.1.0 for the v0.1.0 version of elsa. +``` + +For maximum stabability in production deployments, use a version tag. For the latest features and bug fixs, use the latest tag. You can also build your own release of elsa using the primary Dockerfile: + +``` +docker build -t elsa . +``` + +Clients +----- + +####Request + +A client can reach a registered service by calling: + +``` www.domain.com:port/service/version/endpoint ``` + +For example, with an agent connect to port 8080 on an instance called elsa, and trying to reach version one of the service test's status endpoint the call would look like this: + +``` curl http://elsa:8080/test/v1/status ``` + +####Response + +A client may include an optional *X-ELSA-TIMEOUT* header in the request. If the service responds within a number of milliseconds specified in this header, the client will receive its data as it normally would as though it had called the service directly. This field defaults to 5 seconds. + +If the service misses the timeout window, the agent sends back a 300 status code and a url that the client may check periodically to retrieve its data. When it quieries this url, it will receive one of the following: + +``` + 404 - Task not found. #The task either failed to complete, or the task does not exist. + 204 - Task not yet completed. Please try again later. #The agent still awaits data from the service. Retry later. + 200 #Your task completed successfully, this response contains the response of the service. +``` + +Services +----- +A service must send a JSON document called it's registration to an agent in order to receive forwarded calls from clients. When a service shuts down, it should then send its registration to the agent with a DELETE request: + +``` +POST elsa:8080/registration #Registers the instance if its registration document is valid. +DELETE elsa:8080/registration #Unregisters the instance if its registration document is valid. + +``` + +For the format of a registration document, please reference the [registration](https://github.com/cytoscape-ci/elsa/blob/master/REGISTRATION.md) spec. + + +Development +------ +You can develop through either docker or by running the agent on an Erlang virtual machine. + +####Erlang Virtual Machine Development +First install the latest version of the Erlang virtual machine. Clone the repo, and then use the rebar3 script to +develop with the agent: + +``` +git clone https://github.com/cytoscape-ci/elsa.git && cd elsa + + ./rebar3 shell #Run elsa in an interactive shell. + ./rebar3 eunit #Run the eunit test framework + ./rebar3 release #Create a release of elsa + +``` + +####Docker Container Development + +To develop in a container, you should build your changes with the devleopment Dockerfile: + +``` +docker build -f Dockerfile.develop -t elsa . +``` + +You can then run any rebar3 command by appending it to docker run like so: + +``` +docker run -it elsa shell #Equivelant to ./rebar3 shell +``` + +Contributing +------ +Contributions are welcome in the form of issues or pull requests. For code changes, please submit unit tests in the tests directory. These tests may either use Common Test or Eunit. + +Licensing +========= +You can find the LGPL License for elsa [here](https://github.com/cytoscape-ci/elsa/blob/master/LICENSE.txt). diff --git a/REGISTRATION.md b/REGISTRATION.md new file mode 100644 index 0000000..d4e5f27 --- /dev/null +++ b/REGISTRATION.md @@ -0,0 +1,87 @@ +Registration +===== + +There are three primary fields: + +- service: The name of the service as a string +- version: The version of the service API as a string, should be of the form ("v1", "v2", "vN"...) +- instances: An list containing instance objects + +An instance object has two fields +- location: This should be a domain name or ip address. http:// will be appended if +the protocol is not specified. This will also make the default port 80. +- capacity: An integer or the string "infinity", this tells the agent how many concurrent +requests your service can handle. Infinity means that your service can handle an unlimited +number of concurrent connections. + +This is a minimum registration document. +----- + +```json +{ + "service": "service1", + "version": "v1", + "instances": [ + { + "location": "https://1.1.1.1:8080", + "capacity": "infinity" + } + ] +} +``` + +One service with multiple instances. +----- + +```json +{ + "service": "service1", + "version": "v1", + "instances": [ + { + "capacity": "1.1.1.1", + "capacity": "infinity" + }, + { + "location": "1.1.1.2", + "capacity": 44 + } + ] +} +``` + +Multiple service versions (or services) with multiple instances. +---- + +```json +[ + { + "service": "service1", + "version": "v1", + "instances": [ + { + "location": "1.1.1.1:3000", + "capacity": "infinity" + }, + { + "location": "1.1.1.2", + "capacity": 44 + } + ] + }, + { + "service": "service2", + "version": "v1", + "instances": [ + { + "location": "1.1.1.6", + "capacity": "infinity" + }, + { + "location": "1.1.1.9:80", + "capacity": 44 + } + ] + } +] +``` diff --git a/apps/elsa/src/elsa.app.src b/apps/elsa/src/elsa.app.src new file mode 100644 index 0000000..56e568d --- /dev/null +++ b/apps/elsa/src/elsa.app.src @@ -0,0 +1,20 @@ +{application, 'elsa', + [{description, "An OTP application"}, + {vsn, "0.1.0"}, + {registered, []}, + {mod, {'elsa_app', []}}, + {applications, + [kernel, + stdlib, + cowboy, + mnesia, + inets, + lager + ]}, + {env,[]}, + {modules, []}, + + {contributors, []}, + {licenses, []}, + {links, []} + ]}. diff --git a/apps/elsa/src/elsa_app.erl b/apps/elsa/src/elsa_app.erl new file mode 100644 index 0000000..0c1f171 --- /dev/null +++ b/apps/elsa/src/elsa_app.erl @@ -0,0 +1,35 @@ + +-module(elsa_app). + +-behaviour(application). + +-export([start/2 + ,stop/1]). + +start(_StartType, _StartArgs) -> + lager:info("Starting ELSA."), + lager:info("Setting up database."), + database_setup([node()]), + lager:info("Starting router."), + elsa_router:start(), + lager:info("Router started."), + lager:info("Starting ELSA supervisor."), + 'elsa_sup':start_link(). + +stop(_State) -> + database_teardown([node()]), + ok. + +database_setup(Nodes) -> + mnesia:stop(), + case mnesia:create_schema([node()]) of + ok -> lager:info("Schema created."); + {error, Reason} -> lager:error("Error while creating schema: ~w", [Reason]) + end, + mnesia:start(), + rpc:multicall(Nodes, application, start, [mnesia]), + lager:info("Mnesia started."). + +database_teardown(Nodes) -> + rpc:multicall(Nodes, application, stop, [mnesia]), + lager:info("Mnesia stopped."). diff --git a/apps/elsa/src/elsa_registry.erl b/apps/elsa/src/elsa_registry.erl new file mode 100644 index 0000000..a26d038 --- /dev/null +++ b/apps/elsa/src/elsa_registry.erl @@ -0,0 +1,87 @@ + +-module(elsa_registry). + +-export([register/1, + unregister/1, + checkout/1, + checkin/2]). + +-record(registration, {name, version, instances}). +-record(instance, {location, capacity}). + +register([Service|_] = Registration) when is_list(Service) -> + [register(S) || S <- Registration]; + +register(Registration) -> + lager:info("Registering ~p", [Registration]), + Reg = service(Registration), + Service = get_service_name(Reg#registration.version, Reg#registration.name), + case elsa_service_worker:find(Service) of + undefined -> + elsa_service_worker_sup:start_child(Service), + register_instances(Service, Reg#registration.instances); + _ -> + register_instances(Service, Reg#registration.instances) + end. + +register_instances(Service, Instances) -> + [elsa_service_worker:register(Service, I#instance.location, I#instance.capacity) || I <- Instances]. + +unregister([Service|_] = Registration) when is_list(Service) -> + [elsa_registry:unregister(S) || S <- Registration]; + +unregister(Registration) -> + lager:info("Unregistering ~p", [Registration]), + Reg = service(Registration), + Service = get_service_name(Reg#registration.version, Reg#registration.name), + case elsa_service_worker:find(Service) of + undefined -> + elsa_service_worker_sup:start_child(Service), + unregister_instances(Service, Reg#registration.instances); + _ -> + unregister_instances(Service, Reg#registration.instances) + end. + +unregister_instances(Service, Instances) -> + [elsa_service_worker:unregister(Service, I#instance.location) || I <- Instances]. + +checkout(Service) -> + lager:info("Checking out instance of service: ~w", [Service]), + case elsa_service_worker:find(Service) of + undefined -> + elsa_service_worker_sup:start_child(Service), + elsa_service_worker:checkout(Service); + _ -> + elsa_service_worker:checkout(Service) + end. + +checkin(Service, Instance) -> + lager:info("Checking in instance of service: ~w", [Service]), + case elsa_service_worker:find(Service) of + undefined -> + elsa_service_worker_sup:start_child(Service), + elsa_service_worker:checkin(Service, Instance); + _ -> + elsa_service_worker:checkin(Service, Instance) + end. + +service(Service) -> + #registration{ + name=proplists:get_value(<<"service">>, Service), + version=proplists:get_value(<<"version">>, Service), + instances=[instance(I) || I <- proplists:get_value(<<"instances">>, Service)] + }. + +instance(Instance) -> + #instance{ + location=proplists:get_value(<<"location">>, Instance), + capacity=capacity(proplists:get_value(<<"capacity">>, Instance)) + }. + +capacity(Capacity) when is_binary(Capacity) -> + infinity; +capacity(Capacity) -> + Capacity. + +get_service_name(Version, Name) -> + list_to_binary([Version, Name]). diff --git a/apps/elsa/src/elsa_router.erl b/apps/elsa/src/elsa_router.erl new file mode 100644 index 0000000..07fc371 --- /dev/null +++ b/apps/elsa/src/elsa_router.erl @@ -0,0 +1,21 @@ + +-module(elsa_router). + +-export([start/0 + ]). + +start() -> + {ok, _} = cowboy:start_http(my_http_listener, 100, [{port, 8080}], + [{env, [{dispatch, dispatch()}]}] + ). + +dispatch() -> + Host = '_', + lager:info("Compiling routes."), + cowboy_router:compile([ + {Host, [ + {"/task/:id", elsa_task_handler, []}, + {"/registration/[...]", elsa_registration_handler, []}, + {"/:service/:version/[...]", elsa_service_handler, []} + ]} + ]). diff --git a/apps/elsa/src/elsa_sup.erl b/apps/elsa/src/elsa_sup.erl new file mode 100644 index 0000000..a540ff7 --- /dev/null +++ b/apps/elsa/src/elsa_sup.erl @@ -0,0 +1,27 @@ + +-module(elsa_sup). +-behaviour(supervisor). + +-export([start_link/0 + ]). + +-export([init/1 + ]). + +-define(SUPERVISOR, ?MODULE). +-define(CHILD(Mod, Restart, Type), + {Mod, {Mod, start_link, []}, Restart, 1000, Type, [Mod]}). + +start_link() -> + lager:info("ELSA supervisor started."), + supervisor:start_link({local, ?SUPERVISOR}, ?SUPERVISOR, []). + +init([]) -> + Sup_flags = #{ + strategy => one_for_one + }, + Supervisors = [ + ?CHILD(elsa_service_worker_sup, permanent, supervisor), + ?CHILD(elsa_task_worker_sup, permanent, supervisor) + ], + {ok, {Sup_flags, Supervisors}}. diff --git a/apps/elsa/src/elsa_task.erl b/apps/elsa/src/elsa_task.erl new file mode 100644 index 0000000..da068ce --- /dev/null +++ b/apps/elsa/src/elsa_task.erl @@ -0,0 +1,33 @@ + +-module(elsa_task). + +-export([status/1, + store_data/2, + data/1, + get_id/1 + ]). + +status(ID) -> + lager:info("Checking status of task: ~p", [ID]), + case elsa_task_worker:find(ID) of + undefined -> + not_found; + _ -> + check_data(elsa_task_worker:get_data(ID)) + end. + +check_data(incomplete) -> + incomplete; +check_data(_Data) -> + complete. + +store_data(ID, Data) -> + lager:info("Storing data for task: ~w", [ID]), + elsa_task_worker:store_data(ID, Data). + +data(ID) -> + lager:info("Retreiving data for task: ~w", [ID]), + elsa_task_worker:get_data(ID). + +get_id(Task) when is_pid(Task) -> + base16:encode(crypto:hash(sha256, pid_to_list(Task))). diff --git a/apps/elsa/src/handlers/elsa_handler.erl b/apps/elsa/src/handlers/elsa_handler.erl new file mode 100644 index 0000000..5399a09 --- /dev/null +++ b/apps/elsa/src/handlers/elsa_handler.erl @@ -0,0 +1,38 @@ + +-module(elsa_handler). + +-export([reply/3, + from_json/1, + to_json/1, + has_body/1, + check_json/1, + schema/1 + ]). + +reply(Code, Body, Req) -> + {ok, Reply} = cowboy_req:reply(Code, [], to_json(Body), Req), + Reply. + +from_json(Request) -> + {ok, JSON, Req} = cowboy_req:body(Request), + Body = try jsx:decode(JSON) + catch error:badarg -> invalid_json + end, + {Req, Body}. + +check_json(Request) -> + {_Req, Body} = from_json(Request), + case Body of + invalid_json -> invalid_json; + _ -> valid_json + end. + +to_json(Response) -> + jsx:encode(Response). + +has_body(_Req) -> + true. + +%% HERE IS WHERE WE CAN ADD SCHEMA VALIDATION. +schema(_Req) -> + valid_schema. diff --git a/apps/elsa/src/handlers/elsa_registration_handler.erl b/apps/elsa/src/handlers/elsa_registration_handler.erl new file mode 100644 index 0000000..3d8a437 --- /dev/null +++ b/apps/elsa/src/handlers/elsa_registration_handler.erl @@ -0,0 +1,50 @@ + +-module(elsa_registration_handler). + +-export([init/3, + handle/2, + terminate/3 + ]). + +init({tcp, http}, Req, State) -> + lager:info("Received registration request: ~p", [Req]), + {ok, Req, State}. + +handle(Req, State) -> + process(Req, State). + +terminate(_Reason, _Req, _State) -> + ok. + +%% Validate and Process the Update. + +process(Req, State) -> + validate(Req, State, elsa_handler:has_body(Req)). + +validate(Req, State, true) -> + validate(Req, State, elsa_handler:check_json(Req)); +validate(Req, State, false) -> + lager:error("Client sent empty registration request: ~p", [Req]), + {ok, elsa_handler:reply(400, <<"Missing Body">>, Req), State}; + +validate(Req, State, valid_json) -> + validate(Req, State, elsa_handler:schema(Req)); +validate(Req, State, invalid_json) -> + lager:info("Client sent invalid JSON in registration request: ~p", [Req]), + {ok, elsa_handler:reply(422, <<"Not valid JSON">>, Req), State}; + +validate(Req, State, valid_schema) -> + update(Req, State); +validate(Req, State, invalid_schema) -> + lager:info("Client sent an invalid registration format in registration request: ~p", [Req]), + {ok, elsa_handler:reply(422, <<"Schema does not match">>, Req), State}. + +update(Req, State) -> + {Request, Body} = elsa_handler:from_json(Req), + case cowboy_req:method(Request) of + {<<"POST">>, _} -> + elsa_registry:register(Body); + {<<"DELETE">>, _} -> + elsa_registry:unregister(Body) + end, + {ok, elsa_handler:reply(200, <<"OK.">>, Request), State}. diff --git a/apps/elsa/src/handlers/elsa_service_handler.erl b/apps/elsa/src/handlers/elsa_service_handler.erl new file mode 100644 index 0000000..4b870a0 --- /dev/null +++ b/apps/elsa/src/handlers/elsa_service_handler.erl @@ -0,0 +1,51 @@ + +-module(elsa_service_handler). + +-export([init/3, + handle/2, + terminate/3 + ]). + +init({tcp, http}, Req, _Opts) -> + lager:info("Service request received: ~p", [Req]), + {ok, Req, undefined}. + +handle(Req, State) -> + {Version, Req1} = cowboy_req:binding(version, Req), + {Name, Req2} = cowboy_req:binding(service, Req1), + {Endpoint, Req3} = cowboy_req:path(Req2), + {Timeout, Req4} = cowboy_req:header(<<"x-elsa-timeout">>, Req3, <<"5000">>), + {Method, Req5} = cowboy_req:method(Req4), + {Body, Request} = body(Req5), + {Status, Response} = elsa_task_monitor:start(convert(Method), Name, Version, truncate(Version, Name, Endpoint), Body, binary_to_integer(Timeout)), + {ok, elsa_handler:reply(Status, Response, Request), State}. + +terminate(_Reason, _Req, _State) -> + ok. + +body(Request) -> + case elsa_handler:has_body(Request) of + true -> + {ok, JSON, Req} = cowboy_req:body(Request), + {JSON, Req}; + false -> + {"", Request} + end. + +truncate(Version, Name, Endpoint) -> + Vlength = length(binary_to_list(Version)), + Nlength = length(binary_to_list(Name)), + list_to_binary(string:sub_string(binary_to_list(Endpoint), (3 + Vlength + Nlength))). + +convert(<<"GET">>) -> + get; +convert(<<"POST">>) -> + post; +convert(<<"PUT">>) -> + put; +convert(<<"DELETE">>) -> + delete; +convert(<<"PATCH">>) -> + patch; +convert(<<"OPTIONS">>) -> + options. diff --git a/apps/elsa/src/handlers/elsa_task_handler.erl b/apps/elsa/src/handlers/elsa_task_handler.erl new file mode 100644 index 0000000..3d527a2 --- /dev/null +++ b/apps/elsa/src/handlers/elsa_task_handler.erl @@ -0,0 +1,34 @@ + +-module(elsa_task_handler). + +-export([init/3, + handle/2, + terminate/3 + ]). + +init({tcp, http}, Req, State) -> + lager:info("Received task request: ~p", [Req]), + {ok, Req, State}. + +handle(Req, _State) -> + {ID, Request} = cowboy_req:binding(id, Req), + process(Request, ID). + +terminate(_Reason, _Req, _State) -> + ok. + +process(Req, ID) -> + validate(Req, ID, elsa_task:status(ID)). + +validate(Req, ID, complete) -> + lager:info("Client requested completed task: ~p", [ID]), + send(Req, ID); +validate(Req, ID, incomplete) -> + lager:info("Client requested task that is not yet complete: ~p", [ID]), + {ok, elsa_handler:reply(204, <<"Task not yet completed. Please try again later.">>, Req), ID}; +validate(Req, ID, not_found) -> + lager:error("Client requested task that does not exist: ~p", [ID]), + {ok, elsa_handler:reply(404, <<"Task not found.">>, Req), ID}. + +send(Req, ID) -> + {ok, elsa_handler:reply(200, elsa_task:data(ID), Req), ID}. diff --git a/apps/elsa/src/monitors/elsa_task_monitor.erl b/apps/elsa/src/monitors/elsa_task_monitor.erl new file mode 100644 index 0000000..a794187 --- /dev/null +++ b/apps/elsa/src/monitors/elsa_task_monitor.erl @@ -0,0 +1,63 @@ + +-module(elsa_task_monitor). + +-export([start/6, + request/5 + ]). + +start(Method, Name, Version, Endpoint, Body, Timeout) -> + lager:info("Request method: ~s, service: ~s, version: ~s, endpoint: ~s created.", [Method, Name, Version, Endpoint]), + Service = concat(Version, Name), + timeout(Method, Service, Endpoint, Body, Timeout). + +timeout(Method, Service, Endpoint, Body, Timeout) -> + Conn = spawn_link(?MODULE, request, [self(), Method, Service, Body, Endpoint]), + receive + Msg -> Msg, + {200, Msg} + after Timeout -> + elsa_task_worker_sup:start_child(self()), + Conn ! {timeout, self()}, + {300, concat(<<"http://localhost:8080/task/">>, elsa_task:get_id(self()))} + end. + +request(Monitor, Method, Service, Body, Endpoint) -> + Instance = wait_for_instance(Service), + URL = validate(concat(Instance, Endpoint)), + _Header = [], + Type = "application/json", + DATA = request(Method, URL, Body, Type), + receive + {timeout, PID} -> elsa_task:store_data(elsa_task:get_id(PID), DATA) + after 0 -> + Monitor ! DATA, + elsa_registry:checkin(Service, Instance) + end. + +request(Method, URL, Body, Type) -> + {ok, {{_, _, _},_, DATA}} = case Method of + get -> + httpc:request(Method, {URL, []}, [], []); + _ -> + httpc:request(Method, {URL, [], Type, Body}, [], []) + end, + list_to_binary(DATA). + +wait_for_instance(Service) -> + case elsa_registry:checkout(Service) of + unavailable -> + timer:sleep(5000), + wait_for_instance(Service); + Instance -> + Instance + end. + +concat(X, Y) -> + <>. + +validate(URL_binary) -> + URL = binary_to_list(URL_binary), + case string:sub_string(URL, 1, 4) of + "http" -> URL; + _ -> "http://" ++ URL + end. diff --git a/apps/elsa/src/supervisors/elsa_service_worker_sup.erl b/apps/elsa/src/supervisors/elsa_service_worker_sup.erl new file mode 100644 index 0000000..951138d --- /dev/null +++ b/apps/elsa/src/supervisors/elsa_service_worker_sup.erl @@ -0,0 +1,41 @@ + +-module(elsa_service_worker_sup). +-behaviour(supervisor). + +-export([start_link/0, + start_child/1 + ]). + +-export([init/1 + ]). + +-define(SUPERVISOR, ?MODULE). +-define(CHILD, elsa_service_worker). + +start_link() -> + lager:info("Service worker supervisor started."), + supervisor:start_link({local, ?SUPERVISOR}, ?SUPERVISOR, []). + +start_child(Service) -> + case supervisor:start_child(?SUPERVISOR, [Service]) of + {ok, Pid} -> + lager:info("Service started: ~p", [Service]), + {ok, Pid}; + {error, {already_started, Pid}} -> {ok, Pid} + end. + +%% @hidden +init([]) -> + Sup_flags = #{ + strategy => simple_one_for_one, + intensity => 10, + period => 60 + }, + Service_worker = #{ + id => ?CHILD, + start => {?CHILD, start_link, []}, + restart => transient, + shutdown => 1000, + type => worker + }, + {ok, {Sup_flags, [Service_worker]}}. diff --git a/apps/elsa/src/supervisors/elsa_task_worker_sup.erl b/apps/elsa/src/supervisors/elsa_task_worker_sup.erl new file mode 100644 index 0000000..2ef9e5b --- /dev/null +++ b/apps/elsa/src/supervisors/elsa_task_worker_sup.erl @@ -0,0 +1,41 @@ + +-module(elsa_task_worker_sup). +-behaviour(supervisor). + +-export([start_link/0, + start_child/1 + ]). + +-export([init/1 + ]). + +-define(SUPERVISOR, ?MODULE). +-define(CHILD, elsa_task_worker). + +start_link() -> + lager:info("Task worker supervisor started."), + supervisor:start_link({local, ?SUPERVISOR}, ?SUPERVISOR, []). + +start_child(PID) -> + case supervisor:start_child(?SUPERVISOR, [PID]) of + {ok, Pid} -> + lager:info("Task started for monitor: ~p", [PID]), + {ok, Pid}; + {error, {already_started, Pid}} -> {ok, Pid} + end. + +%% @hidden +init([]) -> + Sup_flags = #{ + strategy => simple_one_for_one, + intensity => 10, + period => 60 + }, + Service_worker = #{ + id => ?CHILD, + start => {?CHILD, start_link, []}, + restart => transient, + shutdown => 1000, + type => worker + }, + {ok, {Sup_flags, [Service_worker]}}. diff --git a/apps/elsa/src/workers/elsa_service_worker.erl b/apps/elsa/src/workers/elsa_service_worker.erl new file mode 100644 index 0000000..3ec3928 --- /dev/null +++ b/apps/elsa/src/workers/elsa_service_worker.erl @@ -0,0 +1,141 @@ + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% @author Eric Sage +% @copyright 2015 Cytoscape Consortium + +-module(elsa_service_worker). +-behaviour(gen_server). + +-include_lib("stdlib/include/qlc.hrl"). + +-export([start_link/1, + find/1, + registration/1, + register/3, + unregister/2, + checkout/1, + transaction/4, + checkin/2]). + +-export([init/1, + handle_cast/2, + handle_call/3, + handle_info/2, + terminate/2, + code_change/3 + ]). + +-record(service_instance, {location, capacity, out}). + +start_link(Name) when is_binary(Name) -> + gen_server:start_link({global, {service_worker, Name}}, + ?MODULE, + Name, []). + +init(Name) -> + case mnesia:create_table(binary_to_atom(Name, utf8), + [{attributes, record_info(fields, service_instance)}, + {record_name, service_instance}, + {disc_copies, [node()]}]) of + {atomic, ok} -> lager:info("Service table ~s created.", [Name]); + {aborted, {already_exists, _}} -> lager:error("Service table ~s already exists.", [Name]) + end, + lager:info("Service worker ~s created.", [Name]), + {ok, {service_name, Name}}. + +find(Name) when is_binary(Name) -> + global:whereis_name({service_worker, Name}). + +registration(Name) when is_binary(Name) -> + do(qlc:q([I || I <- mnesia:table(binary_to_atom(Name, utf8))])). + +register(Name, Instance, Capacity) when is_binary(Name), is_binary(Instance), is_atom(Capacity); is_integer(Capacity) -> + gen_server:call(find(Name), {register, Instance, Capacity}). + +unregister(Name, Instance) when is_binary(Name), is_binary(Instance) -> + gen_server:call(find(Name), {unregister, Instance}). + +checkout(Name) -> + gen_server:call(find(Name), checkout). + +checkin(Name, Instance) when is_binary(Name), is_binary(Instance) -> + gen_server:call(find(Name), {checkin, Instance}). + +%% Callbacks + +handle_call({register, Instance, Capacity}, _From, {service_name, Name}) -> + Row = #service_instance{location=Instance, capacity=Capacity, out=0}, + {atomic, ok} = transaction(Name, Row, write, write), + {reply, ok, {service_name, Name}}; + +handle_call({unregister, Instance}, _From, {service_name, Name}) -> + {atomic, ok} = transaction(Name, Instance, delete, write), + {reply, ok, {service_name, Name}}; + +%%TODO: These two transactions should happen at once. +handle_call({checkin, Instance}, _From, {service_name, Name}) -> +{atomic, [{_, _, C, O}|_]} = transaction(Name, Instance, read, read), +Row = #service_instance{location=Instance, capacity=C, out=O-1}, +{atomic, ok} = transaction(Name, Row, write, write), +{reply, ok, {service_name, Name}}; + +handle_call(checkout, _From, {service_name, Name}) -> + {reply, case bound(Name) of + false -> + case unbound(Name) of + false -> unavailable; + Instance -> Instance + end; + Instance -> Instance + end, {service_name, Name}}. + +bound(Name) -> + B = do(qlc:q([I || I <- mnesia:table(binary_to_atom(Name, utf8)), + I#service_instance.capacity =/= infinity, + I#service_instance.capacity =/= I#service_instance.out])), + Sort = fun(X,Y) -> X#service_instance.out < Y#service_instance.out end, + case lists:sort(Sort, B) of + [] -> false; + [Instance|_] -> remove(Name, Instance) + end. + +unbound(Name) -> + B = do(qlc:q([I || I <- mnesia:table(binary_to_atom(Name, utf8)), + I#service_instance.capacity == infinity])), + Sort = fun(X,Y) -> X#service_instance.out < Y#service_instance.out end, + case lists:sort(Sort, B) of + [] -> false; + [Instance|_] -> remove(Name, Instance) + end. + +remove(Name, Instance) -> + transaction(Name, + #service_instance{ + location = Instance#service_instance.location, + capacity = Instance#service_instance.capacity, + out = Instance#service_instance.out + 1 + }, write, write), + Instance#service_instance.location. + +handle_info(_, Name) -> {noreply, Name}. + +handle_cast({_, _}, Name) -> {noreply, Name}. + +terminate(_Reason, {service_name, Name}) -> +lager:info("Service worker ~s terminated.", [Name]), +ok. + +code_change(_LastVsn, State, _Opt) -> {ok, State}. + +%% Helpers + +transaction(Name, Target, Action, Mode) -> + T = fun() -> + apply(mnesia, Action, [binary_to_atom(Name, utf8), Target, Mode]) + end, + mnesia:transaction(T). + +do(Q) -> + F = fun() -> qlc:e(Q) end, + {atomic, Val} = mnesia:transaction(F), + Val. diff --git a/apps/elsa/src/workers/elsa_task_worker.erl b/apps/elsa/src/workers/elsa_task_worker.erl new file mode 100644 index 0000000..e56c521 --- /dev/null +++ b/apps/elsa/src/workers/elsa_task_worker.erl @@ -0,0 +1,69 @@ + +-module(elsa_task_worker). + +-behaviour(gen_server). + +-export([start_link/1, + find/1, + get_params/1, + store_params/2, + get_data/1, + store_data/2 + ]). + +-export([init/1, + handle_call/3, + handle_cast/2, + handle_info/2, + terminate/2, + code_change/3 + ]). + +-record(task, {params, data}). + +start_link(Task) when is_pid(Task) -> + ID = elsa_task:get_id(Task), + gen_server:start_link({global, {task_worker, ID}}, + ?MODULE, + ID, []). + +find(ID) when is_binary(ID) -> + global:whereis_name({task_worker, ID}). + +get_params(ID) -> + gen_server:call(find(ID), params). + +store_params(ID, Params) -> + gen_server:call(find(ID), {params, Params}). + +get_data(ID) -> + gen_server:call(find(ID), data). + +store_data(ID, Data) -> + gen_server:call(find(ID), {data, Data}). + +init(ID) -> + lager:info("Task ~s created.", [ID]), + {ok, {task, ID, #task{params=none, data=incomplete}}}. + +handle_call(params, _From, {task, ID, Task}) -> + {reply, Task#task.params, {task, ID, Task}}; + +handle_call({params, Params}, _From, {task, ID, Task}) -> + {reply, ok, {task, ID, Task#task{params = Params}}}; + +handle_call(data, _From, {task, ID, Task}) -> + {reply, Task#task.data, {task, ID, Task}}; + +handle_call({data, Data}, _From, {task, ID, Task}) -> + {reply, ok, {task, ID, Task#task{data = Data}}}. + +handle_info(_, Name) -> {noreply, Name}. + +handle_cast({_, _}, Name) -> {noreply, Name}. + +terminate(_Reason, {task, ID, _}) -> +lager:notice("Task worker ~s terminated.", [ID]), +ok. + +code_change(_LastVsn, State, _Opt) -> {ok, State}. diff --git a/apps/elsa/test/elsa_registry_tests.erl b/apps/elsa/test/elsa_registry_tests.erl new file mode 100644 index 0000000..cd13769 --- /dev/null +++ b/apps/elsa/test/elsa_registry_tests.erl @@ -0,0 +1,100 @@ + +-module(elsa_registry_tests). + +-include_lib("eunit/include/eunit.hrl"). + +elsa_service_worker_test_() -> + {"Test service worker API.", + { foreach + , fun setup/0 + , fun cleanup/1 + , [fun test_register_single_instance/1, + fun test_unregister_single_instance/1, + fun test_register_multiple_instances/1, + fun test_unregister_multiple_instances/1, + fun test_register_multiple_services/1, + fun test_unregister_multiple_services/1 + ]}}. + +setup() -> + {ok, _Started} = application:ensure_all_started(elsa), + ok. + +cleanup(Worker)-> + ok. + +test_register_single_instance(_Setup) -> + elsa_registry:register(single_service_single_instance_mock()), + Instance = elsa_registry:checkout(<<"v1test">>), + [?_assertEqual(<<"1.1.1.1">>, Instance)]. + +test_unregister_single_instance(_Setup) -> + elsa_registry:unregister(single_service_single_instance_mock()), + Instance = elsa_registry:checkout(<<"v1test">>), + [?_assertEqual(unavailable, Instance)]. + +test_register_multiple_instances(_Setup) -> + elsa_registry:register(single_service_multiple_instance_mock()), + elsa_registry:checkout(<<"v2test">>), + Instance = elsa_registry:checkout(<<"v2test">>), + [?_assertEqual(<<"1.1.1.2">>, Instance)]. + +test_unregister_multiple_instances(_Setup) -> + elsa_registry:unregister(single_service_multiple_instance_mock()), + elsa_registry:checkout(<<"v2test">>), + Instance = elsa_registry:checkout(<<"v2test">>), + [?_assertEqual(unavailable, Instance)]. + +test_register_multiple_services(_Setup) -> + elsa_registry:register(multiple_service_multiple_instance_mock()), + V1Instance = elsa_registry:checkout(<<"v1testall">>), + V2Instance = elsa_registry:checkout(<<"v2testall">>), + [?_assertEqual(V1Instance, V2Instance)]. + +test_unregister_multiple_services(_Setup) -> + elsa_registry:unregister(multiple_service_multiple_instance_mock()), + Instance = elsa_registry:checkout(<<"v1testall">>), + [?_assertEqual(unavailable, Instance)]. + +single_service_single_instance_mock() -> + [ + {<<"service">>, <<"test">>}, + {<<"version">>,<<"v1">>}, + {<<"instances">>,[ + [{<<"location">>,<<"1.1.1.1">>}, + {<<"capacity">>, 4}] + ]}]. + +single_service_multiple_instance_mock() -> + [ + {<<"service">>, <<"test">>}, + {<<"version">>,<<"v2">>}, + {<<"instances">>,[ + [{<<"location">>,<<"1.1.1.1">>}, + {<<"capacity">>, 1}], + [{<<"location">>,<<"1.1.1.2">>}, + {<<"capacity">>, infinity}] + ]}]. + +multiple_service_multiple_instance_mock() -> + [[ + {<<"service">>, <<"testall">>}, + {<<"version">>,<<"v1">>}, + {<<"instances">>,[ + [{<<"location">>,<<"1.1.1.1">>}, + {<<"capacity">>, 1}], + [{<<"location">>,<<"1.1.1.2">>}, + {<<"capacity">>, infinity}] + ]} + ], + [ + {<<"service">>, <<"testall">>}, + {<<"version">>,<<"v2">>}, + {<<"instances">>,[ + [{<<"location">>,<<"1.1.1.1">>}, + {<<"capacity">>, 1}], + [{<<"location">>,<<"1.1.1.2">>}, + {<<"capacity">>, infinity}] + ]} + ] + ]. diff --git a/apps/elsa/test/elsa_service_worker_tests.erl b/apps/elsa/test/elsa_service_worker_tests.erl new file mode 100644 index 0000000..8777dbf --- /dev/null +++ b/apps/elsa/test/elsa_service_worker_tests.erl @@ -0,0 +1,94 @@ +% @doc Chatastic Tests +% @end + +%%% Module +-module(elsa_service_worker_tests). + +%%% Includes + +-include_lib("eunit/include/eunit.hrl"). + +%%% Macros + + +%%% Tests + +elsa_service_worker_test_() -> + {"Test service worker API.", + { foreach + , fun setup/0 + , fun cleanup/1 + , [fun test_find_service_worker/1, + fun test_register_bounded_service_instance/1, + fun test_checkout_bounded_service_instance/1, + fun test_checkin_bounded_service_instance/1, + fun test_register_unbounded_service_instance/1, + fun test_checkout_unbounded_service_instance/1, + fun test_checkin_unbounded_service_instance/1, + fun test_checkout_different_unbounded_service_instance/1, + fun test_checkout_unbound_before_bound_service_instance/1 + ]}}. + +setup() -> + {ok, _Started} = application:ensure_all_started(elsa), + Worker_Pid = case elsa_service_worker:start_link(<<"test">>) of + {error,{already_started, Worker}} -> Worker; + {ok, Worker} -> Worker + end, + mnesia:wait_for_tables([test], 3000), + Worker_Pid. + +cleanup(Worker)-> + mnesia:clear_table(test), + ok. + +test_find_service_worker(Worker) -> + TestWorker = elsa_service_worker:find(<<"test">>), + [?_assertEqual(Worker, TestWorker)]. + +test_register_bounded_service_instance(Worker) -> + OK = elsa_service_worker:register(<<"test">>, <<"1.1.1.1">>, 3), + [?_assertEqual(ok, OK)]. + +test_checkout_bounded_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.1">>, 3), + Instance = elsa_service_worker:checkout(<<"test">>), + [?_assertEqual(<<"1.1.1.1">>, Instance)]. + +test_checkin_bounded_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.1">>, 1), + elsa_service_worker:checkout(<<"test">>), + Unavailable = elsa_service_worker:checkout(<<"test">>), + elsa_service_worker:checkin(<<"test">>, <<"1.1.1.1">>), + Instance = elsa_service_worker:checkout(<<"test">>), + [?_assertEqual(unavailable, Unavailable), ?_assertEqual(<<"1.1.1.1">>, Instance)]. + +test_register_unbounded_service_instance(Worker) -> + OK = elsa_service_worker:register(<<"test">>, <<"1.1.1.1">>, infinity), + [?_assertEqual(ok, OK)]. + +test_checkout_unbounded_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.2">>, infinity), + Instance = elsa_service_worker:checkout(<<"test">>), + [?_assertEqual(<<"1.1.1.2">>, Instance)]. + +test_checkin_unbounded_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.1">>, 1), + Instance = elsa_service_worker:checkout(<<"test">>), + elsa_service_worker:checkin(<<"test">>, <<"1.1.1.1">>), + Instance = elsa_service_worker:checkout(<<"test">>), + [?_assertEqual(<<"1.1.1.1">>, Instance)]. + +test_checkout_different_unbounded_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.2">>, infinity), + elsa_service_worker:register(<<"test">>, <<"1.1.1.3">>, infinity), + Instance = elsa_service_worker:checkout(<<"test">>), + Instance2 = elsa_service_worker:checkout(<<"test">>), + [?_assertNotEqual(Instance, Instance2)]. + +test_checkout_unbound_before_bound_service_instance(Worker) -> + elsa_service_worker:register(<<"test">>, <<"1.1.1.2">>, 1), + elsa_service_worker:register(<<"test">>, <<"1.1.1.3">>, infinity), + Instance = elsa_service_worker:checkout(<<"test">>), + Instance2 = elsa_service_worker:checkout(<<"test">>), + [?_assertEqual(<<"1.1.1.2">>, Instance), ?_assertEqual(<<"1.1.1.3">>, Instance2)]. diff --git a/apps/elsa/test/elsa_task_tests.erl b/apps/elsa/test/elsa_task_tests.erl new file mode 100644 index 0000000..63033f0 --- /dev/null +++ b/apps/elsa/test/elsa_task_tests.erl @@ -0,0 +1,36 @@ + +-module(elsa_task_tests). + +-include_lib("eunit/include/eunit.hrl"). + +elsa_service_worker_test_() -> + {"Test service worker API.", + { foreach + , fun setup/0 + , fun cleanup/1 + , [fun test_status_without_task/1, + fun test_status_with_task/1, + fun test_status_with_task_and_data/1 + ]}}. + +setup() -> + {ok, _Started} = application:ensure_all_started(elsa), + ok. + +cleanup(Worker)-> + ok. + +test_status_without_task(_Setup) -> + Not_found = elsa_task:status(<<"FAKETASK">>), + [?_assertEqual(not_found, Not_found)]. + +test_status_with_task(_Setup) -> + elsa_task_worker:start_link(self()), + Incomplete = elsa_task:status(elsa_task:get_id(self())), + [?_assertEqual(incomplete, Incomplete)]. + +test_status_with_task_and_data(_Setup) -> + elsa_task_worker:start_link(self()), + elsa_task:store_data(elsa_task:get_id(self()), data), + Complete = elsa_task:status(elsa_task:get_id(self())), + [?_assertEqual(complete, Complete)]. diff --git a/apps/elsa/test/elsa_task_worker_tests.erl b/apps/elsa/test/elsa_task_worker_tests.erl new file mode 100644 index 0000000..ba962fd --- /dev/null +++ b/apps/elsa/test/elsa_task_worker_tests.erl @@ -0,0 +1,52 @@ +-module(elsa_task_worker_tests). + +-include_lib("eunit/include/eunit.hrl"). + +elsa_service_worker_test_() -> + {"Test service worker API.", + { foreach + , fun setup/0 + , fun cleanup/1 + , [fun test_find_task_worker/1, + fun test_store_and_get_params/1, + fun test_change_params/1, + fun test_store_and_get_data/1, + fun test_change_data/1 + ]}}. + +setup() -> + {ok, _Started} = application:ensure_all_started(elsa), + Worker_Pid = case elsa_task_worker:start_link(self()) of + {error,{already_started, Worker}} -> Worker; + {ok, Worker} -> Worker + end, + {Worker_Pid, elsa_task:get_id(self())}. + +cleanup(Worker)-> + ok. + +test_find_task_worker({Worker, ID}) -> + TestWorker = elsa_task_worker:find(ID), + [?_assertEqual(Worker, TestWorker)]. + +test_store_and_get_params({_, ID}) -> + elsa_task_worker:store_params(ID, test_params), + Params = elsa_task_worker:get_params(ID), + [?_assertEqual(test_params, Params)]. + +test_change_params({_, ID}) -> + elsa_task_worker:store_params(ID, first_params), + elsa_task_worker:store_params(ID, test_params), + Params = elsa_task_worker:get_params(ID), + [?_assertEqual(test_params, Params)]. + +test_store_and_get_data({_, ID}) -> + elsa_task_worker:store_data(ID, test_data), + Data = elsa_task_worker:get_data(ID), + [?_assertEqual(test_data, Data)]. + +test_change_data({_, ID}) -> + elsa_task_worker:store_data(ID, first_data), + elsa_task_worker:store_data(ID, test_data), + Data = elsa_task_worker:get_data(ID), + [?_assertEqual(test_data, Data)]. diff --git a/config/sys.config b/config/sys.config new file mode 100644 index 0000000..ac00957 --- /dev/null +++ b/config/sys.config @@ -0,0 +1,12 @@ +[ + {'elsa', []}, + {mnesia, [{dir, "./DATABASE"}]}, + {lager, [ + {error_logger_hwm, 100}, + {handlers, [ + {lager_console_backend, info}, + {lager_syslog_backend, ["elsa", local0, info]} + ]} + ]} + +]. diff --git a/config/sys.config.docker b/config/sys.config.docker new file mode 100644 index 0000000..685ced0 --- /dev/null +++ b/config/sys.config.docker @@ -0,0 +1,10 @@ +[ + {'elsa', []}, + {mnesia, [{dir, "/elsa/DATABASE"}]}, + {lager, [ + {error_logger_hwm, 100}, + {handlers, [ + {lager_console_backend, info} + ]} + ]} +]. diff --git a/config/vm.args b/config/vm.args new file mode 100644 index 0000000..b5dadda --- /dev/null +++ b/config/vm.args @@ -0,0 +1,6 @@ +-sname elsa + +-setcookie elsa_cookie + ++K true ++A30 diff --git a/rebar.config b/rebar.config new file mode 100644 index 0000000..a840b0f --- /dev/null +++ b/rebar.config @@ -0,0 +1,53 @@ +{erl_opts, [ + debug_info, + {parse_transform, lager_transform} +]}. + +{deps, [ + {cowboy, "1.0.4"}, + {lager, "3.0.2"}, + {lager_syslog, {git, "https://github.com/basho/lager_syslog.git"}}, + {jsx, {git, "https://github.com/talentdeficit/jsx.git"}}, + {base16, {git, "https://github.com/goj/base16.git"}} +]}. + +{overrides, + [{override, syslog, [ + {plugins, [ + {pc, {git, "https://github.com/blt/port_compiler.git", {branch, "master"}}} + ]}, + + {provider_hooks, [ + {post, + [ + {compile, {pc, compile}}, + {clean, {pc, clean}} + ] + }] + } + ]} +]}. + +{relx, [{release, {'elsa', "0.1.0"}, + ['elsa', + cowboy, + lager, + lager_syslog, + jsx, + base16, + sasl + ]}, + + {sys_config, "./config/sys.config"}, + {vm_args, "./config/vm.args"}, + + {dev_mode, false}, + {include_erts, true}, + + {extended_start_script, true}] +}. + +{profiles, [{dev, [{relx, [{dev_mode, true}, + {include_erts, false}]}] + }] +}. diff --git a/rebar3 b/rebar3 new file mode 100755 index 0000000..32056ec Binary files /dev/null and b/rebar3 differ