def test_project_stats_work(self):
        tcs = self._fake_client_set_factory()
        tenant = doubles.make(self.mox,
                              doubles.Tenant,
                              id=u'pid',
                              name=u'test project')
        self.fake_client_set.identity_admin.tenants.get(u'pid') \
                .AndReturn(tenant)
        self.fake_client_set.identity_admin.tenants.list_users(u'pid') \
                .AndReturn(range(42))
        auth.client_set_for_tenant(u'pid', fallback_to_api=True) \
                .AndReturn(tcs)
        tcs.compute.servers.list().AndReturn(range(3))
        tcs.image.images.list().AndReturn([])

        expected = {
            u'project': {
                u'id': u'pid',
                u'href': u'/v1/projects/pid',
                u'name': u'test project'
            },
            u'members': 42,
            u'instances': 3,
            u'local-images': 0,
            u'total-images': 0,
            u'href': u'/v1/stats/by-project/pid'
        }

        self.mox.ReplayAll()

        rv = self.client.get('/v1/stats/by-project/pid')
        data = self.check_and_parse_response(rv)
        self.assertEquals(data, expected)
    def test_project_stats_work(self):
        tcs = self._fake_client_set_factory()
        tenant = doubles.make(self.mox, doubles.Tenant,
                              id=u'pid', name=u'test project')
        self.fake_client_set.identity_admin.tenants.get(u'pid') \
                .AndReturn(tenant)
        self.fake_client_set.identity_admin.tenants.list_users(u'pid') \
                .AndReturn(range(42))
        auth.client_set_for_tenant(u'pid', fallback_to_api=True) \
                .AndReturn(tcs)
        tcs.compute.servers.list().AndReturn(range(3))
        tcs.image.images.list().AndReturn([])

        expected = {
            u'project': {
                u'id': u'pid',
                u'href': u'/v1/projects/pid',
                u'name': u'test project'
            },
            u'members': 42,
            u'instances': 3,
            u'local-images': 0,
            u'total-images': 0,
            u'href': u'/v1/stats/by-project/pid'
        }

        self.mox.ReplayAll()

        rv = self.client.get('/v1/stats/by-project/pid')
        data = self.check_and_parse_response(rv)
        self.assertEquals(data, expected)
Beispiel #3
0
    def test_bound_client_user(self):
        # pretend we have unbound client set:
        self.fake_client_set.http_client.access['user']['roles'] = []
        tenants = [doubles.make(self.mox, doubles.Tenant, id='PID1'),
                   doubles.make(self.mox, doubles.Tenant, id='PID2')]

        self.fake_client_set.identity_public.tenants.list() \
                .AndReturn(tenants)
        auth.client_set_for_tenant('PID1').AndReturn('FAKE_CS')

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            self.assertEquals(auth.bound_client_set(), 'FAKE_CS')
Beispiel #4
0
def create_fw_rule(fw_rule_set_id):
    data = parse_request_data(_SCHEMA.allowed, _SCHEMA.required)
    protocol = data['protocol']
    if protocol not in ('TCP', 'UDP', 'ICMP'):
        raise exc.InvalidElementValue('protocol', 'string', protocol,
                                      'Protocol must be one of '
                                      '"TCP", "UDP" or "ICMP"')
    sg = _get_security_group(fw_rule_set_id)

    from_port = data.get('port-range-first', -1)
    to_port = data.get('port-range-last', from_port)
    client = auth.client_set_for_tenant(sg.tenant_id,
                                        fallback_to_api=g.is_admin,
                                        eperm_status=404)
    try:
        rule = client.compute.security_group_rules.create(
            parent_group_id=fw_rule_set_id,
            ip_protocol=protocol.lower(),
            from_port=from_port,
            to_port=to_port,
            cidr=data['source'])
    except osc_exc.NotFound:
        abort(404)
    set_audit_resource_id(rule)
    return make_json_response(_fw_rule_object_to_view(rule))
Beispiel #5
0
def create_image():
    data = parse_request_data(_SCHEMA.create_allowed, _SCHEMA.create_required)

    is_public = data.get('global', 'project' not in data)
    if is_public:
        _assert_param_absent('project', data, 'public')
        auth.assert_admin()
        client_set = g.client_set
    else:
        if 'project' not in data:
            raise exc.MissingElement('project')
        client_set = auth.client_set_for_tenant(data['project'])

    props = {}
    if data['disk-format'] == 'ami':
        # TODO(imelnikov): check that images have correct types
        if 'kernel' in data:
            props['kernel_id'] = data['kernel']
        if 'ramdisk' in data:
            props['ramdisk_id'] = data['ramdisk']
    else:
        _assert_param_absent('kernel', data, data['disk-format'])
        _assert_param_absent('ramdisk', data, data['disk-format'])

    image = client_set.image.images.create(
        name=data['name'],
        disk_format=data['disk-format'],
        container_format=data['container-format'],
        is_public=is_public,
        properties=props)
    set_audit_resource_id(image)
    return make_json_response(_image_to_view(image))
Beispiel #6
0
    def test_bound_client_user(self):
        # pretend we have unbound client set:
        self.fake_client_set.http_client.access['user']['roles'] = []
        tenants = [
            doubles.make(self.mox, doubles.Tenant, id='PID1'),
            doubles.make(self.mox, doubles.Tenant, id='PID2')
        ]

        self.fake_client_set.identity_public.tenants.list() \
                .AndReturn(tenants)
        auth.client_set_for_tenant('PID1').AndReturn('FAKE_CS')

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            self.assertEquals(auth.bound_client_set(), 'FAKE_CS')
Beispiel #7
0
def create_image():
    data = parse_request_data(_SCHEMA.create_allowed, _SCHEMA.create_required)

    is_public = data.get('global', 'project' not in data)
    if is_public:
        _assert_param_absent('project', data, 'public')
        auth.assert_admin()
        client_set = g.client_set
    else:
        if 'project' not in data:
            raise exc.MissingElement('project')
        client_set = auth.client_set_for_tenant(data['project'])

    props = {}
    if data['disk-format'] == 'ami':
        # TODO(imelnikov): check that images have correct types
        if 'kernel' in data:
            props['kernel_id'] = data['kernel']
        if 'ramdisk' in data:
            props['ramdisk_id'] = data['ramdisk']
    else:
        _assert_param_absent('kernel', data, data['disk-format'])
        _assert_param_absent('ramdisk', data, data['disk-format'])

    image = client_set.image.images.create(
        name=data['name'],
        disk_format=data['disk-format'],
        container_format=data['container-format'],
        is_public=is_public,
        properties=props)
    set_audit_resource_id(image)
    return make_json_response(_image_to_view(image))
Beispiel #8
0
def create_fw_rule(fw_rule_set_id):
    data = parse_request_data(_SCHEMA.allowed, _SCHEMA.required)
    protocol = data['protocol']
    if protocol not in ('TCP', 'UDP', 'ICMP'):
        raise exc.InvalidElementValue(
            'protocol', 'string', protocol, 'Protocol must be one of '
            '"TCP", "UDP" or "ICMP"')
    sg = _get_security_group(fw_rule_set_id)

    from_port = data.get('port-range-first', -1)
    to_port = data.get('port-range-last', from_port)
    client = auth.client_set_for_tenant(sg.tenant_id,
                                        fallback_to_api=g.is_admin,
                                        eperm_status=404)
    try:
        rule = client.compute.security_group_rules.create(
            parent_group_id=fw_rule_set_id,
            ip_protocol=protocol.lower(),
            from_port=from_port,
            to_port=to_port,
            cidr=data['source'])
    except osc_exc.NotFound:
        abort(404)
    set_audit_resource_id(rule)
    return make_json_response(_fw_rule_object_to_view(rule))
Beispiel #9
0
def create_fw_rule_set():
    data = parse_request_data(_SCHEMA.allowed, _SCHEMA.required)
    tcs = client_set_for_tenant(data['project'], eperm_status=404,
                                fallback_to_api=g.is_admin)
    sg = tcs.compute.security_groups.create(
        name=data['name'], description=data.get('description', ''))
    set_audit_resource_id(sg)
    return make_json_response(_sg_to_view(sg))
Beispiel #10
0
def remove_instance_fw_rule_set(instance_id, set_id):
    server = fetch_instance(instance_id)
    sg = _find_sg_on_server(instance_id, set_id)
    tcs = client_set_for_tenant(server.tenant_id, fallback_to_api=g.is_admin)

    try:
        tcs.compute.servers.remove_security_group(server, sg.name)
    except osc_exc.BadRequest, e:
        raise exc.InvalidRequest(str(e))
def remove_instance_fw_rule_set(instance_id, set_id):
    server = fetch_instance(instance_id)
    sg = _find_sg_on_server(instance_id, set_id)
    tcs = client_set_for_tenant(server.tenant_id, fallback_to_api=g.is_admin)

    try:
        tcs.compute.servers.remove_security_group(server, sg.name)
    except osc_exc.BadRequest, e:
        raise exc.InvalidRequest(str(e))
Beispiel #12
0
    def test_client_set_for_tenant_works(self):
        tcs = self._fake_client_set_factory()
        self.mock_client_set().AndReturn(tcs)
        tcs.http_client.authenticate()

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            cs = auth.client_set_for_tenant('PID')
            self.assertEquals(cs, tcs)
Beispiel #13
0
    def test_client_set_for_tenant_works(self):
        tcs = self._fake_client_set_factory()
        self.mock_client_set().AndReturn(tcs)
        tcs.http_client.authenticate()

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            cs = auth.client_set_for_tenant('PID')
            self.assertEquals(cs, tcs)
Beispiel #14
0
def create_fw_rule_set():
    data = parse_request_data(_SCHEMA.allowed, _SCHEMA.required)
    tcs = client_set_for_tenant(data['project'],
                                eperm_status=404,
                                fallback_to_api=g.is_admin)
    sg = tcs.compute.security_groups.create(name=data['name'],
                                            description=data.get(
                                                'description', ''))
    set_audit_resource_id(sg)
    return make_json_response(_sg_to_view(sg))
Beispiel #15
0
def _images_for_tenant(tenant_id, is_public):
    try:
        tenant = auth.admin_client_set().identity_admin \
                .tenants.get(tenant_id)
    except osc_exc.NotFound:
        return []  # consistent with project:eq

    client = auth.client_set_for_tenant(tenant_id, fallback_to_api=g.is_admin)
    image_list = client.image.images.list(filters={'is_public': is_public})
    return [_image_to_view(image, tenant) for image in image_list]
Beispiel #16
0
    def test_client_set_for_tenant_fallback(self):
        tcs = self._fake_client_set_factory()
        self.mock_client_set().AndReturn(tcs)
        tcs.http_client.authenticate()\
                .AndRaise(Unauthorized('denied'))
        auth.api_client_set('PID').AndReturn('REPLY')

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            result = auth.client_set_for_tenant('PID', fallback_to_api=True)
        self.assertEquals('REPLY', result)
Beispiel #17
0
def _images_for_tenant(tenant_id, is_public):
    try:
        tenant = auth.admin_client_set().identity_admin \
                .tenants.get(tenant_id)
    except osc_exc.NotFound:
        return []  # consistent with project:eq

    client = auth.client_set_for_tenant(tenant_id,
                                        fallback_to_api=g.is_admin)
    image_list = client.image.images.list(
            filters={'is_public': is_public})
    return [_image_to_view(image, tenant) for image in image_list]
Beispiel #18
0
    def test_client_set_for_tenant_fallback(self):
        tcs = self._fake_client_set_factory()
        self.mock_client_set().AndReturn(tcs)
        tcs.http_client.authenticate()\
                .AndRaise(Unauthorized('denied'))
        auth.api_client_set('PID').AndReturn('REPLY')

        self.mox.ReplayAll()
        with self.app.test_request_context():
            self.install_fake_auth()
            result = auth.client_set_for_tenant('PID',
                                                fallback_to_api=True)
        self.assertEquals('REPLY', result)
Beispiel #19
0
def _servers_for_user():
    project_id = get_matcher_argument("project", "eq")
    if project_id is not None:
        projects = (project_id,)
    else:
        projects = get_matcher_argument("project", "in")

    result = []
    for project_id in current_user_project_ids():
        if projects is None or project_id in projects:
            cs = client_set_for_tenant(project_id)
            result.extend(cs.compute.servers.list())
    return result
Beispiel #20
0
def list_fw_rule_sets():
    parse_collection_request(_SCHEMA)
    if g.my_projects:
        tenants = g.client_set.identity_public.tenants.list()
    else:
        tenants = admin_client_set().identity_admin.tenants.list()

    result = []
    for tenant in tenants:
        if tenant.name != app.config['SYSTENANT']:
            tcs = client_set_for_tenant(tenant.id, fallback_to_api=g.is_admin)
            for sg in tcs.compute.security_groups.list():
                result.append(_sg_to_view(sg, tenant.name))
    return make_collection_response(u'fw-rule-sets', result)
Beispiel #21
0
def list_fw_rule_sets():
    parse_collection_request(_SCHEMA)
    if g.my_projects:
        tenants = g.client_set.identity_public.tenants.list()
    else:
        tenants = admin_client_set().identity_admin.tenants.list()

    result = []
    for tenant in tenants:
        if tenant.name != app.config['SYSTENANT']:
            tcs = client_set_for_tenant(tenant.id, fallback_to_api=g.is_admin)
            for sg in tcs.compute.security_groups.list():
                result.append(_sg_to_view(sg, tenant.name))
    return make_collection_response(u'fw-rule-sets', result)
Beispiel #22
0
def add_instance_fw_rule_set(instance_id):
    server = fetch_instance(instance_id)
    set_id = parse_request_data(required=_SCHEMA.required)['id']
    set_audit_resource_id(set_id)
    try:
        sg = admin_client_set().compute.security_groups.get(set_id)
    except osc_exc.NotFound:
        raise exc.InvalidElementValue('id', 'string', set_id,
                                      'Security group does not exist')

    tcs = client_set_for_tenant(server.tenant_id, fallback_to_api=g.is_admin)
    try:
        tcs.compute.servers.add_security_group(server, sg.name)
    except osc_exc.BadRequest, e:
        raise exc.InvalidRequest(str(e))
def add_instance_fw_rule_set(instance_id):
    server = fetch_instance(instance_id)
    set_id = parse_request_data(required=_SCHEMA.required)['id']
    set_audit_resource_id(set_id)
    try:
        sg = admin_client_set().compute.security_groups.get(set_id)
    except osc_exc.NotFound:
        raise exc.InvalidElementValue('id', 'string', set_id,
                                      'Security group does not exist')

    tcs = client_set_for_tenant(server.tenant_id, fallback_to_api=g.is_admin)
    try:
        tcs.compute.servers.add_security_group(server, sg.name)
    except osc_exc.BadRequest, e:
        raise exc.InvalidRequest(str(e))
Beispiel #24
0
def get_project_stats(project_id):
    tenant = get_tenant(project_id)
    acs = auth.admin_client_set()
    users = acs.identity_admin.tenants.list_users(tenant.id)

    tcs = auth.client_set_for_tenant(project_id, fallback_to_api=g.is_admin)
    servers = tcs.compute.servers.list()
    images = tcs.image.images.list()
    local_images = [image for image in images
                    if image.owner == tenant.id]

    return make_json_response({
        u'project': link_for_tenant(tenant),
        u'instances': len(servers),
        u'members': len(users),
        u'local-images': len(local_images),
        u'total-images': len(images),
        'href': url_for('stats.get_project_stats',
                        project_id=tenant.id)
    })
Beispiel #25
0
def create_instance():
    data = parse_request_data(_SCHEMA.create_allowed, _SCHEMA.create_required)

    tcs = client_set_for_tenant(data["project"])
    security_groups = _security_group_ids_to_names(data.get("fw-rule-sets"), tcs.compute.security_groups)

    try:
        server = tcs.compute.servers.create(
            name=data["name"],
            image=data["image"],
            flavor=data["instance-type"],
            security_groups=security_groups,
            key_name=data.get("ssh-key-pair"),
            admin_pass=data.get("admin-pass"),
        )
        if "expires-at" in data or "remind-at" in data:
            InstanceDataDAO.create(server.id, expires_at=data.get("expires-at"), remind_at=data.get("remind-at"))
    except osc_exc.OverLimit, e:
        return make_json_response(
            status_code=403,
            data={"path": request.path, "method": request.method, "message": "Limits exceeded (%s)" % str(e)},
        )
Beispiel #26
0
def get_project_stats(project_id):
    tenant = get_tenant(project_id)
    acs = auth.admin_client_set()
    users = acs.identity_admin.tenants.list_users(tenant.id)

    tcs = auth.client_set_for_tenant(project_id, fallback_to_api=g.is_admin)
    servers = tcs.compute.servers.list()
    images = tcs.image.images.list()
    local_images = [image for image in images if image.owner == tenant.id]

    return make_json_response({
        u'project':
        link_for_tenant(tenant),
        u'instances':
        len(servers),
        u'members':
        len(users),
        u'local-images':
        len(local_images),
        u'total-images':
        len(images),
        'href':
        url_for('stats.get_project_stats', project_id=tenant.id)
    })