Пример #1
0
def unjoinProj(projPathAtRemote,pattern,pd='Ff'):
    import os, sys, getpass
    import time, pwd
    import subprocess as sp
    from xml.dom.ext.reader import Sax2
    from xml.xpath import Evaluate
    import shutil
    import project
    from UnjoinMail import UnjoinMail
    from xml.dom import minidom
    from pathInfo import pathInfo_base, pathInfo_ks
    from snipTree import snipTree
    # cd home
    homePath=os.environ['HOME']
    os.chdir(os.environ['HOME'])
    # Initialize as in start.project
    startprojectXML = r'//genomics/lib/start.project/start.project.xml'
    BIOINFOprojRootPath = r'//genomics/Projects'
    BIOSTATprojRootPath = r'/proj/BIOSTAT/Projects'
    USERprojRootPathPre = r'MyProjects'
    SHAREDPATH = r'shared'
    PRIVATEPATH = r'private'                 
    # --------------- 
    projPathInfo=pathInfo_base(projPathAtRemote)
    pathInfo_ks(projPathInfo,type='unjoin')
    # pathInfo: pathOutput=(pathAbs,projName,projNameA,projNameP,projNameAP,pathPrefix,secId,pidType,localPathPrefix,projPathAtLocal)
    #                          0       1         2        3         4           5         6    7            8             9
    #                                                                                                       -2            -1
    if pd=='Ff':
        print "\nYou are going to unjoin a project with the following parameters:"
    else:
        print "\nYou are going to delete a project with the following parameters:"
    print "                Section : %s" %(projPathInfo[6])
    print "           Project Type : %s" %(projPathInfo[7])
    print "Local Project Path : %s\n" %(projPathInfo[9])
    pathVerify=raw_input("Are you sure [y] (y/n)? " )
    pathVerify=pathVerify.upper()
    while not (pathVerify in ["","Y","N","YES","NO"]):
        print "Please answer with \"y\" or \"n\" "
        pathVerify=raw_input("Are you sure to take action on this project [y] (y/n) ? " ) 
        pathVerify=pathVerify.upper()
    if pathVerify in ["N","NO"]:
        sys.exit("Start project program exited.")    
    
    secId=projPathInfo[6]
    pidType=projPathInfo[7]
    projName=projPathInfo[1]   
    # give proj path (with proj name), relative to pathPrefix as in pathInfo.py
    projNameP=projPathInfo[3] 
    projPathAtRemote= projPathInfo[0]   #abs proj path at remote
    projPathAtRemoteAP=projPathInfo[4]
    pathPrefix=projPathInfo[5]
    
    if pidType=='private':
        pid=1
    elif pidType=='shared':
        pid=3
    else: sys.exit("Wrong project type, contact support")  
    if secId=='BIOSTAT':
        secIdN=1
    elif secId=='BIOINFO':
        secIdN=3
    else: sys.exit("Wrong section ID, contact support")           
    while not os.path.exists(projPathAtRemote):      
        print "\nThere is no project as your input (\'%s\'). \nPlease verify the directory path and the project name.\n" %(projPathAtRemote)    
        continueDel=raw_input("Do you wan to specify another project to Unjoin? y/n: ")
        print "\n"
        if (continueDel.strip().upper() == 'N'): 
            sys.exit("Good-bye.\n")
            break
        elif (continueDel.strip().upper() != 'Y'):
            print "Please answer with y or n"
        else:    
            projPathAtRemote = raw_input("Please input the name of the project which you want to Unjoin: ")  
    #############################################################################
    # Get local proj path ###
    # ProjToBeUnjoind=projPathAtRemote.split('/')[-1]    
    # name of the project to be unjoined
    ProjToBeUnjoind=projPathInfo[1] 
    if pid in [1,2]:   
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/private'+'/'+ProjToBeUnjoind    
    else:
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/shared'+'/'+ProjToBeUnjoind
    #############################################################################    
    # 1. Permission check
    # Check for ownerhip and postfix of ANALYST_XXX
            
    # 2. Rename the ANALYST_XXX to .ANALYST_XXX +timeTag or /proj/.../proj_name to /proj/.../.proj_name+timeTag
    # 3. Delete the symbolic link at /Users/XXuserXX/MyProjects_BIOINFO/shared/XXX  [genomics can be biostatistics] 
    #############################################################################
            
    if pid!=3:        
        UnjoinProjSubFolderPath=projPathAtRemote     
        projPathAtRemoteNoname=projPathInfo[4]          
        if (not os.path.exists(UnjoinProjSubFolderPath)):                      
            if pd=='Ff':
                sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
             \n Please contact the system administrator\n""")          # 0.1 : check whether path exists
            else:
                sys.exit(""" Delete has been terminated by the remote system. \n \
             \n Please contact the system administrator\n""") 
        else:
            OwnerOfUnjoinProjSubFolder=pwd.getpwuid(os.stat(UnjoinProjSubFolderPath)[4])[0]      
            if (os.environ["USER"]!=OwnerOfUnjoinProjSubFolder):
                if pd=='Ff':
                    print 'Unjoin can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this unjoin action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)   # 0.2 : check file owners 
                else:
                    print 'Delete can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)   # 0.2 : check file owners 
            else:
                if secId=='BIOSTAT':
                    projRoot0=BIOSTATprojRootPath
                else:
                    projRoot0=BIOINFOprojRootPath
                pathToXML=projPathAtRemote+'/.proj_info.xml'
                xmldoc=minidom.parse(pathToXML)  # '/genomics/lib/start.project/test.xml'
                cNodes=xmldoc.childNodes
                projNum=cNodes[0].getElementsByTagName("projNum")
                projInfoFileName=(projNum)[0].firstChild.nodeValue.strip() 
                newFolderPath=projPathInfo[4]  
                projInfoFileNameNoPath=os.path.basename(projInfoFileName)
                newNameForTheUnjoinProjectSubFolder=os.path.join(newFolderPath,'.'+projInfoFileNameNoPath)
                try:
                    commonPublic(dirFs=UnjoinProjSubFolderPath) 
                    shutil.move(UnjoinProjSubFolderPath, newNameForTheUnjoinProjectSubFolder)
                    removeLocalSymbolicLink="rm -R -f \"%s\"" %(projPathAtLocal)
                    os.system(removeLocalSymbolicLink)
                    relink='rm \"%s/.projInfo/%s\"' %(projRoot0,projInfoFileName.replace('/','=>'))
                    os.system(relink) 
                except:
                    sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
                             \n Please contact the system administrator\n""")   
    elif pid==3:
        UnjoinProjSubFolderPath=projPathAtRemote+'/'+'ANALYST_'+os.environ["USER"]        

        if (not os.path.exists(UnjoinProjSubFolderPath)):                      
            if pd=='Ff':            
                print '''Unjoin can not be executed, since the folder %s does not exist. You are currently not a member of the project %s \n''' \
                   %(str('ANALYST_'+os.environ["USER"]), projPathAtRemote)     # why not LOGNAME?
            else:
                print '''Delete can not be executed, since the folder %s does not exist. You are currently not a member of the project %s \n''' \
                   %(str('ANALYST_'+os.environ["USER"]), projPathAtRemote)     # why not LOGNAME?                
            sys.exit()
        else:
            OwnerOfUnjoinProjSubFolder=pwd.getpwuid(os.stat(UnjoinProjSubFolderPath)[4])[0]      
            if (os.environ["USER"]!=OwnerOfUnjoinProjSubFolder):  
                print 'Unjoin can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this unjoin action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)              
            else:
                timeTag=time.strftime("_%Y%b%d%H%M%SSN")+str(int(1000*time.time()))   #1/1000 second accurate
                newNameForTheUnjoinProjectSubFolder=projPathAtRemote+'/.'+'ANALYST_'+os.environ["USER"]+timeTag
                try:
                    commonPublic(dirFs=UnjoinProjSubFolderPath)   
                    UnjoinProjSubFolderPath="mv \"%s\" \"%s\"" %(UnjoinProjSubFolderPath, newNameForTheUnjoinProjectSubFolder)
                    os.system(UnjoinProjSubFolderPath)
                    string1='chmod -R uog=rwx \"%s\"' %(newNameForTheUnjoinProjectSubFolder)   
                    os.system(string1) 
                    removeLocalSymbolicLink="rm -R -f \"%s\"" %(projPathAtLocal)
                    os.system(removeLocalSymbolicLink)
                except:
                    sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
                             \n Please contact the system administrator\n""")   
    # ###########################################################################
    
    # Mail unsubscription
    # Need to readin .maillist from user's home directory
    # readout project type id and section ID from the symbolic link's abs path, i.e., projPathAtRemote
    
    # 1. remove items in /Users/XXX/.mailboxlist, .mailboxlist.bak is untouched.
    try:
        UnjoinMail(projname=ProjToBeUnjoind,pid=pid,secIdN=secIdN)        
    except:
        aa=0
    # ###########################################################################
    string3=os.environ['HOME']+'/mail'+'/MyProjects_'+secId+'/'+pidType+'/'+ProjToBeUnjoind
    if  os.path.islink(string3): 
        if (os.environ["USER"]!=pwd.getpwuid(os.lstat(string3)[4])[0]):
            print 'Warning: %s does not belong to you. Please ask %s to delete it' %(string3,pwd.getpwuid(os.stat(string3)[4])[0])
        else:
            string4='rm -R -f '+string3
            try:
                os.system(string4)
            except:
                aa=0
    elif not os.path.exists(string3):   
        print "Note: %s does not exists" %(string3)
    elif (os.environ["USER"]!=pwd.getpwuid(os.stat(string3)[4])[0]):  
        print 'Warning: %s does not belong to you. Please ask %s to delete it' %(string3,pwd.getpwuid(os.stat(string3)[4])[0])
    else:
        string4='rm -R -f '+string3
        try:
            os.system(string4)     
        except:
            aa=0   
    # look through files in .common and Public/.projects    
    commonFiles=os.path.join(projPathAtRemote,'.common')
    commonPublic(dirFs=commonFiles)
    if secId=='BIOINFO':
       publicFiles=os.path.join('/proj','genomics','Public','.projects',ProjToBeUnjoind)
    elif secId=='BIOSTAT':
       publicFiles=os.path.join('/proj','BIOSTAT','Public','.projects',ProjToBeUnjoind)
    commonPublic(dirFs=publicFiles)
    # write unjoin date into .proj_info.xml
    projType=pid
    if projType==3:    
        pathToXML=projPathAtRemote+'/.common/'+'.proj_info.xml'
        projInfoXMLbkup=projPathAtRemote+'/.common/'+'.proj_info_bkup.xml'
    elif projType in [1,2]:
        pathToXML=newNameForTheUnjoinProjectSubFolder+'/.proj_info.xml'
        projInfoXMLbkup=newNameForTheUnjoinProjectSubFolder+'/.proj_info_bkup.xml' 
    
    try:
        tempstring='cp -f \"%s\" \"%s\"' %(pathToXML, projInfoXMLbkup)
        os.system(tempstring)
    except: 
        print 'Warning: Can not handle the XML for proj info' 
    try:
        xmldoc=minidom.parse(pathToXML) 
        cNodes=xmldoc.childNodes
        projNum=cNodes[0].getElementsByTagName("projNum")
        projInfoFileName=(projNum)[0].firstChild.nodeValue.strip()
        analystList=cNodes[0].getElementsByTagName("analyst")
        for item in analystList:
            if item.getElementsByTagName("loginName")[0].firstChild.nodeValue.strip()==os.environ['USER']:
                item.getElementsByTagName("unjoinDate")[0].firstChild.nodeValue=time.ctime()
                file = open(pathToXML, 'w')  
                file.write(xmldoc.toxml())
                file.close()
                break
            
        tempstring='rm \"%s\"' %(projInfoXMLbkup)
        os.system(tempstring)
    except:
        print 'Warning: Can not handle the XML for proj info'
    if projType==1:
        move2deleted=os.path.join(os.path.dirname(os.path.dirname(pathPrefix)),'.deleted',projInfoFileName.replace('/','=>'))
        move2='mv \"%s\" \"%s\"' %(newNameForTheUnjoinProjectSubFolder,move2deleted)
        os.system(move2)  
    projPathAtLocal= projPathInfo[9]
    localPathPrefix=projPathInfo[8]
    localMail=projPathAtLocal.replace(os.environ['HOME'],os.path.join(os.environ['HOME'],'mail'),1)
    if pidType== 'private':
       snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  #local main     
       snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail'))  
       snipTree(folderPathRaw=projPathAtRemoteAP, stopRaw=pathPrefix)
    else:
       snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  #local main
       snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail')) 
    ############################## Good bye ###################################
    if pd=='Ff':
        print "Unjoin completed. Good bye.\n "
Пример #2
0
        elif Uoptions[1][0]=='-':
            print 'Unknown option %s' %(Uoptions[1])
            sys.exit(helpInfo)
        else:
            projPathAtRemote = Uoptions[1]             
    else: 
            sys.exit(helpInfo)
      
    if not projPathAtRemote:
        projPathAtRemote=raw_input('Please input the project path string: ')
        
    projPathAtRemoteRawAbsNoLinik=os.path.join(os.environ['PWD'],projPathAtRemote)
    if os.path.realpath(os.environ['PWD'])!=os.environ['PWD']:   
        projPathAtRemote=os.path.join(os.environ['PWD'],projPathAtRemote) 
    projPathAtRemote=pathInfo_base(projPathAtRemote)[0]
    pathInfo_ks(pathInfo_base(projPathAtRemote))

    while not os.path.exists(projPathAtRemote):      
        print "\nThere is no project as your input (\'%s\'). \nPlease verify the directory path and the project name to be deleted.\n" %(projPathAtRemoteRawAbsNoLinik)
        continueDel=raw_input("Do you want to specify another project to delete? y/n: ")
        print "\n"
        if (continueDel.strip().upper() == 'N'): 
            sys.exit("Good-bye.\n")
            break
        elif (continueDel.strip().upper() != 'Y'):
            print "Please answer with y or n"
        else:    
            projPathAtRemote = raw_input("Please input the name of the project which you want to delete: ")  
    
    delProj(projPathAtRemote=projPathAtRemote)