<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
#    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.

"""Model classes that form the core of instances functionality."""

import logging
import netaddr

from reddwarf import db

from reddwarf.common import config
from reddwarf.guestagent import api as guest_api
from reddwarf.common import exception as rd_exceptions
from reddwarf.common import utils
from reddwarf.instance.tasks import InstanceTask
from reddwarf.instance.tasks import InstanceTasks
from novaclient.v1_1.client import Client
from reddwarf.common.models import ModelBase
from novaclient import exceptions as nova_exceptions
from reddwarf.common.models import NovaRemoteModelBase
from reddwarf.common.remote import create_nova_client

CONFIG = config.Config
LOG = logging.getLogger(__name__)


def load_server(client, uuid):
    """Loads a server or raises an exception."""
    if uuid is None:
        raise TypeError("Argument uuid not defined.")
    try:
        server = client.servers.get(uuid)
    except nova_exceptions.NotFound, e:
        raise rd_exceptions.NotFound(uuid=uuid)
    except nova_exceptions.ClientException, e:
        raise rd_exceptions.ReddwarfError(str(e))
    return server


def delete_server(client, server_id):
    try:
        client.servers.delete(server_id)
    except nova_exceptions.NotFound, e:
        raise rd_exceptions.NotFound(uuid=server_id)
    except nova_exceptions.ClientException, e:
        raise rd_exceptions.ReddwarfError()


class Instance(object):

    _data_fields = ['name', 'status', 'id', 'created', 'updated',
                    'flavor', 'links', 'addresses']

    def __init__(self, context, db_info, server, service_status):
        self.context = context
        self.db_info = db_info
        self.server = server
        self.service_status = service_status

    @staticmethod
    def load(context, uuid):
        if context is None:
            raise TypeError("Argument context not defined.")
        elif uuid is None:
            raise TypeError("Argument uuid not defined.")
        client = create_nova_client(context)
        db_info = DBInstance.find_by(id=uuid)
        server = load_server(client,
                                      db_info.compute_instance_id)
        task_status = db_info.task_status
        service_status = InstanceServiceStatus.find_by(instance_id=uuid)
        return Instance(context, db_info, server, service_status)

    @classmethod
    def delete(cls, context, uuid):
        if context is None:
            raise TypeError("Argument context not defined.")
        if uuid is None:
            raise TypeError("Argument uuid not defined.")
        LOG.debug("Deleting instance %s..." % uuid)
        LOG.debug("Creating nova client...")
        client = create_nova_client(context)
        instance_info = DBInstance.find_by(id=uuid)
        LOG.debug("  ... deleting compute id = %s" %
                  instance_info.compute_instance_id)
        delete_server(client, instance_info.compute_instance_id)
        LOG.debug(" ... setting status to DELETING.")
        instance_info.task_status = InstanceTasks.DELETING
        instance_info.save()
        #TODO(tim.simpson): Put this in the task manager somehow to shepard
        #                   deletion?

    @classmethod
    def create(cls, context, name, flavor_ref, image_id):
        client = create_nova_client(context)
        server = client.servers.create(name, image_id, flavor_ref)
        LOG.debug("Created new compute instance %s." % server.id)
        db_info = DBInstance.create(name=name,
            compute_instance_id=server.id,
            task_status=InstanceTasks.BUILDING)
        LOG.debug("Created new Reddwarf instance %s..." % db_info.id)
        service_status = InstanceServiceStatus.create(instance_id=db_info.id,
            status=ServiceStatuses.NEW)
        # Now wait for the response from the create to do additional work
        guest_api.API().prepare(context, db_info.id, 512, [])
        return Instance(context, db_info, server, service_status)

    @property
    def id(self):
        return self.db_info.id

    @property
    def is_building(self):
        return self.status in ["BUILDING"]

    @property
    def name(self):
        return self.server.name

    @property
    def status(self):
        #TODO(tim.simpson): Introduce logic to determine status as a function
        # of the current task progress, service status, and server status.
        if self.db_info.task_status == InstanceTasks.BUILDING:
            return "BUILDING"
        if self.db_info.task_status == InstanceTasks.DELETING:
            return "SHUTDOWN"

    @property
    def created(self):
        return self.db_info.created

    @property
    def updated(self):
        return self.db_info.updated

    @property
    def flavor(self):
        return self.server.flavor<commit_msg>Now returning the correct status strings.<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
#    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.

"""Model classes that form the core of instances functionality."""

import logging
import netaddr

from reddwarf import db

from reddwarf.common import config
from reddwarf.guestagent import api as guest_api
from reddwarf.common import exception as rd_exceptions
from reddwarf.common import utils
from reddwarf.instance.tasks import InstanceTask
from reddwarf.instance.tasks import InstanceTasks
from novaclient.v1_1.client import Client
from reddwarf.common.models import ModelBase
from novaclient import exceptions as nova_exceptions
from reddwarf.common.models import NovaRemoteModelBase
from reddwarf.common.remote import create_nova_client

CONFIG = config.Config
LOG = logging.getLogger(__name__)


def load_server(client, uuid):
    """Loads a server or raises an exception."""
    if uuid is None:
        raise TypeError("Argument uuid not defined.")
    try:
        server = client.servers.get(uuid)
    except nova_exceptions.NotFound, e:
        raise rd_exceptions.NotFound(uuid=uuid)
    except nova_exceptions.ClientException, e:
        raise rd_exceptions.ReddwarfError(str(e))
    return server


def delete_server(client, server_id):
    try:
        client.servers.delete(server_id)
    except nova_exceptions.NotFound, e:
        raise rd_exceptions.NotFound(uuid=server_id)
    except nova_exceptions.ClientException, e:
        raise rd_exceptions.ReddwarfError()


class InstanceStatus(object):

    ACTIVE = "ACTIVE"
    BLOCKED = "BLOCKED"
    BUILD = "BUILD"
    FAILED = "FAILED"
    SHUTDOWN = "SHUTDOWN"


class Instance(object):

    _data_fields = ['name', 'status', 'id', 'created', 'updated',
                    'flavor', 'links', 'addresses']

    def __init__(self, context, db_info, server, service_status):
        self.context = context
        self.db_info = db_info
        self.server = server
        self.service_status = service_status

    @staticmethod
    def load(context, uuid):
        if context is None:
            raise TypeError("Argument context not defined.")
        elif uuid is None:
            raise TypeError("Argument uuid not defined.")
        client = create_nova_client(context)
        db_info = DBInstance.find_by(id=uuid)
        server = load_server(client,
                                      db_info.compute_instance_id)
        task_status = db_info.task_status
        service_status = InstanceServiceStatus.find_by(instance_id=uuid)
        return Instance(context, db_info, server, service_status)

    @classmethod
    def delete(cls, context, uuid):
        if context is None:
            raise TypeError("Argument context not defined.")
        if uuid is None:
            raise TypeError("Argument uuid not defined.")
        LOG.debug("Deleting instance %s..." % uuid)
        LOG.debug("Creating nova client...")
        client = create_nova_client(context)
        instance_info = DBInstance.find_by(id=uuid)
        LOG.debug("  ... deleting compute id = %s" %
                  instance_info.compute_instance_id)
        delete_server(client, instance_info.compute_instance_id)
        LOG.debug(" ... setting status to DELETING.")
        instance_info.task_status = InstanceTasks.DELETING
        instance_info.save()
        #TODO(tim.simpson): Put this in the task manager somehow to shepard
        #                   deletion?

    @classmethod
    def create(cls, context, name, flavor_ref, image_id):
        client = create_nova_client(context)
        server = client.servers.create(name, image_id, flavor_ref)
        LOG.debug("Created new compute instance %s." % server.id)
        db_info = DBInstance.create(name=name,
            compute_instance_id=server.id,
            task_status=InstanceTasks.BUILDING)
        LOG.debug("Created new Reddwarf instance %s..." % db_info.id)
        service_status = InstanceServiceStatus.create(instance_id=db_info.id,
            status=ServiceStatuses.NEW)
        # Now wait for the response from the create to do additional work
        guest_api.API().prepare(context, db_info.id, 512, [])
        return Instance(context, db_info, server, service_status)

    @property
    def id(self):
        return self.db_info.id

    @property
    def is_building(self):
        return self.status in [InstanceStatus.BUILD]

    @property
    def name(self):
        return self.server.name

    @property
    def status(self):
        #TODO(tim.simpson): Introduce logic to determine status as a function
        # of the current task progress, service status, and server status.
        if self.db_info.task_status == InstanceTasks.BUILDING:
            return InstanceStatus.BUILD
        if self.db_info.task_status == InstanceTasks.DELETING:
            return InstanceStatus.SHUTDOWN

    @property
    def created(self):
        return self.db_info.created

    @property
    def updated(self):
        return self.db_info.updated

    @property
    def flavor(self):
        return self.server.flavor
{'fraction_non_alphanumeric': 0.0820053715308863, 'fraction_numerical': 0.0035810205908683975, 'mean_word_length': 2.892334494773519, '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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '745992', 'n_tokens_mistral': 3112, 'n_tokens_neox': 3090, 'n_words': 918}