Добавлена поддержка серверов с включенной репликацией

git-svn-id: http://svn.calculate.ru/calculate2/calculate-client/trunk@925 c91db197-33c1-4113-bf15-f8a5c547ca64
develop
asamoukin 15 years ago
parent d08fe25add
commit e24e83c707

@ -238,6 +238,10 @@ conjunction with the 'login' or 'logout'")
# При включениии репликации
# Временные задержки для монтирования в секундах
self.sleeps = [0.5, 2, 5]
# DN хранения последнего посещенного пользователя
self.replHostsDN = self.addDN("ou=Worked","ou=Replication",
"ou=LDAP", self.ServicesDN)
self.replLogoutFile = ".logout"
def isRoot(self):
"""Определяет является ли пользователь root"""
@ -279,6 +283,11 @@ conjunction with the 'login' or 'logout'")
return resSearch
def searchPrevHost(self, userName):
"""Находит сервер к которому был подключен пользователь"""
resSearch = self.searchLdapDN(userName, self.replHostsDN, "uid")
return resSearch
def searchUnixUser(self, userName):
"""Находит пользователя сервиса Unix"""
resSearch = self.searchLdapDN(userName, self.relUsersDN, "uid")
@ -531,7 +540,8 @@ conjunction with the 'login' or 'logout'")
if homeExists:
self.printWARNING(_("Home dir %s exists")%homeDir)
if set(os.listdir(homeDir))-set(["Home","Disks","FTP"]):
if set(os.listdir(homeDir))-set(["Home","Disks","FTP",\
self.replLogoutFile]):
if not applyAlways:
# Получаем пути к профилям постоянного наложения
alwProfilePath = self.getAlwaysProfilePath()
@ -827,11 +837,11 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
pathRemote.append((os.path.join(home,"." + userName), "unix"))
# Удаленный ресурс home
pathRemote.append((os.path.join(homeDir,"Home"), "homes"))
# Удаленный ресурс share
pathRemote.append((os.path.join(homeDir,"Disks"), "share"))
# Удаленный ресурс ftp
if self.clVars.Get("cl_remote_ftp"):
pathRemote.append((os.path.join(homeDir,"FTP"), "ftp"))
# Удаленный ресурс share
pathRemote.append((os.path.join(homeDir,"Disks"), "share"))
self.moveHomeDir(homeDir)
# Синхронизируем настройки
if not self.syncUser(userName, homeDir, "logout"):
@ -841,6 +851,15 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
flagError = False
for path, res in pathRemote:
if self.isMount(path ,"cifs"):
# В случае репликации
if res == "share":
# Проверка на репликацию
pathReplRun = os.path.join(path, self.replRunFileShare)
if os.path.exists(pathReplRun):
FD = open(pathReplRun)
# Записывает доменное имя сервера если
# с сервером корректно соединились
FD.close()
textLine = self.execProg("umount %s"%path)
if not (textLine == None):
self.printERROR(_("Can not umount Samba resource \
@ -855,7 +874,7 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
flagError = True
break
if flagError:
self.printERROR(_("Keep a user profile in the domain"))
self.printERROR(_("Can not keep a user profile in the domain"))
return False
self.printSUCCESS(_("Keep a user profile in the domain"))
self.printOK(_("Umount user resource in domain") + " ...")
@ -891,11 +910,11 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
pathRemote.append((os.path.join(home,"." + userName), "unix"))
# Удаленный ресурс home
pathRemote.append((os.path.join(homeDir,"Home"), "homes"))
# Удаленный ресурс share
pathRemote.append((os.path.join(homeDir,"Disks"), "share"))
# Удаленный ресурс ftp
if self.clVars.Get("cl_remote_ftp"):
pathRemote.append((os.path.join(homeDir,"FTP"), "ftp"))
# Удаленный ресурс share
pathRemote.append((os.path.join(homeDir,"Disks"), "share"))
flagError = False
self.moveHomeDir(homeDir)
for path, res in pathRemote:
@ -948,6 +967,25 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
break
return foundTwoSession
def mountSambaRes(self,userName,userPwd,uid,gid,res,path,
mountUidList=['ftp','share']):
"""Монтирует Samba ресурсы"""
if res in mountUidList:
# Монтируем директории c uid
mountStr="mount -t cifs -o user=%s,password=%s,uid=%s,gid=%s"\
%(userName,userPwd,uid,gid) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
else:
# Монтируем директории
mountStr="mount -t cifs -o user=%s,password=%s"%(userName,
userPwd) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
textLine = self.execProg(mountStr)
return textLine
def mountUserRes(self, userName, sync=True):
"""Монтирование пользовательских ресурсов и синхронизация настроек"""
# Проверяем на root
@ -1002,9 +1040,12 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
# Удаленный ресурс ftp
pathRemote.append((os.path.join(homeDir,"FTP"), "ftp"))
flagError = False
flagSleep = False
# Флаг репликации
flagRepl = False
# Запускаемый файл на сервере в случае репликации
pathReplRun = ""
# Путь к профилю пользователя по умолчанию
defaultPath = ""
# Ност пользователя по умолчанию
defaultHost = self.clVars.Get("cl_remote_host")
for path, res in pathRemote:
# Создаем директории для монтирования
if not os.path.exists(path):
@ -1020,77 +1061,122 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
continue
if res in ['ftp','share']:
# Монтируем директории c uid
mountStr="mount -t cifs -o user=%s,password=%s,uid=%s,gid=%s"\
%(userName,userPwd,uid,gid) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
else:
# Монтируем директории
mountStr="mount -t cifs -o user=%s,password=%s"%(userName,
userPwd) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
textLine = self.execProg(mountStr)
# В случае репликации не монтируем профиль пользователя
if pathReplRun and res=="unix":
defaultPath = path
continue
# Монтируем Samba ресурс
textLine = self.mountSambaRes(userName,userPwd,uid,gid,res,path)
if not (textLine == None):
# В случае репликации
if flagSleep:
i == 0
while (i<len(self.sleeps) and not (textLine == None)):
time.sleep(self.sleeps[i])
if res in ['ftp','share']:
# Монтируем директории c uid
mountStr=\
"mount -t cifs -o user=%s,password=%s,uid=%s,gid=%s"\
%(userName,userPwd,uid,gid) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
else:
# Монтируем директории
mountStr=\
"mount -t cifs -o user=%s,password=%s"\
%(userName,userPwd) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
textLine = self.execProg(mountStr)
if not (textLine == None):
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
textLineUmount = self.execProg("umount %s"%path)
if not (textLineUmount == None):
self.printERROR(_("Can not umount Samba \
resource [%s]")%res + " ...")
flagError = True
break
else:
flagSleep = False
i += 1
if not (textLine == None):
if flagError:
break
self.printERROR(_("Can not mount Samba resource [%s]")\
self.printERROR(_("Can not mount Samba resource [%s]")\
%res + " ...")
flagError = True
break
flagError = True
break
# В случае репликации
if res == "share":
# Проверка на репликацию
pathReplRun = os.path.join(path, self.replRunFileShare)
if os.path.exists(pathReplRun):
FD = open(pathReplRun)
# Создание директорий пользователя на сервере
# в случае если их нет
FD.close()
flagRepl = True
flagSleep = True
if flagError:
return False
# Синхронизируем настройки
if sync:
# Ошибка при монтировании unix ресурса удаленного сервера при
# включенной репликации
replError = False
# В случае репликации
prevHost = ""
if pathReplRun:
searchPrevHost = self.searchPrevHost(userName)
if searchPrevHost and searchPrevHost[0][0][1].has_key('host'):
prevHost = searchPrevHost[0][0][1]['host'][0]
mountHost = ""
if prevHost and prevHost != self.clVars.Get("cl_remote_host"):
# Монтируем настройки пользователя если сервер найден
self.clVars.Set("cl_remote_host", prevHost, True)
mountHost = prevHost
textLine = self.mountSambaRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
textLineUmount=\
self.execProg("umount %s"%defaultPath)
if not (textLineUmount == None):
self.printERROR(_("Can not umount Samba \
resource [%s]")%"unix" + " ...")
return False
i == 0
while (i<len(self.sleeps) and not (textLine == None)):
# Задержка перед следующей попыткой
time.sleep(self.sleeps[i])
# Монтируем Samba ресурс
textLine = self.mountSambaRes(userName,userPwd,uid,
gid,"unix",defaultPath)
if not (textLine == None):
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
textLineUmount=\
self.execProg("umount %s"%defaultPath)
if not (textLineUmount == None):
self.printERROR(_("Can not umount \
Samba resource [%s]")%"unix" + " ...")
return False
i += 1
if not (textLine == None):
replError = True
self.clVars.Set("cl_remote_host", defaultHost, True)
if (not prevHost) or\
(prevHost and\
prevHost == self.clVars.Get("cl_remote_host")) or\
replError:
# Монтируем настройки пользователя если сервер не найден
mountHost = self.clVars.Get("cl_remote_host")
textLine = self.mountSambaRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource \
[%s]")%"unix" + " ...")
return False
# Синхронизируем настройки пользователя
replErrorSync = False
if not self.syncUser(userName, homeDir, "login"):
if pathReplRun and\
mountHost != self.clVars.Get("cl_remote_host"):
replError = True
replErrorSync = True
else:
return False
if pathReplRun and not replError and\
mountHost != self.clVars.Get("cl_remote_host"):
# В случае репликации перемонтируем ресурс профилей
# на текущий сервер (в случае необходимости)
textLine = self.execProg("umount %s"%defaultPath)
if not (textLine == None):
self.printERROR(_("Can not umount Samba resource \
[%s]")%"unix" + " ...")
return False
textLine = self.mountSambaRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%"unix" + " ...")
return False
# Если ошибка синхронизации с удаленного сервера то
# делаем синхронизацию с сервера по умолчанию
if replErrorSync and os.listdir(defaultPath):
if not self.syncUser(userName, homeDir, "login"):
return False
if pathReplRun:
logOutFile = os.path.join(homeDir,self.replLogoutFile)
if replError:
self.createUserFile(logOutFile,"ERROR", uid, gid)
else:
self.createUserFile(logOutFile,"SUCCESS", uid, gid)
self.printSUCCESS(_("Mount user resource in domain"))
self.printOK(_("Get a user profile in the domain") + " ...")
return True
@ -1154,7 +1240,23 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
return self.copyFilesToMovie(userHome)
return True
def createUserFile(self, fileName, fileTxt, uid, gid, mode=0644):
"""Создает пользовательский файл с содержимым
Если директория файла не существует то ошибка
"""
userDir = os.path.split(fileName)[0]
if not os.path.exists(userDir):
self.printERROR(_("Path %s not exists") %userDir)
return False
fd = os.open(fileName, os.O_CREAT)
os.close(fd)
os.chmod(fileName, mode)
os.chown(fileName,uid,gid)
FD = open(fileName, "r+")
FD.write(fileTxt)
FD.close()
return True
def syncUser(self, userName, userHome, sync):
"""Синхронизация пользовательских настроек"""

Loading…
Cancel
Save