summaryrefslogtreecommitdiffstats
path: root/compass-deck/db/api/metadata_holder.py
blob: 24afc673ea2257665900c13eb0565629fa984280 (plain)
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# Copyright 2014 Huawei Technologies Co. Ltd
#
# 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.

"""Metadata related object holder."""
import logging

from compass.db.api import adapter as adapter_api
from compass.db.api import adapter_holder as adapter_holder_api
from compass.db.api import database
from compass.db.api import metadata as metadata_api
from compass.db.api import permission
from compass.db.api import user as user_api
from compass.db.api import utils
from compass.db import exception
from compass.db import models
from compass.utils import setting_wrapper as setting
from compass.utils import util


RESP_METADATA_FIELDS = [
    'os_config', 'package_config'
]
RESP_UI_METADATA_FIELDS = [
    'os_global_config', 'flavor_config'
]


def load_metadatas(force_reload=False):
    """Load metadatas."""
    # TODO(xicheng): today we load metadata in memory as it original
    # format in files in metadata.py. We get these inmemory metadata
    # and do some translation, store the translated metadata into memory
    # too in metadata_holder.py. api can only access the global inmemory
    # data in metadata_holder.py.
    _load_os_metadatas(force_reload=force_reload)
    _load_package_metadatas(force_reload=force_reload)
    _load_flavor_metadatas(force_reload=force_reload)
    _load_os_metadata_ui_converters(force_reload=force_reload)
    _load_flavor_metadata_ui_converters(force_reload=force_reload)


def _load_os_metadata_ui_converters(force_reload=False):
    global OS_METADATA_UI_CONVERTERS
    if force_reload or OS_METADATA_UI_CONVERTERS is None:
        logging.info('load os metadatas ui converters into memory')
        OS_METADATA_UI_CONVERTERS = (
            metadata_api.get_oses_metadata_ui_converters_internal(
                force_reload=force_reload
            )
        )


def _load_os_metadatas(force_reload=False):
    """Load os metadata from inmemory db and map it by os_id."""
    global OS_METADATA_MAPPING
    if force_reload or OS_METADATA_MAPPING is None:
        logging.info('load os metadatas into memory')
        OS_METADATA_MAPPING = metadata_api.get_oses_metadata_internal(
            force_reload=force_reload
        )


def _load_flavor_metadata_ui_converters(force_reload=False):
    """Load flavor metadata ui converters from inmemory db.

    The loaded metadata is mapped by flavor id.
    """
    global FLAVOR_METADATA_UI_CONVERTERS
    if force_reload or FLAVOR_METADATA_UI_CONVERTERS is None:
        logging.info('load flavor metadata ui converters into memory')
        FLAVOR_METADATA_UI_CONVERTERS = {}
        adapters_flavors_metadata_ui_converters = (
            metadata_api.get_flavors_metadata_ui_converters_internal(
                force_reload=force_reload
            )
        )
        for adapter_name, adapter_flavors_metadata_ui_converters in (
            adapters_flavors_metadata_ui_converters.items()
        ):
            for flavor_name, flavor_metadata_ui_converter in (
                adapter_flavors_metadata_ui_converters.items()
            ):
                FLAVOR_METADATA_UI_CONVERTERS[
                    '%s:%s' % (adapter_name, flavor_name)
                ] = flavor_metadata_ui_converter


@util.deprecated
def _load_package_metadatas(force_reload=False):
    """Load deployable package metadata from inmemory db."""
    global PACKAGE_METADATA_MAPPING
    if force_reload or PACKAGE_METADATA_MAPPING is None:
        logging.info('load package metadatas into memory')
        PACKAGE_METADATA_MAPPING = (
            metadata_api.get_packages_metadata_internal(
                force_reload=force_reload
            )
        )


def _load_flavor_metadatas(force_reload=False):
    """Load flavor metadata from inmemory db.

    The loaded metadata are mapped by flavor id.
    """
    global FLAVOR_METADATA_MAPPING
    if force_reload or FLAVOR_METADATA_MAPPING is None:
        logging.info('load flavor metadatas into memory')
        FLAVOR_METADATA_MAPPING = {}
        adapters_flavors_metadata = (
            metadata_api.get_flavors_metadata_internal(
                force_reload=force_reload
            )
        )
        for adapter_name, adapter_flavors_metadata in (
            adapters_flavors_metadata.items()
        ):
            for flavor_name, flavor_metadata in (
                adapter_flavors_metadata.items()
            ):
                FLAVOR_METADATA_MAPPING[
                    '%s:%s' % (adapter_name, flavor_name)
                ] = flavor_metadata


OS_METADATA_MAPPING = None
PACKAGE_METADATA_MAPPING = None
FLAVOR_METADATA_MAPPING = None
OS_METADATA_UI_CONVERTERS = None
FLAVOR_METADATA_UI_CONVERTERS = None


def validate_os_config(
    config, os_id, whole_check=False, **kwargs
):
    """Validate os config."""
    load_metadatas()
    if os_id not in OS_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'os %s is not found in os metadata mapping' % os_id
        )
    _validate_config(
        '', config, OS_METADATA_MAPPING[os_id],
        whole_check, **kwargs
    )


@util.deprecated
def validate_package_config(
    config, adapter_id, whole_check=False, **kwargs
):
    """Validate package config."""
    load_metadatas()
    if adapter_id not in PACKAGE_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'adapter %s is not found in package metedata mapping' % adapter_id
        )
    _validate_config(
        '', config, PACKAGE_METADATA_MAPPING[adapter_id],
        whole_check, **kwargs
    )


def validate_flavor_config(
    config, flavor_id, whole_check=False, **kwargs
):
    """Validate flavor config."""
    load_metadatas()
    if not flavor_id:
        logging.info('There is no flavor, skipping flavor validation...')
    elif flavor_id not in FLAVOR_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'flavor %s is not found in flavor metedata mapping' % flavor_id
        )
    else:
        _validate_config(
            '', config, FLAVOR_METADATA_MAPPING[flavor_id],
            whole_check, **kwargs
        )


def _filter_metadata(metadata, **kwargs):
    """Filter metadata before return it to api.

    Some metadata fields are not json compatible or
    only used in db/api internally.
    We should strip these fields out before return to api.
    """
    if not isinstance(metadata, dict):
        return metadata
    filtered_metadata = {}
    for key, value in metadata.items():
        if key == '_self':
            filtered_metadata[key] = {
                'name': value['name'],
                'description': value.get('description', None),
                'default_value': value.get('default_value', None),
                'is_required': value.get('is_required', False),
                'required_in_whole_config': value.get(
                    'required_in_whole_config', False),
                'js_validator': value.get('js_validator', None),
                'options': value.get('options', None),
                'required_in_options': value.get(
                    'required_in_options', False),
                'field_type': value.get(
                    'field_type_data', 'str'),
                'display_type': value.get('display_type', None),
                'mapping_to': value.get('mapping_to', None)
            }
        else:
            filtered_metadata[key] = _filter_metadata(value, **kwargs)
    return filtered_metadata


@util.deprecated
def _get_package_metadata(adapter_id):
    """get package metadata."""
    load_metadatas()
    if adapter_id not in PACKAGE_METADATA_MAPPING:
        raise exception.RecordNotExists(
            'adpater %s does not exist' % adapter_id
        )
    return _filter_metadata(
        PACKAGE_METADATA_MAPPING[adapter_id]
    )


@util.deprecated
@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_package_metadata(adapter_id, user=None, session=None, **kwargs):
    """Get package metadata from adapter."""
    return {
        'package_config': _get_package_metadata(adapter_id)
    }


def _get_flavor_metadata(flavor_id):
    """get flavor metadata."""
    load_metadatas()
    if not flavor_id:
        logging.info('There is no flavor id, skipping...')
    elif flavor_id not in FLAVOR_METADATA_MAPPING:
        raise exception.RecordNotExists(
            'flavor %s does not exist' % flavor_id
        )
    else:
        return _filter_metadata(FLAVOR_METADATA_MAPPING[flavor_id])


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_flavor_metadata(flavor_id, user=None, session=None, **kwargs):
    """Get flavor metadata by flavor."""
    return {
        'package_config': _get_flavor_metadata(flavor_id)
    }


def _get_os_metadata(os_id):
    """get os metadata."""
    load_metadatas()
    if os_id not in OS_METADATA_MAPPING:
        raise exception.RecordNotExists(
            'os %s does not exist' % os_id
        )
    return _filter_metadata(OS_METADATA_MAPPING[os_id])


def _get_os_metadata_ui_converter(os_id):
    """get os metadata ui converter."""
    load_metadatas()
    if os_id not in OS_METADATA_UI_CONVERTERS:
        raise exception.RecordNotExists(
            'os %s does not exist' % os_id
        )
    return OS_METADATA_UI_CONVERTERS[os_id]


def _get_flavor_metadata_ui_converter(flavor_id):
    """get flavor metadata ui converter."""
    load_metadatas()
    if flavor_id not in FLAVOR_METADATA_UI_CONVERTERS:
        raise exception.RecordNotExists(
            'flavor %s does not exist' % flavor_id
        )
    return FLAVOR_METADATA_UI_CONVERTERS[flavor_id]


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_os_metadata(os_id, user=None, session=None, **kwargs):
    """get os metadatas."""
    return {'os_config': _get_os_metadata(os_id)}


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_UI_METADATA_FIELDS)
def get_os_ui_metadata(os_id, user=None, session=None, **kwargs):
    """Get os metadata ui converter by os."""
    metadata = _get_os_metadata(os_id)
    metadata_ui_converter = _get_os_metadata_ui_converter(os_id)
    return _get_ui_metadata(metadata, metadata_ui_converter)


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_UI_METADATA_FIELDS)
def get_flavor_ui_metadata(flavor_id, user=None, session=None, **kwargs):
    """Get flavor ui metadata by flavor."""
    metadata = _get_flavor_metadata(flavor_id)
    metadata_ui_converter = _get_flavor_metadata_ui_converter(flavor_id)
    return _get_ui_metadata(metadata, metadata_ui_converter)


def _get_ui_metadata(metadata, metadata_ui_converter):
    """convert metadata to ui metadata.

     Args:
        metadata: metadata we defined in metadata files.
        metadata_ui_converter: metadata ui converter defined in metadata
                               mapping files. Used to convert orignal
                               metadata to ui understandable metadata.

     Returns:
        ui understandable metadata.
     """
    ui_metadata = {}
    ui_metadata[metadata_ui_converter['mapped_name']] = []
    for mapped_child in metadata_ui_converter['mapped_children']:
        data_dict = {}
        for ui_key, ui_value in mapped_child.items():
            for key, value in ui_value.items():
                if 'data' == key:
                    result_data = []
                    _get_ui_metadata_data(
                        metadata[ui_key], value, result_data
                    )
                    data_dict['data'] = result_data
                else:
                    data_dict[key] = value
        ui_metadata[metadata_ui_converter['mapped_name']].append(data_dict)
    return ui_metadata


def _get_ui_metadata_data(metadata, config, result_data):
    """Get ui metadata data and fill to result."""
    data_dict = {}
    for key, config_value in config.items():
        if isinstance(config_value, dict) and key != 'content_data':
            if key in metadata.keys():
                _get_ui_metadata_data(metadata[key], config_value, result_data)
            else:
                _get_ui_metadata_data(metadata, config_value, result_data)
        elif isinstance(config_value, list):
            option_list = []
            for item in config_value:
                if isinstance(item, dict):
                    option_list.append(item)
                    data_dict[key] = option_list
                else:
                    if isinstance(metadata['_self'][item], bool):
                        data_dict[item] = str(metadata['_self'][item]).lower()
                    else:
                        data_dict[item] = metadata['_self'][item]
        else:
            data_dict[key] = config_value
    if data_dict:
        result_data.append(data_dict)
    return result_data


@util.deprecated
@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_package_os_metadata(
    adapter_id, os_id,
    user=None, session=None, **kwargs
):
    """Get metadata by adapter and os."""
    adapter = adapter_holder_api.get_adapter(
        adapter_id, user=user, session=session
    )
    os_ids = [os['id'] for os in adapter['supported_oses']]
    if os_id not in os_ids:
        raise exception.InvalidParameter(
            'os %s is not in the supported os list of adapter %s' % (
                os_id, adapter_id
            )
        )
    metadatas = {}
    metadatas['os_config'] = _get_os_metadata(
        os_id
    )
    metadatas['package_config'] = _get_package_metadata(
        adapter_id
    )
    return metadatas


@utils.supported_filters([])
@database.run_in_session()
@user_api.check_user_permission(
    permission.PERMISSION_LIST_METADATAS
)
@utils.wrap_to_dict(RESP_METADATA_FIELDS)
def get_flavor_os_metadata(
    flavor_id, os_id,
    user=None, session=None, **kwargs
):
    """Get metadata by flavor and os."""
    flavor = adapter_holder_api.get_flavor(
        flavor_id, user=user, session=session
    )
    adapter_id = flavor['adapter_id']
    adapter = adapter_holder_api.get_adapter(
        adapter_id, user=user, session=session
    )
    os_ids = [os['id'] for os in adapter['supported_oses']]
    if os_id not in os_ids:
        raise exception.InvalidParameter(
            'os %s is not in the supported os list of adapter %s' % (
                os_id, adapter_id
            )
        )
    metadatas = {}
    metadatas['os_config'] = _get_os_metadata(
        session, os_id
    )
    metadatas['package_config'] = _get_flavor_metadata(
        session, flavor_id
    )
    return metadatas


def _validate_self(
    config_path, config_key, config,
    metadata, whole_check,
    **kwargs
):
    """validate config by metadata self section."""
    logging.debug('validate config self %s', config_path)
    if '_self' not in metadata:
        if isinstance(config, dict):
            _validate_config(
                config_path, config, metadata, whole_check, **kwargs
            )
        return
    field_type = metadata['_self'].get('field_type', basestring)
    if not isinstance(config, field_type):
        raise exception.InvalidParameter(
            '%s config type is not %s: %s' % (config_path, field_type, config)
        )
    is_required = metadata['_self'].get(
        'is_required', False
    )
    required_in_whole_config = metadata['_self'].get(
        'required_in_whole_config', False
    )
    if isinstance(config, basestring):
        if config == '' and not is_required and not required_in_whole_config:
            # ignore empty config when it is optional
            return
    required_in_options = metadata['_self'].get(
        'required_in_options', False
    )
    options = metadata['_self'].get('options', None)
    if required_in_options:
        if field_type in [int, basestring, float, bool]:
            if options and config not in options:
                raise exception.InvalidParameter(
                    '%s config is not in %s: %s' % (
                        config_path, options, config
                    )
                )
        elif field_type in [list, tuple]:
            if options and not set(config).issubset(set(options)):
                raise exception.InvalidParameter(
                    '%s config is not in %s: %s' % (
                        config_path, options, config
                    )
                )
        elif field_type == dict:
            if options and not set(config.keys()).issubset(set(options)):
                raise exception.InvalidParameter(
                    '%s config is not in %s: %s' % (
                        config_path, options, config
                    )
                )
    validator = metadata['_self'].get('validator', None)
    logging.debug('validate by validator %s', validator)
    if validator:
        if not validator(config_key, config, **kwargs):
            raise exception.InvalidParameter(
                '%s config is invalid' % config_path
            )
    if isinstance(config, dict):
        _validate_config(
            config_path, config, metadata, whole_check, **kwargs
        )


def _validate_config(
    config_path, config, metadata, whole_check,
    **kwargs
):
    """validate config by metadata."""
    logging.debug('validate config %s', config_path)
    generals = {}
    specified = {}
    for key, value in metadata.items():
        if key.startswith('$'):
            generals[key] = value
        elif key.startswith('_'):
            pass
        else:
            specified[key] = value
    config_keys = set(config.keys())
    specified_keys = set(specified.keys())
    intersect_keys = config_keys & specified_keys
    not_found_keys = config_keys - specified_keys
    redundant_keys = specified_keys - config_keys
    for key in redundant_keys:
        if '_self' not in specified[key]:
            continue
        if specified[key]['_self'].get('is_required', False):
            raise exception.InvalidParameter(
                '%s/%s does not find but it is required' % (
                    config_path, key
                )
            )
        if (
            whole_check and
            specified[key]['_self'].get(
                'required_in_whole_config', False
            )
        ):
            raise exception.InvalidParameter(
                '%s/%s does not find but it is required in whole config' % (
                    config_path, key
                )
            )
    for key in intersect_keys:
        _validate_self(
            '%s/%s' % (config_path, key),
            key, config[key], specified[key], whole_check,
            **kwargs
        )
    for key in not_found_keys:
        if not generals:
            raise exception.InvalidParameter(
                'key %s missing in metadata %s' % (
                    key, config_path
                )
            )
        for general_key, general_value in generals.items():
            _validate_self(
                '%s/%s' % (config_path, key),
                key, config[key], general_value, whole_check,
                **kwargs
            )


def _autofill_self_config(
    config_path, config_key, config,
    metadata,
    **kwargs
):
    """Autofill config by metadata self section."""
    if '_self' not in metadata:
        if isinstance(config, dict):
            _autofill_config(
                config_path, config, metadata, **kwargs
            )
        return config
    logging.debug(
        'autofill %s by metadata %s', config_path, metadata['_self']
    )
    autofill_callback = metadata['_self'].get(
        'autofill_callback', None
    )
    autofill_callback_params = metadata['_self'].get(
        'autofill_callback_params', {}
    )
    callback_params = dict(kwargs)
    if autofill_callback_params:
        callback_params.update(autofill_callback_params)
    default_value = metadata['_self'].get(
        'default_value', None
    )
    if default_value is not None:
        callback_params['default_value'] = default_value
    options = metadata['_self'].get(
        'options', None
    )
    if options is not None:
        callback_params['options'] = options
    if autofill_callback:
        config = autofill_callback(
            config_key, config, **callback_params
        )
    if config is None:
        new_config = {}
    else:
        new_config = config
    if isinstance(new_config, dict):
        _autofill_config(
            config_path, new_config, metadata, **kwargs
        )
        if new_config:
            config = new_config
    return config


def _autofill_config(
    config_path, config, metadata, **kwargs
):
    """autofill config by metadata."""
    generals = {}
    specified = {}
    for key, value in metadata.items():
        if key.startswith('$'):
            generals[key] = value
        elif key.startswith('_'):
            pass
        else:
            specified[key] = value
    config_keys = set(config.keys())
    specified_keys = set(specified.keys())
    intersect_keys = config_keys & specified_keys
    not_found_keys = config_keys - specified_keys
    redundant_keys = specified_keys - config_keys
    for key in redundant_keys:
        self_config = _autofill_self_config(
            '%s/%s' % (config_path, key),
            key, None, specified[key], **kwargs
        )
        if self_config is not None:
            config[key] = self_config
    for key in intersect_keys:
        config[key] = _autofill_self_config(
            '%s/%s' % (config_path, key),
            key, config[key], specified[key],
            **kwargs
        )
    for key in not_found_keys:
        for general_key, general_value in generals.items():
            config[key] = _autofill_self_config(
                '%s/%s' % (config_path, key),
                key, config[key], general_value,
                **kwargs
            )
    return config


def autofill_os_config(
    config, os_id, **kwargs
):
    load_metadatas()
    if os_id not in OS_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'os %s is not found in os metadata mapping' % os_id
        )

    return _autofill_config(
        '', config, OS_METADATA_MAPPING[os_id], **kwargs
    )


def autofill_package_config(
    config, adapter_id, **kwargs
):
    load_metadatas()
    if adapter_id not in PACKAGE_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'adapter %s is not found in package metadata mapping' % adapter_id
        )

    return _autofill_config(
        '', config, PACKAGE_METADATA_MAPPING[adapter_id], **kwargs
    )


def autofill_flavor_config(
    config, flavor_id, **kwargs
):
    load_metadatas()
    if not flavor_id:
        logging.info('There is no flavor, skipping...')
    elif flavor_id not in FLAVOR_METADATA_MAPPING:
        raise exception.InvalidParameter(
            'flavor %s is not found in flavor metadata mapping' % flavor_id
        )
    else:
        return _autofill_config(
            '', config, FLAVOR_METADATA_MAPPING[flavor_id], **kwargs
        )