Matteo Scandolo | 57fdb4b | 2019-02-06 18:27:56 -0800 | [diff] [blame^] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | # Copyright 2017-present Open Networking Foundation |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain 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, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
| 17 | # TO RUN |
| 18 | # source scripts/setup_venv.sh |
| 19 | # xos-migrate [-s <service-name>] [-r ~/cord] |
| 20 | # eg: xos-migrate -r ~/Sites/cord -s core -s fabric |
| 21 | |
| 22 | # TODO |
| 23 | # - add support for services that are in the cord/orchestration/profiles folders |
| 24 | # - add support to specify a name to be given to the generated migration (--name parameter in django makemigrations) |
| 25 | # - add support to generate empty migrations (needed for data-only migrations) |
| 26 | |
| 27 | import os |
| 28 | import sys |
| 29 | import argparse |
| 30 | import yaml |
| 31 | import shutil |
| 32 | from xosgenx.generator import XOSProcessor, XOSProcessorArgs |
| 33 | from xosconfig import Config |
| 34 | from multistructlog import create_logger |
| 35 | |
| 36 | |
| 37 | def get_abs_path(dir_): |
| 38 | if os.path.isabs(dir_): |
| 39 | return dir_ |
| 40 | if dir_[0] == '~' and not os.path.exists(dir_): |
| 41 | dir_ = os.path.expanduser(dir_) |
| 42 | return os.path.abspath(dir_) |
| 43 | return os.path.dirname(os.path.realpath(__file__)) + "/" + dir_ |
| 44 | |
| 45 | |
| 46 | def print_banner(root): |
| 47 | log.info(r"---------------------------------------------------------------") |
| 48 | log.info(r" _ __ ") |
| 49 | log.info(r" _ ______ _____ ____ ___ (_)___ __________ _/ /____ ") |
| 50 | log.info(r" | |/_/ __ \/ ___/_____/ __ `__ \/ / __ `/ ___/ __ `/ __/ _ \ ") |
| 51 | log.info(r" _> </ /_/ (__ )_____/ / / / / / / /_/ / / / /_/ / /_/ __/ ") |
| 52 | log.info(r"/_/|_|\____/____/ /_/ /_/ /_/_/\__, /_/ \__,_/\__/\___/ ") |
| 53 | log.info(r" /____/ ") |
| 54 | log.info(r"---------------------------------------------------------------") |
| 55 | log.debug("CORD repo root", root=root) |
| 56 | log.debug("Storing logs in: %s" % os.environ["LOG_FILE"]) |
| 57 | # log.debug("Config schema: %s" % os.environ['XOS_CONFIG_SCHEMA']) |
| 58 | # log.debug("Config: %s" % os.environ['XOS_CONFIG_FILE']) |
| 59 | log.debug(r"---------------------------------------------------------------") |
| 60 | |
| 61 | |
| 62 | def generate_core_models(core_dir): |
| 63 | core_xproto = os.path.join(core_dir, "core.xproto") |
| 64 | |
| 65 | args = XOSProcessorArgs( |
| 66 | output=core_dir, |
| 67 | target="django.xtarget", |
| 68 | dest_extension="py", |
| 69 | write_to_file="model", |
| 70 | files=[core_xproto], |
| 71 | ) |
| 72 | XOSProcessor.process(args) |
| 73 | |
| 74 | security_args = XOSProcessorArgs( |
| 75 | output=core_dir, |
| 76 | target="django-security.xtarget", |
| 77 | dest_file="security.py", |
| 78 | write_to_file="single", |
| 79 | files=[core_xproto], |
| 80 | ) |
| 81 | |
| 82 | XOSProcessor.process(security_args) |
| 83 | |
| 84 | init_args = XOSProcessorArgs( |
| 85 | output=core_dir, |
| 86 | target="init.xtarget", |
| 87 | dest_file="__init__.py", |
| 88 | write_to_file="single", |
| 89 | files=[core_xproto], |
| 90 | ) |
| 91 | XOSProcessor.process(init_args) |
| 92 | |
| 93 | |
| 94 | def find_xproto_in_folder(path): |
| 95 | """ |
| 96 | Recursively iterate a folder tree to look for any xProto file. |
| 97 | We use this function in case that the name of the xProto is different from the name of the folder (eg: olt-service) |
| 98 | :param path: the root folder to start the search |
| 99 | :return: [string] |
| 100 | """ |
| 101 | xprotos = [] |
| 102 | for fn in os.listdir(path): |
| 103 | # skip hidden files and folders. plus other useless things |
| 104 | if fn.startswith(".") or fn == "venv-xos" or fn == "htmlcov": |
| 105 | continue |
| 106 | full_path = os.path.join(path, fn) |
| 107 | if fn.endswith(".xproto"): |
| 108 | xprotos.append(full_path) |
| 109 | elif os.path.isdir(full_path): |
| 110 | xprotos = xprotos + find_xproto_in_folder(full_path) |
| 111 | return xprotos |
| 112 | |
| 113 | |
| 114 | def find_decls_models(path): |
| 115 | """ |
| 116 | Recursively iterate a folder tree to look for any models.py file. |
| 117 | This files contain the base model for _decl generated models. |
| 118 | :param path: the root folder to start the search |
| 119 | :return: [string] |
| 120 | """ |
| 121 | decls = [] |
| 122 | for fn in os.listdir(path): |
| 123 | # skip hidden files and folders. plus other useless things |
| 124 | if fn.startswith(".") or fn == "venv-xos" or fn == "htmlcov": |
| 125 | continue |
| 126 | full_path = os.path.join(path, fn) |
| 127 | if fn == "models.py": |
| 128 | decls.append(full_path) |
| 129 | elif os.path.isdir(full_path): |
| 130 | decls = decls + find_decls_models(full_path) |
| 131 | return decls |
| 132 | |
| 133 | |
| 134 | def get_service_name_from_config(path): |
| 135 | """ |
| 136 | Given a service folder look for the config.yaml file and find the name |
| 137 | :param path: the root folder to start the search |
| 138 | :return: string |
| 139 | """ |
| 140 | config = os.path.join(path, "xos/synchronizer/config.yaml") |
| 141 | if not os.path.isfile(config): |
| 142 | raise Exception("Config file not found at: %s" % config) |
| 143 | |
| 144 | cfg_file = open(config) |
| 145 | cfg = yaml.load(cfg_file) |
| 146 | return cfg['name'] |
| 147 | |
| 148 | |
| 149 | def generate_service_models(service_dir, service_dest_dir, service_name): |
| 150 | """ |
| 151 | Generate the django code starting from xProto for a given service. |
| 152 | :param service_dir: string (path to the folder) |
| 153 | :param service_name: string (name of the service) |
| 154 | :return: void |
| 155 | """ |
| 156 | xprotos = find_xproto_in_folder(service_dir) |
| 157 | decls = find_decls_models(service_dir) |
| 158 | log.debug("Generating models for %s from files %s" % (service_name, ", ".join(xprotos))) |
| 159 | out_dir = os.path.join(service_dest_dir, service_name) |
| 160 | if not os.path.isdir(out_dir): |
| 161 | os.mkdir(out_dir) |
| 162 | |
| 163 | args = XOSProcessorArgs( |
| 164 | output=out_dir, |
| 165 | files=xprotos, |
| 166 | target="service.xtarget", |
| 167 | write_to_file="target", |
| 168 | ) |
| 169 | XOSProcessor.process(args) |
| 170 | |
| 171 | security_args = XOSProcessorArgs( |
| 172 | output=out_dir, |
| 173 | target="django-security.xtarget", |
| 174 | dest_file="security.py", |
| 175 | write_to_file="single", |
| 176 | files=xprotos, |
| 177 | ) |
| 178 | |
| 179 | XOSProcessor.process(security_args) |
| 180 | |
| 181 | init_py_filename = os.path.join(out_dir, "__init__.py") |
| 182 | if not os.path.exists(init_py_filename): |
| 183 | open(init_py_filename, "w").write("# created by dynamicbuild") |
| 184 | |
| 185 | # copy over models.py files from the service |
| 186 | if len(decls) > 0: |
| 187 | for file in decls: |
| 188 | fn = os.path.basename(file) |
| 189 | src_fn = file |
| 190 | dest_fn = os.path.join(out_dir, fn) |
| 191 | log.debug("Copying models.py from %s to %s" % (src_fn, dest_fn)) |
| 192 | shutil.copyfile(src_fn, dest_fn) |
| 193 | |
| 194 | # copy existing migrations from the service, otherwise they won't be incremental |
| 195 | src_dir = os.path.join(service_dir, "xos", "synchronizer", "migrations") |
| 196 | if os.path.isdir(src_dir): |
| 197 | dest_dir = os.path.join(out_dir, "migrations") |
| 198 | if os.path.isdir(dest_dir): |
| 199 | shutil.rmtree(dest_dir) # empty the folder, we'll copy everything again |
| 200 | shutil.copytree(src_dir, dest_dir) |
| 201 | |
| 202 | |
| 203 | def copy_service_migrations(service_dir, service_dest_dir, service_name): |
| 204 | """ |
| 205 | Once the migrations are generated, copy them in the correct location |
| 206 | :param service_dir: string (path to the folder) |
| 207 | :param service_name: string (name of the service) |
| 208 | :return: void |
| 209 | """ |
| 210 | # FIXME Django eats this message |
| 211 | log.debug("Copying %s migrations to %s" % (service_name, service_dir)) |
| 212 | migration_dir = os.path.join(service_dest_dir, service_name, "migrations") |
| 213 | dest_dir = os.path.join(service_dir, "xos", "synchronizer", "migrations") |
| 214 | if os.path.isdir(dest_dir): |
| 215 | shutil.rmtree(dest_dir) # empty the folder, we'll copy everything again |
| 216 | shutil.copytree(migration_dir, dest_dir) |
| 217 | |
| 218 | |
| 219 | def monkey_patch_migration_template(): |
| 220 | import django |
| 221 | django.setup() |
| 222 | |
| 223 | import django.db.migrations.writer as dj |
| 224 | dj.MIGRATION_TEMPLATE = """\ |
| 225 | # Copyright 2017-present Open Networking Foundation |
| 226 | # |
| 227 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 228 | # you may not use this file except in compliance with the License. |
| 229 | # You may obtain a copy of the License at |
| 230 | # |
| 231 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 232 | # |
| 233 | # Unless required by applicable law or agreed to in writing, software |
| 234 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 235 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 236 | # See the License for the specific language governing permissions and |
| 237 | # limitations under the License. |
| 238 | |
| 239 | # -*- coding: utf-8 -*- |
| 240 | # Generated by Django %(version)s on %(timestamp)s |
| 241 | from __future__ import unicode_literals |
| 242 | |
| 243 | %(imports)s |
| 244 | |
| 245 | class Migration(migrations.Migration): |
| 246 | %(replaces_str)s%(initial_str)s |
| 247 | dependencies = [ |
| 248 | %(dependencies)s\ |
| 249 | ] |
| 250 | |
| 251 | operations = [ |
| 252 | %(operations)s\ |
| 253 | ] |
| 254 | """ |
| 255 | |
| 256 | # SETTING ENV |
| 257 | os.environ['LOG_FILE'] = get_abs_path("django.log") |
| 258 | os.environ['XOS_CONFIG_SCHEMA'] = get_abs_path("migration_cfg_schema.yaml") |
| 259 | os.environ['XOS_CONFIG_FILE'] = get_abs_path("migration_cfg.yaml") |
| 260 | os.environ["MIGRATIONS"] = "true" |
| 261 | # this is populated in case we generate migrations for services and it's used in settings.py |
| 262 | os.environ["INSTALLED_APPS"] = "" |
| 263 | |
| 264 | # PARAMS |
| 265 | parser = argparse.ArgumentParser(description="XOS Migrations") |
| 266 | required = parser.add_argument_group('required arguments') |
| 267 | |
| 268 | required.add_argument( |
| 269 | '-s', |
| 270 | '--service', |
| 271 | action='append', |
| 272 | required=True, |
| 273 | dest="service_names", |
| 274 | help='The name of the folder containing the service in cord/orchestration/xos_services' |
| 275 | ) |
| 276 | |
| 277 | parser.add_argument( |
| 278 | '-r', |
| 279 | '--repo', |
| 280 | default=get_abs_path("~/cord"), |
| 281 | dest="repo_root", |
| 282 | help='The location of the folder containing the CORD repo root (default to ~/cord)' |
| 283 | ) |
| 284 | |
| 285 | # FIXME this is not working with multistructlog |
| 286 | parser.add_argument( |
| 287 | "-v", |
| 288 | "--verbose", |
| 289 | help="increase log verbosity", |
| 290 | action="store_true" |
| 291 | ) |
| 292 | |
| 293 | # INITIALIZING LOGGER |
| 294 | Config.init() |
| 295 | log = create_logger(Config().get('logging')) |
| 296 | |
| 297 | |
| 298 | def run(): |
| 299 | |
| 300 | args = parser.parse_args() |
| 301 | |
| 302 | print_banner(args.repo_root) |
| 303 | |
| 304 | # find absolute path to the code |
| 305 | xos_path = get_abs_path(os.path.join(args.repo_root, "orchestration/xos/xos/")) |
| 306 | core_dir = get_abs_path(os.path.join(xos_path, "core/models/")) |
| 307 | service_base_dir = get_abs_path(os.path.join(xos_path, "../../xos_services/")) |
| 308 | service_dest_dir = get_abs_path(os.path.join(xos_path, "services/")) |
| 309 | |
| 310 | # we need to append the xos folder to sys.path |
| 311 | original_sys_path = sys.path |
| 312 | sys.path.append(xos_path) |
| 313 | |
| 314 | log.info("Services: %s" % ", ".join(args.service_names)) |
| 315 | |
| 316 | django_cli_args = ['xos-migrate.py', 'makemigrations'] |
| 317 | |
| 318 | # generate the code for each service and create a list of parameters to pass to django |
| 319 | app_list = [] |
| 320 | for service in args.service_names: |
| 321 | if service == "core": |
| 322 | |
| 323 | generate_core_models(core_dir) |
| 324 | django_cli_args.append("core") |
| 325 | else: |
| 326 | service_dir = os.path.join(service_base_dir, service) |
| 327 | service_name = get_service_name_from_config(service_dir) |
| 328 | generate_service_models(service_dir, service_dest_dir, service_name) |
| 329 | app_list.append("services.%s" % service_name) |
| 330 | |
| 331 | django_cli_args.append(service_name) |
| 332 | |
| 333 | os.environ["INSTALLED_APPS"] = ",".join(app_list) |
| 334 | |
| 335 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings") |
| 336 | |
| 337 | monkey_patch_migration_template() |
| 338 | |
| 339 | from django.core.management import execute_from_command_line |
| 340 | |
| 341 | execute_from_command_line(django_cli_args) |
| 342 | |
| 343 | # copying migrations back to the service |
| 344 | for service in args.service_names: |
| 345 | if service == "core": |
| 346 | # we don't need to copy migrations for the core |
| 347 | continue |
| 348 | else: |
| 349 | service_dir = os.path.join(service_base_dir, service) |
| 350 | service_name = get_service_name_from_config(service_dir) |
| 351 | copy_service_migrations(service_dir, service_dest_dir, service_name) |
| 352 | |
| 353 | # restore orginal sys.path |
| 354 | sys.path = original_sys_path |