ltsp-cluster-agent-weblive/0000775000175000017500000000000011707014065016437 5ustar jonathanjonathanltsp-cluster-agent-weblive/AUTHORS0000664000175000017500000000143411700077172017512 0ustar jonathanjonathanCopyright (applies if no explicit header in the file): This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Authors: * Stéphane Graber , 2010 ltsp-cluster-agent-weblive/plugins/0000775000175000017500000000000011700077172020121 5ustar jonathanjonathanltsp-cluster-agent-weblive/plugins/weblive/0000775000175000017500000000000011700077172021556 5ustar jonathanjonathanltsp-cluster-agent-weblive/plugins/weblive/__init__.py0000664000175000017500000005452311700077172023700 0ustar jonathanjonathanfrom LTSPAgent.plugin import Plugin, auto_update from storm.locals import * import datetime, paramiko, re, sys, logging, os, codecs, inspect, socket, subprocess, uuid from hashlib import sha1 class Account(object): __storm_table__ = "account" id = Int(primary=True) server = Unicode() username = Unicode() password = Unicode() fullname = Unicode() source = Unicode() session = Unicode() locale = Unicode() token = Unicode() enabled = Bool() created = DateTime() class weblive(Plugin): # Variables unavailable_servers=[] disabled_servers=[] locales={} locales_description={} packages={} def init_plugin(self): """Prepare logging, database and locales""" # Disable paramiko logging logging.getLogger('paramiko.transport').setLevel(logging.CRITICAL) # Initialize the shared DB connection if not "postgres://" in self.get_config_path(self.config,"general","database"): self.LOGGER.critical("WebLive only supports PostgreSQL") sys.exit(1) self.db=create_database(self.get_config_path(self.config,"general","database")) # Get the store store=Store(self.db) # Create the TABLE if it doesn't exist try: store.execute("CREATE TABLE account (id SERIAL, server VARCHAR, username VARCHAR, password VARCHAR, fullname VARCHAR, source VARCHAR, session VARCHAR, locale VARCHAR, token VARCHAR, enabled BOOLEAN, created timestamp without time zone)") store.commit() except: store.rollback() # Extend the schema for TABLE with missing 'source' or 'session' field try: store.execute("ALTER TABLE account ADD COLUMN source VARCHAR") store.execute("ALTER TABLE account ADD COLUMN session VARCHAR") store.commit() except: store.rollback() # Extend the schema for TABLE with missing 'password' field try: store.execute("ALTER TABLE account ADD COLUMN password VARCHAR") store.commit() except: store.rollback() # Extend the schema for TABLE with missing 'locale' field try: store.execute("ALTER TABLE account ADD COLUMN locale VARCHAR") store.commit() except: store.rollback() # Extend the schema for TABLE with missing 'token' field try: store.execute("ALTER TABLE account ADD COLUMN token VARCHAR") store.commit() except: store.rollback() # Load locale nice names for path in ("/usr/share/ltsp-agent/plugins/weblive/locales.list","plugins/weblive/locales.list"): if os.path.exists(path): for line in codecs.open(path,'r','utf-8').readlines(): line=line.strip() self.locales_description[line.split()[0]]=" ".join(line.split()[1:]) break # Call parent function (start the threads) Plugin.init_plugin(self) def get_ssh(self,serverid): """Connect to an ssh server and return the connection""" # Connect to server ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( self.get_config_path(self.config,"servers",serverid,"server"), port=int(self.get_config_path(self.config,"servers",serverid,"port")), username="root", password=self.get_config_path(self.config,"servers",serverid,"password"), allow_agent=False, look_for_keys=False, timeout=10 ) return ssh def call_hook(self,name,params): """Call a hook in plugins/weblive/hooks/ called 'name' and pass it 'params'""" hook=None for path in ("/usr/share/ltsp-agent/plugins/weblive/hooks","plugins/weblive/hooks"): if os.path.exists("%s/%s" % (path,name)): hook="%s/%s" % (path,name) if hook == None: return False retval=subprocess.Popen([hook]+params,stdout=subprocess.PIPE,stderr=subprocess.PIPE).wait() return retval ## Exported functions def create_user(self,serverid,username,fullname,password,source,session,locale): """Create a new user on the specified server""" # Get the store store=Store(self.db) if serverid not in self.get_config_path(self.config,"servers") or serverid in self.unavailable_servers or serverid in self.disabled_servers: # Invalid server return 7 if not re.match("^[A-Za-z0-9 ]*$",fullname): # Invalid fullname, must only contain alphanumeric characters and spaces return 3 if not re.match("^[a-z]*$",username) or username in self.get_config_path(self.config,"general","username_blacklist"): # Invalid login, must only contain lowercase letters return 4 if not re.match("^[A-Za-z0-9]*$",password): # Invalid password, must contain only alphanumeric characters return 5 if store.find(Account, server=unicode(serverid), enabled=True).count() >= int(self.get_config_path(self.config,"servers",serverid,"userlimit")): # Reached user limit, return false return 1 # Accept invalid locales but mark them as None if locale not in [loc[0] for loc in self.list_locales(serverid)]: locale = None # Generate token token = uuid.uuid4() if store.find(Account, server=unicode(serverid), enabled=True, username=unicode(username)).count() == 1: user = store.find(Account, server=unicode(serverid), enabled=True, username=unicode(username))[0] if user.password == sha1(password).hexdigest(): # Account already exists, renew it user.created = datetime.datetime.now() # If session is different, append to existing session if session not in user.session.split(","): user.session += ",%s" % session # If locale is different, append to existing locale if locale not in user.locale.split(","): user.locale += ",%s" % locale store.commit() return [self.get_config_path(self.config,"servers",serverid,"server"),int(self.get_config_path(self.config,"servers",serverid,"port"))] else: # Different user already exists return 2 # Add user to the database user=Account() user.username = unicode(username) user.fullname = unicode(fullname) user.server = unicode(serverid) user.source = unicode(source) user.session = unicode(session) user.password = unicode(sha1(password).hexdigest()) user.locale = unicode(locale) user.token = unicode(token) user.enabled = True user.created = datetime.datetime.now() try: # Connect to server ssh = self.get_ssh(serverid) # Create the account stdin, stdout, stderr = ssh.exec_command("adduser --quiet --gecos '%s' %s" % (fullname,username)) stdin.write('%s\n' % password) stdin.flush() stdin.write('%s\n' % password) stdin.flush() stdout.read() # Create the container when autoinstall is enabled if self.get_config_path(self.config,"servers",serverid,"autoinstall") != 'false': ssh.exec_command("weblive-arkose adduser %s" % username) #FIXME: Should only do it when on an x2go capable server ssh.exec_command("adduser %s x2gousers" % username) # Set the locale if we know it if locale: ssh.exec_command("echo %s > /home/%s/.weblive_locale" % (locale,username))[1].channel.recv_exit_status() ssh.exec_command("chown %s.%s /home/%s/.weblive_locale" % (username,username,username)) # Set the communication token ssh.exec_command("echo %s > /home/%s/.weblive_token" % (token,username))[1].channel.recv_exit_status() ssh.exec_command("chown %s.%s /home/%s/.weblive_token" % (username,username,username)) # Set the home directory permissions ssh.exec_command("chmod 700 /home/%s" % username) # Disconnect from server ssh.close() # Save the new user store.add(user) store.commit() # Everything worked self.LOGGER.info("Created user '%s' on '%s' for '%s'." % (username,serverid,session)) return [self.get_config_path(self.config,"servers",serverid,"server"),int(self.get_config_path(self.config,"servers",serverid,"port"))] except: if serverid not in self.unavailable_servers: self.LOGGER.error("Server '%s' is unavailale." % serverid) self.unavailable_servers.append(serverid) self.call_hook("server-updown",[serverid,"DOWN"]) return False def delete_user(self,serverid,username): """Delete a user on the specified server""" if serverid not in self.get_config_path(self.config,"servers") or serverid in self.unavailable_servers or serverid in self.disabled_servers: # Invalid server return False self.delete_users({serverid:[username]}) return True def delete_users(self,users): """Delete a batch of users from various servers""" # Get the store store=Store(self.db) for serverid in users: if serverid in self.unavailable_servers or serverid in self.disabled_servers: # Server is unavailable, skip it for now continue for username in users[serverid]: user=store.find(Account, server=unicode(serverid), enabled=True, username=unicode(username)) if user.count() == 0: # User no longer exists or it was already expired, remove it from our list users[serverid].remove(username) else: # Disable the account in the database for user_object in user: user_object.enabled = False store.commit() if len(users[serverid]) == 0: continue try: # Connect to server ssh = self.get_ssh(serverid) # Disconnect the users for username in users[serverid]: ssh.exec_command("nxserver --force-terminate %s" % username)[1].channel.recv_exit_status() ssh.exec_command("pkill -9 -u %s" % username)[1].channel.recv_exit_status() ssh.exec_command("umount /home/%s/.gvfs" % username)[1].channel.recv_exit_status() ssh.exec_command("find /dev/shm /var /tmp -user \"%s\" -delete" % username)[1].channel.recv_exit_status() ssh.exec_command("deluser --force --remove-home --quiet %s" % username)[1].channel.recv_exit_status() if self.get_config_path(self.config,"servers",serverid,"autoinstall") != 'false': ssh.exec_command("weblive-arkose deluser %s" % username)[1].channel.recv_exit_status() # Kill remaining nxserver processes ssh.exec_command("while pkill -9 -P 1 -u nx; do : ; done")[1].channel.recv_exit_status() # Disconnect from server ssh.close() # Everything worked for username in users[serverid]: self.LOGGER.info("Deleted user '%s' from '%s'." % (username,serverid)) except: if serverid not in self.unavailable_servers: self.LOGGER.error("Server '%s' is unavailale." % serverid) self.unavailable_servers.append(serverid) self.call_hook("server-updown",[serverid,"DOWN"]) def list_everything(self): """List all servers including all the packages and locales""" everything={} servers=self.list_servers() for serverid in servers: server=servers[serverid] server['locales']=self.list_locales(serverid) server['packages']=self.list_packages(serverid) everything[serverid]=server return everything def list_locales(self,serverid): """List all the locales available on a server""" if serverid not in self.locales: return [] return self.locales[serverid] def list_package_blacklist(self): """List all blacklisted packages""" return self.get_config_path(self.config,"general","package_blacklist") def list_packages(self,serverid): """List all the packages available on a server""" if serverid not in self.packages: return [] packages=[] for package in self.packages[serverid]: if package[0] in self.get_config_path(self.config,"general","package_blacklist"): continue if package[2] == True and self.get_config_path(self.config,"servers",serverid,"autoinstall") == 'false': continue packages.append(package) return packages def list_servers(self): """List all the servers""" # Get the store store=Store(self.db) servers = {} for serverid in self.get_config_path(self.config,"servers"): if serverid in self.unavailable_servers: continue if serverid in self.disabled_servers: continue server_dict={} server_dict['title']=self.get_config_path(self.config,"servers",serverid,"title") server_dict['description']=self.get_config_path(self.config,"servers",serverid,"description") server_dict['users']=store.find(Account, server=unicode(serverid), enabled=True).count() server_dict['userlimit']=int(self.get_config_path(self.config,"servers",serverid,"userlimit")) server_dict['timelimit']=int(self.get_config_path(self.config,"servers",serverid,"timelimit")) server_dict['autoinstall']=(self.get_config_path(self.config,"servers",serverid,"autoinstall") != 'false') servers[serverid]=server_dict return servers def list_users(self,serverid,enabled = True): """List all the users for a specified server""" # Get the store store=Store(self.db) if enabled: users=store.find(Account, server=unicode(serverid), enabled=True) else: users=store.find(Account, server=unicode(serverid)) userlist=[] for user in users: userlist.append({ 'username':str(user.username), 'fullname':str(user.fullname), 'source':str(user.source), 'session':str(user.session), 'locale':str(user.locale), 'created':str(user.created)}) return userlist @auto_update(3600) def update_locales(self): """Update the list of locales for all servers""" for serverid in self.get_config_path(self.config,"servers"): if serverid in self.unavailable_servers: continue if serverid in self.disabled_servers: continue try: # Connect to the server ssh = self.get_ssh(serverid) # Get supported locales locales=[] for line in ssh.exec_command("locale -a")[1].readlines(): line=line.strip() if line.endswith('utf8'): if line.split('.')[0] in self.locales_description: nice=self.locales_description[line.split('.')[0]] else: nice=line locales.append((line,nice)) # Disconnect from server ssh.close() if len(locales) > 0: self.locales[serverid]=locales except: if serverid not in self.unavailable_servers: self.LOGGER.error("Server '%s' is unavailale." % serverid) self.unavailable_servers.append(serverid) self.call_hook("server-updown",[serverid,"DOWN"]) @auto_update(3600) def update_packages(self): """Update the list of packages for all servers""" for serverid in self.get_config_path(self.config,"servers"): if serverid in self.unavailable_servers: continue if serverid in self.disabled_servers: continue try: # Connect to the server ssh = self.get_ssh(serverid) # Get package list packages=[] use_dpkg=True try: # Try using the package list if it exists for line in ssh.exec_command("cat /var/cache/weblive.pkglist")[1].readlines(): line=line.strip() fields=line.split(';') packages.append([fields[0],fields[1],fields[2] == "True"]) if len(packages) > 0: use_dpkg=False except: pass if use_dpkg == True: # Use good old dpkg for line in ssh.exec_command("dpkg -l")[1].readlines(): line=line.strip() if line.startswith('ii'): packages.append(line.split()[1:3]+[False]) # Disconnect from server ssh.close() if len(packages) > 0: self.packages[serverid]=packages except: if serverid not in self.unavailable_servers: self.LOGGER.error("Server '%s' is unavailale." % serverid) self.unavailable_servers.append(serverid) self.call_hook("server-updown",[serverid,"DOWN"]) @auto_update(60) def update_users(self): """Check for expired users and removed them""" # Get the store store=Store(self.db) servers={} for serverid in self.get_config_path(self.config,"servers"): users=[] for user in store.find(Account, server=unicode(serverid), enabled=True): if (datetime.datetime.now() - user.created).seconds >= int(self.get_config_path(self.config,"servers",serverid,"timelimit")): users.append(user.username) if len(users) != 0: servers[serverid]=users if len(servers) != 0: self.delete_users(servers) return True @auto_update(120) def update_servers(self): """Try to contact all the servers""" for serverid in self.get_config_path(self.config,"servers"): if serverid in self.disabled_servers: continue try: # Connect to the server ssh = self.get_ssh(serverid) # Test the connection ssh.exec_command("echo OK") # Disconnect from server ssh.close() # It worked, so we can remove the server from the blacklist if serverid in self.unavailable_servers: self.LOGGER.error("Server '%s' is back online." % serverid) self.unavailable_servers.remove(serverid) self.call_hook("server-updown",[serverid,"UP"]) except: if serverid not in self.unavailable_servers: self.LOGGER.error("Server '%s' is unavailale." % serverid) self.unavailable_servers.append(serverid) self.call_hook("server-updown",[serverid,"DOWN"]) def set_disabled(self, serverid, state): """Disable a server""" if serverid not in self.get_config_path(self.config,"servers"): return False if state == True: if serverid in self.disabled_servers: return False if serverid in self.unavailable_servers: self.unavailable_servers.remove(serverid) self.disabled_servers.append(serverid) self.LOGGER.info("Server '%s' has been disabled." % serverid) else: if serverid not in self.disabled_servers: return False self.disabled_servers.remove(serverid) self.LOGGER.info("Server '%s' has been re-enabled." % serverid) return True ## Export the functions def json_handler(self,query,client): reply={} # Check if we at least have a function name if 'action' not in query: reply['status']="error" reply['message']=-1 return reply # Check if function is exported over JSON if query['action'] not in self.json_functions(): reply['status']="error" reply['message']=-3 return reply # Standard function without parameters, just return output reply['status']='ok' function=getattr(self,query['action']) function_params=inspect.getargspec(function).args function_params.remove('self') # Set the source query['source']="json:%s" % client # FIXME: Hack for backward compatibility for clients without # language field (expires 2012/10 at the latest) if query['action'] == 'create_user' and 'locale' not in query: query['locale']="None" attrib=[] for param in function_params: if param not in query: reply['status']="error" reply['message']=-2 return reply attrib.append(query[param]) reply['message']=function(*attrib) return reply def rpc_functions(self): return [ 'delete_user', 'set_disabled', 'list_users', ] def json_functions(self): return [ 'create_user', 'list_everything', 'list_locales', 'list_package_blacklist', 'list_packages', 'list_servers', ] ltsp-cluster-agent-weblive/plugins/weblive/locales.list0000664000175000017500000002172011700077172024077 0ustar jonathanjonathanaa_DJ Afar (Djibouti) aa_ER Afar (Eritrea) aa_ER@saaho Afar (Eritrea) aa_ET Afar (Ethiopia) af_ZA Afrikaans (Suid-Afrika) am_ET አማርኛ (ጒት፥ጵ።) an_ES Aragonese (Spain) ar_AE العربية (الإمارات العربيّة المتحدّة) ar_BH العربية (البحرين) ar_DZ العربية (الجزائر) ar_EG العربية (مصر) ar_IN العربية (الهند) ar_IQ العربية (العراق) ar_JO العربية (الأردن) ar_KW العربية (الكويت) ar_LB العربية (لبنان) ar_LY العربية (الجماهيريّة العربيّة اللّيبيّة) ar_MA العربية (المغرب) ar_OM العربية (عمان) ar_QA العربية (قطر) ar_SA العربية (السّعوديّة) ar_SD العربية (السّودان) ar_SY العربية (الجمهوريّة العربيّة السّوريّة) ar_TN العربية (تونس) ar_YE العربية (اليمن) as_IN অসমীয়া (ভাৰত) ast_ES Asturianu (España) az_AZ Azerbaijani (Azərbaycan) be_BY@latin Беларуская (Беларусь) be_BY Беларуская (Беларусь) ber_DZ Berber languages (Algeria) ber_MA Berber languages (Morocco) bg_BG Български (България) bn_BD Bengali (বাংলাদেশ) bn_IN বাংলা (ভারত) bo_CN Tibetan (China) bo_IN Tibetan (India) br_FR Brezhoneg (Frañs) br_FR@euro Brezhoneg (Frañs) bs_BA Bosnian (Bosna i Hercegovina) byn_ER Blin; Bilin (ኤርትራ) ca_AD català; valencià (Andorra) ca_ES català; valencià (Espanya) ca_ES@euro català; valencià (Espanya) ca_ES@valencia català; valencià (Espanya) ca_FR català; valencià (França) ca_IT català; valencià (Itàlia) crh_UA Qırımtatarca; Qırım Türkçesi (Ukraina) csb_PL Kashubian (Poland) cs_CZ čeština (Česká republika) cy_GB Cymraeg (Prydain Fawr) da_DK Dansk (Danmark) de_AT Deutsch (Österreich) de_AT@euro Deutsch (Österreich) de_BE Deutsch (Belgien) de_BE@euro Deutsch (Belgien) de_CH Deutsch (Schweiz) de_DE Deutsch (Deutschland) de_DE@euro Deutsch (Deutschland) de_LI Deutsch (Liechtenstein) de_LU Deutsch (Luxemburg) de_LU@euro Deutsch (Luxemburg) dv_MV Divehi; Dhivehi; Maldivian (Maldives) dz_BT Dzongkha (འབྲུག།) el_CY Ελληνικά, Σύγχρονα (Κύπρος) el_GR Ελληνικά, Σύγχρονα (Ελλάδα) en_AG English (Antigua and Barbuda) en_AU English (Australia) en_BW English (Botswana) en_CA English (Canada) en_DK English (Denmark) en_GB English (United Kingdom) en_HK English (Hong Kong) en_IE English (Ireland) en_IE@euro English (Ireland) en_IN English (India) en_NG English (Nigeria) en_NZ English (New Zealand) en_PH English (Philippines) en_SG English (Singapore) en_US English (United States) en_ZA English (South Africa) en_ZW English (Zimbabwe) eo Esperanto eo_US Esperanto (Usono) es_AR Español; Castellano (Argentina) es_BO Español; Castellano (Bolivia, Estado plurinacional de) es_CL Español; Castellano (Chile) es_CO Español; Castellano (Colombia) es_CR Español; Castellano (Costa Rica) es_DO Español; Castellano (República Dominicana) es_EC Español; Castellano (Ecuador) es_ES Español; Castellano (España) es_ES@euro Español; Castellano (España) es_GT Español; Castellano (Guatemala) es_HN Español; Castellano (Honduras) es_MX Español; Castellano (México) es_NI Español; Castellano (Nicaragua) es_PA Español; Castellano (Panamá) es_PE Español; Castellano (Perú) es_PR Español; Castellano (Puerto Rico) es_PY Español; Castellano (Paraguay) es_SV Español; Castellano (El Salvador) es_US Español; Castellano (Estados Unidos) es_UY Español; Castellano (Uruguay) es_VE Español; Castellano (Venezuela, República Bolivariana de) et_EE Eesti (Eesti) eu_ES@euro Euskara (Espainia) eu_ES Euskara (Espainia) eu_FR@euro Euskara (Frantzia) eu_FR Euskara (Frantzia) fa_IR فارسی (جمهوری اسلامی ایران) fi_FI@euro suomi (Suomi) fi_FI suomi (Suomi) fil_PH Filipino; Pilipino (Philippines) fo_FO Faroese (Føroyar) fr_BE@euro Français (Belgique) fr_BE Français (Belgique) fr_CA Français (Canada) fr_CH Français (Suisse) fr_FR@euro Français (France) fr_FR Français (France) fr_LU@euro Français (Luxembourg) fr_LU Français (Luxembourg) fur_IT Friulian (Italy) fy_DE Western Frisian (Germany) fy_NL Western Frisian (Netherlands) ga_IE@euro Gaeilge (Éire) ga_IE Gaeilge (Éire) gd_GB Gaelic; Scottish Gaelic (United Kingdom) gez_ER ግዕዝኛ (ኤርትራ) gez_ER@abegede ግዕዝኛ (ኤርትራ) gez_ET ግዕዝኛ (ኢትዮጵያ) gez_ET@abegede ግዕዝኛ (ኢትዮጵያ) gl_ES@euro Galego (España) gl_ES Galego (España) gu_IN ગુજરાતી (ભારત) gv_GB Manx (United Kingdom) ha_NG Hausa (Nigeria) he_IL עברית (ישראל) hi_IN हिंदी (भारत) hne_IN hne (India) hr_HR Hrvatski (Hrvatska) hsb_DE Upper Sorbian (Germany) ht_HT Haitian; Haitian Creole (Haiti) hu_HU magyar (Magyarország) hy_AM Armenian (Հայաստանի Հանրապետութիւն) ia Interlingua (International Auxiliary Language Association) id_ID Bahasa Indonesia (Indonesia) ig_NG Igbo (Nigeria) ik_CA Inupiaq (Canada) is_IS Íslenska (Ísland) it_CH Italiano (Svizzera) it_IT@euro Italiano (Italia) it_IT Italiano (Italia) iu_CA Inuktitut (Canada) iw_IL iw (ישראל) ja_JP 日本語 (日本) ka_GE Georgian (საქართველო) kk_KZ Kazakh (Қазақстан) kl_GL Kalaallisut; Greenlandic (Greenland) km_KH Central Khmer (កម្ពុជា) kn_IN ಕನ್ನಡ (ಭಾರತ) ko_KR 한국어 (대한민국) ks_IN@devanagari Kashmiri (India) ks_IN Kashmiri (India) ku_TR Kurdish (Tirkiye) kw_GB Cornish (United Kingdom) ky_KG Kirghiz; Kyrgyz (Kyrgyzstan) la_AU Latin (Australia) lb_LU Luxembourgish; Letzeburgesch (Luxembourg) lg_UG Ganda (Uganda) li_BE Limburgan; Limburger; Limburgish (Belgium) li_NL Limburgan; Limburger; Limburgish (Netherlands) lo_LA Lao (Lao People's Democratic Republic) lt_LT Lietuvių (Lietuva) lv_LV Latviešu (Latvija) mai_IN Maithili (India) mg_MG Malagasy (Madagascar) mi_NZ Reo Māori (Aotearoa) mk_MK Македонски (Македонија) ml_IN മലയാളം (ഇന്ത്യ) mn_MN Монгол (Монгол) mr_IN मराठी (भारत) ms_MY Bahasa Melayu (Malaysia) mt_MT Malti (Malta) my_MM Burmese (Myanmar) nan_TW@latin nan (Taiwan, Province of China) nb_NO Norsk, bokmål (Norge) nds_DE Low German; Low Saxon; German, Low; Saxon, Low (Germany) nds_NL Low German; Low Saxon; German, Low; Saxon, Low (Netherlands) ne_NP Nepali (नेपाल) nl_AW Nederlands (Aruba) nl_BE@euro Nederlands (België) nl_BE Nederlands (België) nl_NL@euro Nederlands (Nederland) nl_NL Nederlands (Nederland) nn_NO Norsk (nynorsk) (Noreg) nr_ZA Ndebele, South; South Ndebele (South Africa) nso_ZA Pedi; Sepedi; Northern Sotho (Africa Borwa) oc_FR Occitan (aprèp 1500) (França) om_ET Oromo (Ethiopia) om_KE Oromo (Kenya) or_IN ଓଡିଆ (ଭାରତ) pa_IN ਪੰਜਾਬੀ (ਭਾਰਤ) pap_AN Papiamento (AN) pa_PK ਪੰਜਾਬੀ (ਪਾਕਿਸਤਾਨ) pl_PL polski (Polska) ps_AF Pushto; Pashto (افغانستان) pt_BR Português (Brasil) pt_PT@euro Português (Portugal) pt_PT Português (Portugal) ro_RO Română (România) ru_RU русский (Российская Федерация) ru_UA русский (Украина) rw_RW Ikinyarwanda (Rwanda) sa_IN Sanskrit (India) sc_IT Sardinian (Italy) sd_IN@devanagari Sindhi (India) sd_IN Sindhi (India) sd_PK Sindhi (Pakistan) se_NO Northern Sami (Norway) shs_CA shs (Canada) sid_ET Sidamo (Ethiopia) si_LK Sinhala; Sinhalese (Sri Lanka) sk_SK slovenčina (Slovensko) sl_SI slovenščina (Slovenija) so_DJ Somali (Jabuuti) so_ET Somali (Itoobiya) so_KE Somali (Kiiniya) so_SO Somali (Soomaaliya) sq_AL Albanian (Shqipëria) sr_ME српски (Црна Гора) sr_RS@latin српски (Србија) sr_RS српски (Србија) ss_ZA Swati (South Africa) st_ZA Sotho, Southern (South Africa) sv_FI@euro Svenska (Finland) sv_FI Svenska (Finland) sv_SE Svenska (Sverige) ta_IN தமிழ் (இந்தியா) te_IN తెలుగు (భారతదేశము) tg_TJ Tajik (Tajikistan) th_TH ไทย (ไทย) ti_ER ትግርኛ (ኤርትራ) ti_ET ትግርኛ (ኢትዮጵያ) tig_ER ትግረ (ኤርትራ) tk_TM Turkmen (Türkmenistan) tlh_GB Klingon; tlhIngan-Hol (United Kingdom) tl_PH Tagalog (Pilipinas) tn_ZA Tswana (South Africa) tr_CY Türkçe (Kıbrıs) tr_TR Türkçe (Türkiye) ts_ZA Tsonga (South Africa) tt_RU@iqtelif Tatarça (Urıs Patşahlıq) tt_RU Tatarça (Urıs Patşahlıq) ug_CN Uighur; Uyghur (China) uk_UA українська (Україна) ur_PK Urdu (Pakistan) uz_UZ@cyrillic Uzbek (Uzbekistan) uz_UZ Uzbek (Uzbekistan) ve_ZA Venda (South Africa) vi_VN Tiếng Việt (Việt Nam) wa_BE@euro Walon (Beldjike) wa_BE Walon (Beldjike) wal_ET Wolaitta; Wolaytta (ኢትዮጵያ) wo_SN Wolof (Senegaal) xh_ZA isiXhosa (Mzantsi Afrika) yi_US Yiddish (United States) yo_NG Yoruba (Nigeria) zh_CN 汉语 (中国) zh_HK 漢語 (香港) zh_SG Chinese (Singapore) zh_TW 漢語 (中華民國) zu_ZA Isi-Zulu (I-Mzantsi Afrika) ltsp-cluster-agent-weblive/plugins/jsonlink/0000775000175000017500000000000011700077172021750 5ustar jonathanjonathanltsp-cluster-agent-weblive/plugins/jsonlink/__init__.py0000664000175000017500000000610411700077172024062 0ustar jonathanjonathanfrom LTSPAgent.plugin import Plugin from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading, json, urlparse, socket class jsonHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): return def do_POST(self): request=self.path.split('/') if len(request) != 3 or request[2] != "json": self.send_response(404) self.end_headers() return plugin=request[1] if not plugin in self.server.plugins: self.send_response(404) self.end_headers() return if not hasattr(self.server.plugins[plugin],'json_handler'): self.send_response(404) self.end_headers() return try: length=self.headers.getheader('content-length','0') content=self.rfile.read(int(length)) post=urlparse.parse_qs(content) if "query" in post: query=json.loads(post['query'][0]) else: self.send_response(404) self.end_headers() return except: self.send_response(404) self.end_headers() return if not "action" in query: self.send_response(500) self.end_headers() return client=self.headers.getheader('X-Forwarded-For',self.client_address[0]) self.send_response(200) self.end_headers() self.server.LOGGER.debug("Remote call on %s with params %s", self.server.plugins[plugin], str(query)) try: self.wfile.write(json.dumps(getattr(self.server.plugins[plugin],'json_handler')(query,client))) self.wfile.write('\n') except: self.server.LOGGER.info("Lost connection with %s" % client) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def __init__(self, server_address, SecureXMLRPCRequestHandler): # Deal with IPv6 addrinfo = socket.getaddrinfo(server_address[0], server_address[1]) for entry in addrinfo: if entry[0] == socket.AF_INET6: self.address_family = socket.AF_INET6 HTTPServer.__init__(self, server_address, SecureXMLRPCRequestHandler) class jsonserverThread(threading.Thread): def run(self): server = ThreadedHTTPServer(self.connection, jsonHandler) server.plugins=self.plugins server.LOGGER=self.LOGGER self.LOGGER.info("Serving HTTP/JSON on %s port %s", self.connection[0],self.connection[1]) server.serve_forever() class jsonlink(Plugin): """Export another plugin's functions over JSON""" def init_plugin(self): jsonserver=jsonserverThread() jsonserver.plugins=self.plugins jsonserver.connection=(self.get_config_path(self.config,'general','bindaddr'), int(self.get_config_path(self.config,'general','bindport'))) jsonserver.LOGGER=self.LOGGER jsonserver.start() Plugin.init_plugin(self) ltsp-cluster-agent-weblive/convert.py0000664000175000017500000000136411700077172020476 0ustar jonathanjonathan#!/usr/bin/python from storm.locals import * import sys if len(sys.argv) != 3: print "Usage: %s " % sys.argv[0] sys.exit(1) sys.path.append('plugins') sys.path.append('/usr/share/ltsp-agent/plugins') from weblive import Account srcdb = create_database(sys.argv[1]) dstdb = create_database(sys.argv[2]) srcstore=Store(srcdb) dststore=Store(dstdb) for account in srcstore.find(Account): user=Account() user.username=account.username user.fullname=account.fullname user.server=account.server user.source=account.source user.session=account.session user.password=account.password user.enabled=account.enabled user.created=account.created dststore.add(user) dststore.commit() ltsp-cluster-agent-weblive/COPYING0000664000175000017500000004307611700077172017505 0ustar jonathanjonathan GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ltsp-cluster-agent-weblive/release.conf0000664000175000017500000000025311700077172020727 0ustar jonathanjonathanNAME="ltsp-cluster-agent-weblive" VERSION="1.8" MODULE_NAME="weblive" AUTHOR="Stephane Graber" AUTHOR_EMAIL="stgraber@ubuntu.com" DESCRIPTION="ltsp-cluster-agent-weblive" ltsp-cluster-agent-weblive/client/0000775000175000017500000000000011700077172017716 5ustar jonathanjonathanltsp-cluster-agent-weblive/client/weblive-x2go-cli.py0000664000175000017500000000346111700077172023353 0ustar jonathanjonathan#!/usr/bin/python import getpass, os, x2go, sys, socket, time from weblive import WebLive # Get a weblive object weblive=WebLive("https://weblive.stgraber.org/weblive/json") # List all the available servers servers=weblive.list_servers() if len(servers) == 0: print "Sorry, there's no server available at this time." sys.exit(0) # Show a readable list of servers for server in servers: attributes=servers[server] print "== %s ==" % server for attribute in attributes: print " * %s: %s" % (attribute,attributes[attribute]) print "" # If first parameter is "auto", then pick up the first server and connect if len(sys.argv) > 1 and sys.argv[1] == "auto": serverid=servers.keys()[0] username="%s%s" % (os.environ['USER'],socket.gethostname()) fullname="WebLive User" password=socket.gethostname() # Yes, the hostname is the password ;) session='desktop'; else: serverid=raw_input("Server (ex. %s): " % servers.keys()[0]) username=raw_input("Username: ") fullname=raw_input("Fullname: ") password=getpass.getpass("Password: ") session=raw_input("Session (ex. 'desktop' or valid executable): ") # Create the user locale=os.environ.get("LANG","None").replace("UTF-8","utf8") connection=weblive.create_user(serverid,username,fullname,password,session,locale) # Start X2GO cli = x2go.X2goClient(start_pulseaudio=True) uuid = cli.register_session( server=str(connection[0]), port=int(connection[1]), username=username, add_to_known_hosts=True, cmd="WEBLIVE", geometry="1024x600" ) x2go.defaults.X2GO_DESKTOPSESSIONS['WEBLIVE']="/usr/local/bin/weblive-session %s" % session cli.connect_session(uuid, password=password) cli.clean_sessions(uuid) cli.start_session(uuid) while cli.session_ok(uuid): time.sleep(0.5) cli.terminate_session(uuid) ltsp-cluster-agent-weblive/client/weblive-test-json.py0000664000175000017500000000337411700077172023660 0ustar jonathanjonathan#!/usr/bin/python import time from weblive import WebLive weblive=WebLive("https://weblive.stgraber.org/weblive/json") # List servers print "= list_servers =" start=time.time() servers=weblive.list_servers() for server in servers: attributes=servers[server] print "== %s ==" % server for attribute in attributes: if attribute in ('locales','packages'): print " * %s: %s" % (attribute,len(attributes[attribute])) else: print " * %s: %s" % (attribute,attributes[attribute]) print "" print "%s\n" % (time.time()-start) # List everything print "= list_everything =" start=time.time() servers=weblive.list_everything() for server in servers: attributes=servers[server] print "== %s ==" % server for attribute in attributes: if attribute in ('locales','packages'): print " * %s: %s" % (attribute,len(attributes[attribute])) else: print " * %s: %s" % (attribute,attributes[attribute]) print "" print "%s\n" % (time.time()-start) # List locales if server: print "= list_locales =" start=time.time() locales=weblive.list_locales(server) print "== %s ==" % server for locale in locales: print "* %s" % locale print "" print "%s\n" % (time.time()-start) # List packages if server: print "= list_packages =" start=time.time() packages=weblive.list_packages(server) print "== %s ==" % server for package in packages: print "* %s" % package print "" print "%s\n" % (time.time()-start) # Create user if server: print "= create_user =" start=time.time() user=weblive.create_user(server,'testjson','testjson','testjson','desktop','en_US.UTF-8') print "== %s ==" % server print user print "" ltsp-cluster-agent-weblive/client/weblive-get-blacklist.py0000664000175000017500000000034311700077172024450 0ustar jonathanjonathan#!/usr/bin/python # WARNING: Used to build the WebLive appservs, DO NOT MODIFY OR REMOVE ! from weblive import WebLive wl=WebLive('https://weblive.stgraber.org/weblive/json',False) print " ".join(wl.list_package_blacklist()) ltsp-cluster-agent-weblive/client/weblive-dialog.py0000664000175000017500000000547511700077172023175 0ustar jonathanjonathan#!/usr/bin/python # -*- coding: utf-8 -*- import gettext, sys, gtk, socket, os from gettext import gettext as _ gettext.textdomain("weblive-dialog") if len(sys.argv) < 2 or sys.argv[1] not in ('login','logout'): print _("Usage: %s [options]" % sys.argv[0]) sys.exit(1) if sys.argv[1] == "login": from weblive import WebLive locales=WebLive("https://weblive.stgraber.org/weblive/json").list_locales(socket.gethostname()) if os.path.exists(os.path.expanduser("~/.weblive_locale")): default=open(os.path.expanduser("~/.weblive_locale"),"r").read().strip() else: default="en_US.utf8" dialog = gtk.Dialog(parent=None, flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) dialog.set_title("Welcome to WebLive!") # Main label label=gtk.Label() label.set_markup("""Welcome to WebLive! This server (%s) is provided free of charge by: Stéphane Graber and is located in: Nürnberg, Germany All internet trafic from WebLive is logged and may be restricted or even blocked completely at any time and for any reason. WebLive is meant to let users easily try Ubuntu, its derivatives and the software they include. Any other use isn't allowed. As servers need maintenance, users may get disconnected at any time. If that happens, just reconnect and you'll be connected to another server. Please report any bug you encounter at: https://launchpad.net/weblive/+filebug If you disagree with any of the above, click Cancel now. Enjoy!""" % socket.gethostname()) label.set_padding(12,12) # Drop down model = gtk.ListStore(str,str) cell = gtk.CellRendererText() index=False for locale in locales: if locale[0] == default: index = model.append(locale) else: model.append(locale) combobox = gtk.ComboBox() combobox.pack_start(cell) combobox.add_attribute(cell, 'text', 1) combobox.set_model(model) if index: combobox.set_active_iter(index) # Language selector language_label = gtk.Label() language_label.set_markup("Session language:") language_label.set_padding(5,0) language_label.set_alignment(0,0.5) language = gtk.HBox() language.pack_start(language_label) language.pack_start(combobox) dialog.vbox.pack_start(label) dialog.vbox.pack_start(language) dialog.set_resizable(False) dialog.set_position(gtk.WIN_POS_CENTER_ALWAYS) dialog.set_modal(True) dialog.show_all() retval=dialog.run() if retval == gtk.RESPONSE_ACCEPT: open(os.path.expanduser("~/.weblive_locale"),"w+").write("%s\n" % model[combobox.get_active()][0]) sys.exit(0) else: sys.exit(1) elif sys.argv[1] == "logout": pass ltsp-cluster-agent-weblive/client/weblive-install-packages.py0000664000175000017500000000452311700077172025151 0ustar jonathanjonathan#!/usr/bin/env python import gettext from gettext import gettext as _ gettext.textdomain("weblive-install-packages") import thread, socket, sys, apt, glob, os, string from weblive import WebLive wl=WebLive('https://weblive.stgraber.org/weblive/json',False) import pygtk pygtk.require("2.0") import gtk import apt.progress.gtk2 progress = apt.progress.gtk2.GtkAptProgress() cache = apt.Cache(progress.open) # Make sure we are allowed to install packages and package isn't blacklisted wanted_packages=sys.argv[1:] packages=[] serverid=socket.gethostname() servers=wl.list_everything() if serverid in servers and servers[serverid]['autoinstall']: for package in wanted_packages: if not package in cache: for desktop in glob.glob("/usr/share/app-install/desktop/*.desktop"): xdg_package=None xdg_exec=None for line in map(string.strip, open(desktop)): if line.startswith("Exec="): xdg_exec=line.split("=")[1].split()[0] if line.startswith("X-AppInstall-Package="): xdg_package=line.split("=")[1] if xdg_package and xdg_exec and xdg_exec in package: wanted_packages.remove(package) wanted_packages.append(xdg_package) break for package in servers[serverid]['packages']: if package[0] in wanted_packages: try: packages.append(package[0]) cache[package[0]].mark_install() except: print _("Failed to install package: %s") % package[0] # Create GTK window win = gtk.Window() win.connect("destroy", lambda a: sys.exit(1)) win.set_title("Installing packages") win.set_resizable(False) win.set_position(gtk.WIN_POS_CENTER) win.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_MENU) label = gtk.Label() label.set_markup(_("We are currently installing the package you requested: %s\nPlease wait, this can take some time.") % ",".join(packages)) vbox = gtk.VBox(False, 12) vbox.set_border_width(12) vbox.pack_start(label) vbox.pack_start(progress) win.add(vbox) win.show_all() # Apply the changes progress.hide_terminal() progress.show() cache.commit(progress.fetch, progress.install) # Cleanup for path in glob.glob("/var/cache/apt/archives/*.deb"): os.unlink(path) ltsp-cluster-agent-weblive/client/weblive-qtnx-cli.py0000664000175000017500000000645711700077172023476 0ustar jonathanjonathan#!/usr/bin/python import getpass, os, subprocess, sys, socket from weblive import WebLive # NXML template nxml_template=""" """ # Check for QTNX if not os.path.exists("/usr/bin/qtnx"): print "Sorry, you need qtnx (/usr/bin/qtnx) installed." sys.exit(1) # Get a weblive object weblive=WebLive("https://weblive.stgraber.org/weblive/json") # List all the available servers servers=weblive.list_servers() if len(servers) == 0: print "Sorry, there's no server available at this time." sys.exit(0) # Show a readable list of servers for server in servers: attributes=servers[server] print "== %s ==" % server for attribute in attributes: print " * %s: %s" % (attribute,attributes[attribute]) print "" # If first parameter is "auto", then pick up the first server and connect if len(sys.argv) > 1 and sys.argv[1] == "auto": serverid=servers.keys()[0] username="%s%s" % (os.environ['USER'],socket.gethostname()) fullname="WebLive User" password=socket.gethostname() # Yes, the hostname is the password ;) session='desktop'; else: serverid=raw_input("Server (ex. %s): " % servers.keys()[0]) username=raw_input("Username: ") fullname=raw_input("Fullname: ") password=getpass.getpass("Password: ") session=raw_input("Session (ex. 'desktop' or valid executable): ") # Create the user locale=os.environ.get("LANG","None").replace("UTF-8","utf8") connection=weblive.create_user(serverid,username,fullname,password,session,locale) # Start QTNX if not os.path.expanduser('~/.qtnx'): os.mkdir(os.path.expanduser('~/.qtnx')) filename=os.path.expanduser('~/.qtnx/%s-%s-%s.nxml') % (connection[0],connection[1],session) nxml=open(filename,"w+") config=nxml_template config=config.replace("WL_NAME","%s-%s-%s" % (connection[0],connection[1],session)) config=config.replace("WL_SERVER",connection[0]) config=config.replace("WL_PORT",str(connection[1])) config=config.replace("WL_COMMAND","weblive-session %s" % session) nxml.write(config) nxml.close() qtnx=subprocess.Popen(['/usr/bin/qtnx','%s-%s-%s' % (connection[0],connection[1],session),username,password]) qtnx.wait() os.remove(filename) ltsp-cluster-agent-weblive/client/weblive-packagelist.py0000664000175000017500000000510011700077172024206 0ustar jonathanjonathan#!/usr/bin/python # WARNING: Used to build the WebLive appservs, DO NOT MODIFY OR REMOVE ! import apt, glob, string from weblive import WebLive wl=WebLive('https://weblive.stgraber.org/weblive/json',False) blacklist_category=['P2P','System','3DGraphics','AudioVideoEditing','AudioVideo','Audio','Video'] blacklist_package=['playonlinux','cheese','synapse','docky','mumble','eclipse-platform','netbeans','qt4-designer','webhttrack','compizconfig-settings-manager','fretsonfire','avogadro'] blacklist_keyword=['3D','GL','virtualbox','compiz'] blacklist_package=sorted(set(blacklist_package+wl.list_package_blacklist())) cache = apt.Cache() packages=[] for desktop in glob.glob("/usr/share/app-install/desktop/*.desktop"): current_pkg = None nodisplay = False terminal = False categories = [] skip = False for line in map(string.strip, open(desktop)): if line.startswith("X-AppInstall-Package"): (tag, sep, value) = line.partition("=") current_pkg = value if line.startswith("NoDisplay"): (tag, sep, value) = line.partition("=") if value in ('true','True'): nodisplay=True if line.startswith("Terminal"): (tag, sep, value) = line.partition("=") if value in ('true','True'): terminal=True if line.startswith("Categories"): (tag, sep, value) = line.partition("=") categories=value.split(';') for keyword in blacklist_keyword: if keyword in line: skip = True if '' in categories: categories.remove('') if current_pkg: if current_pkg in blacklist_package: skip = True if terminal == True or nodisplay == True: skip = True for category in categories: if category in blacklist_category: skip = True if current_pkg not in cache: skip = True for package in packages: if current_pkg == package[0]: skip = True break if skip == False: # Check if package is installable and isn't too big cache.clear() try: cache[current_pkg].mark_install() except: continue if cache.required_space > (150 * 1024 * 1024): continue packages.append([current_pkg,cache[current_pkg].candidateVersion,not cache[current_pkg].is_installed]) for package in sorted(packages): print "%s;%s;%s" % (package[0],package[1],package[2]) ltsp-cluster-agent-weblive/client/admin-xmlrpc.py0000664000175000017500000000266511700077172022674 0ustar jonathanjonathanimport sys, xmlrpclib rpc_srv = xmlrpclib.ServerProxy("https://admin:admin@localhost:8080") if len(sys.argv) == 1: print "%s list_users " % (sys.argv[0]) print "%s delete_user [all]" % (sys.argv[0]) print "%s set_disabled " % (sys.argv[0]) sys.exit(1) if len(sys.argv) > 1 and sys.argv[1] not in ['list_users','delete_user','set_disabled']: print "Invalid command: %s" % sys.argv[1] sys.exit(1) if sys.argv[1] == "list_users": if len(sys.argv) != 3 and len(sys.argv) != 4: print "Invalid parameters" sys.exit(1) else: if len(sys.argv) == 3: for user in rpc_srv.weblive.list_users(sys.argv[2]): print "%s - %s - %s - %s (%s)" % (user['username'],user['fullname'],user['source'],user['session'],user['created']) else: for user in rpc_srv.weblive.list_users(sys.argv[2],False): print "%s - %s - %s - %s (%s)" % (user['username'],user['fullname'],user['source'],user['session'],user['created']) if sys.argv[1] == "delete_user": if len(sys.argv) != 4: print "Invalid parameters" sys.exit(1) else: print rpc_srv.weblive.delete_user(sys.argv[2],sys.argv[3]) if sys.argv[1] == "set_disabled": if len(sys.argv) != 4: print "Invalid parameters" sys.exit(1) else: print rpc_srv.weblive.set_disabled(sys.argv[2],sys.argv[3] == "true") ltsp-cluster-agent-weblive/client/weblive.py0000664000175000017500000001722611700077172021735 0ustar jonathanjonathan#!/usr/bin/python import urllib, urllib2, json class WebLiveJsonError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class WebLiveError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class WebLiveLocale(object): def __init__(self, locale, description): self.locale = locale self.description = description class WebLivePackage(object): def __init__(self, pkgname, version, autoinstall): self.pkgname = pkgname self.version = version self.autoinstall = autoinstall class WebLiveServer(object): def __init__(self, name, title, description, timelimit, userlimit, users, autoinstall): self.name = name self.title = title self.description = description self.timelimit = timelimit self.userlimit = userlimit self.current_users = users self.autoinstall = autoinstall def __repr__(self): return "[WebLiveServer: %s (%s - %s), timelimit=%s, userlimit=%s, current_users=%s, autoinstall=%s" % ( self.name, self.title, self.description, self.timelimit, self.userlimit, self.current_users, self.autoinstall) class WebLiveEverythingServer(WebLiveServer): def __init__(self, name, title, description, timelimit, userlimit, users, autoinstall, locales, packages): self.locales = [WebLiveLocale(x[0], x[1]) for x in locales] self.packages = [WebLivePackage(x[0], x[1], x[2]) for x in packages] WebLiveServer.__init__(self, name, title, description, timelimit, userlimit, users, autoinstall) def __repr__(self): return "[WebLiveServer: %s (%s - %s), timelimit=%s, userlimit=%s, current_users=%s, autoinstall=%s, nr_locales=%s, nr_pkgs=%s" % ( self.name, self.title, self.description, self.timelimit, self.userlimit, self.current_users, self.autoinstall, len(self.locales), len(self.packages)) class WebLive: def __init__(self,url,as_object=False): self.url=url self.as_object=as_object def do_query(self,query): page=urllib2.Request(self.url,urllib.urlencode({'query':json.dumps(query)})) try: response=urllib2.urlopen(page) except urllib2.HTTPError, e: raise WebLiveJsonError("HTTP return code: %s" % e.code) except urllib2.URLError, e: raise WebLiveJsonError("Failed to reach server: %s" % e.reason) try: reply=json.loads(response.read()) except ValueError: raise WebLiveJsonError("Returned json object is invalid.") if reply['status'] != 'ok': if reply['message'] == -1: raise WebliveJsonError("Missing 'action' field in query.") elif reply['message'] == -2: raise WebLiveJsonError("Missing parameter") elif reply['message'] == -3: raise WebliveJsonError("Function '%s' isn't exported over JSON." % query['action']) else: raise WebLiveJsonError("Unknown error code: %s" % reply['message']) if 'message' not in reply: raise WebLiveJsonError("Invalid json reply") return reply def create_user(self,serverid,username,fullname,password,session,locale): query={} query['action']='create_user' query['serverid']=serverid query['username']=username query['fullname']=fullname query['password']=password query['session']=session query['locale']=locale reply=self.do_query(query) if type(reply['message']) != type([]): if reply['message'] == 1: raise WebLiveError("Reached user limit, return false.") elif reply['message'] == 2: raise WebLiveError("Different user with same username already exists.") elif reply['message'] == 3: raise WebLiveError("Invalid fullname, must only contain alphanumeric characters and spaces.") elif reply['message'] == 4: raise WebLiveError("Invalid login, must only contain lowercase letters.") elif reply['message'] == 5: raise WebLiveError("Invalid password, must contain only alphanumeric characters.") elif reply['message'] == 7: raise WebLiveError("Invalid server: %s" % serverid) else: raise WebLiveError("Unknown error code: %s" % reply['message']) return reply['message'] def list_everything(self): query={} query['action']='list_everything' reply=self.do_query(query) if type(reply['message']) != type({}): raise WebLiveError("Invalid value, expected '%s' and got '%s'." % (type({}),type(reply['message']))) if not self.as_object: return reply['message'] else: servers=[] for server in reply['message']: attr=reply['message'][server] servers.append(WebLiveEverythingServer( server, attr['title'], attr['description'], attr['timelimit'], attr['userlimit'], attr['users'], attr['autoinstall'], attr['locales'], attr['packages'])) return servers def list_locales(self,serverid): query={} query['action']='list_locales' query['serverid']=serverid reply=self.do_query(query) if type(reply['message']) != type([]): raise WebLiveError("Invalid value, expected '%s' and got '%s'." % (type({}),type(reply['message']))) if not self.as_object: return reply['message'] else: return [WebLiveLocale(x[0], x[1]) for x in reply['message']] def list_package_blacklist(self): query={} query['action']='list_package_blacklist' reply=self.do_query(query) if type(reply['message']) != type([]): raise WebLiveError("Invalid value, expected '%s' and got '%s'." % (type({}),type(reply['message']))) if not self.as_object: return reply['message'] else: return [WebLivePackage(x, None, None) for x in reply['message']] def list_packages(self,serverid): query={} query['action']='list_packages' query['serverid']=serverid reply=self.do_query(query) if type(reply['message']) != type([]): raise WebLiveError("Invalid value, expected '%s' and got '%s'." % (type({}),type(reply['message']))) if not self.as_object: return reply['message'] else: return [WebLivePackage(x[0], x[1], x[2]) for x in reply['message']] def list_servers(self): query={} query['action']='list_servers' reply=self.do_query(query) if type(reply['message']) != type({}): raise WebLiveError("Invalid value, expected '%s' and got '%s'." % (type({}),type(reply['message']))) if not self.as_object: return reply['message'] else: servers=[] for server in reply['message']: attr=reply['message'][server] servers.append(WebLiveServer( server, attr['title'], attr['description'], attr['timelimit'], attr['userlimit'], attr['users'], attr['autoinstall'])) return servers ltsp-cluster-agent-weblive/client/weblive-html-package-list.py0000664000175000017500000000156611700077172025241 0ustar jonathanjonathan#!/usr/bin/python from weblive import WebLive wl=WebLive('https://weblive.stgraber.org/weblive/json',True) all_packages={} for server in wl.list_everything(): for package in server.packages: if not package.pkgname in all_packages: all_packages[package.pkgname]={} if not package.version in all_packages[package.pkgname]: all_packages[package.pkgname][package.version]=[] all_packages[package.pkgname][package.version].append(server.name) print """ Packages available on WebLive
    """ for package in sorted(all_packages): print "
  • %s
      " % package for version in all_packages[package]: print "
    • %s (%s)
    • " % (version, ", ".join(all_packages[package][version])) print "
  • " print """
""" ltsp-cluster-agent-weblive/client/README0000664000175000017500000000103411700077172020574 0ustar jonathanjonathan== weblive.py == Contains a python class used by weblive-bench-json.py and weblive-qtnx-cli.py. It handles all of the available JSON calls and their return values. == admin-xmlrpc.py == Uses the XML-RPC interface to access restricted functions that aren't available through the JSON interface. == weblive-test-json.py == Test all the various calls in the JSON api using weblive.py It also returns how long each call took. == weblive-qtnx-cli.py == Minimal command line client for weblive. Requires Ubuntu Natty's qtnx for auto-connect. ltsp-cluster-agent-weblive/config/0000775000175000017500000000000011700077172017705 5ustar jonathanjonathanltsp-cluster-agent-weblive/config/agent.d/0000775000175000017500000000000011700077172021225 5ustar jonathanjonathanltsp-cluster-agent-weblive/config/agent.d/weblive.conf0000664000175000017500000000140611700077172023532 0ustar jonathanjonathan[general] database=postgres://weblive:weblive@localhost/weblive username_blacklist='root','daemon','bin','sys','sync','games','man','lp','mail','news','uucp','proxy','www-data','backup','list','irc','gnats','libuuid','syslog','messagebus','avahi-autoipd','avahi','couchdb','usbmux','pulse','speech-dispatcher','haldaemon','kernoops','saned','hplip','gdm','sabayon-admin','sshd','nx' package_blacklist='openarena' [servers] [[server1]] title = "Server 1" description = "Description 1" server = server1.example.com port = 1234 password = password timelimit = 7200 userlimit = 150 autoinstall = false [[server2]] title = "Server 2" description = "Description 2" server = server2.example.com port = 1234 password = password timelimit = 7200 userlimit = 150 autoinstall = true ltsp-cluster-agent-weblive/config/agent.d/jsonlink.conf0000664000175000017500000000004411700077172023721 0ustar jonathanjonathan[general] bindaddr=:: bindport=8081