Пример #1
0
    def test_create_exception_db_securitygroup_create(self):
        self.stubs.Set(db, "group_get_by_gid", fake_group_get_by_id)
        self.mox.StubOutWithMock(manager.ResourceOperator,
                                 "securitygroup_create")
        name = "test_securitygroup"
        securty_group = {
            "securitygroup": {
                "securitygroup_id": SECURITYGROUP_ID,
                "neutron_securitygroup_id": "fake_id",
                "gid": GID,
                "display_name": name,
                "is_default": True,
            }
        }
        manager.ResourceOperator.securitygroup_create(
            IsA(context.RequestContext), name,
            IsA(list)).AndReturn(securty_group)
        self.mox.StubOutWithMock(db, "securitygroup_create")
        db.securitygroup_create(IsA(context.RequestContext),
                                IsA(dict))\
            .AndRaise(exception.RackException())
        self.mox.ReplayAll()

        request_body = {
            "securitygroup": {
                "name": name,
                "is_default": "true",
            }
        }

        url = get_base_url(GID)
        req = get_request(url, 'POST', request_body)
        res = req.get_response(self.app)

        self.assertEqual(res.status_code, 500)
Пример #2
0
    def test_create_with_no_name(self):
        self.stubs.Set(db, "group_get_by_gid", fake_group_get_by_id)
        self.mox.StubOutWithMock(manager.ResourceOperator,
                                 "securitygroup_create")
        result_value = {"neutron_securitygroup_id": "fake_id"}
        manager.ResourceOperator.securitygroup_create(
            IsA(context.RequestContext), IsA(unicode),
            IsA(list)).AndReturn(result_value)
        self.mox.StubOutWithMock(db, "securitygroup_create")
        name = "securitygroup-" + SECURITYGROUP_ID
        db.securitygroup_create(IsA(context.RequestContext),
                                IsA(dict))\
            .AndReturn({"securitygroup_id": SECURITYGROUP_ID,
                        "neutron_securitygroup_id": "fake_id",
                        "gid": GID,
                        "user_id": "noauth",
                        "project_id": "noauth",
                        "display_name": name,
                        "is_default": False})
        self.mox.ReplayAll()

        request_body = {
            "securitygroup": {
                "is_default": "false",
            }
        }

        expected = {
            "securitygroup": {
                "securitygroup_id": SECURITYGROUP_ID,
                "neutron_securitygroup_id": "fake_id",
                "gid": GID,
                "user_id": "noauth",
                "project_id": "noauth",
                "name": name,
                "is_default": False,
            }
        }

        url = get_base_url(GID)
        req = get_request(url, 'POST', request_body)
        res = req.get_response(self.app)
        body = jsonutils.loads(res.body)
        self.assertEqual(res.status_code, 201)
        for key in body["securitygroup"]:
            self.assertEqual(body["securitygroup"][key],
                             expected["securitygroup"][key])
Пример #3
0
    def test_securitygroup_create(self):
        gid = "12345678-1234-5678-9123-123456789012"
        self._create_group(gid)

        values = self._get_base_values(gid)
        securitygroup = db.securitygroup_create(self.user_ctxt, values)
        ignored_keys = ['deleted', 'deleted_at', 'updated_at',
                        'created_at']
        self._assertEqualObjects(securitygroup, values, ignored_keys)
Пример #4
0
 def test_securitygroup_delete(self):
     gid = "12345678-1234-5678-9123-123456789012"
     self._create_group(gid)
     values_before = self._get_base_values(gid)
     securitygroup = db.securitygroup_create(self.user_ctxt, values_before)
     securitygroup_after = db.securitygroup_delete(
         self.user_ctxt, gid, securitygroup["securitygroup_id"])
     self.assertEqual("DELETING", securitygroup_after["status"])
     self.assertEqual(1, securitygroup_after["deleted"])
     self.assertIsNotNone(securitygroup_after.get("deleted_at"))
Пример #5
0
 def _create_securitygroup(self, gid):
     values = {
         "gid": gid,
         "securitygroup_id": unicode(uuid.uuid4()),
         "user_id": self.user_ctxt.user_id,
         "project_id": self.user_ctxt.project_id,
         "display_name": "test_securitygroup",
         "is_default": False,
         "status": "ACTIVE",
         "deleted": 0
     }
     return db.securitygroup_create(self.user_ctxt, values)
Пример #6
0
 def test_securitygroup_update(self):
     gid = "12345678-1234-5678-9123-123456789012"
     self._create_group(gid)
     values_before = self._get_base_values(gid)
     securitygroup = db.securitygroup_create(self.user_ctxt, values_before)
     values = {
         "is_default": False,
         "status": "ACTIVE",
     }
     securitygroup_after = db.securitygroup_update(
         self.user_ctxt, gid, securitygroup["securitygroup_id"], values)
     self.assertEqual(securitygroup_after["is_default"], False)
     self.assertEqual(securitygroup_after["status"], "ACTIVE")
Пример #7
0
    def test_securitygroup_get_by_securitygroup_id(self):
        group = self._create_group("gid1")
        securitygroup_ids = ["sc1", "sc2", "sc3"]
        securitygroups = []
        for securitygroup_id in securitygroup_ids:
            securitygroup = db.securitygroup_create(
                self.user_ctxt, self._get_base_values(group["gid"],
                                                      securitygroup_id))
            securitygroups.append(securitygroup)

        res_securitygroup = db.securitygroup_get_by_securitygroup_id(
            self.user_ctxt, group["gid"], securitygroup_ids[0])
        ignored_keys = ['deleted_at', 'updated_at', 'created_at', 'processes']
        self._assertEqualObjects(
            res_securitygroup, securitygroups[0], ignored_keys)
Пример #8
0
    def test_securitygroup_get_all(self):
        group = self._create_group("gid1")
        securitygroup_ids = ["sc1", "sc2", "sc3"]
        securitygroups = []
        for securitygroup_id in securitygroup_ids:
            securitygroup = db.securitygroup_create(
                self.user_ctxt, self._get_base_values(group["gid"],
                                                      securitygroup_id))
            securitygroups.append(securitygroup)

        res_securitygroups = db.securitygroup_get_all(context, group["gid"])
        ignored_keys = ['deleted_at', 'updated_at', 'created_at']
        self.assertEqual(len(res_securitygroups), len(securitygroups))
        for i in range(0, len(res_securitygroups)):
            self._assertEqualObjects(
                res_securitygroups[i], securitygroups[i], ignored_keys)
Пример #9
0
    def test_create_with_rules(self):
        self.stubs.Set(db, "group_get_by_gid", fake_group_get_by_id)
        self.stubs.Set(db, "securitygroup_get_by_securitygroup_id",
                       fake_securitygroup_get_by_securitygroup_id)
        self.mox.StubOutWithMock(manager.ResourceOperator,
                                 "securitygroup_create")
        name = "test_securitygroup"
        security_group = {"neutron_securitygroup_id": "fake_id"}
        manager.ResourceOperator.securitygroup_create(
            IsA(context.RequestContext), name,
            [{
                "protocol": "icmp",
                "port_range_max": None,
                "port_range_min": None,
                "remote_neutron_securitygroup_id": "fake_key1",
                "remote_ip_prefix": None
            }, {
                "protocol": "tcp",
                "port_range_max": "80",
                "port_range_min": "80",
                "remote_neutron_securitygroup_id": "fake_key1",
                "remote_ip_prefix": None
            }]).AndReturn(security_group)
        self.mox.StubOutWithMock(db, "securitygroup_create")
        db.securitygroup_create(IsA(context.RequestContext),
                                IsA(dict))\
            .AndReturn({"securitygroup_id": SECURITYGROUP_ID,
                        "neutron_securitygroup_id": "fake_id",
                        "gid": GID,
                        "user_id": "noauth",
                        "project_id": "noauth",
                        "display_name": name,
                        "is_default": True})
        self.mox.ReplayAll()

        request_body = {
            "securitygroup": {
                "name":
                name,
                "is_default":
                "true",
                "securitygrouprules": [{
                    "protocol":
                    "icmp",
                    "remote_securitygroup_id":
                    SECURITYGROUP_ID1
                }, {
                    "port_range_max":
                    "80",
                    "port_range_min":
                    "80",
                    "protocol":
                    "tcp",
                    "remote_securitygroup_id":
                    SECURITYGROUP_ID1
                }]
            }
        }

        expected = {
            "securitygroup": {
                "securitygroup_id": SECURITYGROUP_ID,
                "neutron_securitygroup_id": "fake_id",
                "gid": GID,
                "user_id": "noauth",
                "project_id": "noauth",
                "name": name,
                "is_default": True
            }
        }

        url = get_base_url(GID)
        req = get_request(url, 'POST', request_body)
        res = req.get_response(self.app)
        body = jsonutils.loads(res.body)
        self.assertEqual(res.status_code, 201)
        for key in body["securitygroup"]:
            self.assertEqual(body["securitygroup"][key],
                             expected["securitygroup"][key])
Пример #10
0
    def create(self, req, body, gid):

        def _validate_securitygroup(gid, body):
            if not uuidutils.is_uuid_like(gid):
                raise exception.GroupNotFound(gid=gid)

            if not self.is_valid_body(body, 'securitygroup'):
                msg = _("Invalid request body")
                raise exception.InvalidInput(reason=msg)

            values = body["securitygroup"]
            name = values.get("name")
            is_default = values.get("is_default")

            if isinstance(name, six.string_types):
                name = name.strip()
                utils.check_string_length(name, 'name', min_length=1,
                                          max_length=255)

            if is_default:
                try:
                    is_default = strutils.bool_from_string(
                        is_default, strict=True)
                except ValueError:
                    msg = _("is_default must be a boolean")
                    raise exception.InvalidInput(reason=msg)
            else:
                is_default = False

            valid_values = {}
            valid_values["gid"] = gid
            valid_values["display_name"] = name
            valid_values["is_default"] = is_default
            return valid_values

        def _validate_securitygrouprules(securitygrouprules):

            valid_securitygrouprules = []
            for securitygroup in securitygrouprules:
                protocol = securitygroup.get("protocol")
                port_range_max = securitygroup.get("port_range_max")
                port_range_min = securitygroup.get("port_range_min")
                remote_securitygroup_id = securitygroup.get(
                    "remote_securitygroup_id")
                remote_ip_prefix = securitygroup.get("remote_ip_prefix")

                if not protocol:
                    msg = _("SecurityGroupRule protocol is required")
                    raise exception.InvalidInput(reason=msg)
                elif not utils.is_valid_protocol(protocol):
                    msg = _(
                        "SecurityGroupRule protocol should be tcp or udp or "
                        "icmp")
                    raise exception.InvalidInput(reason=msg)

                if not remote_securitygroup_id and not remote_ip_prefix:
                    msg = _(
                        "SecurityGroupRule either remote_securitygroup_id or "
                        "remote_ip_prefix is required")
                    raise exception.InvalidInput(reason=msg)
                elif remote_securitygroup_id and remote_ip_prefix:
                    msg = _(
                        "SecurityGroupRule either remote_securitygroup_id or "
                        "remote_ip_prefix is required")
                    raise exception.InvalidInput(reason=msg)
                elif remote_securitygroup_id is not None:
                    if not uuidutils.is_uuid_like(remote_securitygroup_id):
                        raise exception.SecuritygroupNotFound(
                            securitygroup_id=remote_securitygroup_id)
                elif remote_ip_prefix is not None:
                    if not utils.is_valid_cidr(remote_ip_prefix):
                        msg = _(
                            "SecurityGroupRule remote_ip_prefix should be "
                            "cidr format")
                        raise exception.InvalidInput(reason=msg)

                if protocol in ["tcp", "udp"]:
                    if port_range_max is None:
                        msg = _("SecurityGroupRule port_range_max is "
                                "required")
                        raise exception.InvalidInput(reason=msg)
                    utils.validate_integer(
                        port_range_max, 'port_range_max', min_value=1,
                        max_value=65535)
                    if port_range_min:
                        utils.validate_integer(
                            port_range_min, 'port_range_min', min_value=1,
                            max_value=65535)
                        if port_range_min > port_range_max:
                            msg = _(
                                "SecurityGroupRule port_range_min should be "
                                "lower than port_range_max")
                            raise exception.InvalidInput(reason=msg)
                elif protocol == "icmp":
                    port_range_max = None
                    port_range_min = None

                valid_securitygrouprules.append({
                    "protocol": protocol,
                    "port_range_max": port_range_max,
                    "port_range_min": port_range_min,
                    "remote_securitygroup_id": remote_securitygroup_id,
                    "remote_ip_prefix": unicode(netaddr
                                                .IPNetwork(remote_ip_prefix))
                    if remote_ip_prefix else remote_ip_prefix
                })
            return valid_securitygrouprules

        try:
            context = req.environ['rack.context']
            values = _validate_securitygroup(gid, body)
            if(body["securitygroup"].get("securitygrouprules")):
                securitygrouprules = _validate_securitygrouprules(
                    body["securitygroup"].get("securitygrouprules"))
            else:
                securitygrouprules = []
        except exception.InvalidInput as exc:
            raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
        except exception.NotFound as exc:
            raise webob.exc.HTTPNotFound(explanation=exc.format_message())

        values["deleted"] = 0
        values["status"] = "BUILDING"
        values["securitygroup_id"] = unicode(uuid.uuid4())
        values["user_id"] = context.user_id
        values["project_id"] = context.project_id
        values["display_name"] = values[
            "display_name"] or "sec-" + values["securitygroup_id"]

        try:
            for i in range(len(securitygrouprules)):
                if securitygrouprules[i]["remote_securitygroup_id"]:
                    securitygroup = db\
                        .securitygroup_get_by_securitygroup_id(
                            context, gid,
                            securitygrouprules[i]["remote_securitygroup_id"])
                    remote_neutron_securitygroup_id = securitygroup.get(
                        "neutron_securitygroup_id")
                    securitygrouprules[i][
                        "remote_neutron_securitygroup_id"] =\
                        remote_neutron_securitygroup_id
            db.group_get_by_gid(context, gid)
            securitygroup = db.securitygroup_create(context, values)
        except exception.NotFound as exc:
            raise webob.exc.HTTPNotFound(explanation=exc.format_message())

        try:
            host = self.scheduler_rpcapi.select_destinations(
                context,
                request_spec={},
                filter_properties={})
            self.operator_rpcapi.securitygroup_create(
                context,
                host["host"],
                gid=gid,
                securitygroup_id=values["securitygroup_id"],
                name=values["display_name"],
                securitygrouprules=securitygrouprules)
        except Exception:
            securitygroup_id = values["securitygroup_id"]
            db.securitygroup_update(
                context, gid, securitygroup_id, {"status": "ERROR"})
            raise exception.SecuritygroupCreateFailed()

        return self._view_builder.create(securitygroup)