Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame^] | 1 | """ |
| 2 | Copyright 2020 The Magma Authors. |
| 3 | |
| 4 | This source code is licensed under the BSD-style license found in the |
| 5 | LICENSE file in the root directory of this source tree. |
| 6 | |
| 7 | Unless required by applicable law or agreed to in writing, software |
| 8 | distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | See the License for the specific language governing permissions and |
| 11 | limitations under the License. |
| 12 | """ |
| 13 | |
| 14 | from typing import Any as TAny |
| 15 | from typing import Dict |
| 16 | |
| 17 | from google.protobuf.internal.well_known_types import Any |
| 18 | from configuration import service_configs |
| 19 | from configuration.exceptions import LoadConfigError |
| 20 | |
| 21 | |
| 22 | def 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 | |
| 49 | def 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 |