From f73b6df6fb399f260aa7349fdaac1dbb9932aca2 Mon Sep 17 00:00:00 2001 From: zhangguoqing Date: Wed, 7 Dec 2016 04:45:38 +0000 Subject: [PATCH] Replaces uuid.uuid4 with uuidutils.generate_uuid() Openstack common has a wrapper for generating uuids. We should use that function when generating uuids for consistency. Change-Id: I331fb62e6f7278cdac3852b84fb161732aaad2a3 Closes-Bug: #1082248 --- aodh/api/controllers/v2/alarms.py | 10 +++---- aodh/cmd/alarm_conversion.py | 4 +-- aodh/coordination.py | 4 +-- aodh/evaluator/__init__.py | 4 +-- aodh/notifier/rest.py | 7 ++--- .../functional/api/v2/test_alarm_scenarios.py | 28 +++++++++---------- aodh/tests/functional/db.py | 4 +-- aodh/tests/functional/gabbi/fixtures.py | 4 +-- .../tempest/api/test_alarming_api_negative.py | 5 ++-- aodh/tests/unit/evaluator/test_combination.py | 6 ++-- aodh/tests/unit/evaluator/test_composite.py | 11 ++++---- aodh/tests/unit/evaluator/test_event.py | 8 +++--- aodh/tests/unit/evaluator/test_gnocchi.py | 8 +++--- aodh/tests/unit/evaluator/test_threshold.py | 8 +++--- 14 files changed, 54 insertions(+), 57 deletions(-) diff --git a/aodh/api/controllers/v2/alarms.py b/aodh/api/controllers/v2/alarms.py index c94666054..00f2039a7 100644 --- a/aodh/api/controllers/v2/alarms.py +++ b/aodh/api/controllers/v2/alarms.py @@ -21,13 +21,13 @@ import datetime import itertools import json -import uuid import croniter from oslo_config import cfg from oslo_log import log from oslo_utils import netutils from oslo_utils import timeutils +from oslo_utils import uuidutils import pecan from pecan import rest import pytz @@ -541,7 +541,7 @@ class AlarmController(rest.RestController): project_id = pecan.request.headers.get('X-Project-Id') on_behalf_of = on_behalf_of or project_id severity = scrubbed_data.get('severity') - payload = dict(event_id=str(uuid.uuid4()), + payload = dict(event_id=uuidutils.generate_uuid(), alarm_id=self._id, type=type, detail=detail, @@ -567,7 +567,7 @@ class AlarmController(rest.RestController): detail = {'state': alarm.state} user_id = pecan.request.headers.get('X-User-Id') project_id = pecan.request.headers.get('X-Project-Id') - payload = dict(event_id=str(uuid.uuid4()), + payload = dict(event_id=uuidutils.generate_uuid(), alarm_id=self._id, type=type, detail=detail, @@ -720,7 +720,7 @@ class AlarmsController(rest.RestController): user_id = pecan.request.headers.get('X-User-Id') project_id = pecan.request.headers.get('X-Project-Id') severity = scrubbed_data.get('severity') - payload = dict(event_id=str(uuid.uuid4()), + payload = dict(event_id=uuidutils.generate_uuid(), alarm_id=alarm_id, type=type, detail=detail, @@ -751,7 +751,7 @@ class AlarmsController(rest.RestController): conn = pecan.request.storage now = timeutils.utcnow() - data.alarm_id = str(uuid.uuid4()) + data.alarm_id = uuidutils.generate_uuid() user_limit, project_limit = rbac.get_limited_to(pecan.request.headers, pecan.request.enforcer) diff --git a/aodh/cmd/alarm_conversion.py b/aodh/cmd/alarm_conversion.py index 59b1070f7..971725bc3 100644 --- a/aodh/cmd/alarm_conversion.py +++ b/aodh/cmd/alarm_conversion.py @@ -15,10 +15,10 @@ """ import datetime -import uuid import argparse from oslo_log import log +from oslo_utils import uuidutils from aodh.i18n import _LI, _LW from aodh import service @@ -118,7 +118,7 @@ def conversion(): {'alarm': e.sub_alarm_id, 'type': e.sub_alarm_type}) continue new_alarm = models.Alarm(**alarm.as_dict()) - new_alarm.alarm_id = str(uuid.uuid4()) + new_alarm.alarm_id = uuidutils.generate_uuid() new_alarm.name = new_name new_alarm.type = 'composite' new_alarm.description = ('composite alarm converted from combination ' diff --git a/aodh/coordination.py b/aodh/coordination.py index 8447efe24..00f416d34 100644 --- a/aodh/coordination.py +++ b/aodh/coordination.py @@ -15,10 +15,10 @@ import bisect import hashlib import struct -import uuid from oslo_config import cfg from oslo_log import log +from oslo_utils import uuidutils import six import tenacity import tooz.coordination @@ -116,7 +116,7 @@ class PartitionCoordinator(object): self.backend_url = self.conf.coordination.backend_url self._coordinator = None self._groups = set() - self._my_id = my_id or str(uuid.uuid4()) + self._my_id = my_id or uuidutils.generate_uuid() def start(self): if self.backend_url: diff --git a/aodh/evaluator/__init__.py b/aodh/evaluator/__init__.py index 42f5127ef..877c93e89 100644 --- a/aodh/evaluator/__init__.py +++ b/aodh/evaluator/__init__.py @@ -26,10 +26,10 @@ from futurist import periodics from oslo_config import cfg from oslo_log import log from oslo_utils import timeutils +from oslo_utils import uuidutils import pytz import six from stevedore import extension -import uuid import aodh from aodh import coordination @@ -87,7 +87,7 @@ class Evaluator(object): user_id, project_id = self.ks_client.user_id, self.ks_client.project_id on_behalf_of = alarm.project_id now = timeutils.utcnow() - payload = dict(event_id=str(uuid.uuid4()), + payload = dict(event_id=uuidutils.generate_uuid(), alarm_id=alarm.alarm_id, type=type, detail=detail, diff --git a/aodh/notifier/rest.py b/aodh/notifier/rest.py index a5f893674..8b98352a5 100644 --- a/aodh/notifier/rest.py +++ b/aodh/notifier/rest.py @@ -14,11 +14,10 @@ # under the License. """Rest alarm notifier.""" -import uuid - from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils +from oslo_utils import uuidutils import requests import six.moves.urllib.parse as urlparse @@ -63,8 +62,8 @@ class RestAlarmNotifier(notifier.AlarmNotifier): current, reason, reason_data, headers=None): headers = headers or {} if 'x-openstack-request-id' not in headers: - headers['x-openstack-request-id'] = b'req-' + str( - uuid.uuid4()).encode('ascii') + headers['x-openstack-request-id'] = b'req-' + \ + uuidutils.generate_uuid().encode('ascii') LOG.info(_LI( "Notifying alarm %(alarm_name)s %(alarm_id)s with severity" diff --git a/aodh/tests/functional/api/v2/test_alarm_scenarios.py b/aodh/tests/functional/api/v2/test_alarm_scenarios.py index 23e541d2b..0e7a1c4ec 100644 --- a/aodh/tests/functional/api/v2/test_alarm_scenarios.py +++ b/aodh/tests/functional/api/v2/test_alarm_scenarios.py @@ -16,12 +16,12 @@ import datetime import os -import uuid from gnocchiclient import exceptions import mock import oslo_messaging.conffixture from oslo_serialization import jsonutils +from oslo_utils import uuidutils import six from six import moves @@ -152,8 +152,8 @@ class TestAlarmsBase(v2.FunctionalTest): def setUp(self): super(TestAlarmsBase, self).setUp() - self.auth_headers = {'X-User-Id': str(uuid.uuid4()), - 'X-Project-Id': str(uuid.uuid4())} + self.auth_headers = {'X-User-Id': uuidutils.generate_uuid(), + 'X-Project-Id': uuidutils.generate_uuid()} @staticmethod def _add_default_threshold_rule(alarm): @@ -1971,8 +1971,8 @@ class TestAlarmsHistory(TestAlarmsBase): def test_get_recorded_alarm_history_state_transition_on_behalf_of(self): # credentials for new non-admin user, on who's behalf the alarm # is created - member_user = str(uuid.uuid4()) - member_project = str(uuid.uuid4()) + member_user = uuidutils.generate_uuid() + member_project = uuidutils.generate_uuid() member_auth = {'X-Roles': 'member', 'X-User-Id': member_user, 'X-Project-Id': member_project} @@ -1997,8 +1997,8 @@ class TestAlarmsHistory(TestAlarmsBase): alarm = self.get_json('/alarms', headers=member_auth)[0] # effect a state transition as a new administrative user - admin_user = str(uuid.uuid4()) - admin_project = str(uuid.uuid4()) + admin_user = uuidutils.generate_uuid() + admin_project = uuidutils.generate_uuid() admin_auth = {'X-Roles': 'admin', 'X-User-Id': admin_user, 'X-Project-Id': admin_project} @@ -2045,8 +2045,8 @@ class TestAlarmsHistory(TestAlarmsBase): 'rule change', detail) auth = {'X-Roles': 'member', - 'X-User-Id': str(uuid.uuid4()), - 'X-Project-Id': str(uuid.uuid4())} + 'X-User-Id': uuidutils.generate_uuid(), + 'X-Project-Id': uuidutils.generate_uuid()} self._get_alarm_history('a', auth_headers=auth, expect_errors=True, status=404) @@ -2246,7 +2246,7 @@ class TestAlarmsQuotas(TestAlarmsBase): self.assertEqual(201, resp.status_code) _test('project_id', self.auth_headers['X-Project-Id']) - self.auth_headers['X-Project-Id'] = str(uuid.uuid4()) + self.auth_headers['X-Project-Id'] = uuidutils.generate_uuid() alarm['name'] = 'another_user_alarm' alarm['project_id'] = self.auth_headers['X-Project-Id'] resp = self.post_json('/alarms', params=alarm, @@ -2586,8 +2586,8 @@ class TestAlarmsRuleCombination(TestAlarmsBase): 'operator': 'and', } } - an_other_user_auth = {'X-User-Id': str(uuid.uuid4()), - 'X-Project-Id': str(uuid.uuid4())} + an_other_user_auth = {'X-User-Id': uuidutils.generate_uuid(), + 'X-Project-Id': uuidutils.generate_uuid()} resp = self.post_json('/alarms', params=json, status=404, headers=an_other_user_auth) self.assertEqual("Alarm a not found in project " @@ -2679,8 +2679,8 @@ class TestAlarmsRuleCombination(TestAlarmsBase): 'operator': 'and', } } - an_other_admin_auth = {'X-User-Id': str(uuid.uuid4()), - 'X-Project-Id': str(uuid.uuid4()), + an_other_admin_auth = {'X-User-Id': uuidutils.generate_uuid(), + 'X-Project-Id': uuidutils.generate_uuid(), 'X-Roles': 'admin'} if owner_is_set: json['project_id'] = an_other_admin_auth['X-Project-Id'] diff --git a/aodh/tests/functional/db.py b/aodh/tests/functional/db.py index fd7dd50a7..4762cdbf4 100644 --- a/aodh/tests/functional/db.py +++ b/aodh/tests/functional/db.py @@ -17,10 +17,10 @@ """Base classes for API tests.""" import os -import uuid import fixtures from oslo_config import fixture as fixture_config +from oslo_utils import uuidutils from oslotest import mockpatch import six from six.moves.urllib import parse as urlparse @@ -33,7 +33,7 @@ from aodh.tests import base as test_base class SQLManager(fixtures.Fixture): def __init__(self, conf): self.conf = conf - db_name = 'aodh_%s' % uuid.uuid4().hex + db_name = 'aodh_%s' % uuidutils.generate_uuid(dashed=False) import sqlalchemy self._engine = sqlalchemy.create_engine(conf.database.connection) self._conn = self._engine.connect() diff --git a/aodh/tests/functional/gabbi/fixtures.py b/aodh/tests/functional/gabbi/fixtures.py index 54031ea8f..0e487f2ba 100644 --- a/aodh/tests/functional/gabbi/fixtures.py +++ b/aodh/tests/functional/gabbi/fixtures.py @@ -16,13 +16,13 @@ """Fixtures used during Gabbi-based test runs.""" import os -import uuid from gabbi import fixture import mock from oslo_config import cfg from oslo_config import fixture as fixture_config from oslo_policy import opts +from oslo_utils import uuidutils from six.moves.urllib import parse as urlparse import sqlalchemy_utils @@ -75,7 +75,7 @@ class ConfigFixture(fixture.GabbiFixture): parsed_url = urlparse.urlparse(db_url) if parsed_url.scheme != 'sqlite': parsed_url = list(parsed_url) - parsed_url[2] += '-%s' % str(uuid.uuid4()).replace('-', '') + parsed_url[2] += '-%s' % uuidutils.generate_uuid(dashed=False) db_url = urlparse.urlunparse(parsed_url) conf.set_override('connection', db_url, group='database', diff --git a/aodh/tests/tempest/api/test_alarming_api_negative.py b/aodh/tests/tempest/api/test_alarming_api_negative.py index dedc0a4ea..5119dfcb4 100644 --- a/aodh/tests/tempest/api/test_alarming_api_negative.py +++ b/aodh/tests/tempest/api/test_alarming_api_negative.py @@ -12,8 +12,7 @@ # License for the specific language governing permissions and limitations # under the License. -import uuid - +from oslo_utils import uuidutils from tempest.common.utils import data_utils from tempest.lib import exceptions as lib_exc from tempest import test @@ -34,7 +33,7 @@ class TelemetryAlarmingNegativeTest(base.BaseAlarmingTest): @test.idempotent_id('668743d5-08ad-4480-b2b8-15da34f81e7e') def test_get_non_existent_alarm(self): # get the non-existent alarm - non_existent_id = str(uuid.uuid4()) + non_existent_id = uuidutils.generate_uuid() self.assertRaises(lib_exc.NotFound, self.alarming_client.show_alarm, non_existent_id) diff --git a/aodh/tests/unit/evaluator/test_combination.py b/aodh/tests/unit/evaluator/test_combination.py index 40593fd3b..354ae66de 100644 --- a/aodh/tests/unit/evaluator/test_combination.py +++ b/aodh/tests/unit/evaluator/test_combination.py @@ -17,12 +17,12 @@ """ import datetime -import uuid from ceilometerclient import exc from ceilometerclient.v2 import alarms import mock from oslo_utils import timeutils +from oslo_utils import uuidutils import pytz from aodh.evaluator import combination @@ -42,7 +42,7 @@ class TestEvaluate(base.TestEvaluatorBase): enabled=True, user_id='foobar', project_id='snafu', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, @@ -64,7 +64,7 @@ class TestEvaluate(base.TestEvaluatorBase): enabled=True, user_id='foobar', project_id='snafu', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, diff --git a/aodh/tests/unit/evaluator/test_composite.py b/aodh/tests/unit/evaluator/test_composite.py index ae046aa93..76cc485ed 100644 --- a/aodh/tests/unit/evaluator/test_composite.py +++ b/aodh/tests/unit/evaluator/test_composite.py @@ -13,11 +13,10 @@ """Tests for aodh/evaluator/composite.py """ -import uuid - from ceilometerclient.v2 import statistics import mock from oslo_utils import timeutils +from oslo_utils import uuidutils from oslotest import mockpatch import six from six import moves @@ -123,7 +122,7 @@ class TestEvaluate(base.TestEvaluatorBase): enabled=True, user_id='fake_user', project_id='fake_project', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, @@ -151,7 +150,7 @@ class TestEvaluate(base.TestEvaluatorBase): ok_actions=[], alarm_actions=[], repeat_actions=False, - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), time_constraints=[], rule={ "or": [self.sub_rule1, self.sub_rule2, @@ -172,7 +171,7 @@ class TestEvaluate(base.TestEvaluatorBase): ok_actions=[], alarm_actions=[], repeat_actions=False, - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), time_constraints=[], rule={ "and": [self.sub_rule1, self.sub_rule2, @@ -186,7 +185,7 @@ class TestEvaluate(base.TestEvaluatorBase): enabled=True, user_id='fake_user', project_id='fake_project', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, diff --git a/aodh/tests/unit/evaluator/test_event.py b/aodh/tests/unit/evaluator/test_event.py index 106d39893..ac171aaa5 100644 --- a/aodh/tests/unit/evaluator/test_event.py +++ b/aodh/tests/unit/evaluator/test_event.py @@ -16,11 +16,11 @@ import copy import datetime import six -import uuid import mock from oslo_serialization import jsonutils from oslo_utils import timeutils +from oslo_utils import uuidutils from aodh import evaluator from aodh.evaluator import event as event_evaluator @@ -34,7 +34,7 @@ class TestEventAlarmEvaluate(base.TestEvaluatorBase): @staticmethod def _alarm(**kwargs): - alarm_id = kwargs.get('id') or str(uuid.uuid4()) + alarm_id = kwargs.get('id') or uuidutils.generate_uuid() return models.Alarm(name=kwargs.get('name', alarm_id), type='event', enabled=True, @@ -56,7 +56,7 @@ class TestEventAlarmEvaluate(base.TestEvaluatorBase): @staticmethod def _event(**kwargs): - return {'message_id': kwargs.get('id') or str(uuid.uuid4()), + return {'message_id': kwargs.get('id') or uuidutils.generate_uuid(), 'event_type': kwargs.get('event_type', 'type0'), 'traits': kwargs.get('traits', [])} @@ -193,7 +193,7 @@ class TestEventAlarmEvaluate(base.TestEvaluatorBase): def test_skip_event_missing_event_type(self): alarm = self._alarm() - event = {'message_id': str(uuid.uuid4()), 'traits': []} + event = {'message_id': uuidutils.generate_uuid(), 'traits': []} self._do_test_event_alarm( [alarm], [event], expect_alarm_states={alarm.alarm_id: evaluator.UNKNOWN}, diff --git a/aodh/tests/unit/evaluator/test_gnocchi.py b/aodh/tests/unit/evaluator/test_gnocchi.py index 6d00f4fa8..63aabd94b 100644 --- a/aodh/tests/unit/evaluator/test_gnocchi.py +++ b/aodh/tests/unit/evaluator/test_gnocchi.py @@ -15,11 +15,11 @@ import datetime import unittest -import uuid from gnocchiclient import exceptions import mock from oslo_utils import timeutils +from oslo_utils import uuidutils from oslotest import mockpatch import pytz import six @@ -43,7 +43,7 @@ class TestGnocchiEvaluatorBase(base.TestEvaluatorBase): enabled=True, user_id='foobar', project_id='snafu', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, @@ -75,7 +75,7 @@ class TestGnocchiEvaluatorBase(base.TestEvaluatorBase): ok_actions=[], alarm_actions=[], repeat_actions=False, - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), time_constraints=[], rule=dict( comparison_operator='le', @@ -92,7 +92,7 @@ class TestGnocchiEvaluatorBase(base.TestEvaluatorBase): enabled=True, user_id='foobar', project_id='snafu', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, diff --git a/aodh/tests/unit/evaluator/test_threshold.py b/aodh/tests/unit/evaluator/test_threshold.py index 1134215b0..1d487100c 100644 --- a/aodh/tests/unit/evaluator/test_threshold.py +++ b/aodh/tests/unit/evaluator/test_threshold.py @@ -17,12 +17,12 @@ import copy import datetime import json -import uuid from ceilometerclient import exc from ceilometerclient.v2 import statistics import mock from oslo_utils import timeutils +from oslo_utils import uuidutils import pytz from six import moves @@ -44,7 +44,7 @@ class TestEvaluate(base.TestEvaluatorBase): enabled=True, user_id='foobar', project_id='snafu', - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), state='insufficient data', state_timestamp=constants.MIN_DATETIME, timestamp=constants.MIN_DATETIME, @@ -81,7 +81,7 @@ class TestEvaluate(base.TestEvaluatorBase): ok_actions=[], alarm_actions=[], repeat_actions=False, - alarm_id=str(uuid.uuid4()), + alarm_id=uuidutils.generate_uuid(), time_constraints=[], rule=dict( comparison_operator='le', @@ -290,7 +290,7 @@ class TestEvaluate(base.TestEvaluatorBase): payloads.append(payload) return payloads - @mock.patch.object(uuid, 'uuid4') + @mock.patch.object(uuidutils, 'generate_uuid') @mock.patch.object(timeutils, 'utcnow') @mock.patch.object(messaging, 'get_notifier') def test_alarm_change_record(self, get_notifier, utcnow, mock_uuid):