blob: 88862b538304ac833df3ca33a16e1a43e951e7f1 [file] [log] [blame]
Wei-Yu Chen49950b92021-11-08 19:19:18 +08001"""
2Copyright 2020 The Magma Authors.
3
4This source code is licensed under the BSD-style license found in the
5LICENSE file in the root directory of this source tree.
6
7Unless required by applicable law or agreed to in writing, software
8distributed under the License is distributed on an "AS IS" BASIS,
9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10See the License for the specific language governing permissions and
11limitations under the License.
12"""
13
14from typing import Any as TAny
15from typing import Dict
16
17from google.protobuf.internal.well_known_types import Any
18from configuration import service_configs
19from configuration.exceptions import LoadConfigError
20
21
22def filter_configs_by_key(configs_by_key: Dict[str, TAny]) -> Dict[str, TAny]:
23 """
24 Given a JSON-deserialized map of mconfig protobuf Any's keyed by service
25 name, filter out any entires without a corresponding service or which have
26 values that aren't registered in the protobuf symbol database yet.
27
28 Args:
29 configs_by_key:
30 JSON-deserialized service mconfigs keyed by service name
31
32 Returns:
33 The input map without any services which currently don't exist.
34 """
35 magmad_cfg = service_configs.load_service_config('magmad')
36 services = magmad_cfg.get('magma_services', [])
37 services.append('magmad')
38 services += magmad_cfg.get('registered_dynamic_services', [])
39 services = set(services)
40
41 filtered_configs_by_key = {}
42 for srv, cfg in configs_by_key.items():
43 if srv not in services:
44 continue
45 filtered_configs_by_key[srv] = cfg
46 return filtered_configs_by_key
47
48
49def unpack_mconfig_any(mconfig_any: Any, mconfig_struct: TAny) -> TAny:
50 """
51 Unpack a protobuf Any type into a given an empty protobuf message struct
52 for a service.
53
54 Args:
55 mconfig_any: protobuf Any type to unpack
56 mconfig_struct: protobuf message struct
57
58 Returns: Concrete protobuf object that the provided Any wraps
59 """
60 unpacked = mconfig_any.Unpack(mconfig_struct)
61 if not unpacked:
62 raise LoadConfigError(
63 'Cannot unpack Any type into message: %s' % mconfig_struct,
64 )
65 return mconfig_struct