Revert "Correct a double quote introduced in #4603"

This reverts commit 6a44e0e2ef.

That wiped a lot of files unintentionally
This commit is contained in:
Michael Klishin 2022-04-20 16:05:56 +04:00
parent 6a44e0e2ef
commit 7c47d0925a
No known key found for this signature in database
GPG Key ID: 8ADA141E1AD87C94
84 changed files with 10648 additions and 1743 deletions

View File

@ -7,7 +7,7 @@ define PROJECT_APP_EXTRA_KEYS
{licenses, ["MPL-2.0"]},
{links, [
{"Website", "https://www.rabbitmq.com/"},
{"GitHub", "https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/amqp10_client"}
{"GitHub", ""https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/amqp10_client"}
]},
{build_tools, ["make", "rebar3"]},
{files, [

View File

@ -6,7 +6,7 @@ define PROJECT_APP_EXTRA_KEYS
{licenses, ["MPL-2.0"]},
{links, [
{"Website", "https://www.rabbitmq.com/"},
{"GitHub", "https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/rabbit_common"}
{"GitHub", ""https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/rabbit_common"}
]},
{build_tools, ["make", "rebar3"]},
{files, [

338
deps/rabbit_common/mk/xrefr vendored Executable file
View File

@ -0,0 +1,338 @@
#!/usr/bin/env escript
%% vim:ft=erlang:
%% The code is copied from xref_runner.
%% https://github.com/inaka/xref_runner
%%
%% The only change is the support of our erlang_version_support
%% attribute: we don't want any warnings about functions which will be
%% dropped at load time.
%%
%% It's also a plain text escript instead of a compiled one because we
%% want to support Erlang R16B03 and the version of xref_runner uses
%% maps and is built with something like Erlang 18.
%% This mode allows us to reference local function. For instance:
%% lists:map(fun generate_comment/1, Comments)
-mode(compile).
-define(DIRS, ["ebin", "test"]).
-define(CHECKS, [undefined_function_calls,
undefined_functions,
locals_not_used]).
main(_) ->
Checks = ?CHECKS,
ElixirDeps = get_elixir_deps_paths(),
[true = code:add_path(P) || P <- ElixirDeps],
XrefWarnings = lists:append([check(Check) || Check <- Checks]),
warnings_prn(XrefWarnings),
case XrefWarnings of
[] -> ok;
_ -> halt(1)
end.
get_elixir_deps_paths() ->
case os:getenv("ERLANG_MK_RECURSIVE_DEPS_LIST") of
false ->
[];
Filename ->
{ok, Fd} = file:open(Filename, [read]),
get_elixir_deps_paths1(Fd, [])
end.
get_elixir_deps_paths1(Fd, Paths) ->
case file:read_line(Fd) of
{ok, Line0} ->
Line = Line0 -- [$\r, $\n],
RootPath = case os:type() of
{unix, _} ->
Line;
{win32, _} ->
case os:find_executable("cygpath.exe") of
false ->
Line;
Cygpath ->
os:cmd(
io_lib:format("~s --windows \"~s\"",
[Cygpath, Line]))
-- [$\r, $\n]
end
end,
Glob = filename:join([RootPath, "_build", "dev", "lib", "*", "ebin"]),
NewPaths = filelib:wildcard(Glob),
get_elixir_deps_paths1(Fd, Paths ++ NewPaths);
eof ->
add_elixir_stdlib_path(Paths)
end.
add_elixir_stdlib_path(Paths) ->
case find_elixir_home() of
false -> Paths;
ElixirLibDir -> [ElixirLibDir | Paths]
end.
find_elixir_home() ->
ElixirExe = case os:type() of
{unix, _} -> "elixir";
{win32, _} -> "elixir.bat"
end,
case os:find_executable(ElixirExe) of
false -> false;
ExePath -> resolve_symlink(ExePath)
end.
resolve_symlink(ExePath) ->
case file:read_link_all(ExePath) of
{error, einval} ->
determine_elixir_home(ExePath);
{ok, ResolvedLink} ->
ExePath1 = filename:absname(ResolvedLink,
filename:dirname(ExePath)),
resolve_symlink(ExePath1);
{error, _} ->
false
end.
determine_elixir_home(ExePath) ->
LibPath = filename:join([filename:dirname(filename:dirname(ExePath)),
"lib",
"elixir",
"ebin"]),
case filelib:is_dir(LibPath) of
true -> LibPath;
false -> {skip, "Failed to locate Elixir lib dir"}
end.
check(Check) ->
Dirs = ?DIRS,
lists:foreach(fun code:add_path/1, Dirs),
{ok, Xref} = xref:start([]),
try
ok = xref:set_library_path(Xref, code:get_path()),
lists:foreach(
fun(Dir) ->
case filelib:is_dir(Dir) of
true -> {ok, _} = xref:add_directory(Xref, Dir);
false -> ok
end
end, Dirs),
{ok, Results} = xref:analyze(Xref, Check),
FilteredResults = filter_xref_results(Check, Results),
[result_to_warning(Check, Result) || Result <- FilteredResults]
after
stopped = xref:stop(Xref)
end.
%% -------------------------------------------------------------------
%% Filtering results.
%% -------------------------------------------------------------------
filter_xref_results(Check, Results) ->
SourceModules =
lists:usort([source_module(Result) || Result <- Results]),
Ignores = lists:flatmap(
fun(Module) -> get_ignorelist(Module, Check) end, SourceModules),
UnusedFunctions = lists:flatmap(
fun(Mod) -> get_unused_compat_functions(Mod) end,
SourceModules),
ToIgnore = case get(results_to_ignore) of
undefined -> [];
RTI -> RTI
end,
NewToIgnore = [parse_xref_target(Result)
|| Result <- Results,
lists:member(parse_xref_source(Result), UnusedFunctions)],
AllToIgnore = ToIgnore ++ NewToIgnore ++ [mfa(M, {F, A})
|| {_, {M, F, A}} <- Ignores],
put(results_to_ignore, AllToIgnore),
[Result || Result <- Results,
not lists:member(parse_xref_result(Result), Ignores) andalso
not lists:member(parse_xref_result(Result), AllToIgnore) andalso
not lists:member(parse_xref_source(Result), UnusedFunctions)].
source_module({Mt, _Ft, _At}) -> Mt;
source_module({{Ms, _Fs, _As}, _Target}) -> Ms.
%%
%% Ignore behaviour functions, and explicitly marked functions
%%
%% Functions can be ignored by using
%% -ignore_xref([{F, A}, {M, F, A}...]).
get_ignorelist(Mod, Check) ->
%% Get ignore_xref attribute and combine them in one list
Attributes =
try
Mod:module_info(attributes)
catch
_Class:_Error -> []
end,
IgnoreXref =
[mfa(Mod, Value) || {ignore_xref, Values} <- Attributes, Value <- Values],
BehaviourCallbacks = get_behaviour_callbacks(Check, Mod, Attributes),
%% And create a flat {M, F, A} list
IgnoreXref ++ BehaviourCallbacks.
get_behaviour_callbacks(exports_not_used, Mod, Attributes) ->
Behaviours = [Value || {behaviour, Values} <- Attributes, Value <- Values],
[{Mod, {Mod, F, A}}
|| B <- Behaviours, {F, A} <- B:behaviour_info(callbacks)];
get_behaviour_callbacks(_Check, _Mod, _Attributes) ->
[].
get_unused_compat_functions(Module) ->
OTPVersion = code_version:get_otp_version(),
Attributes = try
Module:module_info(attributes)
catch
_Class:_Error -> []
end,
CompatTuples = [Tuple
|| {erlang_version_support, Tuples} <- Attributes,
Tuple <- Tuples],
get_unused_compat_functions(Module, OTPVersion, CompatTuples, []).
get_unused_compat_functions(_, _, [], Result) ->
Result;
get_unused_compat_functions(Module,
OTPVersion,
[{MinOTPVersion, Choices} | Rest],
Result) ->
Functions = lists:map(
fun({_, Arity, Pre, Post}) ->
if
OTPVersion >= MinOTPVersion ->
%% We ignore the "pre" function.
mfa(Module, {Pre, Arity});
true ->
%% We ignore the "post" function.
mfa(Module, {Post, Arity})
end
end, Choices),
get_unused_compat_functions(Module, OTPVersion, Rest,
Result ++ Functions).
mfa(M, {F, A}) -> {M, {M, F, A}};
mfa(M, MFA) -> {M, MFA}.
parse_xref_result({{SM, _, _}, MFAt}) -> {SM, MFAt};
parse_xref_result({TM, _, _} = MFAt) -> {TM, MFAt}.
parse_xref_source({{SM, _, _} = MFAt, _}) -> {SM, MFAt};
parse_xref_source({TM, _, _} = MFAt) -> {TM, MFAt}.
parse_xref_target({_, {TM, _, _} = MFAt}) -> {TM, MFAt};
parse_xref_target({TM, _, _} = MFAt) -> {TM, MFAt}.
%% -------------------------------------------------------------------
%% Preparing results.
%% -------------------------------------------------------------------
result_to_warning(Check, {MFASource, MFATarget}) ->
{Filename, Line} = get_source(MFASource),
[{filename, Filename},
{line, Line},
{source, MFASource},
{target, MFATarget},
{check, Check}];
result_to_warning(Check, MFA) ->
{Filename, Line} = get_source(MFA),
[{filename, Filename},
{line, Line},
{source, MFA},
{check, Check}].
%%
%% Given a MFA, find the file and LOC where it's defined. Note that
%% xref doesn't work if there is no abstract_code, so we can avoid
%% being too paranoid here.
%%
get_source({M, F, A}) ->
case code:get_object_code(M) of
error -> {"", 0};
{M, Bin, _} -> find_function_source(M, F, A, Bin)
end.
find_function_source(M, F, A, Bin) ->
AbstractCode = beam_lib:chunks(Bin, [abstract_code]),
{ok, {M, [{abstract_code, {raw_abstract_v1, Code}}]}} = AbstractCode,
%% Extract the original source filename from the abstract code
[Source|_] = [S || {attribute, _, file, {S, _}} <- Code],
%% Extract the line number for a given function def
Fn = [E || E <- Code,
element(1, E) == function,
element(3, E) == F,
element(4, E) == A],
case Fn of
[{function, Line, F, _, _}] when is_integer(Line) ->
{Source, Line};
[{function, Line, F, _, _}] ->
{Source, erl_anno:line(Line)};
%% do not crash if functions are exported, even though they
%% are not in the source.
%% parameterized modules add new/1 and instance/1 for example.
[] -> {Source, 0}
end.
%% -------------------------------------------------------------------
%% Reporting results.
%% -------------------------------------------------------------------
warnings_prn([]) ->
ok;
warnings_prn(Comments) ->
Messages = lists:map(fun generate_comment/1, Comments),
lists:foreach(fun warning_prn/1, Messages).
warning_prn(Message) ->
FullMessage = Message ++ "~n",
io:format(FullMessage, []).
generate_comment(XrefWarning) ->
Filename = proplists:get_value(filename, XrefWarning),
Line = proplists:get_value(line, XrefWarning),
Source = proplists:get_value(source, XrefWarning),
Check = proplists:get_value(check, XrefWarning),
Target = proplists:get_value(target, XrefWarning),
Position = case {Filename, Line} of
{"", _} -> "";
{Filename, 0} -> [Filename, " "];
{Filename, Line} -> [Filename, ":",
integer_to_list(Line), " "]
end,
[Position, generate_comment_text(Check, Source, Target)].
generate_comment_text(Check, {SM, SF, SA}, TMFA) ->
SMFA = io_lib:format("`~p:~p/~p`", [SM, SF, SA]),
generate_comment_text(Check, SMFA, TMFA);
generate_comment_text(Check, SMFA, {TM, TF, TA}) ->
TMFA = io_lib:format("`~p:~p/~p`", [TM, TF, TA]),
generate_comment_text(Check, SMFA, TMFA);
generate_comment_text(undefined_function_calls, SMFA, TMFA) ->
io_lib:format("~s calls undefined function ~s", [SMFA, TMFA]);
generate_comment_text(undefined_functions, SMFA, _TMFA) ->
io_lib:format("~s is not defined as a function", [SMFA]);
generate_comment_text(locals_not_used, SMFA, _TMFA) ->
io_lib:format("~s is an unused local function", [SMFA]);
generate_comment_text(exports_not_used, SMFA, _TMFA) ->
io_lib:format("~s is an unused export", [SMFA]);
generate_comment_text(deprecated_function_calls, SMFA, TMFA) ->
io_lib:format("~s calls deprecated function ~s", [SMFA, TMFA]);
generate_comment_text(deprecated_functions, SMFA, _TMFA) ->
io_lib:format("~s is deprecated", [SMFA]).

25
deps/rabbitmq_aws/rabbitmq_aws.iml vendored Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="ERLANG_MODULE" version="4">
<component name="FacetManager">
<facet type="erlang" name="Erlang">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/include" type="erlang-include" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.erlang.mk" />
<excludeFolder url="file://$MODULE_DIR$/.eunit" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/.rebar" />
<excludeFolder url="file://$MODULE_DIR$/_build" />
<excludeFolder url="file://$MODULE_DIR$/bin" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="jsx" />
</component>
</module>

View File

@ -0,0 +1,15 @@
GEM
remote: https://rubygems.org/
specs:
amq-protocol (2.3.1)
bunny (2.15.0)
amq-protocol (~> 2.3, >= 2.3.1)
PLATFORMS
ruby
DEPENDENCIES
bunny (>= 2.15.0, < 3.0)
BUNDLED WITH
2.1.4

View File

@ -0,0 +1,23 @@
*~
.sw?
.*.sw?
*.beam
/.erlang.mk/
/cover/
/deps/
/doc/
/ebin/
/escript/
/escript.lock
/logs/
/plugins/
/plugins.lock
/sbin/
/sbin.lock
/xrefr
/rabbitmq_ct_client_helpers.d
/.rabbitmq_ct_client_helpers.plt
/.bazelrc
/bazel-*

View File

@ -0,0 +1,11 @@
load("@rules_erlang//:erlang_app.bzl", "erlang_app")
erlang_app(
app_name = "rabbitmq_ct_client_helpers",
app_version = "master",
deps = [
"//deps/amqp_client:erlang_app",
"//deps/rabbit_common:erlang_app",
"//deps/rabbitmq_ct_helpers:erlang_app",
],
)

View File

@ -0,0 +1 @@
../../CODE_OF_CONDUCT.md

View File

@ -0,0 +1 @@
../../CONTRIBUTING.md

View File

@ -0,0 +1,4 @@
This package is licensed under the MPL 2.0. For the MPL 2.0, please see LICENSE-MPL-RabbitMQ.
If you have any questions regarding licensing, please contact us at
info@rabbitmq.com.

View File

@ -0,0 +1,373 @@
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.

View File

@ -0,0 +1,16 @@
PROJECT = rabbitmq_ct_client_helpers
PROJECT_DESCRIPTION = Common Test helpers for RabbitMQ (client-side helpers)
DEPS = rabbit_common rabbitmq_ct_helpers amqp_client
# FIXME: Use erlang.mk patched for RabbitMQ, while waiting for PRs to be
# reviewed and merged.
ERLANG_MK_REPO = https://github.com/rabbitmq/erlang.mk.git
ERLANG_MK_COMMIT = rabbitmq-tmp
DEP_PLUGINS = rabbit_common/mk/rabbitmq-build.mk \
rabbit_common/mk/rabbitmq-tools.mk
include ../../rabbitmq-components.mk
include ../../erlang.mk

View File

@ -0,0 +1,24 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel-erlang",
sha256 = "422a9222522216f59a01703a13f578c601d6bddf5617bee8da3c43e3b299fc4e",
strip_prefix = "bazel-erlang-1.1.0",
urls = ["https://github.com/rabbitmq/bazel-erlang/archive/refs/tags/1.1.0.zip"],
)
http_archive(
name = "rabbitmq-server",
strip_prefix = "rabbitmq-server-master",
urls = ["https://github.com/rabbitmq/rabbitmq-server/archive/master.zip"],
)
http_archive(
name = "rabbitmq_ct_helpers",
strip_prefix = "rabbitmq-ct-helpers-master",
urls = ["https://github.com/rabbitmq/rabbitmq-ct-helpers/archive/master.zip"],
)
load("@rabbitmq-server//:workspace_helpers.bzl", "rabbitmq_external_deps")
rabbitmq_external_deps()

View File

@ -0,0 +1,302 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2007-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_ct_client_helpers).
-include_lib("common_test/include/ct.hrl").
-include_lib("amqp_client/include/amqp_client.hrl").
-export([
setup_steps/0,
teardown_steps/0,
start_channels_managers/1,
stop_channels_managers/1,
open_connection/2,
open_unmanaged_connection/1, open_unmanaged_connection/2,
open_unmanaged_connection/3, open_unmanaged_connection/4, open_unmanaged_connection/5,
open_unmanaged_connection_direct/1, open_unmanaged_connection_direct/2,
open_unmanaged_connection_direct/3, open_unmanaged_connection_direct/4,
open_unmanaged_connection_direct/5,
open_unmanaged_connection/6,
close_connection/1, open_channel/2, open_channel/1,
close_channel/1,
open_connection_and_channel/2, open_connection_and_channel/1,
close_connection_and_channel/2,
close_channels_and_connection/2,
publish/3, consume/3, consume_without_acknowledging/3, fetch/3
]).
%% -------------------------------------------------------------------
%% Client setup/teardown steps.
%% -------------------------------------------------------------------
setup_steps() ->
[
fun start_channels_managers/1
].
teardown_steps() ->
[
fun stop_channels_managers/1
].
start_channels_managers(Config) ->
ok = application:set_env(amqp_client, gen_server_call_timeout, infinity),
NodeConfigs = rabbit_ct_broker_helpers:get_node_configs(Config),
NodeConfigs1 = [start_channels_manager(NC) || NC <- NodeConfigs],
rabbit_ct_helpers:set_config(Config, {rmq_nodes, NodeConfigs1}).
start_channels_manager(NodeConfig) ->
Pid = erlang:spawn(
fun() -> channels_manager(NodeConfig, undefined, []) end),
rabbit_ct_helpers:set_config(NodeConfig, {channels_manager, Pid}).
stop_channels_managers(Config) ->
NodeConfigs = rabbit_ct_broker_helpers:get_node_configs(Config),
NodeConfigs1 = [stop_channels_manager(NC) || NC <- NodeConfigs],
rabbit_ct_helpers:set_config(Config, {rmq_nodes, NodeConfigs1}).
stop_channels_manager(NodeConfig) ->
Pid = ?config(channels_manager, NodeConfig),
Pid ! stop,
proplists:delete(channels_manager, NodeConfig).
channels_manager(NodeConfig, ConnTuple, Channels) ->
receive
{open_connection, From} ->
{Conn1, _} = ConnTuple1 = open_conn(NodeConfig, ConnTuple),
From ! Conn1,
channels_manager(NodeConfig, ConnTuple1, Channels);
{open_channel, From} ->
{Conn1, _} = ConnTuple1 = open_conn(NodeConfig, ConnTuple),
{ok, Ch} = amqp_connection:open_channel(Conn1),
ChMRef = erlang:monitor(process, Ch),
From ! Ch,
channels_manager(NodeConfig, ConnTuple1,
[{Ch, ChMRef} | Channels]);
{close_everything, From} ->
close_everything(ConnTuple, Channels),
From ! ok,
channels_manager(NodeConfig, undefined, []);
{'DOWN', ConnMRef, process, Conn, _}
when {Conn, ConnMRef} =:= ConnTuple ->
channels_manager(NodeConfig, undefined, Channels);
{'DOWN', ChMRef, process, Ch, _} ->
Channels1 = Channels -- [{Ch, ChMRef}],
channels_manager(NodeConfig, ConnTuple, Channels1);
stop ->
close_everything(ConnTuple, Channels);
Unhandled ->
ct:pal(?LOW_IMPORTANCE,
"Channels manager ~p: unhandled message: ~p",
[self(), Unhandled]),
channels_manager(NodeConfig, ConnTuple, Channels)
end.
open_conn(NodeConfig, undefined) ->
Port = ?config(tcp_port_amqp, NodeConfig),
Params = #amqp_params_network{port = Port},
{ok, Conn} = amqp_connection:start(Params),
MRef = erlang:monitor(process, Conn),
{Conn, MRef};
open_conn(NodeConfig, {Conn, _} = ConnTuple) ->
case erlang:is_process_alive(Conn) of
true -> ConnTuple;
false -> open_conn(NodeConfig, undefined)
end.
close_everything(Conn, [{Ch, MRef} | Rest]) ->
case erlang:is_process_alive(Ch) of
true ->
amqp_channel:close(Ch),
receive
{'DOWN', MRef, _, Ch, Info} ->
ct:pal("Channel ~p closed: ~p~n", [Ch, Info])
end;
false ->
ok
end,
close_everything(Conn, Rest);
close_everything({Conn, MRef}, []) ->
case erlang:is_process_alive(Conn) of
true ->
amqp_connection:close(Conn),
receive
{'DOWN', MRef, _, Conn, Info} ->
ct:pal("Connection ~p closed: ~p~n", [Conn, Info])
end;
false ->
ok
end;
close_everything(undefined, []) ->
ok.
%% -------------------------------------------------------------------
%% Public API.
%% -------------------------------------------------------------------
open_connection(Config, Node) ->
Pid = rabbit_ct_broker_helpers:get_node_config(Config, Node,
channels_manager),
Pid ! {open_connection, self()},
receive
Conn when is_pid(Conn) -> Conn
end.
open_unmanaged_connection(Config) ->
open_unmanaged_connection(Config, 0).
open_unmanaged_connection(Config, Node) ->
open_unmanaged_connection(Config, Node, ?config(rmq_vhost, Config)).
open_unmanaged_connection(Config, Node, VHost) ->
open_unmanaged_connection(Config, Node, VHost,
?config(rmq_username, Config), ?config(rmq_password, Config)).
open_unmanaged_connection(Config, Node, Username, Password) ->
open_unmanaged_connection(Config, Node, ?config(rmq_vhost, Config),
Username, Password).
open_unmanaged_connection(Config, Node, VHost, Username, Password) ->
open_unmanaged_connection(Config, Node, VHost, Username, Password,
network).
open_unmanaged_connection_direct(Config) ->
open_unmanaged_connection_direct(Config, 0).
open_unmanaged_connection_direct(Config, Node) ->
open_unmanaged_connection_direct(Config, Node, ?config(rmq_vhost, Config)).
open_unmanaged_connection_direct(Config, Node, VHost) ->
open_unmanaged_connection_direct(Config, Node, VHost,
?config(rmq_username, Config), ?config(rmq_password, Config)).
open_unmanaged_connection_direct(Config, Node, Username, Password) ->
open_unmanaged_connection_direct(Config, Node, ?config(rmq_vhost, Config),
Username, Password).
open_unmanaged_connection_direct(Config, Node, VHost, Username, Password) ->
open_unmanaged_connection(Config, Node, VHost, Username, Password, direct).
open_unmanaged_connection(Config, Node, VHost, Username, Password, Type) ->
Params = case Type of
network ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, Node,
tcp_port_amqp),
#amqp_params_network{port = Port,
virtual_host = VHost,
username = Username,
password = Password};
direct ->
NodeName = rabbit_ct_broker_helpers:get_node_config(Config, Node,
nodename),
#amqp_params_direct{node = NodeName,
virtual_host = VHost,
username = Username,
password = Password}
end,
case amqp_connection:start(Params) of
{ok, Conn} -> Conn;
{error, _} = Error -> Error
end.
open_channel(Config) ->
open_channel(Config, 0).
open_channel(Config, Node) ->
Pid = rabbit_ct_broker_helpers:get_node_config(Config, Node,
channels_manager),
Pid ! {open_channel, self()},
receive
Ch when is_pid(Ch) -> Ch
end.
open_connection_and_channel(Config) ->
open_connection_and_channel(Config, 0).
open_connection_and_channel(Config, Node) ->
Conn = open_connection(Config, Node),
Ch = open_channel(Config, Node),
{Conn, Ch}.
close_channel(Ch) ->
case is_process_alive(Ch) of
true -> amqp_channel:close(Ch);
false -> ok
end.
close_connection(Conn) ->
case is_process_alive(Conn) of
true -> amqp_connection:close(Conn);
false -> ok
end.
close_connection_and_channel(Conn, Ch) ->
_ = close_channel(Ch),
case close_connection(Conn) of
ok -> ok;
closing -> ok
end.
close_channels_and_connection(Config, Node) ->
Pid = rabbit_ct_broker_helpers:get_node_config(Config, Node,
channels_manager),
Pid ! {close_everything, self()},
receive
ok -> ok
end.
publish(Ch, QName, Count) ->
amqp_channel:call(Ch, #'confirm.select'{}),
[amqp_channel:call(Ch,
#'basic.publish'{routing_key = QName},
#amqp_msg{props = #'P_basic'{delivery_mode = 2},
payload = list_to_binary(integer_to_list(I))})
|| I <- lists:seq(1, Count)],
amqp_channel:wait_for_confirms(Ch).
consume(Ch, QName, Count) ->
amqp_channel:subscribe(Ch, #'basic.consume'{queue = QName, no_ack = true},
self()),
CTag = receive #'basic.consume_ok'{consumer_tag = C} -> C end,
[begin
Exp = integer_to_binary(I),
receive {#'basic.deliver'{consumer_tag = CTag},
#amqp_msg{payload = Exp}} ->
ok
after 5000 ->
exit(timeout)
end
end || I <- lists:seq(1, Count)],
amqp_channel:call(Ch, #'basic.cancel'{consumer_tag = CTag}),
ok.
consume_without_acknowledging(Ch, QName, Count) ->
amqp_channel:subscribe(Ch, #'basic.consume'{queue = QName, no_ack = false},
self()),
CTag = receive #'basic.consume_ok'{consumer_tag = C} -> C end,
accumulate_without_acknowledging(Ch, CTag, Count, []).
accumulate_without_acknowledging(Ch, CTag, Remaining, Acc) when Remaining =:= 0 ->
amqp_channel:call(Ch, #'basic.cancel'{consumer_tag = CTag}),
lists:reverse(Acc);
accumulate_without_acknowledging(Ch, CTag, Remaining, Acc) ->
receive {#'basic.deliver'{consumer_tag = CTag, delivery_tag = DTag}, _Msg} ->
accumulate_without_acknowledging(Ch, CTag, Remaining - 1, [DTag | Acc])
after 5000 ->
amqp_channel:call(Ch, #'basic.cancel'{consumer_tag = CTag}),
exit(timeout)
end.
fetch(Ch, QName, Count) ->
[{#'basic.get_ok'{}, _} =
amqp_channel:call(Ch, #'basic.get'{queue = QName}) ||
_ <- lists:seq(1, Count)],
ok.

27
deps/rabbitmq_ct_helpers/.gitignore vendored Normal file
View File

@ -0,0 +1,27 @@
*~
.sw?
.*.sw?
*.beam
.terraform/
.terraform-*
terraform.tfstate*
*terraform.lock*
/.erlang.mk/
/cover/
/deps/
/doc/
/ebin/
/escript/
/escript.lock
/logs/
/plugins/
/plugins.lock
/sbin/
/sbin.lock
/xrefr
/rabbitmq_ct_helpers.d
/.rabbitmq_ct_helpers.plt
/.bazelrc
/bazel-*

14
deps/rabbitmq_ct_helpers/BUILD.bazel vendored Normal file
View File

@ -0,0 +1,14 @@
load("@rules_erlang//:erlang_app.bzl", "erlang_app")
erlang_app(
app_name = "rabbitmq_ct_helpers",
app_version = "master",
extra_priv = [
"tools/tls-certs/Makefile",
"tools/tls-certs/openssl.cnf.in",
],
deps = [
"//deps/rabbit_common:erlang_app",
"@proper//:erlang_app",
],
)

View File

@ -0,0 +1 @@
../../CODE_OF_CONDUCT.md

1
deps/rabbitmq_ct_helpers/CONTRIBUTING.md vendored Symbolic link
View File

@ -0,0 +1 @@
../../CONTRIBUTING.md

12
deps/rabbitmq_ct_helpers/LICENSE vendored Normal file
View File

@ -0,0 +1,12 @@
This package, rabbitmq_ct_helpers, is dual-licensed under
the Apache License v2 and the Mozilla Public License v2.0.
For the Apache License, please see the file LICENSE-APACHE2.
For the Mozilla Public License, please see the file LICENSE-MPL-RabbitMQ.
For attribution of copyright and other details of provenance, please
refer to the source code.
If you have any questions regarding licensing, please contact us at
info@rabbitmq.com.

202
deps/rabbitmq_ct_helpers/LICENSE-APACHE2 vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017-2020 VMware, Inc. or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,373 @@
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.

25
deps/rabbitmq_ct_helpers/Makefile vendored Normal file
View File

@ -0,0 +1,25 @@
PROJECT = rabbitmq_ct_helpers
PROJECT_DESCRIPTION = Common Test helpers for RabbitMQ
DEPS = rabbit_common proper inet_tcp_proxy
TEST_DEPS = rabbit
dep_rabbit_common = git-subfolder https://github.com/rabbitmq/rabbitmq-server master deps/rabbit_common
dep_rabbit = git-subfolder https://github.com/rabbitmq/rabbitmq-server master deps/rabbit
dep_inet_tcp_proxy = git https://github.com/rabbitmq/inet_tcp_proxy master
# FIXME: Use erlang.mk patched for RabbitMQ, while waiting for PRs to be
# reviewed and merged.
ERLANG_MK_REPO = https://github.com/rabbitmq/erlang.mk.git
ERLANG_MK_COMMIT = rabbitmq-tmp
DEP_PLUGINS = rabbit_common/mk/rabbitmq-build.mk \
rabbit_common/mk/rabbitmq-dist.mk \
rabbit_common/mk/rabbitmq-run.mk \
rabbit_common/mk/rabbitmq-tools.mk
include ../../rabbitmq-components.mk
include ../../erlang.mk
ERLC_OPTS += +nowarn_export_all

View File

@ -0,0 +1,18 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel-erlang",
sha256 = "422a9222522216f59a01703a13f578c601d6bddf5617bee8da3c43e3b299fc4e",
strip_prefix = "bazel-erlang-1.1.0",
urls = ["https://github.com/rabbitmq/bazel-erlang/archive/refs/tags/1.1.0.zip"],
)
http_archive(
name = "rabbitmq-server",
strip_prefix = "rabbitmq-server-master",
urls = ["https://github.com/rabbitmq/rabbitmq-server/archive/master.zip"],
)
load("@rabbitmq-server//:workspace_helpers.bzl", "rabbitmq_external_deps")
rabbitmq_external_deps()

View File

@ -0,0 +1,49 @@
-define(AWAIT_MATCH_DEFAULT_POLLING_INTERVAL, 50).
-define(awaitMatch(Guard, Expr, Timeout, PollingInterval),
begin
((fun AwaitMatchFilter(AwaitMatchHorizon) ->
AwaitMatchResult = Expr,
case (AwaitMatchResult) of
Guard -> AwaitMatchResult;
__V -> case erlang:system_time(millisecond) of
AwaitMatchNow when AwaitMatchNow < AwaitMatchHorizon ->
timer:sleep(
min(PollingInterval,
AwaitMatchHorizon - AwaitMatchNow)),
AwaitMatchFilter(AwaitMatchHorizon);
_ ->
erlang:error({awaitMatch,
[{module, ?MODULE},
{line, ?LINE},
{expression, (??Expr)},
{pattern, (??Guard)},
{value, __V}]})
end
end
end)(erlang:system_time(millisecond) + Timeout))
end).
-define(awaitMatch(Guard, Expr, Timeout),
begin
((fun AwaitMatchFilter(AwaitMatchHorizon) ->
AwaitMatchResult = Expr,
case (AwaitMatchResult) of
Guard -> AwaitMatchResult;
__V -> case erlang:system_time(millisecond) of
AwaitMatchNow when AwaitMatchNow < AwaitMatchHorizon ->
timer:sleep(
min(?AWAIT_MATCH_DEFAULT_POLLING_INTERVAL,
AwaitMatchHorizon - AwaitMatchNow)),
AwaitMatchFilter(AwaitMatchHorizon);
_ ->
erlang:error({awaitMatch,
[{module, ?MODULE},
{line, ?LINE},
{expression, (??Expr)},
{pattern, (??Guard)},
{value, __V}]})
end
end
end)(erlang:system_time(millisecond) + Timeout))
end).

View File

@ -0,0 +1,11 @@
-include_lib("eunit/include/eunit.hrl").
-define(OK, 200).
-define(CREATED, 201).
-define(NO_CONTENT, 204).
-define(SEE_OTHER, 303).
-define(BAD_REQUEST, 400).
-define(NOT_AUTHORISED, 401).
%%-define(NOT_FOUND, 404). Defined for AMQP by amqp_client.hrl (as 404)
%% httpc seems to get racy when using HTTP 1.1
-define(HTTPC_OPTS, [{version, "HTTP/1.0"}, {autoredirect, false}]).

View File

@ -0,0 +1,46 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2007-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_control_helper).
-export([command/2, command/3, command/4, command_with_output/4, format_command/4]).
command(Command, Node, Args) ->
command(Command, Node, Args, []).
command(Command, Node) ->
command(Command, Node, [], []).
command(Command, Node, Args, Opts) ->
case command_with_output(Command, Node, Args, Opts) of
{ok, _} -> ok;
ok -> ok;
Error -> Error
end.
command_with_output(Command, Node, Args, Opts) ->
Formatted = format_command(Command, Node, Args, Opts),
CommandResult = 'Elixir.RabbitMQCtl':exec_command(
Formatted, fun(Output,_,_) -> Output end),
ct:pal("Executed command ~p against node ~p~nResult: ~p~n", [Formatted, Node, CommandResult]),
CommandResult.
format_command(Command, Node, Args, Opts) ->
Formatted = io_lib:format("~tp ~ts ~ts",
[Command,
format_args(Args),
format_options([{"--node", Node} | Opts])]),
'Elixir.OptionParser':split(iolist_to_binary(Formatted)).
format_args(Args) ->
iolist_to_binary([ io_lib:format("~tp ", [Arg]) || Arg <- Args ]).
format_options(Opts) ->
EffectiveOpts = [{"--script-name", "rabbitmqctl"} | Opts],
iolist_to_binary([io_lib:format("~s=~tp ", [Key, Value])
|| {Key, Value} <- EffectiveOpts ]).

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,107 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2017-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_ct_config_schema).
-include_lib("common_test/include/ct.hrl").
-export([init_schemas/2]).
-export([run_snippets/1]).
init_schemas(App, Config) ->
ResultsDir = filename:join(?config(priv_dir, Config), "results"),
Snippets = filename:join(?config(data_dir, Config),
atom_to_list(App) ++ ".snippets"),
ok = file:make_dir(ResultsDir),
rabbit_ct_helpers:set_config(Config, [
{results_dir, ResultsDir},
{conf_snippets, Snippets}
]).
run_snippets(Config) ->
{ok, [Snippets]} = file:consult(?config(conf_snippets, Config)),
ct:pal("Loaded config schema snippets: ~p", [Snippets]),
lists:map(
fun({N, S, C, P}) -> ok = test_snippet(Config, {snippet_id(N), S, []}, C, P);
({N, S, A, C, P}) -> ok = test_snippet(Config, {snippet_id(N), S, A}, C, P)
end,
Snippets),
ok.
snippet_id(N) when is_integer(N) ->
integer_to_list(N);
snippet_id(F) when is_float(F) ->
float_to_list(F);
snippet_id(A) when is_atom(A) ->
atom_to_list(A);
snippet_id(L) when is_list(L) ->
L.
test_snippet(Config, Snippet, Expected, _Plugins) ->
{ConfFile, AdvancedFile} = write_snippet(Config, Snippet),
%% We ignore the rabbit -> log portion of the config on v3.9+, where the lager
%% dependency has been dropped
Generated = case code:which(lager) of
non_existing ->
without_rabbit_log(generate_config(ConfFile, AdvancedFile));
_ ->
generate_config(ConfFile, AdvancedFile)
end,
Gen = deepsort(Generated),
Exp = deepsort(Expected),
case Exp of
Gen -> ok;
_ ->
ct:pal("Expected: ~p~ngenerated: ~p", [Expected, Generated]),
ct:pal("Expected (sorted): ~p~ngenerated (sorted): ~p", [Exp, Gen]),
error({config_mismatch, Snippet, Exp, Gen})
end.
write_snippet(Config, {Name, Conf, Advanced}) ->
ResultsDir = ?config(results_dir, Config),
file:make_dir(filename:join(ResultsDir, Name)),
ConfFile = filename:join([ResultsDir, Name, "config.conf"]),
AdvancedFile = filename:join([ResultsDir, Name, "advanced.config"]),
file:write_file(ConfFile, Conf),
rabbit_file:write_term_file(AdvancedFile, [Advanced]),
{ConfFile, AdvancedFile}.
generate_config(ConfFile, AdvancedFile) ->
Context = rabbit_env:get_context(),
rabbit_prelaunch_conf:generate_config_from_cuttlefish_files(
Context, [ConfFile], AdvancedFile).
without_rabbit_log(ErlangConfig) ->
case proplists:get_value(rabbit, ErlangConfig) of
undefined ->
ErlangConfig;
RabbitConfig ->
RabbitConfig1 = lists:keydelete(log, 1, RabbitConfig),
case RabbitConfig1 of
[] ->
lists:keydelete(rabbit, 1, ErlangConfig);
_ ->
lists:keystore(rabbit, 1, ErlangConfig,
{rabbit, RabbitConfig1})
end
end.
deepsort(List) ->
case is_proplist(List) of
true ->
lists:keysort(1, lists:map(fun({K, V}) -> {K, deepsort(V)};
(V) -> V end,
List));
false ->
case is_list(List) of
true -> lists:sort(List);
false -> List
end
end.
is_proplist([{_Key, _Val}|_] = List) -> lists:all(fun({_K, _V}) -> true; (_) -> false end, List);
is_proplist(_) -> false.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2016-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_ct_proper_helpers).
-include_lib("common_test/include/ct.hrl").
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([run_proper/3]).
run_proper(Fun, Args, NumTests) ->
?assert(
proper:counterexample(erlang:apply(Fun, Args),
[{numtests, NumTests},
{on_output, fun(".", _) -> ok; % don't print the '.'s on new lines
(F, A) -> ct:pal(?LOW_IMPORTANCE, F, A) end}])).

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,323 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2010-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_mgmt_test_util).
-include("rabbit_mgmt_test.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile([nowarn_export_all, export_all]).
reset_management_settings(Config) ->
rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbit, collect_statistics_interval, 5000]),
Config.
merge_stats_app_env(Config, Interval, SampleInterval) ->
Config1 = rabbit_ct_helpers:merge_app_env(
Config, {rabbit, [{collect_statistics_interval, Interval}]}),
rabbit_ct_helpers:merge_app_env(
Config1, {rabbitmq_management_agent, [{sample_retention_policies,
[{global, [{605, SampleInterval}]},
{basic, [{605, SampleInterval}]},
{detailed, [{10, SampleInterval}]}] }]}).
http_get_from_node(Config, Node, Path) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, Node, get, Path, [auth_header("guest", "guest")]),
assert_code(?OK, CodeAct, "GET", Path, ResBody),
decode(?OK, Headers, ResBody).
http_get(Config, Path) ->
http_get(Config, Path, ?OK).
http_get(Config, Path, CodeExp) ->
http_get(Config, Path, "guest", "guest", CodeExp).
http_get(Config, Path, User, Pass, CodeExp) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, 0, get, Path, [auth_header(User, Pass)]),
assert_code(CodeExp, CodeAct, "GET", Path, ResBody),
decode(CodeExp, Headers, ResBody).
http_get_as_proplist(Config, Path) ->
{ok, {{_HTTP, CodeAct, _}, _Headers, ResBody}} =
req(Config, get, Path, [auth_header("guest", "guest")]),
assert_code(?OK, CodeAct, "GET", Path, ResBody),
JSON = rabbit_data_coercion:to_binary(ResBody),
cleanup(rabbit_json:decode(JSON, [{return_maps, false}])).
http_get_no_map(Config, Path) ->
http_get_as_proplist(Config, Path).
http_get_no_auth(Config, Path, CodeExp) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, 0, get, Path, []),
assert_code(CodeExp, CodeAct, "GET", Path, ResBody),
decode(CodeExp, Headers, ResBody).
http_put(Config, Path, List, CodeExp) ->
http_put_raw(Config, Path, format_for_upload(List), CodeExp).
http_put(Config, Path, List, User, Pass, CodeExp) ->
http_put_raw(Config, Path, format_for_upload(List), User, Pass, CodeExp).
http_post(Config, Path, List, CodeExp) ->
http_post_raw(Config, Path, format_for_upload(List), CodeExp).
http_post(Config, Path, List, User, Pass, CodeExp) ->
http_post_raw(Config, Path, format_for_upload(List), User, Pass, CodeExp).
http_post_accept_json(Config, Path, List, CodeExp) ->
http_post_accept_json(Config, Path, List, "guest", "guest", CodeExp).
http_post_accept_json(Config, Path, List, User, Pass, CodeExp) ->
http_post_raw(Config, Path, format_for_upload(List), User, Pass, CodeExp,
[{"Accept", "application/json"}]).
assert_permanent_redirect(Config, Path, ExpectedLocation) ->
Node = 0,
Uri = uri_base_from(Config, Node, Path),
ExpectedResponseCode = 301,
{ok, {{_, ExpectedResponseCode, _}, Headers, _}} =
httpc:request(get, {Uri, []}, ?HTTPC_OPTS, []),
Prefix = get_uri_prefix(Config),
?assertEqual(Prefix ++ ExpectedLocation,
proplists:get_value("location", Headers)).
req(Config, Type, Path, Headers) ->
req(Config, 0, Type, Path, Headers).
req(Config, Node, get_static, Path, Headers) ->
httpc:request(get, {uri_base_from(Config, Node, "") ++ Path, Headers}, ?HTTPC_OPTS, []);
req(Config, Node, Type, Path, Headers) ->
httpc:request(Type, {uri_base_from(Config, Node) ++ Path, Headers}, ?HTTPC_OPTS, []).
req(Config, Node, Type, Path, Headers, Body) ->
ContentType = case proplists:get_value("content-type", Headers) of
undefined ->
"application/json";
CT ->
CT
end,
httpc:request(Type, {uri_base_from(Config, Node) ++ Path, Headers, ContentType, Body}, ?HTTPC_OPTS, []).
uri_base_from(Config, Node) ->
uri_base_from(Config, Node, "api").
uri_base_from(Config, Node, Base) ->
Port = mgmt_port(Config, Node),
Prefix = get_uri_prefix(Config),
Uri = rabbit_mgmt_format:print("http://localhost:~w~s/~s", [Port, Prefix, Base]),
binary_to_list(Uri).
get_uri_prefix(Config) ->
ErlNodeCnf = proplists:get_value(erlang_node_config, Config, []),
MgmtCnf = proplists:get_value(rabbitmq_management, ErlNodeCnf, []),
proplists:get_value(path_prefix, MgmtCnf, "").
auth_header(Username, Password) when is_binary(Username) ->
auth_header(binary_to_list(Username), Password);
auth_header(Username, Password) when is_binary(Password) ->
auth_header(Username, binary_to_list(Password));
auth_header(Username, Password) ->
{"Authorization",
"Basic " ++ binary_to_list(base64:encode(Username ++ ":" ++ Password))}.
amqp_port(Config) ->
config_port(Config, tcp_port_amqp).
mgmt_port(Config, Node) ->
config_port(Config, Node, tcp_port_mgmt).
config_port(Config, PortKey) ->
config_port(Config, 0, PortKey).
config_port(Config, Node, PortKey) ->
rabbit_ct_broker_helpers:get_node_config(Config, Node, PortKey).
http_put_raw(Config, Path, Body, CodeExp) ->
http_upload_raw(Config, put, Path, Body, "guest", "guest", CodeExp, []).
http_put_raw(Config, Path, Body, User, Pass, CodeExp) ->
http_upload_raw(Config, put, Path, Body, User, Pass, CodeExp, []).
http_post_raw(Config, Path, Body, CodeExp) ->
http_upload_raw(Config, post, Path, Body, "guest", "guest", CodeExp, []).
http_post_raw(Config, Path, Body, User, Pass, CodeExp) ->
http_upload_raw(Config, post, Path, Body, User, Pass, CodeExp, []).
http_post_raw(Config, Path, Body, User, Pass, CodeExp, MoreHeaders) ->
http_upload_raw(Config, post, Path, Body, User, Pass, CodeExp, MoreHeaders).
http_upload_raw(Config, Type, Path, Body, User, Pass, CodeExp, MoreHeaders) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, 0, Type, Path, [auth_header(User, Pass)] ++ MoreHeaders, Body),
assert_code(CodeExp, CodeAct, Type, Path, ResBody),
decode(CodeExp, Headers, ResBody).
http_delete(Config, Path, CodeExp) ->
http_delete(Config, Path, "guest", "guest", CodeExp).
http_delete(Config, Path, CodeExp, Body) ->
http_delete(Config, Path, "guest", "guest", CodeExp, Body).
http_delete(Config, Path, User, Pass, CodeExp, Body) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, 0, delete, Path, [auth_header(User, Pass)], Body),
assert_code(CodeExp, CodeAct, "DELETE", Path, ResBody),
decode(CodeExp, Headers, ResBody).
http_delete(Config, Path, User, Pass, CodeExp) ->
{ok, {{_HTTP, CodeAct, _}, Headers, ResBody}} =
req(Config, 0, delete, Path, [auth_header(User, Pass)]),
assert_code(CodeExp, CodeAct, "DELETE", Path, ResBody),
decode(CodeExp, Headers, ResBody).
format_for_upload(none) ->
<<"">>;
format_for_upload(List) ->
iolist_to_binary(rabbit_json:encode(List)).
assert_code({one_of, CodesExpected}, CodeAct, Type, Path, Body) when is_list(CodesExpected) ->
case lists:member(CodeAct, CodesExpected) of
true ->
ok;
false ->
error({expected, CodesExpected, got, CodeAct, type, Type,
path, Path, body, Body})
end;
assert_code({group, '2xx'} = CodeExp, CodeAct, Type, Path, Body) ->
case CodeAct of
200 -> ok;
201 -> ok;
202 -> ok;
203 -> ok;
204 -> ok;
205 -> ok;
206 -> ok;
_ -> error({expected, CodeExp, got, CodeAct, type, Type,
path, Path, body, Body})
end;
assert_code({group, '3xx'} = CodeExp, CodeAct, Type, Path, Body) ->
case CodeAct of
300 -> ok;
301 -> ok;
302 -> ok;
303 -> ok;
304 -> ok;
305 -> ok;
306 -> ok;
307 -> ok;
_ -> error({expected, CodeExp, got, CodeAct, type, Type,
path, Path, body, Body})
end;
assert_code({group, '4xx'} = CodeExp, CodeAct, Type, Path, Body) ->
case CodeAct of
400 -> ok;
401 -> ok;
402 -> ok;
403 -> ok;
404 -> ok;
405 -> ok;
406 -> ok;
407 -> ok;
408 -> ok;
409 -> ok;
410 -> ok;
411 -> ok;
412 -> ok;
413 -> ok;
414 -> ok;
415 -> ok;
416 -> ok;
417 -> ok;
_ -> error({expected, CodeExp, got, CodeAct, type, Type,
path, Path, body, Body})
end;
assert_code(CodeExp, CodeAct, Type, Path, Body) when is_list(CodeExp) ->
assert_code({one_of, CodeExp}, CodeAct, Type, Path, Body);
assert_code(CodeExp, CodeAct, Type, Path, Body) ->
case CodeExp of
CodeAct -> ok;
_ -> error({expected, CodeExp, got, CodeAct, type, Type,
path, Path, body, Body})
end.
decode(?OK, _Headers, ResBody) ->
JSON = rabbit_data_coercion:to_binary(ResBody),
cleanup(rabbit_json:decode(JSON));
decode(_, Headers, _ResBody) -> Headers.
cleanup(L) when is_list(L) ->
[cleanup(I) || I <- L];
cleanup(M) when is_map(M) ->
maps:fold(fun(K, V, Acc) ->
Acc#{binary_to_atom(K, latin1) => cleanup(V)}
end, #{}, M);
cleanup(I) ->
I.
%% @todo There wasn't a specific order before; now there is; maybe we shouldn't have one?
assert_list(Exp, Act) ->
case length(Exp) == length(Act) of
true -> ok;
false -> error({expected, Exp, actual, Act})
end,
[case length(lists:filter(fun(ActI) -> test_item(ExpI, ActI) end, Act)) of
1 -> ok;
N -> error({found, N, ExpI, in, Act})
end || ExpI <- Exp].
%_ = [assert_item(ExpI, ActI) || {ExpI, ActI} <- lists:zip(Exp, Act)],
assert_item(ExpI, [H | _] = ActI) when is_list(ActI) ->
%% just check first item of the list
assert_item(ExpI, H),
ok;
assert_item(ExpI, ActI) ->
?assertEqual(ExpI, maps:with(maps:keys(ExpI), ActI)),
ok.
assert_item_kv(Exp, Act) when is_list(Exp) ->
case test_item0_kv(Exp, Act) of
[] -> ok;
Or -> error(Or)
end.
test_item(Exp, Act) ->
case test_item0(Exp, Act) of
[] -> true;
_ -> false
end.
test_item0(Exp, Act) ->
[{did_not_find, KeyExpI, in, Act} || KeyExpI <- maps:keys(Exp),
maps:get(KeyExpI, Exp) =/= maps:get(KeyExpI, Act, null)].
test_item0_kv(Exp, Act) ->
[{did_not_find, ExpI, in, Act} || ExpI <- Exp,
not lists:member(ExpI, Act)].
assert_keys(Exp, Act) ->
case test_key0(Exp, Act) of
[] -> ok;
Or -> error(Or)
end.
test_key0(Exp, Act) ->
[{did_not_find, ExpI, in, Act} || ExpI <- Exp,
not maps:is_key(ExpI, Act)].
assert_no_keys(NotExp, Act) ->
case test_no_key0(NotExp, Act) of
[] -> ok;
Or -> error(Or)
end.
test_no_key0(Exp, Act) ->
[{invalid_key, ExpI, in, Act} || ExpI <- Exp,
maps:is_key(ExpI, Act)].

View File

@ -0,0 +1,166 @@
%% 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 https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2018-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(terraform_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([all/0,
groups/0,
init_per_suite/1, end_per_suite/1,
init_per_group/2, end_per_group/2,
init_per_testcase/2, end_per_testcase/2,
run_code_on_one_vm/1, do_run_code_on_one_vm/1,
run_code_on_three_vms/1, do_run_code_on_three_vms/1,
run_one_rabbitmq_node/1,
run_four_rabbitmq_nodes/1
]).
all() ->
[
{group, direct_vms},
{group, autoscaling_group}
].
groups() ->
[
{direct_vms, [parallel], [{group, run_code},
{group, run_rabbitmq}]},
{autoscaling_group, [parallel], [{group, run_code},
{group, run_rabbitmq}]},
{run_code, [parallel], [run_code_on_one_vm,
run_code_on_three_vms]},
{run_rabbitmq, [parallel], [run_one_rabbitmq_node,
run_four_rabbitmq_nodes]}
].
init_per_suite(Config) ->
rabbit_ct_helpers:log_environment(),
rabbit_ct_helpers:run_setup_steps(Config).
end_per_suite(Config) ->
rabbit_ct_helpers:run_teardown_steps(Config).
init_per_group(autoscaling_group, Config) ->
TfConfigDir = rabbit_ct_vm_helpers:aws_autoscaling_group_module(Config),
rabbit_ct_helpers:set_config(
Config, {terraform_config_dir, TfConfigDir});
init_per_group(Group, Config) ->
rabbit_ct_helpers:set_config(
Config, {run_rabbitmq, Group =:= run_rabbitmq}).
end_per_group(_Group, Config) ->
Config.
init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase),
RunRabbitMQ = ?config(run_rabbitmq, Config),
InstanceCount = case Testcase of
run_code_on_three_vms -> 3;
run_three_rabbitmq_nodes -> 3;
% We want more RabbitMQs than VMs.
run_four_rabbitmq_nodes -> 3;
_ -> 1
end,
InstanceName = rabbit_ct_helpers:testcase_absname(Config, Testcase),
ClusterSize = case Testcase of
run_one_rabbitmq_node -> 1;
run_three_rabbitmq_nodes -> 3;
% We want more RabbitMQs than VMs.
run_four_rabbitmq_nodes -> 4;
_ -> 0
end,
Config1 = rabbit_ct_helpers:set_config(
Config,
[{terraform_instance_count, InstanceCount},
{terraform_instance_name, InstanceName},
{rmq_nodename_suffix, Testcase},
{rmq_nodes_count, ClusterSize}]),
case RunRabbitMQ of
false ->
rabbit_ct_helpers:run_steps(
Config1,
rabbit_ct_vm_helpers:setup_steps());
true ->
rabbit_ct_helpers:run_steps(
Config1,
[fun rabbit_ct_broker_helpers:run_make_dist/1] ++
rabbit_ct_vm_helpers:setup_steps() ++
rabbit_ct_broker_helpers:setup_steps_for_vms())
end.
end_per_testcase(Testcase, Config) ->
RunRabbitMQ = ?config(run_rabbitmq, Config),
Config1 = case RunRabbitMQ of
false ->
rabbit_ct_helpers:run_steps(
Config,
rabbit_ct_vm_helpers:teardown_steps());
true ->
rabbit_ct_helpers:run_steps(
Config,
rabbit_ct_broker_helpers:teardown_steps_for_vms() ++
rabbit_ct_vm_helpers:teardown_steps())
end,
rabbit_ct_helpers:testcase_finished(Config1, Testcase).
%% -------------------------------------------------------------------
%% Run arbitrary code.
%% -------------------------------------------------------------------
run_code_on_one_vm(Config) ->
rabbit_ct_vm_helpers:rpc_all(Config,
?MODULE, do_run_code_on_one_vm, [node()]).
do_run_code_on_one_vm(CTMaster) ->
CTPeer = node(),
ct:pal("Testcase running on ~s", [CTPeer]),
?assertNotEqual(CTMaster, CTPeer),
?assertEqual(pong, net_adm:ping(CTMaster)).
run_code_on_three_vms(Config) ->
rabbit_ct_vm_helpers:rpc_all(Config,
?MODULE, do_run_code_on_three_vms, [node()]).
do_run_code_on_three_vms(CTMaster) ->
CTPeer = node(),
ct:pal("Testcase running on ~s", [CTPeer]),
?assertNotEqual(CTMaster, CTPeer),
?assertEqual(pong, net_adm:ping(CTMaster)).
%% -------------------------------------------------------------------
%% Run RabbitMQ node.
%% -------------------------------------------------------------------
run_one_rabbitmq_node(Config) ->
CTPeers = rabbit_ct_vm_helpers:get_ct_peers(Config),
?assertEqual([false],
[rabbit:is_running(CTPeer) || CTPeer <- CTPeers]),
RabbitMQNodes = rabbit_ct_broker_helpers:get_node_configs(Config, nodename),
?assertEqual([true],
[rabbit:is_running(RabbitMQNode) || RabbitMQNode <- RabbitMQNodes]).
run_four_rabbitmq_nodes(Config) ->
CTPeers = rabbit_ct_vm_helpers:get_ct_peers(Config),
?assertEqual([false, false, false],
[rabbit:is_running(CTPeer) || CTPeer <- CTPeers]),
RabbitMQNodes = lists:sort(
rabbit_ct_broker_helpers:get_node_configs(
Config, nodename)),
?assertEqual([true, true, true, true],
[rabbit:is_running(Node) || Node <- RabbitMQNodes]),
?assertEqual([true, true, true, true],
rabbit_ct_broker_helpers:rpc_all(
Config, rabbit_mnesia, is_clustered, [])),
ClusteredNodes = lists:sort(
rabbit_ct_broker_helpers:rpc(
Config, 0, rabbit_mnesia, cluster_nodes, [running])),
?assertEqual(ClusteredNodes, RabbitMQNodes).

View File

@ -0,0 +1,78 @@
# vim:sw=2:et:
provider "aws" {
region = "eu-west-1"
}
module "direct_vms" {
source = "../direct-vms"
instance_count = 0
erlang_version = var.erlang_version
erlang_git_ref = var.erlang_git_ref
elixir_version = var.elixir_version
erlang_cookie = var.erlang_cookie
erlang_nodename = var.erlang_nodename
ssh_key = var.ssh_key
upload_dirs_archive = var.upload_dirs_archive
instance_name_prefix = var.instance_name_prefix
instance_name = var.instance_name
instance_name_suffix = var.instance_name_suffix
vpc_cidr_block = var.vpc_cidr_block
files_suffix = var.files_suffix
aws_ec2_region = var.aws_ec2_region
}
resource "aws_launch_configuration" "lc" {
name_prefix = module.direct_vms.resource_prefix
image_id = module.direct_vms.instance_ami
instance_type = module.direct_vms.instance_type
key_name = module.direct_vms.ssh_key_name
security_groups = module.direct_vms.security_groups
user_data = module.direct_vms.instance_user_data
lifecycle {
create_before_destroy = true
}
}
resource "aws_autoscaling_group" "asg" {
name_prefix = module.direct_vms.resource_prefix
launch_configuration = aws_launch_configuration.lc.name
min_size = var.instance_count
max_size = var.instance_count
desired_capacity = var.instance_count
vpc_zone_identifier = [module.direct_vms.subnet_id]
tags = [
{
key = "Name"
value = "${module.direct_vms.instance_name} (ASG)"
propagate_at_launch = true
},
{
key = "rabbitmq-testing"
value = true
propagate_at_launch = true
},
{
key = "rabbitmq-testing-id"
value = module.direct_vms.uuid
propagate_at_launch = true
},
{
key = "rabbitmq-testing-suffix"
value = var.files_suffix
propagate_at_launch = true
}
]
lifecycle {
create_before_destroy = true
}
}

View File

@ -0,0 +1,5 @@
# vim:sw=2:et:
output "uuid" {
value = module.direct_vms.uuid
}

View File

@ -0,0 +1,178 @@
#!/bin/sh
# vim:sw=2:et:
set -e
usage() {
echo "Syntax: $(basename "$0") [-Dh] [-c <instance_count>] [-e <elixir_version>] [-s <ssh_key>] <erlang_version> [<erlang_app_dir> ...]"
}
instance_count=1
while getopts "c:e:Dhs:" opt; do
case $opt in
h)
usage
exit
;;
c)
instance_count=$OPTARG
;;
e)
elixir_version=$OPTARG
;;
D)
destroy=yes
;;
s)
ssh_key=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage 1>&2
exit 64
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage 1>&2
exit 64
;;
esac
done
shift $((OPTIND - 1))
erlang_version=$1
if test -z "$erlang_version"; then
echo "Erlang version is required" 1>&2
echo 1>&2
usage
exit 64
fi
shift
terraform_dir=$(cd "$(dirname "$0")" && pwd)
erlang_nodename=control
dirs_archive=dirs-archive.tar.xz
instance_name_prefix="[$(basename "$0")/$USER] "
canonicalize_erlang_version() {
version=$1
case "$version" in
R[0-9]*)
echo "$version" | sed -E 's/(R[0-9]+(:?A|B)[0-9]+).*/\1/'
;;
[0-9]*)
echo "$version" | sed -E 's/([0-9]+\.[0-9]+).*/\1/'
;;
esac
}
find_ssh_key() {
for file in ~/.ssh/*terraform* ~/.ssh/id_rsa ~/.ssh/id_ed25519; do
if test -f "$file" && test -f "$file.pub"; then
echo "$file"
return
fi
done
}
list_dirs_to_upload() {
if test -z "$MAKE"; then
if gmake --version 2>&1 | grep -q "GNU Make"; then
MAKE='gmake'
elif make --version 2>&1 | grep -q "GNU Make"; then
MAKE='make'
fi
fi
template='dirs-to-upload.XXXX'
manifest=$(mktemp -t "$template")
for dir in "$@"; do
(cd "$dir" && pwd) >> "$manifest"
"$MAKE" --no-print-directory -C "$dir" fetch-test-deps >/dev/null
cat "$dir/.erlang.mk/recursive-test-deps-list.log" >> "$manifest"
done
sorted_manifest=$(mktemp -t "$template")
sort -u < "$manifest" > "$sorted_manifest"
# shellcheck disable=SC2094
while read -r dir; do
grep -q "^$dir/" "$sorted_manifest" || echo "$dir"
done < "$sorted_manifest" > "$manifest"
tar cf - -P \
--exclude '.terraform*' \
--exclude 'dirs-archive-*' \
--exclude "$erlang_nodename@*" \
-T "$manifest" \
| xz --threads=0 > "$dirs_archive"
rm "$manifest" "$sorted_manifest"
}
init_terraform() {
terraform init "$terraform_dir"
}
start_vms() {
terraform apply \
-auto-approve=true \
-var="erlang_version=$erlang_branch" \
-var="elixir_version=$elixir_version" \
-var="erlang_cookie=$erlang_cookie" \
-var="erlang_nodename=$erlang_nodename" \
-var="ssh_key=$ssh_key" \
-var="instance_count=$instance_count" \
-var="instance_name_prefix=\"$instance_name_prefix\"" \
-var="upload_dirs_archive=$dirs_archive" \
"$terraform_dir"
}
destroy_vms() {
terraform destroy \
-auto-approve=true \
-var="erlang_version=$erlang_branch" \
-var="elixir_version=$elixir_version" \
-var="erlang_cookie=$erlang_cookie" \
-var="erlang_nodename=$erlang_nodename" \
-var="ssh_key=$ssh_key" \
-var="instance_count=$instance_count" \
-var="instance_name_prefix=\"$instance_name_prefix\"" \
-var="upload_dirs_archive=$dirs_archive" \
"$terraform_dir"
}
erlang_branch=$(canonicalize_erlang_version "$erlang_version")
if test -z "$erlang_branch"; then
echo "Erlang version '$erlang_version' malformed or unrecognized" 1>&2
echo 1>&2
usage
exit 65
fi
if test -z "$ssh_key"; then
ssh_key=$(find_ssh_key)
fi
if test -z "$ssh_key" || ! test -f "$ssh_key" || ! test -f "$ssh_key.pub"; then
echo "Please specify a private SSH key using '-s'" 1>&2
echo 1>&2
usage
exit 65
fi
erlang_cookie=$(cat ~/.erlang.cookie)
list_dirs_to_upload "$@"
init_terraform
case "$destroy" in
yes)
destroy_vms
;;
*)
start_vms
;;
esac

View File

@ -0,0 +1,80 @@
# vim:sw=2:et:
variable "erlang_version" {
description = <<EOF
Erlang version to deploy on VMs. This may also determine the version of
the underlying OS.
EOF
}
variable "erlang_git_ref" {
default = ""
description = <<EOF
Git reference if building Erlang from Git. Specifying the Erlang
version is still required.
EOF
}
variable "elixir_version" {
default = ""
description = <<EOF
Elixir version to deploy on VMs. Default to the latest available.
EOF
}
variable "erlang_cookie" {
description = <<EOF
Erlang cookie to deploy on VMs.
EOF
}
variable "erlang_nodename" {
description = <<EOF
Name of the remote Erlang node.
EOF
}
variable "ssh_key" {
description = <<EOF
Path to the private SSH key to use to communicate with the VMs. The
module then assumes that the public key is named "$ssh_key.pub".
EOF
}
variable "instance_count" {
default = "1"
description = <<EOF
Number of VMs to spawn.
EOF
}
variable "upload_dirs_archive" {
description = <<EOF
Archive of the directories to upload to the VMs. They will be placed
in / on the VM, which means that the paths can be identical.
EOF
}
variable "instance_name_prefix" {
default = "RabbitMQ testing: "
}
variable "instance_name_suffix" {
default = ""
}
variable "instance_name" {
default = "Unnamed"
}
variable "vpc_cidr_block" {
default = "10.0.0.0/16"
}
variable "files_suffix" {
default = ""
}
variable "aws_ec2_region" {
default = "eu-west-1"
}

View File

@ -0,0 +1,234 @@
# vim:sw=2:et:
provider "aws" {
region = var.aws_ec2_region
}
locals {
vm_name = "${var.instance_name_prefix}${var.instance_name}${var.instance_name_suffix} - Erlang ${var.erlang_version}"
resource_prefix = "rabbitmq-testing-"
distribution = lookup(var.erlang_version_to_system, var.erlang_version)
ec2_instance_type = lookup(var.ec2_instance_types, local.distribution, "m5.large")
ami = lookup(var.amis, local.distribution)
username = lookup(var.usernames, local.distribution, "ec2-user")
}
// The directories archive is uploaded to Amazon S3. We first create a
// temporary bucket.
//
// Note that we use this unique bucket name as a unique ID elsewhere.
resource "aws_s3_bucket" "dirs_archive" {
bucket_prefix = local.resource_prefix
acl = "private"
}
locals {
uuid = replace(aws_s3_bucket.dirs_archive.id, local.resource_prefix, "")
dirs_archive = var.upload_dirs_archive
}
// We configure a VPC and a bucket policy to allow us to make the
// directories archive private on S3 but still access it from the VMs.
resource "aws_vpc" "vpc" {
cidr_block = var.vpc_cidr_block
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = local.vm_name
rabbitmq-testing = true
rabbitmq-testing-id = local.uuid
rabbitmq-testing-suffix = var.files_suffix
}
}
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.vpc.id
}
resource "aws_default_route_table" "rt" {
default_route_table_id = aws_vpc.vpc.default_route_table_id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
}
resource "aws_vpc_endpoint" "vpc" {
vpc_id = aws_vpc.vpc.id
service_name = "com.amazonaws.${aws_s3_bucket.dirs_archive.region}.s3"
route_table_ids = [aws_default_route_table.rt.id]
}
resource "aws_subnet" "vpc" {
cidr_block = var.vpc_cidr_block
vpc_id = aws_vpc.vpc.id
map_public_ip_on_launch = true
}
resource "aws_s3_bucket_policy" "dirs_archive" {
bucket = aws_s3_bucket.dirs_archive.id
policy = <<EOF
{
"Version": "2012-10-17",
"Id": "Policy",
"Statement": [
{
"Sid": "Access-to-specific-VPCE-only",
"Action": "s3:*",
"Effect": "Allow",
"Resource": ["arn:aws:s3:::${aws_s3_bucket.dirs_archive.id}",
"arn:aws:s3:::${aws_s3_bucket.dirs_archive.id}/*"],
"Condition": {
"StringEquals": {
"aws:sourceVpce": "${aws_vpc_endpoint.vpc.id}"
}
},
"Principal": "*"
}
]
}
EOF
}
// We are now ready to actually upload the directories archive to S3.
resource "aws_s3_bucket_object" "dirs_archive" {
bucket = aws_s3_bucket.dirs_archive.id
key = basename(local.dirs_archive)
source = local.dirs_archive
}
// SSH key to communicate with the VMs.
resource "aws_key_pair" "ci_user" {
key_name_prefix = local.resource_prefix
public_key = file("${var.ssh_key}.pub")
}
// Security group to allow SSH connections.
resource "aws_security_group" "allow_ssh" {
name_prefix = "${local.resource_prefix}ssh-"
description = "Allow incoming SSH connections"
vpc_id = aws_vpc.vpc.id
ingress {
from_port = 0
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
// We need a security group to allow Erlang distribution between VMs and
// also with the local host.
resource "aws_security_group" "allow_erlang_dist" {
name_prefix = "${local.resource_prefix}erlang-"
description = "Allow Erlang distribution connections"
vpc_id = aws_vpc.vpc.id
ingress {
from_port = 0
to_port = 4369
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 10240
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
// Setup script executed on VMs on startup. Its main purpose is to
// install and configure Erlang, and start an Erlang node to later
// control the VM.
data "template_file" "user_data" {
template = file("${path.module}/templates/setup-erlang.sh")
vars = {
default_user = local.username
distribution = local.distribution
dirs_archive_url = "http://${aws_s3_bucket.dirs_archive.bucket_domain_name}/${aws_s3_bucket_object.dirs_archive.id}"
erlang_cookie = var.erlang_cookie
erlang_nodename = var.erlang_nodename
erlang_version = var.erlang_version
erlang_git_ref = var.erlang_git_ref
elixir_version = var.elixir_version
}
}
locals {
security_groups = [
aws_security_group.allow_ssh.id,
aws_security_group.allow_erlang_dist.id,
]
}
// With the directories archive and the VPC in place, we can spawn the
// VMs.
resource "aws_instance" "vm" {
ami = local.ami
instance_type = local.ec2_instance_type
count = var.instance_count
key_name = aws_key_pair.ci_user.key_name
subnet_id = aws_subnet.vpc.id
vpc_security_group_ids = local.security_groups
user_data = data.template_file.user_data.rendered
// We need about 1.5 GiB of storage space, but apparently, 8 GiB is
// the minimum.
root_block_device {
volume_size = 8
delete_on_termination = true
}
tags = {
Name = "${local.vm_name} - #${count.index}"
rabbitmq-testing = true
rabbitmq-testing-id = local.uuid
}
connection {
type = "ssh"
user = local.username
private_key = file(var.ssh_key)
agent = false
}
}
data "template_file" "erlang_node_hostname" {
count = var.instance_count
template = "$${private_dns}"
vars = {
private_dns = element(split(".", aws_instance.vm.*.private_dns[count.index]), 0)
}
}
data "template_file" "erlang_node_nodename" {
count = var.instance_count
template = "${var.erlang_nodename}@$${private_dns}"
vars = {
private_dns = data.template_file.erlang_node_hostname.*.rendered[count.index]
}
}

View File

@ -0,0 +1,59 @@
# vim:sw=2:et:
output "uuid" {
value = local.uuid
}
output "ct_peer_ipaddrs" {
value = zipmap(
data.template_file.erlang_node_hostname.*.rendered,
aws_instance.vm.*.public_ip)
}
output "ct_peer_nodenames" {
value = zipmap(
data.template_file.erlang_node_hostname.*.rendered,
data.template_file.erlang_node_nodename.*.rendered)
}
output "ssh_user_and_host" {
value = zipmap(
data.template_file.erlang_node_hostname.*.rendered,
formatlist("%s@%s", local.username, aws_instance.vm.*.public_dns))
}
// The following variables are used by other modules (e.g.
// `autoscaling-group`) who want to benefit from the same resources
// (beside the actual instances).
output "resource_prefix" {
value = local.resource_prefix
}
output "instance_name" {
value = local.vm_name
}
output "instance_ami" {
value = local.ami
}
output "instance_type" {
value = local.ec2_instance_type
}
output "ssh_key_name" {
value = aws_key_pair.ci_user.key_name
}
output "security_groups" {
value = local.security_groups
}
output "instance_user_data" {
value = data.template_file.user_data.rendered
}
output "subnet_id" {
value = aws_subnet.vpc.id
}

View File

@ -0,0 +1,187 @@
#!/bin/sh
# vim:sw=2:et:
set -e
usage() {
echo "Syntax: $(basename "$0") [-Dh] [-c <instance_count>] [-e <elixir_version>] [-s <ssh_key>] <erlang_version> [<erlang_app_dir> ...]"
}
instance_count=1
while getopts "c:e:Dhs:" opt; do
case $opt in
h)
usage
exit
;;
c)
instance_count=$OPTARG
;;
e)
elixir_version=$OPTARG
;;
D)
destroy=yes
;;
s)
ssh_key=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage 1>&2
exit 64
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage 1>&2
exit 64
;;
esac
done
shift $((OPTIND - 1))
erlang_version=$1
if test -z "$erlang_version"; then
echo "Erlang version is required" 1>&2
echo 1>&2
usage
exit 64
fi
shift
terraform_dir=$(cd "$(dirname "$0")" && pwd)
erlang_nodename=control
dirs_archive=dirs-archive.tar.xz
instance_name_prefix="[$(basename "$0")/$USER] "
canonicalize_erlang_version() {
version=$1
case "$version" in
R[0-9]*)
echo "$version" | sed -E 's/(R[0-9]+(:?A|B)[0-9]+).*/\1/'
;;
[0-9]*)
echo "$version" | sed -E 's/([0-9]+\.[0-9]+).*/\1/'
;;
esac
}
find_ssh_key() {
for file in ~/.ssh/*terraform* ~/.ssh/id_rsa ~/.ssh/id_ed25519; do
if test -f "$file" && test -f "$file.pub"; then
echo "$file"
return
fi
done
}
list_dirs_to_upload() {
if test -z "$MAKE"; then
if gmake --version 2>&1 | grep -q "GNU Make"; then
MAKE='gmake'
elif make --version 2>&1 | grep -q "GNU Make"; then
MAKE='make'
fi
fi
template='dirs-to-upload.XXXX'
manifest=$(mktemp -t "$template")
for dir in "$@"; do
(cd "$dir" && pwd) >> "$manifest"
"$MAKE" --no-print-directory -C "$dir" fetch-test-deps >/dev/null
cat "$dir/.erlang.mk/recursive-test-deps-list.log" >> "$manifest"
done
sorted_manifest=$(mktemp -t "$template")
sort -u < "$manifest" > "$sorted_manifest"
# shellcheck disable=SC2094
while read -r dir; do
grep -q "^$dir/" "$sorted_manifest" || echo "$dir"
done < "$sorted_manifest" > "$manifest"
tar cf - -P \
--exclude '.terraform*' \
--exclude 'dirs-archive-*' \
--exclude "$erlang_nodename@*" \
-T "$manifest" \
| xz --threads=0 > "$dirs_archive"
rm "$manifest" "$sorted_manifest"
}
init_terraform() {
terraform init "$terraform_dir"
}
start_vms() {
terraform apply \
-auto-approve=true \
-var="erlang_version=$erlang_branch" \
-var="elixir_version=$elixir_version" \
-var="erlang_git_ref=$erlang_git_ref" \
-var="erlang_cookie=$erlang_cookie" \
-var="erlang_nodename=$erlang_nodename" \
-var="ssh_key=$ssh_key" \
-var="instance_count=$instance_count" \
-var="instance_name_prefix=\"$instance_name_prefix\"" \
-var="upload_dirs_archive=$dirs_archive" \
"$terraform_dir"
}
destroy_vms() {
terraform destroy \
-auto-approve=true \
-var="erlang_version=$erlang_branch" \
-var="elixir_version=$elixir_version" \
-var="erlang_git_ref=$erlang_git_ref" \
-var="erlang_cookie=$erlang_cookie" \
-var="erlang_nodename=$erlang_nodename" \
-var="ssh_key=$ssh_key" \
-var="instance_count=$instance_count" \
-var="instance_name_prefix=\"$instance_name_prefix\"" \
-var="upload_dirs_archive=$dirs_archive" \
"$terraform_dir"
}
case "$erlang_version" in
*@*)
erlang_git_ref=${erlang_version#*@}
erlang_version=${erlang_version%@*}
;;
esac
erlang_branch=$(canonicalize_erlang_version "$erlang_version")
if test -z "$erlang_branch"; then
echo "Erlang version '$erlang_version' malformed or unrecognized" 1>&2
echo 1>&2
usage
exit 65
fi
if test -z "$ssh_key"; then
ssh_key=$(find_ssh_key)
fi
if test -z "$ssh_key" || ! test -f "$ssh_key" || ! test -f "$ssh_key.pub"; then
echo "Please specify a private SSH key using '-s'" 1>&2
echo 1>&2
usage
exit 65
fi
erlang_cookie=$(cat ~/.erlang.cookie)
list_dirs_to_upload "$@"
init_terraform
case "$destroy" in
yes)
destroy_vms
;;
*)
start_vms
;;
esac

View File

@ -0,0 +1,264 @@
#!/bin/sh
# vim:sw=2:et:
set -ex
# Execute ourselves as root if we are an unprivileged user.
if test "$(id -u)" != '0'; then
exec sudo -i "$0" "$@"
fi
HOME=/root
export HOME
DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND
# shellcheck disable=SC2016
readonly erlang_version='${erlang_version}'
# shellcheck disable=SC2016
erlang_git_ref='${erlang_git_ref}'
# shellcheck disable=SC2016
readonly elixir_version='${elixir_version}'
# shellcheck disable=SC2016
readonly erlang_nodename='${erlang_nodename}'
# shellcheck disable=SC2016
readonly default_user='${default_user}'
# shellcheck disable=SC2016
readonly dirs_archive_url='${dirs_archive_url}'
# shellcheck disable=SC2016
readonly distribution='${distribution}'
# shellcheck disable=SC2016
readonly erlang_cookie='${erlang_cookie}'
readonly debian_codename="$${distribution#debian-*}"
case "$erlang_version" in
24.*)
if test -z "$erlang_git_ref"; then
erlang_git_ref='master'
fi
;;
23.*|22.*|21.*|20.*|19.3)
readonly erlang_package_version="1:$erlang_version-1"
;;
R16B03)
readonly erlang_package_version='1:16.b.3-3'
;;
*)
echo "[ERROR] unknown erlang version: $erlang_version" 1>&2
exit 69 # EX_UNAVAILABLE; see sysexists(3)
;;
esac
install_essentials() {
apt-get -qq update
apt-get -qq install wget curl gnupg
}
setup_backports() {
# Enable backports.
cat >/etc/apt/sources.list.d/backports.list << EOF
deb http://cdn-fastly.deb.debian.org/debian $debian_codename-backports main
EOF
apt-get -qq update
}
# --------------------------------------------------------------------
# Functions to take Erlang and Elixir from Debian packages.
# --------------------------------------------------------------------
determine_version_to_pin() {
package=$1
min_version=$2
apt-cache policy "$package" | \
awk '
BEGIN {
version_to_pin = "";
}
/^ ( |\*\*\*) [^ ]/ {
if ($1 == "***") {
version = $2;
} else {
version = $1;
}
if (version_to_pin) {
exit;
} else if (match(version, /^'$min_version'([-.]|$)/)) {
version_to_pin = version;
}
}
END {
if (version_to_pin) {
print version_to_pin;
exit;
} else {
exit 1;
}
}'
}
setup_erlang_deb_repository() {
# Setup repository to get Erlang.
wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | apt-key add -
wget -O- https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-erlang/gpg.E495BB49CC4BBE5B.key | apt-key add -
cat >/etc/apt/sources.list.d/rabbitmq-erlang.list <<EOF
deb https://dl.cloudsmith.io/public/rabbitmq/rabbitmq-erlang/deb/debian buster main
EOF
# Configure Erlang version pinning.
cat >/etc/apt/preferences.d/erlang <<EOF
Package: erlang*
Pin: version $erlang_package_version
Pin-Priority: 1000
EOF
apt-get -qq install -y --no-install-recommends apt-transport-https
apt-get -qq update
}
apt_install_erlang() {
apt-get -qq install -y --no-install-recommends \
erlang-base erlang-nox erlang-dev erlang-src erlang-common-test
}
apt_install_elixir() {
if test "$elixir_version"; then
# Configure Elixir version pinning.
elixir_package_version=$(determine_version_to_pin elixir "$elixir_version")
cat >/etc/apt/preferences.d/elixir <<EOF
Package: elixir
Pin: version $elixir_package_version
Pin-Priority: 1000
EOF
fi
apt-get -qq install -y --no-install-recommends elixir
}
apt_install_extra() {
readonly extra_pkgs='git make rsync vim-nox xz-utils zip'
readonly extra_backports=''
# shellcheck disable=SC2086
test -z "$extra_pkgs" || \
apt-get -qq install -y --no-install-recommends \
$extra_pkgs
# shellcheck disable=SC2086
test -e "$extra_backports" || \
apt-get -qq install -y -V --fix-missing --no-install-recommends \
-t "$debian_codename"-backports \
$extra_backports
}
# --------------------------------------------------------------------
# Functions to build Erlang and Elixir from sources.
# --------------------------------------------------------------------
install_kerl() {
apt-get -qq install -y --no-install-recommends \
curl
mkdir -p /usr/local/bin
cd /usr/local/bin
curl -O https://raw.githubusercontent.com/kerl/kerl/master/kerl
chmod a+x kerl
}
kerl_install_erlang() {
apt-get -qq install -y --no-install-recommends \
git \
build-essential \
autoconf automake libtool \
libssl-dev \
libncurses5-dev \
libsctp1 libsctp-dev
kerl build git https://github.com/erlang/otp.git "$erlang_git_ref" "$erlang_version"
kerl install "$erlang_version" /usr/local/erlang
. /usr/local/erlang/activate
echo '. /usr/local/erlang/activate' > /etc/profile.d/erlang.sh
}
install_kiex() {
curl -sSL https://raw.githubusercontent.com/taylor/kiex/master/install | bash -s
mv "$HOME/.kiex" /usr/local/kiex
sed -E \
-e 's,\\\$HOME/\.kiex,/usr/local/kiex,' \
-e 's,\$HOME/\.kiex,/usr/local/kiex,' \
< /usr/local/kiex/bin/kiex \
> /usr/local/kiex/bin/kiex.patched
mv /usr/local/kiex/bin/kiex.patched /usr/local/kiex/bin/kiex
chmod a+x /usr/local/kiex/bin/kiex
}
kiex_install_elixir() {
case "$erlang_version" in
22.*|23.*|24.*)
url="https://github.com/elixir-lang/elixir/releases/download/v$elixir_version/Precompiled.zip"
wget -q -O/tmp/elixir.zip "$url"
apt-get -qq install -y --no-install-recommends unzip
mkdir -p /usr/local/elixir
(cd /usr/local/elixir && unzip -q /tmp/elixir.zip)
export PATH=/usr/local/elixir/bin:$PATH
;;
*)
export PATH=/usr/local/kiex/bin:$PATH
latest_elixir_version=$(kiex list releases | tail -n 1 | awk '{print $1}')
kiex install $latest_elixir_version
. /usr/local/kiex/elixirs/elixir-$latest_elixir_version.env
cat >> /etc/profile.d/erlang.sh <<EOF
. /usr/local/kiex/elixirs/elixir-$latest_elixir_version.env
EOF
;;
esac
}
# --------------------------------------------------------------------
# Main.
# --------------------------------------------------------------------
install_essentials
setup_backports
# Install Erlang + various tools.
if test "$erlang_package_version"; then
setup_erlang_deb_repository
apt_install_erlang
apt_install_elixir
elif test "$erlang_git_ref"; then
install_kerl
kerl_install_erlang
install_kiex
kiex_install_elixir
fi
apt_install_extra
# Store Erlang cookie file for both root and the default user.
for file in ~/.erlang.cookie "/home/$default_user/.erlang.cookie"; do
echo "$erlang_cookie" > "$file"
chmod 400 "$file"
done
chown "$default_user" "/home/$default_user/.erlang.cookie"
# Fetch and extract the dirs archive.
dirs_archive="/tmp/$(basename "$dirs_archive_url")"
wget -q -O"$dirs_archive" "$dirs_archive_url"
if test -s "$dirs_archive"; then
xzcat "$dirs_archive" | tar xf - -P
fi
rm -f "$dirs_archive"
# Start an Erlang node to control the VM from Erlang.
erl -noinput -sname "$erlang_nodename" -hidden -detached

View File

@ -0,0 +1,147 @@
# vim:sw=2:et:
variable "erlang_version" {
description = <<EOF
Erlang version to deploy on VMs. This may also determine the version of
the underlying OS.
EOF
}
variable "erlang_git_ref" {
default = ""
description = <<EOF
Git reference if building Erlang from Git. Specifying the Erlang
version is still required.
EOF
}
variable "elixir_version" {
default = ""
description = <<EOF
Elixir version to deploy on VMs. Default to the latest available.
EOF
}
variable "erlang_cookie" {
description = <<EOF
Erlang cookie to deploy on VMs.
EOF
}
variable "erlang_nodename" {
default = "control"
description = <<EOF
Name of the remote Erlang node.
EOF
}
variable "ssh_key" {
description = <<EOF
Path to the private SSH key to use to communicate with the VMs. The
module then assumes that the public key is named "$ssh_key.pub".
EOF
}
variable "instance_count" {
default = "1"
description = <<EOF
Number of VMs to spawn.
EOF
}
variable "upload_dirs_archive" {
description = <<EOF
Archive of the directories to upload to the VMs. They will be placed
in / on the VM, which means that the paths can be identical.
EOF
}
variable "instance_name_prefix" {
default = "RabbitMQ testing: "
}
variable "instance_name_suffix" {
default = ""
}
variable "instance_name" {
default = "Unnamed"
}
variable "vpc_cidr_block" {
default = "10.0.0.0/16"
}
variable "files_suffix" {
default = ""
}
variable "aws_ec2_region" {
default = "eu-west-1"
}
variable "erlang_version_to_system" {
type = map
default = {
"22.3" = "debian-buster"
"23.0" = "debian-buster"
"23.1" = "debian-buster"
"23.2" = "debian-buster"
"23.3" = "debian-buster"
"24.0" = "debian-buster"
}
}
variable "ec2_instance_types" {
type = map
default = {
}
}
# AMIs for eu-west-1 (Ireland)
variable "amis" {
type = map
default = {
"centos-7" = "ami-6e28b517"
"centos-8" = "ami-0645e7b5435a343a5" # Community-provided
"debian-buster" = "ami-02498d1ddb8cc6a86" # Community-provided
"fedora-30" = "ami-0c8df718af40abdae"
"fedora-31" = "ami-00d8194a6e394e1c5"
"fedora-32" = "ami-0f17c0eb4a2e08778"
"fedora-33" = "ami-0aa3a65f84cb982ca"
"freebsd-10" = "ami-76f82c0f"
"freebsd-11" = "ami-ab56bed2"
"opensuse-leap-15.1" = "ami-0f81506cab2b62029"
"opensuse-leap-15.2" = "ami-013f2b687f5a91567"
"rhel-7" = "ami-8b8c57f8"
"sles-11" = "ami-a2baf5d5"
"sles-12" = "ami-f4278487"
"ubuntu-16.04" = "ami-067b6923c66564bf6"
"ubuntu-18.04" = "ami-01cca82393e531118"
"ubuntu-20.04" = "ami-09376517f0f510ad9"
}
}
variable "usernames" {
type = map
default = {
"centos-7" = "centos"
"centos-8" = "centos"
"debian-buster" = "admin"
"debian-bullseye" = "admin"
"fedora-30" = "fedora"
"fedora-31" = "fedora"
"fedora-32" = "fedora"
"fedora-33" = "fedora"
"freebsd-10" = "ec2-user"
"freebsd-11" = "ec2-user"
"opensuse-leap-15.1" = "ec2-user"
"opensuse-leap-15.2" = "ec2-user"
"rhel-7" = "ec2-user"
"sles-11" = "ec2-user"
"sles-12" = "ec2-user"
"ubuntu-16.04" = "ubuntu"
"ubuntu-18.04" = "ubuntu"
"ubuntu-20.04" = "ubuntu"
}
}

View File

@ -0,0 +1,31 @@
# vim:sw=2:et:
provider "aws" {
region = "eu-west-1"
}
data "aws_instances" "vms" {
instance_tags = {
rabbitmq-testing = true
rabbitmq-testing-id = var.uuid
}
}
data "template_file" "erlang_node_hostname" {
count = length(data.aws_instances.vms.ids)
template = "$${private_dns}"
vars = {
// FIXME: Here we hard-code how Amazon EC2 formats hostnames based
// on the private IP address.
private_dns = "ip-${
join("-", split(".", data.aws_instances.vms.private_ips[count.index]))}"
}
}
data "template_file" "erlang_node_nodename" {
count = length(data.aws_instances.vms.ids)
template = "${var.erlang_nodename}@$${private_dns}"
vars = {
private_dns = data.template_file.erlang_node_hostname.*.rendered[count.index]
}
}

View File

@ -0,0 +1,21 @@
# vim:sw=2:et:
output "instance_count" {
value = length(data.aws_instances.vms.ids)
}
output "instance_ids" {
value = data.aws_instances.vms.ids
}
output "ct_peer_ipaddrs" {
value = zipmap(
data.template_file.erlang_node_hostname.*.rendered,
data.aws_instances.vms.public_ips)
}
output "ct_peer_nodenames" {
value = zipmap(
data.template_file.erlang_node_hostname.*.rendered,
data.template_file.erlang_node_nodename.*.rendered)
}

View File

@ -0,0 +1,55 @@
#!/bin/sh
# vim:sw=2:et:
set -e
usage() {
echo "Syntax: $(basename "$0") [-h] <uuid>"
}
while getopts "h" opt; do
case $opt in
h)
usage
exit
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage 1>&2
exit 64
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage 1>&2
exit 64
;;
esac
done
shift $((OPTIND - 1))
uuid=$1
if test -z "$uuid"; then
echo "Unique ID is required" 1>&2
echo 1>&2
usage
exit 64
fi
shift
terraform_dir=$(cd "$(dirname "$0")" && pwd)
init_terraform() {
terraform init "$terraform_dir"
}
query_vms() {
terraform apply \
-auto-approve=true \
-var="uuid=$uuid" \
-var="erlang_nodename=control" \
"$terraform_dir"
}
init_terraform
query_vms

View File

@ -0,0 +1,14 @@
# vim:sw=2:et:
variable "uuid" {
description = <<EOF
Unique ID of the deployment.
EOF
}
variable "erlang_nodename" {
default = "unspecified"
description = <<EOF
Name of the remote Erlang node.
EOF
}

View File

@ -0,0 +1 @@
openssl.cnf

View File

@ -0,0 +1,70 @@
ifndef DIR
$(error DIR must be specified)
endif
PASSWORD ?= changeme
HOSTNAME := $(shell if [ "$$(uname)" = Darwin ]; then hostname -s; else hostname; fi)
# Verbosity.
V ?= 0
verbose_0 = @
verbose_2 = set -x;
verbose = $(verbose_$(V))
gen_verbose_0 = @echo " GEN " $@;
gen_verbose_2 = set -x;
gen_verbose = $(gen_verbose_$(V))
openssl_output_0 = 2>/dev/null
openssl_output = $(openssl_output_$(V))
.PRECIOUS: %/testca/cacert.pem
.PHONY: all testca server client clean
all: server client
@:
testca: $(DIR)/testca/cacert.pem
server: TARGET = server
server: $(DIR)/server/cert.pem
@:
client: TARGET = client
client: $(DIR)/client/cert.pem
@:
$(DIR)/testca/cacert.pem:
$(gen_verbose) mkdir -p $(dir $@)
$(verbose) { ( cd $(dir $@) && \
mkdir -p certs private && \
chmod 700 private && \
echo 01 > serial && \
:> index.txt && \
sed -e 's/@HOSTNAME@/$(HOSTNAME)/g' $(CURDIR)/openssl.cnf.in > $(CURDIR)/openssl.cnf && \
openssl req -x509 -config $(CURDIR)/openssl.cnf -newkey rsa:2048 -days 365 \
-out cacert.pem -outform PEM -subj /CN=MyTestCA/L=$$$$/ -nodes && \
openssl x509 -in cacert.pem -out cacert.cer -outform DER ) $(openssl_output) \
|| (rm -rf $(dir $@) && false); }
$(DIR)/%/cert.pem: $(DIR)/testca/cacert.pem
$(gen_verbose) mkdir -p $(DIR)/$(TARGET)
$(verbose) { ( cd $(DIR)/$(TARGET) && \
openssl genrsa -out key.pem 2048 && \
openssl req -new -key key.pem -out req.pem -outform PEM \
-subj /C=UK/ST=England/CN=$(HOSTNAME)/O=$(TARGET)/L=$$$$/ -nodes && \
cd ../testca && \
sed -e 's/@HOSTNAME@/$(HOSTNAME)/g' $(CURDIR)/openssl.cnf.in > $(CURDIR)/openssl.cnf && \
openssl ca -config $(CURDIR)/openssl.cnf -in ../$(TARGET)/req.pem -out \
../$(TARGET)/cert.pem -notext -batch -extensions \
$(TARGET)_ca_extensions && \
cd ../$(TARGET) && \
openssl pkcs12 -export -out keycert.p12 -in cert.pem -inkey key.pem \
-passout pass:$(PASSWORD) ) $(openssl_output) || (rm -rf $(DIR)/$(TARGET) && false); }
clean:
rm -rf $(DIR)/testca
rm -rf $(DIR)/server
rm -rf $(DIR)/client

View File

@ -0,0 +1,62 @@
[ ca ]
default_ca = testca
[ testca ]
dir = .
certificate = $dir/cacert.pem
database = $dir/index.txt
new_certs_dir = $dir/certs
private_key = $dir/private/cakey.pem
serial = $dir/serial
default_crl_days = 7
default_days = 365
default_md = sha256
policy = testca_policy
x509_extensions = certificate_extensions
[ testca_policy ]
commonName = supplied
stateOrProvinceName = optional
countryName = optional
emailAddress = optional
organizationName = optional
organizationalUnitName = optional
domainComponent = optional
[ certificate_extensions ]
basicConstraints = CA:false
[ req ]
default_bits = 2048
default_keyfile = ./private/cakey.pem
default_md = sha256
prompt = yes
distinguished_name = root_ca_distinguished_name
x509_extensions = root_ca_extensions
[ root_ca_distinguished_name ]
commonName = hostname
countryName_default = UK
stateOrProvinceName_default = London
organizationName_default = RabbitMQ
[ root_ca_extensions ]
basicConstraints = CA:true
keyUsage = keyCertSign, cRLSign
[ client_ca_extensions ]
basicConstraints = CA:false
keyUsage = digitalSignature,keyEncipherment
extendedKeyUsage = 1.3.6.1.5.5.7.3.2
[ server_ca_extensions ]
basicConstraints = CA:false
keyUsage = digitalSignature,keyEncipherment
extendedKeyUsage = 1.3.6.1.5.5.7.3.1
subjectAltName = @server_alt_names
[ server_alt_names ]
DNS.1 = @HOSTNAME@
DNS.2 = localhost

View File

@ -0,0 +1 @@
I'm not a certificate

View File

@ -0,0 +1 @@
I'm not a certificate

View File

@ -0,0 +1 @@
I'm not a certificate

View File

@ -0,0 +1,436 @@
%% ----------------------------------------------------------------------------
%% RabbitMQ Management Plugin
%%
%% See https://www.rabbitmq.com/management.html for details
%% ----------------------------------------------------------------------------
%% Load definitions from a JSON file or directory of files. See
%% https://www.rabbitmq.com/management.html#load-definitions
%%
%% {load_definitions, "/path/to/schema.json"},
%% {load_definitions, "/path/to/schemas"},
{mapping, "management.load_definitions", "rabbitmq_management.load_definitions",
[{datatype, string},
{validators, ["file_accessible"]}]}.
%% Log all requests to the management HTTP API to a file.
%%
%% {http_log_dir, "/path/to/access.log"},
{mapping, "management.http_log_dir", "rabbitmq_management.http_log_dir",
[{datatype, string}]}.
%% HTTP (TCP) listener options ========================================================
%% HTTP listener consistent with Web STOMP and Web MQTT.
%%
%% {tcp_config, [{port, 15672},
%% {ip, "127.0.0.1"}]}
{mapping, "management.tcp.port", "rabbitmq_management.tcp_config.port",
[{datatype, integer}]}.
{mapping, "management.tcp.ip", "rabbitmq_management.tcp_config.ip",
[{datatype, string},
{validators, ["is_ip"]}]}.
{mapping, "management.tcp.compress", "rabbitmq_management.tcp_config.cowboy_opts.compress",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.tcp.idle_timeout", "rabbitmq_management.tcp_config.cowboy_opts.idle_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.tcp.inactivity_timeout", "rabbitmq_management.tcp_config.cowboy_opts.inactivity_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.tcp.request_timeout", "rabbitmq_management.tcp_config.cowboy_opts.request_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.tcp.shutdown_timeout", "rabbitmq_management.tcp_config.cowboy_opts.shutdown_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.tcp.max_keepalive", "rabbitmq_management.tcp_config.cowboy_opts.max_keepalive",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
%% HTTPS (TLS) listener options ========================================================
%% HTTPS listener consistent with Web STOMP and Web MQTT.
%%
%% {ssl_config, [{port, 15671},
%% {ip, "127.0.0.1"},
%% {cacertfile, "/path/to/cacert.pem"},
%% {certfile, "/path/to/cert.pem"},
%% {keyfile, "/path/to/key.pem"}]}
{mapping, "management.ssl.port", "rabbitmq_management.ssl_config.port",
[{datatype, integer}]}.
{mapping, "management.ssl.backlog", "rabbitmq_management.ssl_config.backlog",
[{datatype, integer}]}.
{mapping, "management.ssl.ip", "rabbitmq_management.ssl_config.ip",
[{datatype, string}, {validators, ["is_ip"]}]}.
{mapping, "management.ssl.certfile", "rabbitmq_management.ssl_config.certfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.ssl.keyfile", "rabbitmq_management.ssl_config.keyfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.ssl.cacertfile", "rabbitmq_management.ssl_config.cacertfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.ssl.password", "rabbitmq_management.ssl_config.password",
[{datatype, string}]}.
{mapping, "management.ssl.verify", "rabbitmq_management.ssl_config.verify", [
{datatype, {enum, [verify_peer, verify_none]}}]}.
{mapping, "management.ssl.fail_if_no_peer_cert", "rabbitmq_management.ssl_config.fail_if_no_peer_cert", [
{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.honor_cipher_order", "rabbitmq_management.ssl_config.honor_cipher_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.honor_ecc_order", "rabbitmq_management.ssl_config.honor_ecc_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.reuse_sessions", "rabbitmq_management.ssl_config.reuse_sessions",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.secure_renegotiate", "rabbitmq_management.ssl_config.secure_renegotiate",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.client_renegotiation", "rabbitmq_management.ssl_config.client_renegotiation",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.depth", "rabbitmq_management.ssl_config.depth",
[{datatype, integer}, {validators, ["byte"]}]}.
{mapping, "management.ssl.versions.$version", "rabbitmq_management.ssl_config.versions",
[{datatype, atom}]}.
{translation, "rabbitmq_management.ssl_config.versions",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("management.ssl.versions", Conf),
[V || {_, V} <- Settings]
end}.
{mapping, "management.ssl.ciphers.$cipher", "rabbitmq_management.ssl_config.ciphers",
[{datatype, string}]}.
{translation, "rabbitmq_management.ssl_config.ciphers",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("management.ssl.ciphers", Conf),
lists:reverse([V || {_, V} <- Settings])
end}.
{mapping, "management.ssl.compress", "rabbitmq_management.ssl_config.cowboy_opts.compress",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.ssl.idle_timeout", "rabbitmq_management.ssl_config.cowboy_opts.idle_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.ssl.inactivity_timeout", "rabbitmq_management.ssl_config.cowboy_opts.inactivity_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.ssl.request_timeout", "rabbitmq_management.ssl_config.cowboy_opts.request_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.ssl.shutdown_timeout", "rabbitmq_management.ssl_config.cowboy_opts.shutdown_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.ssl.max_keepalive", "rabbitmq_management.ssl_config.cowboy_opts.max_keepalive",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
%% Legacy listener options ========================================================
%% Legacy (pre-3.7.9) TCP listener format.
%%
%% {listener, [{port, 12345},
%% {ip, "127.0.0.1"},
%% {ssl, true},
%% {ssl_opts, [{cacertfile, "/path/to/cacert.pem"},
%% {certfile, "/path/to/cert.pem"},
%% {keyfile, "/path/to/key.pem"}]}]},
{mapping, "management.listener.port", "rabbitmq_management.listener.port",
[{datatype, integer}]}.
{mapping, "management.listener.ip", "rabbitmq_management.listener.ip",
[{datatype, string},
{validators, ["is_ip"]}]}.
{mapping, "management.listener.ssl", "rabbitmq_management.listener.ssl",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.server.compress", "rabbitmq_management.listener.cowboy_opts.compress",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.server.idle_timeout", "rabbitmq_management.listener.cowboy_opts.idle_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.listener.server.inactivity_timeout", "rabbitmq_management.listener.cowboy_opts.inactivity_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.listener.server.request_timeout", "rabbitmq_management.listener.cowboy_opts.request_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.listener.server.shutdown_timeout", "rabbitmq_management.listener.cowboy_opts.shutdown_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "management.listener.server.max_keepalive", "rabbitmq_management.listener.cowboy_opts.max_keepalive",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
%% Legacy HTTPS listener options ========================================================
{mapping, "management.listener.ssl_opts", "rabbitmq_management.listener.ssl_opts", [
{datatype, {enum, [none]}}
]}.
{translation, "rabbitmq_management.listener.ssl_opts",
fun(Conf) ->
case cuttlefish:conf_get("management.listener.ssl_opts", Conf, undefined) of
none -> [];
_ -> cuttlefish:invalid("Invalid management.listener.ssl_opts")
end
end}.
{mapping, "management.listener.ssl_opts.verify", "rabbitmq_management.listener.ssl_opts.verify", [
{datatype, {enum, [verify_peer, verify_none]}}]}.
{mapping, "management.listener.ssl_opts.fail_if_no_peer_cert", "rabbitmq_management.listener.ssl_opts.fail_if_no_peer_cert", [
{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.cacertfile", "rabbitmq_management.listener.ssl_opts.cacertfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.listener.ssl_opts.certfile", "rabbitmq_management.listener.ssl_opts.certfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.listener.ssl_opts.cacerts.$name", "rabbitmq_management.listener.ssl_opts.cacerts",
[{datatype, string}]}.
{translation, "rabbitmq_management.listener.ssl_opts.cacerts",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("management.listener.ssl_opts.cacerts", Conf),
[ list_to_binary(V) || {_, V} <- Settings ]
end}.
{mapping, "management.listener.ssl_opts.honor_cipher_order", "rabbitmq_management.listener.ssl_opts.honor_cipher_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.honor_ecc_order", "rabbitmq_management.listener.ssl_opts.honor_ecc_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.reuse_sessions", "rabbitmq_management.listener.ssl_opts.reuse_sessions",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.secure_renegotiate", "rabbitmq_management.listener.ssl_opts.secure_renegotiate",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.client_renegotiation", "rabbitmq_management.listener.ssl_opts.client_renegotiation",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.versions.$version", "rabbitmq_management.listener.ssl_opts.versions",
[{datatype, atom}]}.
{translation, "rabbitmq_management.listener.ssl_opts.versions",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("management.listener.ssl_opts.versions", Conf),
[ V || {_, V} <- Settings ]
end}.
{mapping, "management.listener.ssl_opts.cert", "rabbitmq_management.listener.ssl_opts.cert",
[{datatype, string}]}.
{translation, "rabbitmq_management.listener.ssl_opts.cert",
fun(Conf) ->
list_to_binary(cuttlefish:conf_get("management.listener.ssl_opts.cert", Conf))
end}.
{mapping, "management.listener.ssl_opts.crl_check", "rabbitmq_management.listener.ssl_opts.crl_check",
[{datatype, [{enum, [true, false, peer, best_effort]}]}]}.
{mapping, "management.listener.ssl_opts.depth", "rabbitmq_management.listener.ssl_opts.depth",
[{datatype, integer}, {validators, ["byte"]}]}.
{mapping, "management.listener.ssl_opts.dh", "rabbitmq_management.listener.ssl_opts.dh",
[{datatype, string}]}.
{translation, "rabbitmq_management.listener.ssl_opts.dh",
fun(Conf) ->
list_to_binary(cuttlefish:conf_get("management.listener.ssl_opts.dh", Conf))
end}.
{mapping, "management.listener.ssl_opts.dhfile", "rabbitmq_management.listener.ssl_opts.dhfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.listener.ssl_opts.key.RSAPrivateKey", "rabbitmq_management.listener.ssl_opts.key",
[{datatype, string}]}.
{mapping, "management.listener.ssl_opts.key.DSAPrivateKey", "rabbitmq_management.listener.ssl_opts.key",
[{datatype, string}]}.
{mapping, "management.listener.ssl_opts.key.PrivateKeyInfo", "rabbitmq_management.listener.ssl_opts.key",
[{datatype, string}]}.
{translation, "rabbitmq_management.listener.ssl_opts.key",
fun(Conf) ->
case cuttlefish_variable:filter_by_prefix("management.listener.ssl_opts.key", Conf) of
[{[_,_,Key], Val}|_] -> {list_to_atom(Key), list_to_binary(Val)};
_ -> undefined
end
end}.
{mapping, "management.listener.ssl_opts.keyfile", "rabbitmq_management.listener.ssl_opts.keyfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "management.listener.ssl_opts.log_alert", "rabbitmq_management.listener.ssl_opts.log_alert",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.listener.ssl_opts.password", "rabbitmq_management.listener.ssl_opts.password",
[{datatype, string}]}.
{mapping, "management.listener.ssl_opts.psk_identity", "rabbitmq_management.listener.ssl_opts.psk_identity",
[{datatype, string}]}.
%% A custom path prefix for all HTTP request handlers.
%%
%% {path_prefix, "/a/prefix"},
{mapping, "management.path_prefix", "rabbitmq_management.path_prefix",
[{datatype, string}]}.
%% Login session timeout in minutes
{mapping, "management.login_session_timeout", "rabbitmq_management.login_session_timeout", [
{datatype, integer}, {validators, ["non_negative_integer"]}
]}.
%% CORS
{mapping, "management.cors.allow_origins", "rabbitmq_management.cors_allow_origins", [
{datatype, {enum, [none]}}
]}.
{mapping, "management.cors.allow_origins.$name", "rabbitmq_management.cors_allow_origins", [
{datatype, string}
]}.
{translation, "rabbitmq_management.cors_allow_origins",
fun(Conf) ->
case cuttlefish:conf_get("management.cors.allow_origins", Conf, undefined) of
none -> [];
_ ->
Settings = cuttlefish_variable:filter_by_prefix("management.cors.allow_origins", Conf),
[V || {_, V} <- Settings]
end
end}.
{mapping, "management.cors.max_age", "rabbitmq_management.cors_max_age", [
{datatype, integer}, {validators, ["non_negative_integer"]}
]}.
{translation, "rabbitmq_management.cors_max_age",
fun(Conf) ->
case cuttlefish:conf_get("management.cors.max_age", Conf, undefined) of
undefined -> cuttlefish:unset();
Value -> Value
end
end}.
%% CSP (https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
{mapping, "management.csp.policy", "rabbitmq_management.content_security_policy", [
{datatype, string}
]}.
{translation, "rabbitmq_management.content_security_policy",
fun(Conf) ->
case cuttlefish:conf_get("management.csp.policy", Conf, undefined) of
undefined -> cuttlefish:unset();
Value -> Value
end
end}.
%% HSTS (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
{mapping, "management.hsts.policy", "rabbitmq_management.strict_transport_security", [
{datatype, string}
]}.
{translation, "rabbitmq_management.strict_transport_security",
fun(Conf) ->
case cuttlefish:conf_get("management.hsts.policy", Conf, undefined) of
undefined -> cuttlefish:unset();
Value -> Value
end
end}.
%% OAuth 2/SSO access only
{mapping, "management.disable_basic_auth", "rabbitmq_management.disable_basic_auth",
[{datatype, {enum, [true, false]}}]}.
%% Management only
{mapping, "management.disable_stats", "rabbitmq_management.disable_management_stats", [
{datatype, {enum, [true, false]}}
]}.
{mapping, "management.enable_queue_totals", "rabbitmq_management.enable_queue_totals", [
{datatype, {enum, [true, false]}}]}.
%% ===========================================================================
%% Authorization
{mapping, "management.enable_uaa", "rabbitmq_management.enable_uaa",
[{datatype, {enum, [true, false]}}]}.
{mapping, "management.uaa_client_id", "rabbitmq_management.uaa_client_id",
[{datatype, string}]}.
{mapping, "management.uaa_location", "rabbitmq_management.uaa_location",
[{datatype, string}]}.
%% ===========================================================================
%% One of 'basic', 'detailed' or 'none'. See
%% https://www.rabbitmq.com/management.html#fine-stats for more details.
%% {rates_mode, basic},
{mapping, "management.rates_mode", "rabbitmq_management.rates_mode",
[{datatype, {enum, [basic, detailed, none]}}]}.
%% Configure how long aggregated data (such as message rates and queue
%% lengths) is retained. Please read the plugin's documentation in
%% https://www.rabbitmq.com/management.html#configuration for more
%% details.
%%
%% {sample_retention_policies,
%% [{global, [{60, 5}, {3600, 60}, {86400, 1200}]},
%% {basic, [{60, 5}, {3600, 60}]},
%% {detailed, [{10, 5}]}]}
% ]},
{mapping, "management.sample_retention_policies.$section.$interval",
"rabbitmq_management.sample_retention_policies",
[{datatype, integer}]}.
{translation, "rabbitmq_management.sample_retention_policies",
fun(Conf) ->
Global = cuttlefish_variable:filter_by_prefix("management.sample_retention_policies.global", Conf),
Basic = cuttlefish_variable:filter_by_prefix("management.sample_retention_policies.basic", Conf),
Detailed = cuttlefish_variable:filter_by_prefix("management.sample_retention_policies.detailed", Conf),
TranslateKey = fun("minute") -> 60;
("hour") -> 3600;
("day") -> 86400;
(Other) -> list_to_integer(Other)
end,
TranslatePolicy = fun(Section) ->
[ {TranslateKey(Key), Val} || {[_,_,_,Key], Val} <- Section ]
end,
[{global, TranslatePolicy(Global)},
{basic, TranslatePolicy(Basic)},
{detailed, TranslatePolicy(Detailed)}]
end}.
{validator, "is_dir", "is not directory",
fun(File) ->
ReadFile = file:list_dir(File),
element(1, ReadFile) == ok
end}.

View File

@ -0,0 +1,4 @@
%% Agent collectors won't start if metrics collection is disabled, only external stats are enabled.
%% Also the management application will refuse to start if metrics collection is disabled
{mapping, "management_agent.disable_metrics_collector", "rabbitmq_management_agent.disable_metrics_collector",
[{datatype, {enum, [true, false]}}]}.

View File

@ -0,0 +1,116 @@
%% ----------------------------------------------------------------------------
%% RabbitMQ Prometheus Plugin
%%
%% See https://rabbitmq.com/prometheus.html for details
%% ----------------------------------------------------------------------------
%% Endpoint path
{mapping, "prometheus.path", "rabbitmq_prometheus.path",
[{datatype, string}]}.
%% HTTP (TCP) listener options ========================================================
%% HTTP listener consistent with the management plugin, Web STOMP and Web MQTT.
%%
%% {tcp_config, [{port, 15692},
%% {ip, "127.0.0.1"}]}
{mapping, "prometheus.tcp.port", "rabbitmq_prometheus.tcp_config.port",
[{datatype, integer}]}.
{mapping, "prometheus.tcp.ip", "rabbitmq_prometheus.tcp_config.ip",
[{datatype, string},
{validators, ["is_ip"]}]}.
{mapping, "prometheus.tcp.compress", "rabbitmq_prometheus.tcp_config.cowboy_opts.compress",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.tcp.idle_timeout", "rabbitmq_prometheus.tcp_config.cowboy_opts.idle_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.tcp.inactivity_timeout", "rabbitmq_prometheus.tcp_config.cowboy_opts.inactivity_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.tcp.request_timeout", "rabbitmq_prometheus.tcp_config.cowboy_opts.request_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.tcp.shutdown_timeout", "rabbitmq_prometheus.tcp_config.cowboy_opts.shutdown_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.tcp.max_keepalive", "rabbitmq_prometheus.tcp_config.cowboy_opts.max_keepalive",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
%% HTTPS (TLS) listener options ========================================================
%% HTTPS listener consistent with the management plugin, Web STOMP and Web MQTT.
%%
%% {ssl_config, [{port, 15691},
%% {ip, "127.0.0.1"},
%% {cacertfile, "/path/to/cacert.pem"},
%% {certfile, "/path/to/cert.pem"},
%% {keyfile, "/path/to/key.pem"}]}
{mapping, "prometheus.ssl.port", "rabbitmq_prometheus.ssl_config.port",
[{datatype, integer}]}.
{mapping, "prometheus.ssl.backlog", "rabbitmq_prometheus.ssl_config.backlog",
[{datatype, integer}]}.
{mapping, "prometheus.ssl.ip", "rabbitmq_prometheus.ssl_config.ip",
[{datatype, string}, {validators, ["is_ip"]}]}.
{mapping, "prometheus.ssl.certfile", "rabbitmq_prometheus.ssl_config.certfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "prometheus.ssl.keyfile", "rabbitmq_prometheus.ssl_config.keyfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "prometheus.ssl.cacertfile", "rabbitmq_prometheus.ssl_config.cacertfile",
[{datatype, string}, {validators, ["file_accessible"]}]}.
{mapping, "prometheus.ssl.password", "rabbitmq_prometheus.ssl_config.password",
[{datatype, string}]}.
{mapping, "prometheus.ssl.verify", "rabbitmq_prometheus.ssl_config.verify", [
{datatype, {enum, [verify_peer, verify_none]}}]}.
{mapping, "prometheus.ssl.fail_if_no_peer_cert", "rabbitmq_prometheus.ssl_config.fail_if_no_peer_cert", [
{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.honor_cipher_order", "rabbitmq_prometheus.ssl_config.honor_cipher_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.honor_ecc_order", "rabbitmq_prometheus.ssl_config.honor_ecc_order",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.reuse_sessions", "rabbitmq_prometheus.ssl_config.reuse_sessions",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.secure_renegotiate", "rabbitmq_prometheus.ssl_config.secure_renegotiate",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.client_renegotiation", "rabbitmq_prometheus.ssl_config.client_renegotiation",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.depth", "rabbitmq_prometheus.ssl_config.depth",
[{datatype, integer}, {validators, ["byte"]}]}.
{mapping, "prometheus.ssl.versions.$version", "rabbitmq_prometheus.ssl_config.versions",
[{datatype, atom}]}.
{translation, "rabbitmq_prometheus.ssl_config.versions",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("prometheus.ssl.versions", Conf),
[V || {_, V} <- Settings]
end}.
{mapping, "prometheus.ssl.ciphers.$cipher", "rabbitmq_prometheus.ssl_config.ciphers",
[{datatype, string}]}.
{translation, "rabbitmq_prometheus.ssl_config.ciphers",
fun(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("prometheus.ssl.ciphers", Conf),
lists:reverse([V || {_, V} <- Settings])
end}.
{mapping, "prometheus.ssl.compress", "rabbitmq_prometheus.ssl_config.cowboy_opts.compress",
[{datatype, {enum, [true, false]}}]}.
{mapping, "prometheus.ssl.idle_timeout", "rabbitmq_prometheus.ssl_config.cowboy_opts.idle_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.ssl.inactivity_timeout", "rabbitmq_prometheus.ssl_config.cowboy_opts.inactivity_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.ssl.request_timeout", "rabbitmq_prometheus.ssl_config.cowboy_opts.request_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.ssl.shutdown_timeout", "rabbitmq_prometheus.ssl_config.cowboy_opts.shutdown_timeout",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.
{mapping, "prometheus.ssl.max_keepalive", "rabbitmq_prometheus.ssl_config.cowboy_opts.max_keepalive",
[{datatype, integer}, {validators, ["non_negative_integer"]}]}.

View File

@ -0,0 +1,174 @@
<h1>Traces: <b><%= node.name %></b></h1>
<p>
Node:
<select id="traces-node">
<% for (var i = 0; i < nodes.length; i++) { %>
<option name="#/traces/<%= fmt_string(nodes[i].name) %>"<% if (nodes[i].name == node.name) { %>selected="selected"<% } %>><%= nodes[i].name %></option>
<% } %>
</select>
</p>
<div class="section">
<h2>All traces</h2>
<div class="hider updatable">
<table class="two-col-layout">
<tr>
<td>
<h3>Currently running traces</h3>
<% if (traces.length > 0) { %>
<table class="list">
<thead>
<tr>
<% if (vhosts_interesting) { %>
<th>Virtual host</th>
<% } %>
<th>Name</th>
<th>Pattern</th>
<th>Format</th>
<th>Payload limit</th>
<th>Rate</th>
<th>Queued</th>
<th>Tracer connection username</th>
<th></th>
</tr>
</thead>
<tbody>
<%
for (var i = 0; i < traces.length; i++) {
var trace = traces[i];
%>
<tr<%= alt_rows(i)%>>
<% if (vhosts_interesting) { %>
<td><%= fmt_string(trace.vhost) %></td>
<% } %>
<td><%= fmt_string(trace.name) %></td>
<td><%= fmt_string(trace.pattern) %></td>
<td><%= fmt_string(trace.format) %></td>
<td class="c"><%= fmt_string(trace.max_payload_bytes, 'Unlimited') %></td>
<% if (trace.queue) { %>
<td class="r">
<%= fmt_detail_rate(trace.queue.message_stats, 'deliver_no_ack') %>
</td>
<td class="r">
<%= trace.queue.messages %>
<sub><%= link_trace_queue(trace) %></sub>
</td>
<% } else { %>
<td colspan="2">
<div class="status-red"><acronym title="The trace failed to start - check the server logs for details.">FAILED</acronym></div>
</td>
<% } %>
<td><%= fmt_string(trace.tracer_connection_username) %></td>
<td>
<form action="#/traces/node/<%= node.name %>" method="delete">
<input type="hidden" name="vhost" value="<%= fmt_string(trace.vhost) %>"/>
<input type="hidden" name="name" value="<%= fmt_string(trace.name) %>"/>
<input type="submit" value="Stop"/>
</form>
</td>
</tr>
<% } %>
</tbody>
</table>
<% } else { %>
<p>... no traces running ...</p>
<% } %>
</td>
<td>
<h3>Trace log files</h3>
<% if (files.length > 0) { %>
<table class="list">
<thead>
<tr>
<th>Name</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
<%
for (var i = 0; i < files.length; i++) {
var file = files[i];
%>
<tr<%= alt_rows(i)%>>
<td><%= link_trace(node.name, file.name) %></td>
<td class="r"><%= fmt_bytes(file.size) %></td>
<td>
<form action="#/trace-files/node/<%= node.name %>" method="delete" class="inline-form">
<input type="hidden" name="name" value="<%= fmt_string(file.name) %>"/>
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<% } %>
</tbody>
</table>
<% } else { %>
<p>... no files ...</p>
<% } %>
</td>
</tr>
</table>
</div>
</div>
<div class="section">
<h2>Add a new trace</h2>
<div class="hider">
<form action="#/traces/node/<%= node.name %>" method="put">
<table class="form">
<% if (vhosts_interesting) { %>
<tr>
<th><label>Virtual host:</label></th>
<td>
<select name="vhost">
<% for (var i = 0; i < vhosts.length; i++) { %>
<option value="<%= fmt_string(vhosts[i].name) %>"><%= fmt_string(vhosts[i].name) %></option>
<% } %>
</select>
</td>
</tr>
<% } else { %>
<tr><td><input type="hidden" name="vhost" value="<%= fmt_string(vhosts[0].name) %>"/></td></tr>
<% } %>
<tr>
<th><label>Name:</label></th>
<td><input type="text" name="name"/><span class="mand">*</span></td>
</tr>
<tr>
<th><label>Format:</label></th>
<td>
<select name="format">
<option value="text">Text</option>
<option value="json">JSON</option>
</select>
</td>
</tr>
<tr>
<th><label>Tracer connection username:</label></th>
<td><input type="text" name="tracer_connection_username"/></td>
<td><label>Tracer connection password:</label></td>
<td>
<div id="password-div">
<input type="password" name="tracer_connection_password"/>
</div>
</td>
</tr>
<tr>
<th><label>Max payload bytes: <span class="help" id="tracing-max-payload"></span></label></th>
<td>
<input type="text" name="max_payload_bytes" value=""/>
</td>
</tr>
<tr>
<th><label>Pattern:</label></th>
<td>
<input type="text" name="pattern" value="#"/>
<sub>Examples: #, publish.#, deliver.# #.amq.direct, #.myqueue</sub>
</td>
</tr>
</table>
<input type="submit" value="Add trace"/>
</form>
</div>
</div>