# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from oslo.config import cfg
import six

from st2common import log as logging
from st2common.constants.meta import ALLOWED_EXTS
from st2common.bootstrap.base import ResourceRegistrar
from st2common.content.loader import ContentPackLoader
from st2common.models.api.rule import RuleAPI
from st2common.persistence.reactor import Rule

LOG = logging.getLogger(__name__)


class RulesRegistrar(ResourceRegistrar):
    ALLOWED_EXTENSIONS = ALLOWED_EXTS

    def _get_rules_from_pack(self, rules_dir):
        return self._get_resources_from_pack(resources_dir=rules_dir)

    def _register_rules_from_pack(self, pack, rules):
        for rule in rules:
            LOG.debug('Loading rule from %s.', rule)
            try:
                content = self._meta_loader.load(rule)
                rule_api = RuleAPI(**content)
                rule_db = RuleAPI.to_model(rule_api)
                try:
                    rule_db.id = Rule.get_by_name(rule_api.name).id
                except ValueError:
                    LOG.info('Rule %s not found. Creating new one.', rule)
                try:
                    rule_db = Rule.add_or_update(rule_db)
                    LOG.audit('Rule updated. Rule %s from %s.', rule_db, rule)
                except Exception:
                    LOG.exception('Failed to create rule %s.', rule_api.name)
            except:
                LOG.exception('Failed registering rule from %s.', rule)

    def register_rules_from_packs(self, base_dir):
        pack_loader = ContentPackLoader()
        dirs = pack_loader.get_content(base_dir=base_dir,
                                       content_type='rules')
        for pack, rules_dir in six.iteritems(dirs):
            try:
                LOG.info('Registering rules from pack: %s', pack)
                rules = self._get_rules_from_pack(rules_dir)
                self._register_rules_from_pack(pack, rules)
            except:
                LOG.exception('Failed registering all rules from pack: %s', rules_dir)


def register_rules(packs_base_path=None):
    if not packs_base_path:
        packs_base_path = cfg.CONF.content.packs_base_path
    return RulesRegistrar().register_rules_from_packs(packs_base_path)

@@ -777,37 +777,8 @@
 e.%0A%0A
-%0Afrom oslo.config import cfg%0A
 impo
@@ -1074,16 +1074,122 @@
 ort Rule
+%0Aimport st2common.content.utils as content_utils%0A%0A__all__ = %5B%0A    'RulesRegistrar',%0A    'register_rules'%0A%5D
 %0A%0ALOG = 
@@ -2327,24 +2327,25 @@
 lf, base_dir
+s
 ):%0A        p
@@ -2385,20 +2385,23 @@
         
-dirs
+content
  = pack_
@@ -2427,16 +2427,17 @@
 base_dir
+s
 =base_di
@@ -2437,16 +2437,17 @@
 base_dir
+s
 ,%0A      
@@ -2475,24 +2475,27 @@
             
+   
 content_type
@@ -2549,20 +2549,23 @@
 eritems(
-dirs
+content
 ):%0A     
@@ -2910,16 +2910,17 @@
 path
+s
 =None):%0A
     
@@ -2915,16 +2915,93 @@
 =None):%0A
+    if packs_base_paths:%0A        assert(isinstance(packs_base_paths, list))%0A%0A
     if n
@@ -3018,16 +3018,17 @@
 ase_path
+s
 :%0A      
@@ -3048,28 +3048,30 @@
 path
+s
  = c
-fg.CONF.content.
+ontent_utils.get_
 pack
@@ -3081,16 +3081,20 @@
 ase_path
+s()%0A
 %0A    ret
@@ -3140,16 +3140,26 @@
 m_packs(
+base_dirs=
 packs_ba
@@ -3165,10 +3165,11 @@
 ase_path
+s
 )%0A

Update rules registrat so it supports multiple pack load paths.