#!/usr/bin/env python # #******************************************************************************* # #Copyright (c) 2009, Perforce Software, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************* # #Author: Stephen Moon #Date: 7/17/2010 #Last Modifed: 7/24/2010 #Summary: Delete old clients # #******************************************************************************* from subprocess import Popen,PIPE,STDOUT from datetime import date,datetime,time,timedelta import sys,os,re,time,logging,smtplib #Enable logging of the backup script logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='p4client.log', filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) #define all the environmental variables p4debug = logging.getLogger('p4debug') p4error = logging.getLogger('p4error') #p4 = "c:\program files\perforce\p4.exe" p4 = 'c:\p4root\p4.exe' mailhost = 'smtp.perforce.com' server = 'public.perforce.com' port = '1666' P4USER = 'stephen_moon' #P4CHARSET = 'utf8' #set it to empty string if your server is not Unicode P4PORT = server + ':' + port os.environ['P4PORT'] = P4PORT os.environ['P4USER'] = P4USER #os.environ['P4CHARSET'] = P4CHARSET #Define classes for Client and User containers class Client(object): def __init__(self): self.name = "" self.access = "" self.owner = "" self.fullname = "" self.email = "" def getName(self): return self.name class ClientDict(dict): def addClient(self,obj): self[obj.getName()] = obj class User(object): def __init__(self): self.name = "" self.fullname = "" self.email = "" def getName(self): return self.name class UserDict(dict): def addUser(self,obj): self[obj.getName()] = obj def getClientInfo(clientsOutput): matchClient = "^\.\.\.\sclient\s(\S+)" matchAccess = "^\.\.\.\sAccess\s(\d+)" matchOwner = "^\.\.\.\sOwner\s(\S+)" clientMatched = re.compile(matchClient) accessMatched = re.compile(matchAccess) ownerMatched = re.compile(matchOwner) clientList = ClientDict() for line in clientsOutput: mClient = clientMatched.match(line) mAccess = accessMatched.match(line) mOwner = ownerMatched.match(line) try: if mClient is not None: clientObj = Client() #print mClient.group(1) clientObj.name = mClient.group(1) if mAccess is not None: #print mAccess.group(1) clientObj.access = mAccess.group(1) if mOwner is not None: #print mOwner.group(1) clientObj.owner = mOwner.group(1) clientList.addClient(clientObj) except Exception: p4error.exception('An error occurred: %s' % Exception) return clientList def getUserInfo(userOutput): matchUser = "^\.\.\.\sUser\s(\d+)" matchFullName = "^\.\.\.\sFullName\s(.*)" matchEmail = "^\.\.\.\sEmail\s(\S+)" userMatched = re.compile(matchUser) fullnameMatched = re.compile(matchFullName) emailMatched = re.compile(matchEmail) userList = UserDict() for line in userOutput: mUser = userMatched.match(line) mFullName = fullnameMatched.match(line) mEmail = emailMatched.match(line) print "any? ",line try: if mUser is not None: userObj = User() #print mClient.group(1) userObj.name = mUser.group(1) if mFullName is not None: #print mAccess.group(1) userObj.fullname = mFullName.group(1) if mEmail is not None: #print mOwner.group(1) userObj.owner = mEmail.group(1) userList.addUser(userObj) except Exception: p4error.exception('An error occurred: %s' % Exception) return userList def getUsers(): getUsers= [p4,'-ztag','users'] print "getusers: ",getUsers p = Popen(getUsers,shell=True,stdout=PIPE,stderr=PIPE) userList = p.stdout.readlines() userErr = p.communicate()[1] print "list: ",userList users = getUserInfo(userList) p.stdout.close() p.stderr.close() print "dict: ",users if userErr == "": print('"p4 -ztag users" executed successfully') p4debug.exception('"p4 -ztag users" executed successfully') else: sys.stderr.write(userErr) p4error.exception('Unable to list users: \n%s' % userErr) exit(1) return users def addUserEmail(clients): users = getUsers() for k,v in clients.items(): if users[k]: clients[k].fullname = users[k].fullname clients[k].email = users[k].email return clients def getClients(today,oldDate): getClients = [p4,'-ztag','clients'] p = Popen(getClients,shell=True,stdout=PIPE,stderr=PIPE) clientList = p.stdout.readlines() clientErr = p.communicate()[1] clients = getClientInfo(clientList) clients = addUserEmail(clients) p.stdout.close() p.stderr.close() if clientErr == "": for k,v in clients.items(): clientDate = date.fromtimestamp(float(v.access)) if clientDate > oldDate: print("%s, %s, %s %s" % (k,date.fromtimestamp(float(v.access)),v.owner,v.email)) p4debug.exception("keep: %s, %s, %s, %s" % (k,date.fromtimestamp(float(v.access)),v.owner,v.email,v.fullname)) else: #print("%s, %s, %s" % (k,date.fromtimestamp(float(v.access)),v.owner)) p4debug.exception("delete: %s, %s, %s, %s" % (k,date.fromtimestamp(float(v.access)),v.owner,v.email,v.fullname)) else: sys.stderr.write(clientErr) p4error.exception('Unable to list clients: \n%s' % clientErr) exit(1) def main(): inputDays = raw_input("Enter the number of days that the clients have\nnot been used: ") today = date.today() #print("Today: %s" % today) oldDate = timedelta(days=int(inputDays)) #print("OldDAy: %s" % (today - oldDate)) getClients(today,today - oldDate) if __name__ == '__main__': main()