You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by ch...@apache.org on 2016/03/30 19:13:41 UTC
[3/3] qpid-dispatch git commit: DISPATCH-188: Implement policy. merge
from branch crolke-DISPATCH-188-1.
DISPATCH-188: Implement policy. merge from branch crolke-DISPATCH-188-1.
Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/48e81620
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/48e81620
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/48e81620
Branch: refs/heads/master
Commit: 48e8162081806d8b4d55efca7cf5ea49d6083d37
Parents: f93d5ce
Author: Chuck Rolke <cr...@redhat.com>
Authored: Wed Mar 30 13:05:47 2016 -0400
Committer: Chuck Rolke <cr...@redhat.com>
Committed: Wed Mar 30 13:05:47 2016 -0400
----------------------------------------------------------------------
doc/notes/qdr-policy-01.odt | Bin 0 -> 38076 bytes
doc/notes/qdr-policy-01.pdf | Bin 0 -> 168277 bytes
doc/notes/qdr-policy-diagrams-01.odg | Bin 0 -> 30918 bytes
include/qpid/dispatch/container.h | 1 +
include/qpid/dispatch/driver.h | 13 +-
include/qpid/dispatch/server.h | 12 +
python/qpid_dispatch/management/qdrouter.json | 128 ++++
.../qdrouter.policyRuleset.settings.txt | 105 +++
python/qpid_dispatch_internal/dispatch.py | 6 +
.../qpid_dispatch_internal/management/agent.py | 33 +
.../qpid_dispatch_internal/management/config.py | 38 +-
.../qpid_dispatch_internal/management/schema.py | 2 +-
.../qpid_dispatch_internal/policy/__init__.py | 20 +
.../policy/policy_local.py | 709 +++++++++++++++++
.../policy/policy_manager.py | 157 ++++
.../policy/policy_util.py | 338 +++++++++
src/CMakeLists.txt | 1 +
src/container.c | 73 +-
src/dispatch.c | 44 +-
src/dispatch_private.h | 13 +
src/policy.c | 758 +++++++++++++++++++
src/policy.h | 165 ++++
src/policy_internal.h | 103 +++
src/posix/driver.c | 19 +-
src/server.c | 116 ++-
src/server_private.h | 7 +
tests/CMakeLists.txt | 12 +-
tests/config-1/A.json | 81 ++
tests/policy-1/management-access.json | 45 ++
tests/policy-1/policy-boardwalk.json | 96 +++
tests/policy-1/policy-safari.json | 96 +++
.../test-policy-conf-includes-folder.conf.in | 64 ++
tests/policy-2/make-sasl.sh | 63 ++
tests/policy-2/policy-photoserver-sasl.conf.in | 4 +
tests/policy-2/policy-photoserver-sasl.sasldb | Bin 0 -> 12288 bytes
tests/policy-2/ssl_certs/gencerts.sh | 39 +
tests/policy-2/test-router-with-policy.json.in | 170 +++++
tests/policy_test.c | 89 +++
tests/router_policy_test.py | 294 +++++++
tests/run_unit_tests.c | 2 +
tests/system_tests_policy.py.in | 111 +++
41 files changed, 3967 insertions(+), 60 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/doc/notes/qdr-policy-01.odt
----------------------------------------------------------------------
diff --git a/doc/notes/qdr-policy-01.odt b/doc/notes/qdr-policy-01.odt
new file mode 100644
index 0000000..5e9f185
Binary files /dev/null and b/doc/notes/qdr-policy-01.odt differ
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/doc/notes/qdr-policy-01.pdf
----------------------------------------------------------------------
diff --git a/doc/notes/qdr-policy-01.pdf b/doc/notes/qdr-policy-01.pdf
new file mode 100644
index 0000000..024adca
Binary files /dev/null and b/doc/notes/qdr-policy-01.pdf differ
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/doc/notes/qdr-policy-diagrams-01.odg
----------------------------------------------------------------------
diff --git a/doc/notes/qdr-policy-diagrams-01.odg b/doc/notes/qdr-policy-diagrams-01.odg
new file mode 100644
index 0000000..af344ce
Binary files /dev/null and b/doc/notes/qdr-policy-diagrams-01.odg differ
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/include/qpid/dispatch/container.h
----------------------------------------------------------------------
diff --git a/include/qpid/dispatch/container.h b/include/qpid/dispatch/container.h
index 39fe968..22c6870 100644
--- a/include/qpid/dispatch/container.h
+++ b/include/qpid/dispatch/container.h
@@ -169,6 +169,7 @@ void *qd_link_get_context(qd_link_t *link);
void qd_link_set_conn_context(qd_link_t *link, void *link_context);
void *qd_link_get_conn_context(qd_link_t *link);
+void policy_notify_opened(void *container, qd_connection_t *conn, void *context);
qd_direction_t qd_link_direction(const qd_link_t *link);
qd_connection_t *qd_link_connection(qd_link_t *link);
pn_link_t *qd_link_pn(qd_link_t *link);
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/include/qpid/dispatch/driver.h
----------------------------------------------------------------------
diff --git a/include/qpid/dispatch/driver.h b/include/qpid/dispatch/driver.h
index 05e8b18..c3c1b79 100644
--- a/include/qpid/dispatch/driver.h
+++ b/include/qpid/dispatch/driver.h
@@ -178,9 +178,11 @@ void qdpn_listener_trace(qdpn_listener_t *listener, pn_trace_t trace);
/** Accept a connection that is pending on the listener.
*
* @param[in] listener the listener to accept the connection on
+ * @param[in] policy function that accepts remote host name and returns
+ * decision to allow or deny this connection
* @return a new connector for the remote, or NULL on error
*/
-qdpn_connector_t *qdpn_listener_accept(qdpn_listener_t *listener);
+qdpn_connector_t *qdpn_listener_accept(qdpn_listener_t *listener, void *policy, bool (*policy_fn)(void *, const char *));
/** Access the application context that is associated with the listener.
*
@@ -314,11 +316,18 @@ void qdpn_connector_set_context(qdpn_connector_t *connector, void *context);
/** Access the name of the connector
*
- * @param[in] connector the connector which will hole the name
+ * @param[in] connector the connector of interest
* @return the name of the connector in the form of a null-terminated character string.
*/
const char *qdpn_connector_name(const qdpn_connector_t *connector);
+/** Access the numeric host ip of the connector
+ *
+ * @param[in] connector the connector of interest
+ * @return the numeric host ip address of the connector in the form of a null-terminated character string.
+ */
+const char *qdpn_connector_hostip(const qdpn_connector_t *connector);
+
/** Access the transport used by this connector.
*
* @param[in] connector connector whose transport will be returned
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/include/qpid/dispatch/server.h
----------------------------------------------------------------------
diff --git a/include/qpid/dispatch/server.h b/include/qpid/dispatch/server.h
index 46f50b5..71ac479 100644
--- a/include/qpid/dispatch/server.h
+++ b/include/qpid/dispatch/server.h
@@ -572,6 +572,18 @@ void qd_connection_invoke_deferred(qd_connection_t *conn, qd_deferred_t call, vo
/**
+ * Write accessor to the connection's proton-event stall flag.
+ * When set no further events are processed on this connection.
+ * Used during processing of policy decisions to hold off incoming
+ * pipeline of amqp events.
+ *
+ * @param conn Connection object
+ * @param stall Value of stall flag
+ */
+void qd_connection_set_event_stall(qd_connection_t *conn, bool stall);
+
+
+/**
* Create a listener for incoming connections.
*
* @param qd The dispatch handle returned by qd_dispatch.
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch/management/qdrouter.json
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/qdrouter.json b/python/qpid_dispatch/management/qdrouter.json
index 8ff352a..64cf6a4 100644
--- a/python/qpid_dispatch/management/qdrouter.json
+++ b/python/qpid_dispatch/management/qdrouter.json
@@ -735,6 +735,7 @@
"CONFIG",
"ERROR",
"DISPATCH",
+ "POLICY",
"DEFAULT"
],
"required": true,
@@ -1235,6 +1236,133 @@
}
},
+ "policy": {
+ "description": "Defines global connection limit",
+ "extends": "configurationEntity",
+ "singleton": true,
+ "attributes": {
+ "maximumConnections": {
+ "type": "integer",
+ "default": 0,
+ "description": "Global maximum number of concurrent client connections allowed. Zero implies no limit. This limit is always enforced even if no other policy settings have been defined.",
+ "required": false,
+ "create": true
+ },
+ "enableAccessRules": {
+ "type": "boolean",
+ "default": false,
+ "description": "Enable user rule set processing and connection denial.",
+ "required": false,
+ "create": true
+ },
+ "policyFolder": {
+ "type": "path",
+ "default": "",
+ "description": "The path to a folder that holds policyRuleset definition .json files. For a small system the rulesets may all be defined in this file. At a larger scale it is better to have the policy files in their own folder and to have none of the rulesets defined here. All rulesets in all .json files in this folder are processed.",
+ "required": false,
+ "create": true
+ },
+ "connectionsProcessed": {"type": "integer", "graph": true},
+ "connectionsDenied": {"type": "integer", "graph": true},
+ "connectionsCurrent": {"type": "integer", "graph": true}
+ }
+ },
+
+ "policyRuleset": {
+ "description": "Per application definition of the locations from which users may connect and the groups to which users belong.",
+ "extends": "configurationEntity",
+ "operations": ["CREATE"],
+ "attributes": {
+ "applicationName": {
+ "type": "string",
+ "description": "The application name.",
+ "required": true
+ },
+ "maxConnections": {
+ "type": "integer",
+ "default": 0,
+ "description": "Maximum number of concurrent client connections allowed. Zero implies no limit.",
+ "required": false,
+ "create": true
+ },
+ "maxConnPerUser": {
+ "type": "integer",
+ "default": 0,
+ "description": "Maximum number of concurrent client connections allowed for any single user. Zero implies no limit.",
+ "required": false,
+ "create": true
+ },
+ "maxConnPerHost": {
+ "type": "integer",
+ "default": 0,
+ "description": "Maximum number of concurrent client connections allowed for any remote host. Zero implies no limit.",
+ "required": false,
+ "create": true
+ },
+ "userGroups": {
+ "type": "map",
+ "description": "A map where each key is a user group name and the corresponding value is a CSV string naming the users in that group. Users who are assigned to one or more groups are deemed 'restricted'. Restricted users are subject to connection ingress policy and are assigned policy settings based on the assigned user groups. Unrestricted users may be allowed or denied. If unrestricted users are allowed to connect then they are assigned to user group default.",
+ "required": false,
+ "create": true
+ },
+ "ingressHostGroups": {
+ "type": "map",
+ "description": "A map where each key is an ingress host group name and the corresponding value is a CSV string naming the IP addresses or address ranges in that group. IP addresses may be FQDN strings or numeric IPv4 or IPv6 host addresses. A host range is two host addresses of the same address family separated with a hyphen. The wildcard host address '*' represents any host address.",
+ "required": false,
+ "create": true
+ },
+ "ingressPolicies": {
+ "type": "map",
+ "description": "A map where each key is a user group name and the corresponding value is a CSV string naming the ingress host group names that restrict the ingress host for the user group. Users who are members of the user group are allowed to connect only from a host in one of the named ingress host groups.",
+ "required": false,
+ "create": true
+ },
+ "connectionAllowDefault": {
+ "type": "boolean",
+ "description": "Unrestricted users, those who are not members of a defined user group, are allowed to connect to this application. Unrestricted users are assigned to the 'default' user group and receive 'default' settings.",
+ "default": false,
+ "required": false,
+ "create": true
+ },
+ "settings": {
+ "type": "map",
+ "description": "A map where each key is a user group name and the value is a map of the corresponding settings for that group.",
+ "required": false,
+ "create": true
+ }
+ }
+ },
+
+ "policyStats": {
+ "description": "Per application connection and access statistics.",
+ "extends": "operationalEntity",
+ "attributes": {
+ "applicationName": {
+ "type": "string",
+ "description": "The application name."
+ },
+ "connectionsApproved": {"type": "integer", "graph": true},
+ "connectionsDenied": {"type": "integer", "graph": true},
+ "connectionsCurrent": {"type": "integer", "graph": true},
+ "perUserState": {
+ "type": "map",
+ "description": "A map where the key is the authenticated user name and the value is a list of the user's connections."
+ },
+ "perHostState": {
+ "type": "map",
+ "description": "A map where the key is the host name and the value is a list of the host's connections."
+ },
+
+ "sessionDenied": {"type": "integer", "graph": true},
+ "senderDenied": {"type": "integer", "graph": true},
+ "receiverDenied": {"type": "integer", "graph": true},
+ "dynamicSrcDenied": {"type": "integer", "graph": true},
+ "anonymousSenderDenied": {"type": "integer", "graph": true},
+ "linkSourceDenied": {"type": "integer", "graph": true},
+ "linkTargetDenied": {"type": "integer", "graph": true}
+ }
+ },
+
"dummy": {
"description": "Dummy entity for test purposes.",
"extends": "entity",
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch/management/qdrouter.policyRuleset.settings.txt
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/qdrouter.policyRuleset.settings.txt b/python/qpid_dispatch/management/qdrouter.policyRuleset.settings.txt
new file mode 100644
index 0000000..773df7a
--- /dev/null
+++ b/python/qpid_dispatch/management/qdrouter.policyRuleset.settings.txt
@@ -0,0 +1,105 @@
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+
+
+
+The schema `qdrouterd.json` is a JSON format file that defines annotations and
+entity types of the Qpid Dispatch Router management model. The model is based
+on the AMQP management specification.
+
+Schema entity `policyRuleset` includes several attributes of type map. In the current form the management schema provides no way to define the keys and values in these attributes. These maps cannot be specified in the schema and they cannot be checked by the schema processing.
+
+Until the schema is extended specify embedded maps this document describes the policyRuleset settings.
+
+ "policyAppSettings": {
+ "description": "For a given user group define the policy settings applied to the user's AMQP connection.",
+ "extends": "configurationEntity",
+ "attributes": {
+ "userGroupName": {
+ "type": "string",
+ "description": "The user group to which these settings apply.",
+ "required": true
+ },
+ "maxFrameSize": {
+ "type": "integer",
+ "description": "Largest frame that may be sent on this connection. Zero implies system default. (AMQP Open, max-frame-size)",
+ "default": 65536,
+ "required": false,
+ "create": true
+ },
+ "maxMessageSize": {
+ "type": "integer",
+ "description": "Largest message size supported by links created on this connection. Zero implies system default. (AMQP Attach, max-message-size)",
+ "default": 0,
+ "required": false,
+ "create": true
+ },
+ "maxSessionWindow": {
+ "type": "integer",
+ "description": "Largest incoming and outgoing window for sessions created on this connection. Zero implies system default. (AMQP Begin, incoming-window, outgoing-window)",
+ "default": 2147483647,
+ "required": false,
+ "create": true
+ },
+ "maxSessions": {
+ "type": "integer",
+ "description": "Maximum number of sessions that may be created on this connection. Zero implies system default. (AMQP Open, channel-max)",
+ "default": 10,
+ "required": false,
+ "create": true
+ },
+ "maxSenders": {
+ "type": "integer",
+ "description": "Maximum number of sending links that may be created on this connection. Zero implies system default.",
+ "default": 10,
+ "required": false,
+ "create": true
+ },
+ "maxReceivers": {
+ "type": "integer",
+ "description": "Maximum number of receiving links that may be created on this connection. Zero implies system default.",
+ "required": false,
+ "create": true
+ },
+ "allowDynamicSrc": {
+ "type": "boolean",
+ "description": "This connection is allowed to use the dynamic link source feature.",
+ "default": false,
+ "required": false,
+ "create": true
+ },
+ "allowAnonymousSender": {
+ "type": "boolean",
+ "description": "This connection is allowed to use the Anonymous Sender feature.",
+ "default": false,
+ "required": false,
+ "create": true
+ },
+ "sources": {
+ "type": "string",
+ "description": "List of Source addresses allowed when creating receiving links.",
+ "required": false,
+ "create": true
+ },
+ "targets": {
+ "type": "string",
+ "description": "List of Target addresses allowed when creating sending links.",
+ "required": false,
+ "create": true
+ }
+ }
+ }
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/dispatch.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/dispatch.py b/python/qpid_dispatch_internal/dispatch.py
index 3b16193..3ad4436 100644
--- a/python/qpid_dispatch_internal/dispatch.py
+++ b/python/qpid_dispatch_internal/dispatch.py
@@ -72,6 +72,12 @@ class QdDll(ctypes.PyDLL):
self._prototype(self.qd_dispatch_configure_link_route, None, [self.qd_dispatch_p, py_object])
self._prototype(self.qd_dispatch_configure_auto_link, None, [self.qd_dispatch_p, py_object])
+ self._prototype(self.qd_dispatch_configure_policy, None, [self.qd_dispatch_p, py_object])
+ self._prototype(self.qd_dispatch_register_policy_manager, None, [self.qd_dispatch_p, py_object])
+ self._prototype(self.qd_dispatch_policy_c_counts_alloc, c_long, [], check=False)
+ self._prototype(self.qd_dispatch_policy_c_counts_free, None, [c_long], check=False)
+ self._prototype(self.qd_dispatch_policy_c_counts_refresh, None, [c_long, py_object])
+
self._prototype(self.qd_dispatch_set_agent, None, [self.qd_dispatch_p, py_object])
self._prototype(self.qd_router_setup_late, None, [self.qd_dispatch_p])
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/management/agent.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/agent.py b/python/qpid_dispatch_internal/management/agent.py
index 5b9a7f5..336ef86 100644
--- a/python/qpid_dispatch_internal/management/agent.py
+++ b/python/qpid_dispatch_internal/management/agent.py
@@ -81,6 +81,7 @@ from .schema import ValidationError, SchemaEntity, EntityType
from .qdrouter import QdSchema
from ..router.message import Message
from ..router.address import Address
+from ..policy.policy_manager import PolicyManager
def dictstr(d):
@@ -154,6 +155,7 @@ class EntityAdapter(SchemaEntity):
self.__dict__['_log'] = agent.log
self.__dict__['_qd'] = agent.qd
self.__dict__['_dispatch'] = agent.dispatch
+ self.__dict__['_policy'] = agent.policy
self.__dict__['_implementations'] = []
def validate(self, **kwargs):
@@ -278,6 +280,36 @@ class LogEntity(EntityAdapter):
def __str__(self):
return super(LogEntity, self).__str__().replace("Entity(", "LogEntity(")
+
+class PolicyEntity(EntityAdapter):
+ def __init__(self, agent, entity_type, attributes=None):
+ super(PolicyEntity, self).__init__(agent, entity_type, attributes, validate=False)
+ # Policy is a mix of configuration and operational entity.
+ # The statistics attributes are operational not configured.
+ self._add_implementation(
+ CImplementation(agent.qd, entity_type, self._dispatch))
+
+ def create(self):
+ self._qd.qd_dispatch_configure_policy(self._dispatch, self)
+ self._qd.qd_dispatch_register_policy_manager(self._dispatch, self._policy)
+
+ def _identifier(self):
+ return self.attributes.get('module')
+
+
+class PolicyRulesetEntity(EntityAdapter):
+ def create(self):
+ self._policy.create_ruleset(self.attributes)
+
+ def _identifier(self):
+ return self.attributes.get('applicationName')
+
+
+class PolicyStatsEntity(EntityAdapter):
+ def _identifier(self):
+ return self.attributes.get('applicationName')
+
+
def _addr_port_identifier(entity):
for attr in ['addr', 'port']: # Set default values if need be
entity.attributes.setdefault(
@@ -671,6 +703,7 @@ class Agent(object):
self.entities = EntityCache(self)
self.request_lock = Lock()
self.log_adapter = LogAdapter("AGENT")
+ self.policy = PolicyManager(self)
self.management = self.create_entity({"type": "management"})
self.add_entity(self.management)
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/management/config.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/config.py b/python/qpid_dispatch_internal/management/config.py
index 1ae8f6c..d742960 100644
--- a/python/qpid_dispatch_internal/management/config.py
+++ b/python/qpid_dispatch_internal/management/config.py
@@ -22,6 +22,7 @@ Configuration file parsing
"""
import json, re, sys
+import os
from copy import copy
from qpid_dispatch.management.entity import camelcase
@@ -31,13 +32,13 @@ from .qdrouter import QdSchema
class Config(object):
"""Load config entities from qdrouterd.conf and validated against L{QdSchema}."""
- def __init__(self, filename=None, schema=QdSchema()):
+ def __init__(self, filename=None, schema=QdSchema(), raw_json=False):
self.schema = schema
self.config_types = [et for et in schema.entity_types.itervalues()
if schema.is_configuration(et)]
if filename:
try:
- self.load(filename)
+ self.load(filename, raw_json)
except Exception, e:
raise Exception, "Cannot load configuration file %s: %s" % (filename, e), sys.exc_info()[2]
else:
@@ -71,6 +72,17 @@ class Config(object):
if s[0] == "autoLink": s[0] = "router.config.autoLink"
return sections
+ @staticmethod
+ def _parserawjson(lines):
+ """Parse raw json config file format into a section list"""
+ def sub(line):
+ """Do substitutions to make line json-friendly"""
+ line = line.split('#')[0].strip() # Strip comments
+ return line
+ js_text = "%s"%("".join([sub(l) for l in lines]))
+ sections = json.loads(js_text)
+ return sections
+
def _expand(self, content):
"""
@@ -97,16 +109,18 @@ class Config(object):
return [_expand_section(s, annotations) for s in content
if self.schema.is_configuration(self.schema.entity_type(s[0], False))]
- def load(self, source):
+ def load(self, source, raw_json=False):
"""
Load a configuration file.
@param source: A file name, open file object or iterable list of lines
+ @param raw_json: Source is pure json not needing conf-style substitutions
"""
if isinstance(source, basestring):
+ raw_json |= source.endswith(".json")
with open(source) as f:
- self.load(f)
+ self.load(f, raw_json)
else:
- sections = self._parse(source)
+ sections = self._parserawjson(source) if raw_json else self._parse(source)
# Add missing singleton sections
for et in self.config_types:
if et.singleton and not [s for s in sections if s[0] == et.short_name]:
@@ -159,9 +173,11 @@ def configure_dispatch(dispatch, lib_handle, filename):
from qpid_dispatch_internal.display_name.display_name import DisplayNameService
displayname_service = DisplayNameService("$displayname")
+ policyFolder = config.by_type('policy')[0]['policyFolder']
# Remaining configuration
for t in "fixedAddress", "listener", "connector", "waypoint", "linkRoutePattern", \
- "router.config.address", "router.config.linkRoute", "router.config.autoLink":
+ "router.config.address", "router.config.linkRoute", "router.config.autoLink", \
+ "policy", "policyRuleset":
for a in config.by_type(t):
configure(a)
if t == "listener":
@@ -173,4 +189,12 @@ def configure_dispatch(dispatch, lib_handle, filename):
for e in config.entities:
configure(e)
-
+ # Load the policyRulesets from the .json files in policyFolder
+ # Only policyRulesets are loaded. Other entities are silently discarded.
+ if not policyFolder == '':
+ apath = os.path.abspath(policyFolder)
+ for i in os.listdir(policyFolder):
+ if i.endswith(".json"):
+ pconfig = Config(os.path.join(apath, i))
+ for a in pconfig.by_type("policyRuleset"):
+ agent.configure(a)
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/management/schema.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema.py b/python/qpid_dispatch_internal/management/schema.py
index 70e9b83..794e0ad 100644
--- a/python/qpid_dispatch_internal/management/schema.py
+++ b/python/qpid_dispatch_internal/management/schema.py
@@ -155,7 +155,7 @@ BUILTIN_TYPES = OrderedDict(
Type("entityId", str),
Type("integer", int),
Type("list", list),
- Type("map", map),
+ Type("map", dict),
BooleanType()])
def get_type(rep):
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/policy/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/__init__.py b/python/qpid_dispatch_internal/policy/__init__.py
new file mode 100644
index 0000000..6417447
--- /dev/null
+++ b/python/qpid_dispatch_internal/policy/__init__.py
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Qpid Dispatch internal policy package."""
+
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/policy/policy_local.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_local.py b/python/qpid_dispatch_internal/policy/policy_local.py
new file mode 100644
index 0000000..89e5016
--- /dev/null
+++ b/python/qpid_dispatch_internal/policy/policy_local.py
@@ -0,0 +1,709 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License
+#
+
+"""
+
+"""
+
+import json
+from policy_util import PolicyError, HostStruct, HostAddr, PolicyAppConnectionMgr
+
+"""
+Entity implementing the business logic of user connection/access policy.
+"""
+
+#
+#
+class PolicyKeys(object):
+ """
+ String constants
+ """
+ # Common key words
+ KW_IGNORED_NAME = "name"
+ KW_IGNORED_IDENTITY = "identity"
+ KW_IGNORED_TYPE = "type"
+ KW_APPLICATION_NAME = "applicationName"
+
+ # Policy ruleset key words
+ KW_MAXCONN = "maxConnections"
+ KW_MAXCONNPERHOST = "maxConnPerHost"
+ KW_MAXCONNPERUSER = "maxConnPerUser"
+ KW_USER_GROUPS = "userGroups"
+ KW_INGRESS_HOST_GROUPS = "ingressHostGroups"
+ KW_INGRESS_POLICIES = "ingressPolicies"
+ KW_CONNECTION_ALLOW_DEFAULT = "connectionAllowDefault"
+ KW_SETTINGS = "settings"
+
+ # Policy settings key words
+ KW_USER_GROUP_NAME = "userGroupName"
+ KW_MAX_FRAME_SIZE = "maxFrameSize"
+ KW_MAX_MESSAGE_SIZE = "maxMessageSize"
+ KW_MAX_SESSION_WINDOW = "maxSessionWindow"
+ KW_MAX_SESSIONS = "maxSessions"
+ KW_MAX_SENDERS = "maxSenders"
+ KW_MAX_RECEIVERS = "maxReceivers"
+ KW_ALLOW_DYNAMIC_SRC = "allowDynamicSrc"
+ KW_ALLOW_ANONYMOUS_SENDER = "allowAnonymousSender"
+ KW_SOURCES = "sources"
+ KW_TARGETS = "targets"
+
+ # Policy stats key words
+ KW_CONNECTIONS_APPROVED = "connectionsApproved"
+ KW_CONNECTIONS_DENIED = "connectionsDenied"
+ KW_CONNECTIONS_CURRENT = "connectionsCurrent"
+ KW_PER_USER_STATE = "perUserState"
+ KW_PER_HOST_STATE = "perHostState"
+
+ # What settings does a user get when allowed to connect but
+ # not restricted by a user group?
+ KW_DEFAULT_SETTINGS = "default"
+
+ # Config file separator character for two IP addresses in a range
+ KC_CONFIG_IP_SEP = "-"
+
+ # Config file separator character for names in a list
+ KC_CONFIG_LIST_SEP = ","
+
+ # user-to-group computed map in compiled ruleset
+ RULESET_U2G_MAP = "U2G"
+
+ # policy stats controlled by C code but referenced by settings
+ KW_CSTATS = "denialCounts"
+#
+#
+class PolicyCompiler(object):
+ """
+ Validate incoming configuration for legal schema.
+ - Warn about section options that go unused.
+ - Disallow negative max connection numbers.
+ - Check that connectionOrigins resolve to IP hosts.
+ - Enforce internal consistency,
+ """
+
+ allowed_ruleset_options = [
+ PolicyKeys.KW_IGNORED_NAME,
+ PolicyKeys.KW_IGNORED_IDENTITY,
+ PolicyKeys.KW_IGNORED_TYPE,
+ PolicyKeys.KW_APPLICATION_NAME,
+ PolicyKeys.KW_MAXCONN,
+ PolicyKeys.KW_MAXCONNPERHOST,
+ PolicyKeys.KW_MAXCONNPERUSER,
+ PolicyKeys.KW_USER_GROUPS,
+ PolicyKeys.KW_INGRESS_HOST_GROUPS,
+ PolicyKeys.KW_INGRESS_POLICIES,
+ PolicyKeys.KW_CONNECTION_ALLOW_DEFAULT,
+ PolicyKeys.KW_SETTINGS
+ ]
+
+ allowed_settings_options = [
+ PolicyKeys.KW_MAX_FRAME_SIZE,
+ PolicyKeys.KW_MAX_MESSAGE_SIZE,
+ PolicyKeys.KW_MAX_SESSION_WINDOW,
+ PolicyKeys.KW_MAX_SESSIONS,
+ PolicyKeys.KW_MAX_SENDERS,
+ PolicyKeys.KW_MAX_RECEIVERS,
+ PolicyKeys.KW_ALLOW_DYNAMIC_SRC,
+ PolicyKeys.KW_ALLOW_ANONYMOUS_SENDER,
+ PolicyKeys.KW_SOURCES,
+ PolicyKeys.KW_TARGETS
+ ]
+
+ def __init__(self):
+ """
+ Create a validator
+ """
+ pass
+
+
+ def validateNumber(self, val, v_min, v_max, errors):
+ """
+ Range check a numeric int policy value
+ @param[in] val policy value to check
+ @param[in] v_min minumum value
+ @param[in] v_max maximum value. zero disables check
+ @param[out] errors failure message
+ @return v_min <= val <= v_max
+ """
+ try:
+ v_int = int(val)
+ except Exception, e:
+ errors.append("Value '%s' does not resolve to an integer." % val)
+ return False
+ if v_int < v_min:
+ errors.append("Value '%s' is below minimum '%s'." % (val, v_min))
+ return False
+ if v_max > 0 and v_int > v_max:
+ errors.append("Value '%s' is above maximum '%s'." % (val, v_max))
+ return False
+ return True
+
+
+ def compile_connection_groups(self, name, submap_in, submap_out, warnings, errors):
+ """
+ Handle an ingressHostGroups submap.
+ Each origin value is verified. On a successful run the submap
+ is replaced parsed lists of HostAddr objects.
+ @param[in] name application name
+ @param[in] submap_in user input origin list as text strings
+ @param[out] submap_out user inputs replaced with HostAddr objects
+ @param[out] warnings nonfatal irregularities observed
+ @param[out] errors descriptions of failure
+ @return - origins is usable. If True then warnings[] may contain useful
+ information about fields that are ignored. If False then
+ warnings[] may contain info and errors[0] will hold the
+ description of why the origin was rejected.
+ """
+ key = PolicyKeys.KW_INGRESS_HOST_GROUPS
+ for coname in submap_in:
+ try:
+ ostr = str(submap_in[coname])
+ olist = [x.strip(' ') for x in ostr.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+ submap_out[coname] = []
+ for co in olist:
+ coha = HostAddr(co, PolicyKeys.KC_CONFIG_IP_SEP)
+ submap_out[coname].append(coha)
+ except Exception, e:
+ errors.append("Application '%s' option '%s' connectionOption '%s' failed to translate: '%s'." %
+ (name, key, coname, e))
+ return False
+ return True
+
+
+ def compile_app_settings(self, appname, usergroup, policy_in, policy_out, warnings, errors):
+ """
+ Compile a schema from processed json format to local internal format.
+ @param[in] name application name
+ @param[in] policy_in user config settings
+ @param[out] policy_out validated Internal format
+ @param[out] warnings nonfatal irregularities observed
+ @param[out] errors descriptions of failure
+ @return - settings are usable. If True then warnings[] may contain useful
+ information about fields that are ignored. If False then
+ warnings[] may contain info and errors[0] will hold the
+ description of why the policy was rejected.
+ """
+ # rulesets may not come through standard config so make nice defaults
+ policy_out[PolicyKeys.KW_MAX_FRAME_SIZE] = 65536
+ policy_out[PolicyKeys.KW_MAX_MESSAGE_SIZE] = 0
+ policy_out[PolicyKeys.KW_MAX_SESSION_WINDOW] = 2147483647
+ policy_out[PolicyKeys.KW_MAX_SESSIONS] = 10
+ policy_out[PolicyKeys.KW_MAX_SENDERS] = 10
+ policy_out[PolicyKeys.KW_MAX_RECEIVERS] = 10
+ policy_out[PolicyKeys.KW_ALLOW_DYNAMIC_SRC] = False
+ policy_out[PolicyKeys.KW_ALLOW_ANONYMOUS_SENDER] = False
+ policy_out[PolicyKeys.KW_SOURCES] = ''
+ policy_out[PolicyKeys.KW_TARGETS] = ''
+
+ cerror = []
+ for key, val in policy_in.iteritems():
+ if key not in self.allowed_settings_options:
+ warnings.append("Application '%s' user group '%s' option '%s' is ignored." %
+ (appname, usergroup, key))
+ if key in [PolicyKeys.KW_MAX_FRAME_SIZE,
+ PolicyKeys.KW_MAX_MESSAGE_SIZE,
+ PolicyKeys.KW_MAX_RECEIVERS,
+ PolicyKeys.KW_MAX_SENDERS,
+ PolicyKeys.KW_MAX_SESSION_WINDOW,
+ PolicyKeys.KW_MAX_SESSIONS
+ ]:
+ if not self.validateNumber(val, 0, 0, cerror):
+ errors.append("Application '%s' user group '%s' option '%s' has error '%s'." %
+ (appname, usergroup, key, cerror[0]))
+ return False
+ policy_out[key] = val
+ elif key in [PolicyKeys.KW_ALLOW_ANONYMOUS_SENDER,
+ PolicyKeys.KW_ALLOW_DYNAMIC_SRC
+ ]:
+ if not type(val) is bool:
+ errors.append("Application '%s' user group '%s' option '%s' has illegal boolean value '%s'." %
+ (appname, usergroup, key, val))
+ return False
+ policy_out[key] = val
+ elif key in [PolicyKeys.KW_SOURCES,
+ PolicyKeys.KW_TARGETS
+ ]:
+ # accept a string or list
+ if type(val) is str:
+ # 'abc, def, mytarget'
+ val = [x.strip(' ') for x in val.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+ elif type(val) is list:
+ # ['abc', 'def', 'mytarget']
+ pass
+ elif type(val) is unicode:
+ # u'abc, def, mytarget'
+ val = [x.strip(' ') for x in str(val).split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+ else:
+ errors.append("Application '%s' user group '%s' option '%s' has illegal value '%s'. Type must be 'str' or 'list' but is '%s;" %
+ (appname, usergroup, key, val, type(val)))
+ # deduplicate address lists
+ val = list(set(val))
+ # output result is CSV string with no white space between values: 'abc,def,mytarget'
+ policy_out[key] = ','.join(val)
+ return True
+
+
+ def compile_access_ruleset(self, name, policy_in, policy_out, warnings, errors):
+ """
+ Compile a schema from processed json format to local internal format.
+ @param[in] name application name
+ @param[in] policy_in raw policy to be validated
+ @param[out] policy_out validated Internal format
+ @param[out] warnings nonfatal irregularities observed
+ @param[out] errors descriptions of failure
+ @return - policy is usable. If True then warnings[] may contain useful
+ information about fields that are ignored. If False then
+ warnings[] may contain info and errors[0] will hold the
+ description of why the policy was rejected.
+ """
+ cerror = []
+ # rulesets may not come through standard config so make nice defaults
+ policy_out[PolicyKeys.KW_MAXCONN] = 0
+ policy_out[PolicyKeys.KW_MAXCONNPERHOST] = 0
+ policy_out[PolicyKeys.KW_MAXCONNPERUSER] = 0
+ policy_out[PolicyKeys.KW_USER_GROUPS] = {}
+ policy_out[PolicyKeys.KW_INGRESS_HOST_GROUPS] = {}
+ policy_out[PolicyKeys.KW_INGRESS_POLICIES] = {}
+ policy_out[PolicyKeys.KW_CONNECTION_ALLOW_DEFAULT] = False
+ policy_out[PolicyKeys.KW_SETTINGS] = {}
+
+ # validate the options
+ for key, val in policy_in.iteritems():
+ if key not in self.allowed_ruleset_options:
+ warnings.append("Application '%s' option '%s' is ignored." %
+ (name, key))
+ if key in [PolicyKeys.KW_MAXCONN,
+ PolicyKeys.KW_MAXCONNPERHOST,
+ PolicyKeys.KW_MAXCONNPERUSER
+ ]:
+ if not self.validateNumber(val, 0, 65535, cerror):
+ msg = ("Application '%s' option '%s' has error '%s'." %
+ (name, key, cerror[0]))
+ errors.append(msg)
+ return False
+ policy_out[key] = val
+ elif key in [PolicyKeys.KW_USER_GROUPS,
+ PolicyKeys.KW_INGRESS_HOST_GROUPS,
+ PolicyKeys.KW_INGRESS_POLICIES
+ ]:
+ try:
+ if not type(val) is dict:
+ errors.append("Application '%s' option '%s' must be of type 'dict' but is '%s'" %
+ (name, key, type(val)))
+ return False
+ if key == PolicyKeys.KW_INGRESS_HOST_GROUPS:
+ # Conection groups are lists of IP addresses that need to be
+ # converted into binary structures for comparisons.
+ val_out = {}
+ if not self.compile_connection_groups(name, val, val_out, warnings, errors):
+ return False
+ policy_out[key] = {}
+ policy_out[key].update(val_out)
+ else:
+ # deduplicate ingressPolicy and userGroups lists
+ for k,v in val.iteritems():
+ v = [x.strip(' ') for x in v.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+ v = list(set(v))
+ val[k] = v
+ policy_out[key] = val
+ except Exception, e:
+ errors.append("Application '%s' option '%s' error processing map: %s" %
+ (name, key, e))
+ return False
+ elif key in [PolicyKeys.KW_CONNECTION_ALLOW_DEFAULT]:
+ if not type(val) is bool:
+ errors.append("Application '%s' option '%s' must be of type 'bool' but is '%s'" %
+ (name, key, type(val)))
+ return False
+ policy_out[key] = val
+ elif key in [PolicyKeys.KW_SETTINGS]:
+ if not type(val) is dict:
+ errors.append("Application '%s' option '%s' must be of type 'dict' but is '%s'" %
+ (name, key, type(val)))
+ return False
+ for skey, sval in val.iteritems():
+ newsettings = {}
+ if not self.compile_app_settings(name, skey, sval, newsettings, warnings, errors):
+ return False
+ policy_out[key][skey] = {}
+ policy_out[key][skey].update(newsettings)
+
+ # Verify that each user is in only one group.
+ # Verify that each user group has defined settings
+ # Create user-to-group map for looking up user's group
+ policy_out[PolicyKeys.RULESET_U2G_MAP] = {}
+ if PolicyKeys.KW_USER_GROUPS in policy_out:
+ for group, userlist in policy_out[PolicyKeys.KW_USER_GROUPS].iteritems():
+ for user in userlist:
+ if user in policy_out[PolicyKeys.RULESET_U2G_MAP]:
+ errors.append("Application '%s' user '%s' is in multiple user groups '%s' and '%s'" %
+ (name, user, policy_out[PolicyKeys.RULESET_U2G_MAP][user], group))
+ return False
+ else:
+ policy_out[PolicyKeys.RULESET_U2G_MAP][user] = group
+ if not group in policy_out[PolicyKeys.KW_SETTINGS]:
+ errors.append("Application '%s' user group '%s' has no defined settings" %
+ (name, group))
+ return False
+
+ # Default connections require a default settings
+ if policy_out[PolicyKeys.KW_CONNECTION_ALLOW_DEFAULT]:
+ if not PolicyKeys.KW_DEFAULT_SETTINGS in policy_out[PolicyKeys.KW_SETTINGS]:
+ errors.append("Application '%s' allows connections by default but default settings are not defined" %
+ (name))
+ return False
+
+ # Each ingress policy name reference must exist in ingressHostGroups
+ for cipname, cip in policy_out[PolicyKeys.KW_INGRESS_POLICIES].iteritems():
+ for co in cip:
+ if not co in policy_out[PolicyKeys.KW_INGRESS_HOST_GROUPS]:
+ errors.append("Application '%s' connection ingress policy '%s' references ingress host group '%s' but that group does not exist"
+ (name, cipname, co))
+ return False
+
+ return True
+
+
+#
+#
+class AppStats(object):
+ """
+ Maintain live state and statistics for an application.
+ """
+ def __init__(self, id, manager, ruleset):
+ self.my_id = id
+ self._manager = manager
+ self.conn_mgr = PolicyAppConnectionMgr(
+ ruleset[PolicyKeys.KW_MAXCONN],
+ ruleset[PolicyKeys.KW_MAXCONNPERHOST],
+ ruleset[PolicyKeys.KW_MAXCONNPERUSER])
+ self._cstats = self._manager.get_agent().qd.qd_dispatch_policy_c_counts_alloc()
+ self._manager.get_agent().add_implementation(self, "policyStats")
+
+ def update_ruleset(self, ruleset):
+ """
+ The parent ruleset has changed.
+ Propagate settings into the connection manager.
+ @param ruleset: new ruleset
+ @return:
+ """
+ self.conn_mgr.update(
+ ruleset[PolicyKeys.KW_MAXCONN],
+ ruleset[PolicyKeys.KW_MAXCONNPERHOST],
+ ruleset[PolicyKeys.KW_MAXCONNPERUSER])
+
+ def refresh_entity(self, attributes):
+ """Refresh management attributes"""
+ entitymap = {}
+ entitymap[PolicyKeys.KW_APPLICATION_NAME] = self.my_id
+ entitymap[PolicyKeys.KW_CONNECTIONS_APPROVED] = self.conn_mgr.connections_approved
+ entitymap[PolicyKeys.KW_CONNECTIONS_DENIED] = self.conn_mgr.connections_denied
+ entitymap[PolicyKeys.KW_CONNECTIONS_CURRENT] = self.conn_mgr.connections_active
+ entitymap[PolicyKeys.KW_PER_USER_STATE] = self.conn_mgr.per_user_state
+ entitymap[PolicyKeys.KW_PER_HOST_STATE] = self.conn_mgr.per_host_state
+ self._manager.get_agent().qd.qd_dispatch_policy_c_counts_refresh(self._cstats, entitymap)
+ attributes.update(entitymap)
+
+ def can_connect(self, conn_id, user, host, diags):
+ return self.conn_mgr.can_connect(conn_id, user, host, diags)
+
+ def disconnect(self, conn_id, user, host):
+ self.conn_mgr.disconnect(conn_id, user, host)
+
+ def count_other_denial(self):
+ self.conn_mgr.count_other_denial()
+
+ def get_cstats(self):
+ return self._cstats
+
+#
+#
+class ConnectionFacts:
+ def __init__(self, user, host, app, conn_name):
+ self.user = user
+ self.host = host
+ self.app = app
+ self.conn_name = conn_name
+
+#
+#
+class PolicyLocal(object):
+ """
+ The local policy database.
+ """
+
+ def __init__(self, manager):
+ """
+ Create instance
+ @params manager policy manager class
+ """
+ # manager is a class
+ # It provides access the dispatch system functions
+ self._manager = manager
+
+ # rulesetdb is a map
+ # key : application name
+ # val : ruleset for this app
+ # created by configuration
+ # augmented by policy compiler
+ self.rulesetdb = {}
+
+ # settingsdb is a map
+ # key : <application name>
+ # val : a map
+ # key : <user group name>
+ # val : settings to use for user's connection
+ # created by configuration
+ self.settingsdb = {}
+
+ # statsdb is a map
+ # key : <application name>
+ # val : AppStats object
+ self.statsdb = {}
+
+ # _policy_compiler is a function
+ # validates incoming policy and readies it for internal use
+ self._policy_compiler = PolicyCompiler()
+
+ # _connections is a map
+ # key : numeric connection id
+ # val : ConnectionFacts
+ # Entries created as connection AMQP Opens arrive
+ # Entries destroyed as sockets closed
+ self._connections = {}
+ #
+ # Service interfaces
+ #
+ def create_ruleset(self, attributes):
+ """
+ Create named policy ruleset
+ @param[in] attributes: from config
+ """
+ warnings = []
+ diag = []
+ candidate = {}
+ name = attributes[PolicyKeys.KW_APPLICATION_NAME]
+ result = self._policy_compiler.compile_access_ruleset(name, attributes, candidate, warnings, diag)
+ if not result:
+ raise PolicyError( "Policy '%s' is invalid: %s" % (name, diag[0]) )
+ if len(warnings) > 0:
+ for warning in warnings:
+ self._manager.log_warning(warning)
+ if name not in self.rulesetdb:
+ self.statsdb[name] = AppStats(name, self._manager, candidate)
+ self._manager.log_info("Created policy rules for application %s" % name)
+ else:
+ self.statsdb[name].update_ruleset(candidate)
+ self._manager.log_info("Updated policy rules for application %s" % name)
+ self.rulesetdb[name] = {}
+ self.rulesetdb[name].update(candidate)
+
+ def policy_read(self, name):
+ """
+ Read policy for named application
+ @param[in] name application name
+ @return policy data in raw user format
+ """
+ return self.rulesetdb[name]
+
+ def policy_update(self, name, policy):
+ """
+ Update named policy
+ @param[in] name application name
+ @param[in] policy data in raw user input
+ """
+ if not name in self.rulesetdb:
+ raise PolicyError("Policy '%s' does not exist" % name)
+ self.policy_create(name, policy)
+
+ def policy_delete(self, name):
+ """
+ Delete named policy
+ @param[in] name application name
+ """
+ if not name in self.rulesetdb:
+ raise PolicyError("Policy '%s' does not exist" % name)
+ del self.rulesetdb[name]
+
+ #
+ # db enumerator
+ #
+ def policy_db_get_names(self):
+ """
+ Return a list of application names in this policy
+ """
+ return self.rulesetdb.keys()
+
+
+ #
+ # Runtime query interface
+ #
+ def lookup_user(self, user, host, app, conn_name, conn_id):
+ """
+ Lookup function called from C.
+ Determine if a user on host accessing app through AMQP Open is allowed
+ according to the policy access rules.
+ If allowed then return the policy settings name. If stats.can_connect
+ returns true then it has registered and counted the connection.
+ @param[in] user connection authId
+ @param[in] host connection remote host numeric IP address as string
+ @param[in] app application user is accessing
+ @param[in] conn_name connection name used for tracking reports
+ @param[in] conn_id internal connection id
+ @return settings user-group name if allowed; "" if not allowed
+ """
+ try:
+ if not app in self.rulesetdb:
+ self._manager.log_trace(
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "No policy defined for application" % (user, host, app))
+ return ""
+
+ ruleset = self.rulesetdb[app]
+ if not app in self.statsdb:
+ msg = (
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "Policy is defined but stats are missing" % (user, host, app))
+ raise PolicyError(msg)
+ stats = self.statsdb[app]
+ # User in a group or default?
+ if user in ruleset[PolicyKeys.RULESET_U2G_MAP]:
+ usergroup = ruleset[PolicyKeys.RULESET_U2G_MAP][user]
+ else:
+ if ruleset[PolicyKeys.KW_CONNECTION_ALLOW_DEFAULT]:
+ usergroup = PolicyKeys.KW_DEFAULT_SETTINGS
+ else:
+ self._manager.log_trace(
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "User must be in a user group" % (user, host, app))
+ stats.count_other_denial()
+ return ""
+ # User in usergroup allowed to connect from host?
+ if usergroup in ruleset[PolicyKeys.KW_INGRESS_POLICIES]:
+ # User's usergroup is restricted to connecting from a host
+ # defined by the group's ingress policy
+ allowed = False
+ uhs = HostStruct(host)
+ cglist = ruleset[PolicyKeys.KW_INGRESS_POLICIES][usergroup]
+ for cg in cglist:
+ for cohost in ruleset[PolicyKeys.KW_INGRESS_HOST_GROUPS][cg]:
+ if cohost.match_bin(uhs):
+ allowed = True
+ break
+ if allowed:
+ break
+ else:
+ # User's usergroup has no ingress policy so allow
+ allowed = True
+ if not allowed:
+ self._manager.log_trace(
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "User is not allowed to connect from this host" % (user, host, app))
+ stats.count_other_denial()
+ return ""
+
+ # This user passes administrative approval.
+ # Now check live connection counts
+ diags = []
+ if not stats.can_connect(conn_name, user, host, diags):
+ for diag in diags:
+ self._manager.log_trace(
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "%s" % (user, host, app, diag))
+ return ""
+
+ # Record facts about this connection to use during teardown
+ facts = ConnectionFacts(user, host, app, conn_name)
+ self._connections[conn_id] = facts
+
+ # Return success
+ return usergroup
+
+ except Exception, e:
+ self._manager.log_error(
+ "lookup_user failed for user '%s', host '%s', application '%s': "
+ "Internal error: %s" % (user, host, app, e))
+ # return failure
+ return ""
+
+ def lookup_settings(self, appname, name, upolicy):
+ """
+ Given a settings name, return the aggregated policy blob.
+ @param[in] appname: application user is accessing
+ @param[in] name: user group name
+ @param[out] upolicy: dict holding policy values - the settings blob
+ TODO: make this a c struct
+ @return if lookup worked
+ # Note: the upolicy output is a non-nested dict with settings of interest
+ """
+ try:
+ if not appname in self.rulesetdb:
+ self._manager.log_trace(
+ "lookup_settings fail for application '%s', user group '%s': "
+ "No policy defined for this application" % (appname, name))
+ return False
+
+ ruleset = self.rulesetdb[appname]
+
+ if not name in ruleset[PolicyKeys.KW_SETTINGS]:
+ self._manager.log_trace(
+ "lookup_settings fail for application '%s', user group '%s': "
+ "This application has no settings for the user group" % (appname, name))
+ return False
+
+ upolicy.update(ruleset[PolicyKeys.KW_SETTINGS][name])
+ upolicy[PolicyKeys.KW_CSTATS] = self.statsdb[appname].get_cstats()
+ return True
+ except Exception, e:
+ return False
+
+ def close_connection(self, conn_id):
+ """
+ Close the connection.
+ @param conn_id:
+ @return:
+ """
+ try:
+ facts = self._connections[conn_id]
+ stats = self.statsdb[facts.app]
+ stats.disconnect(facts.conn_name, facts.user, facts.host)
+ del self._connections[conn_id]
+ except Exception, e:
+ self._manager.log_trace(
+ "Policy internal error closing connection id %s. %s" % (conn_id, str(e)))
+
+ #
+ #
+ def test_load_config(self):
+ """
+ Test function to load a policy.
+ @return:
+ """
+ ruleset_str = '["policyAccessRuleset", {"applicationName": "photoserver","maxConnections": 50,"maxConnPerUser": 5,"maxConnPerHost": 20,"userGroups": {"anonymous": "anonymous","users": "u1, u2","paidsubscribers": "p1, p2","test": "zeke, ynot","admin": "alice, bob","superuser": "ellen"},"ingressHostGroups": {"Ten18": "10.18.0.0-10.18.255.255","EllensWS": "72.135.2.9","TheLabs": "10.48.0.0-10.48.255.255, 192.168.100.0-192.168.100.255","localhost": "127.0.0.1, ::1","TheWorld": "*"},"ingressPolicies": {"anonymous": "TheWorld","users": "TheWorld","paidsubscribers": "TheWorld","test": "TheLabs","admin": "Ten18, TheLabs, localhost","superuser": "EllensWS, localhost"},"connectionAllowDefault": true,'
+ ruleset_str += '"settings": {'
+ ruleset_str += '"anonymous": {"maxFrameSize": 111111,"maxMessageSize": 111111,"maxSessionWindow": 111111,"maxSessions": 1,"maxSenders": 11,"maxReceivers": 11,"allowDynamicSrc": false,"allowAnonymousSender": false,"sources": "public", "targets": ""},'
+ ruleset_str += '"users": {"maxFrameSize": 222222,"maxMessageSize": 222222,"maxSessionWindow": 222222,"maxSessions": 2,"maxSenders": 22,"maxReceivers": 22,"allowDynamicSrc": false,"allowAnonymousSender": false,"sources": "public, private", "targets": "public"},'
+ ruleset_str += '"paidsubscribers":{"maxFrameSize": 333333,"maxMessageSize": 333333,"maxSessionWindow": 333333,"maxSessions": 3,"maxSenders": 33,"maxReceivers": 33,"allowDynamicSrc": true, "allowAnonymousSender": false,"sources": "public, private", "targets": "public, private"},'
+ ruleset_str += '"test": {"maxFrameSize": 444444,"maxMessageSize": 444444,"maxSessionWindow": 444444,"maxSessions": 4,"maxSenders": 44,"maxReceivers": 44,"allowDynamicSrc": true, "allowAnonymousSender": true, "sources": "private", "targets": "private"},'
+ ruleset_str += '"admin": {"maxFrameSize": 555555,"maxMessageSize": 555555,"maxSessionWindow": 555555,"maxSessions": 5,"maxSenders": 55,"maxReceivers": 55,"allowDynamicSrc": true, "allowAnonymousSender": true, "sources": "public, private, management", "targets": "public, private, management"},'
+ ruleset_str += '"superuser": {"maxFrameSize": 666666,"maxMessageSize": 666666,"maxSessionWindow": 666666,"maxSessions": 6,"maxSenders": 66,"maxReceivers": 66,"allowDynamicSrc": false,"allowAnonymousSender": false,"sources": "public, private, management, root","targets": "public, private, management, root"},'
+ ruleset_str += '"default": {"maxFrameSize": 222222,"maxMessageSize": 222222,"maxSessionWindow": 222222,"maxSessions": 2,"maxSenders": 22,"maxReceivers": 22,"allowDynamicSrc": false,"allowAnonymousSender": false,"sources": "public, private", "targets": "public"}'
+ ruleset_str += '}}]'
+ ruleset = json.loads(ruleset_str)
+
+ self.create_ruleset(ruleset[1])
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/policy/policy_manager.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_manager.py b/python/qpid_dispatch_internal/policy/policy_manager.py
new file mode 100644
index 0000000..a2823c8
--- /dev/null
+++ b/python/qpid_dispatch_internal/policy/policy_manager.py
@@ -0,0 +1,157 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License
+#
+
+"""
+
+"""
+
+import json
+import traceback
+from policy_local import PolicyLocal
+from ..dispatch import LogAdapter, LOG_INFO, LOG_TRACE, LOG_DEBUG, LOG_ERROR
+
+
+
+"""
+Entity implementing the glue between the policy engine and the rest of the system.
+"""
+
+class PolicyManager(object):
+ """
+
+ """
+
+ def __init__(self, agent):
+ """
+ """
+ self._agent = agent
+ self._policy_local = PolicyLocal(self)
+ self.log_adapter = LogAdapter("POLICY")
+
+ def log(self, level, text):
+ info = traceback.extract_stack(limit=2)[0] # Caller frame info
+ self.log_adapter.log(level, text, info[0], info[1])
+
+ def _log(self, level, text):
+ info = traceback.extract_stack(limit=3)[0] # Caller's caller frame info
+ self.log_adapter.log(level, text, info[0], info[1])
+
+ def log_debug(self, text):
+ self._log(LOG_DEBUG, text)
+
+ def log_info(self, text):
+ self._log(LOG_INFO, text)
+
+ def log_trace(self, text):
+ self._log(LOG_TRACE, text)
+
+ def log_error(self, text):
+ self._log(LOG_ERROR, text)
+
+ def get_agent(self):
+ return self._agent
+
+ #
+ # Management interface to create a ruleset
+ #
+ def create_ruleset(self, attributes):
+ """
+ Create named policy ruleset
+ @param[in] attributes: from config
+ """
+ self._policy_local.create_ruleset(attributes)
+
+ #
+ # Runtime query interface
+ #
+ def lookup_user(self, user, host, app, conn_name, conn_id):
+ """
+ Lookup function called from C.
+ Determine if a user on host accessing app through AMQP Open is allowed
+ according to the policy access rules.
+ If allowed then return the policy settings name
+ @param[in] user connection authId
+ @param[in] host connection remote host numeric IP address as string
+ @param[in] app application user is accessing
+ @param[in] conn_name connection name for accounting purposes
+ @param[in] conn_id internal connection id
+ @return settings user-group name if allowed; "" if not allowed
+ """
+ return self._policy_local.lookup_user(user, host, app, conn_name, conn_id)
+
+ def lookup_settings(self, appname, name, upolicy):
+ """
+ Given a settings name, return the aggregated policy blob.
+ @param[in] appname: application user is accessing
+ @param[in] name: user group name
+ @param[out] upolicy: map that receives the settings
+ @return settings were retrieved or not
+ """
+ return self._policy_local.lookup_settings(appname, name, upolicy)
+
+ def close_connection(self, conn_id):
+ """
+ The connection identifed is closing. Remove it from the connection
+ accounting tables.
+ @param facts:
+ @return: none
+ """
+ self._policy_local.close_connection(conn_id)
+#
+#
+#
+def policy_lookup_user(mgr, user, host, app, conn_name, conn_id):
+ """
+ Look up a user in the policy database
+ Called by C code
+ @param mgr:
+ @param user:
+ @param host:
+ @param app:
+ @param conn_name:
+ @return:
+ """
+ return mgr.lookup_user(user, host, app, conn_name, conn_id)
+
+#
+#
+#
+def policy_close_connection(mgr, conn_id):
+ """
+ Close the connection.
+ Called by C code
+ @param mgr:
+ @param conn_id:
+ @return:
+ """
+ mgr.close_connection(conn_id)
+
+#
+#
+#
+def policy_lookup_settings(mgr, appname, name, upolicy):
+ """
+ Return settings for <app, usergroup> in upolicy map
+ @param mgr:
+ @param appname:
+ @param name:
+ @param upolicy:
+ @return:
+ """
+ return mgr.lookup_settings(appname, name, upolicy)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/python/qpid_dispatch_internal/policy/policy_util.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_util.py b/python/qpid_dispatch_internal/policy/policy_util.py
new file mode 100644
index 0000000..71a42be
--- /dev/null
+++ b/python/qpid_dispatch_internal/policy/policy_util.py
@@ -0,0 +1,338 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License
+#
+
+import sys, os
+import socket
+import binascii
+
+
+#
+#
+class PolicyError(Exception):
+ def __init__(self, value):
+ self.value = value
+ def __str__(self):
+ return repr(self.value)
+
+#
+#
+class HostStruct(object):
+ """
+ HostStruct represents a single, binary socket address from getaddrinfo
+ - name : name given to constructor; numeric IP or host name
+ - saddr : net name resolved by getaddrinfo; numeric IP
+ - family : saddr.family; int
+ - binary : saddr packed binary address; binary string
+ """
+ families = [socket.AF_INET]
+ famnames = ["IPv4"]
+ if socket.has_ipv6:
+ families.append(socket.AF_INET6)
+ famnames.append("IPv6")
+
+ def __init__(self, hostname):
+ """
+ Given a host name text string, return the socket info for it.
+ @param[in] hostname host IP address to parse
+ """
+ try:
+ res = socket.getaddrinfo(hostname, 0)
+ if len(res) == 0:
+ raise PolicyError("HostStruct: '%s' did not resolve to an IP address" % hostname)
+ foundFirst = False
+ saddr = ""
+ sfamily = socket.AF_UNSPEC
+ for i0 in range(0, len(res)):
+ family, dum0, dum1, dum2, sockaddr = res[i0]
+ if not foundFirst:
+ if family in self.families:
+ saddr = sockaddr[0]
+ sfamily = family
+ foundFirst = True
+ else:
+ if family in self.families:
+ if not saddr == sockaddr[0] or not sfamily == family:
+ raise PolicyError("HostStruct: '%s' resolves to multiple IP addresses" %
+ hostname)
+
+ if not foundFirst:
+ raise PolicyError("HostStruct: '%s' did not resolve to one of the supported address family" %
+ hostname)
+ self.name = hostname
+ self.saddr = saddr
+ self.family = sfamily
+ self.binary = socket.inet_pton(family, saddr)
+ return
+ except Exception, e:
+ raise PolicyError("HostStruct: '%s' failed to resolve: '%s'" %
+ (hostname, e))
+
+ def __str__(self):
+ return self.name
+
+ def __repr__(self):
+ return self.__str__()
+
+ def dump(self):
+ return ("(%s, %s, %s, %s)" %
+ (self.name,
+ self.saddr,
+ "AF_INET" if self.family == socket.AF_INET else "AF_INET6",
+ binascii.hexlify(self.binary)))
+
+#
+#
+class HostAddr(object):
+ """
+ Provide HostIP address ranges and comparison functions.
+ A HostIP may be:
+ - single address: 10.10.1.1
+ - a pair of addresses: 10.10.0.0,10.10.255.255
+ - a wildcard: *
+ Only IPv4 and IPv6 are supported.
+ - No unix sockets.
+ HostIP names must resolve to a single IP address.
+ Address pairs define a range.
+ - The second address must be numerically larger than the first address.
+ - The addresses must be of the same address 'family', IPv4 or IPv6.
+ The wildcard '*' matches all address IPv4 or IPv6.
+ IPv6 support is conditional based on underlying OS network options.
+ Raises a PolicyError on validation error in constructor.
+ """
+
+ def has_ipv6(self):
+ return socket.has_ipv6
+
+ def __init__(self, hostspec, separator=","):
+ """
+ Parse host spec into binary structures to use for comparisons.
+ Validate the hostspec to enforce usage rules.
+ """
+ self.hoststructs = []
+
+ if hostspec == "*":
+ self.wildcard = True
+ else:
+ self.wildcard = False
+
+ hosts = [x.strip() for x in hostspec.split(separator)]
+
+ # hosts must contain one or two host specs
+ if len(hosts) not in [1, 2]:
+ raise PolicyError("hostspec must contain 1 or 2 host names")
+ self.hoststructs.append(HostStruct(hosts[0]))
+ if len(hosts) > 1:
+ self.hoststructs.append(HostStruct(hosts[1]))
+ if not self.hoststructs[0].family == self.hoststructs[1].family:
+ raise PolicyError("mixed IPv4 and IPv6 host specs in range not allowed")
+ c0 = self.memcmp(self.hoststructs[0].binary, self.hoststructs[1].binary)
+ if c0 > 0:
+ raise PolicyError("host specs in range must have lower numeric address first")
+
+ def __str__(self):
+ if self.wildcard:
+ return "*"
+ res = self.hoststructs[0].name
+ if len(self.hoststructs) > 1:
+ res += "," + self.hoststructs[1].name
+ return res
+
+ def __repr__(self):
+ return self.__str__()
+
+ def dump(self):
+ if self.wildcard:
+ return "(*)"
+ res = "(" + self.hoststructs[0].dump()
+ if len(self.hoststructs) > 1:
+ res += "," + self.hoststructs[1].dump()
+ res += ")"
+ return res
+
+ def memcmp(self, a, b):
+ res = 0
+ for i in range(0,len(a)):
+ if a[i] > b[i]:
+ res = 1
+ break;
+ elif a[i] < b[i]:
+ res = -1
+ break
+ return res
+
+ def match_bin(self, candidate):
+ """
+ Does the candidate hoststruct match the IP or range of IP addresses represented by this?
+ @param[in] candidate the IP address to be tested
+ @return candidate matches this or not
+ """
+ if self.wildcard:
+ return True
+ try:
+ if not candidate.family == self.hoststructs[0].family:
+ # sorry, wrong AF_INET family
+ return False
+ c0 = self.memcmp(candidate.binary, self.hoststructs[0].binary)
+ if len(self.hoststructs) == 1:
+ return c0 == 0
+ c1 = self.memcmp(candidate.binary, self.hoststructs[1].binary)
+ return c0 >= 0 and c1 <= 0
+ except PolicyError:
+ return False
+ except Exception, e:
+ assert isinstance(candidate, HostStruct), \
+ ("Wrong type. Expected HostStruct but received %s" % candidate.__class__.__name__)
+ return False
+
+ def match_str(self, candidate):
+ """
+ Does the candidate string match the IP or range represented by this?
+ @param[in] candidate the IP address to be tested
+ @return candidate matches this or not
+ """
+ try:
+ hoststruct = HostStruct(candidate)
+ except PolicyError:
+ return False
+ return self.match_bin(hoststruct)
+
+#
+#
+class PolicyAppConnectionMgr(object):
+ """
+ Track policy user/host connection limits and statistics for one app.
+ # limits - set at creation and by update()
+ max_total : 20
+ max_per_user : 5
+ max_per_host : 10
+ # statistics - maintained for the lifetime of corresponding application
+ connections_approved : N
+ connections_denied : N
+ # live state - maintained for the lifetime of corresponding application
+ connections_active : 5
+ per_host_state : { 'host1' : [conn1, conn2, conn3],
+ 'host2' : [conn4, conn5] }
+ per_user_state : { 'user1' : [conn1, conn2, conn3],
+ 'user2' : [conn4, conn5] }
+ """
+ def __init__(self, maxconn, maxconnperuser, maxconnperhost):
+ """
+ The object is constructed with the policy limits and zeroed counts.
+ @param[in] maxconn maximum total concurrent connections
+ @param[in] maxconnperuser maximum total conncurrent connections for each user
+ @param[in] maxconnperuser maximum total conncurrent connections for each host
+ """
+ if maxconn < 0 or maxconnperuser < 0 or maxconnperhost < 0:
+ raise PolicyError("PolicyAppConnectionMgr settings must be >= 0")
+ self.max_total = maxconn
+ self.max_per_user = maxconnperuser
+ self.max_per_host = maxconnperhost
+ self.connections_approved = 0
+ self.connections_denied = 0
+ self.connections_active = 0
+ self.per_host_state = {}
+ self.per_user_state = {}
+
+ def __str__(self):
+ res = ("Connection Limits: total: %s, per user: %s, per host: %s\n" %
+ (self.max_total, self.max_per_user, self.max_per_host))
+ res += ("Connections Statistics: total approved: %s, total denied: %s" %
+ (self.connections_approved, self.connections_denied))
+ res += ("Connection State: total current: %s" % self.connections_active)
+ res += ("User state: %s\n" % self.per_user_state)
+ res += ("Host state: %s" % self.per_host_state)
+ return res
+
+ def __repr__(self):
+ return self.__str__()
+
+ def update(self, maxconn, maxconnperuser, maxconnperhost):
+ """
+ Reset connection limits
+ @param[in] maxconn maximum total concurrent connections
+ @param[in] maxconnperuser maximum total conncurrent connections for each user
+ @param[in] maxconnperuser maximum total conncurrent connections for each host
+ """
+ if maxconn < 0 or maxconnperuser < 0 or maxconnperhost < 0:
+ raise PolicyError("PolicyAppConnectionMgr settings must be >= 0")
+ self.max_total = maxconn
+ self.max_per_user = maxconnperuser
+ self.max_per_host = maxconnperhost
+
+ def can_connect(self, conn_id, user, host, diags):
+ """
+ Register a connection attempt.
+ If all the connection limit rules pass then add the
+ user/host to the connection tables.
+ @param[in] conn_id unique ID for connection, usually IP:port
+ @param[in] user authenticated user ID
+ @param[in] host IP address of host
+ @param[out] diags on failure holds 1, 2, or 3 error strings
+ @return connection is allowed and tracked in state tables
+ """
+ n_user = 0
+ if user in self.per_user_state:
+ n_user = len(self.per_user_state[user])
+ n_host = 0
+ if host in self.per_host_state:
+ n_host = len(self.per_host_state[host])
+
+ allowbytotal = self.max_total == 0 or self.connections_active < self.max_total
+ allowbyuser = self.max_per_user == 0 or n_user < self.max_per_user
+ allowbyhost = self.max_per_host == 0 or n_host < self.max_per_host
+
+ if allowbytotal and allowbyuser and allowbyhost:
+ if not user in self.per_user_state:
+ self.per_user_state[user] = []
+ self.per_user_state[user].append(conn_id)
+ if not host in self.per_host_state:
+ self.per_host_state[host] = []
+ self.per_host_state[host].append(conn_id)
+ self.connections_active += 1
+ self.connections_approved += 1
+ return True
+ else:
+ if not allowbytotal:
+ diags.append("Connection denied by total connection limit")
+ if not allowbyuser:
+ diags.append("Connection denied by per user limit")
+ if not allowbyhost:
+ diags.append("Connection denied by per host limit")
+ self.connections_denied += 1
+ return False
+
+ def disconnect(self, conn_id, user, host):
+ """
+ Unregister a connection
+ """
+ assert(self.connections_active > 0)
+ assert(user in self.per_user_state)
+ assert(conn_id in self.per_user_state[user])
+ assert(conn_id in self.per_host_state[host])
+ self.connections_active -= 1
+ self.per_user_state[user].remove(conn_id)
+ self.per_host_state[host].remove(conn_id)
+
+
+ def count_other_denial(self):
+ """
+ Record the statistic for a connection denied by some other process
+ @return:
+ """
+ self.connections_denied += 1
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/48e81620/src/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 8faf28e..cbfae10 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -59,6 +59,7 @@ set(qpid_dispatch_SOURCES
log.c
message.c
parse.c
+ policy.c
posix/driver.c
posix/threading.c
python_embedded.c
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org