Example #1
0
    def delete(self, service):
        """ Delete a new service object """
        from agent.lib.agent_thread.service_delete import ServiceDelete
        try:
            LOG.info('Got a delete request for service ' + service)

            path = ServiceController.servicePath(service)

            if (not os.path.exists(path) and not os.path.isdir(path)):
                return errorResult(request, response, Errors.SERVICE_NOT_FOUND, "No service(%s) found" % service, controller = self)

            # see if active manifest exist for the service
            if manifestutil.hasActiveManifest(service):
                return errorResult(request, response, Errors.MANIFEST_DELETING_ACTIVE_MANIFEST,
                                   'Active manifest exists for service %s, deactivate the manifest first before deleting service' % (service),
                                   controller = self)

            # start the delete thread
            appGlobal = config['pylons.app_globals']
            deleteThread = ServiceDelete(appGlobal.threadMgr, service, path)
            self.injectJobCtx(deleteThread)
            deleteThread.start()
            deleteThread.threadMgrEvent.wait()

            return statusResult(request, response, deleteThread, controller = self)
        except Exception as excep:
            return errorResult(request, response, error = Errors.UNKNOWN_ERROR,
                               errorMsg = 'Unknown error when deleting service(%s) %s - %s' %
                               (service, str(excep), traceback.format_exc(2)),
                               controller = self)
    def doRun(self):
        """ Main body of the thread """
        self._updateProgress(1)

        errorMsg = ""
        errorCode = None
        failed = False
        
        try:
            
            if manifestutil.hasActiveManifest(self._service):

                manifest = manifestutil.getActiveManifest(self._service)

                self.__shutdownSuppressError(self._service, manifest)

                self.__deactivateSuppressError(self._service, manifest)
                
            self.__deleteService(self._service)   

        except SystemExit as exc:
            failed = True
            if (len(exc.args) == 2):
                # ok we got {err code, err msg}
                errorCode = exc.args[0]
                errorMsg = exc.args[1]
        
        except AgentException as exc:
            failed = True
            errorMsg = 'Cleanup Service - Agent Exception - %s' % exc.getMsg()
            errorCode = exc.getCode()
        
        except Exception as exc:
            failed = True
            errorMsg = 'Cleanup Service - Unknown error - (%s/%s) - %s - %s' \
                        % (self._service, self._manifest, str(exc), traceback.format_exc(5))
            errorCode = Errors.UNKNOWN_ERROR
            
        finally:

            if failed: 
                self._LOG.warning(errorMsg)
                self._updateStatus(httpStatus = 500, error = errorCode, errorMsg = errorMsg)
            else:
                self._updateProgress(100)
Example #3
0
    def delete(self, service):
        """ Delete a new service object """
        from agent.lib.agent_thread.service_delete import ServiceDelete
        try:
            LOG.info('Got a delete request for service ' + service)

            path = ServiceController.servicePath(service)

            if (not os.path.exists(path) and not os.path.isdir(path)):
                return errorResult(request,
                                   response,
                                   Errors.SERVICE_NOT_FOUND,
                                   "No service(%s) found" % service,
                                   controller=self)

            # see if active manifest exist for the service
            if manifestutil.hasActiveManifest(service):
                return errorResult(
                    request,
                    response,
                    Errors.MANIFEST_DELETING_ACTIVE_MANIFEST,
                    'Active manifest exists for service %s, deactivate the manifest first before deleting service'
                    % (service),
                    controller=self)

            # start the delete thread
            appGlobal = config['pylons.app_globals']
            deleteThread = ServiceDelete(appGlobal.threadMgr, service, path)
            self.injectJobCtx(deleteThread)
            deleteThread.start()
            deleteThread.threadMgrEvent.wait()

            return statusResult(request,
                                response,
                                deleteThread,
                                controller=self)
        except Exception as excep:
            return errorResult(
                request,
                response,
                error=Errors.UNKNOWN_ERROR,
                errorMsg='Unknown error when deleting service(%s) %s - %s' %
                (service, str(excep), traceback.format_exc(2)),
                controller=self)
Example #4
0
    def startServicesOnAgentStartup():
        """
        when agent is restarted,
        0. check for agent selfupdate
        1. start all service with active manifest, this requires service startup script be idempotent
        2. load dynamic controllers and routes if any
        """
        # check for agent update
        from agent.lib.agenthealth import checkAgentVersion
        checkAgentVersion(True)

        # startup services
        from agent.lib.agent_thread.startstop_service import StartStopService
        appGlobal = config['pylons.app_globals']
        appdelay = int(config['app_restart_init_delay']) if 'app_restart_init_delay' in config else 0
        if appdelay > 0:
            time.sleep(appdelay)
            
        # check if this is agent restart or system restart
        if os.path.exists("/proc/uptime"):
            uptime, _ = [float(f) for f in open("/proc/uptime").read().split()]
        else:
            uptime = 500

        systemRestartTimeThreshold = pylons.config['system_restart_time_threshold']
        if (int(systemRestartTimeThreshold) <= uptime):
            LOG.info('agent recover from agent restart, not goint to restart managed apps')
            return
            
        LOG.info('agent recover from system reboot, restart all managed apps')
        for service in manifestutil.getServices():
            if service != 'agent':
                if manifestutil.hasActiveManifest(service):
                    try:
                        LOG.info('startup for service(%s)', service)

                        startupThread = StartStopService(appGlobal.threadMgr, service, StartStopService.ACTION_STARTUP)
                        startupThread.start()
                        startupThread.threadMgrEvent.wait()

                    except Exception as excep:
                        LOG.error('Unknown error starting service(%s) - %s - %s' % (service, str(excep), traceback.format_exc(2)))
 def testHasActiveManifest(self):
     createManifest(self, manifest = 'testmanifest', service = 'testservice')
     assert False == manifestutil.hasActiveManifest('testservice')
     activateManifest(self, manifest = 'testmanifest', service = 'testservice')
     assert True == manifestutil.hasActiveManifest('testservice')
Example #6
0
    def startServicesOnAgentStartup():
        """
        when agent is restarted,
        0. check for agent selfupdate
        1. start all service with active manifest, this requires service startup script be idempotent
        2. load dynamic controllers and routes if any
        """
        # check for agent update
        from agent.lib.agenthealth import checkAgentVersion
        checkAgentVersion(True)

        # startup services
        from agent.lib.agent_thread.startstop_service import StartStopService
        appGlobal = config['pylons.app_globals']
        appdelay = int(
            config['appinitdelay']) if 'appinitdelay' in config else 0
        if appdelay > 0:
            time.sleep(appdelay)

        # check if this is agent restart or system restart
        if os.name != 'nt' and os.path.exists("/proc/uptime"):
            uptime, _ = [float(f) for f in open("/proc/uptime").read().split()]
        else:
            uptime = 500
        systemRestartTimeThreshold = pylons.config[
            'system_restart_time_threshold']
        actionType = StartStopService.ACTION_RESTART
        if (int(systemRestartTimeThreshold) > uptime):
            actionType = StartStopService.ACTION_REBOOT

        for service in manifestutil.getServices():

            appDataDir = manifestutil.appDataPath(service)
            if not os.path.exists(appDataDir):
                os.makedirs(appDataDir)
                import pwd
                uname = pylons.config['app_user_account']
                uid = pwd.getpwnam(uname).pw_uid
                gid = pwd.getpwnam(uname).pw_gid
                utils.rchown(appDataDir, uid, gid)

            dataDir = manifestutil.dataPath(service)
            if not os.path.exists(dataDir):
                os.makedirs(dataDir)

            if service != 'agent':
                try:
                    manifestutil.updateServiceMetaFile(
                        service, {
                            'servicePath': manifestutil.servicePath(service),
                            'serviceName': service
                        })
                except Exception as excep:
                    LOG.error(
                        'Unknown error updating local metadata service(%s) - %s - %s'
                        % (service, str(excep), traceback.format_exc(2)))

                if manifestutil.hasActiveManifest(service):
                    try:
                        LOG.info('startup for service(%s)', service)

                        startupThread = StartStopService(
                            appGlobal.threadMgr, service, actionType)
                        startupThread.start()
                        startupThread.threadMgrEvent.wait()

                    except Exception as excep:
                        LOG.error(
                            'Unknown error starting service(%s) - %s - %s' %
                            (service, str(excep), traceback.format_exc(2)))

                    try:
                        LOG.info('load controllers and routes for service(%s)',
                                 service)
                        manifestutil.processControllerInPackage(service)

                    except Exception as excep:
                        LOG.error(
                            'Unknown error loading controllers for service(%s) - %s - %s'
                            % (service, str(excep), traceback.format_exc(2)))
Example #7
0
 def testHasActiveManifest(self):
     createManifest(self, manifest='testmanifest', service='testservice')
     assert False == manifestutil.hasActiveManifest('testservice')
     activateManifest(self, manifest='testmanifest', service='testservice')
     assert True == manifestutil.hasActiveManifest('testservice')
Example #8
0
    def startServicesOnAgentStartup():
        """
        when agent is restarted,
        0. check for agent selfupdate
        1. start all service with active manifest, this requires service startup script be idempotent
        2. load dynamic controllers and routes if any
        """
        # check for agent update
        from agent.lib.agenthealth import checkAgentVersion

        checkAgentVersion(True)

        # startup services
        from agent.lib.agent_thread.startstop_service import StartStopService

        appGlobal = config["pylons.app_globals"]
        appdelay = int(config["appinitdelay"]) if "appinitdelay" in config else 0
        if appdelay > 0:
            time.sleep(appdelay)

        # check if this is agent restart or system restart
        if os.name != "nt" and os.path.exists("/proc/uptime"):
            uptime, _ = [float(f) for f in open("/proc/uptime").read().split()]
        else:
            uptime = 500
        systemRestartTimeThreshold = pylons.config["system_restart_time_threshold"]
        actionType = StartStopService.ACTION_RESTART
        if int(systemRestartTimeThreshold) > uptime:
            actionType = StartStopService.ACTION_REBOOT

        for service in manifestutil.getServices():

            appDataDir = manifestutil.appDataPath(service)
            if not os.path.exists(appDataDir):
                os.makedirs(appDataDir)
                import pwd

                uname = pylons.config["app_user_account"]
                uid = pwd.getpwnam(uname).pw_uid
                gid = pwd.getpwnam(uname).pw_gid
                utils.rchown(appDataDir, uid, gid)

            dataDir = manifestutil.dataPath(service)
            if not os.path.exists(dataDir):
                os.makedirs(dataDir)

            if service != "agent":
                try:
                    manifestutil.updateServiceMetaFile(
                        service, {"servicePath": manifestutil.servicePath(service), "serviceName": service}
                    )
                except Exception as excep:
                    LOG.error(
                        "Unknown error updating local metadata service(%s) - %s - %s"
                        % (service, str(excep), traceback.format_exc(2))
                    )

                if manifestutil.hasActiveManifest(service):
                    try:
                        LOG.info("startup for service(%s)", service)

                        startupThread = StartStopService(appGlobal.threadMgr, service, actionType)
                        startupThread.start()
                        startupThread.threadMgrEvent.wait()

                    except Exception as excep:
                        LOG.error(
                            "Unknown error starting service(%s) - %s - %s"
                            % (service, str(excep), traceback.format_exc(2))
                        )

                    try:
                        LOG.info("load controllers and routes for service(%s)", service)
                        manifestutil.processControllerInPackage(service)

                    except Exception as excep:
                        LOG.error(
                            "Unknown error loading controllers for service(%s) - %s - %s"
                            % (service, str(excep), traceback.format_exc(2))
                        )