This repository has been archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
requires.py
72 lines (62 loc) · 2.83 KB
/
requires.py
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
#!/usr/bin/python
# 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.
import os
from charms.reactive import RelationBase
from charms.reactive import hook
from charms.reactive import scopes
class EtcdClientProxy(RelationBase):
scope = scopes.GLOBAL
@hook('{requires:etcd-proxy}-relation-{joined,changed}')
def changed(self):
self.set_state('{relation_name}.connected')
if self.get_cluster_string():
self.set_state('{relation_name}.available')
# Get the ca, key, cert from the relation data.
cert = self.get_client_credentials()
# The tls state depends on the existance of the ca, key and cert.
if cert['client_cert'] and cert['client_key'] and cert['client_ca']: # noqa
self.set_state('{relation_name}.tls.available')
@hook('{requires:etcd-proxy}-relation-{broken, departed}')
def broken(self):
self.remove_state('{relation_name}.available')
self.remove_state('{relation_name}.connected')
self.remove_state('{relation_name}.tls.available')
def get_cluster_string(self):
''' Return the connection string, if available, or None. '''
return self.get_remote('cluster')
def get_client_credentials(self):
''' Return a dict with the client certificate, ca and key to
communicate with etcd using tls. '''
return {'client_cert': self.get_remote('client_cert'),
'client_key': self.get_remote('client_key'),
'client_ca': self.get_remote('client_ca')}
def cluster_string(self):
"""
Get the cluster string, if available, or None.
"""
return self.get_cluster_string()
def save_client_credentials(self, key, cert, ca):
''' Save all the client certificates for etcd to local files. '''
self._save_remote_data('client_cert', cert)
self._save_remote_data('client_key', key)
self._save_remote_data('client_ca', ca)
def _save_remote_data(self, key, path):
''' Save the remote data to a file indicated by path creating the
parent directory if needed.'''
value = self.get_remote(key)
if value:
parent = os.path.dirname(path)
if not os.path.isdir(parent):
os.makedirs(parent)
with open(path, 'w') as stream:
stream.write(value)