예제 #1
0
    def get(self, request):
        """
        This is a get request for getting the file explorer data. It internally calls the
        get_dir_tree_json() in navigator_utils.py to get a list of directories. THIS VIEW EXISTS
        ONLY BECAUSE JSTREE DOES NOT HAVE SUPPORT FOR POST IN LAZY LOADING.

        params sent via the request:

        start_dir: Absolute path to the start directory. If not given, defaulted to "Warriorspace".
        path: Absolute path to the current directory. Send a path via this argument indicates that
              information for current directory's parent needs to be obtained. If not False, it is
              prioritized over start_dir
        lazy_loading: Indicates that jsTree lazy_loading is being used and only direct
                      sub-children's information needs to be obtained.

        """
        nav_obj = Navigator()
        start_dir = "false"
        lazy_loading = True if "lazy_loading" in request.GET and request.GET["lazy_loading"].lower() == "true" else False
        config_data = read_config_file_data()

        get_children_only = False
        if "start_dir" in request.GET:
            get_children_only = True
            start_dir = request.GET["start_dir"]

        if os.environ["pipmode"] == 'True':
            if config_data["pythonsrcdir"] != "" and start_dir == "false":
                get_children_only = False
                if config_data["xmldir"].split("/")[-2] == "warriorspace" or config_data["xmldir"].split("/")[-2] == "Warriorspace":
                    start_dir = config_data["pythonsrcdir"] + "/" +config_data["xmldir"].split("/")[-2]
                elif config_data["xmldir"].split("/")[-3] == "warriorspace" or config_data["xmldir"].split("/")[-3] == "Warriorspace":
                    start_dir = config_data["pythonsrcdir"] + "/" +config_data["xmldir"].split("/")[-3]
                else:
                    start_dir = config_data["pythonsrcdir"]
            elif config_data["pythonsrcdir"] == "" and start_dir == "false":
                get_children_only = False
                start_dir = nav_obj.get_katana_dir()
        else:
            if config_data["pythonsrcdir"] != "" and start_dir == "false":
                get_children_only = False
                if config_data["xmldir"].split("/")[-2] == "warriorspace" or config_data["xmldir"].split("/")[-2] == "Warriorspace":
                    start_dir = config_data["pythonsrcdir"] + "/" +config_data["xmldir"].split("/")[-2]
                elif config_data["xmldir"].split("/")[-3] == "warriorspace" or config_data["xmldir"].split("/")[-3] == "Warriorspace":
                    start_dir = config_data["pythonsrcdir"] + "/" +config_data["xmldir"].split("/")[-3]
                else:
                    start_dir = config_data["pythonsrcdir"]
            elif config_data["pythonsrcdir"] == "" and start_dir == "false":
                get_children_only = False
                start_dir = nav_obj.get_katana_dir()

        if "path" in request.GET:
            get_children_only = False
            start_dir = request.GET["path"]

        output = nav_obj.get_dir_tree_json(start_dir_path=start_dir, lazy_loading=lazy_loading)
        if get_children_only:
            output = output["children"]
        return JsonResponse(output, safe=False)
예제 #2
0
    def ready(self):
        """
        The ready function is trigger only on events like server start up and server reload
        """
        # print "***************You are in Core Katana App Config Class***************"
        nav_obj = Navigator()

        base_directory = nav_obj.get_katana_dir()
        warrior_dir = nav_obj.get_warrior_dir()
        config_file_name = "wf_config.json"
        config_json_file = join_path(base_directory, "config.json")
        settings_file_path = get_abs_path(join_path("wui", "settings.py"),
                                          base_directory)
        core_index_obj = CoreIndex(base_directory,
                                   settings_file_path=settings_file_path)

        available_apps = core_index_obj.get_available_apps()
        settings_apps = core_index_obj.get_apps_from_settings_file()

        AppInformation.information = Apps()

        AppInformation.information.set_apps({
            'base_directory': base_directory,
            'config_file_name': config_file_name,
            'available_apps': available_apps,
            'settings_apps': settings_apps
        })
        if os.environ["pipmode"] == "True":
            pythonsrcdir = read_json_data(config_json_file)['pythonsrcdir']
        else:
            pythonsrcdir = warrior_dir
        ordered_json = validate_config_json(read_json_data(config_json_file),
                                            pythonsrcdir)
        with open(config_json_file, "w") as f:
            f.write(json.dumps(ordered_json, indent=4))
예제 #3
0
def read_config_file(request):
    nav_obj = Navigator()
    config_file_path = join_path(nav_obj.get_katana_dir(), "config.json")
    data = read_json_data(config_file_path)
    if data is None:
        data = False
    return JsonResponse(data)
예제 #4
0
def save_warhorn_config_file(request):
    nav_obj = Navigator()
    directory = request.POST.get('directory')
    if directory == "default":
        directory = os.path.join(nav_obj.get_katana_dir(), "katana.wapps",
                                 "assembler", ".data")
    filepath = os.path.join(directory, request.POST.get('filename') + ".xml")
    json_data = json.loads(request.POST.get('json_data'))
    json_data["data"]["warriorframework"] = "Test"
    data = xmltodict.unparse(json_data)
    response = _save_file(filepath, data)

    return JsonResponse(response)
예제 #5
0
    def post(self, request):
        """
        This is a post request for getting the file explorer data. It internally calls the
        get_dir_tree_json() in navigator_utils.py to get a list of directories.

        params sent via the request:

        start_dir: Absolute path to the start directory. If not given, defaulted to "Warriorspace".
        path: Absolute path to the current directory. Send a path via this argument indicates that
              information for current directory's parent needs to be obtained. If not False, it is
              prioritized over start_dir
        lazy_loading: Indicates that jsTree lazy_loading is being used and only direct
                      sub-children's information needs to be obtained.

        """
        nav_obj = Navigator()
        lazy_loading = True if "data[lazy_loading]" in request.POST and request.POST["data[lazy_loading]"].lower() == "true" else False
        start_dir = "false"
        config_data = read_config_file_data()
        if "data[start_dir]" in request.POST:
            start_dir = request.POST["data[start_dir]"]
        if os.environ["pipmode"] == 'True':
            if config_data["pythonsrcdir"] != "" and start_dir == "false":
                start_dir = config_data["pythonsrcdir"]
            elif config_data["pythonsrcdir"] == "" and start_dir == "false":
                start_dir = nav_obj.get_katana_dir()
        else:
            if config_data["pythonsrcdir"] != "" and start_dir == "false":
                get_children_only = False
                start_dir = config_data["pythonsrcdir"]
            elif config_data["pythonsrcdir"] == "" and start_dir == "false":
                get_children_only = False
                start_dir = nav_obj.get_katana_dir()

        if "data[path]" in request.POST and request.POST["data[path]"] != "false":
            start_dir = get_parent_directory(request.POST["data[path]"])
        output = nav_obj.get_dir_tree_json(start_dir_path=start_dir, lazy_loading=lazy_loading)
        return JsonResponse(output)
예제 #6
0
def save_and_run_warhorn_config_file(request):
    nav_obj = Navigator()
    directory = request.POST.get('directory')
    if directory == "default":
        directory = os.path.join(nav_obj.get_katana_dir(), "katana.wapps",
                                 "assembler", ".data")
    filepath = os.path.join(directory, request.POST.get('filename') + ".xml")
    json_data = json.loads(request.POST.get('json_data'))
    json_data["data"]["warriorframework"] = "Test"
    data = xmltodict.unparse(json_data)
    response = _save_file(filepath, data)
    nav_obj = Navigator()
    warhorn_dir = nav_obj.get_warhorn_dir()
    current_dir = os.getcwd()
    output = ""
    if response["saved"]:
        os.chdir(warhorn_dir)
        output = subprocess.Popen(["python", "warhorn.py", filepath],
                                  stdout=subprocess.PIPE).communicate()[0]
        os.chdir(current_dir)
        os.remove(filepath)
    return JsonResponse({"output": output})
예제 #7
0
파일: views.py 프로젝트: terrakom/wapps
def read_config_file_data():
    nav_obj = Navigator()
    config_file_path = join_path(nav_obj.get_katana_dir(), "config.json")
    data = read_json_data(config_file_path)
    return data
예제 #8
0
    os.environ["pipmode"] = "True"
# except ModuleNotFoundError as error:
except:
    WARRIORDIR = dirname(dirname(abspath(__file__)))
    sys.path.append(WARRIORDIR)
    try:
        import katana

        os.environ["pipmode"] = "False"
    except:
        raise

from katana.utils.navigator_util import Navigator

nav_obj = Navigator()
BASE_DIR = nav_obj.get_katana_dir()
appmanage_py = os.path.join(BASE_DIR, "appmanage.py")

data = requests.get('https://pypi.python.org/pypi/katanaframework/json')
data = data.json()
ord_dict = OrderedDict()
ord_dict = data['releases'].keys()
versn_list = list(ord_dict)

if (os.path.exists(os.path.join(BASE_DIR, 'wapps'))
        or os.path.exists(os.path.join(BASE_DIR, 'native'))):
    print(
        colored(
            "Please manually backup and then delete the following dirs before performing the upgrade operation",
            "red"))
    print(colored("1. katana/native", "red"))
예제 #9
0
from django.views import View
import collections
import json
import os
import xmltodict
from django.http import JsonResponse
from django.template.loader import render_to_string
from katana.utils.directory_traversal_utils import join_path, get_parent_dir_path, get_dir_from_path
from katana.utils.json_utils import read_json_data, read_xml_get_json
from katana.utils.navigator_util import Navigator
from katana.wapps.projects.project_utils.defaults import on_errors, impacts, contexts, runmodes, \
    executiontypes, runtypes
from katana.wapps.projects.project_utils.verify_project_file import VerifyProjectFile

navigator = Navigator()
CONFIG_FILE = join_path(navigator.get_katana_dir(), "config.json")
APP_DIR = join_path(navigator.get_katana_dir(), "wapps", "projects")
STATIC_DIR = join_path(APP_DIR, "static", "projects")
TEMPLATE = join_path(STATIC_DIR, "base_templates", "Project_Template.xml")
DROPDOWN_DEFAULTS = read_json_data(
    join_path(STATIC_DIR, "base_templates", "dropdowns_data.json"))


class projectsView(View):
    def get(self, request):
        """
        Get Request Method
        """
        return render(request, 'projects/projects.html')

예제 #10
0
"""

# -*- coding: utf-8 -*-

import os
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from katana.native.settings.settings import Settings
from katana.utils.navigator_util import Navigator
from katana.utils.json_utils import read_json_data
import ast
import json

nav_obj = Navigator()
REF_FILE = os.path.join(
    nav_obj.get_katana_dir(),
    "katana.native",
    "assembler",
    "static",
    "assembler",
    "base_templates",
    "empty.xml",
)
config_json_path = os.path.join(nav_obj.get_katana_dir(), "config.json")

controls = Settings()


def index(request):
    return render(request, "settings/index.html",
                  {"data": controls.get_location()})
예제 #11
0
def get_data_directory(request):
    nav_obj = Navigator()
    directory = os.path.join(nav_obj.get_katana_dir(), "katana.wapps",
                             "assembler", ".data")
    return JsonResponse({"data_directory": directory})
예제 #12
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
import subprocess
import xmltodict
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from katana.wapps.assembler.assembler_utils.repository_details import KwRepositoryDetails
from katana.wapps.assembler.assembler_utils.verify_file_contents import VerifyFileContents
from katana.utils.directory_traversal_utils import delete_dir
from katana.utils.git_utils import get_repository_name, check_url_is_a_valid_repo
from katana.utils.navigator_util import Navigator
nav_obj = Navigator()
REF_FILE = os.path.join(nav_obj.get_katana_dir(), "wapps", "assembler",
                        "static", "assembler", "base_templates", "empty.xml")


class AssemblerView(View):
    def get(self, request):
        return render(request, 'assembler/assembler.html')


class ConfigurationFileOps(View):
    def post(self, request):
        template = request.POST.get('filepath')
        filename = "Untitled"
        final_data = {}

        if template == "false":
예제 #13
0
class VerifyFileContents:
    def __init__(self, data_file, ref_data_file):
        self.data_file = data_file
        self.data = read_xml_get_json(data_file)
        self.ref_data_file = ref_data_file
        self.nav_obj = Navigator()
        self.dependency_template = join_path(self.nav_obj.get_katana_dir(),
                                             "native", "settings", "static",
                                             "settings", "base_templates",
                                             "empty.xml")
        self.ref_data = self._get_ref_data()
        self.dependency_dict = self.__get_dependency_dict()

    def _get_ref_data(self):
        data = read_xml_get_json(self.ref_data_file)
        dependency_data = read_xml_get_json(self.dependency_template)
        data["data"]["warhorn"] = copy.deepcopy(
            dependency_data["data"]["warhorn"])
        return data

    def __get_dependency_dict(self):
        output = {}
        for el in self.ref_data["data"]["warhorn"]["dependency"]:
            output[el["@name"]] = {
                "version": el["@version"],
                "description": el["@description"]
            }
        return output

    def verify_file(self):
        output = {"status": True, "message": ""}

        if self.data is None:
            output["status"] = False
            output[
                "message"] = "An error occurred while trying to read {0}".format(
                    self.data_file)
        elif "data" not in self.data:
            output["status"] = False
            output[
                "message"] = "{0} does not seem to be in correct format".format(
                    self.data_file)

        if output["status"]:
            self.verify_dependency_json()
            self.verify_tools_data()
            self.verify_drivers_json()
            self.verify_warriorspace_data()

        return output

    def verify_dependency_json(self, ):
        flag = True
        if "warhorn" not in self.data["data"]:
            self.data["data"]["warhorn"] = copy.deepcopy(
                self.ref_data["data"]["warhorn"])
            flag = False
        if "dependency" not in self.data["data"]["warhorn"]:
            self.data["data"]["warhorn"]["dependency"] = copy.deepcopy(
                self.ref_data["data"]["warhorn"]["dependency"])
            flag = False
        if not isinstance(self.data["data"]["warhorn"]["dependency"], list):
            self.data["data"]["warhorn"]["dependency"] = [
                self.data["data"]["warhorn"]["dependency"]
            ]

        if flag:
            data = copy.deepcopy(self.data["data"]["warhorn"]["dependency"])
            extra_dependencies = set()
            for i in range(0, len(data)):
                for key, value in data[i].items():
                    if key == "@name":
                        if value in self.dependency_dict:
                            data[i]["version"] = self.dependency_dict[value][
                                "version"]
                            data[i]["description"] = self.dependency_dict[
                                value]["description"]
                            try:
                                module_name = __import__(value)
                                some_var = module_name.__version__
                            except ImportError:
                                data[i]["installed"] = False
                                data[i]["matched"] = False
                            except Exception as e:
                                print("-- An Exception Occurred -- while getting details about " \
                                      "{0}: {1}".format(value, e))
                                data[i]["installed"] = False
                                data[i]["matched"] = False
                            else:
                                data[i]["installed"] = some_var
                                if self.dependency_dict[value] == some_var:
                                    data[i]["matched"] = True
                                elif self.dependency_dict[value] > some_var:
                                    data[i]["matched"] = "lower"
                                else:
                                    data[i]["matched"] = "higher"
                            break
                        else:
                            extra_dependencies.add(i)
            dependency_list = []
            for i in range(0, len(data)):
                if i not in extra_dependencies:
                    dependency_list.append(copy.deepcopy(data[i]))
            self.data["data"]["warhorn"]["dependency"] = copy.deepcopy(
                dependency_list)

    def verify_tools_data(self):
        if "tools" not in self.data["data"]:
            self.data["data"]["tools"] = copy.deepcopy(
                self.ref_data["data"]["tools"])
        else:
            for key, value in self.ref_data["data"]["tools"].items():
                if key not in self.data["data"]["tools"]:
                    self.data["data"]["tools"][key] = self.ref_data["data"][
                        "tools"][key]

            url = self.data["data"]["tools"]["@url"]
            if url != "":
                self.data["data"]["tools"]["name"] = get_repository_name(
                    url=url)
                self.data["data"]["tools"][
                    "available"] = check_url_is_a_valid_repo(url=url)
            else:
                self.data["data"]["tools"]["available"] = False

    def verify_drivers_json(self):
        flag = True
        if "drivers" not in self.data["data"]:
            self.data["data"]["drivers"] = copy.deepcopy(
                self.ref_data["data"]["drivers"])
            flag = False

        if "repository" not in self.data["data"]["drivers"]:
            self.data["data"]["drivers"]["repository"] = copy.deepcopy(
                self.ref_data["data"]["drivers"]["repository"])
            flag = False

        if not isinstance(self.data["data"]["drivers"]["repository"], list):
            self.data["data"]["drivers"]["repository"] = [
                self.data["data"]["drivers"]["repository"]
            ]

        if flag:
            for i in range(0, len(self.data["data"]["drivers"]["repository"])):
                for key, value in self.ref_data["data"]["drivers"][
                        "repository"].items():
                    if key not in self.data["data"]["drivers"]["repository"][
                            i]:
                        if key != "driver":
                            self.data["data"]["drivers"]["repository"][i][
                                key] = self.ref_data["data"]["drivers"][
                                    "repository"]["key"]
                        else:
                            self.data["data"]["drivers"]["repository"][i][
                                key] = copy.deepcopy(
                                    self.ref_data["data"]["drivers"]
                                    ["repository"][key])

                            if not isinstance(
                                    self.data["data"]["drivers"]["repository"]
                                [i][key], list):
                                self.data["data"]["drivers"]["repository"][i][
                                    key] = [
                                        self.data["data"]["drivers"]
                                        ["repository"][i][key]
                                    ]

                url = self.data["data"]["drivers"]["repository"][i]["@url"]
                if url != "":
                    self.data["data"]["drivers"]["repository"][i][
                        "name"] = get_repository_name(url=url)
                    available = check_url_is_a_valid_repo(url=url)
                    self.data["data"]["drivers"]["repository"][i][
                        "available"] = available
                    if available:
                        drivers_data = []
                        drivers_index = set()
                        temp_directory = os.path.join(
                            self.nav_obj.get_katana_dir(), "katana.wapps",
                            "assembler", ".data")
                        kw_repo_obj = KwRepositoryDetails(url, temp_directory)
                        drivers = set(kw_repo_obj.get_pd_names())

                        if not isinstance(
                                self.data["data"]["drivers"]["repository"][i]
                            ["driver"], list):
                            self.data["data"]["drivers"]["repository"][i][
                                "driver"] = [
                                    self.data["data"]["drivers"]["repository"]
                                    [i]["driver"]
                                ]

                        for j in range(
                                0,
                                len(self.data["data"]["drivers"]["repository"]
                                    [i]["driver"])):
                            if "@name" not in self.data["data"]["drivers"][
                                    "repository"][i]["driver"][j]:
                                self.data["data"]["drivers"]["repository"][i][
                                    "driver"][j]["@name"] = self.ref_data[
                                        "data"]["drivers"]["repository"][
                                            "driver"]["@name"]
                            else:
                                if self.data["data"]["drivers"]["repository"][
                                        i]["driver"][j]["@name"] in drivers:
                                    drivers.remove(self.data["data"]["drivers"]
                                                   ["repository"][i]["driver"]
                                                   [j]["@name"])
                                else:
                                    drivers_index.add(j)
                            if "@clone" not in self.data["data"]["drivers"][
                                    "repository"][i]["driver"][j]:
                                self.data["data"]["drivers"]["repository"][i][
                                    "driver"][j]["@clone"] = self.ref_data[
                                        "data"]["drivers"]["repository"][
                                            "driver"]["@clone"]

                        for j in range(
                                0,
                                len(self.data["data"]["drivers"]["repository"]
                                    [i]["driver"])):
                            if j not in drivers_index:
                                drivers_data.append(
                                    copy.deepcopy(
                                        self.data["data"]["drivers"]
                                        ["repository"][i]["driver"][j]))
                        self.data["data"]["drivers"]["repository"][i][
                            "driver"] = copy.deepcopy(drivers_data)

                        for driver_name in drivers:
                            self.data["data"]["drivers"]["repository"][i][
                                "driver"].append({
                                    "@name": driver_name,
                                    "@clone": "no"
                                })

                        if os.path.isdir(kw_repo_obj.repo_directory):
                            delete_dir(kw_repo_obj.repo_directory)
                else:
                    self.data["data"]["drivers"]["repository"][i][
                        "available"] = False

    def verify_warriorspace_data(self):
        flag = True
        if "warriorspace" not in self.data["data"]:
            flag = False
            self.data["data"]["warriorspace"] = copy.deepcopy(
                self.ref_data["data"]["warriorspace"])

        if "repository" not in self.data["data"]["warriorspace"]:
            flag = False
            self.data["data"]["warriorspace"]["repository"] = copy.copy(
                self.ref_data["data"]["warriorspace"]["repository"])

        if not isinstance(self.data["data"]["warriorspace"]["repository"],
                          list):
            self.data["data"]["warriorspace"]["repository"] = [
                self.data["data"]["warriorspace"]["repository"]
            ]

        if flag:
            for i in range(
                    0, len(self.data["data"]["warriorspace"]["repository"])):
                for key, value in self.ref_data["data"]["warriorspace"][
                        "repository"].items():
                    if key not in self.data["data"]["warriorspace"][
                            "repository"][i]:
                        self.data["data"]["warriorspace"]["repository"][i][
                            key] = self.ref_data["data"]["warriorspace"][
                                "repository"][key]

                url = self.data["data"]["warriorspace"]["repository"][i][
                    "@url"]
                if url != "":
                    self.data["data"]["warriorspace"]["repository"][i][
                        "name"] = get_repository_name(url=url)
                    self.data["data"]["warriorspace"]["repository"][i][
                        "available"] = check_url_is_a_valid_repo(url=url)
                else:
                    self.data["data"]["warriorspace"]["repository"][i][
                        "available"] = False
예제 #14
0
    sys.path.append(WARRIORDIR)
    try:
        import katana

        os.environ["pipmode"] = "False"
    except:
        raise
from katana.primary_process import __appmanager__, install_custom_app, install_default_apps, \
    remove_app_from_settings_custom, remove_appurl_from_urls_custom, remove_cust_app_source, \
    update_fname, update_logo, update_panel_color, create_log
from katana.utils.navigator_util import Navigator
from katana.utils.json_utils import read_json_data
from katana.utils.directory_traversal_utils import join_path

nav_obj = Navigator()
BASE_DIR = nav_obj.get_katana_dir()
wapps_dir_path = BASE_DIR + "/wapps/"
wapps_dir = BASE_DIR + "/wapps"
native_dir = BASE_DIR + "/native"
settings_file = BASE_DIR + "/wui/settings.py"

if os.environ["pipmode"] == "True":
    virtual_env = os.getenv('VIRTUAL_ENV')
    if virtual_env:
        app_config_file = virtual_env + os.sep + "katana_configs" + os.sep + "app_config.json"
    elif os.path.exists(site.getuserbase() + os.sep + "katana_configs"):
        app_config_file = site.getuserbase(
        ) + os.sep + "katana_configs" + os.sep + "app_config.json"
    elif os.path.exists("/usr/local/katana_configs"):
        app_config_file = "/usr/local/katana_configs/app_config.json"
    else:
예제 #15
0
class Settings:
    def __init__(self):
        self.navigator = Navigator()
        self.static_dir = join_path(self.navigator.get_katana_dir(), "native",
                                    "settings", "static", "settings")

    def get_location(self):
        pass

    def smart_analysis_handler(self, request):
        mainFile = self.navigator.get_katana_dir(
        ) + os.sep + 'native' + os.sep + 'settings' + os.sep + 'Tools' + os.sep + 'connection' + os.sep + 'connect_settings.xml'
        if request.method == 'POST':
            val = xmltodict.unparse(
                {
                    'credentials': {
                        'system': json.loads(request.POST.get('data'))
                    }
                },
                pretty=True)
            with open(mainFile, 'w') as f:
                f.write(val)
        else:
            with open(mainFile, 'rb') as f:
                mainDict = xmltodict.parse(f)['credentials']
            if mainDict is not None and not isinstance(mainDict['system'],
                                                       list):
                mainDict['system'] = [mainDict['system']]

            return mainDict

    def general_setting_handler(self, request):
        json_file = self.navigator.get_katana_dir() + os.sep + 'config.json'
        if os.path.exists(self.navigator.get_warrior_dir() + os.sep + 'Tools' +
                          os.sep + 'w_settings.xml'):
            w_settings = self.navigator.get_warrior_dir(
            ) + os.sep + 'Tools' + os.sep + 'w_settings.xml'
        else:
            w_settings = self.navigator.get_katana_dir(
            ) + os.sep + 'native' + os.sep + 'settings' + os.sep + 'Tools' + os.sep + 'w_settings.xml'
        elem_file = xml_controler.parse(w_settings)
        elem_file = elem_file.getroot()
        elem = self.search_by_name('def_dir', elem_file)
        def_dir_string = xml_controler.tostring(elem)
        def_dir_xml_obj = elem

        if request.method == 'POST':
            w_settings_data = {
                'Setting': {
                    'Logsdir': '',
                    'Resultsdir': '',
                    '@name': ''
                }
            }
            returned_json = json.loads(request.POST.get('data'))

            for k, v in list(w_settings_data['Setting'].items()):
                w_settings_data['Setting'][k] = returned_json[0][k]
                del returned_json[0][k]

            elem_file.remove(def_dir_xml_obj)
            val = xmltodict.unparse(w_settings_data, pretty=True)
            elem_file.insert(0, xml_controler.fromstring(val))
            with open(w_settings, 'wb') as f:
                f.write(xml_controler.tostring(elem_file))
            with open(json_file, 'w') as f:
                f.write(
                    json.dumps(returned_json[0],
                               indent=4,
                               separators=(',', ': ')))
        else:
            with open(json_file, 'r') as f:
                json_data = json.load(f)
            if os.environ["pipmode"] == 'True':
                pythonsrcdir = read_json_data(json_file)['pythonsrcdir']
            else:
                pythonsrcdir = self.navigator.get_warrior_dir()
            data = {
                'fromXml':
                xmltodict.parse(def_dir_string).get('Setting'),
                'fromJson':
                validate_config_json(json_data,
                                     self.navigator.get_warrior_dir())
            }

            return data

    def profile_setting_handler(self, request):
        json_file = self.navigator.get_katana_dir(
        ) + os.sep + 'user_profile.json'
        config_json_file = self.navigator.get_katana_dir(
        ) + os.sep + 'config.json'
        if request.method == 'POST':
            data = json.loads(request.POST.get('data'))
            with open(json_file, 'w') as f:
                f.write(
                    json.dumps(data[0],
                               sort_keys=True,
                               indent=4,
                               separators=(',', ': ')))
            with open(config_json_file, 'r+') as a:
                new_json = json.load(a)
                new_json['engineer'] = data[0]['firstName']
                a.seek(0)
                a.truncate()
                a.write(
                    json.dumps(new_json,
                               sort_keys=True,
                               indent=4,
                               separators=(',', ': ')))
        else:
            with open(json_file, 'r') as f:
                json_data = json.load(f)

            return json_data

    def search_by_name(self, name, file):
        for elem in file.findall('Setting'):
            if elem.get('name') == name:
                return elem

    def email_setting_handler(self, request):
        w_settings = self.navigator.get_katana_dir(
        ) + os.sep + 'native' + os.sep + 'settings' + os.sep + 'Tools' + os.sep + 'w_settings.xml'
        elem_file = xml_controler.parse(w_settings)
        elem_file = elem_file.getroot()
        elem = self.search_by_name('mail_to', elem_file)
        email_string = xml_controler.tostring(elem)
        email_xml_obj = elem

        if request.method == 'POST':
            elem_file.remove(email_xml_obj)
            val = xmltodict.unparse(
                {'Setting': json.loads(request.POST.get('data'))}, pretty=True)
            elem_file.append(xml_controler.fromstring(val))
            with open(w_settings, 'w') as f:
                f.write(xml_controler.tostring(elem_file))
        else:
            xmldoc = xmltodict.parse(email_string)
            return xmldoc

    def jira_setting_handler(self, request):
        jira_config = self.navigator.get_katana_dir(
        ) + os.sep + 'native' + os.sep + 'settings' + os.sep + 'Tools' + os.sep + 'jira' + os.sep + 'jira_config.xml'
        elem_file = xml_controler.parse(jira_config)
        elem_file = elem_file.getroot()
        xml_string = xml_controler.tostring(elem_file)
        if request.method == 'POST':
            val = xmltodict.unparse(
                {'jira': {
                    'system': json.loads(request.POST.get('data'))
                }},
                pretty=True)
            with open(jira_config, 'w') as f:
                f.write(val)
        else:
            xmldoc = xmltodict.parse(xml_string)
            if xmldoc is not None and xmldoc['jira'] is not None:
                if not isinstance(xmldoc['jira']['system'], list):
                    xmldoc['jira']['system'] = [xmldoc['jira']['system']]
                for system in xmldoc['jira']['system']:
                    for k, v in list(system.items()):
                        if k == 'issue_type':
                            v = json.dumps(v)
                            system[k] = v
            return xmldoc

    def secret_handler(self, request):
        keyDoc = self.navigator.get_katana_dir(
        ) + os.sep + 'native' + os.sep + 'settings' + os.sep + 'Tools' + os.sep + 'admin' + os.sep + 'secret.key'
        if request.method == 'POST':
            val = request.POST.get("data[0][value]")
            elem_file = open(keyDoc, 'w')
            elem_file.write(val)
            elem_file.close()
        else:
            elem_file = open(keyDoc, 'r')
            key_data = elem_file.read()
            elem_file.close()
            return key_data

    def prerequisites_handler(self, request):
        ref_file = join_path(self.static_dir, "base_templates", "empty.xml")
        prereqs = read_xml_get_json(ref_file)["data"]["warhorn"]["dependency"]
        prereq_data = []
        for prereq in prereqs:
            temp = {}
            for key, value in list(prereq.items()):
                temp[key.strip('@')] = value

            temp["status"] = "install"
            try:
                module_name = __import__(temp["name"])
                some_var = module_name.__version__
            except ImportError:
                temp["available_version"] = "--"
                temp["installBtnText"] = "Install"
            except Exception as e:
                print(
                    "-- An Exception Occurred -- while getting details about {0}: {1}"
                    .format(temp["name"], e))
                temp["available_version"] = "--"
                temp["installBtnText"] = "Install"
            else:
                temp["available_version"] = some_var
                if LooseVersion(str(temp["version"])) <= LooseVersion(
                        str(temp["available_version"])):
                    temp["installBtnText"] = "Installed"
                    temp["status"] = "installed"
                else:
                    temp["installBtnText"] = "Upgrade"
                    temp["status"] = "upgrade"

            prereq_data.append(copy.deepcopy(temp))
        return prereq_data

    def prereq_installation_handler(self, request):
        name = request.POST.get('name')
        admin = request.POST.get('admin')
        version = request.POST.get('version')
        status = False
        return_code = -9
        command = ["pip", "install", "{0}=={1}".format(name, version)]
        if admin == "true":
            if not hasattr(sys, 'real_prefix'):
                command.insert(0, "sudo")
        else:
            command.append("--user")
        p = subprocess.Popen(command,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        kill = lambda process: process.kill()
        my_timer = Timer(10, kill, [p])
        try:
            my_timer.start()
            out, err = p.communicate()
            return_code = p.returncode
            if return_code == 0:
                status = True
        finally:
            if return_code == -9:
                err = "Command could not be completed."
                out = "Command could not be completed in 30 seconds - may be the user is not authorized to install {0}".format(
                    name)
            my_timer.cancel()
        return {
            "status": status,
            "return_code": return_code,
            "errors": err,
            "output": out
        }
예제 #16
0
파일: views.py 프로젝트: terrakom/native
See the License for the specific language governing permissions and
limitations under the License.

"""

# -*- coding: utf-8 -*-

import os
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from katana.native.settings.settings import Settings
from katana.utils.navigator_util import Navigator
import ast

nav_obj = Navigator()
REF_FILE = os.path.join(nav_obj.get_katana_dir(), "katana.native", "assembler",
                        "static", "assembler", "base_templates", "empty.xml")

controls = Settings()


def index(request):
    return render(request, 'settings/index.html',
                  {"data": controls.get_location()})


def email_setting_handler(request):
    return render(request, 'settings/email_setting_handler.html',
                  {"setting": controls.email_setting_handler(request)})