diff options
author | magnus <mfeuer@jaguarlandrover.com> | 2014-10-05 16:05:32 -0700 |
---|---|---|
committer | magnus <mfeuer@jaguarlandrover.com> | 2014-10-05 16:05:32 -0700 |
commit | c2bbe4806acf15a5fb3b945b3481e43604529a9e (patch) | |
tree | a1a077b9d17c9de55c2d592190484e090d3c80ca /components/rvi_common | |
parent | 0a07a86e08afd5e91b4a7c688aaf82fe7de07f30 (diff) | |
parent | 33c0582abf9aadcb53bbb8c35b0033611da1f589 (diff) | |
download | rvi_core-c2bbe4806acf15a5fb3b945b3481e43604529a9e.tar.gz |
Add 'components/rvi_common/' from commit '33c0582abf9aadcb53bbb8c35b0033611da1f589'
git-subtree-dir: components/rvi_common
git-subtree-mainline: 0a07a86e08afd5e91b4a7c688aaf82fe7de07f30
git-subtree-split: 33c0582abf9aadcb53bbb8c35b0033611da1f589
Diffstat (limited to 'components/rvi_common')
-rw-r--r-- | components/rvi_common/.gitignore | 1 | ||||
-rw-r--r-- | components/rvi_common/LICENSE | 354 | ||||
-rw-r--r-- | components/rvi_common/Makefile | 20 | ||||
-rw-r--r-- | components/rvi_common/README.md | 1 | ||||
-rw-r--r-- | components/rvi_common/rebar.config | 9 | ||||
-rw-r--r-- | components/rvi_common/src/exoport_exo_http.erl | 240 | ||||
-rw-r--r-- | components/rvi_common/src/rvi_common.app.src | 24 | ||||
-rw-r--r-- | components/rvi_common/src/rvi_common.erl | 462 | ||||
-rw-r--r-- | components/rvi_common/src/rvi_common_app.erl | 30 | ||||
-rw-r--r-- | components/rvi_common/src/rvi_common_sup.erl | 39 |
10 files changed, 1180 insertions, 0 deletions
diff --git a/components/rvi_common/.gitignore b/components/rvi_common/.gitignore new file mode 100644 index 0000000..cfb2329 --- /dev/null +++ b/components/rvi_common/.gitignore @@ -0,0 +1 @@ +ebin diff --git a/components/rvi_common/LICENSE b/components/rvi_common/LICENSE new file mode 100644 index 0000000..c33dcc7 --- /dev/null +++ b/components/rvi_common/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/components/rvi_common/Makefile b/components/rvi_common/Makefile new file mode 100644 index 0000000..f6ce39f --- /dev/null +++ b/components/rvi_common/Makefile @@ -0,0 +1,20 @@ +.PHONY: all deps compile clean recomp + + +all: deps compile + +deps: + rebar get-deps + +compile: + rebar compile + +recomp: + rebar compile skip_deps=true + +clean: + rebar clean + + + + diff --git a/components/rvi_common/README.md b/components/rvi_common/README.md new file mode 100644 index 0000000..9c0852f --- /dev/null +++ b/components/rvi_common/README.md @@ -0,0 +1 @@ +Better documentation will come. diff --git a/components/rvi_common/rebar.config b/components/rvi_common/rebar.config new file mode 100644 index 0000000..ba687be --- /dev/null +++ b/components/rvi_common/rebar.config @@ -0,0 +1,9 @@ +%% -*- erlang -*- + +{ erl_opts, [debug_info]}. + +{deps, + [ + {lager, ".*", {git, "git://github.com/Feuerlabs/lager.git", "1.0.0.fl.3"}}, + {exo, ".*", {git, "git://github.com/Feuerlabs/exo.git", "1.2"}} + ]}. diff --git a/components/rvi_common/src/exoport_exo_http.erl b/components/rvi_common/src/exoport_exo_http.erl new file mode 100644 index 0000000..8ab6d0d --- /dev/null +++ b/components/rvi_common/src/exoport_exo_http.erl @@ -0,0 +1,240 @@ +%% +%% Copyright (C) 2014, Feuerlabs +%% +%% This program is licensed under the terms and conditions of the +%% Mozilla Public License, version 2.0. The full text of the +%% Mozilla Public License is at https://www.mozilla.org/MPL/2.0/ +%% +-module(exoport_exo_http). +-export([instance/3, + handle_body/4, +%% json_rpc/1, +%% json_rpc/2, + data_to_json/3]). + +-include_lib("exo/include/exo_http.hrl"). +-include_lib("lager/include/log.hrl"). + + +instance(SupMod, AppMod, Opts) -> + ?debug("exoport_exo_http:instance(): SupModule(~p), Opts(~p)", + [ SupMod, Opts]), + Port = opt(port, Opts, 8800), + + Child = {exo_http, {exo_http_server, start_link, + [Port, [{request_handler, + {?MODULE, handle_body, [AppMod]}}]]}, + permanent, 5000, worker, [exo_http_server]}, + case supervisor:start_child(SupMod, Child) of + {ok, _} -> ok; + {ok, _, _} -> ok; + Err -> Err + end. + + +handle_body(Socket, Request, Body, AppMod) when Request#http_request.method == 'POST' -> + try decode_json(Body) of + {call, Id, Method, Args} -> + case handle_rpc(AppMod, Method, Args) of + {ok, Reply} -> + success_response(Socket, Id, Reply); + ok -> + ok; + {error, Error} -> + error_response(Socket, Id, Error) + end; + {notification, _Method, _Args} -> + %% FIXME: Notification. + exo_http_server:response(Socket, undefined, 200, "OK", ""); + {error, _} -> + error_response(Socket, parse_error) + catch + error:_ -> + exo_http_server:response(Socket, undefined, 501, + "Internal Error", + "Internal Error") + end; + +handle_body(Socket, _Request, _Body, _AppMod) -> + exo_http_server:response(Socket, undefined, 404, "Not Found", + "Object not found. Try using POST method."). + + +%% Validated RPC +handle_rpc(Mod, Method, Args) -> + ?debug("exoport_exo_http_server:handle_rpc(): Mod: ~p", [Mod]), + ?debug("exoport_exo_http_server:handle_rpc(): Method: ~p", [Method]), + ?debug("exoport_exo_http_server:handle_rpc(): Args: ~p", [Args]), + + try Mod:handle_rpc(Method, Args) of + {ok, Result} -> + ?debug("exoport_exo_http_server:handle_rpc(ok): Result: ~p", [Result]), + {ok, Result}; + + {error, Reason} -> + {error, Reason} + catch + error:Crash -> + ?error("rpc_callback() CRASHED: Reason: ~p", [Crash]), + ?error("post_request() CRASHED: Stack: ~p", [erlang:get_stacktrace()]), + {error, {internal_error, Crash}} + end. + +success_response(Socket, Id, Reply) -> + JSON = {struct, [{"jsonrpc", "2.0"}, + {"id", Id}, + {"result", {struct, Reply}}]}, + exo_http_server:response(Socket, undefined, 200, "OK", + exo_json:encode(JSON), + [{content_type, "application/json"}]). + +error_response(Socket, Error) -> + %% No Id available + JSON = {struct, [{"jsonrpc", "2.0"}, + {"error", {struct, + [{"code", json_error_code(Error)}, + {"message", json_error_msg(Error)}]}}]}, + Body = list_to_binary(exo_json:encode(JSON)), + exo_http_server:response(Socket, undefined, 200, "OK", Body, + [{content_type, "application/json"}]). + +error_response(Socket, Id, Error) -> + JSON = {struct, [{"jsonrpc", "2.0"}, + {"id", Id}, + {"error", {struct, + [{"code", json_error_code(Error)}, + {"message", json_error_msg(Error)}]}}]}, + Body = list_to_binary(exo_json:encode(JSON)), + exo_http_server:response(Socket, undefined, 200, "OK", Body, + [{content_type, "application/json"}]). + +decode_json(Body) -> + try exo_json:decode_string(binary_to_list(Body)) of + {ok, {struct,Elems}} -> + case [opt(K,Elems,undefined) || K <- ["jsonrpc","id", + "method", "params"]] of + ["2.0",undefined,Method,Params] + when Method =/= undefined, + Params =/= undefined -> + {notification, Method, Params}; + ["2.0",Id,Method,Params] + when Id=/=undefined, + Method=/=undefined, + Params =/= undefined -> + {call, Id, Method, Params}; + _ -> + {error, invalid} + end + catch + error:_ -> + {error, parse_error} + end. + +json_error_code(parse_error ) -> -32700; +json_error_code(invalid_request ) -> -32600; +json_error_code(method_not_found) -> -32601; +json_error_code(invalid_params ) -> -32602; +json_error_code(internal_error ) -> -32603; +json_error_code(_) -> -32603. % internal error + + +json_error_msg(-32700) -> "parse error"; +json_error_msg(-32600) -> "invalid request"; +json_error_msg(-32601) -> "method not found"; +json_error_msg(-32602) -> "invalid params"; +json_error_msg(-32603) -> "internal error"; +json_error_msg(Code) when Code >= -32099, Code =< -32000 -> "server error"; +json_error_msg(_) -> "json error". + +opt(K, L, Def) -> + case lists:keyfind(K, 1, L) of + {_, V} -> V; + false -> Def + end. + + +%% +data_to_json(Elems, Env, Data) -> + ?debug("data_to_json(~p, ~p, ~p)~n", [Elems, Env, Data]), + case find_leaf(<<"rpc-status-string">>, Elems) of + false -> + yang_json:data_to_json(Elems, Env, Data); + _Leaf -> + case keyfind(<<"rpc-status-string">>, Data) of + false -> + case keyfind(<<"rpc-status">>, Data) of + false -> + yang_json:data_to_json(Elems, Env, Data); + Status -> + case enum_descr(find_leaf(<<"rpc-status">>, Elems), + to_binary(element(2, Status))) of + false -> + yang_json:data_to_json(Elems, Env, Data); + Descr -> + yang_json:data_to_json( + Elems, Env, + [{<<"rpc-status-string">>, Descr}|Data]) + end + end; + _ -> + yang_json:data_to_json(Elems, Env, Data) + end + end. + +enum_descr(false, _) -> false; +enum_descr({leaf, _, _, I}, V) -> + case lists:keyfind(type, 1, I) of + {_, _, <<"enumeration">>, I1} -> + enum_descr_(I1, V); + _ -> + false + end. + +%% Assume rpc-status can be either the numeric value or the description. +enum_descr_([{enum,_,V,I}|_], V) -> + case lists:keyfind(description,1,I) of + {_, _, Descr, _} -> Descr; + false -> V + end; +enum_descr_([{enum,_,D,I}|T], V) -> + case lists:keyfind(value, 1, I) of + {_, _, V, _} -> + case lists:keyfind(description,1,I) of + {_, _, Descr, _} -> Descr; + false -> D + end; + _ -> + enum_descr_(T, V) + end; +enum_descr_([_|T], V) -> + enum_descr_(T, V); +enum_descr_([], _) -> + false. + + + +find_leaf(K, [{leaf,_,K,_} = L|_]) -> L; +find_leaf(K, [_|T]) -> find_leaf(K, T); +find_leaf(_, []) -> false. + +keyfind(A, [H|T]) when is_tuple(H) -> + K = element(1, H), + case comp(A,K) of + true -> + H; + false -> + keyfind(A, T) + end; +keyfind(_, []) -> + false. + +comp(A, A) -> true; +comp(A, B) when is_binary(A), is_list(B) -> + binary_to_list(A) == B; +comp(A, B) when is_binary(A), is_atom(B) -> + A == atom_to_binary(B, latin1); +comp(_, _) -> + false. + +to_binary(B) when is_binary(B) -> B; +to_binary(L) when is_list(L) -> list_to_binary(L). diff --git a/components/rvi_common/src/rvi_common.app.src b/components/rvi_common/src/rvi_common.app.src new file mode 100644 index 0000000..4878e37 --- /dev/null +++ b/components/rvi_common/src/rvi_common.app.src @@ -0,0 +1,24 @@ +%% +%% Copyright (C) 2014, Jaguar Land Rover +%% +%% This program is licensed under the terms and conditions of the +%% Mozilla Public License, version 2.0. The full text of the +%% Mozilla Public License is at https://www.mozilla.org/MPL/2.0/ +%% + + +%% -*- erlang -*- +{application, rvi_common, + [ + {description, ""}, + {vsn, "0.1"}, + {registered, []}, + {applications, [ + kernel, + stdlib + ]}, + {mod, { rvi_common_app, []}}, + {env, [ + {yang_spec_modules, [{"$PRIV_DIR/yang", "yang_spec_*.beam"}]} + ]} + ]}. diff --git a/components/rvi_common/src/rvi_common.erl b/components/rvi_common/src/rvi_common.erl new file mode 100644 index 0000000..42b2c1e --- /dev/null +++ b/components/rvi_common/src/rvi_common.erl @@ -0,0 +1,462 @@ +%% +%% Copyright (C) 2014, Jaguar Land Rover +%% +%% This program is licensed under the terms and conditions of the +%% Mozilla Public License, version 2.0. The full text of the +%% Mozilla Public License is at https://www.mozilla.org/MPL/2.0/ +%% + + +-module(rvi_common). + +%%-include_lib("lhttpc/include/lhttpc.hrl"). +-include_lib("lager/include/log.hrl"). + +-export([send_http_request/3]). +-export([send_component_request/3]). +-export([send_component_request/4]). +-export([find_component_address/1]). +-export([json_rpc_status/1]). +-export([get_json_element/2]). +-export([sanitize_service_string/1]). +-export([local_service_to_string/1]). +-export([local_service_to_string/2]). +-export([remote_service_to_string/1]). +-export([remote_service_to_string/2]). +-export([local_service_prefix/0]). +-export([find_static_node/1]). +-export([static_nodes/0]). +-export([is_local_service/1]). +-export([node_address_string/0]). +-export([node_address_tuple/0]). +-export([get_request_result/1]). +-export([get_component_config/1]). +-export([get_component_config/2]). +-export([get_component_config/3]). + + +-define(NODE_SERVICE_PREFIX, node_service_prefix). +-define(NODE_ADDRESS, node_address). +-define(STATIC_NODES, static_nodes). + + +json_rpc_status(0) -> + ok; + +json_rpc_status("0") -> + ok; + +json_rpc_status(1) -> + invalid_command; + +json_rpc_status("1") -> + invalid_command; + +json_rpc_status(2) -> + not_found; + +json_rpc_status("2") -> + not_found; + +json_rpc_status(3) -> + not_available; + +json_rpc_status("3") -> + not_available; + +json_rpc_status(4) -> + internal; + +json_rpc_status("4") -> + internal; + +json_rpc_status(5) -> + already_connected; + +json_rpc_status("5") -> + already_connected; + + +json_rpc_status(Unknown) when is_integer(Unknown)-> + undefined; + +json_rpc_status(Unknown) when is_list(Unknown)-> + undefined; + +json_rpc_status(ok) -> + 0; + +json_rpc_status(invalid_command) -> + 1; + +json_rpc_status(not_found) -> + 2; + +json_rpc_status(not_available) -> + 3; + +json_rpc_status(internal) -> + 4; + +json_rpc_status(already_connected) -> + 5; + +json_rpc_status(_) -> + 999. + +get_request_result({ok, {http_response, {_V1, _V2}, 200, _Text, _Hdr}, JSONBody}) -> + case get_json_element(["result", "status"], JSONBody) of + {ok, Value} -> + { ok, json_rpc_status(Value), JSONBody }; + + { error, undefined} -> + {ok, undefined } + end; + +get_request_result({ok, {http_response, {_V1, _V2}, Status, Reason, _Hdr}, _JSONBody}) -> + {error, {http, Status, Reason}}; + +get_request_result({error, Reason})-> + { error, Reason}; + +get_request_result(ok)-> + { ok, ok, "{}"}; + +get_request_result(Other)-> + ?error("get_request_result(): Unhandled result: ~p", [Other]), + { error, format}. + + +%% Send a request to another component (service_edge, authorize, etc). +send_component_request(Component, Service, ArgList) -> + case send_component_request(Component, Service, ArgList, []) of + { ok, Status, _, Body} -> + { ok, Status, Body }; + + Err -> Err + end. + +send_component_request(Component, Service, ArgList, ReturnParams) -> + Address = rvi_common:find_component_address(Component), + + %% ?debug("send_component_request(): Component: ~p", [ Component]), + %% ?debug("send_component_request(): Address: ~p", [ Address ]), + %% ?debug("send_component_request(): Service: ~p", [ Service]), + %% ?debug("send_component_request(): ArgList: ~p", [ ArgList]), + %% ?debug("send_component_request(): ReturnParams: ~p", [ ReturnParams]), + + case get_request_result( + send_http_request(Address, atom_to_list(Service), ArgList) + ) of + {ok, Status, JSONBody} -> + ReturnVal = retrieve_reply_elements(ReturnParams, JSONBody), + { ok, Status, ReturnVal, JSONBody }; + + Err -> Err + end. + +send_http_request(Url,Method, Args) -> + + Req = binary_to_list( + iolist_to_binary( + exo_json:encode({struct, [{"jsonrpc", "2.0"}, + {"id", 1}, + {"method", Method}, + {"params", {struct, Args}} + ] + }))), + + Hdrs = [{'Content-Type', "application/json"} ], + ?debug("rvi_common:send_http_request() Sending: ~p", [Req]), + try + exo_http:wpost(Url, {1,1}, Hdrs, Req, 1000) + catch + Type:Reason -> + ?error("rvi_common:send_http_request() CRASHED: URL: ~p", [Url]), + ?error("rvi_common:send_http_request() CRASHED: Hdrs: ~p", [Hdrs]), + ?error("rvi_common:send_http_request() CRASHED: Body: ~p", [Req]), + ?error("rvi_common:send_http_request() CRASHED: Type: ~p", [Type]), + ?error("rvi_common:send_http_request() CRASHED: Reason: ~p", [Reason]), + ?error("rvi_common:send_http_request() CRASHED: Stack: ~p", [ erlang:get_stacktrace()]), + {error, internal} + end. + + +find_component_address(Component) when is_atom(Component) -> + %% Locate the correct service address for the given component + case get_component_config(Component, url) of + {ok, URL } -> URL; + _ -> undefined + end. + + +%% If Path is just a single element, convert to list and try again. +get_json_element(ElemPath, JSON) when is_atom(ElemPath) -> + get_json_element([ElemPath], JSON); + +get_json_element(ElemPath, JSON) when is_binary(JSON) -> + get_json_element(ElemPath, binary_to_list(JSON)); + +get_json_element(ElemPath, JSON) when is_tuple(JSON) -> + get_json_element_(ElemPath, JSON); + +get_json_element(ElemPath, JSON) when is_list(JSON) -> + case exo_json:decode_string(JSON) of + {ok, Data } -> + get_json_element_(ElemPath, Data); + + Err -> + Err + end; + +get_json_element(P, J) -> + ?warning("get_json_element(): Unknown call structure; Path: ~p | JSON: ~p", + [P, J]), + {error, call, {P, J}}. + +get_json_element_(_, undefined) -> + { error, undefined }; + +get_json_element_([], {array, JSON}) -> + {ok, JSON}; + +get_json_element_([], {struct, JSON}) -> + {ok, JSON}; + +get_json_element_([], JSON) -> + {ok, JSON}; + + +%% All proplist keys in JSON are strings. +%% Convert atomically provided path elements to strings +get_json_element_([Elem | T], JSON ) when is_atom(Elem) -> + get_json_element_([atom_to_list(Elem) | T], JSON); + +get_json_element_([Elem | T], {struct, JSON} ) -> + Res = get_json_element_(T, proplists:get_value(Elem, JSON, undefined)), + Res; + +get_json_element_([Elem | T], {array, JSON} ) -> + Res = get_json_element_(T, proplists:get_value(Elem, JSON, undefined)), + Res; + +get_json_element_(Path,JSON) -> + ?warning("get_json_element_(): Unhandled: Path: ~p | JSON: ~p", + [Path, JSON]), + { error, undefined }. + + +retrieve_reply_elements(Elem, JSON) -> + retrieve_reply_elements(Elem, JSON, []). + +retrieve_reply_elements([], _, Acc) -> + lists:reverse(Acc); + +retrieve_reply_elements([Elem | T], JSON, Acc) when is_atom(Elem) -> + retrieve_reply_elements([[Elem] | T], JSON, Acc); + + +retrieve_reply_elements([Elem | T], JSON, Acc) when is_list(Elem) -> + %% prefix with result since that is where all reply elements are stored. + case get_json_element([ result | Elem ], JSON) of + { ok, Value } -> + retrieve_reply_elements(T, JSON, [ Value | Acc ]); + { error, undefined } -> + retrieve_reply_elements(T, JSON, [ undefined | Acc ]) + end. + + +sanitize_service_string(Service) when is_binary(Service) -> + sanitize_service_string(binary_to_list(Service)); + +sanitize_service_string(Service) when is_list(Service) -> + %% Check if message type is specced. + %% rpc:/jaguarlandrover.com/1234/hvac", + %% If so, drop message type. + case string:tokens(Service, ":") of + [ Res ] -> + Res; + + [_Type, Res ] -> + Res + end. + + + +local_service_to_string(Type, Svc) -> + Type ++ ":" ++ local_service_to_string(Svc). + + +%% Make sure we don't get two slashes between the prefix and the service name +local_service_to_string([ $/ | Service]) -> + local_service_prefix() ++ Service; + +%% Make sure we don't get two slashes +local_service_to_string(Svc) -> + local_service_prefix() ++ Svc. + +remote_service_to_string(Service) -> + Service. + +remote_service_to_string(Type, Service) -> + Type ++ ":" ++ Service. + +local_service_prefix() -> + Prefix = + case application:get_env(rvi, ?NODE_SERVICE_PREFIX) of + {ok, P} when is_atom(P) -> atom_to_list(P); + {ok, P} when is_list(P) -> P; + undefined -> + ?debug("WARNING: Please set application rvi environment ~p", + [?NODE_SERVICE_PREFIX]), + error({missing_env, ?NODE_SERVICE_PREFIX}) + end, + + %% Tag on a trailing slash if not there already. + case lists:last(Prefix) of + $/ -> Prefix; + + _ -> Prefix ++ "/" + end. + +static_nodes() -> + case application:get_env(rvi, ?STATIC_NODES) of + + {ok, NodeList} -> + NodeList; + + undefined -> + not_found + end. + + +%% Locate the statically configured node whose service(s) prefix- +%% matches the provided service. +%% FIXME: Longest prefix match. +find_static_node(Service) -> + case application:get_env(rvi, ?STATIC_NODES) of + + {ok, NodeList} when is_list(NodeList) -> + find_static_node(Service, NodeList); + + undefined -> + ?debug("No ~p configured under rvi.", [?STATIC_NODES]), + not_found + end. + +find_static_node(_Service, []) -> + not_found; + +%% Validate that argumenst are all lists. +find_static_node(Service, [{ SvcPrefix, NetworkAddress} | T ]) when + not is_list(Service); not is_list(SvcPrefix); not is_list(NetworkAddress) -> + ?warning("rvi_common:find_static_node(): Could not resolve ~p against {~p, ~p}:" + "One or more elements not strings.", [ Service, SvcPrefix, NetworkAddress]), + find_static_node(Service, T ); + + +%% If the service we are trying to resolve has a shorter name than +%% the prefix we are comparing with, ignore. +find_static_node(Service, [{ SvcPrefix, _NetworkAddress } | T ]) when + length(Service) < length(SvcPrefix) -> + ?debug("rvi_common:find_static_node(): Service: ~p is shorter than prefix ~p. Ignore.", + [ Service, SvcPrefix]), + find_static_node(Service, T ); + +find_static_node(Service, [{ SvcPrefix, NetworkAddress} | T] ) -> + case string:str(Service, SvcPrefix) of + 1 -> + ?debug("rvi_common:find_static_node(): Service: ~p -> { ~p, ~p}.", + [ Service, SvcPrefix, NetworkAddress]), + NetworkAddress; + _ -> + ?debug("rvi_common:find_static_node(): Service: ~p != { ~p, ~p}.", + [ Service, SvcPrefix, NetworkAddress]), + find_static_node(Service, T ) + end. + +%% Return true if the provided service is locally connected to this +%% node. In such cases, service edge should just bounce the request +%% off directly to the targeted service without invoking the rest of +%% the RVI structure. +%% +is_local_service(Service) -> + case application:get_env(rvi, ?NODE_SERVICE_PREFIX) of + {ok, P} when is_list(P) -> + case string:str(sanitize_service_string(Service), P) of + 1 -> + ?debug("is_local_service(~p): Is local", [ Service ]), + true; + + Err -> + ?debug("is_local_service(~p): Not local: ~p", [ Service, Err ]), + false + end; + + undefined -> + ?warning("WARNING: Please set application rvi environment ~p", + [?NODE_SERVICE_PREFIX]), + false + end. + + +node_address_string() -> + case application:get_env(rvi, ?NODE_ADDRESS) of + {ok, P} when is_atom(P) -> atom_to_list(P); + {ok, P} when is_list(P) -> P; + undefined -> + ?warning("WARNING: Please set application rvi environment ~p", + [?NODE_ADDRESS]), + error({missing_env, ?NODE_ADDRESS}) + end. + +node_address_tuple() -> + case node_address_string() of + {missing_env, _} = Err -> Err; + Addr -> + [ Address, Port ] = string:tokens(Addr, ":"), + { Address, list_to_integer(Port) } + end. + +get_component_config(Component) -> + case application:get_env(rvi, components, undefined) of + undefined -> + {error, {missing_env, {rvi, { component, [ ]}}}}; + + CompList -> + case proplists:get_value(Component, CompList, undefined) of + undefined -> + Err = {missing_env, {rvi, { component, [ { Component, {}} ]}}}, + ?debug("get_component_config(): Missing app environment: ~p", + [Err]), + {error, Err}; + + CompConf -> + {ok, CompConf} + end + end. + +get_component_config(Component, Key) -> + case get_component_config(Component) of + {ok, PropList } -> + + case proplists:get_value(Key, PropList, undefined ) of + + undefined -> + Err = {missing_env, {rvi, { component, [ { Component, { Key, {}}} ]}}}, + ?warning("get_component_config(): Missing app environment: ~p", [Err]), + {error, Err}; + + Config-> + {ok, Config } + end; + Err -> Err + end. + +get_component_config(Component, Key, Default) -> + case get_component_config(Component) of + {ok, PropList } -> + {ok, proplists:get_value(Key, PropList, Default)}; + + Err -> Err + end. diff --git a/components/rvi_common/src/rvi_common_app.erl b/components/rvi_common/src/rvi_common_app.erl new file mode 100644 index 0000000..f0ad2f5 --- /dev/null +++ b/components/rvi_common/src/rvi_common_app.erl @@ -0,0 +1,30 @@ +%% +%% Copyright (C) 2014, Jaguar Land Rover +%% +%% This program is licensed under the terms and conditions of the +%% Mozilla Public License, version 2.0. The full text of the +%% Mozilla Public License is at https://www.mozilla.org/MPL/2.0/ +%% + + +-module(rvi_common_app). + +-behaviour(application). + +%% Application callbacks +-export([start/2, + start_phase/3, + stop/1]). + +%% =================================================================== +%% Application callbacks +%% =================================================================== + +start(_StartType, _StartArgs) -> + rvi_common_sup:start_link(). + +start_phase(_, _, _) -> + ok. + +stop(_State) -> + ok. diff --git a/components/rvi_common/src/rvi_common_sup.erl b/components/rvi_common/src/rvi_common_sup.erl new file mode 100644 index 0000000..204086d --- /dev/null +++ b/components/rvi_common/src/rvi_common_sup.erl @@ -0,0 +1,39 @@ +%% +%% Copyright (C) 2014, Jaguar Land Rover +%% +%% This program is licensed under the terms and conditions of the +%% Mozilla Public License, version 2.0. The full text of the +%% Mozilla Public License is at https://www.mozilla.org/MPL/2.0/ +%% + + +-module(rvi_common_sup). + +-behaviour(supervisor). + +%% API +-export([start_link/0]). + +%% Supervisor callbacks +-export([init/1]). + +%% Helper macro for declaring children of supervisor +-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}). + +%% =================================================================== +%% API functions +%% =================================================================== + +start_link() -> + supervisor:start_link({local, ?MODULE}, ?MODULE, []). + +%% =================================================================== +%% Supervisor callbacks +%% =================================================================== + +init([]) -> + {ok, { {one_for_one, 5, 10}, + [ +%% ?CHILD(service_edge_can, worker), + ]} }. + |