def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(CifsConnectionBuilder.CIFS_PROTOCOL, self.options)
         connection.setWorkingDirectory(connection.getFile(self.remotePath))
         # upload the script and pass it to powershell
         targetFile = connection.getTempFile("uploaded-powershell-script", ".ps1")
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         targetFile.setExecutable(True)
         scriptCommand = CmdLine.build(
             "powershell",
             "-NoLogo",
             "-NonInteractive",
             "-InputFormat",
             "None",
             "-ExecutionPolicy",
             "Unrestricted",
             "-Command",
             targetFile.getPath(),
         )
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
示例#2
0
文件: Plugin.py 项目: Varma4u/Xebia
    def create_build_gradle_file(connection, workspace_path, variables):
        contents = '''plugins {
    id "com.github.hierynomus.license" version "0.13.0"
}

defaultTasks 'build'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'maven'
version='%s'

license {
    header rootProject.file('License.md')
    strictCheck false
    excludes(["**/*.json"])
    ext.year = Calendar.getInstance().get(Calendar.YEAR)
    ext.name = 'XEBIALABS'
}
''' % variables['initial_version']
        repo_directory = OverthereUtils.constructPath(
            connection.getFile(workspace_path),
            '%s' % variables['github_repo_name'])
        build_gradle_file = connection.getFile(
            OverthereUtils.constructPath(connection.getFile(repo_directory),
                                         'build.gradle'))
        OverthereUtils.write(String(contents).getBytes(), build_gradle_file)
 def execute_knife_command(self,
                           command,
                           script_name,
                           options=None,
                           zip_workspace=False):
     connection = None
     try:
         options = Workstation.process_additional_options(options)
         connection = LocalConnection.getLocalConnection()
         workspace_path = self.create_chef_tmp_workspace(connection)
         knife_command = self.get_os_specific_knife_command(
             workspace_path, command, options)
         script_file = connection.getFile(
             OverthereUtils.constructPath(
                 connection.getFile(workspace_path), script_name))
         OverthereUtils.write(String(knife_command).getBytes(), script_file)
         script_file.setExecutable(True)
         if zip_workspace:
             self.zip_workspace(workspace_path, connection)
         command = CmdLine()
         command.addArgument(script_file.getPath())
         output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler(
         )
         error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler(
         )
         exit_code = connection.execute(output_handler, error_handler,
                                        command)
         return [exit_code, output_handler, error_handler]
     except Exception:
         traceback.print_exc(file=sys.stdout)
         sys.exit(1)
     finally:
         if connection is not None:
             connection.close()
    def create_readme_file(connection, workspace_path, variables):
        if variables['create_in_github_organization']:
            path = variables['github_organization']
        else:
            path = variables['github_username']
        contents='''# %s

[![Build Status](https://travis-ci.org/%s/%s.svg?branch=master)](https://travis-ci.org/%s/%s)
[REPLACE ME WITH CODACY BADGE](https://www.codacy.com)
[![Code Climate](https://codeclimate.com/github/%s/%s/badges/gpa.svg)](https://codeclimate.com/github/%s/%s)
[![License: MIT][%s-license-image] ][%s-license-url]
[![Github All Releases][%s-downloads-image]]()

[%s-license-image]: https://img.shields.io/badge/License-MIT-yellow.svg
[%s-license-url]: https://opensource.org/licenses/MIT
[%s-downloads-image]: https://img.shields.io/github/downloads/xebialabs-community/%s/total.svg

## Preface

## Overview

## Installation

## References
''' % (variables['github_repo_name'], path, variables['github_repo_name'], path,
       variables['github_repo_name'], path, variables['github_repo_name'], path,
       variables['github_repo_name'], variables['github_repo_name'], variables['github_repo_name'], variables['github_repo_name'],
       variables['github_repo_name'], variables['github_repo_name'], variables['github_repo_name'], variables['github_repo_name'],)
        repo_directory=OverthereUtils.constructPath(connection.getFile(workspace_path), '%s' % variables['github_repo_name'])
        readme_file=connection.getFile(OverthereUtils.constructPath(connection.getFile(repo_directory), 'README.md'))
        OverthereUtils.write(String(contents).getBytes(), readme_file)
 def zip_workspace(self, workspace_path, connection):
     zip_script = self.get_os_specific_zip_command(workspace_path)
     zip_script_file = connection.getFile(OverthereUtils.constructPath(connection.getFile(workspace_path), 'zip.cmd'))
     OverthereUtils.write(String(zip_script).getBytes(), zip_script_file)
     zip_script_file.setExecutable(True)
     command = CmdLine()
     command.addArgument(zip_script_file.getPath())
     return connection.execute(command)
示例#6
0
文件: Plugin.py 项目: Varma4u/Xebia
 def create_settings_gradle_file(connection, workspace_path, variables):
     contents = 'rootProject.name=\'%s\'\n' % variables['github_repo_name']
     repo_directory = OverthereUtils.constructPath(
         connection.getFile(workspace_path),
         '%s' % variables['github_repo_name'])
     settings_gradle_file = connection.getFile(
         OverthereUtils.constructPath(connection.getFile(repo_directory),
                                      'settings.gradle'))
     OverthereUtils.write(String(contents).getBytes(), settings_gradle_file)
    def create_gitignore_file(connection, workspace_path, variables):
        contents='''.gradle
.idea
build
supervisord.log
supervisord.pid
'''
        repo_directory=OverthereUtils.constructPath(connection.getFile(workspace_path), '%s' % variables['github_repo_name'])
        gitignore_file=connection.getFile(OverthereUtils.constructPath(connection.getFile(repo_directory), '.gitignore'))
        OverthereUtils.write(String(contents).getBytes(), gitignore_file)
   def generate_knife_rb(self, path, connection):
       knife_contents = '''current_dir = File.dirname(__FILE__)
 log_level %s
 log_location %s
 node_name "%s"
 client_key "#{current_dir}/chefkey.pem"
 chef_server_url "%s"
 cookbook_path ["%s"]''' % (self.log_level, self.log_location, self.node_name,
                            self.chef_server_url, self.cookbook_path)
       knife_rb_file = connection.getFile(
           OverthereUtils.constructPath(connection.getFile(path), 'knife.rb'))
       OverthereUtils.write(knife_contents, knife_rb_file)
 def execute(self):
     connection = None
     try:
         connection = self.getConnection()
         # upload the script and pass it to python
         exeFile = connection.getTempFile('script', '.py')
         OverthereUtils.write(String(self.script).getBytes(), exeFile)
         exeFile.setExecutable(True)
         scriptCommand = CmdLine.build('/usr/bin/python', exeFile.getPath())
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except AttributeError, e:
         self.logger.error(str(e))
 def copy_text_to_file(self, content, target, mkdirs=True):
     """
     Copies the content to the specified file
     :param content: to write to file
     :param target: com.xebialabs.overthere.OverthereFile
     :param mkdirs: Automatically create target directory
     """
     parent = target.parentFile
     if mkdirs and not parent.exists():
         self.logger.info("Creating path " + parent.path)
         parent.mkdirs()
     OverthereUtils.write(str(content), target)
    def create_license_file(connection, workspace_path, variables):
        contents='''
Copyright ${year} ${name}

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.'''
        repo_directory=OverthereUtils.constructPath(connection.getFile(workspace_path), '%s' % variables['github_repo_name'])
        readme_file=connection.getFile(OverthereUtils.constructPath(connection.getFile(repo_directory), 'License.md'))
        OverthereUtils.write(String(contents).getBytes(), readme_file)
    def create_travis_yml_file(connection, workspace_path, variables):
        contents='''language: java
sudo: false
deploy:
    provider: releases
    file: build/libs/%s-%s.jar
    skip_cleanup: true
    on:
        all_branches: true
        tags: true
        repo: %s/%s
''' % (variables['github_repo_name'], variables['initial_version'], variables['github_organization'], variables['github_repo_name'])
        repo_directory=OverthereUtils.constructPath(connection.getFile(workspace_path), '%s' % variables['github_repo_name'])
        travis_yml_file=connection.getFile(OverthereUtils.constructPath(connection.getFile(repo_directory), '.travis.yml'))
        OverthereUtils.write(String(contents).getBytes(), travis_yml_file)
    def bitbucket_downloadcode(self, variables):
        downloadURL = "%s/%s/get/%s.zip" % (variables['server']['url'].replace("api.","www."), variables['repo_full_name'], variables['branch'] )
        connection = LocalConnection.getLocalConnection()

        capturedOutput = ""

        print "Cleaning up download folder : %s" % variables['downloadPath']
        command = CmdLine()
        command.addArgument("rm")
        command.addArgument("-rf")
        command.addArgument(variables['downloadPath'] + "/*")
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput = self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        print " Now downloading code in download folder : %s" % variables['downloadPath']
        command = CmdLine()
        script = '''
            cd %s
            wget --user %s --password %s  -O code.zip %s
            unzip code.zip
            rm -rf *.zip
            foldername=`ls -d */`
            mv -f $foldername* `pwd`
            rm -rf $foldername
        ''' % (variables['downloadPath'], self.http_request.username, self.http_request.password,  downloadURL )
        script_file = connection.getFile(OverthereUtils.constructPath(connection.getFile(variables['downloadPath']), 'extract.sh'))
        OverthereUtils.write(String(script).getBytes(), script_file)
        script_file.setExecutable(True)
        command.addArgument(script_file.getPath())
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput += self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        command = CmdLine()
        command.addArgument("rm")
        command.addArgument("-f")
        command.addArgument(variables['downloadPath'] + "/extract.sh")
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput += self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        return {'output': capturedOutput}
 def execute_command(connection, workspace_path, command):
     try:
         print "executing command: %s" % command
         script_file = connection.getFile(OverthereUtils.constructPath(connection.getFile(workspace_path), 'command.cmd'))
         OverthereUtils.write(String(command).getBytes(), script_file)
         script_file.setExecutable(True)
         command = CmdLine()
         command.addArgument(script_file.getPath())
         output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
         error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
         exit_code = connection.execute(output_handler, error_handler, command)
         print "exit_code : %s" % exit_code
         print "output: %s" % output_handler.getOutput()
         print "errors: %s" % error_handler.getOutput()
         return [exit_code, output_handler, error_handler]
     except Exception:
         traceback.print_exc(file=sys.stdout)
         sys.exit(1)
 def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(SshConnectionBuilder.CONNECTION_TYPE, self.options)
         # upload the script and pass it to python
         exeFile = connection.getTempFile('f5_disable', '.py')
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         exeFile.setExecutable(True)
         # run cscript in batch mode
         scriptCommand = CmdLine.build( '/usr/bin/python', exeFile.getPath() )
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
    def stash_downloadcode(self, variables):
        downloadURL = "%s/rest/archive/latest/projects/%s/repos/%s/archive?at=refs/heads/%s&format=zip" % (variables['server']['url'], variables['project'], variables['repository'], variables['branch'])
        connection = LocalConnection.getLocalConnection()

        capturedOutput = ""

        print "Cleaning up download folder : %s" % variables['downloadPath']
        command = CmdLine()
        command.addArgument("mkdir")
        command.addArgument("-p")
        command.addArgument(variables['downloadPath'])
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput = self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        print " Now downloading code in download folder : %s" % variables['downloadPath']
        command = CmdLine()
        script = '''
            cd %s
            ls | grep -v extract.sh | xargs rm -rf
            wget --user %s --password %s  -O code.zip '%s'
            unzip -o code.zip
            rm code.zip
        ''' % (variables['downloadPath'], self.http_request.username, self.http_request.password,  downloadURL)
        script_file = connection.getFile(OverthereUtils.constructPath(connection.getFile(variables['downloadPath']), 'extract.sh'))
        OverthereUtils.write(String(script).getBytes(), script_file)
        script_file.setExecutable(True)
        command.addArgument(script_file.getPath())
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput += self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        command = CmdLine()
        command.addArgument("rm")
        command.addArgument("-f")
        command.addArgument(variables['downloadPath'] + "/extract.sh")
        output_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        error_handler = CapturingOverthereExecutionOutputHandler.capturingHandler()
        exit_code = connection.execute(output_handler, error_handler, command)
        capturedOutput += self.parse_output(output_handler.getOutputLines()) + self.parse_output(error_handler.getOutputLines())

        return {'output': capturedOutput}
示例#17
0
 def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(CifsConnectionBuilder.CIFS_PROTOCOL, self.options)
         connection.setWorkingDirectory(connection.getFile(self.remotePath))
         # upload the script and pass it to cscript.exe
         targetFile = connection.getTempFile('uploaded-script', '.vbs')
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         targetFile.setExecutable(True)
         # run cscript in batch mode
         scriptCommand = CmdLine.build(cscriptExecutable, '//B', '//nologo', targetFile.getPath())
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
 def read_file(self, filepath, encoding="UTF-8"):
     """
     Reads the content of a remote file as a string
     :param filepath: absolute path on target system
     :param encoding: target file encoding
     :return: String
     """
     otfile = self.get_conn().getFile(filepath)
     if not otfile.exists():
         raise Exception("File [%s] does not exist" % filepath)
     return OverthereUtils.read(otfile, encoding)
示例#19
0
 def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(
             CifsConnectionBuilder.CIFS_PROTOCOL, self.options)
         connection.setWorkingDirectory(connection.getFile(self.remotePath))
         # upload the script and pass it to cscript.exe
         targetFile = connection.getTempFile('uploaded-script', '.vbs')
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         targetFile.setExecutable(True)
         # run cscript in batch mode
         scriptCommand = CmdLine.build(cscriptExecutable, '//B', '//nologo',
                                       targetFile.getPath())
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
 def create_chef_tmp_workspace(self, connection):
     try:
         tmp_workspace_file = connection.getTempFile('tmp_workspace')
         workspace_path = re.sub('tmp_workspace', '',
                                 tmp_workspace_file.getPath())
         workspace_directory = connection.getFile(workspace_path)
         connection.setWorkingDirectory(workspace_directory)
         new_path = "%s.chef" % workspace_path
         if not os.path.exists(new_path):
             os.makedirs(new_path)
         self.generate_knife_rb(new_path, connection)
         chef_key_file = connection.getFile(
             OverthereUtils.constructPath(connection.getFile(new_path),
                                          'chefkey.pem'))
         OverthereUtils.write(
             String(self.client_key).getBytes(), chef_key_file)
         ssl_script = self.get_os_specific_ssl_script(workspace_path)
         script_file = connection.getFile(
             OverthereUtils.constructPath(
                 connection.getFile(workspace_path), 'ssl.cmd'))
         OverthereUtils.write(String(ssl_script).getBytes(), script_file)
         script_file.setExecutable(True)
         self.cmd_line.addArgument(script_file.getPath())
         connection.execute(self.stdout, self.stderr, self.cmd_line)
         return workspace_path
     except Exception:
         traceback.print_exc(file=sys.stdout)
         sys.exit(1)
示例#21
0
 def execute( self ):
    connection = None
    try:
       connection = LocalConnection.getLocalConnection()
       scriptFile = connection.getTempFile('xlrScript', '.py')
       OverthereUtils.write( String( self.script ).getBytes(), scriptFile )
       scriptFile.setExecutable(True)
       self.cmdLine.addArgument( '-source' )
       self.cmdLine.addArgument( scriptFile.getPath() )
       if ( len( self.options ) > 1 ):
          self.cmdLine.addArgument( '--' )
          optionsList = self.options.split(' ')
          for opt in optionsList:
              self.cmdLine.addArgument( opt )
          # End for
       # End if
       exitCode = connection.execute( self.stdout, self.stderr, self.cmdLine )
    except Exception, e:
          stacktrace = StringWriter()
          writer = PrintWriter(stacktrace, True)
          e.printStackTrace(writer)
          self.stderr.handleLine(stacktrace.toString())
          return 1
 def execute(self):
     self.customize(self.options)
     connection = None
     try:
         connection = Overthere.getConnection(CifsConnectionBuilder.CIFS_PROTOCOL, self.options)
         connection.setWorkingDirectory(connection.getFile(self.remotePath))
         # upload the script and pass it to cscript.exe
         targetFile = connection.getTempFile('parameters', '.txt')
         OverthereUtils.write(String(self.script).getBytes(), targetFile)
         targetFile.setExecutable(True)
         exeFile = connection.getTempFile('HpToolsLauncher', '.exe')
         sysloader = ClassLoader.getSystemClassLoader()
         OverthereUtils.write(sysloader.getResourceAsStream("HpTools/HpToolsLauncher.exe"), exeFile)
         exeFile.setExecutable(True)
         # run cscript in batch mode
         scriptCommand = CmdLine.build(exeFile.getPath(), '-paramfile', targetFile.getPath())
         return connection.execute(self.stdout, self.stderr, scriptCommand)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
 def execute(self):
     connection = None
     try:
         connection = LocalConnection.getLocalConnection()
         scriptFile = connection.getTempFile('xlrScript', '.py')
         OverthereUtils.write(String(self.script).getBytes(), scriptFile)
         scriptFile.setExecutable(True)
         self.cmdLine.addArgument('-source')
         self.cmdLine.addArgument(scriptFile.getPath())
         if len(self.options) > 1:
             self.cmdLine.addArgument('--')
             optionsList = self.options.split(' ')
             for opt in optionsList:
                 self.cmdLine.addArgument(opt)
             # End for
         # End if
         exitCode = connection.execute(self.stdout, self.stderr,
                                       self.cmdLine)
     except Exception, e:
         stacktrace = StringWriter()
         writer = PrintWriter(stacktrace, True)
         e.printStackTrace(writer)
         self.stderr.handleLine(stacktrace.toString())
         return 1
#
# 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 was.portal.utils.xmlaccess import XmlAccess
from was.portal.utils.template import TemplateRenderer
from com.xebialabs.overthere.util import OverthereUtils

xmlaccess = XmlAccess.new_instance_from_container(context, deployed.container.cell, deployed.container.cell.portalHost)

if is_file:
    req_file = deployed.file.getFile(req_xml)
    xml = OverthereUtils.read(req_file, "UTF-8")
else:
    xml = req_xml

rendered_xml = TemplateRenderer().render(xml, {'deployed': deployed})
xmlaccess.execute_and_log_input_output(rendered_xml, config_uri=deployed.configUri)
示例#25
0
#
# Copyright 2018 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from was.portal.utils.xmlaccess import XmlAccess
from was.portal.utils.template import TemplateRenderer
from com.xebialabs.overthere.util import OverthereUtils

xmlaccess = XmlAccess.new_instance_from_container(context, deployed)

if is_file:
    req_file = deployed.file.getFile(req_xml)
    xml = OverthereUtils.read(req_file, "UTF-8")
else:
    xml = req_xml

rendered_xml = TemplateRenderer().render(xml, {'deployed': deployed})
xmlaccess.execute_and_log_input_output(rendered_xml, config_uri=deployed.configUri)
script = """

%s
%s

""" % (cmdLogon, cmdProject)
#print script
print "-------------------------"

stdout = CapturingOverthereExecutionOutputHandler.capturingHandler()
stderr = CapturingOverthereExecutionOutputHandler.capturingHandler()

try:
    connection = LocalConnection.getLocalConnection()
    targetScript = connection.getTempFile('oc-script', '.bat')
    OverthereUtils.write( String(script).getBytes(), targetScript)
    targetScript.setExecutable(True)
    cmd = CmdLine.build( targetScript.getPath() )
    connection.execute( stdout, stderr, cmd )
except Exception, e:
    stacktrace = StringWriter()
    writer = PrintWriter( stacktrace, True )
    e.printStackTrace(writer)
    stderr.hadleLine(stacktrace.toString())

# set variables
output = stdout.getOutput()
error = stderr.getOutput()


if len(output) > 0:
ocUrl = openShiftServer['url']
ocHome = openShiftServer['ocHome']
ocCmd = "%soc" % (ocHome)

print "URL       = %s" % ocUrl
print "USERNAME  = %s" % ocUsername
print "OC        = %s" % ocCmd
print " "

stdout = CapturingOverthereExecutionOutputHandler.capturingHandler()
stderr = CapturingOverthereExecutionOutputHandler.capturingHandler()

try:
    connection = LocalConnection.getLocalConnection()
    targetYaml = connection.getTempFile('resource', '.yaml')
    OverthereUtils.write(String(resourceYaml).getBytes(), targetYaml)
    cmdLogon = "%s login --server=%s -u %s -p %s --insecure-skip-tls-verify" % (
        ocCmd, ocUrl, ocUsername, ocPassword)
    cmdProject = "%s project %s" % (ocCmd, ocProject)
    cmdCreate = "%s create -f %s -n %s " % (ocCmd, targetYaml.getPath(),
                                            ocProject)
    script = """
    %s
    %s
    %s
    """ % (cmdLogon, cmdProject, cmdCreate)

    #print script
    print "-------------------------"

    targetScript = connection.getTempFile('oc-script', '.bat')
示例#28
0
    os = OperatingSystemFamily.WINDOWS
else:
    os = OperatingSystemFamily.UNIX

local_opts = LocalConnectionOptions(os=os)
local_host = OverthereHost(local_opts)
local_session = OverthereHostSession(local_host, stream_command_output=True)

local_yaml_file = local_session.work_dir_file(remote_yaml_file.getName())
print("local_yaml_file {0}".format(local_yaml_file))

print("copy....")
local_session.copy_to(remote_yaml_file, local_yaml_file)

print("---- YAML ")
print(OverthereUtils.read(local_yaml_file, Charset.defaultCharset().name()))
print("/----")

context = {
    'devopsAsCodePassword': ansible_controler.devopsAsCodePassword,
    'devopsAsCodeUsername': ansible_controler.devopsAsCodeUsername,
    'devopsAsCodeUrl': ansible_controler.devopsAsCodeUrl,
    'yaml_file': local_yaml_file.path,
    'xlPath': ansible_controler.xlPath
}

command_line = "{xlPath} --xl-deploy-password {devopsAsCodePassword} --xl-deploy-username {devopsAsCodeUsername} --xl-deploy-url {devopsAsCodeUrl} apply -f {yaml_file} ".format(
    **context)
print(command_line)

import subprocess