def logoff_user(self, user): Logger.info("SessionManagement::logoff_user %s" % (user.name)) if user.infos.has_key("tsid"): sessid = user.infos["tsid"] try: status = RolePlatform.TS.getState(sessid) except Exception, err: Logger.error("RDP server dialog failed ... ") Logger.debug("SessionManagement::logoff_user: %s" % (str(err))) return if status in [ RolePlatform.TS.STATUS_LOGGED, RolePlatform.TS.STATUS_DISCONNECTED ]: Logger.info("must log off ts session %s user %s" % (sessid, user.name)) try: RolePlatform.TS.logoff(sessid) except Exception, err: Logger.error("RDP server dialog failed ... ") Logger.debug("SessionManagement::logoff_user: %s" % (str(err))) return del (user.infos["tsid"])
def init(self): Logger.info("FileServer init") if not Config.init_role(): return False if not self.FSBackend.start(): Logger.error("FileServer: failed to initialize FSBackend") self.FSBackend.stop() return False if not self.cleanup_samba(): Logger.error("FileServer: unable to cleanup samba") return False if not self.purgeGroup(): Logger.error("FileServer: unable to cleanup users") return False if not self.cleanup_repository(): Logger.error("FileServer: unable to cleanup users") return False self.shares = self.get_existing_shares() return True
def destroy_user(self, user): Logger.info("SessionManagement::destroy_user %s"%(user.name)) if user.infos.has_key("tsid"): self.logoff_user(user) user.destroy()
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) #win32evtlogutil.ReportEvent(self.log_type, 2, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["Message d'arret"]) if not SlaveServer.init(self): Logger.error("Unable to initialize SlaveServer") SlaveServer.stop(self) return self.ReportServiceStatus(win32service.SERVICE_RUNNING) inited = False rc = win32event.WAIT_TIMEOUT while rc == win32event.WAIT_TIMEOUT: if not inited: ret = SlaveServer.push_production(self) if ret: inited = True Logger.info("SlaveServer started") else: Logger.warn("Session Manager not connected. Sleeping for a while ...") if inited: SlaveServer.loop_procedure(self) rc = win32event.WaitForSingleObject(self.hWaitStop, 30 * 1000) if not self.stopped: SlaveServer.stop(self) Logger.info("SlaveServer stopped")
def init(self): Logger.info("FileServer init") if not Config.init_role(): return False if not self.FSBackend.start(): Logger.error("FileServer: failed to initialize FSBackend") self.FSBackend.stop() return False if not self.cleanup_samba(): Logger.error("FileServer: unable to cleanup samba") return False if not self.purgeGroup(): Logger.error("FileServer: unable to cleanup users") return False if not self.cleanup_repository(): Logger.error("FileServer: unable to cleanup users") return False self.shares = self.get_existing_shares() return True
def destroy_user(self, user): Logger.info("SessionManagement::destroy_user %s" % (user.name)) if user.infos.has_key("tsid"): self.logoff_user(user) user.destroy()
def init(self): Logger.info("FileServer init") if not Config.init_role(): Logger.info( "FileServer never initialized, creating repository on '%s'" % (Config.spool)) os.makedirs(Config.spool) if not self.cleanup_samba(): Logger.error("FileServer: unable to cleanup samba") return False if not self.purgeGroup(): Logger.error("FileServer: unable to cleanup users") return False if not self.cleanup_repository(): Logger.error("FileServer: unable to cleanup users") return False self.wm = DirectoryWatcher() self.shares = self.get_existing_shares() return True
def _create(self, data): sess_id = data.pop('id') Logger.info('[WebApps] creating session id={0} for user {1}'.format(sess_id, data.get('login'))) data.setdefault('cookies', {}) session = Session(sess_id, data, self.debug) self.sessions[sess_id] = session return session
def disconnect_session(self, session): Logger.info("SessionManagement::disconnect %s"%(session.id)) if session.user.created or not session.domain.manage_user(): # Doesn't have to disconnect the session if the user was never created try: sessid = TS.getSessionID(session.user.name) except Exception: Logger.exception("RDP server dialog failed ... ") return False try: status = TS.getState(sessid) except Exception: Logger.exception("RDP server dialog failed ... ") return if status in [TS.STATUS_LOGGED]: Logger.info("must disconnect ts session %s user %s"%(sessid, session.user.name)) try: TS.disconnect(sessid) except Exception: Logger.exception("RDP server dialog failed ... ") return session.switch_status(Session.SESSION_STATUS_INACTIVE)
def process(self, request): path = request["path"] if request["method"] == "GET": Logger.debug("[WebApps] do_GET " + path) if path == "/sync": Logger.info("[WebApps] Starting config synchronization") setup_apps(reset=True) return self.req_answerText('OK') elif path.startswith("/session/status/"): buf = path[len("/session/status/"):] return self.req_session_status(buf) elif path.startswith("/session/destroy/"): buf = path[len("/session/destroy/"):] return self.req_session_destroy(buf) elif request["method"] == "POST": Logger.debug("[WebApps] do_POST " + path) if path == "/session/create": return self.req_session_create(request) Logger.info("WebApps role Dialog::process(%s)" % (str(request))) return None
def init(self): Logger.info("Gateway init") if version[0] != 2 or version[1] < 6 or (version[1] == 7 and version[2] in [1, 2]): Logger.error("Gateway:: incompatibility with current Python machine '%d.%d.%d'" % version[:3]) return False fpem = os.path.join(Config.general.conf_dir, "gateway.pem") if os.path.exists(fpem): self.ssl_ctx = SSL.Context(SSL.SSLv23_METHOD) self.ssl_ctx.use_privatekey_file(fpem) self.ssl_ctx.use_certificate_file(fpem) self.ssl_ctx.load_verify_locations(fpem) else: Logger.error("Gateway role need a certificate (%s)" % fpem) return False addr = (Config.address, Config.port) try: GatewayTCPHandler.role = self self.server = TCPServer(addr, GatewayTCPHandler, bind_and_activate=False) self.server.allow_reuse_address = Config.general.server_allow_reuse_address self.server.server_bind() self.server.server_activate() except socket.error, e: Logger.error("Gateway:: socket init: %s" % e) return False
def create_session(self, session): Logger.info("SessionManagement::create %s for user %s"%(session.id, session.user.name)) if System.userExist(session.user.name): Logger.error("unable to create session: user %s already exists"%(session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR self.aps_instance.session_switch_status(session, Session.SESSION_STATUS_ERROR) return self.destroy_session(session) rr = session.user.create() if rr is False: Logger.error("unable to create session for user %s"%(session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR self.aps_instance.session_switch_status(session, Session.SESSION_STATUS_ERROR) return self.destroy_session(session) session.user.created = True try: rr = session.install_client() except Exception,err: Logger.debug("Unable to initialize session %s: %s"%(session.id, str(err))) rr = False
def disconnect_session(self, session): Logger.info("SessionManagement::disconnect %s" % (session.id)) if session.user.created or not session.domain.manage_user(): # Doesn't have to disconnect the session if the user was never created try: sessid = TS.getSessionID(session.user.name) except Exception: Logger.exception("RDP server dialog failed ... ") return False try: status = TS.getState(sessid) except Exception: Logger.exception("RDP server dialog failed ... ") return if status in [TS.STATUS_LOGGED]: Logger.info("must disconnect ts session %s user %s" % (sessid, session.user.name)) try: TS.disconnect(sessid) except Exception: Logger.exception("RDP server dialog failed ... ") return session.switch_status(Session.SESSION_STATUS_INACTIVE)
def session_switch_status(self, session, status): if status == Session.SESSION_STATUS_DESTROYED: self.send_session_dump(session) session.switch_status(status) Logger.info("Session %s switch status %s"%(session.id, session.status)) self.send_session_status(session)
def init_role(cls): try: infos = pwd.getpwnam(cls.user) except KeyError, err: Logger.info("FileServer Config failed: no such user '%s'" % (cls.user)) return False
def process(self, request): path = request["path"] if request["method"] == "GET": Logger.debug("[WebApps] do_GET " + path) if path == "/sync": Logger.info("[WebApps] Starting config synchronization") setup_apps(reset=True) return self.req_answerText("OK") elif path.startswith("/session/status/"): buf = path[len("/session/status/") :] return self.req_session_status(buf) elif path.startswith("/session/destroy/"): buf = path[len("/session/destroy/") :] return self.req_session_destroy(buf) elif request["method"] == "POST": Logger.debug("[WebApps] do_POST " + path) if path == "/session/create": return self.req_session_create(request) Logger.info("WebApps role Dialog::process(%s)" % (str(request))) return None
def init(self): Logger.info("Gateway init") if version[0] != 2 or version[1] < 6 or (version[1] == 7 and version[2] in [1, 2]): Logger.error("Gateway:: incompatibility with current Python machine '%d.%d.%d'" % version[:3]) return False fpem = os.path.join(Config.general.conf_dir, "gateway.pem") if os.path.exists(fpem): self.ssl_ctx = SSL.Context(SSL.SSLv23_METHOD) self.ssl_ctx.use_privatekey_file(fpem) self.ssl_ctx.use_certificate_file(fpem) self.ssl_ctx.load_verify_locations(fpem) if Config.disable_sslv2: self.ssl_ctx.set_options(SSL.OP_NO_SSLv2) else: Logger.error("Gateway role need a certificate (%s)" % fpem) return False addr = (Config.address, Config.port) try: GatewayTCPHandler.role = self self.server = GatewayTCPServer(addr, GatewayTCPHandler, bind_and_activate=False) self.server.allow_reuse_address = Config.general.server_allow_reuse_address self.server.server_bind() self.server.server_activate() except socket.error: Logger.exception("Gateway:: socket init") return False Logger.info('Gateway:: running on (%s, %d)' % addr) return True
def order_stop(self): Logger.info("%s role::stop"%(self.getName())) if self.status == Role.STATUS_INIT: self.status = Role.STATUS_STOP return self.status = Role.STATUS_STOPPING
def req_session_status(self, session_id): session = SessionsRepository.get(session_id, check_active=False) if session is None: Logger.info("[WebApps] session id={0} not found".format(session_id)) session = Session(session_id, {}) session.status = Session.SESSION_STATUS_UNKNOWN return self.req_answer(self.session2xmlstatus(session))
def disconnect(self): Logger.info("%s is disconnecting..." % self.uuid) if self.libvirt_connection: self.libvirt_connection.close() self.libvirt_connection = None
def disconnect(self): Logger.info("%s is disconnecting..." % self.uuid) if self.libvirt_connection: self.libvirt_connection.close() self.libvirt_connection = None
def session_switch_status(self, session, status): if status == Session.SESSION_STATUS_DESTROYED: self.send_session_dump(session) session.switch_status(status) Logger.info("Session %s switch status %s" % (session.id, session.status)) self.send_session_status(session)
def init(cls, infos): Logger.info("Guest role Config::init") if not infos.has_key("hypervisor"): return False cls.hypervisor = infos["hypervisor"] return True
def pre_process(self, context): Logger.debug("StaticRequestFilter pre_process") session = context.session if not session.get('ulteo_autologin', self.options.get('autologin', False)): Logger.debug("StaticRequestFilter pre_process autologin = false") return target = self.config['target'] login_url = '{0}://{1}/{2}'.format(target.scheme, target.netloc, self.options['path']) needed_fields = set(self.options['form']) Logger.debug( "StaticRequestFilter pre_process target:%s url:%s fields:%r" % (target, login_url, needed_fields)) br = mechanize.Browser() #br.set_debug_http(True) #br.set_debug_responses(True) #br.set_debug_redirects(True) br.set_handle_robots(False) br.addheaders = parse_request_headers_list(context.communicator) for header in br.addheaders: if header[0].lower() in ('accept-encoding', ): br.addheaders.remove(header) br.open(login_url) to_select = None for i, form in enumerate(br.forms()): available_fields = set([control.name for control in form.controls]) if needed_fields.issubset(available_fields): to_select = i if to_select is None: Logger.info('Necessary fields not found in any form!') session['ulteo_autologin'] = False return br.select_form(nr=to_select) for name, value in self.options['form'].items(): br.form[name] = self.get_value(value, session) response = br.submit() if response.code != 200: Logger.error("Couldn't log in:") Logger.error(response.get_data()) session['ulteo_autologin'] = False return False session['auth_cookies'] = {} for value in response.info().getheaders('set-cookie'): m = COOKIE_RE.search(value) if m: session['auth_cookies'][m.group(1)] = value session['ulteo_autologin'] = response.get_data() Logger.debug("StaticRequestFilter pre_process set autologin")
def connect_domain(self): if self.domain: Logger.info("Already connected to domain. Ignoring") return try: self.domain = self.virt_co.lookupByName(self.name) except: Logger.error("Can't connect to domain with name %s " % self.name)
def req_session_status(self, session_id): session = SessionsRepository.get(session_id, check_active=False) if session is None: Logger.info( "[WebApps] session id={0} not found".format(session_id)) session = Session(session_id, {}) session.status = Session.SESSION_STATUS_UNKNOWN return self.req_answer(self.session2xmlstatus(session))
def connect_domain(self): if self.domain: Logger.info("Already connected to domain. Ignoring") return try: self.domain = self.virt_co.lookupByName(self.name) except: Logger.error("Can't connect to domain with name %s " %self.name)
def create_session(self, session): Logger.info("SessionManagement::create %s for user %s" % (session.id, session.user.name)) if session.domain.manage_user(): if System.userExist(session.user.name): Logger.error( "unable to create session: user %s already exists" % (session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) session.user.infos["groups"] = [ self.aps_instance.ts_group_name, self.aps_instance.ovd_group_name ] if session.mode == "desktop": session.user.infos["shell"] = "OvdDesktop" else: session.user.infos["shell"] = "OvdRemoteApps" rr = session.user.create() if rr is False: Logger.error("unable to create session for user %s" % (session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) session.user.created = True try: rr = session.install_client() except Exception: Logger.exception("Unable to initialize session %s" % session.id) rr = False if rr is False: Logger.error("unable to initialize session %s" % (session.id)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) else: # will be customize by a lock system when the users will connect in RDP if not session.domain.onSessionCreate(): session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return False session.post_install() session.switch_status(Session.SESSION_STATUS_INITED)
def main(): parser = OptionParser() parser.add_option("-V", "--verbose", action="store_true", dest="verbose", default=False, help="Print more informations") parser.add_option("-a", "--address", action="store_true", dest="address", default="127.0.0.1", help="TCP Bind ip address") parser.add_option("-p", "--port", action="store_true", dest="port", default=3000, help="TCP port to bind") parser.add_option("-c", "--config", action="store", type="string", dest="config", default=None, help="Json configuration file") parser.add_option("-v", "--value", action="append", nargs=2, type="string", dest="values", default=[], help="Configuration value") options, args = parser.parse_args() if not options.config: parser.error("You must supply a configuration file") loglevel = Logger.ERROR|Logger.WARN if options.verbose: loglevel |= Logger.INFO|Logger.DEBUG|Logger.DEBUG_2|Logger.DEBUG_3 Logger.initialize("WEBAPPS", loglevel, stdout=True) Logger.info("Start webapps") repo = ApplicationsRepository.initialize() SessionsRepository.debug = True sess = SessionsRepository.initialize() sess.start() repo.start() my_sess = {'id': 1, 'published_applications': (1, ), 'login':'******'} for k, v in options.values: my_sess[k] = v SessionsRepository.create(my_sess) SessionsRepository._instance.sessions[1].switch_status(Session.SESSION_STATUS_ACTIVE) server = WebAppsServer(options.address, int(options.port)) try: config = json.load(open(options.config, "r")) for k, v in options.values: config['Configuration'][k]['value'] = v app_id = 1 app_name = "app" appl = setup_app({"app":config}, app_id, app_name, "domain") if not appl: parser.error("Invalid parameters") appl.rule = re.compile('') ApplicationsRepository.register(appl) try: print "Connect to http://%s:%s/" % (options.address, options.port) asyncore.loop() except (InterruptedException, KeyboardInterrupt): Logger.info("interruption") finally: server.close() repo.stop() sess.stop()
def dump(self): if self.gpos == {}: Logger.info("There is no GPO") return for action in self.gpos: print "%s rules" % (action) for (program, parameters) in self.gpos[action]: Logger.info("\t - %s %s" % (program, parameters))
def dump(self): if self.gpos == {}: Logger.info("There is no GPO") return for action in self.gpos: print "%s rules"%(action) for (program, parameters) in self.gpos[action]: Logger.info("\t - %s %s"%(program, parameters))
def run(self): if self.domain and (self.domain.info()[0] == 1 or self.domain.info()[0] == 2 or self.domain.info()[0] == 3): return "ERROR" self.domain.create() Logger.info("Virtual Machine created") return "OK"
def destroy(self): if self.domain and (self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.destroy() Logger.info("Domain destroyed") return "OK"
def shutdown(self): if self.domain and (self.domain.info()[0] == 4 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.shutdown() Logger.info("Domain shutdown") return "OK"
def suspend(self): if self.domain and (self.domain.info()[0] == 3 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.suspend() Logger.info("Virtual machine paused") return "OK"
def resume(self): if self.domain and (self.domain.info()[0] == 4 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.resume() Logger.info("Virtual machine unpaused") return "OK"
def __init__(self): Logger.info('[WebApps] SessionsRepository init') self.sessions = {} self.looping = False self.queue_in = multiprocessing.Queue() self.queue_out = multiprocessing.Queue() self.lock = threading.Lock() self.thread = threading.Thread(name="webapps_session", target=self.run)
def resume(self): if self.domain and (self.domain.info()[0] == 4 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.resume() Logger.info("Virtual machine unpaused") return "OK"
def suspend(self): if self.domain and (self.domain.info()[0] == 3 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.suspend() Logger.info("Virtual machine paused") return "OK"
def shutdown(self): if self.domain and (self.domain.info()[0] == 4 or self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.shutdown() Logger.info("Domain shutdown") return "OK"
def pre_process(self, context): Logger.debug("StaticRequestFilter pre_process") session = context.session if not session.get('ulteo_autologin', self.options.get('autologin', False)): Logger.debug("StaticRequestFilter pre_process autologin = false") return target = self.config['target'] login_url = '{0}://{1}/{2}'.format(target.scheme, target.netloc, self.options['path']) needed_fields = set(self.options['form']) Logger.debug("StaticRequestFilter pre_process target:%s url:%s fields:%r"%(target,login_url,needed_fields)) br = mechanize.Browser() #br.set_debug_http(True) #br.set_debug_responses(True) #br.set_debug_redirects(True) br.set_handle_robots(False) br.addheaders = parse_request_headers_list(context.communicator) for header in br.addheaders: if header[0].lower() in ('accept-encoding', ): br.addheaders.remove(header) br.open(login_url) to_select = None for i, form in enumerate(br.forms()): available_fields = set([control.name for control in form.controls]) if needed_fields.issubset(available_fields): to_select = i if to_select is None: Logger.info('Necessary fields not found in any form!') session['ulteo_autologin'] = False return br.select_form(nr=to_select) for name, value in self.options['form'].items(): br.form[name] = self.get_value(value, session) response = br.submit() if response.code != 200: Logger.error("Couldn't log in:") Logger.error(response.get_data()) session['ulteo_autologin'] = False return False session['auth_cookies'] = {} for value in response.info().getheaders('set-cookie'): m = COOKIE_RE.search(value) if m: session['auth_cookies'][m.group(1)] = value session['ulteo_autologin'] = response.get_data() Logger.debug("StaticRequestFilter pre_process set autologin")
def destroy(self): if self.domain and (self.domain.info()[0] == 5 or self.domain.info()[0] == 6): return "ERROR" self.domain.destroy() Logger.info("Domain destroyed") return "OK"
def run(self): if self.domain and (self.domain.info()[0] == 1 or self.domain.info()[0] == 2 or self.domain.info()[0] == 3): return "ERROR" self.domain.create() Logger.info("Virtual Machine created") return "OK"
def init(self): Logger.debug("ApplicationServer init") try: TS.getList() except Exception: Logger.exception("RDP server dialog failed ... exiting") return if not System.groupExist(self.manager.ts_group_name): Logger.error("The group '%s' doesn't exist" % (self.manager.ts_group_name)) return False if not System.groupExist(self.manager.ovd_group_name): if not System.groupCreate(self.manager.ovd_group_name): return False if not self.manager.purgeGroup(): Logger.error("Unable to purge group") return False if Config.clean_dump_archive: self.purgeArchives() if Config.thread_count is None: cpuInfos = System.getCPUInfos() vcpu = cpuInfos[0] ram_total = System.getRAMTotal() ram = int(round(ram_total / 1024.0 / 1024.0)) nb_thread = int(round(1 + (ram + vcpu * 2) / 3)) else: nb_thread = Config.thread_count Logger._instance.setQueue(self.logging_queue, True) for _ in xrange(nb_thread): self.threads.append( SessionManagement(self.manager, self.sessions_spooler, self.sessions_spooler2, self.sessions_sync, self.logging_queue)) if self.canManageApplications(): self.apt = Apt() self.apt.init() self.threads.append(self.apt) Logger.info( "ApplicationServer:: retrieve all applications installed (can take some time)" ) self.updateApplications() return True
class Config: general = None user = "******" group = None uid = None gid = None spool = None backendSpool = None dav_user = "******" dav_uid = None dav_passwd_file = "/var/spool/ulteo/ovd/fs.dav.passwd" dav_group_file = "/var/spool/ulteo/ovd/fs.dav.group" FSBackendConf = "/etc/ulteo/rufs/FSBackend.conf" @classmethod def init(cls, infos): if infos.has_key("user"): cls.user = infos["user"] if infos.has_key("FSBackendConf"): cls.FSBackendConf = infos["FSBackendConf"] return True @classmethod def init_role(cls): try: infos = pwd.getpwnam(cls.user) except KeyError, err: Logger.info("FileServer Config failed: no such user '%s'" % (cls.user)) return False cls.uid = infos[2] cls.gid = infos[3] cls.spool = infos.pw_dir cls.backendSpool = cls.spool + ".real" if not os.path.isdir(cls.spool): Logger.info("FileServer Config failed: no such directory '%s'" % (cls.spool)) return False try: infos = grp.getgrgid(cls.gid) except KeyError, err: Logger.info("FileServer Config failed: no such group '%d'" % (cls.gid)) return False
def SvcDoRun(self): config_file = os.path.join(System.get_default_config_dir(), "slaveserver.conf") if not Config.read(ConfigReader.process(None)): return if not Config.is_valid(): return Win32Logger.initialize("OVD", Config.log_level, Config.log_file) try: ServerCheckup.check() except: Logger.exception("Server checkup") return slave = SlaveServer(Communication) if not slave.load_roles(): return if not slave.init(): Logger.error("Unable to initialize SlaveServer") slave.stop() return inited = False rc = win32event.WAIT_TIMEOUT while rc == win32event.WAIT_TIMEOUT: if not inited: ret = slave.push_production() if ret: inited = True Logger.info("SlaveServer started") else: Logger.warn( "Session Manager not connected. Sleeping for a while ..." ) if inited: slave.loop_procedure() rc = win32event.WaitForSingleObject(self.hWaitStop, 30 * 1000) if not slave.stopped: slave.stop() Logger.info("SlaveServer stopped")
def __init__(self, main_instance): AbstractRole.__init__(self, main_instance) Logger.info("Guest role::__init__") self.loop = True self.url = None self.host = Conf.hypervisor self.port = "1112" self.session = None self.session_spooler = multiprocessing.Queue() self.session_sync = multiprocessing.Queue() self.manager = Manager(self.main_instance.smRequestManager) self.session_manager = SessionManagement(self.manager, self.session_spooler, self.session_sync) self.current_session_status = None
def init(self): Logger.debug("SlaveServer init") if not self.communication.initialize(): return False self.communication.thread.start() for (role, dialog) in self.role_dialogs: try: if not role.init(): raise Exception() except InterruptedException: return False except Exception: Logger.exception("SlaveServer: unable to initialize role '%s'" % role.getName()) return False role.thread.start() # Check each thread has started correctly (communication + roles) t0 = time.time() while self.communication.getStatus() is not self.communication.STATUS_RUNNING: t1 = time.time() if ( (t1 - t0 > 20) or (not self.communication.thread.isAlive()) or self.communication.getStatus() is self.communication.STATUS_ERROR ): Logger.warn("SlaveServer::init communication thread error") return False Logger.info("Waiting for communication status running") time.sleep(1) for (role, dialog) in self.role_dialogs: while role.getStatus() is not role.STATUS_RUNNING: t1 = time.time() if (t1 - t0 > 20) or (not role.thread.isAlive()) or role.getStatus() is role.STATUS_ERROR: Logger.warn("SlaveServer::init role %s error" % (role.getName())) return False Logger.info("Waiting for role %s status running" % (role.getName())) time.sleep(1) self.updateMonitoring() return True
def create_session(self, session): Logger.info("SessionManagement::create %s for user %s"%(session.id, session.user.name)) if session.domain.manage_user(): if System.userExist(session.user.name): Logger.error("unable to create session: user %s already exists"%(session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) session.user.infos["groups"] = [self.aps_instance.ts_group_name, self.aps_instance.ovd_group_name] if session.mode == "desktop": session.user.infos["shell"] = "OvdDesktop" else: session.user.infos["shell"] = "OvdRemoteApps" rr = session.user.create() if rr is False: Logger.error("unable to create session for user %s"%(session.user.name)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) session.user.created = True try: rr = session.install_client() except Exception: Logger.exception("Unable to initialize session %s"%session.id) rr = False if rr is False: Logger.error("unable to initialize session %s"%(session.id)) session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return self.destroy_session(session) else: # will be customize by a lock system when the users will connect in RDP if not session.domain.onSessionCreate(): session.end_status = Session.SESSION_END_STATUS_ERROR session.switch_status(Session.SESSION_STATUS_ERROR) return False session.post_install() session.switch_status(Session.SESSION_STATUS_INITED)
def init(self): Logger.debug("ApplicationServer init") try: TS.getList() except Exception: Logger.exception("RDP server dialog failed ... exiting") return if not System.groupExist(self.manager.ts_group_name): Logger.error("The group '%s' doesn't exist"%(self.manager.ts_group_name)) return False if not System.groupExist(self.manager.ovd_group_name): if not System.groupCreate(self.manager.ovd_group_name): return False if not self.manager.purgeGroup(): Logger.error("Unable to purge group") return False if Config.clean_dump_archive: self.purgeArchives() if Config.thread_count is None: cpuInfos = System.getCPUInfos() vcpu = cpuInfos[0] ram_total = System.getRAMTotal() ram = int(round(ram_total / 1024.0 / 1024.0)) nb_thread = int(round(1 + (ram + vcpu * 2)/3)) else: nb_thread = Config.thread_count Logger._instance.setQueue(self.logging_queue, True) for _ in xrange(nb_thread): self.threads.append(SessionManagement(self.manager, self.sessions_spooler, self.sessions_spooler2, self.sessions_sync, self.logging_queue)) if self.canManageApplications(): self.apt = Apt() self.apt.init() self.threads.append(self.apt) Logger.info("ApplicationServer:: retrieve all applications installed (can take some time)") self.updateApplications() return True
def destroy_session(self, session): Logger.info("SessionManagement::destroy %s"%(session.id)) if session.user.created or not session.domain.manage_user(): # Doesn't have to destroy the session if the user was never created try: sessid = RolePlatform.TS.getSessionID(session.user.name) except Exception,err: Logger.error("RDP server dialog failed ... ") Logger.debug("SessionManagement::destroy_session: %s"%(str(err))) return if sessid is not None: session.user.infos["tsid"] = sessid self.logoff_user(session.user)
def SvcDoRun(self): config_file = os.path.join(System.get_default_config_dir(), "slaveserver.conf") if not Config.read(ConfigReader.process(None)): return if not Config.is_valid(): return Win32Logger.initialize("OVD", Config.log_level, Config.log_file) try: ServerCheckup.check() except: Logger.exception("Server checkup") return slave = SlaveServer(Communication) if not slave.load_roles(): return if not slave.init(): Logger.error("Unable to initialize SlaveServer") slave.stop() return inited = False rc = win32event.WAIT_TIMEOUT while rc == win32event.WAIT_TIMEOUT: if not inited: ret = slave.push_production() if ret: inited = True Logger.info("SlaveServer started") else: Logger.warn("Session Manager not connected. Sleeping for a while ...") if inited: slave.loop_procedure() rc = win32event.WaitForSingleObject(self.hWaitStop, 30 * 1000) if not slave.stopped: slave.stop() Logger.info("SlaveServer stopped")
def stop(self, Signum=None, Frame=None): Logger.info("SlaveServer stop") self.stopped = True t0 = time.time() stop_timeout = Config.stop_timeout for (role, dialog) in self.role_dialogs: role.order_stop() self.smRequestManager.switch_status(self.smRequestManager.STATUS_PENDING) for (role, dialog) in self.role_dialogs: while not role.stopped(): t1 = time.time() if (stop_timeout > 0) and (t1 - t0 > stop_timeout): Logger.warn("SlaveServer::stop role %s error" % (role.getName())) role.force_stop() break Logger.debug("Waiting for role %s status stop" % (role.getName())) time.sleep(2) for (role, dialog) in self.role_dialogs: if role.thread.isAlive(): Logger.debug("Waiting %s will stop" % role.getName()) role.thread.join(10) if role.thread.isAlive(): Logger.error("Role %s was stopped by using low force" % role.getName()) role.thread._Thread__stop() role.thread.join(5) if role.thread.isAlive(): Logger.error("Role %s was stopped by using force" % role.getName()) role.thread._Thread__delete() role.finalize() Logger.info("Role %s stopped" % role.getName()) self.communication.stop() if self.communication.thread.isAlive(): self.communication.thread.join() self.smRequestManager.switch_status(self.smRequestManager.STATUS_DOWN)