blob: 903be4fbd2b96fcdf3546e5fc7492186eac9d096 [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_secret.py
18
19 Synchronize Secrets.
20"""
21
22import json
23from synchronizers.new_base.syncstep import SyncStep
24from synchronizers.new_base.modelaccessor import KubernetesSecret
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 SyncKubernetesSecret(SyncStep):
35
36 """
37 SyncKubernetesSecret
38
39 Implements sync step for syncing Secrets.
40 """
41
42 provides = [KubernetesSecret]
43 observes = KubernetesSecret
44 requested_interval = 0
45
46 def __init__(self, *args, **kwargs):
47 super(SyncKubernetesSecret, self).__init__(*args, **kwargs)
48 kubernetes_config.load_incluster_config()
49 self.v1 = kubernetes_client.CoreV1Api()
50
51 def get_secret(self, o):
52 """ Given an XOS KubernetesSecret object, read the corresponding Secret from Kubernetes.
53 return None if no Secret exists.
54 """
55 try:
56 secret = self.v1.read_namespaced_secret(o.name, o.trust_domain.name)
57 except ApiException, e:
58 if e.status == 404:
59 return None
60 raise
61 return secret
62
63 def sync_record(self, o):
64 secret = self.get_secret(o)
65 if not secret:
66 secret = kubernetes_client.V1Secret()
67 secret.data = json.loads(o.data)
68 secret.metadata = kubernetes_client.V1ObjectMeta(name=o.name)
69
70 secret = self.v1.create_namespaced_secret(o.trust_domain.name, secret)
71 else:
72 secret.data = json.loads(o.data)
73 self.v1.patch_namespaced_secret(o.name, o.trust_domain.name, secret)
74
75 if (not o.backend_handle):
76 o.backend_handle = secret.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