Test Failed
Pull Request — master (#3658)
by Lakshmi
05:04
created

get_pack_common_libs_path()   A

Complexity

Conditions 2

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
dl 0
loc 23
rs 9.0856
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  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 implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import os
17
import re
18
19
import jsonschema
20
21
from st2common.util import schema as util_schema
22
from st2common.constants.pack import MANIFEST_FILE_NAME
23
from st2common.constants.pack import PACK_REF_WHITELIST_REGEX
24
from st2common.content.loader import MetaLoader
25
26
__all__ = [
27
    'get_pack_ref_from_metadata',
28
    'get_pack_metadata',
29
    'get_pack_path_from_metadata',
0 ignored issues
show
Bug introduced by
Undefined variable name 'get_pack_path_from_metadata' in __all__
Loading history...
30
31
    'validate_config_against_schema',
32
33
    'normalize_pack_version'
34
]
35
36
37
def get_pack_ref_from_metadata(metadata, pack_directory_name=None):
38
    """
39
    Utility function which retrieves pack "ref" attribute from the pack metadata file.
40
41
    If this attribute is not provided, an attempt is made to infer "ref" from the "name" attribute.
42
43
    :rtype: ``str``
44
    """
45
    pack_ref = None
46
47
    # The rules for the pack ref are as follows:
48
    # 1. If ref attribute is available, we used that
49
    # 2. If pack_directory_name is available we use that (this only applies to packs
50
    # which are in sub-directories)
51
    # 2. If attribute is not available, but pack name is and pack name meets the valid name
52
    # criteria, we use that
53
    if metadata.get('ref', None):
54
        pack_ref = metadata['ref']
55
    elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name):
56
        pack_ref = pack_directory_name
57
    else:
58
        if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']):
59
            pack_ref = metadata['name']
60
        else:
61
            msg = ('Pack name "%s" contains invalid characters and "ref" attribute is not '
62
                   'available. You either need to add "ref" attribute which contains only word '
63
                   'characters to the pack metadata file or update name attribute to contain only'
64
                   'word characters.')
65
            raise ValueError(msg % (metadata['name']))
66
67
    return pack_ref
68
69
70
def get_pack_metadata(pack_dir):
71
    """
72
    Return parsed metadata for a particular pack directory.
73
74
    :rtype: ``dict``
75
    """
76
    manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME)
77
78
    if not os.path.isfile(manifest_path):
79
        raise ValueError('Pack "%s" is missing %s file' % (pack_dir, MANIFEST_FILE_NAME))
80
81
    meta_loader = MetaLoader()
82
    content = meta_loader.load(manifest_path)
83
    if not content:
84
        raise ValueError('Pack "%s" metadata file is empty' % (pack_dir))
85
86
    return content
87
88
89
def validate_config_against_schema(config_schema, config_object, config_path,
90
                                  pack_name=None):
91
    """
92
    Validate provided config dictionary against the provided config schema
93
    dictionary.
94
    """
95
    pack_name = pack_name or 'unknown'
96
97
    schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema,
98
                                                            allow_additional_properties=True)
99
    instance = config_object
100
101
    try:
102
        cleaned = util_schema.validate(instance=instance, schema=schema,
103
                                       cls=util_schema.CustomValidator, use_default=True,
104
                                       allow_default_none=True)
105
    except jsonschema.ValidationError as e:
106
        attribute = getattr(e, 'path', [])
107
        attribute = '.'.join(attribute)
108
109
        msg = ('Failed validating attribute "%s" in config for pack "%s" (%s): %s' %
110
               (attribute, pack_name, config_path, str(e)))
111
        raise jsonschema.ValidationError(msg)
112
113
    return cleaned
114
115
116
def get_pack_common_libs_path(pack_db):
117
    """
118
    Return the pack's common lib path. This is the path where common code for sensors
119
    and actions are placed.
120
121
    For example, if the pack is at /opt/stackstorm/packs/my_pack, you can place
122
    common library code for actions and sensors in /opt/stackstorm/packs/my_pack/lib/.
123
    This common library code is only available for python sensors and actions. The lib
124
    structure also needs to follow a python convention with a __init__.py file.
125
126
    :param pack_db: Pack DB model
127
    :type pack_db: :class:`PackDB`
128
129
    :rtype: ``str``
130
    """
131
    pack_dir = getattr(pack_db, 'path', None)
132
133
    if not pack_dir:
134
        return None
135
136
    libs_path = os.path.join(pack_dir, 'lib')
137
138
    return libs_path
139
140
141
def normalize_pack_version(version):
142
    """
143
    Normalize old, pre StackStorm v2.1 non valid semver version string (e.g. 0.2) to a valid
144
    semver version string (0.2.0).
145
146
    :rtype: ``str``
147
    """
148
    version = str(version)
149
150
    version_seperator_count = version.count('.')
151
    if version_seperator_count == 1:
152
        version = version + '.0'
153
154
    return version
155