def createSimpleTask(phaseId, taskTypeValue, title, propertyMap):
    """
    adds a custom task to a phase in the release
    :param phaseId: id of the phase
    :param taskTypeValue: type of task to add
    :param title: title of the task
    :param propertyMap: properties to add to the task
    :return:
    """
    #print propertyMap

    parenttaskType = Type.valueOf("xlrelease.CustomScriptTask")

    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)

    childTaskType = Type.valueOf(taskTypeValue)
    childTask = childTaskType.descriptor.newInstance("nonamerequired")
    for item in propertyMap:
        if childTask.hasProperty(item):
            childTask.setProperty(item,propertyMap[item])
        else:
            Base.info( "dropped property: %s on %s because: not applicable" % (item, taskTypeValue))
    parentTask.setPythonScript(childTask)

    print str(parentTask)
    taskApi.addTask(str(phaseId),parentTask)
Exemplo n.º 2
0
def create_env(id, name, token, repositoryService, metadataService,
               serviceType):
    print("Debug - id = %s, name = %s, " % (id, name))
    envUrl = "https://anypoint.mulesoft.com/accounts/api/organizations/%s/environments" % id
    authHeader = {"Authorization": "Bearer " + token}
    envResponse = requests.get(envUrl, headers=authHeader)
    if envResponse.raise_for_status():
        raise Exception("Failed to get environments. Server returned %s.\n%s" %
                        (envResponse.status_code, envResponse.reason))

    envResponseJson = envResponse.json()
    for envItem in envResponseJson['data']:
        print('Name: ' + envItem['name'] + '\r\n')  # Debugging
        print('ID: ' + envItem['id'] + '\r\n')  # Debugging
        newCiId = name + '/' + envItem['name']
        print('Adding: ' + newCiId)

        if repositoryService.exists(newCiId):
            print('   ' + envItem['name'] + ' already exists, skipping.')
        else:
            if serviceType == "Runtime Fabric":
                newTeCi = metadataService.findDescriptor(
                    Type.valueOf('mule.Mulesoft.Domain.RTFTargetEnvironment')
                ).newInstance(newCiId)
            else:
                newTeCi = metadataService.findDescriptor(
                    Type.valueOf('mule.Mulesoft.Domain.TargetEnvironment')
                ).newInstance(newCiId)
            newTeCi.envName = envItem['name']
            newTeCi.envId = envItem['id']
            repositoryService.create(newCiId, newTeCi)
    def createSimpleTaskObject(self, taskTypeValue, title, propertyMap={}, parentTypeValue = None ):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """



        if parentTypeValue == None:
            taskType = Type.valueOf(str(taskTypeValue))

            Task = taskType.descriptor.newInstance("nonamerequired")
            Task.setTitle(title)
            for item in propertyMap:

                if Task.hasProperty(item):
                    type = Task.getType()
                    desc = type.getDescriptor()
                    pd = desc.getPropertyDescriptor(item)

                    if str(pd.getKind()) == "CI":
                        Task.setProperty(item, self.find_ci_id(str(item), pd.getReferencedType()))
                    else:
                        Task.setProperty(item, propertyMap[item])

                else:
                    Base.info("dropped property: %s on %s because: not applicable" % (item, taskTypeValue))

            return Task


        else:
        # print propertyMap
            parenttaskType = Type.valueOf(str(parentTypeValue))

            parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
            parentTask.setTitle(title)
            childTaskType = Type.valueOf(taskTypeValue)
            childTask = childTaskType.descriptor.newInstance("nonamerequired")
            for item in propertyMap:

                if childTask.hasProperty(item):
                    type = childTask.getType()
                    desc = type.getDescriptor()
                    pd = desc.getPropertyDescriptor(item)

                    if str(pd.getKind()) == "CI":
                        childTask.setProperty(item, self.find_ci_id(str(item), pd.getReferencedType()))
                    else:
                        childTask.setProperty(item, propertyMap[item])

                else:
                    Base.info("dropped property: %s on %s because: not applicable" % (item, taskTypeValue))
            parentTask.setPythonScript(childTask)

            return parentTask
def createSimpleTask(phaseId, taskTypeValue, title, propertyMap):
    """
    adds a custom task to a phase in the release
    :param phaseId: id of the phase
    :param taskTypeValue: type of task to add
    :param title: title of the task
    :param propertyMap: properties to add to the task
    :return:
    """
    # print propertyMap

    parenttaskType = Type.valueOf("xlrelease.CustomScriptTask")

    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)

    childTaskType = Type.valueOf(taskTypeValue)
    childTask = childTaskType.descriptor.newInstance("nonamerequired")
    for item in propertyMap:
        if childTask.hasProperty(item):
            childTask.setProperty(item, propertyMap[item])
        else:
            Base.info("dropped property: %s on %s because: not applicable" % (item, taskTypeValue))
    parentTask.setPythonScript(childTask)

    print str(parentTask)
    taskApi.addTask(str(phaseId), parentTask)
    def createCustomScriptTask(self,
                               phaseId,
                               taskTypeValue,
                               title,
                               propertyMap,
                               release,
                               parentTypeValue=None):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """
        # print propertyMap

        if parentTypeValue == None:
            parentTypeValue = 'xlrelease.CustomScriptTask'

        phaseName = self.get_target_phase(phaseId, release)

        parenttaskType = Type.valueOf(parentTypeValue)

        parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
        parentTask.setTitle(title)
        childTaskType = Type.valueOf(taskTypeValue)
        childTask = childTaskType.descriptor.newInstance("nonamerequired")
        vm = {}
        for item in propertyMap:
            Base.info("settings %s on task of type: %s" %
                      (item, childTaskType))
            if childTask.hasProperty(item):
                type = childTask.getType()
                desc = type.getDescriptor()
                pd = desc.getPropertyDescriptor(item)

                if str(pd.getKind()) == "CI":
                    childTask.setProperty(
                        item, self.find_ci_id(str(item),
                                              pd.getReferencedType()))
                else:
                    childTask.setProperty(item, propertyMap[item])
                if str(pd.getCategory()) == "output":
                    Base.info("added %s to variable mapping" %
                              propertyMap[item])
                    vm['%s.%s' %
                       ("pythonScript", item)] = "${" + propertyMap[item] + "}"

            else:
                Base.info(
                    "dropped property: %s on %s because: not applicable" %
                    (item, taskTypeValue))
        parentTask.setPythonScript(childTask)
        if parentTask.hasProperty('variableMapping'):
            parentTask.setVariableMapping(vm)

        self.__taskApi.addTask(str(phaseName), parentTask)
def create_undeploy_task(phaseId, title, precondition, propertyMap):

    parenttaskType = Type.valueOf("xlrelease.CustomScriptTask")
    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)
    childTaskType = Type.valueOf("xldeploy.UndeployTask")
    childTask = childTaskType.descriptor.newInstance("nonamerequired")
    for item in propertyMap:
        childTask.setProperty(item, propertyMap[item])
    parentTask.setPythonScript(childTask)
    parentTask.setPrecondition(precondition)
    taskApi.addTask(phaseId, parentTask)
def createPowershellTask(phaseId,title,precondition, propertyMap):

    parenttaskType = Type.valueOf("xlrelease.CustomScriptTask")
    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)
    
    childTaskType = Type.valueOf("remoteScript.Powershell")
    childTask = childTaskType.descriptor.newInstance("nonamerequired")
    for item in propertyMap:
        childTask.setProperty(item,propertyMap[item])
    parentTask.setPythonScript(childTask)
    parentTask.setPrecondition(precondition)
    taskApi.addTask(phaseId,parentTask)
def mapProperties(old, new):
  new.setType(Type.valueOf("was.JavaProcessDefinitionSpec"))
  if old.JavaVirtualMachine_classpath is not None:    	
    new.setProperty('JavaVirtualMachine_classpath', old.JavaVirtualMachine_classpath)
  if old.JavaVirtualMachine_bootClasspath is not None:
  	new.setProperty('JavaVirtualMachine_bootClasspath', old.JavaVirtualMachine_bootClasspath)
  if old.JavaVirtualMachine_verboseModeClass is not None:
  	new.setProperty('JavaVirtualMachine_verboseModeClass', old.JavaVirtualMachine_verboseModeClass)
  if old.JavaVirtualMachine_verboseModeGarbageCollection is not None:
  	new.setProperty('JavaVirtualMachine_verboseModeGarbageCollection', old.JavaVirtualMachine_verboseModeGarbageCollection)
  if old.JavaVirtualMachine_verboseModeJNI is not None:
  	new.setProperty('JavaVirtualMachine_verboseModeJNI', old.JavaVirtualMachine_verboseModeJNI)
  if old.JavaVirtualMachine_initialHeapSize is not None:
  	new.setProperty('JavaVirtualMachine_initialHeapSize', old.JavaVirtualMachine_initialHeapSize)
  if old.JavaVirtualMachine_maximumHeapSize is not None:
  	new.setProperty('JavaVirtualMachine_maximumHeapSize', old.JavaVirtualMachine_maximumHeapSize)
  if old.JavaVirtualMachine_genericJvmArguments is not None:
    new.setProperty('JavaVirtualMachine_genericJvmArguments', old.JavaVirtualMachine_genericJvmArguments)
  if old.JavaVirtualMachine_disableJIT is not None:
    new.setProperty('JavaVirtualMachine_disableJIT', old.JavaVirtualMachine_disableJIT)
# TODO: 
  if old.jvmCustomProperties is not None:
    map = {}
#   parse the custom properties
#   Example:
#   map['newtestkey'] = 'newtestvalue'
    new.setProperty('JavaVirtualMachine_customProperties', map)
def load_profile(profile):
    sp = SearchParameters()
    sp.setType(Type.valueOf('rel.ReleaseProfile'))

    for p in XLReleaseServiceHolder.getRepositoryService().listEntities(sp):
        if str(p.getTitle()) == profile:
            return json.loads(p.getProperty('profileJson'))
Exemplo n.º 10
0
def find_ci_id(name, type):
    sp = SearchParameters()
    sp.setType(Type.valueOf(type))

    for p in XLReleaseServiceHolder.getRepositoryService().listEntities(sp):
        if str(p.getTitle()) == name:
           return p
Exemplo n.º 11
0
def createParallelTask(phaseId, title, precondition, propertyMap):
    paralleltaskType = Type.valueOf("xlrelease.ParallelGroup")
    parallelTask = paralleltaskType.descriptor.newInstance("nonamerequired")
    parallelTask.setTitle(title)
    parallelTask.setPrecondition(precondition)
    taskApi.addTask(phaseId, parallelTask)
    return parallelTask.id
Exemplo n.º 12
0
    def createParallelTaskContainer(self, phaseId, release):

        taskType = Type.valueOf('xlrelease.ParallelGroup')

        task = taskType.descriptor.newInstance("nonamerequired")

        return self.__taskApi.addTask(str(self.get_target_phase(phaseId, release)), task)
Exemplo n.º 13
0
def get_env(id):
    global token
    envUrl = "https://anypoint.mulesoft.com/accounts/api/organizations/%s/environments" % id
    print envUrl
    authHeader = {
        "Authorization": "Bearer " + token
    }
    profileResponse = requests.get(envUrl, headers=authHeader)
    profileResponseJson = profileResponse.json()
    for envItem in profileResponseJson['data']:

        print 'Name: ' + envItem['name'] + '\r\n'  # Debugging
        print 'ID: ' + envItem['id'] + '\r\n'  # Debugging
        newCiId = thisCi.id + '/' + envItem['name']
        print 'Adding: ' + newCiId

        if repositoryService.exists(newCiId):
            print '   ' + envItem['name'] + ' already exists, skipping.'
        else:
            newTeCi = metadataService.findDescriptor(
                Type.valueOf('mule.Mulesoft.Domain.TargetEnvironment')
            ).newInstance(newCiId)
            newTeCi.envName = envItem['name']
            newTeCi.envId = envItem['id']
            repositoryService.create(newCiId, newTeCi)
Exemplo n.º 14
0
    def find_ci_id(self, name, type):
        sp = SearchParameters()
        sp.setType(Type.valueOf(str(type)))

        for p in XLReleaseServiceHolder.getRepositoryService().listEntities(sp):
            if str(p.getTitle()) == name:
               return p
def createParallelTask(phaseId,title,precondition,propertyMap):
    paralleltaskType = Type.valueOf("xlrelease.ParallelGroup")
    parallelTask = paralleltaskType.descriptor.newInstance("nonamerequired")
    parallelTask.setTitle(title)
    parallelTask.setPrecondition(precondition)
    taskApi.addTask(phaseId,parallelTask)
    return parallelTask.id
Exemplo n.º 16
0
    def createCustomScriptTask(self, phaseId, taskTypeValue, title, propertyMap, release, parentTypeValue = None):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """
        # print propertyMap

        if parentTypeValue == None:
            parentTypeValue = 'xlrelease.CustomScriptTask'

        phaseName = self.get_target_phase(phaseId, release)

        parenttaskType = Type.valueOf(parentTypeValue)

        parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
        parentTask.setTitle(title)
        childTaskType = Type.valueOf(taskTypeValue)
        childTask = childTaskType.descriptor.newInstance("nonamerequired")
        vm = {}
        for item in propertyMap:
            Base.info("settings %s on task of type: %s" % (item, childTaskType))
            if childTask.hasProperty(item):
                 type = childTask.getType()
                 desc = type.getDescriptor()
                 pd   = desc.getPropertyDescriptor(item)


                 if str(pd.getKind()) == "CI":
                    childTask.setProperty(item, self.find_ci_id(str(item), pd.getReferencedType()))
                 else:
                    childTask.setProperty(item, propertyMap[item])
                 if str(pd.getCategory()) == "output":
                    Base.info("added %s to variable mapping" % propertyMap[item])
                    vm['%s.%s' % ("pythonScript", item)] = "${" + propertyMap[item] + "}"


            else:
                Base.info("dropped property: %s on %s because: not applicable" % (item, taskTypeValue))
        parentTask.setPythonScript(childTask)
        if parentTask.hasProperty('variableMapping'):
            parentTask.setVariableMapping(vm)

        self.__taskApi.addTask(str(phaseName), parentTask)
Exemplo n.º 17
0
def query_all_containers(ci_id, results):
    # print("query {0}".format(ci_id))
    result = repositoryService.query(Type.valueOf('udm.Container'), ci_id, None, '', None, None, 0, -1)
    sub_result = []
    for sub_ci in result:
        results.append(sub_ci)
        query_all_containers(sub_ci.id, sub_result)
    results.extend(sub_result)
def create_container_task(phaseId, title, precondition, propertyMap,
                          containerType):
    containertaskType = Type.valueOf("xlrelease." + containerType + "Group")
    containertask = containertaskType.descriptor.newInstance("nonamerequired")
    containertask.setTitle(title)
    containertask.setPrecondition(precondition)
    taskApi.addTask(phaseId, containertask)
    return containertask.id
Exemplo n.º 19
0
    def createParallelTaskContainer(self, phaseId, release):

        taskType = Type.valueOf('xlrelease.ParallelGroup')

        task = taskType.descriptor.newInstance("nonamerequired")

        return self.__taskApi.addTask(
            str(self.get_target_phase(phaseId, release)), task)
Exemplo n.º 20
0
    def createTaskContainer(self, phaseId, release,containerType="xlrelease.ParallelGroup", title = "Basic Container"):

        taskType = Type.valueOf(str(containerType))

        task = taskType.descriptor.newInstance("nonamerequired")
        task.setTitle(str(title))

        return self.__taskApi.addTask(str(self.get_target_phase(phaseId, release)), task)
def default_ansible_controller(default_ansible_controller_id):
    result = repositoryService.query(Type.valueOf('ansible.Controller'), None,
                                     None, default_ansible_controller_id, None,
                                     None, 0, -1)
    if len(result) == 0:
        return None
    else:
        return repositoryService.read(result[0].id)
Exemplo n.º 22
0
def collect_artifacts(applicationName, versionName):
    cis = repositoryService.query(Type.valueOf("udm.Application"), None, None,
                                  applicationName, None, None, 0, -1)
    if cis:
        versionId = cis[0].getId() + '/' + versionName
        try:
            version = repositoryService.read(versionId)
        except NotFoundException as exc:
            response.setStatusCode(404)
            logging.error("On Application [%s] version [%s] not found" %
                          (applicationName, versionName))
            return

        xldConf = None
        try:
            xldConf = repositoryService.read(
                ArgosConfiguration.getXldClientConfigId())
        except NotFoundException as exc:
            response.setStatusCode(500)
            logging.error("XLD Client Config [%s] not found" %
                          ArgosConfiguration.getXldClientConfigId())
            return

        tempDeployables = version.getDeployables()
        remoteDeployables = []
        for deployable in tempDeployables:
            deployable = repositoryService.read(str(deployable))
            if deployable.hasProperty('fileUri') \
                and not deployable.getFileUri() is None \
                and not deployable.getFileUri().startswith('internal:'):
                dep = {}
                dep['uri'] = deployable.getFileUri()
                if not deployable.getCredentials() is None:
                    creds = repositoryService.read(
                        str(deployable.getCredentials()))
                    dep['username'] = creds.getUsername()
                    dep['password'] = creds.getPassword()
                remoteDeployables.append(dep)
        # for backwards compatibility
        password = None
        if PasswordEncrypter.getInstance().isEncrypted(xldConf.getPassword()):
            password = PasswordEncrypter.getInstance().decrypt(
                xldConf.getPassword())
        else:
            password = xldConf.getPassword()
        try:

            response.setEntity(
                ArgosCollectArtifactList.collectArtifacts(
                    xldConf.getUsername(), password, versionId,
                    remoteDeployables))
        except Exception as exc:
            logging.error("During artifact collect %s", exc.message)
            response.setStatusCode(400)
    else:
        response.setStatusCode(404)
        logging.error("Application [%s] unknown" % applicationName)
Exemplo n.º 23
0
    def find_template_id_by_name(self, name):
        sp = SearchParameters()
        sp.setType(Type.valueOf(str('xlrelease.Release')))

        for p in XLReleaseServiceHolder.getRepositoryService().listEntities(sp):
            if p.isTemplate() == True:
                if str(p.getTitle()) == str(name):
                    Base.info("Found id: %s for name %s" % (str(p.getId()), name))
                    return str(p.getId())

        return None
Exemplo n.º 24
0
def ci_exists(storeName, type):

    sp = SearchParameters()
    sp.setType(Type.valueOf(type))

    for p in __repositoryService.listEntities(sp):

        if str(p.getTitle()) == storeName:
            return True

    return False
def createSimpleTask(phaseId, taskTypeValue, title, propertyMap):
    parenttaskType = Type.valueOf(taskTypeValue)
    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)
    sdf = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
    for item in propertyMap:
        if item.lower().find("date") > -1:
            if propertyMap[item] is not None and len(propertyMap[item]) != 0:
                parentTask.setProperty(item,sdf.parse(propertyMap[item]))
        else:
            parentTask.setProperty(item,propertyMap[item])
    taskApi.addTask(phaseId,parentTask)
Exemplo n.º 26
0
def createSimpleTask(phaseId, taskTypeValue, title, propertyMap):
    parenttaskType = Type.valueOf(taskTypeValue)
    parentTask = parenttaskType.descriptor.newInstance("nonamerequired")
    parentTask.setTitle(title)
    sdf = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
    for item in propertyMap:
        if item.lower().find("date") > -1:
            if propertyMap[item] is not None and len(propertyMap[item]) != 0:
                parentTask.setProperty(item, sdf.parse(propertyMap[item]))
        else:
            parentTask.setProperty(item, propertyMap[item])
    taskApi.addTask(phaseId, parentTask)
Exemplo n.º 27
0
def load_ci_from_repo(storeName, type):

    sp = SearchParameters()
    sp.setType(Type.valueOf(type))

    for p in __repositoryService.listEntities(sp):
        print p.getId()
        if str(p.getTitle()) == storeName:
            return p

    Base.fatal("unable to find json data repository: %s" % storeName)
    sys.exit(2)
Exemplo n.º 28
0
    def load_profile_from_xlr_repo(self, profileName):
        """
        load the profile from the xlr repository
        :param profileName: name of the profile as it was configured
        :return:
        """
        sp = SearchParameters()
        sp.setType(Type.valueOf('rel.ReleaseProfile'))

        for p in self.__repositoryService.listEntities(sp):
            if str(p.getTitle()) == profileName:
                return json.loads(p.getProperty('profileJson'))
Exemplo n.º 29
0
    def load_profile_from_xlr_repo(self, profileName):
        """
        load the profile from the xlr repository
        :param profileName: name of the profile as it was configured
        :return:
        """
        sp = SearchParameters()
        sp.setType(Type.valueOf('rel.ReleaseProfile'))

        for p in self.__repositoryService.listEntities(sp):
            if str(p.getTitle()) == profileName:
                return json.loads(p.getProperty('profileJson'))
Exemplo n.º 30
0
    def find_template_id_by_name(self, name):
        sp = SearchParameters()
        sp.setType(Type.valueOf(str('xlrelease.Release')))

        for p in XLReleaseServiceHolder.getRepositoryService().listEntities(
                sp):
            if p.isTemplate() == True:
                if str(p.getTitle()) == str(name):
                    Base.info("Found id: %s for name %s" %
                              (str(p.getId()), name))
                    return str(p.getId())

        return None
Exemplo n.º 31
0
    def createTaskContainer(self,
                            phaseId,
                            release,
                            containerType="xlrelease.ParallelGroup",
                            title="Basic Container"):

        taskType = Type.valueOf(str(containerType))

        task = taskType.descriptor.newInstance("nonamerequired")
        task.setTitle(str(title))

        return self.__taskApi.addTask(
            str(self.get_target_phase(phaseId, release)), task)
Exemplo n.º 32
0
def convertToDeployable(deployedId, pkgId):
	deployed = repository.read(deployedId)
	deployedDescriptor = DescriptorRegistry.getDescriptor(deployed.type)
	if (deployedDescriptor.type.instanceOf(Type.valueOf("udm.DeployedArtifact"))):
		print "Cannot convert artifact deployed [%s]. Ignoring " %(deployable.id)
		return None
	
	deployableDescriptor = DescriptorRegistry.getDescriptor(deployedDescriptor.deployableType)
	deployable = factory.configurationItem("%s/%s" % (pkgId, deployed.name), str(deployableDescriptor.type))
	if (repository.exists(deployable.id)):
		print "[%s] already exists. Ignoring " %(deployable.id)
		return None
	
	print "Converting [%s] to type [%s]" % (deployedId, str(deployable.type))
	for pd in deployableDescriptor.propertyDescriptors:
		deployedPd = deployedDescriptor.getPropertyDescriptor(pd.name)
		if (deployedPd):
			try:
				deployable[pdName] = deployed[pdName]
			except:	
				deployable.values[pdName] = deployed[pdName]
	
	return deployable
Exemplo n.º 33
0
def get_ci_object(ciType, id):
    if not DescriptorRegistry.exists(Type.valueOf(ciType)):
        raise ValueError('Unknown CI type %s' % ciType)
    type = Type.valueOf(ciType)
    configurationItem = type.descriptor.newInstance(id)
    return configurationItem
def new_instance(ci_type, ci_id):
    return metadataService.findDescriptor(
        Type.valueOf(ci_type)).newInstance(ci_id)
Exemplo n.º 35
0
 def get_filtered_cis(self, type, parent=None):
     type_ci = Type.valueOf(type)
     ci_ids = self._repositoryService.query(type_ci, None, parent, None,
                                            None, None, 0, -1)
     return map(lambda ci_id: self._repositoryService.read(ci_id.id),
                ci_ids)
def get_all_executors_servers():
    parameters = SearchParameters().setType(Type.valueOf("executors.Server"))
    executors_servers = _repositoryService.listEntities(parameters)
    return executors_servers
Exemplo n.º 37
0
def is_file_request(deployed):
    return deployed.type.instanceOf(Type.valueOf("wp.ExecutedXmlAccessScriptPair"))
Exemplo n.º 38
0
    def createSimpleTask(self, phaseId, taskTypeValue, title, propertyMap,
                         release, parentTaskType):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """
        # print propertyMap

        Base.warning("createSimpleTask")

        phaseName = self.get_target_phase(phaseId, release)

        TaskType = Type.valueOf(taskTypeValue)
        Task = TaskType.descriptor.newInstance("nonamerequired")
        Task.setTitle(title)

        vm = {}
        for item in propertyMap:
            Base.info("settings %s on task of type: %s" % (item, TaskType))
            if Task.hasProperty(item):
                type = Task.getType()
                desc = type.getDescriptor()
                pd = desc.getPropertyDescriptor(item)

                Base.warning(pd.getKind())
                if item == "dependencies":
                    Base.info("dependencies found, these will be set later")
                elif item == "templateId" and "Application" not in propertyMap[
                        item]:
                    Task.setProperty(
                        item,
                        self.find_template_id_by_name(str(propertyMap[item])))
                elif str(pd.getKind()) == "CI":
                    Task.setProperty(
                        item, self.find_ci_id(str(item),
                                              pd.getReferencedType()))
                elif str(pd.getKind()) == "bool":
                    if propertyMap[item] == "false":
                        Task.setProperty(item, False)
                    else:
                        Task.setProperty(item, True)
                else:
                    Task.setProperty(item, propertyMap[item])

            else:
                Base.info(
                    "dropped property: %s on %s because: not applicable" %
                    (item, taskTypeValue))

        print dir(Task.getType().getDescriptor().getPropertyDescriptor(
            'templateVariables'))

        taskId = self.__taskApi.addTask(str(phaseName), Task)

        if propertyMap.has_key("dependencies"):

            for dep in propertyMap["dependencies"]:
                if dep.has_key("targetId"):
                    self.__taskApi.addDependency(str(taskId), dep["targetId"])
                if dep.has_key("target"):
                    self.__taskApi.addDependency(str(taskId), dep['target'])
  except:
    print "Couldn't archive " + task.id + ", probably it failed"
    try:
      print "Canceling task " + task.id
      taskBlockService.cancel(task.id)
    except:
      print "Couldn't cancel " + task.id + ", probably something is really messed up"

def wait_for_tasks_to_finish(tasks):
  for task in tasks:
    while task.state.active:
      print "Waiting for task " + task.id + " to finish"
      time.sleep(5)
    
    archive_or_cancel(task)

containers = repositoryService.query(Type.valueOf("tomcat.Server"), None, thisCi.id, None, None, None, 0, -1)
print "Found Tomcat containers: " + str(containers)

tasks = []
for container in containers:
  tasks.append(run_control_task(container, "stop"))
wait_for_tasks_to_finish(tasks)


tasks = []
for container in containers:
  tasks.append(run_control_task(container, "start"))
wait_for_tasks_to_finish(tasks)
  
Exemplo n.º 40
0
    def createSimpleTaskObject(self,
                               taskTypeValue,
                               title,
                               propertyMap={},
                               parentTypeValue=None):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """

        if parentTypeValue == None:
            taskType = Type.valueOf(str(taskTypeValue))

            Task = taskType.descriptor.newInstance("nonamerequired")
            Task.setTitle(title)
            for item in propertyMap:

                if Task.hasProperty(item):
                    type = Task.getType()
                    desc = type.getDescriptor()
                    pd = desc.getPropertyDescriptor(item)

                    if str(pd.getKind()) == "CI":
                        Task.setProperty(
                            item,
                            self.find_ci_id(str(item), pd.getReferencedType()))
                    else:
                        Task.setProperty(item, propertyMap[item])

                else:
                    Base.info(
                        "dropped property: %s on %s because: not applicable" %
                        (item, taskTypeValue))

            return Task

        else:
            # print propertyMap
            parenttaskType = Type.valueOf(str(parentTypeValue))

            parentTask = parenttaskType.descriptor.newInstance(
                "nonamerequired")
            parentTask.setTitle(title)
            childTaskType = Type.valueOf(taskTypeValue)
            childTask = childTaskType.descriptor.newInstance("nonamerequired")
            for item in propertyMap:

                if childTask.hasProperty(item):
                    type = childTask.getType()
                    desc = type.getDescriptor()
                    pd = desc.getPropertyDescriptor(item)

                    if str(pd.getKind()) == "CI":
                        childTask.setProperty(
                            item,
                            self.find_ci_id(str(item), pd.getReferencedType()))
                    else:
                        childTask.setProperty(item, propertyMap[item])

                else:
                    Base.info(
                        "dropped property: %s on %s because: not applicable" %
                        (item, taskTypeValue))
            parentTask.setPythonScript(childTask)

            return parentTask
def is_file_request(deployed):
    return deployed.type.instanceOf(Type.valueOf("wp.ExecutedXmlAccessScriptPair"))
Exemplo n.º 42
0
 def get_filtered_cis(self, type, parent=None):
     type_ci = Type.valueOf(type)
     ci_ids = self._repositoryService.query(type_ci, None, parent, None, None, None, 0, -1)
     return map(lambda ci_id: self._repositoryService.read(ci_id.id), ci_ids)
Exemplo n.º 43
0
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS
# FOR A PARTICULAR PURPOSE. THIS CODE AND INFORMATION ARE NOT SUPPORTED BY XEBIALABS.
#

from com.xebialabs.deployit.plugin.api.reflect import Type

result = []
objs = repositoryService.query(Type.valueOf(request.query['type'],request.query['parent'],request.query['ancestor'],request.query['namePattern'],None,None,1,-1)
for obj in objs:
	result.append(obj)

response.entity = result
Exemplo n.º 44
0
def search(ciType, parentId):
	ciIds = proxies.getRepository().query(Type.valueOf(ciType), parentId, None, None, None, 0, -1)
	ids = []
	for ciId in ciIds:
		ids.append(str(ciId.id))
	return ids
Exemplo n.º 45
0
    def createSimpleTask(self, phaseId, taskTypeValue, title, propertyMap, release, parentTaskType):
        """
        adds a custom task to a phase in the release
        :param phaseId: id of the phase
        :param taskTypeValue: type of task to add
        :param title: title of the task
        :param propertyMap: properties to add to the task
        :return:
        """
        # print propertyMap

        Base.warning("createSimpleTask")



        phaseName = self.get_target_phase(phaseId, release)

        TaskType = Type.valueOf(taskTypeValue)
        Task = TaskType.descriptor.newInstance("nonamerequired")
        Task.setTitle(title)

        vm = {}
        for item in propertyMap:
            Base.info("settings %s on task of type: %s" % (item, TaskType))
            if Task.hasProperty(item):
                 type = Task.getType()
                 desc = type.getDescriptor()
                 pd   = desc.getPropertyDescriptor(item)

                 Base.warning(pd.getKind())
                 if item == "dependencies":
                    Base.info("dependencies found, these will be set later")
                 elif item == "templateId" and "Application" not in propertyMap[item]:
                     Task.setProperty(item, self.find_template_id_by_name(str(propertyMap[item])))
                 elif str(pd.getKind()) == "CI":
                    Task.setProperty(item, self.find_ci_id(str(item), pd.getReferencedType()))
                 elif str(pd.getKind()) == "bool":
                    if propertyMap[item] == "false":
                        Task.setProperty(item, False)
                    else:
                        Task.setProperty(item, True)
                 else:
                    Task.setProperty(item, propertyMap[item])


            else:
                Base.info("dropped property: %s on %s because: not applicable" % (item, taskTypeValue))

        

        print dir(Task.getType().getDescriptor().getPropertyDescriptor('templateVariables'))

        taskId = self.__taskApi.addTask(str(phaseName), Task)

        if propertyMap.has_key("dependencies"):

            for dep in propertyMap["dependencies"]:
                if dep.has_key("targetId"):
                    self.__taskApi.addDependency(str(taskId), dep["targetId"])
                if dep.has_key("target"):
                    self.__taskApi.addDependency(str(taskId), dep['target'])
        ci.setProperty(name, value)


def discover_resource_groups(client, ctx, descriptor, webapp_descriptor, service_plan_descriptor, base_id):
    resource_groups = client.list_resource_groups()
    print "Discovered %s resource groups" % (len(resource_groups))
    for rg in resource_groups:
        ci = descriptor.newInstance("%s/%s" % (base_id, rg.getName()))
        ci.setProperty("resourceLocation", rg.getLocation())
        ci.setProperty("resourceName", rg.getName())
        ci.setProperty("resourceTags", rg.getTags())
        discovered(ci, ctx)
    [discover_webapps(client, ctx,webapp_descriptor, "%s/%s" % (base_id, rg.name), rg.name) for rg in resource_groups]
    [discover_service_plans(client, ctx, service_plan_descriptor, "%s/%s" % (base_id, rg.name), rg.name) for rg in resource_groups]


def perform_discovery(subscription, ctx, resource_group_descriptor, web_app_module_descriptor, service_plan_descriptor):
    client = AzureClient.new_instance(subscription)
    discover_resource_groups(client, ctx, resource_group_descriptor, web_app_module_descriptor, service_plan_descriptor, subscription.id)


if __name__ == '__main__' or __name__ == '__builtin__':
    print "Starting discovery of resource groups and web apps"
    resource_group_descriptor = Type.valueOf("azure.ResourceGroup").getDescriptor()
    web_app_module_descriptor = Type.valueOf("azure.WebAppModule").getDescriptor()
    service_plan_descriptor = Type.valueOf("azure.AppServicePlan").getDescriptor()
    # if XLD sugar utility wrappers available use it to
    if wrap:
        thisCi = wrap(thisCi)
    perform_discovery(thisCi, inspectionContext, resource_group_descriptor, web_app_module_descriptor, service_plan_descriptor)
def newInstance(ci_type, ci_id):
    return metadataService.findDescriptor(Type.valueOf(ci_type)).newInstance(ci_id)
Exemplo n.º 48
0
    print("Warning: Problem retrieving or saving the organizationId.")

# Create the domains
for domainItem in profileResponseJson['contributorOfOrganizations']:
    print('Name: ' + domainItem['name'] + '\r\n')  # Debugging
    print('ID: ' + domainItem['id'] + '\r\n')  # Debugging
    newCiId = thisCi.id + '/' + domainItem['name']
    print('Adding: ' + newCiId)
    if repositoryService.exists(newCiId):
        print('   ' + domainItem['name'] + ' already exists, skipping.')
        mulesoftUtils.create_env(str(domainItem['id']), str(newCiId), token,
                                 repositoryService, metadataService,
                                 thisCi.serviceType)
    else:
        newTeCi = metadataService.findDescriptor(
            Type.valueOf('mule.Mulesoft.Domain')).newInstance(newCiId)
        newTeCi.OrgDomain = domainItem['name']
        newTeCi.OrgId = domainItem['id']
        repositoryService.create(newCiId, newTeCi)
        try:
            mulesoftUtils.create_env(str(domainItem['id']), str(newCiId),
                                     token, repositoryService, metadataService,
                                     thisCi.serviceType)
        except Exception as e:
            print(
                "Unable to retrieve envionments for this domain - %s, will delete this domain and continue"
                % str(newCiId))
            print("Exeception = %s" % e)
            repositoryService.delete(newCiId)

print('Done.')
Exemplo n.º 49
0
#

import sys
import com.xebialabs.deployit.plugin.api.reflect.Type as Type

working_directory=deployedApplication.environment.backupDictionariesDirectory
if not repositoryService.exists(working_directory):
    raise Exception("{0} doesn't exist, please create it and re-run the step again".format(working_directory))
target_directory = repositoryService.read(working_directory)
task_id = context.getTask().getId()
print ("task_id {0}".format(task_id))
new_folder = "{0}/{1}".format(target_directory,task_id)
if repositoryService.exists(new_folder):
    repositoryService.delete(new_folder)


type = Type.valueOf('core.Directory')
configuration_item = type.descriptor.newInstance(new_folder)
print ("create new folder {0}".format(configuration_item))
repositoryService.create([configuration_item])

for d in dictionaries:
    dict_name = d.name
    new_id = "{0}/{1}".format(new_folder,d.name)
    print ("Backup {0} -> {1}".format(d.id,new_id))
    new_dictionary = repositoryService.copy(d.id,new_id)




Exemplo n.º 50
0
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS
# FOR A PARTICULAR PURPOSE. THIS CODE AND INFORMATION ARE NOT SUPPORTED BY XEBIALABS.
#

from mule.mmc_client import MMCClient
from com.xebialabs.deployit.plugin.api.reflect import Type

print "Starting discovery of clusters and server groups on %s " % thisCi.url

cluster_descriptor = Type.valueOf("mule.Cluster").getDescriptor()
server_group_descriptor = Type.valueOf("mule.ServerGroup").getDescriptor()

client = MMCClient(thisCi.url, thisCi.username, thisCi.password)

def discovered(ci):
    inspectionContext.discovered(ci)
    inspectionContext.inspected(ci)

print "Starting discovery of clusters"
for cluster in client.get_clusters():
    print "Found cluster %s" % cluster["name"]
    discovered(cluster_descriptor.newInstance("%s/%s" % (thisCi.id, cluster['name'])))

print "Starting discovery of server groups"
for sg in client.get_server_groups():
    print "Found server group %s" % sg["name"]
    discovered(server_group_descriptor.newInstance("%s/%s" % (thisCi.id, sg['name'])))