File: resources.py

package info (click to toggle)
senlin 14.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,448 kB
  • sloc: python: 72,605; sh: 586; makefile: 199
file content (291 lines) | stat: -rw-r--r-- 9,420 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#
#    Licensed 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.
# -*- coding: utf-8 -*-

from docutils import nodes
from docutils.parsers import rst
from docutils.parsers.rst import directives
from functools import cmp_to_key
from oslo_utils import importutils
from sphinx.util import logging

from senlin.common import schema

LOG = logging.getLogger(__name__)


class SchemaDirective(rst.Directive):
    required_arguments = 0
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {'package': directives.unchanged}
    has_content = False
    add_index = True
    section_title = 'Spec'
    properties_only = False

    def run(self):
        """Build doctree nodes consisting for the specified schema class

        :returns: doctree node list
        """

        # gives you access to the options of the directive
        options = self.options

        content = []

        # read in package class
        obj = importutils.import_class(options['package'])

        # skip other spec properties if properties_only is True
        if not self.properties_only:
            section = self._create_section(content, 'spec',
                                           title=self.section_title)

            # create version section
            version_section = self._create_section(section, 'version',
                                                   title='Latest Version')
            field = nodes.line('', obj.VERSION)
            version_section.append(field)

            # build versions table
            version_tbody = self._build_table(
                section, 'Available Versions',
                ['Version', 'Status', 'Supported Since'])
            sorted_versions = sorted(obj.VERSIONS.items())
            for version, support_status in sorted_versions:
                for support in support_status:
                    cells = [version]
                    sorted_support = sorted(support.items(), reverse=True)
                    cells += [x[1] for x in sorted_support]
                    self._create_table_row(cells, version_tbody)

            # create applicable profile types
            profile_type_description = ('This policy is designed to handle '
                                        'the following profile types:')
            profile_type_section = self._create_section(
                section, 'profile_types', title='Applicable Profile Types')
            field = nodes.line('', profile_type_description)
            profile_type_section.append(field)
            for profile_type in obj.PROFILE_TYPE:
                profile_type_section += self._create_list_item(profile_type)

            # create actions handled
            policy_trigger_description = ('This policy is triggered by the '
                                          'following actions during the '
                                          'respective phases:')
            target_tbody = self._build_table(
                section, 'Policy Triggers',
                ['Action', 'Phase'],
                policy_trigger_description
            )
            sorted_targets = sorted(obj.TARGET, key=lambda tup: tup[1])
            for phase, action in sorted_targets:
                cells = [action, phase]
                self._create_table_row(cells, target_tbody)

            # build properties
            properties_section = self._create_section(section, 'properties',
                                                      title='Properties')
        else:
            properties_section = content

        sorted_schema = sorted(obj.properties_schema.items(),
                               key=cmp_to_key(self._sort_by_type))
        for k, v in sorted_schema:
            self._build_properties(k, v, properties_section)

        # we return the result
        return content

    def _create_section(self, parent, sectionid, title=None, term=None):
        """Create a new section

        :returns: If term is specified, returns a definition node contained
        within the newly created section.  Otherwise return the newly created
        section node.
        """

        idb = nodes.make_id(sectionid)
        section = nodes.section(ids=[idb])
        parent.append(section)

        if term:
            if term != '**':
                section.append(nodes.term('', term))

            definition = nodes.definition()
            section.append(definition)

            return definition

        if title:
            section.append(nodes.title('', title))

        return section

    def _create_list_item(self, str):
        """Creates a new list item

        :returns: List item node
        """
        para = nodes.paragraph()
        para += nodes.strong('', str)

        item = nodes.list_item()
        item += para

        return item

    def _create_def_list(self, parent):
        """Creates a definition list

        :returns: Definition list node
        """

        definition_list = nodes.definition_list()
        parent.append(definition_list)

        return definition_list

    def _sort_by_type(self, x, y):
        """Sort two keys so that map and list types are ordered last."""

        x_key, x_value = x
        y_key, y_value = y

        # if both values are map or list, sort by their keys
        if ((isinstance(x_value, schema.Map) or
             isinstance(x_value, schema.List)) and
                (isinstance(y_value, schema.Map) or
                 isinstance(y_value, schema.List))):
            return (x_key > y_key) - (x_key < y_key)

        # show simple types before maps or list
        if (isinstance(x_value, schema.Map) or
                isinstance(x_value, schema.List)):
            return 1

        if (isinstance(y_value, schema.Map) or
                isinstance(y_value, schema.List)):
            return -1

        return (x_key > y_key) - (x_key < y_key)

    def _create_table_row(self, cells, parent):
        """Creates a table row for cell in cells

        :returns: Row node
        """

        row = nodes.row()
        parent.append(row)

        for c in cells:
            entry = nodes.entry()
            row += entry
            entry += nodes.literal(text=c)

        return row

    def _build_table(self, section, title, headers, description=None):
        """Creates a table with given title, headers and description

        :returns: Table body node
        """

        table_section = self._create_section(section, title, title=title)

        if description:
            field = nodes.line('', description)
            table_section.append(field)

        table = nodes.table()
        tgroup = nodes.tgroup(len(headers))
        table += tgroup

        table_section.append(table)

        for _ in headers:
            tgroup.append(nodes.colspec(colwidth=1))

        # create header
        thead = nodes.thead()
        tgroup += thead
        self._create_table_row(headers, thead)

        tbody = nodes.tbody()
        tgroup += tbody

        # create body consisting of targets
        tbody = nodes.tbody()
        tgroup += tbody

        return tbody

    def _build_properties(self, k, v, definition):
        """Build schema property documentation

        :returns: None
        """

        if isinstance(v, schema.Map):
            newdef = self._create_section(definition, k, term=k)

            if v.schema is None:
                # if it's a map for arbritary values, only include description
                field = nodes.line('', v.description)
                newdef.append(field)
                return

            newdeflist = self._create_def_list(newdef)

            sorted_schema = sorted(v.schema.items(),
                                   key=cmp_to_key(self._sort_by_type))
            for key, value in sorted_schema:
                self._build_properties(key, value, newdeflist)
        elif isinstance(v, schema.List):
            newdef = self._create_section(definition, k, term=k)

            # identify next section as list properties
            field = nodes.line()
            emph = nodes.emphasis('', 'List properties:')
            field.append(emph)
            newdef.append(field)

            newdeflist = self._create_def_list(newdef)

            self._build_properties('**', v.schema['*'], newdeflist)
        else:
            newdef = self._create_section(definition, k, term=k)
            if 'description' in v:
                field = nodes.line('', v['description'])
                newdef.append(field)
            else:
                field = nodes.line('', '++')
                newdef.append(field)


class SchemaProperties(SchemaDirective):
    properties_only = True


class SchemaSpec(SchemaDirective):
    section_title = 'Spec'
    properties_only = False


def setup(app):
    app.add_directive('schemaprops', SchemaProperties)
    app.add_directive('schemaspec', SchemaSpec)