Beispiel #1
0
def _init_platform():
    logger = logging.getLogger(__name__)
    cnf = bus.cnf
    ini = cnf.rawini

    platform_name = ini.get('general', 'platform')

    if linux.os['name'] == 'RedHat' and platform_name == 'ec2':
        # Enable RedHat subscription
        logger.debug('Enable RedHat subscription')
        urllib.urlretrieve(
            'http://169.254.169.254/latest/dynamic/instance-identity/document')

    if cnf.state != ScalarizrState.RUNNING and not linux.os.windows_family:
        try:
            pkgmgr.updatedb()
        except:
            logger.warn('Failed to update package manager database: %s',
                        sys.exc_info()[1],
                        exc_info=sys.exc_info())

    if httplib2_loaded:
        httplib2.CA_CERTS = os.path.join(os.path.dirname(__file__),
                                         'cacert.pem')

    # Initialize platform
    logger.debug("Initialize platform")
    if platform_name:
        bus.platform = PlatformFactory().new_platform(platform_name)
    else:
        raise ScalarizrError("Platform not defined")
Beispiel #2
0
def _init_platform():
    logger = logging.getLogger(__name__)
    cnf = bus.cnf; ini = cnf.rawini
    
    platform_name = ini.get('general', 'platform')

    if linux.os['name'] == 'RedHat' and platform_name == 'ec2':
        # Enable RedHat subscription 
        logger.debug('Enable RedHat subscription')
        urllib.urlretrieve('http://169.254.169.254/latest/dynamic/instance-identity/document')

    if cnf.state != ScalarizrState.RUNNING and not linux.os.windows_family:
        try:
            pkgmgr.updatedb()
        except:
            logger.warn('Failed to update package manager database: %s', 
                    sys.exc_info()[1], exc_info=sys.exc_info())

    if httplib2_loaded:
        httplib2.CA_CERTS = os.path.join(os.path.dirname(__file__), 'cacert.pem')

    # Initialize platform
    logger.debug("Initialize platform")
    if platform_name:
        bus.platform = PlatformFactory().new_platform(platform_name)
    else:
        raise ScalarizrError("Platform not defined")
Beispiel #3
0
 def _prepare_software(self):
     # windows has no ami tools. Bundle is made by scalr
     if linux.os['family'] != 'Windows':
         pkgmgr.updatedb()
         self._install_sg3_utils()
         self._install_ami_tools()
         if linux.os['family'] == 'RedHat':
             pkgmgr.installed('parted')
         pkgmgr.installed('kpartx')
Beispiel #4
0
 def _prepare_software(self):
     # windows has no ami tools. Bundle is made by scalr
     if linux.os['family'] != 'Windows':
         pkgmgr.updatedb()
         self._install_sg3_utils()
         self._install_ami_tools()
         if linux.os['family'] == 'RedHat':
             pkgmgr.installed('parted')
         pkgmgr.installed('kpartx')
Beispiel #5
0
def _init_platform():
	logger = logging.getLogger(__name__)
	cnf = bus.cnf; ini = cnf.rawini
	
	try:
		pkgmgr.updatedb()
	except:
		logger.warn('Failed to update package manager database: %s', 
				sys.exc_info()[1], exc_info=sys.exc_info())

	# Initialize platform
	logger.debug("Initialize platform")
	name = ini.get('general', 'platform')
	if name:
		bus.platform = PlatformFactory().new_platform(name)
	else:
		raise ScalarizrError("Platform not defined")
Beispiel #6
0
def _init_platform():
    logger = logging.getLogger(__name__)
    cnf = bus.cnf
    ini = cnf.rawini

    try:
        pkgmgr.updatedb()
    except:
        logger.warn('Failed to update package manager database: %s',
                    sys.exc_info()[1],
                    exc_info=sys.exc_info())

    # Initialize platform
    logger.debug("Initialize platform")
    name = ini.get('general', 'platform')
    if name:
        bus.platform = PlatformFactory().new_platform(name)
    else:
        raise ScalarizrError("Platform not defined")
Beispiel #7
0
    def start(self):
        self._logger.debug("Initialize scalarizr...")
        _init()
        _init_environ()

        # Starting scalarizr daemon initialization
        globals()['_pid'] = pid = os.getpid()
        self._logger.info('[pid: %d] Starting scalarizr %s', pid, __version__)
        __node__['start_time'] = time.time()

        if not 'Windows' == linux.os['family']:
            # Check for another running scalarzir
            if os.path.exists(PID_FILE):
                try:
                    another_pid = None
                    with open(PID_FILE, 'r') as fp:
                        another_pid = int(fp.read().strip())
                except ValueError:
                    pass
                else:
                    if pid != another_pid and os.path.exists(
                            '/proc/%s/status' % (another_pid, )):
                        self._logger.error(
                            'Cannot start scalarizr: Another process (pid: %s) already running',
                            another_pid)
                        sys.exit(1)

            # Write PID
            with open(PID_FILE, 'w') as fp:
                fp.write(str(pid))

        cnf = bus.cnf

        optparser = bus.optparser
        if optparser and optparser.values.configure:
            do_configure()
            sys.exit()

        elif optparser:
            if optparser.values.import_server:
                print "Starting import process..."
                print "Don't terminate Scalarizr until Scalr will create the new role"
                __node__['state'] = 'importing'
                # Load Command-line configuration options and auto-configure Scalarizr

                values = CmdLineIni.to_kvals(optparser.values.cnf)
                if not values.get('server_id'):
                    values['server_id'] = str(uuid.uuid4())
                self._logger.info(
                    'Configuring Scalarizr. This can take a few minutes...')
                cnf.reconfigure(values=values, silent=True, yesall=True)
            elif __node__['state'] == 'importing':
                # Reset state
                __node__['state'] = 'unknown'

        if __node__['state'] != 'importing':
            self._talk_to_updclient()
            # UpdateClient should fetch meta-data for us.
            metadata.wait(timeout=60)

        if linux.os.windows:
            try:
                wintool.wait_boot()
            except wintool.RebootExpected:
                self._logger.info('Waiting for interruption...')
                time.sleep(600)

        try:
            server_id = __node__['server_id']
        except KeyError:
            server_id = None
        if optparser and not optparser.values.import_server \
                and server_id != metadata.user_data()['serverid']:
            # This role was bundled with Cloud API call (i.e. CreateImage)
            # Now we're starting with a new server and should reset it's state
            self._logger.info(('This image was bundled with cloud API call. '
                               'Cleauping ancestor server data'))
            _cleanup_after_rebundle()
            __node__['state'] = 'bootstrapping'

        if __node__['state'] == 'unknown':
            __node__['state'] = 'bootstrapping'
        if __node__['state'] == 'rebundling':
            __node__['state'] == 'running'

        if __node__['state'] == 'bootstrapping':
            _apply_user_data(from_scalr=False)

        # Load INI files configuration
        cnf.bootstrap(force_reload=True)
        ini = cnf.rawini

        # Initialize platform module
        _init_platform()
        pl = bus.platform

        # Initialize local database
        _init_db()

        STATE['global.start_after_update'] = int(
            bool(STATE['global.version']
                 and STATE['global.version'] != __version__))
        STATE['global.version'] = __version__

        if __node__['state'] == 'importing' and not linux.os.windows:
            try:
                pkgmgr.updatedb()
            except:
                self._logger.warn(
                    'Failed to update package manager database: %s',
                    sys.exc_info()[1],
                    exc_info=sys.exc_info())

        # Check Scalr version
        if not bus.scalr_version:
            version_file = cnf.private_path('.scalr-version')
            if os.path.exists(version_file):
                bus.scalr_version = None
                with open(version_file, 'r') as fp:
                    bus.scalr_version = tuple(fp.read().strip().split('.'))
            else:
                bus.scalr_version = _detect_scalr_version()
                with open(version_file, 'w') as fp:
                    fp.write('.'.join(map(str, bus.scalr_version)))

        # Apply Command-line passed configuration options
        if optparser:
            cnf.update(CmdLineIni.to_ini_sections(optparser.values.cnf))

        # Validate configuration
        num_errors = do_validate_cnf()
        if num_errors or (optparser and optparser.values.validate_cnf):
            sys.exit(int(not num_errors or 1))

        # Initialize scalarizr services
        self._init_services()

        if STATE['global.start_after_update'] and __node__[
                'state'] == 'running':
            self._logger.info('Scalarizr was updated to %s', __version__)
            __node__['messaging'].send(
                'HostUpdate', body={'scalarizr': {
                    'version': __version__
                }})

        if __node__['state'] == 'running':
            # ReSync user-data
            _apply_user_data(from_scalr=True)
        try:
            bus.fire('init')
        except:
            self._logger.warn('Caught exception in "init": %s',
                              sys.exc_info()[1],
                              exc_info=sys.exc_info())

        # Install signal handlers
        if not linux.os.windows:
            signal.signal(signal.SIGTERM, self.onSIGTERM)

        self._start_services()

        # Fire start
        self.running = True
        try:
            bus.fire("start")
        except (BaseException, Exception) as e:
            if isinstance(e, SystemExit):
                raise
            self._logger.warn('Caught exception in "start": %s',
                              e,
                              exc_info=sys.exc_info())

        try:
            while self.running:
                if linux.os.windows_family:
                    rc = win32event.WaitForSingleObject(self.hWaitStop, 30000)
                    if rc == win32event.WAIT_OBJECT_0:
                        # Service stopped, stop main loop
                        break
                else:
                    try:
                        select.select([], [], [], 30)
                    except select.error, e:
                        if e.args[0] == 4:
                            # Interrupted syscall
                            continue
                        raise

        except KeyboardInterrupt:
            self._logger.debug('Mainloop: KeyboardInterrupt')
        finally:
            self._logger.debug('Mainloop: finally')
            if self.running and os.getpid() == _pid:
                self._shutdown()
        self._logger.debug('Mainloop: leave')
Beispiel #8
0
    def start(self):
        self._logger.debug("Initialize scalarizr...")
        _init()
        _init_environ()

        # Starting scalarizr daemon initialization
        globals()['_pid'] = pid = os.getpid()
        self._logger.info('[pid: %d] Starting scalarizr %s', pid, __version__)
        __node__['start_time'] = time.time()

        if not 'Windows' == linux.os['family']:
            # Check for another running scalarzir
            if os.path.exists(PID_FILE):
                try:
                    another_pid = None
                    with open(PID_FILE, 'r') as fp:
                        another_pid = int(fp.read().strip())
                except ValueError:
                    pass
                else:
                    if pid != another_pid and os.path.exists('/proc/%s/status' % (another_pid,)):
                        self._logger.error('Cannot start scalarizr: Another process (pid: %s) already running', another_pid)
                        sys.exit(1)

            # Write PID
            with open(PID_FILE, 'w') as fp:
                fp.write(str(pid))

        cnf = bus.cnf

        optparser = bus.optparser
        if optparser and optparser.values.configure:
            do_configure()
            sys.exit()

        elif optparser and optparser.values.import_server:
            print "Starting import process..."
            print "Don't terminate Scalarizr until Scalr will create the new role"
            __node__['state'] = 'importing'
            # Load Command-line configuration options and auto-configure Scalarizr

            values = CmdLineIni.to_kvals(optparser.values.cnf)
            if not values.get('server_id'):
                values['server_id'] = str(uuid.uuid4())
            self._logger.info('Configuring Scalarizr. This can take a few minutes...')
            cnf.reconfigure(values=values, silent=True, yesall=True)


        try:
            server_id = __node__['server_id']
        except KeyError:
            server_id = None
        if optparser and not optparser.values.import_server \
                and server_id != _meta.user_data()['serverid']:
            # This role was bundled with Cloud API call (i.e. CreateImage)
            # Now we're starting with a new server and should reset it's state
            self._logger.info(('This image was bundled with cloud API call. '
                    'Cleauping ancestor server data'))
            _cleanup_after_rebundle()
            __node__['state'] = 'bootstrapping'

        if __node__['state'] == 'unknown':
            __node__['state'] = 'bootstrapping'

        if __node__['state'] == 'bootstrapping':
            _apply_user_data(from_scalr=False)

        # Load INI files configuration
        cnf.bootstrap(force_reload=True)
        ini = cnf.rawini

        # Initialize platform module
        _init_platform()
        pl = bus.platform

        if linux.os.windows:
            self._wait_sysprep_oobe()

        # Initialize local database
        _init_db()

        STATE['global.start_after_update'] = int(bool(STATE['global.version'] and STATE['global.version'] != __version__))
        STATE['global.version'] = __version__
            
        if __node__['state'] != 'importing':
            self._talk_to_updclient()

        if __node__['state'] == 'importing':
            try:
                pkgmgr.updatedb()
            except:
                self._logger.warn('Failed to update package manager database: %s', 
                    sys.exc_info()[1], exc_info=sys.exc_info())

        # Check Scalr version
        if not bus.scalr_version:
            version_file = cnf.private_path('.scalr-version')
            if os.path.exists(version_file):
                bus.scalr_version = None
                with open(version_file, 'r') as fp:
                    bus.scalr_version = tuple(fp.read().strip().split('.'))
            else:
                bus.scalr_version = _detect_scalr_version()
                with open(version_file, 'w') as fp:
                    fp.write('.'.join(map(str, bus.scalr_version)))

        # Apply Command-line passed configuration options
        if optparser:
            cnf.update(CmdLineIni.to_ini_sections(optparser.values.cnf))

        # Validate configuration
        num_errors = do_validate_cnf()
        if num_errors or (optparser and optparser.values.validate_cnf):
            sys.exit(int(not num_errors or 1))

        # Initialize scalarizr services
        self._init_services()
        
        if STATE['global.start_after_update'] and __node__['state'] == 'running':
            self._logger.info('Scalarizr was updated to %s', __version__)
            __node__['messaging'].send(
                'HostUpdate',
                body={'scalarizr': {'version': __version__}}
            )

        if __node__['state'] == 'running':
            # ReSync user-data
            _apply_user_data(from_scalr=True)
        try:
            bus.fire('init')
        except:
            self._logger.warn('Caught exception in "init": %s', sys.exc_info()[1],
                        exc_info=sys.exc_info())

        # Install signal handlers
        if not linux.os.windows:
            signal.signal(signal.SIGTERM, self.onSIGTERM)
            signal.signal(signal.SIGHUP, self.onSIGHUP)

        self._start_services()

        # Fire start
        self._running = True
        try:
            bus.fire("start")
        except:
            self._logger.warn('Caught exception in "start": %s', sys.exc_info()[1],
                        exc_info=sys.exc_info())

        try:
            while self._running:
                if linux.os.windows_family:
                    rc = win32event.WaitForSingleObject(self.hWaitStop, 30000)
                    if rc == win32event.WAIT_OBJECT_0:
                        # Service stopped, stop main loop
                        break
                else:
                    try:
                        select.select([], [], [], 30)
                    except select.error, e:
                        if e.args[0] == 4:
                            # Interrupted syscall
                            continue
                        raise

        except KeyboardInterrupt:
            self._logger.debug('Mainloop: KeyboardInterrupt')
        finally:
            self._logger.debug('Mainloop: finally')
            if self._running and os.getpid() == _pid:
                self._shutdown()
        self._logger.debug('Mainloop: leave')