summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthias Radestock <matthias@lshift.net>2008-10-17 17:21:02 +0100
committerMatthias Radestock <matthias@lshift.net>2008-10-17 17:21:02 +0100
commitb2bd184f7dbb5d65158366e10fbbfbf4b90daf75 (patch)
tree3f88a9b12cd5d6e5a531da7ca27cdb7732fa841f
parent7279a32f7a905a94283834bd8df4c357e0e900b7 (diff)
parentc6bf18acc51cfa569d97de4913b55ae56dfc8a69 (diff)
downloadrabbitmq-server-bug18732.tar.gz
merge default into bug18732bug18732
-rw-r--r--.hgignore17
-rw-r--r--BUILD.in2
-rw-r--r--Makefile22
-rw-r--r--codegen.py34
-rw-r--r--docs/rabbitmq-multi.pod58
-rw-r--r--docs/rabbitmq-server.pod80
-rw-r--r--docs/rabbitmqctl.pod157
-rw-r--r--ebin/rabbit.app2
-rw-r--r--include/rabbit.hrl32
-rw-r--r--include/rabbit_framing_spec.hrl2
-rw-r--r--packaging/RPMS/Fedora/Makefile3
-rw-r--r--packaging/RPMS/Fedora/README.txt28
-rw-r--r--packaging/RPMS/Fedora/init.d129
-rw-r--r--packaging/RPMS/Fedora/rabbitmq-server.logrotate12
-rw-r--r--packaging/RPMS/Fedora/rabbitmq-server.spec129
-rw-r--r--packaging/debs/Debian/Makefile8
-rw-r--r--packaging/debs/Debian/debian/changelog6
-rw-r--r--packaging/debs/Debian/debian/control6
-rw-r--r--packaging/debs/Debian/debian/copyright6
-rw-r--r--packaging/debs/Debian/debian/dirs3
-rw-r--r--packaging/debs/Debian/debian/init.d119
-rw-r--r--packaging/debs/Debian/debian/rabbitmq-server.logrotate12
-rw-r--r--packaging/debs/Debian/debian/rules5
-rw-r--r--packaging/generic-unix/Makefile3
-rw-r--r--packaging/windows/Makefile1
-rwxr-xr-xscripts/rabbitmq-multi2
-rw-r--r--scripts/rabbitmq-multi.bat4
-rwxr-xr-xscripts/rabbitmq-server9
-rw-r--r--scripts/rabbitmq-server.bat7
-rwxr-xr-xscripts/rabbitmqctl2
-rw-r--r--scripts/rabbitmqctl.bat2
-rw-r--r--src/rabbit.erl167
-rw-r--r--src/rabbit_access_control.erl124
-rw-r--r--src/rabbit_amqqueue.erl97
-rw-r--r--src/rabbit_channel.erl178
-rw-r--r--src/rabbit_control.erl82
-rw-r--r--src/rabbit_error_logger.erl5
-rw-r--r--src/rabbit_error_logger_file_h.erl74
-rw-r--r--src/rabbit_exchange.erl38
-rw-r--r--src/rabbit_misc.erl100
-rw-r--r--src/rabbit_mnesia.erl19
-rw-r--r--src/rabbit_multi.erl66
-rw-r--r--src/rabbit_node_monitor.erl1
-rw-r--r--src/rabbit_reader.erl40
-rw-r--r--src/rabbit_realm.erl316
-rw-r--r--src/rabbit_router.erl8
-rw-r--r--src/rabbit_sasl_report_file_h.erl86
-rw-r--r--src/rabbit_tests.erl235
-rw-r--r--src/rabbit_ticket.erl131
-rw-r--r--src/rabbit_writer.erl11
50 files changed, 1376 insertions, 1304 deletions
diff --git a/.hgignore b/.hgignore
new file mode 100644
index 00000000..0781e32f
--- /dev/null
+++ b/.hgignore
@@ -0,0 +1,17 @@
+syntax: glob
+*.beam
+*~
+erl_crash.dump
+
+syntax: regexp
+^cover/
+^dist/
+^include/rabbit_framing.hrl$
+^src/rabbit_framing.erl$
+^rabbit.plt$
+
+^packaging/RPMS/Fedora/(BUILD|RPMS|SOURCES|SPECS|SRPMS)$
+^packaging/debs/Debian/rabbitmq-server_.*\.(dsc|tar\.gz|deb|changes)$
+^packaging/debs/apt-repository/debian$
+^packaging/generic-unix/rabbitmq-server-generic-unix-.*\.tar\.gz$
+^packaging/windows/rabbitmq-server-windows-.*\.zip$
diff --git a/BUILD.in b/BUILD.in
index b013bc3c..0e70d0e7 100644
--- a/BUILD.in
+++ b/BUILD.in
@@ -1,4 +1,4 @@
-Please see http://www.rabbitmq.com/build.html for build
+Please see http://www.rabbitmq.com/build-server.html for build
instructions.
For your convenience, a text copy of these instructions is available
diff --git a/Makefile b/Makefile
index 680003cf..ee7bb30d 100644
--- a/Makefile
+++ b/Makefile
@@ -5,7 +5,6 @@ EBIN_DIR=ebin
INCLUDE_DIR=include
SOURCES=$(wildcard $(SOURCE_DIR)/*.erl)
TARGETS=$(EBIN_DIR)/rabbit_framing.beam $(patsubst $(SOURCE_DIR)/%.erl, $(EBIN_DIR)/%.beam,$(SOURCES))
-PLT=rabbit.plt
WEB_URL=http://stage.rabbitmq.com/
ifndef USE_SPECS
@@ -47,16 +46,13 @@ $(INCLUDE_DIR)/rabbit_framing.hrl $(SOURCE_DIR)/rabbit_framing.erl: codegen.py $
$(EBIN_DIR)/rabbit.boot $(EBIN_DIR)/rabbit.script: $(EBIN_DIR)/rabbit.app $(EBIN_DIR)/rabbit.rel $(TARGETS)
erl -noshell -eval 'systools:make_script("ebin/rabbit", [{path, ["ebin"]}]), halt().'
-$(PLT): $(TARGETS)
- dialyzer -c $? --output_plt $@ $(shell if [ -f $@ ] ; then echo "--plt $@"; fi)
-
-dialyze: $(PLT)
+dialyze: $(TARGETS)
+ dialyzer -c $?
clean: cleandb
rm -f $(EBIN_DIR)/*.beam
rm -f $(EBIN_DIR)/rabbit.boot $(EBIN_DIR)/rabbit.script
rm -f $(INCLUDE_DIR)/rabbit_framing.hrl $(SOURCE_DIR)/rabbit_framing.erl codegen.pyc
- rm -f $(PLT)
cleandb: stop-node
erl -mnesia dir '"$(MNESIA_DIR)"' -noshell -eval 'lists:foreach(fun file:delete/1, filelib:wildcard(mnesia:system_info(directory) ++ "/*")), halt().'
@@ -106,7 +102,7 @@ generic_stage:
elinks -dump -no-references -no-numbering $(WEB_URL)install.html \
>> $(GENERIC_STAGE_DIR)/INSTALL; \
cp BUILD.in $(GENERIC_STAGE_DIR)/BUILD; \
- elinks -dump -no-references -no-numbering $(WEB_URL)build.html \
+ elinks -dump -no-references -no-numbering $(WEB_URL)build-server.html \
>> $(GENERIC_STAGE_DIR)/BUILD; \
else \
cp INSTALL $(GENERIC_STAGE_DIR); \
@@ -118,10 +114,12 @@ generic_stage:
srcdist: distclean
$(MAKE) VERSION=$(VERSION) GENERIC_STAGE_DIR=dist/$(TARBALL_NAME) generic_stage
- cp -r $(AMQP_CODEGEN_DIR) dist/$(TARBALL_NAME)/codegen
+ mkdir -p dist/$(TARBALL_NAME)/codegen
+ cp -r $(AMQP_CODEGEN_DIR)/* dist/$(TARBALL_NAME)/codegen/
cp codegen.py Makefile dist/$(TARBALL_NAME)
cp -r scripts dist/$(TARBALL_NAME)
+ cp -r docs dist/$(TARBALL_NAME)
chmod 0755 dist/$(TARBALL_NAME)/scripts/*
(cd dist; tar -zcf $(TARBALL_NAME).tar.gz $(TARBALL_NAME))
@@ -136,12 +134,20 @@ distclean: clean
install: all
@[ -n "$(TARGET_DIR)" ] || (echo "Please set TARGET_DIR."; false)
@[ -n "$(SBIN_DIR)" ] || (echo "Please set SBIN_DIR."; false)
+ @[ -n "$(MAN_DIR)" ] || (echo "Please set MAN_DIR."; false)
$(MAKE) VERSION=$(VERSION) GENERIC_STAGE_DIR=$(TARGET_DIR) generic_stage
chmod 0755 scripts/*
mkdir -p $(SBIN_DIR)
+ mkdir -p $(MAN_DIR)/man1
cp scripts/rabbitmq-server $(SBIN_DIR)
cp scripts/rabbitmqctl $(SBIN_DIR)
cp scripts/rabbitmq-multi $(SBIN_DIR)
+ for manpage in docs/*.pod ; do \
+ pod2man -c "RabbitMQ AMQP Server" -d "" -r "" \
+ $$manpage | gzip --best > \
+ $(MAN_DIR)/man1/`echo $$manpage | sed -e 's:docs/\(.*\)\.pod:\1\.1\.gz:g'`; \
+ done
+
rm -f $(TARGET_DIR)/BUILD
diff --git a/codegen.py b/codegen.py
index 242c2418..5dbc57c7 100644
--- a/codegen.py
+++ b/codegen.py
@@ -45,6 +45,22 @@ erlangTypeMap = {
'timestamp': 'timestamp',
}
+# Coming up with a proper encoding of AMQP tables in JSON is too much
+# hassle at this stage. Given that the only default value we are
+# interested in is for the empty table, we only support that.
+def convertTable(d):
+ if len(d) == 0:
+ return "[]"
+ else: raise 'Non-empty table defaults not supported', d
+
+erlangDefaultValueTypeConvMap = {
+ bool : lambda x: str(x).lower(),
+ str : lambda x: "<<\"" + x + "\">>",
+ int : lambda x: str(x),
+ float : lambda x: str(x),
+ dict: convertTable
+}
+
def erlangize(s):
s = s.replace('-', '_')
s = s.replace(' ', '_')
@@ -271,6 +287,15 @@ def genHrl(spec):
def fieldNameList(fields):
return ', '.join([erlangize(f.name) for f in fields])
+
+ def fieldNameListDefaults(fields):
+ def fillField(field):
+ result = erlangize(f.name)
+ if field.defaultvalue != None:
+ conv_fn = erlangDefaultValueTypeConvMap[type(field.defaultvalue)]
+ result += ' = ' + conv_fn(field.defaultvalue)
+ return result
+ return ', '.join([fillField(f) for f in fields])
methods = spec.allMethods()
@@ -283,23 +308,18 @@ def genHrl(spec):
print "%% Method field records."
for m in methods:
- print "-record(%s, {%s})." % (m.erlangName(), fieldNameList(m.arguments))
+ print "-record(%s, {%s})." % (m.erlangName(), fieldNameListDefaults(m.arguments))
print "%% Class property records."
for c in spec.allClasses():
print "-record('P_%s', {%s})." % (erlangize(c.name), fieldNameList(c.fields))
-#---------------------------------------------------------------------------
-
def generateErl(specPath):
genErl(AmqpSpec(specPath))
def generateHrl(specPath):
genHrl(AmqpSpec(specPath))
-
+
if __name__ == "__main__":
do_main(generateHrl, generateErl)
-
-
-
diff --git a/docs/rabbitmq-multi.pod b/docs/rabbitmq-multi.pod
new file mode 100644
index 00000000..65d05833
--- /dev/null
+++ b/docs/rabbitmq-multi.pod
@@ -0,0 +1,58 @@
+=head1 NAME
+
+rabbitmq-multi - start/stop local cluster RabbitMQ nodes
+
+=head1 SYNOPSIS
+
+rabbitmq-multi I<command> [command option]
+
+=head1 DESCRIPTION
+
+RabbitMQ is an implementation of AMQP, the emerging standard for high
+performance enterprise messaging. The RabbitMQ server is a robust and
+scalable implementation of an AMQP broker.
+
+rabbitmq-multi scripts allows for easy set-up of a cluster on a single
+machine.
+
+See also rabbitmq-server(1) for configuration information.
+
+=head1 COMMANDS
+
+start_all I<count>
+ start count nodes with unique names, listening on all IP addresses
+ and on sequential ports starting from 5672.
+
+status
+ print the status of all running RabbitMQ nodes
+
+stop_all
+ stop all local RabbitMQ nodes
+
+rotate_logs
+ rotate log files for all local and running RabbitMQ nodes
+
+=head1 EXAMPLES
+
+Start 3 local RabbitMQ nodes with unique, sequential port numbers:
+
+ rabbitmq-multi start_all 3
+
+=head1 SEE ALSO
+
+rabbitmq-server(1), rabbitmqctl(1)
+
+=head1 AUTHOR
+
+Originally written by The RabbitMQ Team <info@lshift.net>
+
+=head1 COPYRIGHT
+
+This package, the RabbitMQ server is licensed under the MPL.
+
+If you have any questions regarding licensing, please contact us at
+info@rabbitmq.com.
+
+=head1 REFERENCES
+
+RabbitMQ Web Site: http://www.rabbitmq.com
diff --git a/docs/rabbitmq-server.pod b/docs/rabbitmq-server.pod
new file mode 100644
index 00000000..1eaf2dfd
--- /dev/null
+++ b/docs/rabbitmq-server.pod
@@ -0,0 +1,80 @@
+=head1 NAME
+
+rabbitmq-server - start RabbitMQ AMQP server
+
+=head1 SYNOPSIS
+
+rabbitmq-server [-detached]
+
+=head1 DESCRIPTION
+
+RabbitMQ is an implementation of AMQP, the emerging standard for high
+performance enterprise messaging. The RabbitMQ server is a robust and
+scalable implementation of an AMQP broker.
+
+Running rabbitmq-server in the foreground displays a banner message,
+and reports on progress in the startup sequence, concluding with the
+message "broker running", indicating that the RabbitMQ broker has been
+started successfully. To shut down the server, just terminate the
+process or use rabbitmqctl(1).
+
+=head1 ENVIRONMENT
+
+B<MNESIA_BASE>
+ Defaults to /var/lib/rabbitmq/mnesia. Set this to the directory
+ where Mnesia database files should be placed.
+
+B<LOG_BASE>
+ Defaults to /var/log/rabbitmq. Log files generated by the server
+ will be placed in this directory.
+
+B<NODENAME>
+ Defaults to rabbit. This can be useful if you want to run more
+ than one node per machine - B<NODENAME> should be unique per
+ erlang-node-and-machine combination. See clustering on a single
+ machine guide
+ at http://www.rabbitmq.com/clustering.html#single-machine for
+ details.
+
+B<NODE_IP_ADDRESS>
+ Defaults to 0.0.0.0. This can be changed if you only want to bind
+ to one network interface.
+
+B<NODE_PORT>
+ Defaults to 5672.
+
+B<CLUSTER_CONFIG_FILE>
+ Defaults to /etc/default/rabbitmq_cluster.config. If this file is
+ present it is used by the server to auto-configure a RabbitMQ
+ cluster.
+ See the clustering guide at http://www.rabbitmq.com/clustering.html
+ for details.
+
+=head1 OPTIONS
+
+B<-detached> start the server process in the background
+
+=head1 EXAMPLES
+
+Run RabbitMQ AMQP server in the background:
+
+ rabbitmq-server -detached
+
+=head1 SEE ALSO
+
+rabbitmq-multi(1), rabbitmqctl(1)
+
+=head1 AUTHOR
+
+Originally written by The RabbitMQ Team <info@lshift.net>
+
+=head1 COPYRIGHT
+
+This package, the RabbitMQ server is licensed under the MPL.
+
+If you have any questions regarding licensing, please contact us at
+info@rabbitmq.com.
+
+=head1 REFERENCES
+
+RabbitMQ Web Site: http://www.rabbitmq.com
diff --git a/docs/rabbitmqctl.pod b/docs/rabbitmqctl.pod
new file mode 100644
index 00000000..b34cbca7
--- /dev/null
+++ b/docs/rabbitmqctl.pod
@@ -0,0 +1,157 @@
+=head1 NAME
+
+rabbitmqctl - command line tool for managing a RabbitMQ broker
+
+=head1 SYNOPSIS
+
+rabbitmqctl [-n I<node>] I<<command>> [command options]
+
+=head1 DESCRIPTION
+
+RabbitMQ is an implementation of AMQP, the emerging standard for high
+performance enterprise messaging. The RabbitMQ server is a robust and
+scalable implementation of an AMQP broker.
+
+rabbitmqctl is a command line tool for managing a RabbitMQ broker.
+It performs all actions by connecting to one of the broker's nodes.
+
+
+=head1 OPTIONS
+
+B<-n> I<node>
+ default node is C<rabbit@server>, where server is the local host.
+ On a host named C<server.example.com>, the node name of the RabbitMQ
+ Erlang node will usually be rabbit@server (unless NODENAME has been
+ set to some non-default value at broker startup time).
+ The output of hostname -s is usually the correct suffix to use
+ after the "@" sign. See rabbitmq-server(1) for details of configur-
+ ing the RabbitMQ broker.
+
+
+=head1 COMMANDS
+
+=head2 APPLICATION AND CLUSTER MANAGEMENT
+
+stop
+ stop the Erlang node on which RabbitMQ broker is running.
+
+stop_app
+ stop the RabbitMQ application, leaving the Erlang node running.
+ This command is typically run prior to performing other management
+ actions that require the RabbitMQ application to be stopped,
+ e.g. I<reset>.
+
+start_app
+ start the RabbitMQ application.
+ This command is typically run prior to performing other management
+ actions that require the RabbitMQ application to be stopped,
+ e.g. I<reset>.
+
+status
+ display various information about the RabbitMQ broker, such as
+ whether the RabbitMQ application on the current node, its version
+ number, what nodes are part of the broker, which of these are
+ running.
+
+force
+ return a RabbitMQ node to its virgin state.
+ Removes the node from any cluster it belongs to, removes all data
+ from the management database, such as configured users, vhosts and
+ deletes all persistent messages.
+
+force_reset
+ the same as I<force> command, but resets the node unconditionally,
+ regardless of the current management database state and cluster
+ configuration.
+ It should only be used as a last resort if the database or cluster
+ configuration has been corrupted.
+
+rotate_logs [suffix]
+ instruct the RabbitMQ node to rotate the log files. The RabbitMQ
+ broker will attempt to append the current contents of the log file
+ to the file with the name composed of the original name and the
+ suffix. It will create a new file if such a file does not already
+ exist. When no I<suffix> is specified, the empty log file is
+ simply created at the original location; no rotation takes place.
+ When an error occurs while appending the contents of the old log
+ file, the operation behaves in the same way as if no I<suffix> was
+ specified.
+ This command might be helpful when you are e.g. writing your own
+ logrotate script and you do not want to restart the RabbitMQ node.
+
+cluster I<clusternode> ...
+ instruct the node to become member of a cluster with the specified
+ nodes determined by I<clusternode> option(s).
+ See http://www.rabbitmq.com/clustering.html for more information
+ about clustering.
+
+=head2 USER MANAGEMENT
+
+add_user I<username> I<password>
+ create a user named I<username> with (initial) password I<password>.
+
+change_password I<username> I<newpassword>
+ change the password for the user named I<username> to I<newpassword>.
+
+list_users
+ list all users.
+
+=head2 ACCESS CONTROL
+
+add_vhost I<vhostpath>
+ create a new virtual host called I<vhostpath>.
+
+delete_vhost I<vhostpath>
+ delete a virtual host I<vhostpath>.
+ That command deletes also all its exchanges, queues and user mappings.
+
+list_vhosts
+ list all virtual hosts.
+
+map_user_vhost I<username> I<vhostpath>
+ grant the user named I<username> access to the virtual host called
+ I<vhostpath>.
+
+unmap_user_vhost I<username> I<vhostpath>
+ deny the user named I<username> access to the virtual host called
+ I<vhostpath>.
+
+list_user_vhost I<username>
+ list all the virtual hosts to which the user named I<username> has
+ been granted access.
+
+=head1 EXAMPLES
+
+Create a user named foo with (initial) password bar at the Erlang node
+rabbit@test:
+
+ rabbitmqctl -n rabbit@test add_user foo bar
+
+Grant user named foo access to the virtual host called test at the
+default Erlang node:
+
+ rabbitmqctl map_user_vhost foo test
+
+Append the current logs' content to the files with ".1" suffix and reopen
+them:
+
+ rabbitmqctl rotate_logs .1
+
+=head1 SEE ALSO
+
+rabbitmq-multi(1), rabbitmq-server(1)
+
+=head1 AUTHOR
+
+Originally written by The RabbitMQ Team <info@lshift.net>
+
+=head1 COPYRIGHT
+
+This package, the RabbitMQ server is licensed under the MPL.
+
+If you have any questions regarding licensing, please contact us at
+info@rabbitmq.com.
+
+=head1 REFERENCES
+
+RabbitMQ Web Site: http://www.rabbitmq.com
diff --git a/ebin/rabbit.app b/ebin/rabbit.app
index 20d5afcf..0326f461 100644
--- a/ebin/rabbit.app
+++ b/ebin/rabbit.app
@@ -25,11 +25,9 @@
rabbit_node_monitor,
rabbit_persister,
rabbit_reader,
- rabbit_realm,
rabbit_router,
rabbit_sup,
rabbit_tests,
- rabbit_ticket,
rabbit_tracer,
rabbit_writer,
tcp_acceptor,
diff --git a/include/rabbit.hrl b/include/rabbit.hrl
index d8af670a..180a0dc3 100644
--- a/include/rabbit.hrl
+++ b/include/rabbit.hrl
@@ -27,26 +27,20 @@
-record(user_vhost, {username, virtual_host}).
-record(vhost, {virtual_host, dummy}).
--record(vhost_realm, {virtual_host, realm}).
-
--record(realm, {name, exchanges, queues}).
--record(user_realm, {username, realm, ticket_pattern}).
-
--record(realm_visitor, {realm, pid}).
-record(connection, {user, timeout_sec, frame_max, vhost}).
--record(content, {class_id,
- properties, %% either 'none', or a decoded record/tuple
- properties_bin, %% either 'none', or an encoded properties binary
- %% Note: at most one of properties and properties_bin can be 'none' at once.
- payload_fragments_rev %% list of binaries, in reverse order (!)
- }).
+-record(content,
+ {class_id,
+ properties, %% either 'none', or a decoded record/tuple
+ properties_bin, %% either 'none', or an encoded properties binary
+ %% Note: at most one of properties and properties_bin can be
+ %% 'none' at once.
+ payload_fragments_rev %% list of binaries, in reverse order (!)
+ }).
-record(resource, {virtual_host, kind, name}).
--record(ticket, {realm_name, passive_flag, active_flag, write_flag, read_flag}).
-
-record(exchange, {name, type, durable, auto_delete, arguments}).
-record(amqqueue, {name, durable, auto_delete, arguments, binding_specs, pid}).
@@ -77,20 +71,12 @@
-type(r(Kind) ::
#resource{virtual_host :: vhost(),
kind :: Kind,
- name :: name()}).
--type(realm_name() :: r('realm')).
+ name :: resource_name()}).
-type(queue_name() :: r('queue')).
-type(exchange_name() :: r('exchange')).
-type(user() ::
#user{username :: username(),
password :: password()}).
--type(ticket() ::
- #ticket{realm_name :: realm_name(),
- passive_flag :: bool(),
- active_flag :: bool(),
- write_flag :: bool(),
- read_flag :: bool()}).
--type(permission() :: 'passive' | 'active' | 'write' | 'read').
-type(binding_spec() ::
#binding_spec{exchange_name :: exchange_name(),
routing_key :: routing_key(),
diff --git a/include/rabbit_framing_spec.hrl b/include/rabbit_framing_spec.hrl
index ef9ab584..e9e65092 100644
--- a/include/rabbit_framing_spec.hrl
+++ b/include/rabbit_framing_spec.hrl
@@ -46,7 +46,7 @@
-type(channel_number() :: non_neg_integer()).
%% TODO: make this more precise
-type(amqp_error() :: {bool(), non_neg_integer(), binary()}).
--type(name() :: binary()).
+-type(resource_name() :: binary()).
-type(routing_key() :: binary()).
-type(username() :: binary()).
-type(password() :: binary()).
diff --git a/packaging/RPMS/Fedora/Makefile b/packaging/RPMS/Fedora/Makefile
index c8e979a7..814c79f0 100644
--- a/packaging/RPMS/Fedora/Makefile
+++ b/packaging/RPMS/Fedora/Makefile
@@ -5,7 +5,7 @@ SOURCE_TARBALL_DIR=../../../dist
TARBALL=$(SOURCE_TARBALL_DIR)/rabbitmq-server-$(VERSION).tar.gz
TOP_DIR=$(shell pwd)
RPM_VERSION=$(shell echo $(VERSION) | tr - _)
-DEFINES=--define '_topdir $(TOP_DIR)' --define '_tmppath $(TOP_DIR)/tmp' --define 'main_version $(VERSION)' --define 'rpm_version $(RPM_VERSION)'
+DEFINES=--define '_topdir $(TOP_DIR)' --define '_tmppath $(TOP_DIR)/tmp' --define 'main_version $(VERSION)' --define 'rpm_version $(RPM_VERSION)' --define 'debian 1'
rpms: clean server
@@ -21,6 +21,7 @@ prepare:
cp $(TOP_DIR)/rabbitmq-server.spec $(TOP_DIR)/SPECS
cp $(TOP_DIR)/init.d $(TOP_DIR)/BUILD
cp $(TOP_DIR)/rabbitmqctl_wrapper $(TOP_DIR)/BUILD
+ cp $(TOP_DIR)/rabbitmq-server.logrotate $(TOP_DIR)/BUILD
server: prepare
rpmbuild -ba $(TOP_DIR)/SPECS/rabbitmq-server.spec $(DEFINES) --target noarch
diff --git a/packaging/RPMS/Fedora/README.txt b/packaging/RPMS/Fedora/README.txt
index a7db530b..6f313259 100644
--- a/packaging/RPMS/Fedora/README.txt
+++ b/packaging/RPMS/Fedora/README.txt
@@ -1,8 +1,7 @@
Notes on creating rpms for rabbitmq
-Assuming that rpm will be built under $TOP_DIR/rpm
-directory the rpm macros configuration file
-would look like:
+Assuming that rpm will be built under $TOP_DIR/rpm,
+the main configuration variables would look like:
%_topdir $TOP_DIR/rpm
%_tmppath $TOP_DIR/rpm/tmp
@@ -11,11 +10,7 @@ would look like:
%_includedir /usr/include
%_mandir /usr/share/man
-Where $TOP_DIR can be any directory (usually $HOME)
-However this configuration has to be under the following
-path:
-$HOME/.rpmmacros
-since this is a fixed place where rpmbuild looks for macros.
+Where $TOP_DIR can be any directory (default is $HOME).
The $TOP_DIR/rpm directory has following structure:
@@ -24,14 +19,14 @@ rpm
+---- SOURCES // where source tarballs are put
+---- SPECS // directory containing specs
+---- SRPMS // rpmbuild puts here srpms
- +---- RPMS // rpmbuils puts here rpms
- +---- tmp // where rpm packages are built
+ +---- RPMS // rpmbuils puts here rpms
+ +---- tmp // where rpm packages are built
Makefile will copy the source tarball from fixed directory
specified by $TARBALL_DIR to SOURCES directory and
similarly specs from $SPEC_DIR to SPECS directory.
-'make rpms' should create both client and server rabbitmq.
+'make rpms' should create rabbitmq-server package.
If there are any errors reported by rpmbuild this is
possibly due to incorrect name of the packages
(if all dependencies are satisifed) - different distros
@@ -39,15 +34,16 @@ can have slightly different names.
rpms and srpms are placed in their respective directories.
-'make prepare' will create the necessary structure and
-create the rpmmacros file. Change top variables to adjust
-it to your system. Note that it will *overwrite* any current
-rpmmacros configuration file.
+'make prepare' will create the necessary structure.
+Change main configuration variables specified in the 'DEFINES'
+variable in the Makefile to adjust it to your system.
+Note that it will *overwrite* any current rpmmacros
+configurations.
The first thing to do for building rpms is to create you own
source tarball of AMQ. In the spec files two top variables
determine the name of the tarball. Adjust it to you needs.
-The final name has to match the *Source* tag in specs' headers.
+The final name has to match the *Source* tag in spec's headers.
For information on how to sign the package see:
http://fedoranews.org/tchung/gpg/
diff --git a/packaging/RPMS/Fedora/init.d b/packaging/RPMS/Fedora/init.d
index 09ca02c9..397beeaa 100644
--- a/packaging/RPMS/Fedora/init.d
+++ b/packaging/RPMS/Fedora/init.d
@@ -1,79 +1,140 @@
#!/bin/sh
+#
+# rabbitmq-server RabbitMQ broker
+#
+#chkconfig: 2345 80 05
+#description: Enable AMQP service provided by RabbitMQ
+#
+
### BEGIN INIT INFO
# Provides: rabbitmq
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
+# Description: RabbitMQ broker
+# Short-Description: Enable AMQP service provided by RabbitMQ broker
### END INIT INFO
-#chkconfig: 2345 80 05
-#description: RabbitMQ Server
-
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/rabbitmq-multi
+DAEMON_NAME=rabbitmq-multi
+DAEMON=/usr/sbin/$DAEMON_NAME
NAME=rabbitmq-server
DESC=rabbitmq-server
USER=rabbitmq
NODE_COUNT=1
+ROTATE_SUFFIX=
+
+LOCK_FILE=/var/lock/subsys/$NAME
test -x $DAEMON || exit 0
+# source function library
+. /etc/rc.d/init.d/functions
+
# Include rabbitmq defaults if available
if [ -f /etc/default/rabbitmq ] ; then
. /etc/default/rabbitmq
fi
+RETVAL=0
set -e
cd /
start_rabbitmq () {
set +e
- su rabbitmq -s /bin/sh -c "$DAEMON start_all ${NODE_COUNT}" > /var/log/rabbitmq/startup.log 2> /var/log/rabbitmq/startup.err
+ su $USER -s /bin/sh -c "$DAEMON start_all ${NODE_COUNT}" > /var/log/rabbitmq/startup_log 2> /var/log/rabbitmq/startup_err
case "$?" in
0)
- echo SUCCESS;;
+ echo SUCCESS && touch $LOCK_FILE
+ RETVAL=0
+ ;;
1)
- echo TIMEOUT - check /var/log/rabbitmq/startup.\{log,err\};;
+ echo TIMEOUT - check /var/log/rabbitmq/startup_\{log,err\}
+ RETVAL=1
+ ;;
*)
- echo FAILED - check /var/log/rabbitmq/startup.log, .err
- exit 1;;
+ echo FAILED - check /var/log/rabbitmq/startup_log, _err
+ RETVAL=1
+ ;;
esac
set -e
}
stop_rabbitmq () {
set +e
- su rabbitmq -s /bin/sh -c "$DAEMON stop_all" > /var/log/rabbitmq/shutdown.log 2> /var/log/rabbitmq/shutdown.err
+ status_rabbitmq quiet
+ if [ $RETVAL == 0 ] ; then
+ su $USER -s /bin/sh -c "$DAEMON stop_all" > /var/log/rabbitmq/shutdown_log 2> /var/log/rabbitmq/shutdown_err
+ RETVAL=$?
+ if [ $RETVAL != 0 ] ; then
+ echo FAILED - check /var/log/rabbitmq/shutdown_log, _err
+ else
+ rm -rf $LOCK_FILE
+ fi
+ else
+ echo No nodes running
+ RETVAL=0
+ fi
+ set -e
+}
+
+status_rabbitmq() {
+ set +e
+ if [ "$1" != "quiet" ] ; then
+ su $USER -s /bin/sh -c "$DAEMON status" 2>&1
+ else
+ su $USER -s /bin/sh -c "$DAEMON status" > /dev/null 2>&1
+ fi
if [ $? != 0 ] ; then
- echo FAILED - check /var/log/rabbitmq/shutdown.log, .err
- exit 0
+ RETVAL=1
fi
set -e
}
+rotate_logs_rabbitmq() {
+ set +e
+ su $USER -s /bin/sh -c "$DAEMON rotate_logs ${ROTATE_SUFFIX}" 2>&1
+ set -e
+}
+
+restart_rabbitmq() {
+ stop_rabbitmq
+ start_rabbitmq
+}
+
case "$1" in
- start)
- echo -n "Starting $DESC: "
- start_rabbitmq
- echo "$NAME."
- ;;
- stop)
- echo -n "Stopping $DESC: "
- stop_rabbitmq
- echo "$NAME."
- ;;
- force-reload|restart)
- echo -n "Restarting $DESC: "
- stop_rabbitmq
- start_rabbitmq
- echo "$NAME."
- ;;
- *)
- N=/etc/init.d/$NAME
- echo "Usage: $N {start|stop|restart|force-reload}" >&2
- exit 1
- ;;
+ start)
+ echo -n "Starting $DESC: "
+ start_rabbitmq
+ echo "$NAME."
+ ;;
+ stop)
+ echo -n "Stopping $DESC: "
+ stop_rabbitmq
+ echo "$NAME."
+ ;;
+ status)
+ status_rabbitmq
+ ;;
+ rotate-logs)
+ echo -n "Rotating log files for $DESC: "
+ rotate_logs_rabbitmq
+ ;;
+ force-reload|reload|restart)
+ echo -n "Restarting $DESC: "
+ restart_rabbitmq
+ echo "$NAME."
+ ;;
+ condrestart|try-restart)
+ echo -n "Restarting $DESC: "
+ restart_rabbitmq
+ echo "$NAME."
+ ;;
+ *)
+ echo "Usage: $0 {start|stop|status|rotate-logs|restart|condrestart|try-restart|reload|force-reload}" >&2
+ RETVAL=1
+ ;;
esac
-exit 0
+exit $RETVAL
diff --git a/packaging/RPMS/Fedora/rabbitmq-server.logrotate b/packaging/RPMS/Fedora/rabbitmq-server.logrotate
new file mode 100644
index 00000000..64cd01a1
--- /dev/null
+++ b/packaging/RPMS/Fedora/rabbitmq-server.logrotate
@@ -0,0 +1,12 @@
+/var/log/rabbitmq/*.log {
+ weekly
+ missingok
+ rotate 20
+ compress
+ delaycompress
+ notifempty
+ sharedscripts
+ postrotate
+ /sbin/service rabbitmq-server rotate-logs
+ endscript
+} \ No newline at end of file
diff --git a/packaging/RPMS/Fedora/rabbitmq-server.spec b/packaging/RPMS/Fedora/rabbitmq-server.spec
index 4f3dafaa..43837ba3 100644
--- a/packaging/RPMS/Fedora/rabbitmq-server.spec
+++ b/packaging/RPMS/Fedora/rabbitmq-server.spec
@@ -1,67 +1,69 @@
-%define source_name rabbitmq-server
-
Name: rabbitmq-server
Version: %{rpm_version}
Release: 1
-License: Mozilla Public License
+License: MPLv1.1
Group: Development/Libraries
-Source: http://www.rabbitmq.com/releases/%{source_name}-%{main_version}.tar.gz
+Source: http://www.rabbitmq.com/releases/rabbitmq-server/v%{main_version}/%{name}-%{main_version}.tar.gz
URL: http://www.rabbitmq.com/
Vendor: LShift Ltd., Cohesive Financial Technologies LLC., Rabbit Technlogies Ltd.
-Requires: erlang
+%if 0%{?debian}
+%else
+BuildRequires: python, python-json
+%endif
+Requires: erlang, logrotate
Packager: Hubert Plociniczak <hubert@lshift.net>
BuildRoot: %{_tmppath}/%{name}-%{main_version}-%{release}-root
Summary: The RabbitMQ server
+Requires(post): chkconfig
+Requires(pre): chkconfig initscripts
%description
RabbitMQ is an implementation of AMQP, the emerging standard for high
performance enterprise messaging. The RabbitMQ server is a robust and
scalable implementation of an AMQP broker.
-%define _libdir /usr/lib/erlang
-%define _docdir /usr/share/doc
-%define _maindir $RPM_BUILD_ROOT%{_libdir}/lib/rabbitmq_server-%{main_version}
-%define package_name rabbitmq-server-dist
+%define _mandir /usr/share/man
+%define _sbindir /usr/sbin
+%define _libdir %(erl -noshell -eval "io:format('~s~n', [code:lib_dir()]), halt().")
+%define _maindir %{buildroot}%{_libdir}/rabbitmq_server-%{main_version}
%pre
if [ $1 -gt 1 ]; then
- #Upgrade - stop and remove previous instance of rabbitmq init.d script
- /etc/init.d/rabbitmq-server stop
+ #Upgrade - stop and remove previous instance of rabbitmq-server init.d script
+ /sbin/service rabbitmq-server stop
/sbin/chkconfig --del rabbitmq-server
fi
%prep
-%setup -n %{source_name}-%{main_version}
+%setup -n %{name}-%{main_version}
%build
-mkdir %{package_name}
-mkdir %{package_name}/sbin
-make install TARGET_DIR=`pwd`/%{package_name} \
- SBIN_DIR=`pwd`/%{package_name}/sbin \
- VERSION=%{main_version}
+make
%install
-mkdir -p %{_maindir}
-mkdir -p $RPM_BUILD_ROOT%{_docdir}/rabbitmq-server
-mkdir -p $RPM_BUILD_ROOT/etc/init.d
-mkdir -p $RPM_BUILD_ROOT/usr/sbin
+rm -rf %{buildroot}
-mkdir -p $RPM_BUILD_ROOT/var/lib/rabbitmq/mnesia
-mkdir -p $RPM_BUILD_ROOT/var/log/rabbitmq
+make install TARGET_DIR=%{_maindir} \
+ SBIN_DIR=%{buildroot}%{_sbindir} \
+ MAN_DIR=%{buildroot}%{_mandir}
+ VERSION=%{main_version}
+
+mkdir -p %{buildroot}/var/lib/rabbitmq/mnesia
+mkdir -p %{buildroot}/var/log/rabbitmq
+mkdir -p %{buildroot}/etc/rc.d/init.d/
#Copy all necessary lib files etc.
-cp -r %{package_name}/ebin %{_maindir}
-cp -r %{package_name}/src %{_maindir}
-cp -r %{package_name}/include %{_maindir}
-chmod 755 %{package_name}/sbin/*
-cp %{package_name}/sbin/* $RPM_BUILD_ROOT/usr/sbin/
+cp ../init.d %{buildroot}/etc/rc.d/init.d/rabbitmq-server
+chmod 0755 %{buildroot}/etc/rc.d/init.d/rabbitmq-server
+
+mv %{buildroot}/usr/sbin/rabbitmqctl %{buildroot}/usr/sbin/rabbitmqctl_real
+cp ../rabbitmqctl_wrapper %{buildroot}/usr/sbin/rabbitmqctl
+chmod 0755 %{buildroot}/usr/sbin/rabbitmqctl
-cp ../init.d $RPM_BUILD_ROOT/etc/init.d/rabbitmq-server
-chmod 775 $RPM_BUILD_ROOT/etc/init.d/rabbitmq-server
+cp %{buildroot}%{_mandir}/man1/rabbitmqctl.1.gz %{buildroot}%{_mandir}/man1/rabbitmqctl_real.1.gz
-mv $RPM_BUILD_ROOT/usr/sbin/rabbitmqctl $RPM_BUILD_ROOT/usr/sbin/rabbitmqctl_real
-cp ../rabbitmqctl_wrapper $RPM_BUILD_ROOT/usr/sbin/rabbitmqctl
-chmod 755 $RPM_BUILD_ROOT/usr/sbin/rabbitmqctl
+mkdir -p %{buildroot}/etc/logrotate.d
+cp ../rabbitmq-server.logrotate %{buildroot}/etc/logrotate.d/rabbitmq-server
%post
# create rabbitmq group
@@ -75,64 +77,59 @@ if ! getent passwd rabbitmq >/dev/null; then
usermod -c "Rabbit AMQP Messaging Server" rabbitmq
fi
-# On 64bit /usr/lib64 contains Erlang, not /usr/lib. Fix with a symlink
-ERL_LIB_DIR=$(erl -noshell -eval "io:format(\"~s~n\", [code:lib_dir()]), halt().")
-if [ ! ${ERL_LIB_DIR} = "/usr/lib/erlang/lib" ] ; then
- ln -s /usr/lib/erlang/lib/rabbitmq_server-%{main_version} ${ERL_LIB_DIR}
-fi
-
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq
chown -R rabbitmq:rabbitmq /var/log/rabbitmq
-/sbin/chkconfig --add rabbitmq-server
-/etc/init.d/rabbitmq-server start
+/sbin/chkconfig --add %{name}
+/sbin/service rabbitmq-server start
%preun
if [ $1 = 0 ]; then
#Complete uninstall
- /etc/init.d/rabbitmq-server stop
+ /sbin/service rabbitmq-server stop
/sbin/chkconfig --del rabbitmq-server
-
- # Remove symlink we added above
- ERL_LIB_DIR=$(erl -noshell -eval "io:format(\"~s~n\", [code:lib_dir()]), halt().")
- if [ ! ${ERL_LIB_DIR} = "/usr/lib/erlang/lib" ] ; then
- rm ${ERL_LIB_DIR}/rabbitmq_server-%{main_version}
- fi
- # We do not remove log and lib directories
+ # We do not remove /var/log and /var/lib directories
# Leave rabbitmq user and group
fi
%files
-%defattr(-,root,root)
-%{_libdir}/lib/rabbitmq_server-%{main_version}/
-%{_docdir}/rabbitmq-server/
-/usr/sbin/rabbitmq-server
-/usr/sbin/rabbitmq-multi
-/usr/sbin/rabbitmqctl
-/usr/sbin/rabbitmqctl_real
-/var/lib/rabbitmq
-/var/log/rabbitmq
-/etc/init.d/rabbitmq-server
+%defattr(-,root,root,-)
+%{_libdir}/rabbitmq_server-%{main_version}/
+%{_mandir}/man1/rabbitmq-multi.1.gz
+%{_mandir}/man1/rabbitmq-server.1.gz
+%{_mandir}/man1/rabbitmqctl.1.gz
+%{_mandir}/man1/rabbitmqctl_real.1.gz
+%{_sbindir}/rabbitmq-multi
+%{_sbindir}/rabbitmq-server
+%{_sbindir}/rabbitmqctl
+%{_sbindir}/rabbitmqctl_real
+/var/lib/rabbitmq/
+/var/log/rabbitmq/
+/etc/rc.d/init.d/rabbitmq-server
+%config(noreplace) /etc/logrotate.d/rabbitmq-server
%clean
-rm -rf $RPM_BUILD_ROOT
+rm -rf %{buildroot}
%changelog
-* Mon Mar 3 2008 Adrien Pierard <adrian@lshift.net> 1.3.0
+* Thu Jul 24 2008 Tony Garnock-Jones <tonyg@lshift.net> 1.4.0-1
+- New upstream release
+
+* Mon Mar 3 2008 Adrien Pierard <adrian@lshift.net> 1.3.0-1
- New upstream release
-* Wed Sep 26 2007 Simon MacMullen <simon@lshift.net> 1.2.0
+* Wed Sep 26 2007 Simon MacMullen <simon@lshift.net> 1.2.0-1
- New upstream release
-* Wed Aug 29 2007 Simon MacMullen <simon@lshift.net> 1.1.1
+* Wed Aug 29 2007 Simon MacMullen <simon@lshift.net> 1.1.1-1
- New upstream release
-* Mon Jul 30 2007 Simon MacMullen <simon@lshift.net> 1.1.0-alpha
+* Mon Jul 30 2007 Simon MacMullen <simon@lshift.net> 1.1.0-1.alpha
- New upstream release
-* Tue Jun 12 2007 Hubert Plociniczak <hubert@lshift.net> hubert-20070607
+* Tue Jun 12 2007 Hubert Plociniczak <hubert@lshift.net> 1.0.0-1.20070607
- Building from source tarball, added starting script, stopping
-* Mon May 21 2007 Hubert Plociniczak <hubert@lshift.net> 1.0.0-alpha
+* Mon May 21 2007 Hubert Plociniczak <hubert@lshift.net> 1.0.0-1.alpha
- Initial build of server library of RabbitMQ package
diff --git a/packaging/debs/Debian/Makefile b/packaging/debs/Debian/Makefile
index b49094e2..3e74cb52 100644
--- a/packaging/debs/Debian/Makefile
+++ b/packaging/debs/Debian/Makefile
@@ -1,5 +1,6 @@
TARBALL_DIR=../../../dist
TARBALL=$(shell (cd $(TARBALL_DIR); echo rabbitmq-server-[0-9]*.tar.gz))
+DEBIAN_ORIG_TARBALL=$(shell echo $(TARBALL) | sed -e 's:\(.*\)-\(.*\)\(\.tar\.gz\):\1_\2\.orig\3:g')
VERSION=$(shell echo $(TARBALL) | sed -e 's:rabbitmq-server-\(.*\)\.tar\.gz:\1:g')
UNPACKED_DIR=rabbitmq-server-$(VERSION)
PACKAGENAME=rabbitmq-server
@@ -16,11 +17,12 @@ all:
package: clean
make -C ../.. check_tools
- tar -zxvf $(TARBALL_DIR)/$(TARBALL)
+ cp $(TARBALL_DIR)/$(TARBALL) $(DEBIAN_ORIG_TARBALL)
+ tar -zxvf $(DEBIAN_ORIG_TARBALL)
cp -r debian $(UNPACKED_DIR)
- chmod -R a+x $(UNPACKED_DIR)/debian
+ chmod a+x $(UNPACKED_DIR)/debian/rules
UNOFFICIAL_RELEASE=$(UNOFFICIAL_RELEASE) VERSION=$(VERSION) ./check-changelog.sh rabbitmq-server $(UNPACKED_DIR)
- cd $(UNPACKED_DIR); dpkg-buildpackage -rfakeroot $(SIGNING)
+ cd $(UNPACKED_DIR); GNUPGHOME=$(GNUPG_PATH)/.gnupg dpkg-buildpackage -rfakeroot $(SIGNING)
rm -rf $(UNPACKED_DIR)
clean:
diff --git a/packaging/debs/Debian/debian/changelog b/packaging/debs/Debian/debian/changelog
index 08b760e9..07f5a8dd 100644
--- a/packaging/debs/Debian/debian/changelog
+++ b/packaging/debs/Debian/debian/changelog
@@ -1,3 +1,9 @@
+rabbitmq-server (1.4.0-1) testing; urgency=low
+
+ * New Upstream Release
+
+ -- Tony Garnock-Jones <tonyg@lshift.net> Thu, 24 Jul 2008 13:21:48 +0100
+
rabbitmq-server (1.3.0-1) testing; urgency=low
* New Upstream Release
diff --git a/packaging/debs/Debian/debian/control b/packaging/debs/Debian/debian/control
index ae698e1e..675e15f4 100644
--- a/packaging/debs/Debian/debian/control
+++ b/packaging/debs/Debian/debian/control
@@ -2,14 +2,14 @@ Source: rabbitmq-server
Section: net
Priority: extra
Maintainer: Tony Garnock-Jones <tonyg@rabbitmq.com>
-Build-Depends: cdbs, debhelper (>= 5), erlang-base | erlang-base-hipe, erlang-nox, erlang-dev, erlang-src, make, python
+Build-Depends: cdbs, debhelper (>= 5), erlang-base | erlang-base-hipe, erlang-nox, erlang-dev, erlang-src, make, python, python-json
Standards-Version: 3.7.2
Package: rabbitmq-server
Architecture: all
-Depends: erlang-nox, adduser
+Depends: erlang-nox, adduser, logrotate
Description: An AMQP server written in Erlang
RabbitMQ is an implementation of AMQP, the emerging standard for high
performance enterprise messaging. The RabbitMQ server is a robust and
scalable implementation of an AMQP broker.
- Homepage: http://www.rabbitmq.com/
+Homepage: http://www.rabbitmq.com/
diff --git a/packaging/debs/Debian/debian/copyright b/packaging/debs/Debian/debian/copyright
index e16996e5..9f9f8672 100644
--- a/packaging/debs/Debian/debian/copyright
+++ b/packaging/debs/Debian/debian/copyright
@@ -5,7 +5,7 @@ It was downloaded from http://www.rabbitmq.com/
Upstream Author: The RabbitMQ team <info@rabbitmq.com>
-Copyright: 2006-2008 LShift Ltd.
+Copyright: 2006-2008 Rabbit Technologies Ltd.
License:
The RabbitMQ server is licensed under the MPL.
@@ -485,7 +485,7 @@ EXHIBIT A -Mozilla Public License.
If you have any questions regarding licensing, please contact us at
info@rabbitmq.com.
-The Debian packaging is (C) 2007, Tony Garnock-Jones <tonyg@rabbitmq.com> and
-is licensed under the GPL, see `/usr/share/common-licenses/GPL'.
+The Debian packaging is (C) 2007-2008, Rabbit Technologies Ltd. <info@rabbitmq.com>
+and is licensed under the MPL 1.1, see above.
diff --git a/packaging/debs/Debian/debian/dirs b/packaging/debs/Debian/debian/dirs
index 74ff60e2..74f86314 100644
--- a/packaging/debs/Debian/debian/dirs
+++ b/packaging/debs/Debian/debian/dirs
@@ -1,6 +1,7 @@
usr/lib/erlang/lib
usr/sbin
-usr/share/linda/overrides
+usr/share/man
var/lib/rabbitmq/mnesia
var/log/rabbitmq
+etc/logrotate.d
diff --git a/packaging/debs/Debian/debian/init.d b/packaging/debs/Debian/debian/init.d
index f3999888..a93f3066 100644
--- a/packaging/debs/Debian/debian/init.d
+++ b/packaging/debs/Debian/debian/init.d
@@ -5,7 +5,8 @@
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
-# Short-Description: Enable AMQP service provided by RabbitMQ.
+# Description: RabbitMQ broker
+# Short-Description: Enable AMQP service provided by RabbitMQ broker
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
@@ -14,6 +15,7 @@ NAME=rabbitmq-server
DESC=rabbitmq-server
USER=rabbitmq
NODE_COUNT=1
+ROTATE_SUFFIX=
test -x $DAEMON || exit 0
@@ -22,56 +24,97 @@ if [ -f /etc/default/rabbitmq ] ; then
. /etc/default/rabbitmq
fi
+RETVAL=0
set -e
cd /
start_rabbitmq () {
- set +e
- su rabbitmq -s /bin/sh -c "$DAEMON start_all ${NODE_COUNT}" > /var/log/rabbitmq/startup.log 2> /var/log/rabbitmq/startup.err
- case "$?" in
- 0)
- echo SUCCESS;;
- 1)
- echo TIMEOUT - check /var/log/rabbitmq/startup.\{log,err\};;
- *)
- echo FAILED - check /var/log/rabbitmq/startup.log, .err
- exit 1;;
- esac
- set -e
+ set +e
+ su $USER -s /bin/sh -c "$DAEMON start_all ${NODE_COUNT}" > /var/log/rabbitmq/startup_log 2> /var/log/rabbitmq/startup_err
+ case "$?" in
+ 0)
+ echo SUCCESS
+ RETVAL=0
+ ;;
+ 1)
+ echo TIMEOUT - check /var/log/rabbitmq/startup_\{log,err\}
+ RETVAL=1
+ ;;
+ *)
+ echo FAILED - check /var/log/rabbitmq/startup_log, _err
+ RETVAL=1
+ ;;
+ esac
+ set -e
}
stop_rabbitmq () {
set +e
- su rabbitmq -s /bin/sh -c "$DAEMON stop_all" > /var/log/rabbitmq/shutdown.log 2> /var/log/rabbitmq/shutdown.err
+ status_rabbitmq quiet
+ if [ $RETVAL == 0 ] ; then
+ su $USER -s /bin/sh -c "$DAEMON stop_all" > /var/log/rabbitmq/shutdown_log 2> /var/log/rabbitmq/shutdown_err
+ RETVAL=$?
+ if [ $RETVAL != 0 ] ; then
+ echo FAILED - check /var/log/rabbitmq/shutdown_log, _err
+ fi
+ else
+ echo No nodes running
+ RETVAL=0
+ fi
+ set -e
+}
+
+status_rabbitmq() {
+ set +e
+ if [ "$1" != "quiet" ] ; then
+ su $USER -s /bin/sh -c "$DAEMON status" 2>&1
+ else
+ su $USER -s /bin/sh -c "$DAEMON status" > /dev/null 2>&1
+ fi
if [ $? != 0 ] ; then
- echo FAILED - check /var/log/rabbitmq/shutdown.log, .err
- exit 0
+ RETVAL=1
fi
set -e
}
+rotate_logs_rabbitmq() {
+ set +e
+ su $USER -s /bin/sh -c "$DAEMON rotate_logs ${ROTATE_SUFFIX}" 2>&1
+ set -e
+}
+
+restart_rabbitmq() {
+ stop_rabbitmq
+ start_rabbitmq
+}
+
case "$1" in
- start)
- echo -n "Starting $DESC: "
- start_rabbitmq
- echo "$NAME."
- ;;
- stop)
- echo -n "Stopping $DESC: "
- stop_rabbitmq
- echo "$NAME."
- ;;
- force-reload|restart)
- echo -n "Restarting $DESC: "
- stop_rabbitmq
- start_rabbitmq
- echo "$NAME."
- ;;
- *)
- N=/etc/init.d/$NAME
- echo "Usage: $N {start|stop|restart|force-reload}" >&2
- exit 1
- ;;
+ start)
+ echo -n "Starting $DESC: "
+ start_rabbitmq
+ echo "$NAME."
+ ;;
+ stop)
+ echo -n "Stopping $DESC: "
+ stop_rabbitmq
+ echo "$NAME."
+ ;;
+ status)
+ status_rabbitmq
+ ;;
+ rotate-logs)
+ echo -n "Rotating log files for $DESC: "
+ rotate_logs_rabbitmq
+ ;;
+ force-reload|restart)
+ echo -n "Restarting $DESC: "
+ restart_rabbitmq
+ echo "$NAME."
+ ;;
+ *)
+ echo "Usage: $0 {start|stop|status|rotate-logs|restart|force-reload}" >&2
+ RETVAL=1
+ ;;
esac
-exit 0
+exit $RETVAL
diff --git a/packaging/debs/Debian/debian/rabbitmq-server.logrotate b/packaging/debs/Debian/debian/rabbitmq-server.logrotate
new file mode 100644
index 00000000..247635d1
--- /dev/null
+++ b/packaging/debs/Debian/debian/rabbitmq-server.logrotate
@@ -0,0 +1,12 @@
+/var/log/rabbitmq/*.log {
+ weekly
+ missingok
+ rotate 20
+ compress
+ delaycompress
+ notifempty
+ sharedscripts
+ postrotate
+ /etc/init.d/rabbitmq-server rotate-logs
+ endscript
+} \ No newline at end of file
diff --git a/packaging/debs/Debian/debian/rules b/packaging/debs/Debian/debian/rules
index 15b0d50a..39af711c 100644
--- a/packaging/debs/Debian/debian/rules
+++ b/packaging/debs/Debian/debian/rules
@@ -5,7 +5,7 @@ include /usr/share/cdbs/1/class/makefile.mk
RABBIT_LIB=$(DEB_DESTDIR)usr/lib/erlang/lib/rabbitmq_server-$(DEB_UPSTREAM_VERSION)
-DEB_MAKE_INSTALL_TARGET := install TARGET_DIR=$(RABBIT_LIB)/ SBIN_DIR=$(DEB_DESTDIR)usr/sbin
+DEB_MAKE_INSTALL_TARGET := install TARGET_DIR=$(RABBIT_LIB)/ SBIN_DIR=$(DEB_DESTDIR)usr/sbin MAN_DIR=$(DEB_DESTDIR)usr/share/man
DOCDIR=$(DEB_DESTDIR)usr/share/doc/rabbitmq-server/
@@ -14,5 +14,6 @@ install/rabbitmq-server::
rm $(RABBIT_LIB)/LICENSE*
mv $(DEB_DESTDIR)usr/sbin/rabbitmqctl $(DEB_DESTDIR)usr/sbin/rabbitmqctl_real
cp debian/rabbitmqctl_wrapper $(DEB_DESTDIR)usr/sbin/rabbitmqctl
+ cp debian/rabbitmq-server.logrotate $(DEB_DESTDIR)etc/logrotate.d/rabbitmq-server
+ cp $(DEB_DESTDIR)usr/share/man/man1/rabbitmqctl.1.gz $(DEB_DESTDIR)usr/share/man/man1/rabbitmqctl_real.1.gz
chmod a+x $(DEB_DESTDIR)usr/sbin/rabbitmqctl
- echo "Tag: usr-lib-in-arch-all" > $(DEB_DESTDIR)usr/share/linda/overrides/rabbitmq-server
diff --git a/packaging/generic-unix/Makefile b/packaging/generic-unix/Makefile
index 13257522..b3988696 100644
--- a/packaging/generic-unix/Makefile
+++ b/packaging/generic-unix/Makefile
@@ -7,11 +7,10 @@ dist:
make -C ../.. VERSION=$(VERSION) srcdist
tar -zxvf ../../dist/$(SOURCE_DIR).tar.gz
- mkdir $(TARGET_DIR)
- mkdir $(TARGET_DIR)/sbin
make -C $(SOURCE_DIR) \
TARGET_DIR=`pwd`/$(TARGET_DIR) \
SBIN_DIR=`pwd`/$(TARGET_DIR)/sbin \
+ MAN_DIR=`pwd`/$(TARGET_DIR)/share/man \
install
tar -zcf $(TARGET_TARBALL).tar.gz $(TARGET_DIR)
diff --git a/packaging/windows/Makefile b/packaging/windows/Makefile
index 077461c5..f9437da7 100644
--- a/packaging/windows/Makefile
+++ b/packaging/windows/Makefile
@@ -15,6 +15,7 @@ dist:
rm -rf $(SOURCE_DIR)/scripts
rm -rf $(SOURCE_DIR)/codegen* $(SOURCE_DIR)/Makefile
rm -f $(SOURCE_DIR)/BUILD
+ rm -rf $(SOURCE_DIR)/docs
mv $(SOURCE_DIR) $(TARGET_DIR)
zip -r $(TARGET_ZIP).zip $(TARGET_DIR)
diff --git a/scripts/rabbitmq-multi b/scripts/rabbitmq-multi
index 4709ca0b..5e4f4b38 100755
--- a/scripts/rabbitmq-multi
+++ b/scripts/rabbitmq-multi
@@ -36,7 +36,7 @@ SCRIPT_HOME=$(dirname $0)
export NODENAME NODE_IP_ADDRESS NODE_PORT SCRIPT_HOME PIDS_FILE
exec erl \
- -pa ../ebin \
+ -pa "`dirname $0`/../ebin" \
-noinput \
-hidden \
${ERL_ARGS} \
diff --git a/scripts/rabbitmq-multi.bat b/scripts/rabbitmq-multi.bat
index 34e34ef9..819c99af 100644
--- a/scripts/rabbitmq-multi.bat
+++ b/scripts/rabbitmq-multi.bat
@@ -41,7 +41,7 @@ if "%NODE_PORT%"=="" (
)
set PIDS_FILE=%RABBITMQ_BASE%\rabbitmq.pids
-set SCRIPT_HOME=.
+set SCRIPT_HOME=%~dp0%
if "%ERLANG_HOME%"=="" (
set ERLANG_HOME=%~dp0%..\..\..
@@ -59,5 +59,5 @@ if not exist "%ERLANG_HOME%\bin\erl.exe" (
exit /B
)
-"%ERLANG_HOME%\bin\erl.exe" -pa ../ebin -noinput -hidden -sname rabbitmq_multi -s rabbit_multi %START_ARGS% -extra %*
+"%ERLANG_HOME%\bin\erl.exe" -pa "%~dp0..\ebin" -noinput -hidden -sname rabbitmq_multi -s rabbit_multi %START_ARGS% -extra %*
diff --git a/scripts/rabbitmq-server b/scripts/rabbitmq-server
index a44dd6da..b930c8ed 100755
--- a/scripts/rabbitmq-server
+++ b/scripts/rabbitmq-server
@@ -28,7 +28,10 @@
[ "x" = "x$NODE_IP_ADDRESS" ] && NODE_IP_ADDRESS=0.0.0.0
[ "x" = "x$NODE_PORT" ] && NODE_PORT=5672
-ERL_ARGS="+K true +A30 -kernel inet_default_listen_options [{sndbuf,16384},{recbuf,4096}]"
+ERL_ARGS="+K true +A30 \
+-kernel inet_default_listen_options [{nodelay,true},{sndbuf,16384},{recbuf,4096}] \
+-kernel inet_default_connect_options [{nodelay,true}]"
+
CLUSTER_CONFIG_FILE=/etc/default/rabbitmq_cluster.config
[ "x" = "x$LOG_BASE" ] && LOG_BASE=/var/log/rabbitmq
@@ -39,7 +42,7 @@ CLUSTER_CONFIG_FILE=/etc/default/rabbitmq_cluster.config
## Log rotation
LOGS="${LOG_BASE}/${NODENAME}.log"
SASL_LOGS="${LOG_BASE}/${NODENAME}-sasl.log"
-BACKUP_EXTENSION=".bak"
+BACKUP_EXTENSION=".1"
[ -f "${LOGS}" ] && cat "${LOGS}" >> "${LOGS}${BACKUP_EXTENSION}"
[ -f "${SASL_LOGS}" ] && cat "${SASL_LOGS}" >> "${SASL_LOGS}${BACKUP_EXTENSION}"
@@ -51,7 +54,7 @@ else
fi
erl \
- -pa $(dirname $0)/../ebin \
+ -pa "`dirname $0`/../ebin" \
${START_RABBIT} \
-sname ${NODENAME} \
-boot start_sasl \
diff --git a/scripts/rabbitmq-server.bat b/scripts/rabbitmq-server.bat
index 46f4bd92..f08027d2 100644
--- a/scripts/rabbitmq-server.bat
+++ b/scripts/rabbitmq-server.bat
@@ -65,7 +65,7 @@ set LOG_BASE=%RABBITMQ_BASE_UNIX%/log
rem We save the previous logs in their respective backup
rem Log management (rotation, filtering based of size...) is left as an exercice for the user.
-set BACKUP_EXTENSION=.bak
+set BACKUP_EXTENSION=.1
set LOGS="%RABBITMQ_BASE%\log\%NODENAME%.log"
set SASL_LOGS="%RABBITMQ_BASE%\log\%NODENAME%-sasl.log"
@@ -92,14 +92,15 @@ set CLUSTER_CONFIG=-rabbit cluster_config \""%CLUSTER_CONFIG_FILE:\=/%"\"
set MNESIA_DIR=%MNESIA_BASE%/%NODENAME%-mnesia
"%ERLANG_HOME%\bin\erl.exe" ^
--pa ..\ebin ^
+-pa "%~dp0..\ebin" ^
-noinput ^
-boot start_sasl ^
-sname %NODENAME% ^
-s rabbit ^
+W w ^
+A30 ^
--kernel inet_default_listen_options "[{sndbuf, 16384}, {recbuf, 4096}]" ^
+-kernel inet_default_listen_options "[{nodelay, true}, {sndbuf, 16384}, {recbuf, 4096}]" ^
+-kernel inet_default_connect_options "[{nodelay, true}]" ^
-rabbit tcp_listeners "[{\"%NODE_IP_ADDRESS%\", %NODE_PORT%}]" ^
-kernel error_logger {file,\""%LOG_BASE%/%NODENAME%.log"\"} ^
-sasl errlog_type error ^
diff --git a/scripts/rabbitmqctl b/scripts/rabbitmqctl
index eb359dad..419dcf63 100755
--- a/scripts/rabbitmqctl
+++ b/scripts/rabbitmqctl
@@ -31,7 +31,7 @@ ERL_ARGS=
MNESIA_DIR=${MNESIA_BASE}/${NODENAME}
exec erl \
- -pa ../ebin \
+ -pa "`dirname $0`/../ebin" \
-noinput \
-hidden \
${ERL_ARGS} \
diff --git a/scripts/rabbitmqctl.bat b/scripts/rabbitmqctl.bat
index b34adebe..1ee7e825 100644
--- a/scripts/rabbitmqctl.bat
+++ b/scripts/rabbitmqctl.bat
@@ -40,4 +40,4 @@ if not exist "%ERLANG_HOME%\bin\erl.exe" (
exit /B
)
-"%ERLANG_HOME%\bin\erl.exe" -pa ..\ebin -noinput -hidden -sname rabbitmqctl -s rabbit_control -extra %*
+"%ERLANG_HOME%\bin\erl.exe" -pa "%~dp0..\ebin" -noinput -hidden -sname rabbitmqctl -s rabbit_control -extra %*
diff --git a/src/rabbit.erl b/src/rabbit.erl
index e65d532b..c6ef1749 100644
--- a/src/rabbit.erl
+++ b/src/rabbit.erl
@@ -27,10 +27,12 @@
-behaviour(application).
--export([start/0, stop/0, stop_and_halt/0, status/0]).
+-export([start/0, stop/0, stop_and_halt/0, status/0, rotate_logs/1]).
-export([start/2, stop/1]).
+-export([log_location/1]).
+
-import(application).
-import(mnesia).
-import(lists).
@@ -46,13 +48,18 @@
-ifdef(use_specs).
+-type(log_location() :: 'tty' | 'undefined' | string()).
+-type(file_suffix() :: binary()).
+
-spec(start/0 :: () -> 'ok').
-spec(stop/0 :: () -> 'ok').
-spec(stop_and_halt/0 :: () -> 'ok').
+-spec(rotate_logs/1 :: (file_suffix()) -> 'ok' | {'error', any()}).
-spec(status/0 :: () ->
[{running_applications, [{atom(), string(), string()}]} |
{nodes, [node()]} |
{running_nodes, [node()]}]).
+-spec(log_location/1 :: ('sasl' | 'kernel') -> log_location()).
-endif.
@@ -60,7 +67,7 @@
start() ->
try
- ok = ensure_working_log_config(),
+ ok = ensure_working_log_handlers(),
ok = rabbit_mnesia:ensure_mnesia_dir(),
ok = start_applications(?APPS)
after
@@ -85,6 +92,15 @@ status() ->
[{running_applications, application:which_applications()}] ++
rabbit_mnesia:status().
+rotate_logs(BinarySuffix) ->
+ Suffix = binary_to_list(BinarySuffix),
+ log_rotation_result(rotate_logs(log_location(kernel),
+ Suffix,
+ rabbit_error_logger_file_h),
+ rotate_logs(log_location(sasl),
+ Suffix,
+ rabbit_sasl_report_file_h)).
+
%%--------------------------------------------------------------------
manage_applications(Iterate, Do, Undo, SkipError, ErrorTag, Apps) ->
@@ -98,7 +114,7 @@ manage_applications(Iterate, Do, Undo, SkipError, ErrorTag, Apps) ->
end
end, [], Apps),
ok.
-
+
start_applications(Apps) ->
manage_applications(fun lists:foldl/3,
fun application:start/1,
@@ -128,9 +144,9 @@ start(normal, []) ->
io:format("starting ~-20s ...", [Msg]),
Thunk(),
io:format("done~n");
- ({Msg, M, F, A}) ->
+ ({Msg, M, F, A}) ->
io:format("starting ~-20s ...", [Msg]),
- apply(M, F, A),
+ apply(M, F, A),
io:format("done~n")
end,
[{"database",
@@ -150,14 +166,12 @@ start(normal, []) ->
{"recovery",
fun () ->
ok = maybe_insert_default_data(),
-
ok = rabbit_exchange:recover(),
- ok = rabbit_amqqueue:recover(),
- ok = rabbit_realm:recover()
+ ok = rabbit_amqqueue:recover()
end},
{"persister",
- fun () ->
- ok = start_child(rabbit_persister)
+ fun () ->
+ ok = start_child(rabbit_persister)
end},
{"builtin applications",
fun () ->
@@ -188,6 +202,21 @@ stop(_State) ->
%---------------------------------------------------------------------------
+log_location(Type) ->
+ case application:get_env(Type, case Type of
+ kernel -> error_logger;
+ sasl -> sasl_error_logger
+ end) of
+ {ok, {file, File}} -> File;
+ {ok, false} -> undefined;
+ {ok, tty} -> tty;
+ {ok, silent} -> undefined;
+ {ok, Bad} -> throw({error, {cannot_log_to_file, Bad}});
+ _ -> undefined
+ end.
+
+%---------------------------------------------------------------------------
+
print_banner() ->
{ok, Product} = application:get_key(id),
{ok, Version} = application:get_key(vsn),
@@ -196,7 +225,9 @@ print_banner() ->
?PROTOCOL_VERSION_MAJOR, ?PROTOCOL_VERSION_MINOR,
?COPYRIGHT_MESSAGE, ?INFORMATION_MESSAGE]),
io:format("Logging to ~p~nSASL logging to ~p~n~n",
- [error_log_location(), sasl_log_location()]).
+ [log_location(kernel), log_location(sasl)]).
+
+
start_child(Mod) ->
{ok,_} = supervisor:start_child(rabbit_sup,
@@ -204,6 +235,43 @@ start_child(Mod) ->
transient, 100, worker, [Mod]}),
ok.
+ensure_working_log_handlers() ->
+ Handlers = gen_event:which_handlers(error_logger),
+ ok = ensure_working_log_handler(error_logger_file_h,
+ rabbit_error_logger_file_h,
+ error_logger_tty_h,
+ log_location(kernel),
+ Handlers),
+
+ ok = ensure_working_log_handler(sasl_report_file_h,
+ rabbit_sasl_report_file_h,
+ sasl_report_tty_h,
+ log_location(sasl),
+ Handlers),
+ ok.
+
+ensure_working_log_handler(OldFHandler, NewFHandler, TTYHandler,
+ LogLocation, Handlers) ->
+ case LogLocation of
+ undefined -> ok;
+ tty -> case lists:member(TTYHandler, Handlers) of
+ true -> ok;
+ false ->
+ throw({error, {cannot_log_to_tty,
+ TTYHandler, not_installed}})
+ end;
+ _ -> case lists:member(NewFHandler, Handlers) of
+ true -> ok;
+ false -> case rotate_logs(LogLocation, "",
+ OldFHandler, NewFHandler) of
+ ok -> ok;
+ {error, Reason} ->
+ throw({error, {cannot_log_to_file,
+ LogLocation, Reason}})
+ end
+ end
+ end.
+
maybe_insert_default_data() ->
case rabbit_mnesia:is_db_empty() of
true -> insert_default_data();
@@ -215,26 +283,8 @@ insert_default_data() ->
{ok, DefaultPass} = application:get_env(default_pass),
{ok, DefaultVHost} = application:get_env(default_vhost),
ok = rabbit_access_control:add_vhost(DefaultVHost),
- ok = insert_default_user(DefaultUser, DefaultPass,
- [{DefaultVHost, [<<"/data">>, <<"/admin">>]}]),
- ok.
-
-insert_default_user(Username, Password, VHostSpecs) ->
- ok = rabbit_access_control:add_user(Username, Password),
- lists:foreach(
- fun ({VHostPath, Realms}) ->
- ok = rabbit_access_control:map_user_vhost(
- Username, VHostPath),
- lists:foreach(
- fun (Realm) ->
- RealmFullName =
- rabbit_misc:r(VHostPath, realm, Realm),
- ok = rabbit_access_control:map_user_realm(
- Username,
- rabbit_access_control:full_ticket(
- RealmFullName))
- end, Realms)
- end, VHostSpecs),
+ ok = rabbit_access_control:add_user(DefaultUser, DefaultPass),
+ ok = rabbit_access_control:map_user_vhost(DefaultUser, DefaultVHost),
ok.
start_builtin_amq_applications() ->
@@ -243,40 +293,25 @@ start_builtin_amq_applications() ->
%%restart
ok.
-ensure_working_log_config() ->
- case error_logger:logfile(filename) of
- {error, no_log_file} ->
- %% either no log file was configured or opening it failed.
- case application:get_env(kernel, error_logger) of
- {ok, {file, Filename}} ->
- case filelib:ensure_dir(Filename) of
- ok -> ok;
- {error, Reason1} ->
- throw({error, {cannot_log_to_file,
- Filename, Reason1}})
- end,
- case error_logger:logfile({open, Filename}) of
- ok -> ok;
- {error, Reason2} ->
- throw({error, {cannot_log_to_file,
- Filename, Reason2}})
- end;
- _ -> ok
- end;
- _Filename -> ok
- end.
-
-error_log_location() ->
- case error_logger:logfile(filename) of
- {error,no_log_file} -> tty;
- File -> File
+rotate_logs(File, Suffix, Handler) ->
+ rotate_logs(File, Suffix, Handler, Handler).
+
+rotate_logs(File, Suffix, OldHandler, NewHandler) ->
+ case File of
+ undefined -> ok;
+ tty -> ok;
+ _ -> gen_event:swap_handler(
+ error_logger,
+ {OldHandler, swap},
+ {NewHandler, {File, Suffix}})
end.
-sasl_log_location() ->
- case application:get_env(sasl, sasl_error_logger) of
- {ok, {file, File}} -> File;
- {ok, false} -> undefined;
- {ok, tty} -> tty;
- {ok, Bad} -> throw({error, {cannot_log_to_file, Bad}});
- _ -> undefined
- end.
+log_rotation_result({error, MainLogError}, {error, SaslLogError}) ->
+ {error, {{cannot_rotate_main_logs, MainLogError},
+ {cannot_rotate_sasl_logs, SaslLogError}}};
+log_rotation_result({error, MainLogError}, ok) ->
+ {error, {cannot_rotate_main_logs, MainLogError}};
+log_rotation_result(ok, {error, SaslLogError}) ->
+ {error, {cannot_rotate_sasl_logs, SaslLogError}};
+log_rotation_result(ok, ok) ->
+ ok.
diff --git a/src/rabbit_access_control.erl b/src/rabbit_access_control.erl
index 2be07b19..4342e15b 100644
--- a/src/rabbit_access_control.erl
+++ b/src/rabbit_access_control.erl
@@ -28,12 +28,11 @@
-include("rabbit.hrl").
-export([check_login/2, user_pass_login/2,
- check_vhost_access/2, lookup_realm_access/2]).
+ check_vhost_access/2]).
-export([add_user/2, delete_user/1, change_password/2, list_users/0,
lookup_user/1]).
-export([add_vhost/1, delete_vhost/1, list_vhosts/0, list_vhost_users/1]).
-export([list_user_vhosts/1, map_user_vhost/2, unmap_user_vhost/2]).
--export([list_user_realms/2, map_user_realm/2, full_ticket/1]).
%%----------------------------------------------------------------------------
@@ -42,7 +41,6 @@
-spec(check_login/2 :: (binary(), binary()) -> user()).
-spec(user_pass_login/2 :: (username(), password()) -> user()).
-spec(check_vhost_access/2 :: (user(), vhost()) -> 'ok').
--spec(lookup_realm_access/2 :: (user(), realm_name()) -> maybe(ticket())).
-spec(add_user/2 :: (username(), password()) -> 'ok').
-spec(delete_user/1 :: (username()) -> 'ok').
-spec(change_password/2 :: (username(), password()) -> 'ok').
@@ -55,9 +53,6 @@
-spec(list_user_vhosts/1 :: (username()) -> [vhost()]).
-spec(map_user_vhost/2 :: (username(), vhost()) -> 'ok').
-spec(unmap_user_vhost/2 :: (username(), vhost()) -> 'ok').
--spec(map_user_realm/2 :: (username(), ticket()) -> 'ok').
--spec(list_user_realms/2 :: (username(), vhost()) -> [{name(), ticket()}]).
--spec(full_ticket/1 :: (realm_name()) -> ticket()).
-endif.
@@ -87,7 +82,7 @@ check_login(<<"AMQPLAIN">>, Response) ->
[LoginTable])
end;
-check_login(Mechanism, _Response) ->
+check_login(Mechanism, _Response) ->
rabbit_misc:protocol_error(
access_refused, "unsupported authentication mechanism '~s'",
[Mechanism]).
@@ -130,18 +125,6 @@ check_vhost_access(#user{username = Username}, VHostPath) ->
[VHostPath, Username])
end.
-lookup_realm_access(#user{username = Username}, RealmName = #resource{kind = realm}) ->
- %% TODO: use dirty ops instead
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- case user_realms(Username, RealmName) of
- [] ->
- none;
- [#user_realm{ticket_pattern = TicketPattern}] ->
- TicketPattern
- end
- end).
-
add_user(Username, Password) ->
R = rabbit_misc:execute_mnesia_transaction(
fun () ->
@@ -162,8 +145,7 @@ delete_user(Username) ->
Username,
fun () ->
ok = mnesia:delete({user, Username}),
- ok = mnesia:delete({user_vhost, Username}),
- ok = mnesia:delete({user_realm, Username})
+ ok = mnesia:delete({user_vhost, Username})
end)),
rabbit_log:info("Deleted user ~p~n", [Username]),
R.
@@ -191,24 +173,14 @@ add_vhost(VHostPath) ->
case mnesia:read({vhost, VHostPath}) of
[] ->
ok = mnesia:write(#vhost{virtual_host = VHostPath}),
- DataRealm =
- rabbit_misc:r(VHostPath, realm, <<"/data">>),
- AdminRealm =
- rabbit_misc:r(VHostPath, realm, <<"/admin">>),
- ok = rabbit_realm:add_realm(DataRealm),
- ok = rabbit_realm:add_realm(AdminRealm),
- #exchange{} = rabbit_exchange:declare(
- DataRealm, <<"">>,
- direct, true, false, []),
- #exchange{} = rabbit_exchange:declare(
- DataRealm, <<"amq.direct">>,
- direct, true, false, []),
- #exchange{} = rabbit_exchange:declare(
- DataRealm, <<"amq.topic">>,
- topic, true, false, []),
- #exchange{} = rabbit_exchange:declare(
- DataRealm, <<"amq.fanout">>,
- fanout, true, false, []),
+ [rabbit_exchange:declare(
+ rabbit_misc:r(VHostPath, exchange, Name),
+ Type, true, false, []) ||
+ {Name,Type} <-
+ [{<<"">>, direct},
+ {<<"amq.direct">>, direct},
+ {<<"amq.topic">>, topic},
+ {<<"amq.fanout">>, fanout}]],
ok;
[_] ->
mnesia:abort({vhost_already_exists, VHostPath})
@@ -240,11 +212,6 @@ internal_delete_vhost(VHostPath) ->
ok = rabbit_exchange:delete(Name, false)
end,
rabbit_exchange:list_vhost_exchanges(VHostPath)),
- lists:foreach(fun (RealmName) ->
- ok = rabbit_realm:delete_realm(
- rabbit_misc:r(VHostPath, realm, RealmName))
- end,
- rabbit_realm:list_vhost_realms(VHostPath)),
lists:foreach(fun (Username) ->
ok = unmap_user_vhost(Username, VHostPath)
end,
@@ -290,77 +257,8 @@ unmap_user_vhost(Username, VHostPath) ->
rabbit_misc:with_user_and_vhost(
Username, VHostPath,
fun () ->
- lists:foreach(fun mnesia:delete_object/1,
- user_realms(Username,
- rabbit_misc:r(VHostPath, realm))),
ok = mnesia:delete_object(
#user_vhost{username = Username,
virtual_host = VHostPath})
end)).
-map_user_realm(Username,
- Ticket = #ticket{realm_name = RealmName =
- #resource{virtual_host = VHostPath,
- kind = realm}}) ->
- rabbit_misc:execute_mnesia_transaction(
- rabbit_misc:with_user_and_vhost(
- Username, VHostPath,
- rabbit_misc:with_realm(
- RealmName,
- fun () ->
- lists:foreach(fun mnesia:delete_object/1,
- user_realms(Username, RealmName)),
- case internal_lookup_vhost_access(Username, VHostPath) of
- {ok, _R} ->
- case ticket_liveness(Ticket) of
- alive ->
- ok = mnesia:write(
- #user_realm{username = Username,
- realm = RealmName,
- ticket_pattern = Ticket});
- dead ->
- ok
- end;
- not_found ->
- mnesia:abort(not_mapped_to_vhost)
- end
- end))).
-
-list_user_realms(Username, VHostPath) ->
- [{Name, Pattern} ||
- #user_realm{realm = #resource{name = Name},
- ticket_pattern = Pattern} <-
- %% TODO: use dirty ops instead
- rabbit_misc:execute_mnesia_transaction(
- rabbit_misc:with_user_and_vhost(
- Username, VHostPath,
- fun () ->
- case internal_lookup_vhost_access(
- Username, VHostPath) of
- {ok, _R} ->
- user_realms(Username,
- rabbit_misc:r(VHostPath, realm));
- not_found ->
- mnesia:abort(not_mapped_to_vhost)
- end
- end))].
-
-ticket_liveness(#ticket{passive_flag = false,
- active_flag = false,
- write_flag = false,
- read_flag = false}) ->
- dead;
-ticket_liveness(_) ->
- alive.
-
-full_ticket(RealmName) ->
- #ticket{realm_name = RealmName,
- passive_flag = true,
- active_flag = true,
- write_flag = true,
- read_flag = true}.
-
-user_realms(Username, RealmName) ->
- mnesia:match_object(#user_realm{username = Username,
- realm = RealmName,
- _ = '_'}).
diff --git a/src/rabbit_amqqueue.erl b/src/rabbit_amqqueue.erl
index 63f043ba..bd64f1e4 100644
--- a/src/rabbit_amqqueue.erl
+++ b/src/rabbit_amqqueue.erl
@@ -25,15 +25,15 @@
-module(rabbit_amqqueue).
--export([start/0, recover/0, declare/5, delete/3, purge/1, internal_delete/1]).
--export([pseudo_queue/3]).
+-export([start/0, recover/0, declare/4, delete/3, purge/1, internal_delete/1]).
+-export([pseudo_queue/2]).
-export([lookup/1, with/2, with_or_die/2, list_vhost_queues/1,
- stat/1, stat_all/0, deliver/5, redeliver/2, requeue/3, ack/4,
- commit/2, rollback/2]).
+ stat/1, stat_all/0, deliver/5, redeliver/2, requeue/3, ack/4]).
-export([add_binding/4, delete_binding/4, binding_forcibly_removed/2]).
-export([claim_queue/2]).
-export([basic_get/3, basic_consume/7, basic_cancel/4]).
--export([notify_sent/2, notify_down/2]).
+-export([notify_sent/2]).
+-export([commit_all/2, rollback_all/2, notify_down_all/2]).
-export([on_node_down/1]).
-import(mnesia).
@@ -44,6 +44,8 @@
-include("rabbit.hrl").
-include_lib("stdlib/include/qlc.hrl").
+-define(CALL_TIMEOUT, 5000).
+
%%----------------------------------------------------------------------------
-ifdef(use_specs).
@@ -53,9 +55,12 @@
-type(qfun(A) :: fun ((amqqueue()) -> A)).
-type(bind_res() :: {'ok', non_neg_integer()} |
{'error', 'queue_not_found' | 'exchange_not_found'}).
+-type(ok_or_errors() ::
+ 'ok' | {'error', [{'error' | 'exit' | 'throw', any()}]}).
+
-spec(start/0 :: () -> 'ok').
-spec(recover/0 :: () -> 'ok').
--spec(declare/5 :: (realm_name(), name(), bool(), bool(), amqp_table()) ->
+-spec(declare/4 :: (queue_name(), bool(), bool(), amqp_table()) ->
amqqueue()).
-spec(add_binding/4 ::
(queue_name(), exchange_name(), routing_key(), amqp_table()) ->
@@ -81,9 +86,9 @@
-spec(redeliver/2 :: (pid(), [{message(), bool()}]) -> 'ok').
-spec(requeue/3 :: (pid(), [msg_id()], pid()) -> 'ok').
-spec(ack/4 :: (pid(), maybe(txn()), [msg_id()], pid()) -> 'ok').
--spec(commit/2 :: (pid(), txn()) -> 'ok').
--spec(rollback/2 :: (pid(), txn()) -> 'ok').
--spec(notify_down/2 :: (amqqueue(), pid()) -> 'ok').
+-spec(commit_all/2 :: ([pid()], txn()) -> ok_or_errors()).
+-spec(rollback_all/2 :: ([pid()], txn()) -> ok_or_errors()).
+-spec(notify_down_all/2 :: ([pid()], pid()) -> ok_or_errors()).
-spec(binding_forcibly_removed/2 :: (binding_spec(), queue_name()) -> 'ok').
-spec(claim_queue/2 :: (amqqueue(), pid()) -> 'ok' | 'locked').
-spec(basic_get/3 :: (amqqueue(), pid(), bool()) ->
@@ -96,7 +101,7 @@
-spec(notify_sent/2 :: (pid(), pid()) -> 'ok').
-spec(internal_delete/1 :: (queue_name()) -> 'ok' | not_found()).
-spec(on_node_down/1 :: (node()) -> 'ok').
--spec(pseudo_queue/3 :: (realm_name(), binary(), pid()) -> amqqueue()).
+-spec(pseudo_queue/2 :: (binary(), pid()) -> amqqueue()).
-endif.
@@ -130,9 +135,8 @@ recover_durable_queues() ->
ok
end).
-declare(RealmName, NameBin, Durable, AutoDelete, Args) ->
- QName = rabbit_misc:r(RealmName, queue, NameBin),
- Q = start_queue_process(#amqqueue{name = QName,
+declare(QueueName, Durable, AutoDelete, Args) ->
+ Q = start_queue_process(#amqqueue{name = QueueName,
durable = Durable,
auto_delete = AutoDelete,
arguments = Args,
@@ -140,9 +144,8 @@ declare(RealmName, NameBin, Durable, AutoDelete, Args) ->
pid = none}),
case rabbit_misc:execute_mnesia_transaction(
fun () ->
- case mnesia:wread({amqqueue, QName}) of
+ case mnesia:wread({amqqueue, QueueName}) of
[] -> ok = recover_queue(Q),
- ok = rabbit_realm:add(RealmName, QName),
Q;
[ExistingQ] -> ExistingQ
end
@@ -251,7 +254,7 @@ with(Name, F, E) ->
end.
with(Name, F) ->
- with(Name, F, fun () -> {error, not_found} end).
+ with(Name, F, fun () -> {error, not_found} end).
with_or_die(Name, F) ->
with(Name, F, fun () -> rabbit_misc:protocol_error(
not_found, "no ~s", [rabbit_misc:rs(Name)])
@@ -289,14 +292,29 @@ requeue(QPid, MsgIds, ChPid) ->
ack(QPid, Txn, MsgIds, ChPid) ->
gen_server:cast(QPid, {ack, Txn, MsgIds, ChPid}).
-commit(QPid, Txn) ->
- gen_server:call(QPid, {commit, Txn}).
-
-rollback(QPid, Txn) ->
- gen_server:cast(QPid, {rollback, Txn}).
-
-notify_down(#amqqueue{ pid = QPid }, ChPid) ->
- gen_server:call(QPid, {notify_down, ChPid}).
+commit_all(QPids, Txn) ->
+ Timeout = length(QPids) * ?CALL_TIMEOUT,
+ safe_pmap_ok(
+ fun (QPid) -> gen_server:call(QPid, {commit, Txn}, Timeout) end,
+ QPids).
+
+rollback_all(QPids, Txn) ->
+ safe_pmap_ok(
+ fun (QPid) -> gen_server:cast(QPid, {rollback, Txn}) end,
+ QPids).
+
+notify_down_all(QPids, ChPid) ->
+ Timeout = length(QPids) * ?CALL_TIMEOUT,
+ safe_pmap_ok(
+ fun (QPid) ->
+ rabbit_misc:with_exit_handler(
+ %% we don't care if the queue process has terminated
+ %% in the meantime
+ fun () -> ok end,
+ fun () -> gen_server:call(QPid, {notify_down, ChPid},
+ Timeout) end)
+ end,
+ QPids).
binding_forcibly_removed(BindingSpec, QueueName) ->
rabbit_misc:execute_mnesia_transaction(
@@ -338,28 +356,20 @@ internal_delete(QueueName) ->
case mnesia:wread({amqqueue, QueueName}) of
[] -> {error, not_found};
[Q] ->
- ok = delete_temp(Q),
+ ok = delete_queue(Q),
ok = mnesia:delete({durable_queues, QueueName}),
- ok = rabbit_realm:delete_from_all(QueueName),
ok
end
end).
-delete_temp(Q = #amqqueue{name = QueueName}) ->
+delete_queue(Q = #amqqueue{name = QueueName}) ->
ok = delete_bindings(Q),
ok = rabbit_exchange:delete_binding(
default_binding_spec(QueueName), Q),
ok = mnesia:delete({amqqueue, QueueName}),
ok.
-delete_queue(Q = #amqqueue{name = QueueName, durable = Durable}) ->
- ok = delete_temp(Q),
- if
- Durable -> ok;
- true -> ok = rabbit_realm:delete_from_all(QueueName)
- end.
-
-on_node_down(Node) ->
+on_node_down(Node) ->
rabbit_misc:execute_mnesia_transaction(
fun () ->
qlc:fold(
@@ -370,10 +380,23 @@ on_node_down(Node) ->
node(Pid) == Node]))
end).
-pseudo_queue(RealmName, NameBin, Pid) ->
- #amqqueue{name = rabbit_misc:r(RealmName, queue, NameBin),
+pseudo_queue(QueueName, Pid) ->
+ #amqqueue{name = QueueName,
durable = false,
auto_delete = false,
arguments = [],
binding_specs = [],
pid = Pid}.
+
+safe_pmap_ok(F, L) ->
+ case [R || R <- rabbit_misc:upmap(
+ fun (V) ->
+ try F(V)
+ catch Class:Reason -> {Class, Reason}
+ end
+ end, L),
+ R =/= ok] of
+ [] -> ok;
+ Errors -> {error, Errors}
+ end.
+
diff --git a/src/rabbit_channel.erl b/src/rabbit_channel.erl
index ec1d1fba..a9278898 100644
--- a/src/rabbit_channel.erl
+++ b/src/rabbit_channel.erl
@@ -37,7 +37,7 @@
transaction_id, tx_participants, next_tag,
uncommitted_ack_q, unacked_message_q,
username, virtual_host,
- most_recently_declared_queue, consumer_mapping, next_ticket}).
+ most_recently_declared_queue, consumer_mapping}).
%%----------------------------------------------------------------------------
@@ -94,8 +94,7 @@ init(ProxyPid, [ReaderPid, WriterPid, Username, VHost]) ->
username = Username,
virtual_host = VHost,
most_recently_declared_queue = <<>>,
- consumer_mapping = dict:new(),
- next_ticket = 101}.
+ consumer_mapping = dict:new()}.
handle_message({method, Method, Content}, State) ->
case (catch handle_method(Method, Content, State)) of
@@ -140,7 +139,6 @@ handle_message(Other, State) ->
terminate(Reason, State = #ch{writer_pid = WriterPid}) ->
Res = notify_queues(internal_rollback(State)),
- ok = rabbit_realm:leave_realms(self()),
case Reason of
normal -> ok = Res;
_ -> ok
@@ -195,14 +193,6 @@ die_precondition_failed(Fmt, Params) ->
rabbit_misc:protocol_error({false, 406, <<"PRECONDITION_FAILED">>},
Fmt, Params).
-check_ticket(TicketNumber, FieldIndex, Name, #ch{ username = Username}) ->
- rabbit_ticket:check_ticket(TicketNumber, FieldIndex, Name, Username).
-
-lookup_ticket(TicketNumber, FieldIndex,
- #ch{ username = Username, virtual_host = VHostPath }) ->
- rabbit_ticket:lookup_ticket(TicketNumber, FieldIndex,
- Username, VHostPath).
-
%% check that an exchange/queue name does not contain the reserved
%% "amq." prefix.
%%
@@ -235,57 +225,19 @@ handle_method(_Method, _, #ch{state = starting}) ->
handle_method(#'channel.close'{}, _, State = #ch{writer_pid = WriterPid}) ->
ok = notify_queues(internal_rollback(State)),
- ok = rabbit_realm:leave_realms(self()),
ok = rabbit_writer:send_command(WriterPid, #'channel.close_ok'{}),
ok = rabbit_writer:shutdown(WriterPid),
stop;
-handle_method(#'access.request'{realm = RealmNameBin,
- exclusive = Exclusive,
- passive = Passive,
- active = Active,
- write = Write,
- read = Read},
- _, State = #ch{username = Username,
- virtual_host = VHostPath,
- next_ticket = NextTicket}) ->
- RealmName = rabbit_misc:r(VHostPath, realm, RealmNameBin),
- Ticket = #ticket{realm_name = RealmName,
- passive_flag = Passive,
- active_flag = Active,
- write_flag = Write,
- read_flag = Read},
- case rabbit_realm:access_request(Username, Exclusive, Ticket) of
- ok ->
- rabbit_ticket:record_ticket(NextTicket, Ticket),
- NewState = State#ch{next_ticket = NextTicket + 1},
- {reply, #'access.request_ok'{ticket = NextTicket}, NewState};
- {error, not_found} ->
- rabbit_misc:protocol_error(
- invalid_path, "no ~s", [rabbit_misc:rs(RealmName)]);
- {error, bad_realm_path} ->
- %% FIXME: spec bug? access_refused is a soft error, spec requires it to be hard
- rabbit_misc:protocol_error(
- access_refused, "bad path for ~s", [rabbit_misc:rs(RealmName)]);
- {error, resource_locked} ->
- rabbit_misc:protocol_error(
- resource_locked, "~s is locked", [rabbit_misc:rs(RealmName)]);
- {error, access_refused} ->
- rabbit_misc:protocol_error(
- access_refused,
- "~w permissions denied for user '~s' attempting to access ~s",
- [rabbit_misc:permission_list(Ticket),
- Username, rabbit_misc:rs(RealmName)])
- end;
+handle_method(#'access.request'{},_, State) ->
+ {reply, #'access.request_ok'{ticket = 1}, State};
-handle_method(#'basic.publish'{ticket = TicketNumber,
- exchange = ExchangeNameBin,
+handle_method(#'basic.publish'{exchange = ExchangeNameBin,
routing_key = RoutingKey,
mandatory = Mandatory,
immediate = Immediate},
Content, State = #ch{ virtual_host = VHostPath}) ->
ExchangeName = rabbit_misc:r(VHostPath, exchange, ExchangeNameBin),
- check_ticket(TicketNumber, #ticket.write_flag, ExchangeName, State),
Exchange = rabbit_exchange:lookup_or_die(ExchangeName),
%% We decode the content's properties here because we're almost
%% certain to want to look at delivery-mode and priority.
@@ -323,13 +275,11 @@ handle_method(#'basic.ack'{delivery_tag = DeliveryTag,
uncommitted_ack_q = NewUAQ})
end};
-handle_method(#'basic.get'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'basic.get'{queue = QueueNameBin,
no_ack = NoAck},
_, State = #ch{ proxy_pid = ProxyPid, writer_pid = WriterPid,
next_tag = DeliveryTag }) ->
QueueName = expand_queue_name_shortcut(QueueNameBin, State),
- check_ticket(TicketNumber, #ticket.read_flag, QueueName, State),
case rabbit_amqqueue:with_or_die(
QueueName,
fun (Q) -> rabbit_amqqueue:basic_get(Q, ProxyPid, NoAck) end) of
@@ -352,8 +302,7 @@ handle_method(#'basic.get'{ticket = TicketNumber,
{reply, #'basic.get_empty'{cluster_id = <<>>}, State}
end;
-handle_method(#'basic.consume'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'basic.consume'{queue = QueueNameBin,
consumer_tag = ConsumerTag,
no_local = _, % FIXME: implement
no_ack = NoAck,
@@ -365,7 +314,6 @@ handle_method(#'basic.consume'{ticket = TicketNumber,
case dict:find(ConsumerTag, ConsumerMapping) of
error ->
QueueName = expand_queue_name_shortcut(QueueNameBin, State),
- check_ticket(TicketNumber, #ticket.read_flag, QueueName, State),
ActualConsumerTag =
case ConsumerTag of
<<>> -> rabbit_misc:binstring_guid("amq.ctag");
@@ -391,7 +339,7 @@ handle_method(#'basic.consume'{ticket = TicketNumber,
ConsumerMapping)}};
{error, queue_owned_by_another_connection} ->
%% The spec is silent on which exception to use
- %% here. This seems reasonable?
+ %% here. This seems reasonable?
%% FIXME: check this
rabbit_misc:protocol_error(
@@ -495,8 +443,7 @@ handle_method(#'basic.recover'{}, _, _State) ->
rabbit_misc:protocol_error(
not_allowed, "attempt to recover a transactional channel",[]);
-handle_method(#'exchange.declare'{ticket = TicketNumber,
- exchange = ExchangeNameBin,
+handle_method(#'exchange.declare'{exchange = ExchangeNameBin,
type = TypeNameBin,
passive = false,
durable = Durable,
@@ -505,17 +452,13 @@ handle_method(#'exchange.declare'{ticket = TicketNumber,
nowait = NoWait,
arguments = Args},
_, State = #ch{ virtual_host = VHostPath }) ->
- #ticket{realm_name = RealmName} =
- lookup_ticket(TicketNumber, #ticket.active_flag, State),
CheckedType = rabbit_exchange:check_type(TypeNameBin),
- %% FIXME: clarify spec as per declare wrt differing realms
- X = case rabbit_exchange:lookup(
- rabbit_misc:r(VHostPath, exchange, ExchangeNameBin)) of
+ ExchangeName = rabbit_misc:r(VHostPath, exchange, ExchangeNameBin),
+ X = case rabbit_exchange:lookup(ExchangeName) of
{ok, FoundX} -> FoundX;
{error, not_found} ->
- ActualNameBin = check_name('exchange', ExchangeNameBin),
- rabbit_exchange:declare(RealmName,
- ActualNameBin,
+ check_name('exchange', ExchangeNameBin),
+ rabbit_exchange:declare(ExchangeName,
CheckedType,
Durable,
AutoDelete,
@@ -524,26 +467,21 @@ handle_method(#'exchange.declare'{ticket = TicketNumber,
ok = rabbit_exchange:assert_type(X, CheckedType),
return_ok(State, NoWait, #'exchange.declare_ok'{});
-handle_method(#'exchange.declare'{ticket = TicketNumber,
- exchange = ExchangeNameBin,
+handle_method(#'exchange.declare'{exchange = ExchangeNameBin,
type = TypeNameBin,
passive = true,
nowait = NoWait},
_, State = #ch{ virtual_host = VHostPath }) ->
- %% FIXME: spec issue: permit active_flag here as well as passive_flag?
- #ticket{} = lookup_ticket(TicketNumber, #ticket.passive_flag, State),
ExchangeName = rabbit_misc:r(VHostPath, exchange, ExchangeNameBin),
X = rabbit_exchange:lookup_or_die(ExchangeName),
ok = rabbit_exchange:assert_type(X, rabbit_exchange:check_type(TypeNameBin)),
return_ok(State, NoWait, #'exchange.declare_ok'{});
-handle_method(#'exchange.delete'{ticket = TicketNumber,
- exchange = ExchangeNameBin,
+handle_method(#'exchange.delete'{exchange = ExchangeNameBin,
if_unused = IfUnused,
nowait = NoWait},
_, State = #ch { virtual_host = VHostPath }) ->
ExchangeName = rabbit_misc:r(VHostPath, exchange, ExchangeNameBin),
- check_ticket(TicketNumber, #ticket.active_flag, ExchangeName, State),
case rabbit_exchange:delete(ExchangeName, IfUnused) of
{error, not_found} ->
rabbit_misc:protocol_error(
@@ -555,8 +493,7 @@ handle_method(#'exchange.delete'{ticket = TicketNumber,
return_ok(State, NoWait, #'exchange.delete_ok'{})
end;
-handle_method(#'queue.declare'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'queue.declare'{queue = QueueNameBin,
passive = false,
durable = Durable,
exclusive = ExclusiveDeclare,
@@ -565,8 +502,6 @@ handle_method(#'queue.declare'{ticket = TicketNumber,
arguments = Args},
_, State = #ch { virtual_host = VHostPath,
reader_pid = ReaderPid }) ->
- #ticket{realm_name = RealmName} =
- lookup_ticket(TicketNumber, #ticket.active_flag, State),
%% FIXME: atomic create&claim
Finish =
fun (Q) ->
@@ -587,7 +522,6 @@ handle_method(#'queue.declare'{ticket = TicketNumber,
end,
Q
end,
- %% FIXME: clarify spec as per declare wrt differing realms
Q = case rabbit_amqqueue:with(
rabbit_misc:r(VHostPath, queue, QueueNameBin),
Finish) of
@@ -597,34 +531,28 @@ handle_method(#'queue.declare'{ticket = TicketNumber,
<<>> -> rabbit_misc:binstring_guid("amq.gen");
Other -> check_name('queue', Other)
end,
- Finish(rabbit_amqqueue:declare(RealmName,
- ActualNameBin,
- Durable,
- AutoDelete,
- Args));
+ QueueName = rabbit_misc:r(VHostPath, queue, ActualNameBin),
+ Finish(rabbit_amqqueue:declare(QueueName,
+ Durable, AutoDelete, Args));
Other -> Other
end,
return_queue_declare_ok(State, NoWait, Q);
-handle_method(#'queue.declare'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'queue.declare'{queue = QueueNameBin,
passive = true,
nowait = NoWait},
_, State = #ch{ virtual_host = VHostPath }) ->
- #ticket{} = lookup_ticket(TicketNumber, #ticket.passive_flag, State),
QueueName = rabbit_misc:r(VHostPath, queue, QueueNameBin),
Q = rabbit_amqqueue:with_or_die(QueueName, fun (Q) -> Q end),
return_queue_declare_ok(State, NoWait, Q);
-handle_method(#'queue.delete'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'queue.delete'{queue = QueueNameBin,
if_unused = IfUnused,
if_empty = IfEmpty,
nowait = NoWait
},
_, State) ->
QueueName = expand_queue_name_shortcut(QueueNameBin, State),
- check_ticket(TicketNumber, #ticket.active_flag, QueueName, State),
case rabbit_amqqueue:with_or_die(
QueueName,
fun (Q) -> rabbit_amqqueue:delete(Q, IfUnused, IfEmpty) end) of
@@ -640,8 +568,7 @@ handle_method(#'queue.delete'{ticket = TicketNumber,
message_count = PurgedMessageCount})
end;
-handle_method(#'queue.bind'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'queue.bind'{queue = QueueNameBin,
exchange = ExchangeNameBin,
routing_key = RoutingKey,
nowait = NoWait,
@@ -652,14 +579,13 @@ handle_method(#'queue.bind'{ticket = TicketNumber,
QueueName = expand_queue_name_shortcut(QueueNameBin, State),
ActualRoutingKey = expand_routing_key_shortcut(QueueNameBin, RoutingKey,
State),
- check_ticket(TicketNumber, #ticket.active_flag, QueueName, State),
ExchangeName = rabbit_misc:r(VHostPath, exchange, ExchangeNameBin),
case rabbit_amqqueue:add_binding(QueueName, ExchangeName,
ActualRoutingKey, Arguments) of
- {error, queue_not_found} ->
+ {error, queue_not_found} ->
rabbit_misc:protocol_error(
not_found, "no ~s", [rabbit_misc:rs(QueueName)]);
- {error, exchange_not_found} ->
+ {error, exchange_not_found} ->
rabbit_misc:protocol_error(
not_found, "no ~s", [rabbit_misc:rs(ExchangeName)]);
{error, durability_settings_incompatible} ->
@@ -670,12 +596,10 @@ handle_method(#'queue.bind'{ticket = TicketNumber,
return_ok(State, NoWait, #'queue.bind_ok'{})
end;
-handle_method(#'queue.purge'{ticket = TicketNumber,
- queue = QueueNameBin,
+handle_method(#'queue.purge'{queue = QueueNameBin,
nowait = NoWait},
_, State) ->
QueueName = expand_queue_name_shortcut(QueueNameBin, State),
- check_ticket(TicketNumber, #ticket.read_flag, QueueName, State),
{ok, PurgedMessageCount} = rabbit_amqqueue:with_or_die(
QueueName,
fun (Q) -> rabbit_amqqueue:purge(Q) end),
@@ -783,21 +707,6 @@ ack(ProxyPid, TxnKey, UAQ) ->
make_tx_id() -> rabbit_misc:guid().
-safe_pmap_set_ok(F, S) ->
- case lists:filter(fun (R) -> R =/= ok end,
- rabbit_misc:upmap(
- fun (V) ->
- try F(V)
- catch Class:Reason -> {Class, Reason}
- end
- end, sets:to_list(S))) of
- [] -> ok;
- Errors -> {error, Errors}
- end.
-
-notify_participants(F, TxnKey, Participants) ->
- safe_pmap_set_ok(fun (QPid) -> F(QPid, TxnKey) end, Participants).
-
new_tx(State) ->
State#ch{transaction_id = make_tx_id(),
tx_participants = sets:new(),
@@ -805,8 +714,8 @@ new_tx(State) ->
internal_commit(State = #ch{transaction_id = TxnKey,
tx_participants = Participants}) ->
- case notify_participants(fun rabbit_amqqueue:commit/2,
- TxnKey, Participants) of
+ case rabbit_amqqueue:commit_all(sets:to_list(Participants),
+ TxnKey) of
ok -> new_tx(State);
{error, Errors} -> exit({commit_failed, Errors})
end.
@@ -819,8 +728,8 @@ internal_rollback(State = #ch{transaction_id = TxnKey,
[self(),
queue:len(UAQ),
queue:len(UAMQ)]),
- case notify_participants(fun rabbit_amqqueue:rollback/2,
- TxnKey, Participants) of
+ case rabbit_amqqueue:rollback_all(sets:to_list(Participants),
+ TxnKey) of
ok -> NewUAMQ = queue:join(UAQ, UAMQ),
new_tx(State#ch{unacked_message_q = NewUAMQ});
{error, Errors} -> exit({rollback_failed, Errors})
@@ -843,23 +752,18 @@ fold_per_queue(F, Acc0, UAQ) ->
Acc0, D).
notify_queues(#ch{proxy_pid = ProxyPid, consumer_mapping = Consumers}) ->
- safe_pmap_set_ok(
- fun (QueueName) ->
- case rabbit_amqqueue:with(
- QueueName,
- fun (Q) ->
- rabbit_amqqueue:notify_down(Q, ProxyPid)
- end) of
- ok ->
- ok;
- {error, not_found} ->
- %% queue has been deleted in the meantime
- ok
- end
- end,
- dict:fold(fun (_ConsumerTag, QueueName, S) ->
- sets:add_element(QueueName, S)
- end, sets:new(), Consumers)).
+ rabbit_amqqueue:notify_down_all(
+ [QPid || QueueName <-
+ sets:to_list(
+ dict:fold(fun (_ConsumerTag, QueueName, S) ->
+ sets:add_element(QueueName, S)
+ end, sets:new(), Consumers)),
+ case rabbit_amqqueue:lookup(QueueName) of
+ {ok, Q} -> QPid = Q#amqqueue.pid, true;
+ %% queue has been deleted in the meantime
+ {error, not_found} -> QPid = none, false
+ end],
+ ProxyPid).
is_message_persistent(#content{properties = #'P_basic'{
delivery_mode = Mode}}) ->
diff --git a/src/rabbit_control.erl b/src/rabbit_control.erl
index ad796b61..bc588279 100644
--- a/src/rabbit_control.erl
+++ b/src/rabbit_control.erl
@@ -73,6 +73,7 @@ Available commands:
force_reset
cluster <ClusterNode> ...
status
+ rotate_logs [Suffix]
add_user <UserName> <Password>
delete_user <UserName>
@@ -88,17 +89,6 @@ Available commands:
list_user_vhosts <UserName>
list_vhost_users <VHostPath>
- add_realm <VHostPath> <RealmName>
- delete_realm <VHostPath> <RealmName>
- list_realms <VHostPath>
-
- set_permissions <UserName> <VHostPath> <RealmName> [<Permission> ...]
- Permissions management. The available permissions are 'passive',
- 'active', 'write' and 'read', corresponding to the permissions
- referred to in AMQP's \"access.request\" message, or 'all' as an
- abbreviation for all defined permission flags.
- list_permissions <UserName> <VHostPath>
-
<node> should be the name of the master node of the RabbitMQ cluster. It
defaults to the node named \"rabbit\" on the local host. On a host named
\"server.example.com\", the master node will usually be rabbit@server (unless
@@ -140,6 +130,13 @@ action(status, Node, []) ->
io:format("~n~p~n", [Res]),
ok;
+action(rotate_logs, Node, []) ->
+ io:format("Reopening logs for node ~p ...", [Node]),
+ call(Node, {rabbit, rotate_logs, [""]});
+action(rotate_logs, Node, Args = [Suffix]) ->
+ io:format("Rotating logs to files with suffix ~p ...", [Suffix]),
+ call(Node, {rabbit, rotate_logs, Args});
+
action(add_user, Node, Args = [Username, _Password]) ->
io:format("Creating user ~p ...", [Username]),
call(Node, {rabbit_access_control, add_user, Args});
@@ -182,68 +179,7 @@ action(list_user_vhosts, Node, Args = [_Username]) ->
action(list_vhost_users, Node, Args = [_VHostPath]) ->
io:format("Listing users for vhosts ~p...", Args),
- display_list(call(Node, {rabbit_access_control, list_vhost_users, Args}));
-
-action(add_realm, Node, [VHostPath, RealmName]) ->
- io:format("Adding realm ~p to vhost ~p ...", [RealmName, VHostPath]),
- rpc_call(Node, rabbit_realm, add_realm,
- [realm_rsrc(VHostPath, RealmName)]);
-
-action(delete_realm, Node, [VHostPath, RealmName]) ->
- io:format("Deleting realm ~p from vhost ~p ...", [RealmName, VHostPath]),
- rpc_call(Node, rabbit_realm, delete_realm,
- [realm_rsrc(VHostPath, RealmName)]);
-
-action(list_realms, Node, Args = [_VHostPath]) ->
- io:format("Listing realms for vhost ~p ...", Args),
- display_list(call(Node, {rabbit_realm, list_vhost_realms, Args}));
-
-action(set_permissions, Node,
- [Username, VHostPath, RealmName | Permissions]) ->
- io:format("Setting permissions for user ~p, vhost ~p, realm ~p ...",
- [Username, VHostPath, RealmName]),
- CheckedPermissions = check_permissions(Permissions),
- Ticket = #ticket{
- realm_name = realm_rsrc(VHostPath, RealmName),
- passive_flag = lists:member(passive, CheckedPermissions),
- active_flag = lists:member(active, CheckedPermissions),
- write_flag = lists:member(write, CheckedPermissions),
- read_flag = lists:member(read, CheckedPermissions)},
- rpc_call(Node, rabbit_access_control, map_user_realm,
- [list_to_binary(Username), Ticket]);
-
-action(list_permissions, Node, Args = [_Username, _VHostPath]) ->
- io:format("Listing permissions for user ~p in vhost ~p ...", Args),
- Perms = call(Node, {rabbit_access_control, list_user_realms, Args}),
- if is_list(Perms) ->
- lists:foreach(
- fun ({RealmName, Pattern}) ->
- io:format("~n~s: ~p",
- [binary_to_list(RealmName),
- rabbit_misc:permission_list(Pattern)])
- end,
- lists:sort(Perms)),
- io:nl(),
- ok;
- true -> Perms
- end.
-
-check_permissions([]) -> [];
-check_permissions(["all" | R]) ->
- [passive, active, write, read | check_permissions(R)];
-check_permissions([P | R]) when (P == "passive") or
- (P == "active") or
- (P == "write") or
- (P == "read") ->
- [list_to_atom(P) | check_permissions(R)];
-check_permissions([P | _R]) ->
- io:format("~nError: invalid permission flag ~p~n", [P]),
- usage().
-
-realm_rsrc(VHostPath, RealmName) ->
- rabbit_misc:r(list_to_binary(VHostPath),
- realm,
- list_to_binary(RealmName)).
+ display_list(call(Node, {rabbit_access_control, list_vhost_users, Args})).
display_list(L) when is_list(L) ->
lists:foreach(fun (I) ->
diff --git a/src/rabbit_error_logger.erl b/src/rabbit_error_logger.erl
index 0ae116bb..9220d7b4 100644
--- a/src/rabbit_error_logger.erl
+++ b/src/rabbit_error_logger.erl
@@ -34,10 +34,7 @@
init([DefaultVHost]) ->
#exchange{} = rabbit_exchange:declare(
- #resource{virtual_host = DefaultVHost,
- kind = realm,
- name = <<"/admin">>},
- ?LOG_EXCH_NAME,
+ rabbit_misc:r(DefaultVHost, exchange, ?LOG_EXCH_NAME),
topic, true, false, []),
{ok, #resource{virtual_host = DefaultVHost,
kind = exchange,
diff --git a/src/rabbit_error_logger_file_h.erl b/src/rabbit_error_logger_file_h.erl
new file mode 100644
index 00000000..d67b02ef
--- /dev/null
+++ b/src/rabbit_error_logger_file_h.erl
@@ -0,0 +1,74 @@
+%% The contents of this file are subject to the Mozilla Public License
+%% Version 1.1 (the "License"); you may not use this file except in
+%% compliance with the License. You may obtain a copy of the License at
+%% http://www.mozilla.org/MPL/
+%%
+%% Software distributed under the License is distributed on an "AS IS"
+%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+%% License for the specific language governing rights and limitations
+%% under the License.
+%%
+%% The Original Code is RabbitMQ.
+%%
+%% The Initial Developers of the Original Code are LShift Ltd.,
+%% Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.
+%%
+%% Portions created by LShift Ltd., Cohesive Financial Technologies
+%% LLC., and Rabbit Technologies Ltd. are Copyright (C) 2007-2008
+%% LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit
+%% Technologies Ltd.;
+%%
+%% All Rights Reserved.
+%%
+%% Contributor(s): ______________________________________.
+%%
+
+-module(rabbit_error_logger_file_h).
+
+-behaviour(gen_event).
+
+-export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]).
+
+%% rabbit_error_logger_file_h is a wrapper around the error_logger_file_h
+%% module because the original's init/1 does not match properly
+%% with the result of closing the old handler when swapping handlers.
+%% The first init/1 additionally allows for simple log rotation
+%% when the suffix is not the empty string.
+
+%% Used only when swapping handlers in log rotation
+init({{File, Suffix}, []}) ->
+ case rabbit_misc:append_file(File, Suffix) of
+ ok -> ok;
+ {error, Error} ->
+ rabbit_log:error("Failed to append contents of " ++
+ "log file '~s' to '~s':~n~p~n",
+ [File, [File, Suffix], Error])
+ end,
+ init(File);
+%% Used only when swapping handlers and the original handler
+%% failed to terminate or was never installed
+init({{File, _}, error}) ->
+ init(File);
+%% Used only when swapping handlers without performing
+%% log rotation
+init({File, []}) ->
+ init(File);
+init({_File, _Type} = FileInfo) ->
+ error_logger_file_h:init(FileInfo);
+init(File) ->
+ error_logger_file_h:init(File).
+
+handle_event(Event, State) ->
+ error_logger_file_h:handle_event(Event, State).
+
+handle_info(Event, State) ->
+ error_logger_file_h:handle_info(Event, State).
+
+handle_call(Event, State) ->
+ error_logger_file_h:handle_call(Event, State).
+
+terminate(Reason, State) ->
+ error_logger_file_h:terminate(Reason, State).
+
+code_change(OldVsn, State, Extra) ->
+ error_logger_file_h:code_change(OldVsn, State, Extra).
diff --git a/src/rabbit_exchange.erl b/src/rabbit_exchange.erl
index 113b7878..bb132a50 100644
--- a/src/rabbit_exchange.erl
+++ b/src/rabbit_exchange.erl
@@ -28,7 +28,7 @@
-include("rabbit.hrl").
-include("rabbit_framing.hrl").
--export([recover/0, declare/6, lookup/1, lookup_or_die/1,
+-export([recover/0, declare/5, lookup/1, lookup_or_die/1,
list_vhost_exchanges/1, list_exchange_bindings/1,
simple_publish/6, simple_publish/3,
route/2]).
@@ -50,21 +50,21 @@
not_found() | {'error', 'unroutable' | 'not_delivered'}).
-spec(recover/0 :: () -> 'ok').
--spec(declare/6 :: (realm_name(), name(), exchange_type(), bool(), bool(),
+-spec(declare/5 :: (exchange_name(), exchange_type(), bool(), bool(),
amqp_table()) -> exchange()).
-spec(check_type/1 :: (binary()) -> atom()).
--spec(assert_type/2 :: (exchange(), atom()) -> 'ok').
+-spec(assert_type/2 :: (exchange(), atom()) -> 'ok').
-spec(lookup/1 :: (exchange_name()) -> {'ok', exchange()} | not_found()).
-spec(lookup_or_die/1 :: (exchange_name()) -> exchange()).
-spec(list_vhost_exchanges/1 :: (vhost()) -> [exchange()]).
--spec(list_exchange_bindings/1 :: (exchange_name()) ->
+-spec(list_exchange_bindings/1 :: (exchange_name()) ->
[{queue_name(), routing_key(), amqp_table()}]).
-spec(simple_publish/6 ::
(bool(), bool(), exchange_name(), routing_key(), binary(), binary()) ->
publish_res()).
-spec(simple_publish/3 :: (bool(), bool(), message()) -> publish_res()).
-spec(route/2 :: (exchange(), routing_key()) -> [pid()]).
--spec(add_binding/2 :: (binding_spec(), amqqueue()) ->
+-spec(add_binding/2 :: (binding_spec(), amqqueue()) ->
'ok' | not_found() |
{'error', 'durability_settings_incompatible'}).
-spec(delete_binding/2 :: (binding_spec(), amqqueue()) ->
@@ -90,23 +90,21 @@ recover_durable_exchanges() ->
end, ok, durable_exchanges)
end).
-declare(RealmName, NameBin, Type, Durable, AutoDelete, Args) ->
- XName = rabbit_misc:r(RealmName, exchange, NameBin),
- Exchange = #exchange{name = XName,
+declare(ExchangeName, Type, Durable, AutoDelete, Args) ->
+ Exchange = #exchange{name = ExchangeName,
type = Type,
durable = Durable,
auto_delete = AutoDelete,
arguments = Args},
rabbit_misc:execute_mnesia_transaction(
fun () ->
- case mnesia:wread({exchange, XName}) of
+ case mnesia:wread({exchange, ExchangeName}) of
[] -> ok = mnesia:write(Exchange),
if Durable ->
ok = mnesia:write(
durable_exchanges, Exchange, write);
true -> ok
end,
- ok = rabbit_realm:add(RealmName, XName),
Exchange;
[ExistingX] -> ExistingX
end
@@ -147,15 +145,14 @@ list_vhost_exchanges(VHostPath) ->
list_exchange_bindings(Name) ->
[{QueueName, RoutingKey, Arguments} ||
- #binding{handlers = Handlers} <- bindings_for_exchange(Name),
- #handler{binding_spec = #binding_spec{routing_key = RoutingKey,
- arguments = Arguments},
- queue = QueueName} <- Handlers].
+ #binding{handlers = Handlers} <- bindings_for_exchange(Name),
+ #handler{binding_spec = #binding_spec{routing_key = RoutingKey,
+ arguments = Arguments},
+ queue = QueueName} <- Handlers].
bindings_for_exchange(Name) ->
- qlc:e(qlc:q([B ||
- B = #binding{key = K} <- mnesia:table(binding),
- element(1, K) == Name])).
+ qlc:e(qlc:q([B || B = #binding{key = K} <- mnesia:table(binding),
+ element(1, K) == Name])).
empty_handlers() ->
[].
@@ -187,7 +184,7 @@ simple_publish(Mandatory, Immediate,
%% return the list of qpids to which a message with a given routing
%% key, sent to a particular exchange, should be delivered.
-%%
+%%
%% The function ensures that a qpid appears in the return list exactly
%% as many times as a message should be delivered to it. With the
%% current exchange types that is at most once.
@@ -197,7 +194,7 @@ route(#exchange{name = Name, type = topic}, RoutingKey) ->
mnesia:activity(
async_dirty,
fun () ->
- qlc:e(qlc:q([handler_qpids(H) ||
+ qlc:e(qlc:q([handler_qpids(H) ||
#binding{key = {Name1, PatternKey},
handlers = H}
<- mnesia:table(binding),
@@ -375,6 +372,5 @@ do_internal_delete(ExchangeName, Bindings) ->
ok = mnesia:delete({binding, K})
end, Bindings),
ok = mnesia:delete({durable_exchanges, ExchangeName}),
- ok = mnesia:delete({exchange, ExchangeName}),
- ok = rabbit_realm:delete_from_all(ExchangeName)
+ ok = mnesia:delete({exchange, ExchangeName})
end.
diff --git a/src/rabbit_misc.erl b/src/rabbit_misc.erl
index b71aba42..89648f4f 100644
--- a/src/rabbit_misc.erl
+++ b/src/rabbit_misc.erl
@@ -26,23 +26,23 @@
-module(rabbit_misc).
-include("rabbit.hrl").
-include("rabbit_framing.hrl").
+-include_lib("kernel/include/file.hrl").
-export([method_record_type/1, polite_pause/0, polite_pause/1]).
-export([die/1, frame_error/2, protocol_error/3, protocol_error/4]).
--export([strict_ticket_checking/0]).
-export([get_config/1, get_config/2, set_config/2]).
-export([dirty_read/1]).
-export([r/3, r/2, rs/1]).
--export([permission_list/1]).
-export([enable_cover/0, report_cover/0]).
-export([throw_on_error/2, with_exit_handler/2]).
--export([with_user/2, with_vhost/2, with_realm/2, with_user_and_vhost/3]).
+-export([with_user/2, with_vhost/2, with_user_and_vhost/3]).
-export([execute_mnesia_transaction/1]).
-export([ensure_ok/2]).
-export([localnode/1, tcp_name/3]).
-export([intersperse/2, upmap/2, map_in_order/2]).
-export([guid/0, string_guid/1, binstring_guid/1]).
-export([dirty_read_all/1, dirty_foreach_key/2, dirty_dump_log/1]).
+-export([append_file/2]).
-import(mnesia).
-import(lists).
@@ -64,34 +64,30 @@
(atom() | amqp_error(), string(), [any()]) -> no_return()).
-spec(protocol_error/4 ::
(atom() | amqp_error(), string(), [any()], atom()) -> no_return()).
--spec(strict_ticket_checking/0 :: () -> bool()).
-spec(get_config/1 :: (atom()) -> {'ok', any()} | not_found()).
-spec(get_config/2 :: (atom(), A) -> A).
-spec(set_config/2 :: (atom(), any()) -> 'ok').
-spec(dirty_read/1 :: ({atom(), any()}) -> {'ok', any()} | not_found()).
--spec(r/3 :: (realm_name() | vhost(), K, name()) ->
- r(K) when is_subtype(K, atom())).
+-spec(r/3 :: (vhost(), K, resource_name()) -> r(K) when is_subtype(K, atom())).
-spec(r/2 :: (vhost(), K) -> #resource{virtual_host :: vhost(),
kind :: K,
name :: '_'}
when is_subtype(K, atom())).
--spec(rs/1 :: (r(atom())) -> string()).
--spec(permission_list/1 :: (ticket()) -> [permission()]).
+-spec(rs/1 :: (r(atom())) -> string()).
-spec(enable_cover/0 :: () -> 'ok' | {'error', any()}).
-spec(report_cover/0 :: () -> 'ok').
-spec(throw_on_error/2 ::
(atom(), thunk({error, any()} | {ok, A} | A)) -> A).
--spec(with_exit_handler/2 :: (thunk(A), thunk(A)) -> A).
--spec(with_user/2 :: (username(), thunk(A)) -> A).
+-spec(with_exit_handler/2 :: (thunk(A), thunk(A)) -> A).
+-spec(with_user/2 :: (username(), thunk(A)) -> A).
-spec(with_vhost/2 :: (vhost(), thunk(A)) -> A).
--spec(with_realm/2 :: (realm_name(), thunk(A)) -> A).
--spec(with_user_and_vhost/3 :: (username(), vhost(), thunk(A)) -> A).
+-spec(with_user_and_vhost/3 :: (username(), vhost(), thunk(A)) -> A).
-spec(execute_mnesia_transaction/1 :: (thunk(A)) -> A).
--spec(ensure_ok/2 :: ('ok' | {'error', any()}, atom()) -> 'ok').
+-spec(ensure_ok/2 :: ('ok' | {'error', any()}, atom()) -> 'ok').
-spec(localnode/1 :: (atom()) -> node()).
--spec(tcp_name/3 :: (atom(), ip_address(), ip_port()) -> atom()).
+-spec(tcp_name/3 :: (atom(), ip_address(), ip_port()) -> atom()).
-spec(intersperse/2 :: (A, [A]) -> [A]).
--spec(upmap/2 :: (fun ((A) -> B), [A]) -> [B]).
+-spec(upmap/2 :: (fun ((A) -> B), [A]) -> [B]).
-spec(map_in_order/2 :: (fun ((A) -> B), [A]) -> [B]).
-spec(guid/0 :: () -> guid()).
-spec(string_guid/1 :: (any()) -> string()).
@@ -100,6 +96,7 @@
-spec(dirty_foreach_key/2 :: (fun ((any()) -> any()), atom()) ->
'ok' | 'aborted').
-spec(dirty_dump_log/1 :: (string()) -> 'ok' | {'error', any()}).
+-spec(append_file/2 :: (string(), string()) -> 'ok' | {'error', any()}).
-endif.
@@ -130,24 +127,6 @@ protocol_error(Error, Explanation, Params, Method) ->
CompleteExplanation = lists:flatten(io_lib:format(Explanation, Params)),
exit({amqp, Error, CompleteExplanation, Method}).
-boolean_config_param(Name, TrueValue, FalseValue, DefaultValue) ->
- ActualValue = get_config(Name, DefaultValue),
- if
- ActualValue == TrueValue ->
- true;
- ActualValue == FalseValue ->
- false;
- true ->
- rabbit_log:error(
- "Bad setting for config param '~w': ~p~n" ++
- "legal values are '~w', '~w'; using default value '~w'",
- [Name, ActualValue, TrueValue, FalseValue, DefaultValue]),
- DefaultValue == TrueValue
- end.
-
-strict_ticket_checking() ->
- boolean_config_param(strict_ticket_checking, enabled, disabled, disabled).
-
get_config(Key) ->
case dirty_read({rabbit_config, Key}) of
{ok, {rabbit_config, Key, V}} -> {ok, V};
@@ -182,19 +161,6 @@ rs(#resource{virtual_host = VHostPath, kind = Kind, name = Name}) ->
lists:flatten(io_lib:format("~s '~s' in vhost '~s'",
[Kind, Name, VHostPath])).
-permission_list(Ticket = #ticket{}) ->
- lists:foldr(fun ({Field, Label}, L) ->
- case element(Field, Ticket) of
- true -> [Label | L];
- false -> L
- end
- end,
- [],
- [{#ticket.passive_flag, passive},
- {#ticket.active_flag, active},
- {#ticket.write_flag, write},
- {#ticket.read_flag, read}]).
-
enable_cover() ->
case cover:compile_beam_directory("ebin") of
{error,Reason} -> {error,Reason};
@@ -260,32 +226,13 @@ with_user(Username, Thunk) ->
with_vhost(VHostPath, Thunk) ->
fun () ->
case mnesia:read({vhost, VHostPath}) of
- [] ->
+ [] ->
mnesia:abort({no_such_vhost, VHostPath});
[_V] ->
Thunk()
end
end.
-with_realm(Name = #resource{virtual_host = VHostPath, kind = realm},
- Thunk) ->
- fun () ->
- case mnesia:read({realm, Name}) of
- [] ->
- mnesia:abort({no_such_realm, Name});
- [_R] ->
- case mnesia:match_object(
- #vhost_realm{virtual_host = VHostPath,
- realm = Name}) of
- [] ->
- %% This should never happen
- mnesia:abort({no_such_realm, Name});
- [_VR] ->
- Thunk()
- end
- end
- end.
-
with_user_and_vhost(Username, VHostPath, Thunk) ->
with_user(Username, with_vhost(VHostPath, Thunk)).
@@ -398,3 +345,24 @@ dirty_dump_log1(LH, {K, Terms}) ->
dirty_dump_log1(LH, {K, Terms, BadBytes}) ->
io:format("Bad Chunk, ~p: ~p~n", [BadBytes, Terms]),
dirty_dump_log1(LH, disk_log:chunk(LH, K)).
+
+
+append_file(File, Suffix) ->
+ case file:read_file_info(File) of
+ {ok, FInfo} -> append_file(File, FInfo#file_info.size, Suffix);
+ {error, enoent} -> append_file(File, 0, Suffix);
+ Error -> Error
+ end.
+
+append_file(_, _, "") ->
+ ok;
+append_file(File, 0, Suffix) ->
+ case file:open([File, Suffix], [append]) of
+ {ok, Fd} -> file:close(Fd);
+ Error -> Error
+ end;
+append_file(File, _, Suffix) ->
+ case file:read_file(File) of
+ {ok, Data} -> file:write_file([File, Suffix], Data, [append]);
+ Error -> Error
+ end.
diff --git a/src/rabbit_mnesia.erl b/src/rabbit_mnesia.erl
index 82b80cb4..4ae367ba 100644
--- a/src/rabbit_mnesia.erl
+++ b/src/rabbit_mnesia.erl
@@ -102,23 +102,6 @@ table_definitions() ->
{index, [virtual_host]}]},
{vhost, [{disc_copies, [node()]},
{attributes, record_info(fields, vhost)}]},
- {vhost_realm, [{type, bag},
- {disc_copies, [node()]},
- {attributes, record_info(fields, vhost_realm)},
- {index, [realm]}]},
- {realm, [{disc_copies, [node()]},
- {attributes, record_info(fields, realm)}]},
- {user_realm, [{type, bag},
- {disc_copies, [node()]},
- {attributes, record_info(fields, user_realm)},
- {index, [realm]}]},
- {exclusive_realm_visitor,
- [{record_name, realm_visitor},
- {attributes, record_info(fields, realm_visitor)},
- {index, [pid]}]},
- {realm_visitor, [{type, bag},
- {attributes, record_info(fields, realm_visitor)},
- {index, [pid]}]},
{rabbit_config, [{disc_copies, [node()]}]},
{listener, [{type, bag},
{attributes, record_info(fields, listener)}]},
@@ -257,7 +240,6 @@ init_db(ClusterNodes) ->
ClusterNodes}})
end;
{ok, [_|_]} ->
- ok = ensure_schema_integrity(),
ok = wait_for_tables(),
ok = create_local_table_copies(
case IsDiskNode of
@@ -341,6 +323,7 @@ create_local_table_copy(Tab, Type) ->
ok.
wait_for_tables() ->
+ ok = ensure_schema_integrity(),
case mnesia:wait_for_tables(table_names(), 30000) of
ok -> ok;
{timeout, BadTabs} ->
diff --git a/src/rabbit_multi.erl b/src/rabbit_multi.erl
index cd92f1ac..c6a7e920 100644
--- a/src/rabbit_multi.erl
+++ b/src/rabbit_multi.erl
@@ -70,7 +70,9 @@ usage() ->
Available commands:
start_all <NodeCount> - start a local cluster of RabbitMQ nodes.
+ status - print status of all running nodes
stop_all - stops all local RabbitMQ nodes.
+ rotate_logs [Suffix] - rotate logs for all local and running RabbitMQ nodes.
"),
halt(3).
@@ -87,13 +89,46 @@ action(start_all, [NodeCount], RpcTimeout) ->
false -> timeout
end;
+action(status, [], RpcTimeout) ->
+ io:format("Status of all running nodes...~n", []),
+ call_all_nodes(
+ fun({Node, Pid}) ->
+ Status = rpc:call(Node, rabbit, status, [], RpcTimeout),
+ io:format("Node '~p' with Pid ~p: ~p~n",
+ [Node, Pid, case parse_status(Status) of
+ false -> not_running;
+ true -> running
+ end])
+ end);
+
action(stop_all, [], RpcTimeout) ->
io:format("Stopping all nodes...~n", []),
- case read_pids_file() of
- [] -> throw(no_nodes_running);
- NodePids -> stop_nodes(NodePids, RpcTimeout),
- delete_pids_file()
- end.
+ call_all_nodes(fun({Node, Pid}) ->
+ io:format("Stopping node ~p~n", [Node]),
+ rpc:call(Node, rabbit, stop_and_halt, []),
+ case kill_wait(Pid, RpcTimeout, false) of
+ false -> kill_wait(Pid, RpcTimeout, true);
+ true -> ok
+ end,
+ io:format("OK~n", [])
+ end),
+ delete_pids_file();
+
+action(rotate_logs, [], RpcTimeout) ->
+ action(rotate_logs, [""], RpcTimeout);
+
+action(rotate_logs, [Suffix], RpcTimeout) ->
+ io:format("Rotating logs for all nodes...~n", []),
+ BinarySuffix = list_to_binary(Suffix),
+ call_all_nodes(
+ fun ({Node, _}) ->
+ io:format("Rotating logs for node ~p", [Node]),
+ case rpc:call(Node, rabbit, rotate_logs,
+ [BinarySuffix], RpcTimeout) of
+ {badrpc, Error} -> io:format(": ~p.~n", [Error]);
+ ok -> io:format(": ok.~n", [])
+ end
+ end).
%% PNodePid is the list of PIDs
%% Running is a boolean exhibiting success at some moment
@@ -222,21 +257,6 @@ read_pids_file() ->
FileName, Reason}})
end.
-stop_nodes([],_) -> ok;
-
-stop_nodes([NodePid | Rest], RpcTimeout) ->
- stop_node(NodePid, RpcTimeout),
- stop_nodes(Rest, RpcTimeout).
-
-stop_node({Node, Pid}, RpcTimeout) ->
- io:format("Stopping node ~p~n", [Node]),
- rpc:call(Node, rabbit, stop_and_halt, []),
- case kill_wait(Pid, RpcTimeout, false) of
- false -> kill_wait(Pid, RpcTimeout, true);
- true -> ok
- end,
- io:format("OK~n", []).
-
kill_wait(Pid, TimeLeft, Forceful) when TimeLeft < 0 ->
Cmd = with_os([{unix, fun () -> if Forceful -> "kill -9";
true -> "kill"
@@ -272,6 +292,12 @@ is_dead(Pid) ->
end
end}]).
+call_all_nodes(Func) ->
+ case read_pids_file() of
+ [] -> throw(no_nodes_running);
+ NodePids -> lists:foreach(Func, NodePids)
+ end.
+
getenv(Var) ->
case os:getenv(Var) of
false -> throw({missing_env_var, Var});
diff --git a/src/rabbit_node_monitor.erl b/src/rabbit_node_monitor.erl
index beef5285..2fb582a9 100644
--- a/src/rabbit_node_monitor.erl
+++ b/src/rabbit_node_monitor.erl
@@ -60,7 +60,6 @@ handle_info({nodedown, Node}, State) ->
%% lots of nodes. We really only need to execute this code on
%% *one* node, rather than all of them.
ok = rabbit_networking:on_node_down(Node),
- ok = rabbit_realm:on_node_down(Node),
ok = rabbit_amqqueue:on_node_down(Node),
{noreply, State};
handle_info(_Info, State) ->
diff --git a/src/rabbit_reader.erl b/src/rabbit_reader.erl
index 38349a1c..ce26c11a 100644
--- a/src/rabbit_reader.erl
+++ b/src/rabbit_reader.erl
@@ -59,6 +59,7 @@
%% all states, unless specified otherwise:
%% socket error -> *exit*
%% socket close -> *throw*
+%% writer send failure -> *throw*
%% forced termination -> *exit*
%% handshake_timeout -> *throw*
%% pre-init:
@@ -93,10 +94,18 @@
%% terminate_channel timeout -> remove 'closing' mark, *closing*
%% handshake_timeout -> ignore, *closing*
%% heartbeat timeout -> *throw*
-%% channel exit ->
-%% if abnormal exit then log error
-%% if last channel to exit then send connection.close_ok, start
-%% terminate_connection timer, *closing*
+%% channel exit with hard error
+%% -> log error, wait for channels to terminate forcefully, start
+%% terminate_connection timer, send close, *closed*
+%% channel exit with soft error
+%% -> log error, start terminate_channel timer, mark channel as
+%% closing
+%% if last channel to exit then send connection.close_ok,
+%% start terminate_connection timer, *closed*
+%% else *closing*
+%% channel exits normally
+%% -> if last channel to exit then send connection.close_ok,
+%% start terminate_connection timer, *closed*
%% closed:
%% socket close -> *terminate*
%% receive connection.close_ok -> self() ! terminate_connection,
@@ -243,6 +252,8 @@ mainloop(Parent, Deb, State = #v1{sock= Sock, recv_ref = Ref}) ->
%% since this termination is initiated by our parent it is
%% probably more important to exit quickly.
exit(Reason);
+ {'EXIT', _Pid, E = {writer, send_failed, _Error}} ->
+ throw(E);
{'EXIT', Pid, Reason} ->
mainloop(Parent, Deb, handle_dependent_exit(Pid, Reason, State));
{terminate_channel, Channel, Ref1} ->
@@ -302,24 +313,13 @@ terminate_channel(Channel, Ref, State) ->
end,
State.
-handle_dependent_exit(Pid, Reason,
- State = #v1{connection_state = closing}) ->
- case channel_cleanup(Pid) of
- undefined -> exit({abnormal_dependent_exit, Pid, Reason});
- Channel ->
- case Reason of
- normal -> ok;
- _ -> log_channel_error(closing, Channel, Reason)
- end,
- maybe_close(State)
- end;
handle_dependent_exit(Pid, normal, State) ->
channel_cleanup(Pid),
- State;
+ maybe_close(State);
handle_dependent_exit(Pid, Reason, State) ->
case channel_cleanup(Pid) of
undefined -> exit({abnormal_dependent_exit, Pid, Reason});
- Channel -> handle_exception(State, Channel, Reason)
+ Channel -> maybe_close(handle_exception(State, Channel, Reason))
end.
channel_cleanup(Pid) ->
@@ -376,13 +376,15 @@ wait_for_channel_termination(N, TimerRef) ->
exit(channel_termination_timeout)
end.
-maybe_close(State) ->
+maybe_close(State = #v1{connection_state = closing}) ->
case all_channels() of
[] -> ok = send_on_channel0(
State#v1.sock, #'connection.close_ok'{}),
close_connection(State);
_ -> State
- end.
+ end;
+maybe_close(State) ->
+ State.
handle_frame(Type, 0, Payload, State = #v1{connection_state = CS})
when CS =:= closing; CS =:= closed ->
diff --git a/src/rabbit_realm.erl b/src/rabbit_realm.erl
deleted file mode 100644
index 4463954d..00000000
--- a/src/rabbit_realm.erl
+++ /dev/null
@@ -1,316 +0,0 @@
-%% The contents of this file are subject to the Mozilla Public License
-%% Version 1.1 (the "License"); you may not use this file except in
-%% compliance with the License. You may obtain a copy of the License at
-%% http://www.mozilla.org/MPL/
-%%
-%% Software distributed under the License is distributed on an "AS IS"
-%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-%% License for the specific language governing rights and limitations
-%% under the License.
-%%
-%% The Original Code is RabbitMQ.
-%%
-%% The Initial Developers of the Original Code are LShift Ltd.,
-%% Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.
-%%
-%% Portions created by LShift Ltd., Cohesive Financial Technologies
-%% LLC., and Rabbit Technologies Ltd. are Copyright (C) 2007-2008
-%% LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit
-%% Technologies Ltd.;
-%%
-%% All Rights Reserved.
-%%
-%% Contributor(s): ______________________________________.
-%%
-
--module(rabbit_realm).
-
--export([recover/0]).
--export([add_realm/1, delete_realm/1, list_vhost_realms/1]).
--export([add/2, delete/2, check/2, delete_from_all/1]).
--export([access_request/3, enter_realm/3, leave_realms/1]).
--export([on_node_down/1]).
-
--include("rabbit.hrl").
--include_lib("stdlib/include/qlc.hrl").
-
-%%----------------------------------------------------------------------------
-
--ifdef(use_specs).
-
--type(e_or_q() :: 'exchange' | 'queue').
-
--spec(recover/0 :: () -> 'ok').
--spec(add_realm/1 :: (realm_name()) -> 'ok').
--spec(delete_realm/1 :: (realm_name()) -> 'ok').
--spec(list_vhost_realms/1 :: (vhost()) -> [name()]).
--spec(add/2 :: (realm_name(), r(e_or_q())) -> 'ok').
--spec(delete/2 :: (realm_name(), r(e_or_q())) -> 'ok').
--spec(check/2 :: (realm_name(), r(e_or_q())) -> bool() | not_found()).
--spec(delete_from_all/1 :: (r(e_or_q())) -> 'ok').
--spec(access_request/3 :: (username(), bool(), ticket()) ->
- 'ok' | not_found() | {'error', 'bad_realm_path' |
- 'access_refused' |
- 'resource_locked'}).
--spec(enter_realm/3 :: (realm_name(), bool(), pid()) ->
- 'ok' | {'error', 'resource_locked'}).
--spec(leave_realms/1 :: (pid()) -> 'ok').
--spec(on_node_down/1 :: (node()) -> 'ok').
-
--endif.
-
-%%--------------------------------------------------------------------
-
-recover() ->
- %% preens resource lists, limiting them to currently-extant resources
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- Realms = mnesia:foldl(fun preen_realm/2, [], realm),
- lists:foreach(fun mnesia:write/1, Realms),
- ok
- end).
-
-add_realm(Name = #resource{virtual_host = VHostPath, kind = realm}) ->
- rabbit_misc:execute_mnesia_transaction(
- rabbit_misc:with_vhost(
- VHostPath,
- fun () ->
- case mnesia:read({realm, Name}) of
- [] ->
- NewRealm = #realm{name = Name,
- exchanges = ordsets:new(),
- queues = ordsets:new()},
- ok = mnesia:write(NewRealm),
- ok = mnesia:write(
- #vhost_realm{virtual_host = VHostPath,
- realm = Name}),
- ok;
- [_R] ->
- mnesia:abort({realm_already_exists, Name})
- end
- end)).
-
-delete_realm(Name = #resource{virtual_host = VHostPath, kind = realm}) ->
- rabbit_misc:execute_mnesia_transaction(
- rabbit_misc:with_vhost(
- VHostPath,
- rabbit_misc:with_realm(
- Name,
- fun () ->
- ok = mnesia:delete({realm, Name}),
- ok = mnesia:delete_object(
- #vhost_realm{virtual_host = VHostPath,
- realm = Name}),
- lists:foreach(fun mnesia:delete_object/1,
- mnesia:index_read(user_realm, Name,
- #user_realm.realm)),
- ok
- end))).
-
-list_vhost_realms(VHostPath) ->
- [Name ||
- #vhost_realm{realm = #resource{name = Name}} <-
- %% TODO: use dirty ops instead
- rabbit_misc:execute_mnesia_transaction(
- rabbit_misc:with_vhost(
- VHostPath,
- fun () -> mnesia:read({vhost_realm, VHostPath}) end))].
-
-add(Name = #resource{kind = realm}, Resource) ->
- internal_update_realm_byname(Name, Resource, fun ordsets:add_element/2).
-
-delete(Name = #resource{kind = realm}, Resource) ->
- internal_update_realm_byname(Name, Resource, fun ordsets:del_element/2).
-
-check(Name = #resource{kind = realm}, Resource = #resource{kind = Kind}) ->
- case rabbit_misc:dirty_read({realm, Name}) of
- {ok, R} ->
- case Kind of
- exchange -> ordsets:is_element(Resource, R#realm.exchanges);
- queue -> ordsets:is_element(Resource, R#realm.queues)
- end;
- Other -> Other
- end.
-
-% Requires a mnesia transaction.
-delete_from_all(Resource = #resource{kind = Kind}) ->
- Realms = mnesia:foldl
- (fun (Realm = #realm{exchanges = E0,
- queues = Q0},
- Acc) ->
- IsMember = lists:member(Resource,
- case Kind of
- exchange -> E0;
- queue -> Q0
- end),
- if
- IsMember ->
- [internal_update_realm_record(
- Realm, Resource,
- fun ordsets:del_element/2)
- | Acc];
- true ->
- Acc
- end
- end, [], realm),
- lists:foreach(fun mnesia:write/1, Realms),
- ok.
-
-access_request(Username, Exclusive, Ticket = #ticket{realm_name = RealmName})
- when is_binary(Username) ->
- %% FIXME: We should do this all in a single tx. Otherwise we may
- %% a) get weird answers, b) create inconsistencies in the db
- %% (e.g. realm_visitor records referring to non-existing realms).
- case check_and_lookup(RealmName) of
- {error, Reason} ->
- {error, Reason};
- {ok, _Realm} ->
- {ok, U} = rabbit_access_control:lookup_user(Username),
- case rabbit_access_control:lookup_realm_access(U, RealmName) of
- none ->
- {error, access_refused};
- TicketPattern ->
- case match_ticket(TicketPattern, Ticket) of
- no_match ->
- {error, access_refused};
- match ->
- enter_realm(RealmName, Exclusive, self())
- end
- end
- end.
-
-enter_realm(Name = #resource{kind = realm}, IsExclusive, Pid) ->
- RealmVisitor = #realm_visitor{realm = Name, pid = Pid},
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- case mnesia:read({exclusive_realm_visitor, Name}) of
- [] when IsExclusive ->
- ok = mnesia:delete_object(RealmVisitor),
- %% TODO: find a more efficient way of checking
- %% for "no machting results" that doesn't
- %% involve retrieving all the records
- case mnesia:read({realm_visitor, Name}) of
- [] ->
- mnesia:write(
- exclusive_realm_visitor, RealmVisitor, write),
- ok;
- [_|_] ->
- {error, resource_locked}
- end;
- [] ->
- ok = mnesia:write(RealmVisitor),
- ok;
- [RealmVisitor] when IsExclusive -> ok;
- [RealmVisitor] ->
- ok = mnesia:delete({exclusive_realm_visitor, Name}),
- ok = mnesia:write(RealmVisitor),
- ok;
- [_] ->
- {error, resource_locked}
- end
- end).
-
-leave_realms(Pid) ->
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- case mnesia:index_read(exclusive_realm_visitor, Pid,
- #realm_visitor.pid) of
- [] -> ok;
- [R] ->
- ok = mnesia:delete_object(
- exclusive_realm_visitor, R, write)
- end,
- lists:foreach(fun mnesia:delete_object/1,
- mnesia:index_read(realm_visitor, Pid,
- #realm_visitor.pid)),
- ok
- end).
-
-on_node_down(Node) ->
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- lists:foreach(
- fun (T) -> ok = remove_visitors(Node, T) end,
- [exclusive_realm_visitor, realm_visitor]),
- ok
- end).
-
-%%--------------------------------------------------------------------
-
-preen_realm(Realm = #realm{name = #resource{kind = realm},
- exchanges = E0,
- queues = Q0},
- Realms) ->
- [Realm#realm{exchanges = filter_out_missing(E0, exchange),
- queues = filter_out_missing(Q0, amqqueue)}
- | Realms].
-
-filter_out_missing(Items, TableName) ->
- ordsets:filter(fun (Item) ->
- case mnesia:read({TableName, Item}) of
- [] -> false;
- _ -> true
- end
- end, Items).
-
-internal_update_realm_byname(Name, Resource, SetUpdater) ->
- rabbit_misc:execute_mnesia_transaction(
- fun () ->
- case mnesia:read({realm, Name}) of
- [] ->
- mnesia:abort(not_found);
- [R] ->
- ok = mnesia:write(internal_update_realm_record
- (R, Resource, SetUpdater))
- end
- end).
-
-internal_update_realm_record(R = #realm{exchanges = E0, queues = Q0},
- Resource = #resource{kind = Kind},
- SetUpdater) ->
- case Kind of
- exchange -> R#realm{exchanges = SetUpdater(Resource, E0)};
- queue -> R#realm{queues = SetUpdater(Resource, Q0)}
- end.
-
-check_and_lookup(RealmName = #resource{kind = realm,
- name = <<"/data", _/binary>>}) ->
- lookup(RealmName);
-check_and_lookup(RealmName = #resource{kind = realm,
- name = <<"/admin", _/binary>>}) ->
- lookup(RealmName);
-check_and_lookup(_) ->
- {error, bad_realm_path}.
-
-lookup(Name = #resource{kind = realm}) ->
- rabbit_misc:dirty_read({realm, Name}).
-
-match_ticket(#ticket{passive_flag = PP,
- active_flag = PA,
- write_flag = PW,
- read_flag = PR},
- #ticket{passive_flag = TP,
- active_flag = TA,
- write_flag = TW,
- read_flag = TR}) ->
- if
- %% Matches if either we're not requesting passive access, or
- %% passive access is permitted, and ...
- (not(TP) orelse PP) andalso
- (not(TA) orelse PA) andalso
- (not(TW) orelse PW) andalso
- (not(TR) orelse PR) ->
- match;
- true ->
- no_match
- end.
-
-remove_visitors(Node, T) ->
- qlc:fold(
- fun (R, Acc) ->
- ok = mnesia:delete_object(T, R, write),
- Acc
- end,
- ok,
- qlc:q([R || R = #realm_visitor{pid = Pid} <- mnesia:table(T),
- node(Pid) == Node])).
diff --git a/src/rabbit_router.erl b/src/rabbit_router.erl
index 41a8d64c..a2337647 100644
--- a/src/rabbit_router.erl
+++ b/src/rabbit_router.erl
@@ -150,11 +150,9 @@ run_bindings(QPids, IsMandatory, IsImmediate, Txn, Message) ->
fun (QPid, {Routed, Handled}) ->
case catch rabbit_amqqueue:deliver(IsMandatory, IsImmediate,
Txn, Message, QPid) of
- true -> {true, [QPid | Handled]};
- false -> {true, Handled};
- {'EXIT', Reason} -> rabbit_log:warning("delivery to ~p failed:~n~p~n",
- [QPid, Reason]),
- {Routed, Handled}
+ true -> {true, [QPid | Handled]};
+ false -> {true, Handled};
+ {'EXIT', _Reason} -> {Routed, Handled}
end
end,
{false, []},
diff --git a/src/rabbit_sasl_report_file_h.erl b/src/rabbit_sasl_report_file_h.erl
new file mode 100644
index 00000000..3374d63d
--- /dev/null
+++ b/src/rabbit_sasl_report_file_h.erl
@@ -0,0 +1,86 @@
+%% The contents of this file are subject to the Mozilla Public License
+%% Version 1.1 (the "License"); you may not use this file except in
+%% compliance with the License. You may obtain a copy of the License at
+%% http://www.mozilla.org/MPL/
+%%
+%% Software distributed under the License is distributed on an "AS IS"
+%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+%% License for the specific language governing rights and limitations
+%% under the License.
+%%
+%% The Original Code is RabbitMQ.
+%%
+%% The Initial Developers of the Original Code are LShift Ltd.,
+%% Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.
+%%
+%% Portions created by LShift Ltd., Cohesive Financial Technologies
+%% LLC., and Rabbit Technologies Ltd. are Copyright (C) 2007-2008
+%% LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit
+%% Technologies Ltd.;
+%%
+%% All Rights Reserved.
+%%
+%% Contributor(s): ______________________________________.
+%%
+
+-module(rabbit_sasl_report_file_h).
+
+-behaviour(gen_event).
+
+-export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]).
+
+%% rabbit_sasl_report_file_h is a wrapper around the sasl_report_file_h
+%% module because the original's init/1 does not match properly
+%% with the result of closing the old handler when swapping handlers.
+%% The first init/1 additionally allows for simple log rotation
+%% when the suffix is not the empty string.
+
+%% Used only when swapping handlers and performing
+%% log rotation
+init({{File, Suffix}, []}) ->
+ case rabbit_misc:append_file(File, Suffix) of
+ ok -> ok;
+ {error, Error} ->
+ rabbit_log:error("Failed to append contents of " ++
+ "sasl log file '~s' to '~s':~n~p~n",
+ [File, [File, Suffix], Error])
+ end,
+ init(File);
+%% Used only when swapping handlers and the original handler
+%% failed to terminate or was never installed
+init({{File, _}, error}) ->
+ init(File);
+%% Used only when swapping handlers without
+%% doing any log rotation
+init({File, []}) ->
+ init(File);
+init({_File, _Type} = FileInfo) ->
+ sasl_report_file_h:init(FileInfo);
+init(File) ->
+ sasl_report_file_h:init({File, sasl_error_logger_type()}).
+
+handle_event(Event, State) ->
+ sasl_report_file_h:handle_event(Event, State).
+
+handle_info(Event, State) ->
+ sasl_report_file_h:handle_info(Event, State).
+
+handle_call(Event, State) ->
+ sasl_report_file_h:handle_call(Event, State).
+
+terminate(Reason, State) ->
+ sasl_report_file_h:terminate(Reason, State).
+
+code_change(OldVsn, State, Extra) ->
+ sasl_report_file_h:code_change(OldVsn, State, Extra).
+
+%%----------------------------------------------------------------------
+
+sasl_error_logger_type() ->
+ case application:get_env(sasl, errlog_type) of
+ {ok, error} -> error;
+ {ok, progress} -> progress;
+ {ok, all} -> all;
+ {ok, Bad} -> throw({error, {wrong_errlog_type, Bad}});
+ _ -> all
+ end.
diff --git a/src/rabbit_tests.erl b/src/rabbit_tests.erl
index beeb3508..fff02d73 100644
--- a/src/rabbit_tests.erl
+++ b/src/rabbit_tests.erl
@@ -29,6 +29,8 @@
-import(lists).
+-include_lib("kernel/include/file.hrl").
+
test_content_prop_roundtrip(Datum, Binary) ->
Types = [element(1, E) || E <- Datum],
Values = [element(2, E) || E <- Datum],
@@ -38,7 +40,9 @@ test_content_prop_roundtrip(Datum, Binary) ->
all_tests() ->
passed = test_parsing(),
passed = test_topic_matching(),
+ passed = test_log_management(),
passed = test_app_management(),
+ passed = test_log_management_during_startup(),
passed = test_cluster_management(),
passed = test_user_management(),
passed.
@@ -136,6 +140,134 @@ test_app_management() ->
ok = control_action(status, []),
passed.
+test_log_management() ->
+ MainLog = rabbit:log_location(kernel),
+ SaslLog = rabbit:log_location(sasl),
+ Suffix = ".1",
+
+ %% prepare basic logs
+ file:delete([MainLog, Suffix]),
+ file:delete([SaslLog, Suffix]),
+
+ %% simple logs reopening
+ ok = control_action(rotate_logs, []),
+ [true, true] = empty_files([MainLog, SaslLog]),
+ ok = test_logs_working(MainLog, SaslLog),
+
+ %% simple log rotation
+ ok = control_action(rotate_logs, [Suffix]),
+ [true, true] = non_empty_files([[MainLog, Suffix], [SaslLog, Suffix]]),
+ [true, true] = empty_files([MainLog, SaslLog]),
+ ok = test_logs_working(MainLog, SaslLog),
+
+ %% reopening logs with log rotation performed first
+ ok = clean_logs([MainLog, SaslLog], Suffix),
+ ok = control_action(rotate_logs, []),
+ ok = file:rename(MainLog, [MainLog, Suffix]),
+ ok = file:rename(SaslLog, [SaslLog, Suffix]),
+ ok = test_logs_working([MainLog, Suffix], [SaslLog, Suffix]),
+ ok = control_action(rotate_logs, []),
+ ok = test_logs_working(MainLog, SaslLog),
+
+ %% log rotation on empty file
+ ok = clean_logs([MainLog, SaslLog], Suffix),
+ ok = control_action(rotate_logs, []),
+ ok = control_action(rotate_logs, [Suffix]),
+ [true, true] = empty_files([[MainLog, Suffix], [SaslLog, Suffix]]),
+
+ %% original main log file is not writable
+ ok = make_files_non_writable([MainLog]),
+ {error, {cannot_rotate_main_logs, _}} = control_action(rotate_logs, []),
+ ok = clean_logs([MainLog], Suffix),
+ ok = add_log_handlers([{rabbit_error_logger_file_h, MainLog}]),
+
+ %% original sasl log file is not writable
+ ok = make_files_non_writable([SaslLog]),
+ {error, {cannot_rotate_sasl_logs, _}} = control_action(rotate_logs, []),
+ ok = clean_logs([SaslLog], Suffix),
+ ok = add_log_handlers([{rabbit_sasl_report_file_h, SaslLog}]),
+
+ %% logs with suffix are not writable
+ ok = control_action(rotate_logs, [Suffix]),
+ ok = make_files_non_writable([[MainLog, Suffix], [SaslLog, Suffix]]),
+ ok = control_action(rotate_logs, [Suffix]),
+ ok = test_logs_working(MainLog, SaslLog),
+
+ %% original log files are not writable
+ ok = make_files_non_writable([MainLog, SaslLog]),
+ {error, {{cannot_rotate_main_logs, _},
+ {cannot_rotate_sasl_logs, _}}} = control_action(rotate_logs, []),
+
+ %% logging directed to tty (handlers were removed in last test)
+ ok = clean_logs([MainLog, SaslLog], Suffix),
+ ok = application:set_env(sasl, sasl_error_logger, tty),
+ ok = application:set_env(kernel, error_logger, tty),
+ ok = control_action(rotate_logs, []),
+ [{error, enoent}, {error, enoent}] = empty_files([MainLog, SaslLog]),
+
+ %% rotate logs when logging is turned off
+ ok = application:set_env(sasl, sasl_error_logger, false),
+ ok = application:set_env(kernel, error_logger, silent),
+ ok = control_action(rotate_logs, []),
+ [{error, enoent}, {error, enoent}] = empty_files([MainLog, SaslLog]),
+
+ %% cleanup
+ ok = application:set_env(sasl, sasl_error_logger, {file, SaslLog}),
+ ok = application:set_env(kernel, error_logger, {file, MainLog}),
+ ok = add_log_handlers([{rabbit_error_logger_file_h, MainLog},
+ {rabbit_sasl_report_file_h, SaslLog}]),
+ passed.
+
+test_log_management_during_startup() ->
+ MainLog = rabbit:log_location(kernel),
+ SaslLog = rabbit:log_location(sasl),
+
+ %% start application with simple tty logging
+ ok = control_action(stop_app, []),
+ ok = application:set_env(kernel, error_logger, tty),
+ ok = application:set_env(sasl, sasl_error_logger, tty),
+ ok = add_log_handlers([{error_logger_tty_h, []},
+ {sasl_report_tty_h, []}]),
+ ok = control_action(start_app, []),
+
+ %% start application with tty logging and
+ %% proper handlers not installed
+ ok = control_action(stop_app, []),
+ ok = error_logger:tty(false),
+ ok = delete_log_handlers([sasl_report_tty_h]),
+ ok = case catch control_action(start_app, []) of
+ ok -> exit(got_success_but_expected_failure);
+ {error, {cannot_log_to_tty, _, _}} -> ok
+ end,
+
+ %% fix sasl logging
+ ok = application:set_env(sasl, sasl_error_logger,
+ {file, SaslLog}),
+
+ %% start application with logging to invalid directory
+ TmpLog = "/tmp/rabbit-tests/test.log",
+ file:delete(TmpLog),
+ ok = application:set_env(kernel, error_logger, {file, TmpLog}),
+
+ ok = delete_log_handlers([rabbit_error_logger_file_h]),
+ ok = add_log_handlers([{error_logger_file_h, MainLog}]),
+ ok = case catch control_action(start_app, []) of
+ ok -> exit(got_success_but_expected_failure);
+ {error, {cannot_log_to_file, _, _}} -> ok
+ end,
+
+ %% start application with standard error_logger_file_h
+ %% handler not installed
+ ok = application:set_env(kernel, error_logger, {file, MainLog}),
+ ok = control_action(start_app, []),
+ ok = control_action(stop_app, []),
+
+ %% start application with standard sasl handler not installed
+ %% and rabbit main log handler installed correctly
+ ok = delete_log_handlers([rabbit_sasl_report_file_h]),
+ ok = control_action(start_app, []),
+ passed.
+
test_cluster_management() ->
%% 'cluster' and 'reset' should only work if the app is stopped
@@ -203,7 +335,6 @@ test_cluster_management() ->
end,
ok = control_action(start_app, []),
-
passed.
test_cluster_management2(SecondaryNode) ->
@@ -284,31 +415,12 @@ test_user_management() ->
control_action(unmap_user_vhost, ["foo", "/"]),
{error, {no_such_user, _}} =
control_action(list_user_vhosts, ["foo"]),
- {error, {no_such_user, _}} =
- control_action(set_permissions, ["foo", "/", "/data"]),
- {error, {no_such_user, _}} =
- control_action(list_permissions, ["foo", "/"]),
{error, {no_such_vhost, _}} =
control_action(map_user_vhost, ["guest", "/testhost"]),
{error, {no_such_vhost, _}} =
control_action(unmap_user_vhost, ["guest", "/testhost"]),
{error, {no_such_vhost, _}} =
control_action(list_vhost_users, ["/testhost"]),
- {error, {no_such_vhost, _}} =
- control_action(set_permissions, ["guest", "/testhost", "/data"]),
- {error, {no_such_vhost, _}} =
- control_action(list_permissions, ["guest", "/testhost"]),
- {error, {no_such_vhost, _}} =
- control_action(add_realm, ["/testhost", "/data/test"]),
- {error, {no_such_vhost, _}} =
- control_action(delete_realm, ["/testhost", "/data/test"]),
- {error, {no_such_vhost, _}} =
- control_action(list_realms, ["/testhost"]),
- {error, {no_such_realm, _}} =
- control_action(set_permissions, ["guest", "/", "/data/test"]),
- {error, {no_such_realm, _}} =
- control_action(delete_realm, ["/", "/data/test"]),
-
%% user creation
ok = control_action(add_user, ["foo", "bar"]),
{error, {user_already_exists, _}} =
@@ -327,32 +439,6 @@ test_user_management() ->
ok = control_action(map_user_vhost, ["foo", "/testhost"]),
ok = control_action(list_user_vhosts, ["foo"]),
- %% realm creation
- ok = control_action(add_realm, ["/testhost", "/data/test"]),
- {error, {realm_already_exists, _}} =
- control_action(add_realm, ["/testhost", "/data/test"]),
- ok = control_action(list_realms, ["/testhost"]),
-
- %% user permissions
- ok = control_action(set_permissions,
- ["foo", "/testhost", "/data/test",
- "passive", "active", "write", "read"]),
- ok = control_action(list_permissions, ["foo", "/testhost"]),
- ok = control_action(set_permissions,
- ["foo", "/testhost", "/data/test", "all"]),
- ok = control_action(set_permissions,
- ["foo", "/testhost", "/data/test"]),
- {error, not_mapped_to_vhost} =
- control_action(set_permissions,
- ["guest", "/testhost", "/data/test"]),
- {error, not_mapped_to_vhost} =
- control_action(list_permissions, ["guest", "/testhost"]),
-
- %% realm deletion
- ok = control_action(delete_realm, ["/testhost", "/data/test"]),
- {error, {no_such_realm, _}} =
- control_action(delete_realm, ["/testhost", "/data/test"]),
-
%% user/vhost unmapping
ok = control_action(unmap_user_vhost, ["foo", "/testhost"]),
ok = control_action(unmap_user_vhost, ["foo", "/testhost"]),
@@ -364,13 +450,7 @@ test_user_management() ->
%% deleting a populated vhost
ok = control_action(add_vhost, ["/testhost"]),
- ok = control_action(add_realm, ["/testhost", "/data/test"]),
ok = control_action(map_user_vhost, ["foo", "/testhost"]),
- ok = control_action(set_permissions,
- ["foo", "/testhost", "/data/test", "all"]),
- _ = rabbit_amqqueue:declare(
- rabbit_misc:r(<<"/testhost">>, realm, <<"/data/test">>),
- <<"bar">>, true, false, []),
ok = control_action(delete_vhost, ["/testhost"]),
%% user deletion
@@ -380,6 +460,8 @@ test_user_management() ->
passed.
+%---------------------------------------------------------------------
+
control_action(Command, Args) -> control_action(Command, node(), Args).
control_action(Command, Node, Args) ->
@@ -391,3 +473,52 @@ control_action(Command, Node, Args) ->
io:format("failed.~n"),
Other
end.
+
+empty_files(Files) ->
+ [case file:read_file_info(File) of
+ {ok, FInfo} -> FInfo#file_info.size == 0;
+ Error -> Error
+ end || File <- Files].
+
+non_empty_files(Files) ->
+ [case EmptyFile of
+ {error, Reason} -> {error, Reason};
+ _ -> not(EmptyFile)
+ end || EmptyFile <- empty_files(Files)].
+
+test_logs_working(MainLogFile, SaslLogFile) ->
+ ok = rabbit_log:error("foo bar"),
+ ok = error_logger:error_report(crash_report, [foo, bar]),
+ %% give the error loggers some time to catch up
+ timer:sleep(50),
+ [true, true] = non_empty_files([MainLogFile, SaslLogFile]),
+ ok.
+
+clean_logs(Files, Suffix) ->
+ [begin
+ ok = delete_file(File),
+ ok = delete_file([File, Suffix])
+ end || File <- Files],
+ ok.
+
+delete_file(File) ->
+ case file:delete(File) of
+ ok -> ok;
+ {error, enoent} -> ok;
+ Error -> Error
+ end.
+
+make_files_non_writable(Files) ->
+ [ok = file:write_file_info(File, #file_info{mode=0}) ||
+ File <- Files],
+ ok.
+
+add_log_handlers(Handlers) ->
+ [ok = error_logger:add_report_handler(Handler, Args) ||
+ {Handler, Args} <- Handlers],
+ ok.
+
+delete_log_handlers(Handlers) ->
+ [[] = error_logger:delete_report_handler(Handler) ||
+ Handler <- Handlers],
+ ok.
diff --git a/src/rabbit_ticket.erl b/src/rabbit_ticket.erl
deleted file mode 100644
index 3a608faa..00000000
--- a/src/rabbit_ticket.erl
+++ /dev/null
@@ -1,131 +0,0 @@
-%% The contents of this file are subject to the Mozilla Public License
-%% Version 1.1 (the "License"); you may not use this file except in
-%% compliance with the License. You may obtain a copy of the License at
-%% http://www.mozilla.org/MPL/
-%%
-%% Software distributed under the License is distributed on an "AS IS"
-%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-%% License for the specific language governing rights and limitations
-%% under the License.
-%%
-%% The Original Code is RabbitMQ.
-%%
-%% The Initial Developers of the Original Code are LShift Ltd.,
-%% Cohesive Financial Technologies LLC., and Rabbit Technologies Ltd.
-%%
-%% Portions created by LShift Ltd., Cohesive Financial Technologies
-%% LLC., and Rabbit Technologies Ltd. are Copyright (C) 2007-2008
-%% LShift Ltd., Cohesive Financial Technologies LLC., and Rabbit
-%% Technologies Ltd.;
-%%
-%% All Rights Reserved.
-%%
-%% Contributor(s): ______________________________________.
-%%
-
--module(rabbit_ticket).
--include("rabbit.hrl").
-
--export([record_ticket/2, lookup_ticket/4, check_ticket/4]).
-
--import(application).
-
-%%----------------------------------------------------------------------------
-
--ifdef(use_specs).
-
--type(ticket_number() :: non_neg_integer()).
-%% we'd like to write #ticket.passive_flag | #ticket.active_flag | ...
-%% but dialyzer doesn't support that.
--type(ticket_field() :: 3..6).
-
--spec(record_ticket/2 :: (ticket_number(), ticket()) -> 'ok').
--spec(lookup_ticket/4 ::
- (ticket_number(), ticket_field(), username(), vhost()) ->
- ticket()).
--spec(check_ticket/4 ::
- (ticket_number(), ticket_field(), r('exchange' | 'queue'), username()) ->
- 'ok').
-
--endif.
-
-%%----------------------------------------------------------------------------
-
-record_ticket(TicketNumber, Ticket) ->
- put({ticket, TicketNumber}, Ticket),
- ok.
-
-lookup_ticket(TicketNumber, FieldIndex, Username, VHostPath) ->
- case get({ticket, TicketNumber}) of
- undefined ->
- %% Spec: "The server MUST isolate access tickets per
- %% channel and treat an attempt by a client to mix these
- %% as a connection exception."
- rabbit_log:warning("Attempt by client to use invalid ticket ~p~n", [TicketNumber]),
- maybe_relax_checks(TicketNumber, Username, VHostPath);
- Ticket = #ticket{} ->
- case element(FieldIndex, Ticket) of
- false -> rabbit_misc:protocol_error(
- access_refused,
- "ticket ~w has insufficient permissions",
- [TicketNumber]);
- true -> Ticket
- end
- end.
-
-maybe_relax_checks(TicketNumber, Username, VHostPath) ->
- case rabbit_misc:strict_ticket_checking() of
- true ->
- rabbit_misc:protocol_error(
- access_refused, "invalid ticket ~w", [TicketNumber]);
- false ->
- rabbit_log:warning("Lax ticket check mode: fabricating full ticket ~p for user ~p, vhost ~p~n",
- [TicketNumber, Username, VHostPath]),
- Ticket = rabbit_access_control:full_ticket(
- rabbit_misc:r(VHostPath, realm, <<"/data">>)),
- case rabbit_realm:access_request(Username, false, Ticket) of
- ok -> record_ticket(TicketNumber, Ticket),
- Ticket;
- {error, Reason} ->
- rabbit_misc:protocol_error(
- Reason,
- "fabrication of ticket ~w for user '~s' in vhost '~s' failed",
- [TicketNumber, Username, VHostPath])
- end
- end.
-
-check_ticket(TicketNumber, FieldIndex,
- Name = #resource{virtual_host = VHostPath}, Username) ->
- #ticket{realm_name = RealmName} =
- lookup_ticket(TicketNumber, FieldIndex, Username, VHostPath),
- case resource_in_realm(RealmName, Name) of
- false ->
- case rabbit_misc:strict_ticket_checking() of
- true ->
- rabbit_misc:protocol_error(
- access_refused,
- "insufficient permissions in ticket ~w to access ~s in ~s",
- [TicketNumber, rabbit_misc:rs(Name),
- rabbit_misc:rs(RealmName)]);
- false ->
- rabbit_log:warning("Lax ticket check mode: ignoring cross-realm access for ticket ~p~n", [TicketNumber]),
- ok
- end;
- true ->
- ok
- end.
-
-resource_in_realm(RealmName, ResourceName = #resource{kind = Kind}) ->
- CacheKey = {resource_cache, RealmName, Kind},
- case get(CacheKey) of
- Name when Name == ResourceName ->
- true;
- _ ->
- case rabbit_realm:check(RealmName, ResourceName) of
- true ->
- put(CacheKey, ResourceName),
- true;
- _ ->
- false
- end
- end.
diff --git a/src/rabbit_writer.erl b/src/rabbit_writer.erl
index c3c7db53..2c7fa2ab 100644
--- a/src/rabbit_writer.erl
+++ b/src/rabbit_writer.erl
@@ -157,10 +157,15 @@ internal_send_command(Sock, Channel, MethodRecord, Content, FrameMax) ->
%% when these are full. So the fact that we process the result
%% asynchronously does not impact flow control.
internal_send_command_async(Sock, Channel, MethodRecord) ->
- true = erlang:port_command(Sock, assemble_frames(Channel, MethodRecord)),
+ true = port_cmd(Sock, assemble_frames(Channel, MethodRecord)),
ok.
internal_send_command_async(Sock, Channel, MethodRecord, Content, FrameMax) ->
- true = erlang:port_command(Sock, assemble_frames(Channel, MethodRecord,
- Content, FrameMax)),
+ true = port_cmd(Sock, assemble_frames(Channel, MethodRecord,
+ Content, FrameMax)),
ok.
+
+port_cmd(Sock, Data) ->
+ try erlang:port_command(Sock, Data)
+ catch error:Error -> exit({writer, send_failed, Error})
+ end.