1 # Copyright 2020 Canonical Ltd.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from charms
.reactive
import endpoint_from_flag
15 from charms
.layer
.caas_base
import pod_spec_set
16 from charms
.reactive
import when
, when_not
, hook
17 from charms
.reactive
.flags
import set_flag
, clear_flag
18 from charmhelpers
.core
.hookenv
import log
, metadata
, config
19 from charms
import layer
22 @hook("upgrade-charm")
23 @when("leadership.is_leader")
25 clear_flag("pol-k8s.configured")
28 @when("config.changed")
29 @when("leadership.is_leader")
31 clear_flag("pol-k8s.configured")
34 @when_not("kafka.ready")
35 @when_not("pol-k8s.configured")
36 def waiting_for_kafka():
37 layer
.status
.waiting("Waiting for kafka to be ready")
40 @when_not("mongo.ready")
41 @when_not("pol-k8s.configured")
42 def waiting_for_mongo():
43 layer
.status
.waiting("Waiting for mongo to be ready")
46 @when("kafka.ready", "mongo.ready")
47 @when_not("pol-k8s.configured")
48 @when("leadership.is_leader")
50 layer
.status
.maintenance("Configuring pol container")
52 kafka
= endpoint_from_flag("kafka.ready")
53 mongo
= endpoint_from_flag("mongo.ready")
56 kafka_units
= kafka
.kafkas()
57 kafka_unit
= kafka_units
[0]
59 mongo_uri
= mongo
.connection_string()
60 log("Mongo URI: {}".format(mongo_uri
))
62 if mongo_uri
and kafka_unit
["host"]:
63 spec
= make_pod_spec(kafka_unit
["host"], kafka_unit
["port"], mongo_uri
)
65 log("set pod spec:\n{}".format(spec
))
67 set_flag("pol-k8s.configured")
68 except Exception as e
:
69 layer
.status
.blocked("k8s spec failed to deploy: {}".format(e
))
72 @when("pol-k8s.configured")
74 layer
.status
.active("ready")
77 def make_pod_spec(kafka_host
, kafka_port
, mongo_uri
):
78 """Make pod specification for Kubernetes
81 kafka_host (str): Kafka hostname or IP
82 kafka_port (int): Kafka port
83 mongo_host (str): Mongo URI
85 pod_spec: Pod specification for Kubernetes
88 with
open("reactive/spec_template.yaml") as spec_file
:
89 pod_spec_template
= spec_file
.read()
94 "name": md
.get("name"),
95 "docker_image": cfg
.get("image"),
96 "kafka_host": kafka_host
,
97 "kafka_port": kafka_port
,
98 "mongo_uri": mongo_uri
,
101 return pod_spec_template
% data