<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import logging
import os
import time
import yaml

from octane.helpers import tasks as tasks_helpers
from octane.helpers import transformations
from octane import magic_consts
from octane.util import ssh
from octane.util import subprocess

from cliff import command as cmd
from fuelclient.objects import environment as environment_obj
from fuelclient.objects import node as node_obj

LOG = logging.getLogger(__name__)


def parse_tenant_get(output, field):
    for line in output.splitlines()[3:-1]:
        parts = line.split()
        if parts[1] == field:
            return parts[3]
    raise Exception(
        "Field {0} not found in output:\n{1}".format(field, output))


def get_service_tenant_id(node):
    fname = os.path.join(
        magic_consts.FUEL_CACHE,
        "env-{0}-service-tenant-id".format(node.data['cluster']),
    )
    if os.path.exists(fname):
        with open(fname) as f:
            return f.readline()

    tenant_out, _ = ssh.call(
        [
            'sh', '-c',
            '. /root/openrc; keystone tenant-get services',
        ],
        node=node,
        stdout=ssh.PIPE,
    )
    tenant_id = parse_tenant_get(tenant_out, 'id')
    with open(fname, 'w') as f:
        f.write(tenant_id)
    return tenant_id


class UpgradeHandler(object):
    def __init__(self, node, env, isolated):
        self.node = node
        self.env = env
        self.isolated = isolated

    def preupgrade(self):
        raise NotImplementedError('preupgrade')

    def prepare(self):
        raise NotImplementedError('prepare')

    def predeploy(self):
        raise NotImplementedError('predeploy')

    def postdeploy(self):
        raise NotImplementedError('postdeploy')


class ControllerUpgrade(UpgradeHandler):
    def __init__(self, node, env, isolated):
        super(ControllerUpgrade, self).__init__(node, env, isolated)
        self.service_tenant_id = None
        self.gateway = None

    def preupgrade(self):
        self.service_tenant_id = get_service_tenant_id(self.node)

    def predeploy(self):
        deployment_info = self.env.get_default_facts(
            'deployment', nodes=[self.node.data['id']])
        if self.isolated:
            # From backup_deployment_info
            backup_path = os.path.join(
                magic_consts.FUEL_CACHE,
                "deployment_{0}.orig".format(self.node.data['cluster']),
            )
            os.rename(backup_path, backup_path + '.orig')
            os.makedirs(backup_path)
            # Roughly taken from Environment.write_facts_to_dir
            for info in deployment_info:
                fname = os.path.join(
                    backup_path,
                    "{0}_{1}.yaml".format(info['role'], info['uid']),
                )
                with open(fname, 'w') as f:
                    yaml.dump(info, f, default_flow_style=False)
        for info in deployment_info:
            if self.isolated:
                transformations.remove_physical_ports(info)
                endpoints = deployment_info[0]["network_scheme"]["endpoints"]
                self.gateway = endpoints["br-ex"]["gateway"]<commit_msg>Check if path exists before create backup path<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import logging
import os
import time
import yaml

from octane.helpers import tasks as tasks_helpers
from octane.helpers import transformations
from octane import magic_consts
from octane.util import ssh
from octane.util import subprocess

from cliff import command as cmd
from fuelclient.objects import environment as environment_obj
from fuelclient.objects import node as node_obj

LOG = logging.getLogger(__name__)


def parse_tenant_get(output, field):
    for line in output.splitlines()[3:-1]:
        parts = line.split()
        if parts[1] == field:
            return parts[3]
    raise Exception(
        "Field {0} not found in output:\n{1}".format(field, output))


def get_service_tenant_id(node):
    fname = os.path.join(
        magic_consts.FUEL_CACHE,
        "env-{0}-service-tenant-id".format(node.data['cluster']),
    )
    if os.path.exists(fname):
        with open(fname) as f:
            return f.readline()

    tenant_out, _ = ssh.call(
        [
            'sh', '-c',
            '. /root/openrc; keystone tenant-get services',
        ],
        node=node,
        stdout=ssh.PIPE,
    )
    tenant_id = parse_tenant_get(tenant_out, 'id')
    with open(fname, 'w') as f:
        f.write(tenant_id)
    return tenant_id


class UpgradeHandler(object):
    def __init__(self, node, env, isolated):
        self.node = node
        self.env = env
        self.isolated = isolated

    def preupgrade(self):
        raise NotImplementedError('preupgrade')

    def prepare(self):
        raise NotImplementedError('prepare')

    def predeploy(self):
        raise NotImplementedError('predeploy')

    def postdeploy(self):
        raise NotImplementedError('postdeploy')


class ControllerUpgrade(UpgradeHandler):
    def __init__(self, node, env, isolated):
        super(ControllerUpgrade, self).__init__(node, env, isolated)
        self.service_tenant_id = None
        self.gateway = None

    def preupgrade(self):
        self.service_tenant_id = get_service_tenant_id(self.node)

    def predeploy(self):
        deployment_info = self.env.get_default_facts(
            'deployment', nodes=[self.node.data['id']])
        if self.isolated:
            # From backup_deployment_info
            backup_path = os.path.join(
                magic_consts.FUEL_CACHE,
                "deployment_{0}.orig".format(self.node.data['cluster']),
            )
            if not os.path.exists(backup_path):
                os.makedirs(backup_path)
            # Roughly taken from Environment.write_facts_to_dir
            for info in deployment_info:
                fname = os.path.join(
                    backup_path,
                    "{0}_{1}.yaml".format(info['role'], info['uid']),
                )
                with open(fname, 'w') as f:
                    yaml.dump(info, f, default_flow_style=False)
        for info in deployment_info:
            if self.isolated:
                transformations.remove_physical_ports(info)
                endpoints = deployment_info[0]["network_scheme"]["endpoints"]
                self.gateway = endpoints["br-ex"]["gateway"]
{'fraction_non_alphanumeric': 0.09745248685806712, 'fraction_numerical': 0.0040436716538617065, 'mean_word_length': 2.5519387266634754, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3374305', 'n_tokens_mistral': 2168, 'n_tokens_neox': 2111, 'n_words': 576}