Beispiel #1
0
def get_q_from_condition(resource_uuid, startTime, endTime):
    """
    获取过滤条件
    :param resource_uuid: 
    :param startTime: 
    :param endTime: 
    :return: 
    """
    q = []
    q_item = base.Query()
    q_item.field = "resource_id"
    q_item.type = "string"
    q_item.op = "eq"
    q_item.value = resource_uuid
    q.append(q_item)
    start_item = base.Query()
    start_item.field = "timestamp"
    start_item.op = "le"
    start_item.value = str(endTime)
    q.append(start_item)
    end_item = base.Query()
    end_item.field = "timestamp"
    end_item.op = "ge"
    end_item.value = str(startTime)
    q.append(end_item)
    return q
 def test_sample_filter_meta(self):
     q = [
         v2_base.Query(field='metadata.size', op='eq', value='20'),
         v2_base.Query(field='resource_metadata.id',
                       op='eq',
                       value='meta_id')
     ]
     kwargs = utils.query_to_kwargs(q, storage.SampleFilter.__init__)
     self.assertEqual(1, len(kwargs))
     self.assertEqual(2, len(kwargs['metaquery']))
     self.assertEqual(20, kwargs['metaquery']['metadata.size'])
     self.assertEqual('meta_id', kwargs['metaquery']['metadata.id'])
 def test_sample_filter_timestamp(self):
     ts_start = timeutils.utcnow()
     ts_end = ts_start + datetime.timedelta(minutes=5)
     q = [
         v2_base.Query(field='timestamp', op='lt', value=str(ts_end)),
         v2_base.Query(field='timestamp', op='gt', value=str(ts_start))
     ]
     kwargs = utils.query_to_kwargs(q, storage.SampleFilter.__init__)
     self.assertEqual(4, len(kwargs))
     self.assertTimestampEqual(kwargs['start_timestamp'], ts_start)
     self.assertTimestampEqual(kwargs['end_timestamp'], ts_end)
     self.assertEqual('gt', kwargs['start_timestamp_op'])
     self.assertEqual('lt', kwargs['end_timestamp_op'])
 def test_sample_filter_non_equality_on_metadata(self):
     queries = [
         v2_base.Query(field='resource_metadata.image_id',
                       op='gt',
                       value='image',
                       type='string'),
         v2_base.Query(field='metadata.ramdisk_id',
                       op='le',
                       value='ramdisk',
                       type='string')
     ]
     with mock.patch('pecan.request') as request:
         request.headers.return_value = {'X-ProjectId': 'foobar'}
         self.assertRaises(wsme.exc.InvalidInput, utils.query_to_kwargs,
                           queries, storage.SampleFilter.__init__)
 def test_sample_filter_multi(self):
     q = [
         v2_base.Query(field='user_id', op='eq', value='uid'),
         v2_base.Query(field='project_id', op='eq', value='pid'),
         v2_base.Query(field='resource_id', op='eq', value='rid'),
         v2_base.Query(field='source', op='eq', value='source_name'),
         v2_base.Query(field='meter', op='eq', value='meter_name')
     ]
     kwargs = utils.query_to_kwargs(q, storage.SampleFilter.__init__)
     self.assertEqual(5, len(kwargs))
     self.assertEqual('uid', kwargs['user'])
     self.assertEqual('pid', kwargs['project'])
     self.assertEqual('rid', kwargs['resource'])
     self.assertEqual('source_name', kwargs['source'])
     self.assertEqual('meter_name', kwargs['meter'])
Beispiel #6
0
 def test_sample_filter_invalid_op(self):
     q = [v2_base.Query(field='user_id',
                        op='lt',
                        value='20')]
     self.assertRaises(
         wsme.exc.InvalidInput,
         utils.query_to_kwargs, q, storage.SampleFilter.__init__)
Beispiel #7
0
 def test_sample_filter_invalid_field(self):
     q = [v2_base.Query(field='invalid',
                        op='eq',
                        value='20')]
     self.assertRaises(
         wsme.exc.UnknownArgument,
         utils.query_to_kwargs, q, storage.SampleFilter.__init__)
 def test_get_value_as_type_with_datetime(self):
     query = v2_base.Query(field='metadata.date',
                           op='eq',
                           value='2014-01-01T05:00:00',
                           type='datetime')
     self.assertIsInstance(query._get_value_as_type(), datetime.datetime)
     self.assertIsNone(query._get_value_as_type().tzinfo)
 def test_get_value_as_type_with_float(self):
     query = v2_base.Query(field='metadata.size',
                           op='eq',
                           value='123.456',
                           type='float')
     expected = 123.456
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #10
0
 def test_get_value_as_type_with_integer(self):
     query = v2_base.Query(field='metadata.size',
                           op='eq',
                           value='123',
                           type='integer')
     expected = 123
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #11
0
 def test_get_value_as_type_integer_expression_without_type(self):
     # bug 1221736
     query = v2_base.Query(field='should_be_a_string',
                           op='eq',
                           value='WWW-Layer-4a80714f')
     expected = 'WWW-Layer-4a80714f'
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #12
0
 def test_get_value_as_type_with_boolean(self):
     query = v2_base.Query(field='metadata.is_public',
                           op='eq',
                           value='True',
                           type='boolean')
     expected = True
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #13
0
 def test_get_value_as_type_with_string(self):
     query = v2_base.Query(field='metadata.name',
                           op='eq',
                           value='linux',
                           type='string')
     expected = 'linux'
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #14
0
 def test_sample_filter_self_always_excluded(self):
     queries = [v2_base.Query(field='user_id', op='eq', value='20')]
     with mock.patch('pecan.request') as request:
         request.headers.return_value = {'X-ProjectId': 'foobar'}
         kwargs = utils.query_to_kwargs(queries,
                                        storage.SampleFilter.__init__)
         self.assertNotIn('self', kwargs)
Beispiel #15
0
 def test_get_value_as_type_boolean_expression_without_type(self):
     # bug 1221736
     query = v2_base.Query(field='should_be_a_string',
                           op='eq',
                           value='True or False')
     expected = 'True or False'
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #16
0
 def test_sample_filter_single(self):
     q = [v2_base.Query(field='user_id',
                        op='eq',
                        value='uid')]
     kwargs = utils.query_to_kwargs(q, storage.SampleFilter.__init__)
     self.assertIn('user', kwargs)
     self.assertEqual(1, len(kwargs))
     self.assertEqual('uid', kwargs['user'])
Beispiel #17
0
 def test_sample_filter_timestamp_invalid_op(self):
     ts_start = timeutils.utcnow()
     q = [v2_base.Query(field='timestamp',
                        op='eq',
                        value=str(ts_start))]
     self.assertRaises(
         wsme.exc.InvalidInput,
         utils.query_to_kwargs, q, storage.SampleFilter.__init__)
Beispiel #18
0
 def test_get_value_as_type_with_syntax_error(self):
     # bug 1221736
     value = 'WWW-Layer-4a80714f-0232-4580-aa5e-81494d1a4147-uolhh25p5xxm'
     query = v2_base.Query(field='group_id',
                           op='eq',
                           value=value)
     expected = value
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #19
0
 def test_event_query_to_event_filter_with_bad_op(self):
     # bug 1511592
     query = v2_base.Query(field='event_type',
                           op='ne',
                           value='compute.instance.create.end',
                           type='string')
     self.assertRaises(v2_base.ClientSideError,
                       events._event_query_to_event_filter, [query])
Beispiel #20
0
 def test_get_value_as_type_with_syntax_error_colons(self):
     # bug 1221736
     value = 'Ref::StackId'
     query = v2_base.Query(field='field_name',
                           op='eq',
                           value=value)
     expected = value
     self.assertEqual(expected, query._get_value_as_type())
Beispiel #21
0
    def test_timestamp_validation(self):
        q = [v2_base.Query(field='timestamp', op='le', value='123')]

        exc = self.assertRaises(wsme.exc.InvalidInput, utils.query_to_kwargs,
                                q, storage.SampleFilter.__init__)
        expected_exc = wsme.exc.InvalidInput('timestamp', '123',
                                             'invalid timestamp format')
        self.assertEqual(str(expected_exc), str(exc))
Beispiel #22
0
 def test_get_meters_filter_valid_fields(self):
     q = [v2_base.Query(field='abc', op='eq', value='abc')]
     exc = self.assertRaises(wsme.exc.UnknownArgument,
                             utils.query_to_kwargs, q,
                             storage_base.Connection.get_meters)
     valid_keys = ['pagination', 'project', 'resource', 'source', 'user']
     msg = ("unrecognized field in query: %s, "
            "valid keys: %s") % (q, valid_keys)
     expected_exc = wsme.exc.UnknownArgument('abc', msg)
     self.assertEqual(str(expected_exc), str(exc))
Beispiel #23
0
 def test_sample_filter_translation(self):
     queries = [
         v2_base.Query(field=f, op='eq', value='fake_%s' % f, type='string')
         for f in ['user_id', 'project_id', 'resource_id']
     ]
     with mock.patch('pecan.request') as request:
         request.headers.return_value = {'X-ProjectId': 'foobar'}
         kwargs = utils.query_to_kwargs(queries,
                                        storage.SampleFilter.__init__)
         for o in ['user', 'project', 'resource']:
             self.assertEqual('fake_%s_id' % o, kwargs.get(o))
Beispiel #24
0
 def test_sample_filter_exclude_internal(self):
     queries = [
         v2_base.Query(field=f, op='eq', value='fake', type='string')
         for f in ['y', 'on_behalf_of', 'x']
     ]
     with mock.patch('pecan.request') as request:
         request.headers.return_value = {'X-ProjectId': 'foobar'}
         self.assertRaises(wsme.exc.ClientSideError,
                           utils.query_to_kwargs,
                           queries,
                           storage.SampleFilter.__init__,
                           internal_keys=['on_behalf_of'])
Beispiel #25
0
 def test_get_alarm_changes_filter_valid_fields(self):
     q = [v2_base.Query(field='abc', op='eq', value='abc')]
     exc = self.assertRaises(
         wsme.exc.UnknownArgument, utils.query_to_kwargs, q,
         alarm_storage_base.Connection.get_alarm_changes)
     valid_keys = [
         'alarm_id', 'on_behalf_of', 'project', 'search_offset', 'severity',
         'timestamp', 'type', 'user'
     ]
     msg = ("unrecognized field in query: %s, "
            "valid keys: %s") % (q, valid_keys)
     expected_exc = wsme.exc.UnknownArgument('abc', msg)
     self.assertEqual(str(expected_exc), str(exc))
Beispiel #26
0
 def test_sample_filter_valid_fields(self):
     q = [v2_base.Query(field='abc', op='eq', value='abc')]
     exc = self.assertRaises(wsme.exc.UnknownArgument,
                             utils.query_to_kwargs, q,
                             storage.SampleFilter.__init__)
     valid_keys = [
         'message_id', 'meter', 'project', 'resource', 'search_offset',
         'source', 'timestamp', 'user'
     ]
     msg = ("unrecognized field in query: %s, "
            "valid keys: %s") % (q, valid_keys)
     expected_exc = wsme.exc.UnknownArgument('abc', msg)
     self.assertEqual(str(expected_exc), str(exc))
Beispiel #27
0
 def test_get_alarms_filter_valid_fields(self):
     q = [v2_base.Query(field='abc', op='eq', value='abc')]
     exc = self.assertRaises(wsme.exc.UnknownArgument,
                             utils.query_to_kwargs, q,
                             alarm_storage_base.Connection.get_alarms)
     valid_keys = [
         'alarm_id', 'enabled', 'meter', 'name', 'pagination', 'project',
         'severity', 'state', 'type', 'user'
     ]
     msg = ("unrecognized field in query: %s, "
            "valid keys: %s") % (q, valid_keys)
     expected_exc = wsme.exc.UnknownArgument('abc', msg)
     self.assertEqual(str(expected_exc), str(exc))
Beispiel #28
0
def sanitize_query(query, db_func, on_behalf_of=None):
    """Check the query.

    See if:
    1) the request is coming from admin - then allow full visibility
    2) non-admin - make sure that the query includes the requester's project.
    """
    q = copy.copy(query)

    auth_project = get_auth_project(on_behalf_of)
    if auth_project:
        _verify_query_segregation(q, auth_project)

        proj_q = [i for i in q if i.field == 'project_id']
        valid_keys = inspect.getargspec(db_func)[0]
        if not proj_q and 'on_behalf_of' not in valid_keys:
            # The user is restricted, but they didn't specify a project
            # so add it for them.
            q.append(
                base.Query(field='project_id', op='eq', value=auth_project))
    return q
Beispiel #29
0
 def __init__(self, query=None, **kwargs):
     if query:
         query = [base.Query(**q) for q in query]
     super(AlarmThresholdRule, self).__init__(query=query, **kwargs)
Beispiel #30
0
 def test_get_value_as_type_with_bad_value(self):
     query = v2_base.Query(field='metadata.size',
                           op='eq',
                           value='fake',
                           type='integer')
     self.assertRaises(wsme.exc.ClientSideError, query._get_value_as_type)