Coverage for watcher/decision_engine/strategy/selection/default.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.8.2, created at 2025-06-17 12:22 +0000

1# -*- encoding: utf-8 -*- 

2# Copyright (c) 2015 b<>com 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 

13# implied. 

14# See the License for the specific language governing permissions and 

15# limitations under the License. 

16 

17from oslo_log import log 

18 

19from watcher._i18n import _ 

20from watcher.common import exception 

21from watcher.decision_engine.loading import default 

22from watcher.decision_engine.strategy.selection import base 

23 

24LOG = log.getLogger(__name__) 

25 

26 

27class DefaultStrategySelector(base.BaseSelector): 

28 

29 def __init__(self, goal_name, strategy_name=None, osc=None): 

30 """Default strategy selector 

31 

32 :param goal_name: Name of the goal 

33 :param strategy_name: Name of the strategy 

34 :param osc: an OpenStackClients instance 

35 """ 

36 super(DefaultStrategySelector, self).__init__() 

37 self.goal_name = goal_name 

38 self.strategy_name = strategy_name 

39 self.osc = osc 

40 self.strategy_loader = default.DefaultStrategyLoader() 

41 

42 def select(self): 

43 """Selects a strategy 

44 

45 :raises: :py:class:`~.LoadingError` if it failed to load a strategy 

46 :returns: A :py:class:`~.BaseStrategy` instance 

47 """ 

48 strategy_to_load = None 

49 try: 

50 if self.strategy_name: 

51 strategy_to_load = self.strategy_name 

52 else: 

53 available_strategies = self.strategy_loader.list_available() 

54 available_strategies_for_goal = list( 

55 key for key, strategy in available_strategies.items() 

56 if strategy.get_goal_name() == self.goal_name) 

57 

58 if not available_strategies_for_goal: 

59 raise exception.NoAvailableStrategyForGoal( 

60 goal=self.goal_name) 

61 

62 # TODO(v-francoise): We should do some more work here to select 

63 # a strategy out of a given goal instead of just choosing the 

64 # 1st one 

65 strategy_to_load = available_strategies_for_goal[0] 

66 return self.strategy_loader.load(strategy_to_load, osc=self.osc) 

67 except exception.NoAvailableStrategyForGoal: 

68 raise 

69 except Exception as exc: 

70 LOG.exception(exc) 

71 raise exception.LoadingError( 

72 _("Could not load any strategy for goal %(goal)s"), 

73 goal=self.goal_name)