/
adapters.py
1251 lines (1070 loc) · 46.4 KB
/
adapters.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016 Canonical Ltd
#
# 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.
"""Adapter classes and utilities for use with Reactive interfaces"""
from __future__ import absolute_import
import collections
import itertools
import re
import weakref
import charms.reactive.relations as relations
import charms.reactive.bus
import charmhelpers.contrib.hahelpers.cluster as ch_cluster
import charmhelpers.contrib.network.ip as ch_ip
import charmhelpers.contrib.openstack.context as ch_context
import charmhelpers.contrib.openstack.utils as ch_utils
import charmhelpers.core.hookenv as hookenv
import charmhelpers.core.host as ch_host
import charms_openstack.ip as os_ip
ADDRESS_TYPES = sorted(os_ip.ADDRESS_MAP.keys(), reverse=True)
# handle declarative adapter properties using a decorator and simple functions
# Hold the custom adapter properties somewhere!
_custom_adapter_properties = {}
def adapter_property(interface_name):
"""Decorator to take the interface name and add a custom property.
These are used to generate custom Adapter classes automatically for the
charm author which are then plugged into the class. The adapter class is
built using a different function.
:param interface_name: the name of the interface to add the property to
"""
def wrapper(f):
property_name = f.__name__
if interface_name not in _custom_adapter_properties:
_custom_adapter_properties[interface_name] = {}
if property_name in _custom_adapter_properties[interface_name]:
raise RuntimeError(
"Property name '{}' used more than once for '{} interface?"
.format(property_name, interface_name))
_custom_adapter_properties[interface_name][property_name] = f
return f
return wrapper
# declaring custom configuration properties:
# Hold the custom configuration adapter properties somewhere!
_custom_config_properties = {}
def config_property(f):
"""Decorator to add a custom configuration property.
These are used to generate a custom ConfigurationAdapter for use when
automatically creating a Charm class
:param f: the function passed as part of the @decorator syntax
"""
property_name = f.__name__
if property_name in _custom_config_properties:
raise RuntimeError(
"Property name '{}' used more than once for configuration?"
.format(property_name))
_custom_config_properties[property_name] = f
return f
##
class OpenStackRelationAdapter(object):
"""
Base adapter class for all OpenStack related adapters.
"""
interface_type = None
"""
The generic type of the interface the adapter is wrapping.
"""
def __init__(self, relation=None, accessors=None, relation_name=None):
"""Class will usually be initialised using the 'relation' option to
pass in an instance of a interface class. If there is no relation
class yet available then 'relation_name' can be used instead.
:param relation: Instance of an interface class
:param accessors: List of accessible interfaces properties
:param relation_name: String name of relation
"""
self.relation = relation
if relation and relation_name:
raise ValueError('Cannot speciiy relation and relation_name')
if relation:
self.accessors = accessors or []
self._setup_properties()
else:
self._relation_name = relation_name
@property
def relation_name(self):
"""
Name of the relation this adapter is handling.
"""
if self.relation:
return self.relation.relation_name
else:
return self._relation_name
def _setup_properties(self):
"""
Setup property based accessors for interface.
For charms.reactive.Endpoint interfaces a list of properties is built
by looking for type(property) attributes added by the interface class.
For charms.reactive.RelationBase interfaces the auto_accessors list is
used to determine which properties to set.
Note that the accessor is dynamic as each access calls the underlying
getattr() for each property access.
"""
if isinstance(self.relation, charms.reactive.Endpoint):
# Get names of properties the interface class instance has,
# remove the properties inherited from charms.reactive.Endpoint
# base class
interface_instance_names = dir(self.relation)
base_class_names = dir(charms.reactive.Endpoint)
property_names = [
p for p in interface_instance_names if isinstance(
getattr(type(self.relation), p, None), property) and
p not in base_class_names]
for name in property_names:
# The double lamda trick is necessary to ensure we get fresh
# data from the interface class property at every call to the
# new property. Without it we would store the value that was
# there at instantiation of this class.
setattr(self.__class__,
name,
(lambda name: property(
lambda self: getattr(
self.relation, name)))(name))
else:
try:
self.accessors.extend(self.relation.auto_accessors)
except AttributeError:
self.accessors = []
for field in self.accessors:
meth_name = field.replace('-', '_')
# Get the relation property dynamically
# Note the additional lambda name: is to create a closure over
# meth_name so that a new 'name' gets created for each loop,
# otherwise the same variable meth_name is referenced in each
# of the internal lambdas. i.e. this is (lambda x: ...)(value)
setattr(self.__class__,
meth_name,
(lambda name: property(
lambda self: getattr(
self.relation, name)()))(meth_name))
class MemcacheRelationAdapter(OpenStackRelationAdapter):
"""
Adapter for the MemcacheRequires relation interface.
"""
interface_type = 'memcache'
@property
def url(self):
hosts = sorted(self.relation.memcache_hosts())
if hosts:
return "memcached://{}:11211?timeout=5".format(hosts[0])
return None
class RabbitMQRelationAdapter(OpenStackRelationAdapter):
"""
Adapter for the RabbitMQRequires relation interface.
"""
interface_type = "messaging"
DEFAULT_PORT = "5672"
def __init__(self, relation):
add_accessors = ['vhost', 'username']
super(RabbitMQRelationAdapter, self).__init__(relation, add_accessors)
@property
def host(self):
"""
Hostname that should be used to access RabbitMQ.
"""
if self.vip:
return self.vip
else:
return self.private_address
@property
def hosts(self):
"""
Comma separated list of hosts that should be used
to access RabbitMQ.
"""
hosts = self.relation.rabbitmq_hosts()
if len(hosts) > 1:
return ','.join(hosts)
else:
return None
@property
def ssl_data_complete(self):
return self.relation.ssl_data_complete()
@property
def ssl_ca_file(self):
return '/var/lib/charm/{}/rabbit-client-ca.pem'.format(
hookenv.service_name())
@property
def port(self):
"""Return the AMQP port
:returns: AMQP port number
:rtype: string
"""
return self.ssl_port or self.DEFAULT_PORT
@property
def transport_url(self):
"""
oslo.messaging formatted transport URL
:returns: oslo.messaging formatted transport URL
:rtype: string
"""
hosts = self.relation.rabbitmq_hosts()
transport_url_hosts = ','.join([
"{}:{}@{}:{}".format(self.username,
self.password,
ch_ip.format_ipv6_addr(host_) or host_,
self.port)
for host_ in hosts
])
return "rabbit://{}/{}".format(transport_url_hosts, self.vhost)
class PeerHARelationAdapter(OpenStackRelationAdapter):
"""
Adapter for cluster relation of nodes of the same service
"""
interface_type = "cluster"
def __init__(self, relation=None, relation_name=None):
"""Map of local units addresses for each address type
:param relation: Instance of openstack-ha relation
:param relation_name: Name of relation if openstack-ha relation is
not available e.g. 'cluster'
NOTE: This excludes private-address
@return dict of backends and networks for local unit e.g.
{'this_unit_admin_addr': {
'backends': {
'this_unit-1': 'this_unit_admin_addr'},
'network': 'this_unit_admin_addr/admin_netmask'},
'this_unit_internal_addr': {
'backends': {
'this_unit-1': 'this_unit_internal_addr'},
'network': 'this_unit_internal_addr/internal_netmask'},
'this_unit_public_addr': {
'backends': {
'this_unit-1': 'this_unit_public_addr'},
'network': 'this_unit_public_addr/public_netmask'}}
"""
super(PeerHARelationAdapter, self).__init__(
relation=relation,
relation_name=relation_name)
self.config = hookenv.config()
self.api_config_adapter = APIConfigurationAdapter()
self.local_address = self.api_config_adapter.local_address
self.local_unit_name = self.api_config_adapter.local_unit_name
# Note(AJK) - bug #1698814 - cluster_hosts needs to be ordered so that
# re-writes with no changed data don't cause a restart (dictionaries
# are 'randomly' ordered)
self.cluster_hosts = collections.OrderedDict()
if relation:
self.add_network_split_addresses()
self.add_default_addresses()
@property
def internal_addresses(self):
"""Return list of internal addresses of this unit and peers
Return list of internal addresses of this unit and peers. If no
internal address cidr has been set return private addresses.
@return list [ip1, ip2, ...]
"""
cfg_opt = os_ip.ADDRESS_MAP[os_ip.INTERNAL]['config']
int_net = self.config.get(cfg_opt)
laddr = ch_ip.get_relation_ip(
os_ip.ADDRESS_MAP[os_ip.INTERNAL]['binding'],
int_net)
try:
hosts = sorted(
list(self.cluster_hosts[laddr]['backends'].values()))
except KeyError:
hosts = [laddr]
return hosts
@property
def single_mode_map(self):
"""Return map of local addresses only if this is a single node cluster
@return dict of local address info e.g.
{'cluster_hosts':
{'this_unit_private_addr': {
'backends': {
'this_unit-1': 'this_unit_private_addr'},
'network': 'this_unit_private_addr/private_netmask'},
'internal_addresses': ['intaddr']}
"""
relation_info = collections.OrderedDict()
try:
cluster_relid = hookenv.relation_ids('cluster')[0]
if not hookenv.related_units(relid=cluster_relid):
relation_info = {
'cluster_hosts': self.local_default_addresses(),
'internal_addresses': self.internal_addresses,
}
net_split = self.local_network_split_addresses()
for key in net_split.keys():
relation_info['cluster_hosts'][key] = net_split[key]
except IndexError:
pass
return relation_info
def local_network_split_addresses(self):
"""Map of local units addresses for each address type
NOTE: This excludes private-address
@return dict of backends and networks for local unit e.g.
{'this_unit_admin_addr': {
'backends': {
'this_unit-1': 'this_unit_admin_addr'},
'network': 'this_unit_admin_addr/admin_netmask'},
'this_unit_internal_addr': {
'backends': {
'this_unit-1': 'this_unit_internal_addr'},
'network': 'this_unit_internal_addr/internal_netmask'},
'this_unit_public_addr': {
'backends': {
'this_unit-1': 'this_unit_public_addr'},
'network': 'this_unit_public_addr/public_netmask'}}
"""
config = hookenv.config()
_cluster_hosts = collections.OrderedDict()
for addr_type in ADDRESS_TYPES:
cfg_opt = os_ip.ADDRESS_MAP[addr_type]['config']
laddr = ch_ip.get_relation_ip(
os_ip.ADDRESS_MAP[addr_type]['binding'],
config.get(cfg_opt))
if laddr:
netmask = ch_ip.get_netmask_for_address(laddr)
_cluster_hosts[laddr] = {
'network': "{}/{}".format(laddr, netmask),
'backends': collections.OrderedDict(
[(self.local_unit_name, laddr)])}
return _cluster_hosts
def local_default_addresses(self):
"""Map of local units private address
@return dict of private address info local unit e.g.
{'this_unit_private_addr': {
'backends': {
'this_unit-1': 'this_unit_private_addr'},
'network': 'this_unit_private_addr/private_netmask'}}
"""
netmask = ch_ip.get_netmask_for_address(self.local_address)
_local_map = {
self.local_address: {
'network': "{}/{}".format(self.local_address, netmask),
'backends': collections.OrderedDict(
[(self.local_unit_name, self.local_address)])}}
return _local_map
def add_network_split_addresses(self):
"""Populate cluster_hosts with addresses of this unit and its
peers on each address type
@return None
"""
for addr_type in ADDRESS_TYPES:
cfg_opt = os_ip.ADDRESS_MAP[addr_type]['config']
laddr = ch_ip.get_relation_ip(
os_ip.ADDRESS_MAP[addr_type]['binding'],
self.config.get(cfg_opt))
if laddr:
self.cluster_hosts[laddr] = \
self.local_network_split_addresses()[laddr]
key = '{}-address'.format(
os_ip.ADDRESS_MAP[addr_type]['binding'])
for _unit, _laddr in self.relation.ip_map(address_key=key):
if _laddr:
self.cluster_hosts[laddr]['backends'][_unit] = _laddr
def add_default_addresses(self):
"""Populate cluster_hosts with private-address of this unit and its
peers
@return None
"""
self.cluster_hosts[self.local_address] = \
self.local_default_addresses()[self.local_address]
for _unit, _laddr in self.relation.ip_map():
self.cluster_hosts[self.local_address]['backends'][_unit] = _laddr
class DatabaseRelationAdapter(OpenStackRelationAdapter):
"""
Adapter for the Database relation interface.
"""
interface_type = "database"
def __init__(self, relation):
# Note: These accessors need closer inspection and potentially need
# to be removed. The actual interface implements them as methods with
# parameters. See bug: https://bugs.launchpad.net/bugs/1848216.
add_accessors = ['password', 'username', 'database']
super(DatabaseRelationAdapter, self).__init__(relation, add_accessors)
self.config = hookenv.config()
@property
def host(self):
"""
Hostname that should be used to access a database.
"""
return self.relation.db_host()
@property
def type(self):
return 'mysql'
def get_password(self, prefix=None):
if prefix:
return self.relation.password(prefix=prefix)
return self.password
def get_uri(self, prefix=None):
driver = 'mysql'
release = ch_utils.get_os_codename_install_source(
self.config['openstack-origin'])
if (ch_utils.OPENSTACK_RELEASES.index(release) >=
ch_utils.OPENSTACK_RELEASES.index('stein')):
driver = 'mysql+pymysql'
if prefix:
uri = '{}://{}:{}@{}/{}'.format(
driver,
self.relation.username(prefix=prefix),
self.relation.password(prefix=prefix),
self.host,
self.relation.database(prefix=prefix),
)
else:
uri = '{}://{}:{}@{}/{}'.format(
driver,
self.username,
self.password,
self.host,
self.database,
)
try:
if self.ssl_ca:
uri = '{}?ssl_ca={}'.format(uri, self.ssl_ca)
if self.ssl_cert:
uri = ('{}&ssl_cert={}&ssl_key={}'
.format(uri, self.ssl_cert, self.ssl_key))
except AttributeError:
# ignore ssl_ca or ssl_cert if not available
pass
return uri
@property
def uri(self):
return self.get_uri()
def make_default_options(base_cls=None, charm_instance=None):
"""Create a default, customised ConfigurationAdapter, or derived class
(based on the base_cls) using any custom properties that might have been
made.
If base_cls is None, the default ConfigurationAdapter will be used.
:param base_cls: a ConfigurationAdapter or derived class
:param charm_instance: the charm instance to plug into the options.
"""
return make_default_configuration_adapter_class(
base_cls=base_cls,
custom_properties=_custom_config_properties)(
charm_instance=charm_instance)
def make_default_configuration_adapter_class(base_cls=None,
custom_properties=None):
"""Create a default configuration adapter, using the base type specified
and any customer configuration properties.
This is called by the charm creation metaclass when 'bringing' up the class
if no configuration adapter has been specified in the adapters_class
:param base_cls: a ConfigurationAdapter derived class; or None
:param custom_properties: the name:function for the properties to set.
"""
base_cls = base_cls or ConfigurationAdapter
# if there are no custom properties, just return the base_cls
if not custom_properties:
return base_cls
# turns the functions into properties on the class
properties = {n: property(f) for n, f in custom_properties.items()}
# build a custom class with the custom properties
return type('DefaultConfigurationAdapter', (base_cls, ), properties)
class ConfigurationAdapter(object):
"""
Configuration Adapter which provides python based access
to all configuration options for the current charm.
It also holds a weakref to the instance of the OpenStackCharm derived class
that it is associated with. This is so that methods on the configuration
adapter can query the charm class for global config (e.g. service_name).
The configuration items from Juju are copied over and the '-' are replaced
with '_'. This allows them to be used directly on the instance.
"""
def __init__(self, charm_instance=None):
"""Create a ConfigurationAdapter (or derived) class.
:param charm_instance: the instance of the OpenStackCharm derived
class.
"""
self._charm_instance_weakref = None
if charm_instance is not None:
self._charm_instance_weakref = weakref.ref(charm_instance)
# copy over (statically) the items of the charms Juju configuration
for k, v in hookenv.config().items():
k = k.replace('-', '_')
setattr(self, k, v)
@property
def charm_instance(self):
"""Return the reference to the charm_instance or return None"""
if self._charm_instance_weakref:
return self._charm_instance_weakref()
return None
@property
def application_name(self):
"""Return the name of the deployed charm"""
return hookenv.service_name()
class APIConfigurationAdapter(ConfigurationAdapter):
"""This configuration adapter extends the base class and adds properties
common across most OpenstackAPI services.
"""
def __init__(self, port_map=None, service_name=None, charm_instance=None):
"""
Note passing port_map and service_name is deprecated, but supported for
backwards compatibility. The port_map and service_name can be obtained
from the self.charm_instance weak reference.
:param port_map: Map containing service names and the ports used e.g.
port_map = {
'svc1': {
'admin': 9001,
'public': 9001,
'int': 9001,
},
'svc2': {
'admin': 9002,
'public': 9002,
'int': 9002,
},
}
:param service_name: Name of service being deployed
:param charm_instance: a charm instance that will be passed to the base
constructor
"""
super(APIConfigurationAdapter, self).__init__(
charm_instance=charm_instance)
if port_map is not None:
hookenv.log(
"DEPRECATION: should not use port_map parameter in "
"APIConfigurationAdapter.__init__()", level=hookenv.WARNING)
self.port_map = port_map
elif self.charm_instance is not None:
self.port_map = self.charm_instance.api_ports
else:
self.port_map = None
if service_name is not None:
hookenv.log(
"DEPRECATION: should not use service_name parameter in "
"APIConfigurationAdapter.__init__()", level=hookenv.WARNING)
self.service_name = service_name
elif self.charm_instance is not None:
self.service_name = self.charm_instance.name
else:
self.service_name = None
self.__network_addresses = None
@property
def network_addresses(self):
"""Return the network_addresses as a property for a consuming template.
See APIConfigurationAdapter.get_network_addresses() for detail on the
return type.
"""
# cache and lazy resolve the network addresses - also helps with unit
# testing
if self.__network_addresses is None:
self.__network_addresses = self.get_network_addresses()
return self.__network_addresses
@property
def external_ports(self):
"""Return ports the service will be accessed on
The self.port_map is a dictionary of dictionaries, where the ports are
two levels deep (the leaves). This returns a set() of those ports.
@return set of ports service can be accessed on
"""
# the map take the first list of dictionaries to extract the 2nd level
# of values.
return set(itertools.chain(*map(lambda x: x.values(),
self.port_map.values())))
@property
def ipv6_mode(self):
"""Return if charm should enable IPv6
@return True if user has requested ipv6 support otherwise False
"""
return getattr(self, 'prefer_ipv6', False)
@property
def ipv6_enabled(self):
"""
@return True if IPv6 is enabled
"""
return not ch_ip.is_ipv6_disabled()
@property
def local_address(self):
"""Return remotely accessible address of charm (not localhost)
@return True if user has requested ipv6 support otherwise False
"""
if self.ipv6_mode:
addr = ch_ip.get_ipv6_addr(exc_list=[self.vip])[0]
else:
addr = ch_utils.get_host_ip(
hookenv.unit_get('private-address'))
return addr
@property
def local_unit_name(self):
"""
@return local unit name
"""
return hookenv.local_unit().replace('/', '-')
@property
def local_host(self):
"""Return localhost address depending on whether IPv6 is enabled
@return localhost ip address
"""
return 'ip6-localhost' if self.ipv6_mode else '127.0.0.1'
@property
def haproxy_host(self):
"""Return haproxy bind address depending on whether IPv6 is enabled
@return address
"""
return '::' if self.ipv6_mode else '0.0.0.0'
@property
def haproxy_stat_port(self):
"""Port to listen on to access haproxy statistics
@return port
"""
return '8888'
@property
def haproxy_stat_password(self):
"""Password for accessing haproxy statistics
@return password
"""
return charms.reactive.bus.get_state('haproxy.stat.password')
@property
def service_ports(self):
"""Dict of service names and the ports they listen on
@return {'svc1': ['portA', 'portB'], 'svc2': ['portC', 'portD'], ...}
"""
# Note(AJK) - ensure that service ports is always in the same order
service_ports = collections.OrderedDict()
if self.port_map:
for service in sorted(self.port_map.keys()):
port_types = sorted(list(self.port_map[service].keys()))
for port_type in port_types:
listen_port = self.port_map[service][port_type]
key = '{}_{}'.format(service, port_type)
used_ports = [v[0] for v in service_ports.values()]
if listen_port in used_ports:
hookenv.log("Not adding haproxy listen stanza for {} "
"port is already in use".format(key),
level=hookenv.WARNING)
continue
service_ports[key] = [
self.port_map[service][port_type],
ch_cluster.determine_apache_port(
self.port_map[service][port_type],
singlenode_mode=True)]
return service_ports
@property
def apache_enabled(self):
"""Whether apache is being used for this service
@return True if apache2 os being used for this service
"""
return charms.reactive.bus.get_state('ssl.enabled')
@property
def ssl(self):
"""Whether SSL is being used for this service
@return True is SSL has been enable
"""
return charms.reactive.bus.get_state('ssl.enabled')
def determine_service_port(self, port):
"""Calculate port service should use given external port
Haproxy fronts connections for a service and may pass connections to
Apache for SSL termination. Is Apache is being used:
Haproxy listens on N
Apache listens on N-10
Service listens on N-20
else
Haproxy listens on N
Service listens on N-10
:param int port: port service uses for external connections
@return int port: port backend service should use
"""
i = 10
if self.apache_enabled:
i = 20
return (port - i)
@property
def service_listen_info(self):
"""Dict of service names and attributes for backend to listen on
@return {
'svc1': {
'proto': 'http',
'ip': '10.0.0.10',
'port': '8080',
'url': 'http://10.0.0.10:8080},
'svc2': {
'proto': 'https',
'ip': '10.0.0.20',
'port': '8443',
'url': 'https://10.0.0.20:8443},
...
"""
info = {}
ip = self.local_host if self.apache_enabled else self.local_address
if self.port_map:
for service in self.port_map.keys():
key = service.replace('-', '_')
info[key] = {
'proto': 'http',
'ip': ip,
'port': self.determine_service_port(
self.port_map[service]['admin'])}
for port_type in self.port_map[service].keys():
port_key = '{}_port'.format(port_type)
info[key][port_key] = self.determine_service_port(
self.port_map[service][port_type])
info[key]['url'] = '{proto}://{ip}:{port}'.format(**info[key])
return info
@property
def external_endpoints(self):
"""Dict of service names and attributes that clients use to connect
@return {
'svc1': {
'proto': 'http',
'ip': '10.0.0.10',
'port': '8080',
'url': 'http://10.0.0.10:8080},
'svc2': {
'proto': 'https',
'ip': '10.0.0.20',
'port': '8443',
'url': 'https://10.0.0.20:8443},
...
"""
info = {}
proto = 'https' if self.apache_enabled else 'http'
if self.port_map:
for service in self.port_map.keys():
key = service.replace('-', '_')
info[key] = {
'proto': proto,
'ip': os_ip.resolve_address(os_ip.ADMIN),
'port': self.port_map[service][os_ip.ADMIN]}
info[key]['url'] = '{proto}://{ip}:{port}'.format(**info[key])
return info
def get_network_addresses(self):
"""For each network configured, return corresponding address and vip
(if available).
Returns a list of tuples of the form:
[(address_in_net_a, vip_in_net_a),
(address_in_net_b, vip_in_net_b),
...]
or, if no vip(s) available:
[(address_in_net_a, address_in_net_a),
(address_in_net_b, address_in_net_b),
...]
"""
addresses = []
for net_type in ADDRESS_TYPES:
net_cfg_opt = os_ip.ADDRESS_MAP[net_type]['config']
config_cidr = getattr(self, net_cfg_opt.replace('-', '_'), None)
if hookenv.config(net_cfg_opt):
addr = ch_ip.get_address_in_network(
config_cidr,
hookenv.unit_get('private-address'))
else:
addr = ch_ip.get_relation_ip(
os_ip.ADDRESS_MAP[net_type]['binding'])
addresses.append(
(addr, os_ip.resolve_address(endpoint_type=net_type)))
return sorted(addresses)
@property
def endpoints(self):
"""List of endpoint information.
Endpoint information used to configure apache
Client -> endpoint -> address:ext_port -> local:int_port
NOTE: endpoint map be a vi
returns [
(address1, endpoint1, ext_port1, int_port1),
(address2, endpoint2, ext_port2, int_port2)
...
]
"""
endpoints = []
for address, endpoint in sorted(set(self.network_addresses)):
for api_port in self.external_ports:
ext_port = ch_cluster.determine_apache_port(
api_port,
singlenode_mode=True)
int_port = ch_cluster.determine_api_port(
api_port,
singlenode_mode=True)
portmap = (address, endpoint, int(ext_port), int(int_port))
endpoints.append(portmap)
return endpoints
@property
def ext_ports(self):
""" List of endpoint ports
@returns List of ports
"""
eps = [ep[2] for ep in self.endpoints]
return sorted(list(set(eps)))
@property
def use_memcache(self):
return self.memcache.get('use_memcache', False)
@property
def memcache_server(self):
return self.memcache.get('memcache_server', '')
@property
def memcache_host(self):
return self.memcache.get('memcache_server_formatted', '')
@property
def memcache_port(self):
return self.memcache.get('memcache_port', '')
@property
def memcache_url(self):
return self.memcache.get('memcache_url', '')
@property
@hookenv.cached
def memcache(self):
ctxt = {}
ctxt['use_memcache'] = False
if self.charm_instance:
if (ch_utils.OPENSTACK_RELEASES.index(
self.charm_instance.release) >=
ch_utils.OPENSTACK_RELEASES.index('mitaka')):
ctxt['use_memcache'] = True
if ctxt['use_memcache']:
# Trusty version of memcached does not support ::1 as a listen
# address so use host file entry instead
release = ch_host.lsb_release()['DISTRIB_CODENAME'].lower()
if ch_ip.is_ipv6_disabled():
if ch_host.CompareHostReleases(release) > 'trusty':
ctxt['memcache_server'] = '127.0.0.1'
else:
ctxt['memcache_server'] = 'localhost'
ctxt['memcache_server_formatted'] = '127.0.0.1'
ctxt['memcache_port'] = '11211'
ctxt['memcache_url'] = '{}:{}'.format(
ctxt['memcache_server_formatted'],
ctxt['memcache_port'])
else:
if ch_host.CompareHostReleases(release) > 'trusty':
ctxt['memcache_server'] = '::1'
else:
ctxt['memcache_server'] = 'ip6-localhost'
ctxt['memcache_server_formatted'] = '[::1]'
ctxt['memcache_port'] = '11211'
ctxt['memcache_url'] = 'inet6:{}:{}'.format(
ctxt['memcache_server_formatted'],
ctxt['memcache_port'])
return ctxt
@property
@hookenv.cached
def workers(self):
"""Return the a number of workers that depends on the
config('worker_muliplier') and the number of cpus. This function uses
the charmhelpers.contrib.openstack.context.WorkerConfigContext() to do
the heavy lifting so that any changes in charmhelpers propagate to this
function
:returns: <int> the number of workers to apply to a configuration file.
"""
return ch_context.WorkerConfigContext()()["workers"]
@property
@hookenv.cached
def wsgi_worker_context(self):
"""Return a WSGIWorkerConfigContext dictionary.