Esempio n. 1
0
 def prepare(self):
     # XXX: server is terminated during sysprep.
     # we should better understand how it works
     #shutil.copy(r'C:\Windows\System32\sysprep\RunSysprep_2.cmd', r'C:\windows\system32\sysprep\RunSysprep.cmd')
     #shutil.copy(r'C:\Windows\System32\sysprep\SetupComplete_2.cmd', r'C:\windows\setup\scripts\SetupComplete.cmd')
     #linux.system((r'C:\windows\system32\sysprep\RunSysprep.cmd', ))
     return software.system_info()
Esempio n. 2
0
    def on_Rebundle(self, message):
        try:
            self._role_name = message.role_name.encode("ascii")
            self._excludes = message.excludes.encode("ascii").split(":") \
                            if message.body.has_key("excludes") and message.excludes else []
            self._rebundle_message = message

            # Preparing...
            self.before_rebundle()
            bus.fire("before_rebundle", role_name=self._role_name)

            # Send wall message before rebundling. So console users can run away
            if not system2(('which', 'wall'), raise_exc=False)[2]:
                system2(('wall'), stdin=WALL_MESSAGE, raise_exc=False)

            # Do actual rebundle work
            cnf = bus.cnf
            saved_state = cnf.state
            image_id = self.rebundle()

            # Creating message
            result = dict(status="ok",
                          snapshot_id=image_id,
                          bundle_task_id=message.bundle_task_id)

            # Updating message with OS, software and modules info
            result.update(software.system_info())

            # Fire 'rebundle'diss
            bus.fire("rebundle",
                     role_name=self._role_name,
                     snapshot_id=image_id,
                     rebundle_result=result)

            # Notify Scalr
            self.send_message(Messages.REBUNDLE_RESULT, result)

            LOG.info(
                'Rebundle complete! If you imported this server to Scalr, '
                'you can terminate Scalarizr now.')

        except (Exception, BaseException), e:
            LOG.exception(e)
            last_error = hasattr(e,
                                 "error_message") and e.error_message or str(e)

            # Send message to Scalr
            self.send_message(
                Messages.REBUNDLE_RESULT,
                dict(status="error",
                     last_error=last_error,
                     bundle_task_id=message.bundle_task_id))

            # Fire 'rebundle_error'
            bus.fire("rebundle_error",
                     role_name=self._role_name,
                     last_error=last_error)
Esempio n. 3
0
    def on_Rebundle(self, message):
        try:
            self._role_name = message.role_name.encode("ascii")
            self._excludes = message.excludes.encode("ascii").split(":") \
                            if message.body.has_key("excludes") and message.excludes else []
            self._rebundle_message = message

            # Preparing...
            self.before_rebundle()
            bus.fire("before_rebundle", role_name=self._role_name)

            # Send wall message before rebundling. So console users can run away
            if not system2(('which', 'wall'), raise_exc=False)[2]:
                system2(('wall'), stdin=WALL_MESSAGE, raise_exc=False)

            # Do actual rebundle work
            cnf = bus.cnf
            saved_state = cnf.state
            try:
                cnf.state = ScalarizrState.REBUNDLING
                image_id = self.rebundle()
            finally:
                cnf.state = saved_state

            # Creating message
            result = dict(
                    status = "ok",
                    snapshot_id = image_id,
                    bundle_task_id = message.bundle_task_id
            )

            # Updating message with OS, software and modules info
            result.update(software.system_info())

            # Fire 'rebundle'diss
            bus.fire("rebundle", role_name=self._role_name, snapshot_id=image_id, rebundle_result=result)

            # Notify Scalr
            self.send_message(Messages.REBUNDLE_RESULT, result)

            LOG.info('Rebundle complete! If you imported this server to Scalr, '
                            'you can terminate Scalarizr now.')

        except (Exception, BaseException), e:
            LOG.exception(e)
            last_error = hasattr(e, "error_message") and e.error_message or str(e)

            # Send message to Scalr
            self.send_message(Messages.REBUNDLE_RESULT, dict(
                    status = "error",
                    last_error = last_error,
                    bundle_task_id = message.bundle_task_id
            ))

            # Fire 'rebundle_error'
            bus.fire("rebundle_error", role_name=self._role_name, last_error=last_error)
Esempio n. 4
0
class ImageAPI(object):

    __metaclass__ = Singleton

    platform_to_delegate = {
        BuiltinPlatforms.OPENSTACK:
        ('scalarizr.api.image.openstack', 'OpenStackImageAPIDelegate'),
        BuiltinPlatforms.EC2:
        ('scalarizr.api.image.ec2', 'EC2ImageAPIDelegate'),
        BuiltinPlatforms.CLOUDSTACK:
        ('scalarizr.api.image.cloudstack', 'CloudStackImageAPIDelegate'),
        BuiltinPlatforms.IDCF:
        ('scalarizr.api.image.cloudstack', 'CloudStackImageAPIDelegate'),
        BuiltinPlatforms.GCE: ('scalarizr.api.image.gce',
                               'GCEImageAPIDelegate'),
    }

    def __init__(self):
        self._op_api = OperationAPI()
        self.delegate = None

    def delegate_for_platform(self, platform_name):
        delegate = self.platform_to_delegate.get(platform_name)
        if not delegate:
            LOG.debug('platform object: %s, class: %s' %
                      (__node__['platform'], type(__node__['platform'])))
            raise ImageAPIError('unknown platform: %s' %
                                __node__['platform'].name)
        module = __import__(delegate[0], globals(), locals(), [delegate[1]],
                            -1)
        return module.__getattribute__(delegate[1])()

    def init_delegate(self):
        if self.delegate:
            return
        self.delegate = self.delegate_for_platform(__node__['platform'].name)

    @rpc.command_method
    def prepare(self, name=None, async=False):
        self.init_delegate()
        if not system2(('which', 'wall'), raise_exc=False)[2]:
            system2(('wall'), stdin=WALL_MESSAGE, raise_exc=False)
        prepare_result = self._op_api.run('api.image.prepare',
                                          func=self.delegate.prepare,
                                          async=async,
                                          exclusive=True,
                                          func_kwds={'name': name})
        result = {}
        if prepare_result:
            result['prepare_result'] = prepare_result

        result.update(software.system_info())
        return result
Esempio n. 5
0
    def get_ready_behaviours(self):
        handlers = list()
        info = software.system_info(verbose=True)
        if 'software' in info:
            Version = distutils.version.LooseVersion
            for entry in info['software']:
                if not ('name' in entry and 'version' in entry):
                    continue
                name = entry['name']

                version = Version(entry['version'])

                str_ver = entry[
                    'string_version'] if 'string_version' in entry else ''
                if name == 'nginx':
                    handlers.append(config.BuiltinBehaviours.WWW)
                elif name == 'chef':
                    handlers.append(config.BuiltinBehaviours.CHEF)
                elif name == 'memcached':
                    handlers.append(config.BuiltinBehaviours.MEMCACHED)

                elif name == 'postgresql' and Version(
                        '9.0') <= version < Version('9.3'):
                    handlers.append(config.BuiltinBehaviours.POSTGRESQL)
                elif name == 'redis' and Version('2.2') <= version < Version(
                        '2.9'):
                    handlers.append(config.BuiltinBehaviours.REDIS)
                elif name == 'rabbitmq' and Version(
                        '2.6') <= version < Version('3.2'):
                    handlers.append(config.BuiltinBehaviours.RABBITMQ)
                elif name == 'mongodb' and Version('2.0') <= version < Version(
                        '2.5'):
                    handlers.append(config.BuiltinBehaviours.MONGODB)
                elif name == 'apache' and Version('2.0') <= version < Version(
                        '2.5'):  # experimental for ubuntu1304
                    handlers.append(config.BuiltinBehaviours.APP)
                elif name == 'haproxy' and Version('1.3') < version < Version(
                        '1.5'):
                    handlers.append(config.BuiltinBehaviours.HAPROXY)
                elif name == 'mysql' and Version('5.0') <= version < Version(
                        '5.6'):
                    handlers.append(config.BuiltinBehaviours.MYSQL)
                    if 'Percona' in str_ver:
                        handlers.append(config.BuiltinBehaviours.PERCONA)
                    elif 'Maria' in str_ver:
                        handlers.append(config.BuiltinBehaviours.MARIADB)
                    else:
                        handlers.append(config.BuiltinBehaviours.MYSQL2)
                elif name == 'tomcat':
                    handlers.append(config.BuiltinBehaviours.TOMCAT)

        return handlers
Esempio n. 6
0
	def _start_import(self):
		data = software.system_info()
		data['architecture'] = self._platform.get_architecture()
		data['server_id'] = self._cnf.rawini.get(config.SECT_GENERAL, config.OPT_SERVER_ID)

		# Send Hello
		msg = self.new_message(Messages.HELLO, data,
			broadcast=True # It's not really broadcast but need to contain broadcast message data 
		)
		msg.body['behaviour'] = self.get_ready_behaviours()
		bus.fire("before_hello", msg)
		self.send_message(msg)
		bus.fire("hello")
Esempio n. 7
0
    def _start_import(self):
        data = software.system_info()
        data["architecture"] = self._platform.get_architecture()
        data["server_id"] = self._cnf.rawini.get(config.SECT_GENERAL, config.OPT_SERVER_ID)

        # Send Hello
        msg = self.new_message(
            Messages.HELLO, data, broadcast=True  # It's not really broadcast but need to contain broadcast message data
        )
        behs = self.get_ready_behaviours()
        if "mysql2" in behs or "percona" in behs:
            # only mysql2 should be returned to Scalr
            try:
                behs.remove("mysql")
            except (IndexError, ValueError):
                pass
        msg.body["behaviour"] = behs
        bus.fire("before_hello", msg)
        self.send_message(msg)
        bus.fire("hello")
Esempio n. 8
0
    def on_Win_PrepareBundle(self, message):
        try:
            # XXX: server is terminated during sysprep.
            # we should better understand how it works
            #shutil.copy(r'C:\Windows\System32\sysprep\RunSysprep_2.cmd', r'C:\windows\system32\sysprep\RunSysprep.cmd')
            #shutil.copy(r'C:\Windows\System32\sysprep\SetupComplete_2.cmd', r'C:\windows\setup\scripts\SetupComplete.cmd')
            #linux.system((r'C:\windows\system32\sysprep\RunSysprep.cmd', ))

            result = dict(status="ok", bundle_task_id=message.bundle_task_id)
            result.update(software.system_info())
            self.send_message(Messages.WIN_PREPARE_BUNDLE_RESULT, result)

        except:
            e = sys.exc_info()[1]
            LOG.exception(e)
            last_error = hasattr(e,
                                 "error_message") and e.error_message or str(e)
            self.send_message(
                Messages.WIN_PREPARE_BUNDLE_RESULT,
                dict(status="error",
                     last_error=last_error,
                     bundle_task_id=message.bundle_task_id))
Esempio n. 9
0
    def _start_import(self):
        data = software.system_info()
        data['architecture'] = self._platform.get_architecture()
        data['server_id'] = self._cnf.rawini.get(config.SECT_GENERAL,
                                                 config.OPT_SERVER_ID)

        # Send Hello
        msg = self.new_message(
            Messages.HELLO,
            data,
            broadcast=
            True  # It's not really broadcast but need to contain broadcast message data
        )
        behs = self.get_ready_behaviours()
        if 'mysql2' in behs or 'percona' in behs:
            # only mysql2 should be returned to Scalr
            try:
                behs.remove('mysql')
            except (IndexError, ValueError):
                pass
        msg.body['behaviour'] = behs
        bus.fire("before_hello", msg)
        self.send_message(msg)
        bus.fire("hello")
Esempio n. 10
0
    def on_Win_PrepareBundle(self, message):
        try:
            # XXX: server is terminated during sysprep.
            # we should better understand how it works
            #shutil.copy(r'C:\Windows\System32\sysprep\RunSysprep_2.cmd', r'C:\windows\system32\sysprep\RunSysprep.cmd')
            #shutil.copy(r'C:\Windows\System32\sysprep\SetupComplete_2.cmd', r'C:\windows\setup\scripts\SetupComplete.cmd')
            #linux.system((r'C:\windows\system32\sysprep\RunSysprep.cmd', ))

            result = dict(
                status = "ok",
                bundle_task_id = message.bundle_task_id              
            )
            result.update(software.system_info())
            self.send_message(Messages.WIN_PREPARE_BUNDLE_RESULT, result)

        except:
            e = sys.exc_info()[1]
            LOG.exception(e)
            last_error = hasattr(e, "error_message") and e.error_message or str(e)
            self.send_message(Messages.WIN_PREPARE_BUNDLE_RESULT, dict(
                status = "error",
                last_error = last_error,
                bundle_task_id = message.bundle_task_id
            ))
Esempio n. 11
0
			json_file = os.path.join(os.getcwd(), 'sysinfo-%s.json' % hostname)

			cnf = bus.cnf
			cnf.bootstrap()
			ini = cnf.rawini
			try:
				log_params = ini.get('handler_file', 'args')
				try:
					log_file = log_params(0)
				except IndexError, TypeError:
					raise
			except Exception, BaseException:
				log_file = '/var/log/scalarizr.log'

			file = open(json_file, 'w')
			json.dump(system_info(), file, sort_keys=True, indent=4)
			file.close()

			tar = tarfile.open(tar_file, "w:gz")
			tar.add(json_file)
			if os.path.exists(log_file):
				tar.add(log_file)
			tar.close()

			#cleaning
			if os.path.exists(json_file):
				os.remove(json_file)

			#sending
			fromaddr='root@%s' % hostname
			try:
Esempio n. 12
0
            json_file = os.path.join(os.getcwd(), 'sysinfo-%s.json' % hostname)

            cnf = bus.cnf
            cnf.bootstrap()
            ini = cnf.rawini
            try:
                log_params = ini.get('handler_file', 'args')
                try:
                    log_file = log_params(0)
                except (IndexError, TypeError):
                    raise
            except Exception, BaseException:
                log_file = '/var/log/scalarizr.log'

            file = open(json_file, 'w')
            json.dump(system_info(), file, sort_keys=True, indent=4)
            file.close()

            tar = tarfile.open(tar_file, "w:gz")
            tar.add(json_file)
            if os.path.exists(log_file):
                tar.add(log_file)
            tar.close()

            #cleaning
            if os.path.exists(json_file):
                os.remove(json_file)

            #sending
            fromaddr = 'root@%s' % hostname
            try: