<commit_before>import os

import celery
import ipaddr
import json
from piston.handler import BaseHandler
from piston.utils import rc, validate
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings

from nailgun.models import Cluster, Node, Recipe, Role, Release, Network
from nailgun.api.validators import validate_json, validate_json_list
from nailgun.api.forms import ClusterForm, ClusterCreationForm, RecipeForm, \
        RoleForm, RoleFilterForm, NodeCreationForm, NodeFilterForm, NodeForm, \
        ReleaseCreationForm, NetworkCreationForm
from nailgun import tasks
import nailgun.api.validators as vld


class JSONHandler(BaseHandler):
    """
    Basic JSON handler
    """
    fields = None
    special_fields = None

    @classmethod
    def render(cls, item, fields=None):
        json_data = {}
        use_fields = fields if fields else cls.fields
        if not use_fields:
            raise ValueError("No fields for serialize")
        for field in use_fields:
            if cls is JSONHandler or cls.special_fields and \
                field not in cls.special_fields:
                json_data[field] = getattr(item, field)
        return json_data


class TaskHandler(BaseHandler):

    allowed_methods = ('GET',)
    fields = ('task_id', 'status')
    special_fields = ('result',)

    @classmethod
    def render(cls, task):
        json_data = {
            "task_id": task.task_id,
            "status": task.state,
            "subtasks": None,
            "result": None,
            "error": None,
            "traceback": None,
        }

        if isinstance(task.result, celery.result.ResultSet):
            json_data['subtasks'] = [TaskHandler.render(t) for t in \
                    task.result.results]
        elif isinstance(task.result, celery.result.AsyncResult):
            json_data['subtasks'] = [TaskHandler.render(task.result)]
        elif isinstance(task.result, Exception):
            json_data['error'] = task.result
            json_data['traceback'] = task.traceback
        else:
            json_data['result'] = task.result

        return json_data

    def read(self, request, task_id):
        try:
            task = celery.result.AsyncResult(task_id)
        except:
            return rc.NOT_FOUND
        return TaskHandler.render(task)


class ClusterChangesHandler(BaseHandler):

    allowed_methods = ('PUT', 'DELETE')

    def update(self, request, cluster_id):
        try:
            cluster = Cluster.objects.get(id=cluster_id)
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

        task = tasks.deploy_cluster.delay(cluster_id)

        for node in cluster.nodes.filter(redeployment_needed=True):
            node.roles = node.new_roles.all()
            node.new_roles.clear()
            node.redeployment_needed = False
            node.save()

        for nw in cluster.release.networks.all():
            for node in cluster.nodes.all():
                nw.update_node_network_info(node)

        task = tasks.deploy_cluster.delay(cluster_id)
<commit_msg>Show task name in API output, fix incorrect merge at deployment start handler<commit_after>import os

import celery
import ipaddr
import json
from piston.handler import BaseHandler
from piston.utils import rc, validate
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings

from nailgun.models import Cluster, Node, Recipe, Role, Release, Network
from nailgun.api.validators import validate_json, validate_json_list
from nailgun.api.forms import ClusterForm, ClusterCreationForm, RecipeForm, \
        RoleForm, RoleFilterForm, NodeCreationForm, NodeFilterForm, NodeForm, \
        ReleaseCreationForm, NetworkCreationForm
from nailgun import tasks
import nailgun.api.validators as vld


class JSONHandler(BaseHandler):
    """
    Basic JSON handler
    """
    fields = None
    special_fields = None

    @classmethod
    def render(cls, item, fields=None):
        json_data = {}
        use_fields = fields if fields else cls.fields
        if not use_fields:
            raise ValueError("No fields for serialize")
        for field in use_fields:
            if cls is JSONHandler or cls.special_fields and \
                field not in cls.special_fields:
                json_data[field] = getattr(item, field)
        return json_data


class TaskHandler(BaseHandler):

    allowed_methods = ('GET',)

    @classmethod
    def render(cls, task):
        json_data = {
            "task_id": task.task_id,
            "name": task.task_name,
            "status": task.state,
            "subtasks": None,
            "result": None,
            "error": None,
            "traceback": None,
        }

        if isinstance(task.result, celery.result.ResultSet):
            json_data['subtasks'] = [TaskHandler.render(t) for t in \
                    task.result.results]
        elif isinstance(task.result, celery.result.AsyncResult):
            json_data['subtasks'] = [TaskHandler.render(task.result)]
        elif isinstance(task.result, Exception):
            json_data['error'] = task.result
            json_data['traceback'] = task.traceback
        else:
            json_data['result'] = task.result

        return json_data

    def read(self, request, task_id):
        try:
            task = celery.result.AsyncResult(task_id)
        except:
            return rc.NOT_FOUND
        return TaskHandler.render(task)


class ClusterChangesHandler(BaseHandler):

    allowed_methods = ('PUT', 'DELETE')

    def update(self, request, cluster_id):
        try:
            cluster = Cluster.objects.get(id=cluster_id)
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

        for node in cluster.nodes.filter(redeployment_needed=True):
            node.roles = node.new_roles.all()
            node.new_roles.clear()
            node.redeployment_needed = False
            node.save()

        for nw in cluster.release.networks.all():
            for node in cluster.nodes.all():
                nw.update_node_network_info(node)

        task = tasks.deploy_cluster.delay(cluster_id)

{'fraction_non_alphanumeric': 0.08792458963107427, 'fraction_numerical': 0.0, 'mean_word_length': 2.4207893274041132, 'pattern_counts': {'":': 13, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1532717', 'n_tokens_mistral': 1725, 'n_tokens_neox': 1662, 'n_words': 431}