blob: e69a39218507822d81954013550887de30401314 [file] [log] [blame]
Scott Bakerac43a742018-05-07 16:54:03 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# 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"""
17 sync_configmap.py
18
19 Synchronize Config Maps.
20"""
21
22import json
23from synchronizers.new_base.syncstep import SyncStep
24from synchronizers.new_base.modelaccessor import KubernetesConfigMap
25
26from xosconfig import Config
27from multistructlog import create_logger
28
29from kubernetes.client.rest import ApiException
30from kubernetes import client as kubernetes_client, config as kubernetes_config
31
32log = create_logger(Config().get('logging'))
33
34class SyncKubernetesConfigMap(SyncStep):
35
36 """
37 SyncKubernetesConfigMap
38
39 Implements sync step for syncing ConfigMaps.
40 """
41
42 provides = [KubernetesConfigMap]
43 observes = KubernetesConfigMap
44 requested_interval = 0
45
46 def __init__(self, *args, **kwargs):
47 super(SyncKubernetesConfigMap, self).__init__(*args, **kwargs)
48 kubernetes_config.load_incluster_config()
49 self.v1 = kubernetes_client.CoreV1Api()
50
51 def get_config_map(self, o):
52 """ Given an XOS KubernetesConfigMap object, read the corresponding ConfigMap from Kubernetes.
53 return None if no ConfigMap exists.
54 """
55 try:
56 config_map = self.v1.read_namespaced_config_map(o.name, o.trust_domain.name)
57 except ApiException, e:
58 if e.status == 404:
59 return None
60 raise
61 return config_map
62
63 def sync_record(self, o):
64 config_map = self.get_config_map(o)
65 if not config_map:
66 config_map = kubernetes_client.V1ConfigMap()
67 config_map.data = json.loads(o.data)
68 config_map.metadata = kubernetes_client.V1ObjectMeta(name=o.name)
69
70 config_map = self.v1.create_namespaced_config_map(o.trust_domain.name, config_map)
71 else:
72 config_map.data = json.loads(o.data)
73 self.v1.patch_namespaced_config_map(o.name, o.trust_domain.name, config_map)
74
75 if (not o.backend_handle):
76 o.backend_handle = config_map.metadata.self_link
77 o.save(update_fields=["backend_handle"])
78
79 def delete_record(self, port):
80 # TODO(smbaker): Implement delete step
81 pass
82