changed/added license heading. Moved some json files to yaml
[osm/openvim.git] / charm / openvim / interface-openvim / requires.py
1 ##
2 # Copyright 2016
3 # This file is part of openvim
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16 #
17 ##
18
19 from charms.reactive import hook
20 from charms.reactive import RelationBase
21 from charms.reactive import scopes
22
23
24 class OpenVimRequires(RelationBase):
25 scope = scopes.UNIT
26
27 @hook('{requires:openvim}-relation-{joined,changed}')
28 def changed(self):
29 conv = self.conversation()
30 if conv.get_remote('port'):
31 # this unit's conversation has a port, so
32 # it is part of the set of available units
33 conv.set_state('{relation_name}.available')
34
35 @hook('{requires:openvim}-relation-{departed,broken}')
36 def broken(self):
37 conv = self.conversation()
38 conv.remove_state('{relation_name}.available')
39
40 def services(self):
41 """
42 Returns a list of available openvim services and their associated hosts
43 and ports.
44
45 The return value is a list of dicts of the following form::
46
47 [
48 {
49 'service_name': name_of_service,
50 'hosts': [
51 {
52 'hostname': address_of_host,
53 'port': port_for_host,
54 'user': user_for_host,
55 },
56 # ...
57 ],
58 },
59 # ...
60 ]
61 """
62 services = {}
63 for conv in self.conversations():
64 service_name = conv.scope.split('/')[0]
65 service = services.setdefault(service_name, {
66 'service_name': service_name,
67 'hosts': [],
68 })
69 host = conv.get_remote('hostname') or \
70 conv.get_remote('private-address')
71 port = conv.get_remote('port')
72 user = conv.get_remote('user')
73 if host and port:
74 service['hosts'].append({
75 'hostname': host,
76 'port': port,
77 'user': user,
78 })
79 return [s for s in services.values() if s['hosts']]