def __init__(self, **kwds):
		'''
		Variant A:
		Script(name='AppPreStart', body='#!/usr/bin/python ...', asynchronous=True)
		
		Variant B:
		Script(id=43432234343, name='AppPreStart', pid=12145, 
				interpreter='/usr/bin/python', start_time=4342424324, asynchronous=True)
		'''
		for key, value in kwds.items():
			setattr(self, key, value)
		
		assert self.name, '`name` required'
		assert self.exec_timeout, '`exec_timeout` required'
		
		if self.name and self.body:
			self.id = str(time.time())
			interpreter = read_shebang(script=self.body)
			if not interpreter:
				raise HandlerError("Can't execute script '%s' cause it hasn't shebang.\n"
								"First line of the script should have the form of a shebang "
								"interpreter directive is as follows:\n" 
								"#!interpreter [optional-arg]" % (self.name, ))
			self.interpreter = interpreter
		else:
			assert self.id, '`id` required'
			assert self.pid, '`pid` required'			
			assert self.start_time, '`start_time` required'

		self.logger = logging.getLogger('%s.%s' % (__name__, self.id))
		self.exec_path = os.path.join(exec_dir_prefix + self.id, self.name)
		args = (self.name, self.event_name, self.role_name, self.id)
		self.stdout_path = os.path.join(logs_dir, '%s.%s.%s.%s-out.log' % args)
		self.stderr_path = os.path.join(logs_dir, '%s.%s.%s.%s-err.log' % args)
Exemple #2
0
    def check_runability(self):
        path_params = urlparse(self.path or '')
        if path_params.scheme in ('http', 'https'):
            if path_params.scheme == 'https' and with_httplib2:
                # we are using httplib2 for opening https url because it
                # makes ssl certificate validation and urlopen doesn't
                h = httplib2.Http()
                meta, self.body = h.request(self.path)
                if meta['status'].startswith('4') or meta['status'].startswith(
                        '5'):
                    raise HandlerError(
                        "Can't download script from URL '%s'. Status code: %s"
                        % (self.path, meta['status']))
            else:
                try:
                    response = urlopen(self.path)
                    self.body = response.read()
                except:
                    raise HandlerError(
                        "Can't download script from URL '%s'. Reason: "
                        "%s" % (self.path, sys.exc_info()[1]))
            self.path = None
            self.exec_path = self._generate_exec_path()

        if self.body or (self.path and not coreutils.is_binary(self.path)):
            self.interpreter = read_shebang(path=self.path, script=self.body)
            if linux.os['family'] == 'Windows' and self.body:
                # Erase first line with #!
                self.body = '\n'.join(self.body.splitlines()[1:])
        elif self.path:
            self.interpreter = self.path

        if self.interpreter == 'powershell' \
                and os.path.splitext(self.exec_path)[1] not in ('.ps1', '.psm1'):
            self.exec_path += '.ps1'
        elif self.interpreter == 'cmd' \
                and os.path.splitext(self.exec_path)[1] not in ('.cmd', '.bat'):
            self.exec_path += '.bat'

        if self.path and not os.access(self.path, os.X_OK):
            msg = 'Path {0!r} is not executable'.format(self.path)
            raise HandlerError(msg)
        if linux.os['family'] == 'Windows' and self.run_as:
            raise HandlerError("Windows can't execute scripts remotely " \
                               "under user other than Administrator. " \
                               "Script '%s', given user: '******'" % (self.name, self.run_as))
        if not self.interpreter:
            raise HandlerError(
                "Can't execute script '%s' cause it has no shebang.\n"
                "First line of the script should have the form of a shebang "
                "interpreter directive is as follows:\n"
                "#!interpreter [optional-arg]" % (self.name, ))
        if not os.path.exists(
                self.interpreter) and linux.os['family'] != 'Windows':
            raise HandlerError("Can't execute script '%s' cause "
                               "interpreter '%s' not found" %
                               (self.name, self.interpreter))
    def check_runability(self):
        path_params = urlparse(self.path or '')
        if path_params.scheme != '':
            if path_params.scheme == 'https':
                # we are using httplib2 for opening https url because it
                # makes ssl certificate validation and urlopen doesn't
                h = httplib2.Http()
                meta, self.body = h.request(self.path)
                if meta['status'].startswith('4') or meta['status'].startswith('5'):
                    raise HandlerError("Can't download script from URL '%s'. Status code: %s"
                        % (self.path, meta['status']))
            else:
                try:
                    response = urlopen(self.path)
                    self.body = response.read()
                except:
                    raise HandlerError("Can't download script from URL '%s'. Reason: "
                        "%s" % (self.path, sys.exc_info()[1]))
            self.path = None
            self.exec_path = self._generate_exec_path()

        if self.body or self.path:
            self.interpreter = read_shebang(path=self.path, script=self.body)
            if linux.os['family'] == 'Windows' and self.body:
                # Erase first line with #!
                self.body = '\n'.join(self.body.splitlines()[1:])

        if self.interpreter == 'powershell' \
                and os.path.splitext(self.exec_path)[1] not in ('.ps1', '.psm1'):
            self.exec_path += '.ps1'
        elif self.interpreter == 'cmd' \
                and os.path.splitext(self.exec_path)[1] not in ('.cmd', '.bat'):
            self.exec_path += '.bat'

        if self.path and not os.access(self.path, os.X_OK):
            msg = 'Path {0!r} is not executable'.format(self.path)
            raise HandlerError(msg)
        if linux.os['family'] == 'Windows' and self.run_as:
            raise HandlerError("Windows can't execute scripts remotely " \
                               "under user other than Administrator. " \
                               "Script '%s', given user: '******'" % (self.name, self.run_as))
        if not self.interpreter:
            raise HandlerError("Can't execute script '%s' cause it has no shebang.\n"
                "First line of the script should have the form of a shebang "
                "interpreter directive is as follows:\n"
                "#!interpreter [optional-arg]" % (self.name, ))
        if not os.path.exists(self.interpreter) and linux.os['family'] != 'Windows':
            raise HandlerError("Can't execute script '%s' cause "
                "interpreter '%s' not found" % (self.name, self.interpreter))
    def __init__(self, **kwds):
        '''
        Variant A:
        Script(name='AppPreStart', body='#!/usr/bin/python ...', asynchronous=True)

        Variant B:
        Script(id=43432234343, name='AppPreStart', pid=12145,
                        interpreter='/usr/bin/python', start_time=4342424324, asynchronous=True)
        '''
        for key, value in kwds.items():
            setattr(self, key, value)

        assert self.name, '`name` required'
        assert self.exec_timeout, '`exec_timeout` required'

        if self.name and self.body:
            self.id = str(time.time())
            interpreter = read_shebang(script=self.body)
            if not interpreter:
                raise HandlerError(
                    "Can't execute script '%s' cause it hasn't shebang.\n"
                    "First line of the script should have the form of a shebang "
                    "interpreter directive is as follows:\n"
                    "#!interpreter [optional-arg]" % (self.name, ))
            self.interpreter = interpreter
        else:
            assert self.id, '`id` required'
            assert self.pid, '`pid` required'
            assert self.start_time, '`start_time` required'
            if self.interpreter:
                self.interpreter = split_strip(self.interpreter)[0]

        self.logger = logging.getLogger('%s.%s' % (__name__, self.id))
        self.exec_path = os.path.join(exec_dir_prefix + self.id, self.name)
        if self.exec_timeout:
            self.exec_timeout = int(self.exec_timeout)
        args = (self.name, self.event_name, self.role_name, self.id)
        self.stdout_path = os.path.join(logs_dir, '%s.%s.%s.%s-out.log' % args)
        self.stderr_path = os.path.join(logs_dir, '%s.%s.%s.%s-err.log' % args)
    def __init__(self, **kwds):
        '''
        Variant A:
        Script(name='AppPreStart', body='#!/usr/bin/python ...', asynchronous=True)

        Variant B:
        Script(id=43432234343, name='AppPreStart', pid=12145,
                        interpreter='/usr/bin/python', start_time=4342424324, asynchronous=True)
        '''
        for key, value in kwds.items():
            setattr(self, key, value)

        assert self.name, '`name` required'
        assert self.exec_timeout, '`exec_timeout` required'
        if linux.os['family'] == 'Windows' and self.run_as:
            raise HandlerError("Windows can't execute scripts remotely " \
                               "under user other than Administrator. " \
                               "Script '%s', given user: '******'" % (self.name, self.run_as))

        if self.name and (self.body or self.path):
            random.seed()
            # time.time() can produce the same microseconds fraction in different async script execution threads,
            # and therefore produce the same id. solution is to seed random millisecods number
            self.id = '%d.%d' % (time.time(), random.randint(0, 100))

            interpreter = read_shebang(path=self.path, script=self.body)
            if not interpreter:
                raise HandlerError(
                    "Can't execute script '%s' cause it hasn't shebang.\n"
                    "First line of the script should have the form of a shebang "
                    "interpreter directive is as follows:\n"
                    "#!interpreter [optional-arg]" % (self.name, ))
            self.interpreter = interpreter

            if linux.os['family'] == 'Windows' and self.body:
                # Erase first line with #!
                self.body = '\n'.join(self.body.splitlines()[1:])

        else:
            assert self.id, '`id` required'
            assert self.pid, '`pid` required'
            assert self.start_time, '`start_time` required'
            if self.interpreter:
                self.interpreter = split_strip(self.interpreter)[0]

        self.logger = logging.getLogger('%s.%s' % (__name__, self.id))
        self.exec_path = self.path or os.path.join(exec_dir_prefix + self.id,
                                                   self.name)

        if  self.interpreter == 'powershell' \
                and os.path.splitext(self.exec_path)[1] not in ('ps1', 'psm1'):
            self.exec_path += '.ps1'
        elif self.interpreter == 'cmd' \
                and os.path.splitext(self.exec_path)[1] not in ('cmd', 'bat'):
            self.exec_path += '.bat'

        if self.exec_timeout:
            self.exec_timeout = int(self.exec_timeout)

        if self.execution_id:
            args = (self.name, self.event_name, self.execution_id)
            self.stdout_path = os.path.join(logs_dir,
                                            '%s.%s.%s-out.log' % args)
            self.stderr_path = os.path.join(logs_dir,
                                            '%s.%s.%s-err.log' % args)
        else:
            args = (self.name, self.event_name, self.role_name, self.id)
            self.stdout_path = os.path.join(logs_dir,
                                            '%s.%s.%s.%s-out.log' % args)
            self.stderr_path = os.path.join(logs_dir,
                                            '%s.%s.%s.%s-err.log' % args)
    def __init__(self, **kwds):
        '''
        Variant A:
        Script(name='AppPreStart', body='#!/usr/bin/python ...', asynchronous=True)

        Variant B:
        Script(id=43432234343, name='AppPreStart', pid=12145,
                        interpreter='/usr/bin/python', start_time=4342424324, asynchronous=True)
        '''
        for key, value in kwds.items():
            setattr(self, key, value)


        assert self.name, '`name` required'
        assert self.exec_timeout, '`exec_timeout` required'
        if linux.os['family'] == 'Windows' and self.run_as:
            raise HandlerError("Windows can't execute scripts remotely " \
                               "under user other than Administrator. " \
                               "Script '%s', given user: '******'" % (self.name, self.run_as))

        if self.name and (self.body or self.path):
            random.seed()
            # time.time() can produce the same microseconds fraction in different async script execution threads, 
            # and therefore produce the same id. solution is to seed random millisecods number
            self.id = '%d.%d' % (time.time(), random.randint(0, 100))

            interpreter = read_shebang(path=self.path, script=self.body)
            if not interpreter:
                raise HandlerError("Can't execute script '%s' cause it hasn't shebang.\n"
                                                "First line of the script should have the form of a shebang "
                                                "interpreter directive is as follows:\n"
                                                "#!interpreter [optional-arg]" % (self.name, ))
            self.interpreter = interpreter
            
            if linux.os['family'] == 'Windows' and self.body:
                # Erase first line with #!
                self.body = '\n'.join(self.body.splitlines()[1:])

        else:
            assert self.id, '`id` required'
            assert self.pid, '`pid` required'
            assert self.start_time, '`start_time` required'
            if self.interpreter:
                self.interpreter = split_strip(self.interpreter)[0]
                

        self.logger = logging.getLogger('%s.%s' % (__name__, self.id))
        self.exec_path = self.path or os.path.join(exec_dir_prefix + self.id, self.name)

        if  self.interpreter == 'powershell' \
                and os.path.splitext(self.exec_path)[1] not in ('ps1', 'psm1'):
            self.exec_path += '.ps1'
        elif self.interpreter == 'cmd' \
                and os.path.splitext(self.exec_path)[1] not in ('cmd', 'bat'):
            self.exec_path += '.bat'

        if self.exec_timeout:
            self.exec_timeout = int(self.exec_timeout)

        if self.execution_id:
            args = (self.name, self.event_name, self.execution_id)
            self.stdout_path = os.path.join(logs_dir, '%s.%s.%s-out.log' % args)
            self.stderr_path = os.path.join(logs_dir, '%s.%s.%s-err.log' % args)
        else:
            args = (self.name, self.event_name, self.role_name, self.id)
            self.stdout_path = os.path.join(logs_dir, '%s.%s.%s.%s-out.log' % args)
            self.stderr_path = os.path.join(logs_dir, '%s.%s.%s.%s-err.log' % args)