OSM DB Update Charm
[osm/devops.git] / installers / charm / osm-update-db-operator / src / charm.py
1 #!/usr/bin/env python3
2 # Copyright 2022 Canonical Ltd.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # 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, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 """Update DB charm module."""
17
18 import logging
19
20 from ops.charm import CharmBase
21 from ops.framework import StoredState
22 from ops.main import main
23 from ops.model import ActiveStatus, BlockedStatus
24
25 from db_upgrade import MongoUpgrade, MysqlUpgrade
26
27 logger = logging.getLogger(__name__)
28
29
30 class UpgradeDBCharm(CharmBase):
31 """Upgrade DB Charm operator."""
32
33 _stored = StoredState()
34
35 def __init__(self, *args):
36 super().__init__(*args)
37
38 # Observe events
39 event_observe_mapping = {
40 self.on.update_db_action: self._on_update_db_action,
41 self.on.apply_patch_action: self._on_apply_patch_action,
42 self.on.config_changed: self._on_config_changed,
43 }
44 for event, observer in event_observe_mapping.items():
45 self.framework.observe(event, observer)
46
47 @property
48 def mongo(self):
49 """Create MongoUpgrade object if the configuration has been set."""
50 mongo_uri = self.config.get("mongodb-uri")
51 return MongoUpgrade(mongo_uri) if mongo_uri else None
52
53 @property
54 def mysql(self):
55 """Create MysqlUpgrade object if the configuration has been set."""
56 mysql_uri = self.config.get("mysql-uri")
57 return MysqlUpgrade(mysql_uri) if mysql_uri else None
58
59 def _on_config_changed(self, _):
60 mongo_uri = self.config.get("mongodb-uri")
61 mysql_uri = self.config.get("mysql-uri")
62 if not mongo_uri and not mysql_uri:
63 self.unit.status = BlockedStatus("mongodb-uri and/or mysql-uri must be set")
64 return
65 self.unit.status = ActiveStatus()
66
67 def _on_update_db_action(self, event):
68 """Handle the update-db action."""
69 current_version = str(event.params["current-version"])
70 target_version = str(event.params["target-version"])
71 mysql_only = event.params.get("mysql-only")
72 mongodb_only = event.params.get("mongodb-only")
73 try:
74 results = {}
75 if mysql_only and mongodb_only:
76 raise Exception("cannot set both mysql-only and mongodb-only options to True")
77 if mysql_only:
78 self._upgrade_mysql(current_version, target_version)
79 results["mysql"] = "Upgraded successfully"
80 elif mongodb_only:
81 self._upgrade_mongodb(current_version, target_version)
82 results["mongodb"] = "Upgraded successfully"
83 else:
84 self._upgrade_mysql(current_version, target_version)
85 results["mysql"] = "Upgraded successfully"
86 self._upgrade_mongodb(current_version, target_version)
87 results["mongodb"] = "Upgraded successfully"
88 event.set_results(results)
89 except Exception as e:
90 event.fail(f"Failed DB Upgrade: {e}")
91
92 def _upgrade_mysql(self, current_version, target_version):
93 logger.debug("Upgrading mysql")
94 if self.mysql:
95 self.mysql.upgrade(current_version, target_version)
96 else:
97 raise Exception("mysql-uri not set")
98
99 def _upgrade_mongodb(self, current_version, target_version):
100 logger.debug("Upgrading mongodb")
101 if self.mongo:
102 self.mongo.upgrade(current_version, target_version)
103 else:
104 raise Exception("mongo-uri not set")
105
106 def _on_apply_patch_action(self, event):
107 bug_number = event.params["bug-number"]
108 logger.debug("Patching bug number {}".format(str(bug_number)))
109 try:
110 if self.mongo:
111 self.mongo.apply_patch(bug_number)
112 else:
113 raise Exception("mongo-uri not set")
114 except Exception as e:
115 event.fail(f"Failed Patch Application: {e}")
116
117
118 if __name__ == "__main__": # pragma: no cover
119 main(UpgradeDBCharm, use_juju_for_storage=True)