Пример #1
0
    async def remove(
        self,
        reason: str,
        ids: Optional[List[str]] = None,
        users: Optional[List[str]] = None,
        node_indexes: Optional[List[int]] = None,
        node_names: Optional[List[str]] = None,
        blocked: Optional[bool] = None,
        completed: Optional[bool] = None,
        in_progress: Optional[bool] = None,
        log_user: Optional[str] = None,
        include_internal_maintenances=False,
    ) -> None:
        """
        Removes maintenances specified by filters.
        """
        ctx = context.get_context()

        async with ctx.get_cluster_admin_client() as client:
            cv = await get_cluster_view(client)

        all_maintenances = cv.get_all_maintenance_views()
        mvs = list(
            _filter_maintenance_views(
                # pyre-ignore
                all_maintenances,
                cv,
                ids=ids,
                users=users,
                node_indexes=node_indexes,
                node_names=node_names,
                blocked=blocked,
                completed=completed,
                in_progress=in_progress,
                include_internal_maintenances=include_internal_maintenances,
            ))

        if len(mvs) == 0 and include_internal_maintenances:
            print(colored("No maintenances matching given criteria", "white"))
            return
        elif len(mvs) == 0:
            print(
                colored(
                    "No maintenances matching given criteria, did you "
                    "mean to target internal maintenances?\nUse "
                    "`include-internal-maintenances` for this.",
                    "white",
                ))
            return

        print("You are going to remove following maintenances:\n")
        print(_render_expanded(mvs, cv, False))

        # Only user-created maintenances.
        if not include_internal_maintenances:
            cprint(
                "NOTE: Your query might have matched internal maintenances.\n"
                "We have excluded them from your remove request for "
                "safety. If you really need to remove internal maintenances,"
                " You need to to set `include-internal-maintenances to "
                "True`",
                "yellow",
            )
            if not confirm_prompt("Continue?"):
                return
        else:
            cprint(
                "\n\nWARNING: You might be deleting internal maintenances.\n "
                "This is a DANGEROUS operation. Only proceed if you are "
                "absolutely sure.",
                "red",
            )
            if not confirm_prompt("Take the RISK?"):
                return

        group_ids = [mv.group_id for mv in mvs]
        print(f"Removing maintenances {group_ids}")

        async with ctx.get_cluster_admin_client() as client:
            maintenances = await remove_maintenances(
                client=client,
                group_ids=group_ids,
                log_user=log_user or getuser(),
                log_reason=reason,
            )

        print(f"Removed maintenances {[mnt.group_id for mnt in maintenances]}")
Пример #2
0
    async def edit(self):
        """Open the tier's NodesConfig in a text editor. Will try to use $EDITOR
        environment variable. If not set it falls back to `nano`
        """

        try:
            client = _get_client()
            nc = _get_nodes_config(client)
        except Exception as e:
            termcolor.cprint(str(e), "red")
            return 1

        formatted = json.dumps(nc, indent=4, sort_keys=True)

        edited_text = None
        while True:
            try:
                edited_text = _edit_text_with_editor(
                    formatted if edited_text is None else edited_text)
                edited_nc = json.loads(edited_text)
                nc_list = json.dumps(nc, indent=4, sort_keys=True).split("\n")
                edited_nc_list = json.dumps(edited_nc,
                                            indent=4,
                                            sort_keys=True).split("\n")
                diff = difflib.unified_diff(nc_list,
                                            edited_nc_list,
                                            lineterm="")

                if next(diff, None) is None:
                    raise EditorError("No changes detected")

                if edited_nc.get("version", nc["version"]) == nc["version"]:
                    edited_nc["version"] = nc["version"] + 1

                if (edited_nc.get(
                        "last_timestamp",
                        nc["last_timestamp"]) == nc["last_timestamp"]):
                    edited_nc["last_timestamp"] = int(time.time() *
                                                      1000)  # time in ms

                # It seems everything is fine, it's time to show final diff
                edited_nc_json_str = json.dumps(edited_nc,
                                                indent=4,
                                                sort_keys=True)
                edited_nc_list = edited_nc_json_str.split("\n")
                diff = difflib.unified_diff(nc_list,
                                            edited_nc_list,
                                            lineterm="")
                termcolor.cprint("You're going to apply the following diff:",
                                 "red")
                for line in diff:
                    print(line)

                termcolor.cprint("\nWhat to do now?")
                termcolor.cprint("[1] Apply")
                termcolor.cprint("[2] Edit")
                termcolor.cprint("[3] Cancel")
                choice = ask_prompt("Choice:", options=("1", "2", "3"))
                if choice == "2":
                    continue
                elif choice == "3":
                    break

                # Need to catch all exceptions from NCM and re-raise it
                # to distinguish from other errors
                try:
                    nc_bin = ncm.json_to_nodes_configuration(
                        edited_nc_json_str)
                except Exception as e:
                    raise NCMError(f"Error on serializing config: {e}")

                try:
                    ncm.overwrite_nodes_configuration(client, nc_bin)
                    break
                except Exception as e:
                    raise NCMError(f"Error on overwriting config: {e}")

            except (EditorError, json.JSONDecodeError, NCMError) as e:
                termcolor.cprint(str(e), "red")
                if not confirm_prompt("Try again?"):
                    break

                continue

        return 0