def __init__(self, dictionary):
     # Fix error handling for None
     self._dictionary = dictionary
     self._logger = PlatformLogger('wlsdeploy.json')
     return
class MBeanMethodHelper(object):
    
    __logger = PlatformLogger('test.aliases.generate', resource_bundle_name='aliastest_rb')
    __logger.set_level(Level.FINER)

    def __init__(self, mbean_instance, mbean_path, mbean_type=None):
        self.__class_name__ = self.__class__.__name__
        self.__mbean_path = mbean_path
        self.__mbean_instance = self.__encapsulate_mbean_instance(mbean_instance=mbean_instance, mbean_path=mbean_path)
        self.__mbean_type = mbean_type
        self.__mbean_info = None
        self.__all_helpers = None
        self.__child_mbean_helpers = None
        self.__attribute_mbean_helpers = None

    def get_mbean_type(self):
        if self.__mbean_type is None:
            _get_mbean_type(self.__mbean_instance)
        return self.__mbean_type

    def get_attributes(self):
        _method_name = 'get_attributes'
        if self.__attribute_mbean_helpers is None:
            self.__attribute_mbean_helpers = all_utils.dict_obj()
            if self.__exists():
                for attribute_name, helper in self.get_all_attributes().iteritems():
                    if helper.is_attribute():
                        self.__logger.finest('MBean {0} has attribute {1} in CMO methods map', self.get_mbean_type(),
                                             attribute_name, class_name=self.__class_name__, method_name=_method_name)
                        self.__attribute_mbean_helpers[attribute_name] = helper
            else:
                self.__logger.finer('MBean type {0} is not valid and cannot produce a list of attributes',
                                    self.get_mbean_type(), class_name=self.__class_name__, method_name=_method_name)
        return self.__attribute_mbean_helpers

    def get_attribute(self, attribute_name):
        if attribute_name in self.get_attributes():
            return self.get_attributes()[attribute_name]
        else:
            return self.__create_attribute_helper(attribute_name)

    def get_child_mbeans(self):
        _method_name = 'get_child_mbeans'
        if self.__child_mbean_helpers is None:
            self.__child_mbean_helpers = all_utils.dict_obj()
            if self.__exists():
                for attribute_name, helper in self.get_all_attributes().iteritems():
                    if helper.is_mbean() and not all_utils.ignore_mbean(attribute_name):
                        self.__logger.finest('MBean type {0} has child MBean {1} in CMO methods map',
                                             self.get_mbean_type(), attribute_name,
                                             class_name=self.__class_name__, method_name=_method_name)
                        self.__child_mbean_helpers[attribute_name] = helper
            else:
                self.__logger.finer('MBean type {0} is not valid and cannot produce a list of child MBeans',
                                    self.get_mbean_type(), class_name=self.__class_name__, method_name=_method_name)
        return self.__child_mbean_helpers

    def get_child_mbean(self, attribute):
        if attribute in self.get_child_mbeans():
            return self.get_child_mbeans()[attribute]
        else:
            return self.__create_attribute_helper(attribute)

    def get_all_attributes(self):
        _method_name = 'get_attributes'
        if self.__all_helpers is None:
            self.__all_helpers = all_utils.dict_obj()
            if self.__exists():
                for attribute_name in self.__get_mbean_info():
                    self.__all_helpers[attribute_name] = self.__create_attribute_helper(attribute_name)
            else:
                self.__logger.finer('MBean type {0} is not valid and cannot produce a list of attributes',
                                    self.get_mbean_type(), class_name=self.__class_name__, method_name=_method_name)
        return self.__all_helpers

    def get_all_attribute(self, attribute_name):
        if attribute_name in self.get_all_attributes():
            return self.get_all_attributes()[attribute_name]
        else:
            return self.__create_attribute_helper(attribute_name)

    def generate_attribute(self, dictionary, attribute_name, helper=None):
        _method_name = 'generate_attribute'
        if helper is None:
            helper = self.get_attribute(attribute_name)
        if helper is not None:
            self.__logger.finer('WLSDPLYST-01119', self.__mbean_type, attribute_name, class_name=self.__class_name__,
                                method_name=_method_name)
            helper.generate_attribute(dictionary)
        else:
            self.__logger.fine('Mbean type {0} attribute {1} cannot be located', self.__mbean_type, attribute_name,
                               class_name=self.__class_name__, method_name=_method_name)

    def __create_attribute_helper(self, attribute_name):
        return MBeanMethodAttributeHelper(self.__mbean_info, attribute_name, self.__mbean_instance)

    def __exists(self):
        return self.__get_mbean_info() is not None and self.__len__() > 0

    def __get_mbean_info(self):
        _method_name = '__get_mbean_info'
        if self.__mbean_info is None:
            method_list = self.__mbean_instance.getClass().getMethods()
            if method_list is None or len(method_list) == 0:
                self.__mbean_info = dict()
                self.__logger.fine('Unable to locate CMO methods for MBean at location {0}', self.__mbean_path,
                                   class_name=self.__class_name__, method_name=_method_name)
            else:
                self.__mbean_info = self.__massage_methods(method_list)
        return self.__mbean_info

    def __encapsulate_mbean_instance(self, mbean_instance=None, mbean_path=None):
        _method_name = '__encapsulate_mbean_instance'
        if mbean_instance is None:
            mbean_instance = generator_wlst.get_mbean_proxy(mbean_path)
        path = mbean_path
        if path is None:
            path = generator_wlst.current_path()
        self.__logger.finer('Located the MBean instance is {0} at location {1}',
                            Boolean(mbean_instance is not None), path,
                            class_name=self.__class_name__, method_name=_method_name)

        return mbean_instance

    def __massage_methods(self, methods):
        _method_name = '__massage_methods'
        self.__logger.entering(len(methods), class_name=self.__class_name__, method_name=_method_name)
        attribute_map = dict()
        for attribute_name in _get_attribute_names(methods):
            attribute_map[attribute_name] = [method for method in methods if method.getName().endswith(attribute_name)]
        self.__logger.exiting(class_name=self.__class_name__, method_name=_method_name, result=len(attribute_map))
        return attribute_map

    def __len__(self):
        if self.__mbean_info is not None and len(self.__mbean_info) > 0:
            return len(self.__mbean_info.keys())
        return 0

    def str(self):
        return self.__str__()

    def __str__(self):
        return '%s, %s, valid=%s location=%s' % (self.__class_name__, self.get_mbean_type(),
                                                 Boolean(self.__exists()), self.__mbean_path)

    def __repr__(self):
        return self.__class_name__ + ' MBean type ' + self.get_mbean_type() + \
               ' valid=' + Boolean(self.__exists()).toString()
Esempio n. 3
0
"""
Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
The Universal Permissive License (UPL), Version 1.0
"""

from wlsdeploy.logging.platform_logger import PlatformLogger

_logger = PlatformLogger('wlsdeploy.deploy')


def log_updating_folder(type_name, parent_type, parent_name, is_add,
                        class_name, method_name):
    """
    Log a message indicating that a folder is being updated or added.
    The type of the folder and the type and name of its parent are logged, if present.
    :param type_name: the type of the folder being updated
    :param parent_type: the type of the folder's parent
    :param parent_name: the name of the folder's parent
    :param is_add: true if the folder is being added
    :param class_name: the class name of the caller
    :param method_name: the method name of the caller
    """
    if is_add:
        if parent_type is None:
            _logger.info('WLSDPLY-09600',
                         type_name,
                         class_name=class_name,
                         method_name=method_name)
        elif parent_name is None:
            _logger.info('WLSDPLY-09601',
                         type_name,
Esempio n. 4
0
 def setUp(self):
     self.name = 'ModelHelpPrinterTestCase'
     self._logger = PlatformLogger('wlsdeploy.modelhelp')
from wlsdeploy.util import tool_exit
from wlsdeploy.util import variables
from wlsdeploy.util import wlst_extended
from wlsdeploy.util import wlst_helper
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.model_context import ModelContext
from wlsdeploy.util.model_translator import FileToPython
from wlsdeploy.util.weblogic_helper import WebLogicHelper
from wlsdeploy.tool.create import atp_helper

wlst_extended.wlst_functions = globals()

_program_name = CREATE_DOMAIN

_class_name = 'create'
__logger = PlatformLogger('wlsdeploy.create')
__wlst_mode = WlstModes.OFFLINE
__version = WebLogicHelper(__logger).get_actual_weblogic_version()
__tmp_model_dir = None

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH,
    CommandLineArgUtil.DOMAIN_TYPE_SWITCH
]

__optional_arguments = [
    CommandLineArgUtil.ARCHIVE_FILE_SWITCH,
    CommandLineArgUtil.DOMAIN_HOME_SWITCH,
    CommandLineArgUtil.DOMAIN_PARENT_SWITCH,
    CommandLineArgUtil.JAVA_HOME_SWITCH,
    CommandLineArgUtil.MODEL_FILE_SWITCH,
Esempio n. 6
0
from wlsdeploy.exception import exception_helper
from wlsdeploy.exception.expection_types import ExceptionType
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.encrypt import encryption_utils
from wlsdeploy.tool.util.alias_helper import AliasHelper
from wlsdeploy.util import getcreds
from wlsdeploy.util import variables as variable_helper
from wlsdeploy.util import wlst_helper
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.model_context import ModelContext
from wlsdeploy.util.model_translator import FileToPython
from wlsdeploy.util.model_translator import PythonToFile

_program_name = 'encryptModel'
_class_name = 'encrypt'
__logger = PlatformLogger('wlsdeploy.encrypt')

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH,
]

__optional_arguments = [
    CommandLineArgUtil.DOMAIN_TYPE_SWITCH,
    CommandLineArgUtil.MODEL_FILE_SWITCH,
    CommandLineArgUtil.VARIABLE_FILE_SWITCH,
    CommandLineArgUtil.PASSPHRASE_SWITCH,
    CommandLineArgUtil.ENCRYPT_MANUAL_SWITCH,
    CommandLineArgUtil.ONE_PASS_SWITCH
]

from wlsdeploy.util import target_configuration_helper
from wlsdeploy.util import tool_exit
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.model import Model
from wlsdeploy.util.model_context import ModelContext
from wlsdeploy.util.model_translator import FileToPython
from wlsdeploy.util.weblogic_helper import WebLogicHelper
from wlsdeploy.yaml.yaml_translator import PythonToYaml

VALIDATION_FAIL = 2
PATH_TOKEN = '|'
BLANK_LINE = ""

_program_name = 'prepareModel'
_class_name = 'prepare_model'
__logger = PlatformLogger('wlsdeploy.prepare_model')

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH,
    CommandLineArgUtil.MODEL_FILE_SWITCH, CommandLineArgUtil.OUTPUT_DIR_SWITCH,
    CommandLineArgUtil.TARGET_SWITCH
]

__optional_arguments = [CommandLineArgUtil.VARIABLE_FILE_SWITCH]

all_changes = []
all_added = []
all_removed = []
compare_msgs = sets.Set()

"""
Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
The Universal Permissive License (UPL), Version 1.0
"""
import com.oracle.cie.domain.script.jython.WLSTException as offlineWLSTException

import wlstModule as wlst

from wlsdeploy.exception import exception_helper
from wlsdeploy.logging.platform_logger import PlatformLogger
from oracle.weblogic.deploy.util import PyWLSTException

_logger = PlatformLogger('wlsdeploy.wlst')
_class_name = 'wlst_helper'


def cd(path):
    """
    Change location to the provided path.

    :param path: wlst directory to which to change location
    :return: cmo object reference of the new location
    :raises: PyWLSTException: if a WLST error occurs
    """

    _method_name = 'cd'
    _logger.finest('WLSDPLY-00001', path, class_name=_class_name, method_name=_method_name)

    try:
        result = wlst.cd(path)
    except (wlst.WLSTException, offlineWLSTException), e:
class _ModelEncrypter(object):
    """
    Enables encryption of the password fields in a model dictionary.
    The methods in this class are not thread safe, and it should be accessed only through the static methods at
    the end of this file.
    """
    _class_name = '_ModelEncrypter'
    _logger = PlatformLogger('wlsdeploy.encrypt')

    def __init__(self, passphrase, alias_helper, variables=None):
        """
        Initialize variables for use throughout.
        :param passphrase: the passphrase used to encrypt/decrypt the passwords
        :param alias_helper: the alias helper for the tool
        :param variables: the variables property object
        :raises EncryptionException if an error occurs
        """
        self.passphrase = passphrase
        self.alias_helper = alias_helper
        self.variables = variables
        self.model_changes = 0
        self.variables_changed = []

    def encrypt_model_dictionary(self, model_dict):
        """
        Encrypt the model dictionary (and referenced variables, if provided) using the specified passphrase.
        :param model_dict: the model dictionary
        :return: the number of model elements encrypted, and the number of variables encrypted
        :raises EncryptionException if an error occurs
        """

        if model.get_model_domain_info_key() in model_dict:
            domain_info_dict = model_dict[model.get_model_domain_info_key()]
            self._encrypt_info_nodes(domain_info_dict)

        if model.get_model_topology_key() in model_dict:
            top_folder_names = self.alias_helper.get_model_topology_top_level_folder_names(
            )
            topology_nodes = model_dict[model.get_model_topology_key()]
            location = LocationContext()
            self._encrypt_nodes(location, topology_nodes, top_folder_names)

        if model.get_model_resources_key() in model_dict:
            top_folder_names = self.alias_helper.get_model_resources_top_level_folder_names(
            )
            resources_nodes = model_dict[model.get_model_resources_key()]
            location = LocationContext()
            self._encrypt_nodes(location, resources_nodes, top_folder_names)

        if model.get_model_deployments_key() in model_dict:
            top_folder_names = self.alias_helper.get_model_app_deployments_top_level_folder_names(
            )
            deployments_nodes = model_dict[model.get_model_deployments_key()]
            location = LocationContext()
            self._encrypt_nodes(location, deployments_nodes, top_folder_names)

        return self.model_changes, len(self.variables_changed)

    def _encrypt_info_nodes(self, info_nodes):
        """
        Encrypt a set of nodes from the domainInfo section of the model.
        :param info_nodes: the model nodes
        """
        info_location = self.alias_helper.get_model_section_attribute_location(
            DOMAIN_INFO)
        password_attribute_names = self.alias_helper.get_model_password_type_attribute_names(
            info_location)

        subfolder_names = self.alias_helper.get_model_section_top_level_folder_names(
            DOMAIN_INFO)

        for node in info_nodes:
            if node in subfolder_names:
                child_location = LocationContext().append_location(node)
                child_nodes = info_nodes[node]
                self._encrypt_nodes(child_location, child_nodes)

            elif node in password_attribute_names:
                self._encrypt_attribute(DOMAIN_INFO, info_nodes, node)

    def _encrypt_nodes(self, location, model_nodes, subfolder_names=None):
        """
        Encrypt a set of nodes corresponding to the specified location.
        :param location: the location of the model nodes
        :param model_nodes: the model nodes
        :param subfolder_names: the valid sub-folders of the location. If not specified, derive from location
        """
        _method_name = '_encrypt_nodes'

        folder_name = location.get_folder_path()

        password_attribute_names = self.alias_helper.get_model_password_type_attribute_names(
            location)

        if subfolder_names is None:
            subfolder_names = self.alias_helper.get_model_subfolder_names(
                location)

        for node in model_nodes:
            if node in subfolder_names:
                child_location = LocationContext(location).append_location(
                    node)

                # check artificial type first, those locations will cause error in other checks
                has_multiple = (not self.alias_helper.is_artificial_type_folder(child_location)) and \
                               (self.alias_helper.requires_artificial_type_subfolder_handling(child_location) or
                                self.alias_helper.supports_multiple_mbean_instances(child_location))

                if has_multiple:
                    name_nodes = model_nodes[node]
                    for name_node in name_nodes:
                        child_nodes = name_nodes[name_node]
                        self._encrypt_nodes(child_location, child_nodes)
                else:
                    child_nodes = model_nodes[node]
                    self._encrypt_nodes(child_location, child_nodes)

            elif (not self.alias_helper.is_artificial_type_folder(location)) and \
                    self.alias_helper.requires_artificial_type_subfolder_handling(location):
                # if a child of a security provider type is not a known subfolder, possibly a custom provider
                self._logger.info('WLSDPLY-04108',
                                  node,
                                  folder_name,
                                  class_name=self._class_name,
                                  method_name=_method_name)

            elif node in password_attribute_names:
                self._encrypt_attribute(folder_name, model_nodes, node)

    def _encrypt_attribute(self, folder_name, model_nodes, key):
        """
        Encrypt a specific attribute that was flagged as password type.
        If the attribute value uses a variable, encrypt the variable and replace the value,
        otherwise replace the value in the dictionary with the encrypted value.
        :param folder_name: text describing the folder location, used for logging
        :param model_nodes: the dictionary containing the attribute
        :param key: the key of the model attribute
        """
        _method_name = '_encrypt_attribute'

        value = model_nodes[key]
        variable_names = variable_helper.get_variable_names(value)
        if len(variable_names) == 0:
            if not EncryptionUtils.isEncryptedString(value):
                encrypted_value = EncryptionUtils.encryptString(
                    value,
                    String(self.passphrase).toCharArray())
                model_nodes[key] = encrypted_value
                self._logger.fine('WLSDPLY-04103',
                                  folder_name,
                                  key,
                                  class_name=self._class_name,
                                  method_name=_method_name)
                self.model_changes += 1
            else:
                self._logger.fine('WLSDPLY-04104',
                                  folder_name,
                                  key,
                                  class_name=self._class_name,
                                  method_name=_method_name)
        elif len(variable_names) == 1:
            self._encrypt_variable_value(folder_name, key, variable_names[0])
        else:
            self._logger.warning('WLSDPLY-04105',
                                 folder_name,
                                 key,
                                 len(variable_names),
                                 variable_names,
                                 class_name=self._class_name,
                                 method_name=_method_name)

    def _encrypt_variable_value(self, folder_name, field_name, var_name):
        """
        Encrypt the variable value, and replace it in the variable set.
        :param folder_name: text describing the folder location, used for logging
        :param field_name: the attribute name
        :param var_name: the variable name
        :return: the number of variable changes
        """
        _method_name = '_encrypt_variable_value'

        # if variables file was not specified, don't try to encrypt
        if self.variables is None:
            return

        # this variable may have been encrypted for another attribute
        if var_name in self.variables_changed:
            return

        if var_name in self.variables:
            var_value = self.variables[var_name]
            if len(var_value) > 0:
                encrypted_value = EncryptionUtils.encryptString(
                    var_value,
                    String(self.passphrase).toCharArray())
                self.variables[var_name] = encrypted_value
                self.variables_changed.append(var_name)
                self._logger.fine('WLSDPLY-04106',
                                  folder_name,
                                  field_name,
                                  var_name,
                                  class_name=self._class_name,
                                  method_name=_method_name)
        else:
            ex = exception_helper.create_encryption_exception(
                'WLSDPLY-04107', var_name, field_name, folder_name)
            self._logger.throwing(ex,
                                  class_name=self._class_name,
                                  method_name=_method_name)
            raise ex
class ModelKubernetesPrinter(object):
    """
    Class for printing kubernetes sections as model samples.
    """
    _class_name = "ModelKubernetesPrinter"
    _logger = PlatformLogger('wlsdeploy.modelhelp')

    def __init__(self):
        self._schema = wko_schema_helper.get_domain_resource_schema()

    def print_model_sample(self, model_path_tokens, control_option):
        """
        Prints out a model sample for the given model path tokens.
        :param model_path_tokens: a list of folder tokens indicating a model location
        :param control_option: a command-line switch that controls what is output
        :raises CLAException: if a problem is encountered
        """
        section_name = model_path_tokens[0]

        if len(model_path_tokens) == 1:
            self._print_model_section_sample(section_name, control_option)
        else:
            self._print_model_folder_sample(section_name, model_path_tokens,
                                            control_option)

    def _print_model_section_sample(self, section_name, control_option):
        """
        Prints a model sample for a section of a model, when just the section_name[:] is provided
        :param section_name: the name of the model section
        :param control_option: A command-line switch that controls what is output to STDOUT
        """
        _method_name = '_print_model_section_sample'

        print
        path = section_name + ":"
        _print_indent(path, 0)

        if model_help_utils.show_attributes(control_option):
            self._print_attributes_sample(self._schema, 1)

        if model_help_utils.show_folders(control_option):
            self._print_subfolders_sample(self._schema, control_option, 1,
                                          path)

    def _print_model_folder_sample(self, section_name, model_path_tokens,
                                   control_option):
        """
        Prints a model sample for a folder in a model, when more than just the section_name[:] is provided.
        :param section_name: the name of the model section
        :param model_path_tokens: a Python list of path elements built from model path
        :param control_option: A command-line switch that controls what is output to STDOUT
        """
        _method_name = '_print_model_folder_sample'

        print("")

        # write the parent folders leading up to the specified folder.
        # include any name folders.

        indent = 0
        _print_indent(section_name + ":", indent)
        indent += 1

        model_path = section_name + ":"
        current_folder = self._schema
        for token in model_path_tokens[1:]:
            properties = _get_properties(current_folder)

            valid_subfolder_keys = _get_folder_names(properties)
            if token not in valid_subfolder_keys:
                ex = exception_helper.create_cla_exception(
                    "WLSDPLY-10111", model_path, token,
                    ', '.join(valid_subfolder_keys))
                self._logger.throwing(ex,
                                      class_name=self._class_name,
                                      method_name=_method_name)
                raise ex

            current_folder = properties[token]

            _print_indent(token + ":", indent)
            indent += 1

            if wko_schema_helper.is_multiple_folder(current_folder):
                name = token + '-1'
                _print_indent(name + ":", indent)
                indent += 1

            model_path = model_path + "/" + token

        # list the attributes and folders, as specified

        if model_help_utils.show_attributes(control_option):
            # Print the attributes associated with schema folder
            self._print_attributes_sample(current_folder, indent)

        if model_help_utils.show_folders(control_option):
            self._print_subfolders_sample(current_folder, control_option,
                                          indent, model_path)

    def _print_subfolders_sample(self, schema_folder, control_option,
                                 indent_level, path):
        """
        Prints a model sample section for the folders in a model location.
        :param schema_folder: the schema folder being printed
        :param control_option: a command-line switch that controls what is output to STDOUT
        :param indent_level: the level to indent by, before printing output
        """
        _method_name = '_print_subfolders_sample'

        folder_info = _get_properties(schema_folder)
        folder_map = dict()
        multi_folders = []

        for key in folder_info:
            property_map = folder_info[key]

            if property_map is not None:
                if wko_schema_helper.is_single_folder(property_map):
                    folder_map[key] = property_map

                elif wko_schema_helper.is_multiple_folder(property_map):
                    folder_map[key] = wko_schema_helper.get_array_item_info(
                        property_map)
                    multi_folders.append(key)

        folder_keys = list(folder_map.keys())
        folder_keys.sort()

        for key in folder_keys:
            folder_info = folder_map[key]

            if control_option != ControlOptions.RECURSIVE:
                print("")

            key_level = indent_level
            _print_indent(key + ":", key_level)

            child_level = key_level
            if key in multi_folders:
                name = key + "-1"
                child_level += 1
                _print_indent(name + ":", child_level)

            if control_option == ControlOptions.RECURSIVE:
                # Call this method recursively
                self._print_subfolders_sample(folder_info, control_option,
                                              child_level + 1, path)
            else:
                next_path = path + "/" + key
                _print_indent("# see " + next_path, child_level + 1)

    def _print_attributes_sample(self, schema_folder, indent_level):
        """
        Prints a model sample for the attributes in a model location
        :param schema_folder: the schema folder to be printed
        :param indent_level: the level of indention for this folder
        """
        _method_name = '_print_attributes_sample'

        attribute_map = dict()
        properties = _get_properties(schema_folder)

        for key in properties:
            property_map = properties[key]
            if property_map is not None:
                if wko_schema_helper.is_simple_map(property_map):
                    # map of key / value pairs
                    attribute_map[key] = 'properties'

                elif wko_schema_helper.is_simple_array(property_map):
                    # array of simple type
                    attribute_map[
                        key] = 'list of ' + wko_schema_helper.get_array_element_type(
                            property_map)

                elif not wko_schema_helper.is_folder(property_map):
                    type_text = wko_schema_helper.get_type(property_map)
                    enum_values = wko_schema_helper.get_enum_values(
                        property_map)
                    if enum_values:
                        type_text += ' (' + ', '.join(enum_values) + ')'
                    attribute_map[key] = type_text

        if attribute_map:
            attr_list = attribute_map.keys()
            attr_list.sort()

            maxlen = 0
            for name in attr_list:
                if len(name) > maxlen:
                    maxlen = len(name)

            format_string = '%-' + str(maxlen + 1) + 's # %s'
            for attr_name in attr_list:
                line = format_string % (attr_name + ":",
                                        attribute_map[attr_name])
                _print_indent(line, indent_level)
        else:
            _print_indent("# no attributes", indent_level)
class TestHelper:
    """
    Common alias types of helper methods used for both generate and verify.
    """
    
    __logger = PlatformLogger('test.aliases', resource_bundle_name='aliastest_rb')
    __logger.set_level(Level.FINEST)

    def __init__(self, model_context):
        self.__class_name__ = self.__class__.__name__
        self.__model_context = model_context
        self.__aliases = Aliases(self.__model_context, self.__model_context.get_target_wlst_mode(),
                                 self.__model_context.get_target_wls_version())

    def mode(self):
        """
        Get the mode (online or offline) for the current processing
        :return: mode enum value
        """
        return self.__model_context.get_target_wlst_mode()

    def version(self):
        """
        Get the weblogic version for the oracle home in use
        :return: weblogic version
        """
        return self.__model_context.get_target_wls_version()

    def admin_url(self):
        """
        Get the URL for the admin server passed as an argument on the test.
        :return: Admin server URL
        """
        return self.__model_context.get_admin_url()

    def admin_user(self):
        """
        Get the admin user passed as an argument on the test.
        :return: Admin server userid
        """
        return self.__model_context.get_admin_user()

    def admin_password(self):
        """
        Get the admin password passed as an argument on the test.
        :return: Admin server password
        """
        return self.__model_context.get_admin_password()

    def oracle_home(self):
        """
        Get the location of the oracle home passed as an argument on the test.
        :return: oracle home location
        """
        return self.__model_context.get_oracle_home()

    def domain_home(self):
        """
        Get the location of the domain home passed as an argument on the test.
        :return: domain home location
        """
        return self.__model_context.get_domain_home()

    def domain_name(self):
        """
        Name of the domain at the domain home location.
        :return: domain name.
        """
        return self.__model_context.get_domain_name()

    def aliases(self):
        """
        Return the aliases instance encapsulated by the test.
        :return: aliases instance
        """
        return self.__aliases

    def check_flattened_folder(self, location, folder):
        """
        Determine from aliases if an MBean is a flattened folder in the aliases model.
        :param location: location constructed with mbean information
        :param folder: mbean to check against aliases
        :return: True if the mbean at the location is a flattened folder in the model
        """
        flattened_info = self.__aliases.get_wlst_flattened_folder_info(location)
        if flattened_info is not None:
            mbean_type = flattened_info.get_mbean_type()
            if mbean_type == folder:
                return True
        return False

    def get_top_folder_map(self, location):
        return self.get_folder_map(self.__aliases.get_model_top_level_folder_names(), location)

    def get_subfolder_map(self, location):
        return self.get_folder_map(self.__aliases.get_model_subfolder_names(location), location)

    def get_folder_map(self, model_folder_list, base_location):
        location = LocationContext(base_location)
        folder_map = dict()
        for name in model_folder_list:
            if name is None:
                self.__logger.warning('have a problem with the list at location {0} : {1}', location.get_folder_path(),
                                model_folder_list)
            else:
                location.append_location(name)
                self.__logger.finer('Checking the folder {0} for flattened and type', location.get_folder_path())
                flattened_info = None
                print '******* ', location.get_folder_path()
                if not location.get_folder_path().startswith('/NMProperties') and not location.get_folder_path() == '/':
                    flattened_info = self.__aliases.get_wlst_flattened_folder_info(location)
                if flattened_info is not None:
                    # make a message
                    self.__logger.fine('The mbean type {0} at location {1} is a flattened folder ', name,
                                 location.get_folder_path())
                    wlst_mbean = flattened_info.get_mbean_type()
                else:
                    wlst_mbean = self.__aliases.get_wlst_mbean_type(location)
                if wlst_mbean is None:
                    # create a message for this
                    self.__logger.finer('Mbean folder {0} at location {1} is not implemented in aliases for version {2}}',
                                  name, location.get_folder_path(), self.__model_context.get_target_wls_version())
                else:
                    folder_map[wlst_mbean] = name
                location.pop_location()
        return folder_map

    def build_location(self, location, model_name):

        name_token = self.__aliases.get_name_token(location)
        if name_token:
            location.add_name_token(name_token, all_utils.mbean_name(model_name)[0])
        return name_token

    def get_alias_get_required_attribute_list(self, location):
        get_required_list = []
        try:
            get_required_list = self.__aliases.get_wlst_get_required_attribute_names(location)
        except AliasException, ae:
            self.__logger.fine('WLSDPLYST-01130', location.get_folder_path(), ae.getLocalizedMessage(),
                               class_name=self.__class_name__, method_name='_method_name')
        return get_required_list
Esempio n. 12
0
 def __init__(self, dictionary):
     # Fix error handling for None
     self._dictionary = dictionary
     self._logger = PlatformLogger('wlsdeploy.yaml')
     self._hyphenate_lists = False
     return
class MBeanMethodAttributeHelper(object):

    __tossed_attributes = ['DefaultedMBean', 'Attribute', 'Comments', 'Attributes', 'PersistenceEnabled']
    __logger = PlatformLogger('test.aliases.generate', resource_bundle_name='aliastest_rb')
    __logger.set_level(Level.FINER)

    def __init__(self, mbean_info, attribute_name, mbean_instance):
        self.__class_name__ = self.__class__.__name__
        self.__attribute_name = attribute_name
        self.__mbean_instance = mbean_instance
        self.__attribute_info = self.__get_mbean_attribute_info(mbean_info, attribute_name)
        self.__exists = self.__attribute_info is not None
        self.__mbean_type = _get_mbean_type(mbean_instance)
        self.__attribute_value = None
        self.__method_names = None

    def is_attribute_found(self):
        return self.__exists

    def get_name(self):
        return self.__attribute_name

    def get_mbean_type(self):
        return self.__mbean_type

    def has_since(self):
        return self.since_version() is not None

    def since_version(self):
        self.__logger.finest('{0} does not contain since version', self.__class_name__,
                             class_name=self.__class_name__, method_name='since_version')
        return None

    def is_deprecated(self):
        return self.deprecated_version() is not None

    def deprecated_version(self):
        self.__logger.finest('{0} does not contain deprecated version', self.__class_name__,
                             class_name=self.__class_name__, method_name='deprecated_version')
        return None

    def restart_required(self):
        self.__logger.finest('{0} does not contain restart value', self.__class_name__,
                             class_name=self.__class_name__, method_name='restart_required')
        return None

    def get_read_method(self):
        method = None
        if self.__exists:
            method = self.__get_method_for_name('get' + self.__attribute_name)
            if method is None:
                method = self.__get_method_for_name('is' + self.__attribute_name)
        return method

    def getter_name(self):
        getter = self.get_read_method()
        if getter is not None:
            return getter.getName()
        return None

    def is_readable(self):
        return self.get_read_method() is not None

    def is_writable(self):
        return self.__get_method_for_name('set' + self.__attribute_name) is not None

    def is_readonly(self):
        return self.__exists and not self.is_writable()

    def is_mbean(self):
        if self.__exists:
            attribute_type = self.attribute_type()
            return attribute_type is not None and \
                (attribute_type.startswith('weblogic') or attribute_type.startswith('[Lweblogic')) and \
                 self.is_readonly()
        return False

    def is_attribute(self):
        return self.is_mbean() is False and self.get_name() not in self.__tossed_attributes

    def is_reference(self):
        self.__logger.finest('{0} cannot determine reference', self.__class_name__,
                             class_name=self.__class_name__, method_name='is_reference')
        return None

    def is_valid_reference(self):
        self.__logger.finest('{0} cannot determine reference', self.__class_name__,
                             class_name=self.__class_name__, method_name='is_valid_reference')
        return None

    def is_reference_only(self):
        self.__logger.finest('{0} cannot determine reference', self.__class_name__,
                             class_name=self.__class_name__, method_name='is_reference_only')
        return None

    def attribute_type(self):
        _method_name = 'attribute_type'
        attr_type = all_utils.UNKNOWN
        if self.__exists:
            getter = self.get_read_method()
            if getter is not None:
                check_type = getter.getReturnType()
                if check_type is not None:
                    try:
                        type_getter = getattr(check_type, 'getTypeName', str(check_type))
                        attr_type = type_getter()
                    except (Exception, JException):
                        attr_type = str(check_type)
        self.__logger.finest('Attribute type for MBean {0} attribute {1} is {3}',
                             self.get_mbean_type(), self.get_name(), attr_type,
                             class_name=self.__class_name__, method_name=_method_name)
        return attr_type

    def default_value(self):
        return self.attribute_value()

    def attribute_value(self):
        if self.is_valid_getter():
            return self.__attribute_value
        return all_utils.FAIL

    def is_encrypted(self):
        return self.__exists and str(self.get_read_method().getReturnType()) == '[B'

    def is_valid_getter(self):
        success = False
        if self.__exists and self.__mbean_instance is not None:
            success, self.__attribute_value = \
                all_utils.get_from_bean_proxy(self.__mbean_instance, self.__mbean_type,
                                              self.getter_name(), self.get_name())
        return success

    def creator_method_name(self):
        creator = self.creator_method()
        if creator is not None:
            return creator.getName()
        return None

    def creator_method(self):
        if self.__exists:
            return self.__get_method_for_name('create' + self.__attribute_name)
        return None

    def mbean_instance(self):
        return self.__mbean_instance

    def generate_attribute(self, dictionary):
        _method_name = 'generate_attribute'
        self.__logger.entering(class_name=self.__class_name__, method_name=_method_name)
        if self.__exists:
            if self.is_readonly():
                dictionary[all_utils.CMO_READ_TYPE] = all_utils.READ_ONLY
            else:
                dictionary[all_utils.CMO_READ_TYPE] = all_utils.READ_WRITE

        self.__logger.exiting(class_name=self.__class_name__, method_name=_method_name, result=dictionary)

    def generate_mbean(self, dictionary):
        _method_name = 'generate_mbean'
        if self.__exists:
            self.__logger.finest('Nothing to generate by Methods helper for MBean {0} attribute {1}',
                                 self.get_mbean_type(), self.get_name(),
                                 class_name=self.__class_name__, method_name=_method_name, result=dictionary)

    def __get_method_for_name(self, method_name):
        list_index = self._get_index_of_method_in_list(method_name)
        if list_index >= 0:
            return self.__attribute_info[list_index]
        return None

    def __get_attribute_method_names(self):
        if self.__exists:
            if self.__method_names is None:
                self.__method_names = [method.getName() for method in self.__attribute_info]
        return self.__method_names

    def _get_index_of_method_in_list(self, method_name):
        if self.__exists:
            try:
                return self.__get_attribute_method_names().index(method_name)
            except ValueError:
                pass
        return -1

    def __get_mbean_attribute_info(self, mbean_info, attribute_name):
        _method_name = '__get_mbean_attribute_info'
        attribute_info = None
        if mbean_info is not None and attribute_name is not None and attribute_name in mbean_info:
            attribute_info = [method for method in mbean_info[attribute_name]
                              if method.getName().endswith(attribute_name)]
        if attribute_info is not None and len(attribute_info) > 0:
            self.__logger.finest('Attribute {0} exists in MBean methods', attribute_name,
                                 class_name=self.__class_name__, method_name=_method_name)
        else:
            self.__logger.fine('Unable to locate attribute {0} in MBean methods', attribute_name,
                               class_name=self.__class_name__, method_name=_method_name)

        return attribute_info

    def str(self):
        return self.__str__()

    def __str__(self):
        atype = 'No '
        if self.is_attribute_found():
            if self.is_mbean():
                atype = 'Child MBean '
            elif self.is_reference():
                atype = 'Reference '
            else:
                atype = ' '
        return self.__class_name__ + ' MBean type ' + str(self.get_mbean_type()) + \
            atype + 'attribute ' + self.get_name()
from oracle.weblogic.deploy.util import WebLogicDeployToolingVersion

sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0])))

from wlsdeploy.aliases.aliases import Aliases
from wlsdeploy.exception import exception_helper
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.modelhelp.model_help_printer import ModelHelpPrinter
from wlsdeploy.tool.modelhelp.model_help_utils import ControlOptions
from wlsdeploy.tool.util import model_context_helper
from wlsdeploy.util import cla_helper
from wlsdeploy.util.cla_utils import CommandLineArgUtil

_program_name = 'modelHelp'
_class_name = 'model_help'
__logger = PlatformLogger('wlsdeploy.modelhelp')

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH
]

__optional_arguments = [
    CommandLineArgUtil.ATTRIBUTES_ONLY_SWITCH,
    CommandLineArgUtil.FOLDERS_ONLY_SWITCH,
    CommandLineArgUtil.MODEL_SAMPLE_SWITCH,
    CommandLineArgUtil.RECURSIVE_SWITCH
]

__output_types = [
    CommandLineArgUtil.ATTRIBUTES_ONLY_SWITCH,
    CommandLineArgUtil.FOLDERS_ONLY_SWITCH,
class AliasEncryptedModelTestCase(unittest.TestCase):
    """
    Test cases for a the -use_encryption feature.
    """

    _logger = PlatformLogger('wlsdeploy.aliases')
    _wls_version = '12.2.1.3'
    _wlst_password_name = "Password"
    _wlst_password_encrypted_name = "PasswordEncrypted"

    _passphrase = 'RE a drop of golden sun'
    _password = '******'
    _encrypted_password = '******'

    def setUp(self):
        # construct aliases as if the -use_encryption and -passphrase switches were used
        model_context = ModelContext(
            "test", {
                CommandLineArgUtil.USE_ENCRYPTION_SWITCH: 'true',
                CommandLineArgUtil.PASSPHRASE_SWITCH: self._passphrase
            })
        self.aliases = Aliases(model_context,
                               wlst_mode=WlstModes.OFFLINE,
                               wls_version=self._wls_version)
        self.online_aliases = Aliases(model_context,
                                      wlst_mode=WlstModes.ONLINE,
                                      wls_version=self._wls_version)

        self.location = aliases_test.get_jdbc_driver_params_location(
            "Mine", self.aliases)

    def testOfflineWlstNames(self):
        # Using offline WLST, the PasswordEncrypted model attribute should translate to the PasswordEncrypted WLST
        # attribute, regardless of whether the password is encrypted. The password value should be plain text.

        # using encrypted password
        wlst_name, wlst_value = \
            self.aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._encrypted_password)
        self.assertEqual(wlst_name, self._wlst_password_encrypted_name)
        self.assertEqual(wlst_value, self._password)

        # using unencrypted password
        wlst_name, wlst_value = \
            self.aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._password)
        self.assertEquals(wlst_name, self._wlst_password_encrypted_name)
        self.assertEqual(wlst_value, self._password)

    def testOnlineWlstNames(self):
        # Using online WLST, the PasswordEncrypted model attribute should always translate to the Password WLST
        # attribute, and the value should translate to the unencrypted value.

        # using encrypted password
        wlst_name, wlst_value = \
            self.online_aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED,
                                                                  self._encrypted_password)
        self.assertEqual(wlst_name, self._wlst_password_name)
        self.assertEqual(wlst_value, self._password)

        # using unencrypted password
        wlst_name, wlst_value = \
            self.online_aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._password)
        self.assertEquals(wlst_name, self._wlst_password_name)
        self.assertEqual(wlst_value, self._password)
import java.math.BigInteger as BigInteger
import java.util.Map as Map
import java.util.Properties as Properties
import javax.management.ObjectName as ObjectName

import oracle.weblogic.deploy.util.PyOrderedDict as PyOrderedDict

import wlsdeploy.aliases.alias_constants as alias_constants
from wlsdeploy.aliases.location_context import LocationContext
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.util.mbean_utils import MBeanUtils
from wlsdeploy.tool.util.variable_injector import STANDARD_PASSWORD_INJECTOR
from wlsdeploy.tool.util.wlst_helper import WlstHelper
from wlsdeploy.util.weblogic_helper import WebLogicHelper

_logger = PlatformLogger('wlsdeploy.discover')
_class_name = 'CustomFolderHelper'


class CustomFolderHelper(object):
    """
    Helper for locating the custom MBeans and its attributes.

    These require special handling, since they do not have alias definitions.
    Discover the MBean attributes using the information provided by the MBeanAttributes
    wrapper class.
    """
    def __init__(self,
                 aliases,
                 logger,
                 model_context,
Esempio n. 17
0
sys.path.append(pathname)
pathname = os.path.join(os.environ['WLSDEPLOY_HOME'], 'lib', 'python')
sys.path.append(pathname)

sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0])))
print sys.path

from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.aliases.wlst_modes import WlstModes

import aliastest.generate.generator_wlst as generator_wlst
import aliastest.generate.generator_helper as generator_helper
import aliastest.util.all_utils as all_utils
from aliastest.generate.generator_online import OnlineGenerator

__logger = PlatformLogger('test.aliases.generate',
                          resource_bundle_name='aliastest_rb')
__logger.set_level(Level.FINEST)
CLASS_NAME = 'generate_online'


def persist_file(model_context, dictionary):
    """
    Persist the generated online dictionary to the test files location and generated file name.
    :param model_context: containing the test files location
    :param dictionary: generated dictionary
    :return: File name for persisted dictionary
    """
    _method_name = 'persist_file'
    __logger.entering(class_name=CLASS_NAME, method_name=_method_name)
    filename = all_utils.filename(
        generator_helper.filename(), all_utils.str_mode(model_context),
 def tearDown(self):
     # remove summary handler for next test suite
     PlatformLogger('wlsdeploy.validate').logger.removeHandler(
         self._summary_handler)
Esempio n. 19
0
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.aliases.aliases import Aliases
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.aliases.location_context import LocationContext
from wlsdeploy.util.model_context import ModelContext
from wlsdeploy.tool.validate.validator import Validator
from oracle.weblogic.deploy.validate import ValidateException
from wlsdeploy.exception.expection_types import ExceptionType

VALIDATION_FAIL = 2
PATH_TOKEN = '|'
BLANK_LINE = ""

_program_name = 'compareModel'
_class_name = 'compare_model'
_logger = PlatformLogger('wlsdeploy.compare_model')

__required_arguments = [CommandLineArgUtil.ORACLE_HOME_SWITCH]

__optional_arguments = [
    CommandLineArgUtil.OUTPUT_DIR_SWITCH,
    CommandLineArgUtil.VARIABLE_FILE_SWITCH
]

all_changes = []
all_added = []
all_removed = []
compare_msgs = sets.Set()


def __process_args(args):
Esempio n. 20
0
from wlsdeploy.util import dictionary_utils
from wlsdeploy.util import getcreds
from wlsdeploy.util import tool_exit
from wlsdeploy.util import variables
from wlsdeploy.util import wlst_extended
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.model import Model
from wlsdeploy.util.model_context import ModelContext
from wlsdeploy.util.model_translator import FileToPython
from wlsdeploy.util.weblogic_helper import WebLogicHelper

wlst_extended.wlst_functions = globals()

_program_name = UPDATE_DOMAIN
_class_name = 'update'
__logger = PlatformLogger('wlsdeploy.update')
__wls_helper = WebLogicHelper(__logger)
__wlst_helper = WlstHelper(__logger, ExceptionType.DEPLOY)
__wlst_mode = WlstModes.OFFLINE
__tmp_model_dir = None

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH,
    CommandLineArgUtil.DOMAIN_HOME_SWITCH
]

__optional_arguments = [
    # Used by shell script to locate WLST
    CommandLineArgUtil.DOMAIN_TYPE_SWITCH,
    CommandLineArgUtil.ARCHIVE_FILE_SWITCH,
    CommandLineArgUtil.MODEL_FILE_SWITCH,
Esempio n. 21
0
class AliasPasswordTestCase(unittest.TestCase):

    _logger = PlatformLogger('wlsdeploy.aliases')
    _wls_version = '12.2.1.3'
    _wlst_password_name = "Password"
    _wlst_password_encrypted_name = "PasswordEncrypted"

    _passphrase = 'RE a drop of golden sun'
    _password = '******'
    _encrypted_password = '******'
    _encrypted_password_bytes = jarray.array(_encrypted_password, 'b')

    def setUp(self):
        model_context = ModelContext("test", {CommandLineArgUtil.USE_ENCRYPTION_SWITCH: 'true',
                                              CommandLineArgUtil.PASSPHRASE_SWITCH: self._passphrase})
        self.aliases = Aliases(model_context, wlst_mode=WlstModes.OFFLINE, wls_version=self._wls_version)
        self.online_aliases = Aliases(model_context, wlst_mode=WlstModes.ONLINE, wls_version=self._wls_version)

        self.location = LocationContext()
        self.location.append_location(JDBC_SYSTEM_RESOURCE)
        self.location.add_name_token(self.aliases.get_name_token(self.location), "Mine")
        self.location.append_location(JDBC_RESOURCE)
        self.location.append_location(JDBC_DRIVER_PARAMS)

    def testOfflineModelNames(self):
        # Using offline WLST, only PasswordEncrypted is an attribute, and its value is encrypted.
        # The model name should be PasswordEncrypted.
        model_name, model_value = \
            self.aliases.get_model_attribute_name_and_value(self.location, self._wlst_password_encrypted_name,
                                                            self._encrypted_password)
        self.assertEquals(model_name, PASSWORD_ENCRYPTED)

    def testOnlineModelNames(self):
        # Using online WLST, both Password and PasswordEncrypted are WLST attributes.

        # The PasswordEncrypted WLST attribute should translate to the PasswordEncrypted model attribute.
        model_name, model_value = \
            self.online_aliases.get_model_attribute_name_and_value(self.location, self._wlst_password_encrypted_name,
                                                                   self._encrypted_password)
        self.assertEqual(model_name, PASSWORD_ENCRYPTED)

        # The Password WLST attribute should be skipped, since its value cannot be retrieved.
        # This is accomplished by returning a model name of None.
        model_name, model_value = \
            self.online_aliases.get_model_attribute_name_and_value(self.location, self._wlst_password_name,
                                                                   self._encrypted_password)
        self.assertEquals(model_name, None)

    def testOfflineWlstNames(self):
        # Using offline WLST, the PasswordEncrypted model attribute should translate to the PasswordEncrypted WLST
        # attribute, regardless of whether the password is encrypted.

        # using encrypted password
        wlst_name, wlst_value = \
            self.aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._encrypted_password)
        self.assertEqual(wlst_name, self._wlst_password_encrypted_name)
        self.assertEqual(wlst_value, self._password)

        # using unencrypted password
        wlst_name, wlst_value = \
            self.aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._password)
        self.assertEquals(wlst_name, self._wlst_password_encrypted_name)

    def testOnlineWlstNames(self):
        # Using online WLST, the PasswordEncrypted model attribute should translate to the PasswordEncrypted WLST
        # attribute if the password is encrypted, otherwise to Password.

        # using encrypted password
        wlst_name, wlst_value = \
            self.online_aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED,
                                                                  self._encrypted_password)
        self.assertEqual(wlst_name, self._wlst_password_encrypted_name)
        self.assertEqual(wlst_value, self._password)

        # using unencrypted password
        wlst_name, wlst_value = \
            self.online_aliases.get_wlst_attribute_name_and_value(self.location, PASSWORD_ENCRYPTED, self._password)
        self.assertEquals(wlst_name, self._wlst_password_name)
Esempio n. 22
0
# imports from local packages start here
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.exception import exception_helper
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.util import model_context_helper
from wlsdeploy.tool.validate.validator import Validator
from wlsdeploy.util import cla_helper
from wlsdeploy.util import dictionary_utils
from wlsdeploy.util import tool_exit
from wlsdeploy.util import variables
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.weblogic_helper import WebLogicHelper

_program_name = 'validateModel'
_class_name = 'validate'
__logger = PlatformLogger('wlsdeploy.validate')
__wls_helper = WebLogicHelper(__logger)
__wlst_mode = WlstModes.OFFLINE

__required_arguments = [CommandLineArgUtil.ORACLE_HOME_SWITCH]

__optional_arguments = [
    CommandLineArgUtil.
    DOMAIN_TYPE_SWITCH,  # Used by shell script to locate WLST
    CommandLineArgUtil.MODEL_FILE_SWITCH,
    CommandLineArgUtil.ARCHIVE_FILE_SWITCH,
    CommandLineArgUtil.VARIABLE_FILE_SWITCH,
    CommandLineArgUtil.TARGET_VERSION_SWITCH,
    CommandLineArgUtil.TARGET_MODE_SWITCH,
    CommandLineArgUtil.VALIDATION_METHOD
]
Esempio n. 23
0
class ModelComparer(object):
    """
    Class for comparing two WDT models.
    """
    _class_name = "ModelComparer"
    _logger = PlatformLogger('wlsdeploy.compare_model')

    SOURCE_PATH_FOLDERS = [APPLICATION, LIBRARY]

    def __init__(self, current_model_dict, past_model_dict, aliases, messages):
        """
        :param current_model_dict: the new dictionary being compared
        :param past_model_dict: the old dictionary being compared
        :param aliases: a reference to an Aliases class instance
        :param messages: a Set to be updated with messages
        """
        self._current_model_dict = current_model_dict
        self._past_model_dict = past_model_dict
        self._aliases = aliases
        self._messages = messages

    def compare_models(self):
        """
        Compare the current an past models from the top level.
        :return: a dictionary of differences between these models
        """
        self._messages.clear()
        location = None
        change_model_dict = self._compare_folders(self._current_model_dict,
                                                  self._past_model_dict,
                                                  location, location)
        return change_model_dict

    def _compare_folders(self, current_folder, past_folder, location,
                         attributes_location):
        """
        Compare folders after determining if the folder has named sub-folders.
        :param current_folder: a folder in the current model
        :param past_folder: corresponding folder in the past model
        :param location: the location for the specified folders
        :param attributes_location: the attribute location for the specified folders
        :return: a dictionary of differences between these folders
        """
        _method_name = '_compare_folders'

        # determine if the specified location has named folders, such as topology/Server
        has_named_folders = False
        if (location is not None
            ) and not self._aliases.is_artificial_type_folder(location):
            has_named_folders = self._aliases.supports_multiple_mbean_instances(location) or \
                                self._aliases.requires_artificial_type_subfolder_handling(location)

        if has_named_folders:
            return self._compare_named_folders(current_folder, past_folder,
                                               location, attributes_location)
        else:
            return self._compare_folder_contents(current_folder, past_folder,
                                                 location, attributes_location)

    def _compare_named_folders(self, current_folder, past_folder, location,
                               attributes_location):
        """
        Compare current and past named folders using the specified locations.
        A named folder is a subfolder of a multiple-MBean folder, such as topology/Server/my-server
        :param current_folder: a folder in the current model
        :param past_folder: corresponding folder in the past model
        :param location: the location for the specified folders
        :param attributes_location: the attribute location for the specified folders
        :return: a dictionary of differences between these folders
        """
        change_folder = PyOrderedDict()

        for name in current_folder:
            # check if name is present in both folders.
            # if found, compare the two folders recursively.
            if name in past_folder:
                next_current = current_folder[name]
                next_past = past_folder[name]
                location.add_name_token(self._aliases.get_name_token(location),
                                        name)
                attributes_location.add_name_token(
                    self._aliases.get_name_token(attributes_location), name)
                changes = self._compare_folder_contents(
                    next_current, next_past, location, attributes_location)
                if changes:
                    change_folder[name] = changes

            # check for added names.
            # if found, add the entire folder contents.
            else:
                change_folder[name] = current_folder[name]
                pass

        # check for deleted names.
        # if name is not in the current folder, add its delete name.
        for name in past_folder:
            if name not in current_folder:
                delete_name = model_helper.get_delete_name(name)
                change_folder[delete_name] = PyOrderedDict()

        return change_folder

    def _compare_folder_contents(self, current_folder, past_folder, location,
                                 attributes_location):
        """
        Compare the contents of current and past folders using the specified locations.
        :param current_folder: a folder in the current model
        :param past_folder: corresponding folder in the past model
        :param location: the location for the specified folders
        :param attributes_location: the attribute location for the specified folders
        :return: a dictionary of differences between these folders
        """
        change_folder = PyOrderedDict()

        attribute_names = []
        if attributes_location is not None:
            attribute_names = self._aliases.get_model_attribute_names(
                attributes_location)

        # check if keys in the current folder are present in the past folder
        for key in current_folder:
            if not self._check_key(key, location):
                continue

            if key in past_folder:
                current_value = current_folder[key]
                past_value = past_folder[key]

                if key in attribute_names:
                    self._compare_attribute(current_value, past_value,
                                            attributes_location, key,
                                            change_folder)

                else:
                    next_location, next_attributes_location = self._get_next_location(
                        location, key)
                    next_change = self._compare_folders(
                        current_value, past_value, next_location,
                        next_attributes_location)

                    if next_change:
                        change_folder[key] = next_change

            else:
                # key is present the current folder, not in the past folder.
                # just add to the change folder, no further recursion needed.
                change_folder[key] = current_folder[key]

        # check if keys in the past folder are not in the current folder
        for key in past_folder:
            if not self._check_key(key, location):
                continue

            if key not in current_folder:
                if key in attribute_names:
                    # if an attribute was deleted, just add a message
                    change_path = self._aliases.get_model_folder_path(
                        location) + "/" + key
                    self._messages.add(('WLSDPLY-05701', change_path))

                else:
                    # if a folder was deleted, keep recursing through the past model.
                    # there may be named elements underneath that need to be deleted.
                    current_value = PyOrderedDict()
                    past_value = past_folder[key]
                    next_location, next_attributes_location = self._get_next_location(
                        location, key)
                    next_change = self._compare_folders(
                        current_value, past_value, next_location,
                        next_attributes_location)

                    if next_change:
                        change_folder[key] = next_change

        self._finalize_folder(current_folder, past_folder, change_folder,
                              location)
        return change_folder

    def _get_next_location(self, location, key):
        """
        Get the next locations for the specified key and location.
        :param location: the current location (None indicates model root)
        :param key: the key of the next location
        :return: a tuple with the next location and the next attributes location
        """
        if location is None:
            next_location = LocationContext()
            next_attributes_location = self._aliases.get_model_section_attribute_location(
                key)
        else:
            next_location = LocationContext(location)
            next_location.append_location(key)
            next_location.add_name_token(
                self._aliases.get_name_token(next_location), 'FOLDER')
            next_attributes_location = next_location

        return next_location, next_attributes_location

    def _compare_attribute(self, current_value, past_value, location, key,
                           change_folder):
        """
        Compare values of an attribute from the current and past folders.
        The change value and any comments will be added to the change folder.
        :param current_value: the value from the current model
        :param past_value: the value from the past model
        :param key: the key of the attribute
        :param change_folder: the folder in the change model to be updated
        :param location: the location for attributes in the specified folders
        """
        if current_value != past_value:
            attribute_type = self._aliases.get_model_attribute_type(
                location, key)
            if attribute_type in ALIAS_LIST_TYPES:
                current_list = alias_utils.create_list(current_value,
                                                       'WLSDPLY-08001')
                previous_list = alias_utils.create_list(
                    past_value, 'WLSDPLY-08000')

                change_list = list(previous_list)
                for item in current_list:
                    if item in previous_list:
                        change_list.remove(item)
                    else:
                        change_list.append(item)
                for item in previous_list:
                    if item not in current_list:
                        change_list.remove(item)
                        change_list.append(model_helper.get_delete_name(item))

                current_text = ','.join(current_list)
                previous_text = ','.join(previous_list)
                comment = key + ": '" + previous_text + "' -> '" + current_text + "'"
                _add_comment(comment, change_folder)
                change_folder[key] = ','.join(change_list)

            elif attribute_type == PROPERTIES:
                self._compare_properties(current_value, past_value, key,
                                         change_folder)

            else:
                if not isinstance(past_value, dict):
                    comment = key + ": '" + str(past_value) + "'"
                    _add_comment(comment, change_folder)
                change_folder[key] = current_value

    def _compare_properties(self, current_value, past_value, key,
                            change_folder):
        """
        Compare values of a properties attribute from the current and past folders.
        The change value and any comments will be added to the change folder.
        :param current_value: the value from the current model
        :param past_value: the value from the past model
        :param key: the key of the attribute
        :param change_folder: the folder in the change model to be updated
        """
        property_dict = PyOrderedDict()
        for property_key in current_value:
            current_property_value = current_value[property_key]
            if property_key in past_value:
                past_property_value = past_value[property_key]
                if past_property_value != current_property_value:
                    comment = property_key + ": '" + str(
                        past_property_value) + "'"
                    _add_comment(comment, property_dict)
                    property_dict[property_key] = current_property_value
            else:
                property_dict[property_key] = current_property_value

        # property values don't support delete notation,
        # so any deleted keys in the current value will be ignored.

        if property_dict:
            change_folder[key] = property_dict

    def _check_key(self, key, location):
        """
        Determine if the specified key and location will be compared.
        :param key: the key to be checked
        :param location: the location to be checked
        :return: True if the key and location will be compared, False otherwise
        """
        _method_name = '_check_key'

        if (location is None) and (key == KUBERNETES):
            self._logger.info('WLSDPLY-05713',
                              KUBERNETES,
                              class_name=self._class_name,
                              method_name=_method_name)
            return False
        return True

    def _finalize_folder(self, current_folder, past_folder, change_folder,
                         location):
        """
        Perform any adjustments after a folder has been evaluated.
        :param current_folder: folder in the current model
        :param past_folder: corresponding folder in the past model
        :param change_folder: the folder with the changed attributes and sub-folders
        :param location: the location for the specified folders
        """
        _method_name = '_finalize_folder'

        folder_path = []
        if location is not None:
            folder_path = location.get_model_folders()

        # Application and Library should include SourcePath if they have any other elements
        if (len(folder_path) == 1) and (folder_path[0]
                                        in self.SOURCE_PATH_FOLDERS):
            if change_folder and (SOURCE_PATH not in change_folder):
                # if SourcePath not present, past and current folder had matching values
                source_path = dictionary_utils.get_element(
                    current_folder, SOURCE_PATH)
                if source_path is not None:
                    comment = exception_helper.get_message(
                        'WLSDPLY-05714', SOURCE_PATH)
                    _add_comment(comment, change_folder)
                    change_folder[SOURCE_PATH] = source_path
Esempio n. 24
0
from wlsdeploy.aliases.location_context import LocationContext
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.exception import exception_helper
from wlsdeploy.exception.expection_types import ExceptionType
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.util.mbean_utils import MBeanUtils
from wlsdeploy.tool.util.alias_helper import AliasHelper
from wlsdeploy.tool.util.wlst_helper import WlstHelper
from wlsdeploy.util import path_utils
from wlsdeploy.util import wlst_helper
from wlsdeploy.util.weblogic_helper import WebLogicHelper

_DISCOVER_LOGGER_NAME = 'wlsdeploy.discover'

_class_name = 'Discoverer'
_logger = PlatformLogger(_DISCOVER_LOGGER_NAME)


class Discoverer(object):
    """
    Discoverer contains the private methods used to facilitate discovery of the domain information by its subclasses.
    """
    def __init__(self, model_context, base_location, wlst_mode, aliases=None):
        """

        :param model_context: context about the model for this instance of discover domain
        :param base_location: to look for common weblogic resources. By default this is the global path or '/'
        """
        self._model_context = model_context
        self._base_location = base_location
        self._wlst_mode = wlst_mode
Esempio n. 25
0
# imports from local packages start here
from wlsdeploy.aliases.aliases import Aliases
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.extract.domain_resource_extractor import DomainResourceExtractor
from wlsdeploy.tool.util import model_context_helper
from wlsdeploy.util import cla_helper
from wlsdeploy.util import tool_exit
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.cla_utils import TOOL_TYPE_EXTRACT
from wlsdeploy.util.model import Model
from wlsdeploy.util.weblogic_helper import WebLogicHelper

_program_name = 'extractDomainResource'
_class_name = 'extract_resource'
__logger = PlatformLogger('wlsdeploy.extract')
__wls_helper = WebLogicHelper(__logger)
__wlst_mode = WlstModes.OFFLINE

__required_arguments = [
    CommandLineArgUtil.ORACLE_HOME_SWITCH,
    CommandLineArgUtil.DOMAIN_HOME_SWITCH,
    CommandLineArgUtil.DOMAIN_RESOURCE_FILE_SWITCH
]

__optional_arguments = [
    # Used by shell script to locate WLST
    CommandLineArgUtil.DOMAIN_TYPE_SWITCH,
    CommandLineArgUtil.ARCHIVE_FILE_SWITCH,
    CommandLineArgUtil.MODEL_FILE_SWITCH,
    CommandLineArgUtil.VARIABLE_FILE_SWITCH,
from wlsdeploy.tool.util import filter_helper
from wlsdeploy.tool.util.archive_helper import ArchiveHelper
from wlsdeploy.tool.validate.validator import Validator
from wlsdeploy.util import cla_utils
from wlsdeploy.util import getcreds
from wlsdeploy.util import model_helper
from wlsdeploy.util import model_translator
from wlsdeploy.util import path_utils

from wlsdeploy.util import tool_exit
from wlsdeploy.util import variables
from wlsdeploy.util.cla_utils import CommandLineArgUtil
from wlsdeploy.util.model_translator import FileToPython


__logger = PlatformLogger('wlsdeploy.util')
_class_name = 'cla_helper'

_store_environment_variable = '__WLSDEPLOY_STORE_MODEL__'

__tmp_model_dir = None


def validate_optional_archive(program_name, optional_arg_map):
    """
    If the archive file was specified on the command line, verify that it exists.
    :param program_name: the name of the calling program, for logging
    :param optional_arg_map: the optional arguments from the command line
    :raises CLAException: if the archive was specified and does not exist
    """
    _method_name = 'validate_optional_archive'
Esempio n. 27
0
"""
import re

import java.lang.Boolean as Boolean
import java.lang.Exception as JException

from oracle.weblogic.deploy.exception import BundleAwareException

from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.exception import exception_helper
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.util.wlst_helper import WlstHelper
from wlsdeploy.util.weblogic_helper import WebLogicHelper


_logger = PlatformLogger('wlsdeploy.mbean.utils')


class MBeanUtils(object):
    """
    Utility class used to provide information about WLST attributes as retrieved from the MBeans MBeanInfo or Interface
    methods. This class has methods to provide the information stored in different combinations. All methods that want
    to combine the information from the MBeans helpers into different combinations are located in this class.
    """

    def __init__(self, model_context, alias_helper, exception_type):
        self.__model_context = model_context
        self.__exception_type = exception_type
        self.__alias_helper = alias_helper
        self.__wlst_helper = WlstHelper(_logger, exception_type)
        self.__helper = self.__get_helper()
Esempio n. 28
0
from java.net import URISyntaxException
from java.net import MalformedURLException

from oracle.weblogic.deploy.util import FileUtils
from oracle.weblogic.deploy.util import PyOrderedDict as OrderedDict
from oracle.weblogic.deploy.util import WLSDeployArchiveIOException

from wlsdeploy.aliases import model_constants
from wlsdeploy.aliases.location_context import LocationContext
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.tool.discover import discoverer
from wlsdeploy.tool.discover.discoverer import Discoverer

_class_name = 'CoherenceResourcesDiscoverer'
_logger = PlatformLogger(discoverer.get_discover_logger_name())


class CoherenceResourcesDiscoverer(Discoverer):
    """
    Discover the weblogic coherence resources from the domain.
    """
    def __init__(self,
                 model_context,
                 resource_dictionary,
                 base_location,
                 wlst_mode=WlstModes.OFFLINE,
                 aliases=None):
        """
        Initialize this discoverer instance with the specific information needed to discover coherence resources.
        :param model_context: context about the model for this instance of discover domain
The discovery code makes special provisions to skip the unencrypted online attribute.

The create and deploy code makes special provisions to set either the encrypted unencrypted online attribute,
depending on whether the model value is encrypted.
"""

from oracle.weblogic.deploy.encrypt import EncryptionUtils

from wlsdeploy.aliases.alias_constants import WLST_NAME
from wlsdeploy.aliases.alias_constants import WLST_TYPE
from wlsdeploy.aliases.wlst_modes import WlstModes
from wlsdeploy.logging.platform_logger import PlatformLogger
from wlsdeploy.util import dictionary_utils

_class_name = 'password_utils'
_logger = PlatformLogger('wlsdeploy.aliases')
_dual_password_suffix = 'Encrypted'


def get_wlst_skip_name(attribute_info, wlst_mode):
    """
    Returns a WLST attribute name, derived from the the specified attribute information, that should be ignored.
    For example, the model attribute PasswordEncrypted may indicate that the WLST attribute Password should be ignored.
    :param attribute_info: the attribute information to be checked
    :param wlst_mode: the offline or online type to be checked
    :return: a single name to be skipped, or None
    """
    if _is_dual_password(attribute_info) and (wlst_mode == WlstModes.ONLINE):
        return _get_non_encrypted_wlst_name(attribute_info)
    return None