def adjust_cron_expression_for_schedule_tasks(check=None):
    operation = os.environ["OPERATION"]
    if validate(operation):
        return
    for group in groups:
        groupName = group.get("name")
        if check is not None:
            if check not in str(groupName):
                schedule = None
            else:
                schedule = group.get("scheduling")
        else:
            schedule = group.get("scheduling")
        if schedule is not None:
            scaling_tasks = schedule.get("tasks")
            if scaling_tasks is not None:
                for n in range(len(scaling_tasks)):
                    schedule = scaling_tasks[n]
                    adjusted_cron_expression = adjust_schedule(schedule.get("cron_expression"), operation=operation)
                    scale_min_capacity = schedule.get("scale_min_capacity")
                    scale_max_capacity = schedule.get("scale_max_capacity")
                    scale_target_capacity = schedule.get("scale_target_capacity")
                    configure_scheduled_tasks(groupName,
                                              adjusted_cron_expression,
                                              scale_min_capacity,
                                              scale_max_capacity,
                                              scale_target_capacity)
Ejemplo n.º 2
0
def adjust_zmon_alerts(zmon_directory):
    operation = os.environ["OPERATION"]
    if validate(operation):
        return
    export_zmon_alerts(zmon_directory)
    yaml = ruamel.yaml.YAML(typ='safe')
    msgs = set()
    for root, dirs, files in os.walk(zmon_directory):
        for file in files:
            fname = os.path.join(root, file)
            with open(fname) as f:
                if "period: wd" in f.read():
                    print(file)
                else:
                    os.remove(fname)
            try:
                with open(fname, 'r') as f:
                    data = yaml.load(f)
                    data["period"] = adjust_zmon_time_period(
                        data.get("period"))
                    with open(fname, "w") as f:
                        f.write(json.dumps(data))
                subprocess.run(["zmon", "alert-definition", "update", fname])
                msgs.add("Updated Schedule of Alert %s successfully" % file)

            except FileNotFoundError:
                pass

    for msg in msgs:
        logger.info(msg)
Ejemplo n.º 3
0
def adjust_aws_schedule_tasks(check=None):
    operation = os.environ["OPERATION"]
    if validate(operation):
        return
    groups = client.describe_auto_scaling_groups().get("AutoScalingGroups")
    autoscaling_groups = []
    for group in groups:
        asg = group.get("AutoScalingGroupName")
        if check is not None:
            if check not in str(asg):
                continue
            else:
                autoscaling_groups.append(asg)
        else:
            autoscaling_groups.append(asg)

    schedules = {}
    for group in autoscaling_groups:
        scheduled_actions = client.describe_scheduled_actions(
            AutoScalingGroupName=group).get("ScheduledUpdateGroupActions")
        if not scheduled_actions:
            pass
        else:
            schedules[group] = scheduled_actions

    for schedule, actions in schedules.items():
        for n in range(len(actions)):
            action = actions[n]
            AutoScalingGroupName = action.get("AutoScalingGroupName")
            ScheduledActionName = action.get("ScheduledActionName")
            StartTime = action.get("StartTime")
            Recurrence = action.get("Recurrence")
            MinSize = action.get("MinSize")
            MaxSize = action.get("MaxSize")
            update = adjust_schedule(Recurrence, operation)
            try:
                response = client.put_scheduled_update_group_action(
                    AutoScalingGroupName=AutoScalingGroupName,
                    ScheduledActionName=ScheduledActionName,
                    Recurrence=update,
                    MinSize=MinSize,
                    MaxSize=MaxSize)
                logger.info(
                    "Adusted schedule of AutoscalingGroup %s from %s to %s successfully."
                    % (AutoScalingGroupName, Recurrence, update))
            except exception as e:
                logger.error(e)
Ejemplo n.º 4
0
def adjust_kube_schedule_json_files(json_files):
    logger = applogger("JSON_FILES")
    operation = os.environ["OPERATION"]
    if validate(operation):
        return
    if not os.path.exists(json_files):
        logger.error("The provided directory is not exist.")
        return
    msgs = set()
    for root, dirs, files in os.walk(json_files):
        for file in files:
            if file.endswith(".json"):
                fname = os.path.join(root, file)
                with open(fname) as f:
                    datafile = f.readlines()
                for line in datafile:
                    if "schedule" in line:
                        schedule = line.split(":")[1].lstrip()
                        exp = str(schedule.replace('"', ''))
                        exp = re.sub(',$', '', exp)
                        updated_schedule = adjust_schedule(
                            exp, operation).rstrip('\n')
                        updated_schedule = '"%s",' % updated_schedule
                        updated_schedule = updated_schedule + '\n'
                        with fileinput.FileInput(fname, inplace=True) as file:
                            for line in file:
                                print(line.replace(schedule, updated_schedule),
                                      end='')
                                msgs.add(
                                    "Updated Cron Expressions of %s successfully"
                                    % fname)
    if not msgs:
        logger.warn(
            "There is no JSON File matching the provided criteria or may be directory is empty"
        )
    else:
        for msg in msgs:
            logger.info(msg)
Ejemplo n.º 5
0
def adjust_senza_yaml_files_definitions(senza_files):
    operation = os.environ["OPERATION"]
    if validate(operation):
        return
    if not os.path.exists(senza_files):
        logger.error("The provided directory is not exist.")
        return
    msgs = set()
    for root, dirs, files in os.walk(senza_files):
        for file in files:
            if file.endswith(".yaml"):
                fname = os.path.join(root, file)
                file_name = file
                with open(fname) as f:
                    if "TimeSaving" in f.read():
                        msgs.add(
                            "File %s will not be modified as preotection flag TimeSaving exist"
                            % file_name)
                        f.close()
                    else:
                        with open(fname) as f:
                            datafile = f.readlines()
                        for line in datafile:
                            if "cronExpression" in line:
                                expression = line.split(":")[1].lstrip()
                                _expression = expression.strip("\n")
                                exp = str(expression.replace('"', ''))
                                updated_schedule = adjust_schedule(
                                    exp, operation)
                                with fileinput.FileInput(fname,
                                                         inplace=True) as file:
                                    for line in file:
                                        print(line.replace(
                                            expression, updated_schedule),
                                              end='')
                                        msgs.add(
                                            "Updated Cron Expression of %s from %s to %s"
                                            % (file_name, _expression,
                                               updated_schedule.strip("\n")))
                                with fileinput.FileInput(fname,
                                                         inplace=True) as file:
                                    for line in file:
                                        if "TimeSaving" in line:
                                            print(line.replace(line, line),
                                                  end='')
                                        else:
                                            print(line.replace(
                                                "taskType: scale",
                                                "taskType: scale  # TimeSaving"
                                            ),
                                                  end='')
    if not msgs:
        logger.warn(
            "There is no YAML File matching the provided criteria or may be directory is empty"
        )
    else:
        for msg in msgs:
            if str("preotection flag TimeSaving exist") in msg:
                logger.warn(msg)
            elif str("Updated Cron Expression") in msg:
                logger.info(msg)