Изменения для нового API

master3.3
parent dc7fdb4c0d
commit 8659570d2a

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -24,30 +24,26 @@ import traceback
from datavars import DataVarsDesktop, DataVars, __version__,__app__
from calculate.lib.cl_template import Template, ProgressTemplate,TemplatesError
from calculate.lib.utils.files import runOsCommand, isMount,process, \
getRunCommands
from calculate.lib.utils.common import getpathenv,appendProgramToEnvFile, \
removeProgramToEnvFile
from calculate.core.server.func import safetyWrapper
from calculate.lib.cl_template import (Template, ProgressTemplate,TemplatesError)
from calculate.lib.utils.files import (runOsCommand, isMount,process,
getRunCommands)
from calculate.lib.utils.common import getpathenv
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_desktop3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
from itertools import ifilter
class DesktopError(Exception):
"""Desktop Error"""
class Desktop:
"""
Desktop logic object
Has fundamental method createHome for configure user profile
Модуль для настройки пользовательского сеанса и выполнения
принудительного выхода из X сессии пользователя
"""
# username
userName = ""
verbose = False
def __init__(self):
self.homeDir = ""
@ -67,17 +63,6 @@ class Desktop:
else:
raise DesktopError(_("Path %s exists") %userDir)
def displayTemplatesApplied(self,dirsFiles):
"""
Display templates are applied (--verbose)
"""
self.printSUCCESS(_("The following files were changed")+":")
for nameF in dirsFiles[1]:
nameFile = nameF
if nameFile[:1] != "/":
nameFile = "/" + nameFile
self.printSUCCESS(" "*5 + nameFile)
def applyTemplatesFromUser(self):
"""Apply templates for user"""
if self.clTempl:
@ -105,14 +90,6 @@ class Desktop:
else:
return dirsFiles
def initVars(self,datavars=None):
"""Primary variables initialization"""
if not datavars:
self.clVars = DataVarsDesktop()
self.clVars.importDesktop()
self.clVars.flIniFile()
else:
self.clVars = datavars
def closeClTemplate(self):
if self.clTempl:
@ -135,54 +112,49 @@ class Desktop:
break
return ret
@safetyWrapper(native_errors=(TemplatesError,DesktopError),
man_int=__("Configuration manually interrupted"),
post_action=umountUserRes)
def createHome(self, datavars=None):
#!!!!post_action=umountUserRes)
def createHome(self, userName,):
"""
Creating user profile and userdir
"""
self.initVars(datavars)
self.verbose = self.clVars.Get('cl_verbose_set') == 'on'
#uid = os.getuid()
#try:
# realUserName = pwd.getpwuid(uid).pw_name
#except:
# realUserName = ""
userName = self.clVars.Get("ur_login")
uidGid = False
if self.clVars.isModuleInstalled("client"):
# domain host
domain = self.clVars.Get("client.cl_remote_host")
# authorized in domain or local
hostAuth = self.clVars.Get("client.os_remote_auth")
else:
domain = ""
hostAuth = ""
uid = self.clVars.Get('ur_uid')
gid = self.clVars.Get('ur_gid')
if not uid or not gid:
raise DesktopError(_("Failed to determine the user UID"))
uid,gid = int(uid),int(gid)
#userName = self.clVars.Get("ur_login")
#uidGid = False
#if self.clVars.isModuleInstalled("client"):
# # domain host
# domain = self.clVars.Get("client.cl_remote_host")
# # authorized in domain or local
# hostAuth = self.clVars.Get("client.os_remote_auth")
#else:
# domain = ""
# hostAuth = ""
#uid = self.clVars.Get('ur_uid')
#gid = self.clVars.Get('ur_gid')
#if not uid or not gid:
# raise DesktopError(_("Failed to determine the user UID"))
#uid,gid = int(uid),int(gid)
self.homeDir = self.clVars.Get('ur_home_path')
rootPath = self.clVars.Get('cl_root_path')
# real path to home dir
self.homeDir = path.join(rootPath, self.homeDir[1:])
if not path.exists(self.homeDir):
self.startTask(_("Creating the home directory for %s")%self.homeDir)
self.createUserDir(uid,gid,self.homeDir)
self.endTask()
# action - "user profile configuration"
self.clVars.Set("cl_action", "desktop", True)
# apply user profiles
self.startTask(_("Setting up the user profile"),progress=True)
dirsAndFiles = self.applyTemplatesFromUser()
self.endTask()
if not dirsAndFiles:
raise DesktopError(_("Failed to apply user profile templates"))
self.printSUCCESS(_("User account %s is configured")%userName + " ...")
return True
#self.homeDir = self.clVars.Get('ur_home_path')
#rootPath = self.clVars.Get('cl_root_path')
## real path to home dir
#self.homeDir = path.join(rootPath, self.homeDir[1:])
#if not path.exists(self.homeDir):
# self.startTask(_("Creating the home directory for %s")%self.homeDir)
# self.createUserDir(uid,gid,self.homeDir)
## action - "user profile configuration"
#self.clVars.Set("cl_action", "desktop", True)
## apply user profiles
#self.startTask(_("Setting up the user profile"),progress=True)
#dirsAndFiles = self.applyTemplatesFromUser()
#self.endTask()
#if not dirsAndFiles:
# raise DesktopError(_("Failed to apply user profile templates"))
#return True
def getMountUserPaths(self, homeDir=False):
"""
@ -239,20 +211,10 @@ class Desktop:
return False
return True
@safetyWrapper(native_errors=(TemplatesError,DesktopError),
man_int=__("Logout manually interrupted"),
post_action=umountUserRes,
success_message=__("The user logged out from the session!"),
failed_message=__("Unable to logout the user"))
def userLogout(self, datavars=None):
def userLogout(self, urLogin):
"""
Raise user logout throught dbus
Выполнить logout пользователя через dbus
"""
self.initVars(datavars)
if not self.clVars.Get('ur_login') in \
self.clVars.Get('cl_desktop_online_user'):
raise DesktopError(_("X session users not found"))
urLogin = self.clVars.Get('ur_login')
display = self.clVars.Select('cl_desktop_online_display',
where='cl_desktop_online_user',eq=urLogin,limit=1)
session = self.clVars.Get('cl_desktop_xsession')
@ -269,24 +231,30 @@ class Desktop:
if process("su",urLogin,"-c",
("DISPLAY=:%s /usr/bin/qdbus "%display)+logoutCommand).failed():
raise DesktopError(_("Unable send logout command"))
for i in range(0,20):
if filter(lambda x: "xdm/xdm\x00--logout" in x,
getRunCommands()):
break
time.sleep(0.5)
return True
def waitLogout(self,urLogin,waitTime,postWaitTime=5):
"""
Ожидать завершения пользовательского сеанса
Args:
urLogin: логин пользователя
waitTime: время ожидания завершения сеанса
"""
if filter(lambda x: "xdm/xdm\x00--logout" in x,
getRunCommands()):
self.startTask(_("Waiting for completion of the user logout"))
for i in range(0,300):
for i in range(0,waitTime):
if not filter(lambda x: "xdm/xdm\x00--logout" in x,
getRunCommands()):
return True
time.sleep(1)
self.endTask()
else:
raise DesktopError(_("Unable to wait for completion "
"of the user logout"))
if self.clVars.Get('ur_login') in \
self.clVars.Get('cl_desktop_online_user'):
raise DesktopError(_("Wrong logout"))
return True
for wait in range(0,5):
self.clVars.Invalidate('cl_desktop_online_data')
if not urLogin in self.clVars.Get('cl_desktop_online_user'):
return True
time.sleep(1)
else:
return False

@ -0,0 +1,72 @@
#-*- coding: utf-8 -*-
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from calculate.core.server.func import Action
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.lib.utils.files import FilesError
from calculate.desktop.desktop import DesktopError
from calculate.lib.cl_template import TemplatesError
setLocalTranslate('cl_desktop3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class ClDesktopLogoutAction(Action):
"""
Вывести пользователя из X сессии
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError,DesktopError,TemplatesError)
successMessage = __("The user logged out from the session!")
failedMessage = __("Unable to logout the user")
interruptMessage = __("Logout manually interrupted")
# список задач для действия
tasks = [
{'name':'user_logout',
'method':'Desktop.userLogout(cl_desktop_login)',
},
{'name':'wait_logout',
'message':__("Waiting for completion of the user logout"),
'method':'Desktop.waitLogout(cl_desktop_login,300)'}
]
class ClDesktopAction(Action):
"""
Настроить пользовательский профиль
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError,DesktopError,TemplatesError)
successMessage = __("User account {ur_login} is configured")
#failedMessage = __("Failed to update system")
#interruptMessage = __("Configuration manually interrupted")
# список задач для действия
tasks = [
{'name':'create_home',
'message':__("Creating the home directory for {ur_home_path}"),
'method':'Desktop.createUserDir(ur_uid,ur_gid,ur_home_path)',
'condition':lambda dv:not path.exists(dv.Get('ur_home_path'))
},
{'name':'user_profile',
'message':__("Setting up the user profile"),
'method':'Install.applyTemplates(install.cl_source,False,'\
'False,None)',
'condition':lambda dv:not path.exists(dv.Get('ur_home_path'))
},
]

@ -2,8 +2,10 @@ import os
import sys
import re
from os import path
import pwd
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable, \
ReadonlyTableVariable,FieldValue
from calculate.lib.variables.user import VariableUrLogin
from calculate.lib.utils.files import readLinesFile,process
from itertools import *
@ -213,3 +215,29 @@ class VariableClDesktopOnlineDisplay(FieldValue,ReadonlyVariable):
type = "list"
source_variable = "cl_desktop_online_data"
column = 1
class VariableClDesktopLogin(VariableUrLogin):
"""
User Login
"""
opt = ["cl_desktop_login"]
def choice(self):
if self.Get('cl_action') == 'logout':
return self.Get('cl_desktop_online_user')
else:
return VariableUrLogin.choice(self)
def check(self,value):
"""Does user exist"""
if not value in self.choice() and self.Get('cl_action') == 'logout':
raise VariableError(_("X session users not found"))
if value == "":
raise VariableError(_("Need to specify user"))
try:
pwd.getpwnam(value).pw_gid
except:
raise VariableError(_("User %s does not exist")%value)
def get(self):
return ""

@ -11,102 +11,87 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, time, os
import soaplib, sys, time, os
import threading
from calculate.lib.datavars import VariableError,DataVarsError,DataVars
from calculate.core.server.func import WsdlBase
from desktop import DesktopError
from utils.cl_desktop import ClDesktopLogoutAction,ClDesktopAction
import desktop
import calculate.install.install as install
from soaplib.serializers.primitive import String, Integer, Any, Boolean
from soaplib.serializers.clazz import Array
from soaplib.service import rpc, DefinitionBase
from calculate.core.server.api_types import ReturnedMessage,CommonInfo
from calculate.core.server.api_types import ChoiceValue, Table, Option, Field, \
GroupField, ViewInfo, ViewParams
from calculate.lib.datavars import VariableError,DataVarsError
from calculate.desktop.cl_desktop import DesktopError
from cl_desktop import Desktop,DataVarsDesktop
import cl_desktop
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.core.server.decorators import Dec
from calculate.core.server.func import catchExcept
core_method = Dec.core_method
setLocalTranslate('cl_desktop3',sys.modules[__name__])
import traceback
from functools import wraps,WRAPPER_ASSIGNMENTS
__ = getLazyLocalTranslate(_)
class DesktopInfo(CommonInfo):
"""Parameters for method install"""
ur_login = String
desktopCatchExcept = catchExcept(VariableError,DataVarsError,
cl_desktop.DesktopError)
class Wsdl:
"""
cl-desktop
"""
@rpc(Integer, DesktopInfo, _returns = Array(ReturnedMessage))
@core_method(category=__('Desktop'),title=__('Configure user'),
image='user-desktop,preferences-desktop',
gui=True,command='cl-desktop',
rights=['userconfigure'])
def desktop(self, sid, info):
return self.callMethod(sid,info,method_name="desktop",
logicClass=Desktop,
method="createHome")
def desktop_vars(self,dv=None):
if not dv:
dv = DataVarsDesktop()
dv.importDesktop()
dv.flIniFile()
dv.Set('cl_action','desktop',True)
dv.addGroup(None,
normal=('ur_login',),
expert=('cl_verbose_set','cl_templates_locate'),
next_label=_("Configure"),)
return dv
@rpc(Integer, ViewParams,_returns = ViewInfo)
def desktop_view (self, sid, params):
dv = self.get_cache(sid,"desktop","vars")
if not dv:
dv = self.desktop_vars()
else:
dv.processRefresh()
view = ViewInfo(dv,viewparams=params)
self.set_cache(sid, 'desktop', "vars",dv,smart=False)
return view
@rpc(Integer, DesktopInfo, _returns = Array(ReturnedMessage))
@core_method(category=__('Desktop'),title=__('Logout user'),
image='system-log-out',
gui=True,command='cl-desktop-logout',
rights=['userconfigure'])
def desktop_logout(self, sid, info):
return self.callMethod(sid,info,method_name="desktop_logout",
logicClass=Desktop,
method="userLogout")
def desktop_logout_vars(self,dv=None):
if not dv:
dv = DataVarsDesktop()
dv.importDesktop()
dv.flIniFile()
dv.addGroup(None,
normal=('ur_login',),
next_label=_("Logout"),)
return dv
@rpc(Integer, ViewParams,_returns = ViewInfo)
def desktop_logout_view (self, sid, params):
dv = self.get_cache(sid,"desktop_logout","vars")
if not dv:
dv = self.desktop_logout_vars()
else:
dv.processRefresh()
view = ViewInfo(dv,viewparams=params)
self.set_cache(sid, 'desktop_logout', "vars",dv,smart=False)
return view
class Wsdl(WsdlBase):
methods = [
#
# вывести пользователя из сеанса
#
{
# идентификатор метода
'method_name':"desktop_logout",
# категория метода
'category':__('Desktop'),
# заголовок метода
'title':__("Logout user"),
# иконка для графической консоли
'image':'system-log-out',
# метод присутствует в графической консоли
'gui':True,
# консольная команда
'command':'cl-desktop-logout',
# права для запуска метода
'rights':['userconfigure'],
# объект содержащий модули для действия
'logic':{'Desktop':desktop.Desktop},
# описание действия
'action':ClDesktopLogoutAction,
# объект переменных
'datavars':"desktop",
'native_error':(VariableError,DataVarsError,
DesktopError),
# значения по умолчанию для переменных этого метода
'setvars':{'cl_action!':'logout'},
# описание груп (список лямбда функций)
'groups':[
lambda group:group(_("Logout user"),
normal=('cl_desktop_login',),
next_label=_("Logout"))]},
#
# настроить пользовательский сеанс
#
{
# идентификатор метода
'method_name':"desktop",
# категория метода
'category':__('Desktop'),
# заголовок метода
'title':__("Configure user"),
# иконка для графической консоли
'image':'user-desktop,preferences-desktop',
# метод присутствует в графической консоли
'gui':True,
# консольная команда
'command':'cl-desktop',
# права для запуска метода
'rights':['userconfigure'],
# объект содержащий модули для действия
'logic':{'Desktop':desktop.Desktop,'Install':install.Install},
# описание действия
'action':ClDesktopAction,
# объект переменных
'datavars':"desktop",
'native_error':(VariableError,DataVarsError,
DesktopError),
# значения по умолчанию для переменных этого метода
'setvars':{'cl_action!':'desktop'},
# описание груп (список лямбда функций)
'groups':[
lambda group:group(_("Configure user"),
normal=('ur_login',),
expert=('cl_verbose_set','cl_templates_locate'),
next_label=_("Configure"))]},
]

@ -112,6 +112,6 @@ setup(
url = "http://calculate-linux.org",
license = "http://www.apache.org/licenses/LICENSE-2.0",
package_dir = {'calculate.desktop': "desktop"},
packages = ['calculate.desktop','calculate.desktop.variables'],
packages = ['calculate.desktop','calculate.desktop.utils','calculate.desktop.variables'],
data_files = data_files,
cmdclass={'install_data': cl_install_data})

Loading…
Cancel
Save