D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
proc
/
3
/
root
/
bin
/
Filename :
cmu_ded.py
back
Copy
#!/opt/imh-python/bin/python """ This is the attempt to automate everything in regards to account moves. This file acts mainly as a argument parser that goes into the actual script, Libs/cmumain Error Codes: 2: Problem with SSH at some level. Check the errors in the program to find out. """ import os import signal import socket import argparse import traceback import cmuwatcher import getpass import Libs import Libs.logthis import logging from rads.common import send_email from config import dev_mode # Global items. args = None def splash_page(): """ This is the splash page that is ran every time the program is executed. :return: Returns the splash page. """ return_string = """ Welcome to cmu_ded, an snm-ded replacement. Created by: Alex K. Email: alexk@inmotionhosting.com The script is running in the background. Running cmuwatcher.py will allow you to attach back to the process. Any questions? Please feel free to pidgin me. Any errors in running cmu_ded? Please either pidgin me or email me. Starting Now...... """ return return_string def parse_arguments(): """ Parsing arguments. Server is required at this time. :return: Returns the arguments in a dictionary. """ parser = argparse.ArgumentParser(description="Doing the needful one account at a time") parser.add_argument('--server', '-s', default=None, metavar='SERVER', help="Server to transfer accounts from.") parser.add_argument('--port', '-P', default=22, help="Port for the server you are connecting too.") parser.add_argument('--user', '-u', default=None, help="User to connect to the server with") parser.add_argument('--password', '-p', default=None, help="Pass the password if you have it. This also holds the " "pass phrase on the ssh_key if you have it.") parser.add_argument('--ssh_key', default=None, help="ssh_key for the other server. This is the file itself") parser.add_argument('--accesshash', default=None, help="Access hash for the server") parser.add_argument('--daemon', action='store_true', help="Daemonizing script") parser.add_argument('--start', action='store_true', help="Start the script") parser.add_argument('--stop', action='store_true', help="Stop the script") parser.add_argument('--restart', action='store_true', help="Reset then start the script") parser.add_argument('--reset', action='store_true', help="Reset VPS for everything.") parser.add_argument('--resume', action='store_true', help="Resume from a different cmu_ded proc.") parser.add_argument('--rsyncspeed', type=int, default=10000, help="Sets the rsync speed for transfering files.") parser.add_argument('--verbose', '-v', action='store_true', help="Print out all the details.") args = parser.parse_args() return { 'server': args.server, 'port': args.port, 'user': args.user, 'password': args.password, 'ssh_key': args.ssh_key, 'accesshash': args.accesshash, 'daemon': args.daemon, 'start': args.start, 'stop': args.stop, 'restart': args.restart, 'reset': args.reset, 'resume': args.resume, 'rsyncspeed': args.rsyncspeed, 'verbose': args.verbose } def setup_logging(print_info=False): """ Setup logging for everything else. :return: """ if print_info: FORMAT = '%(levelname)10s :: %(message)s' # Supressing Paramiko logger. logging.basicConfig(format=FORMAT) logger = logging.getLogger("cmu_ded") else: if not os.path.exists("/opt/cmu_ded/logs/"): os.makedirs("/opt/cmu_ded/logs/") logger = logging.getLogger("cmu_ded") file_handler = logging.FileHandler('/opt/cmu_ded/logs/cmu.debug') file_format = logging.Formatter('%(asctime)s %(levelname)10s :: %(message)s') file_handler.setFormatter(file_format) logger.addHandler(file_handler) # Supressing Paramiko logger. logging.getLogger("paramiko").setLevel(logging.WARNING) # Building our logger. logger.setLevel(logging.INFO) return logger def grab_input(args): """ Checking the args before attempting a connection. I felt this was more friendly that forcing args to pass. :param args: args of the system. :return: Filled out args. """ print("\nChecking Arguments:") if args['server'] is None: args['server'] = raw_input("What server do you want to pull from: ") if args['user'] is None: args['user'] = raw_input("What reseller user do you want to move: ") if args['password'] is None and args['ssh_key'] is None: args['password'] = getpass.getpass(prompt="What is the password: ") checker = args['server'].count(".") if checker == 0: args['server'] = args['server'] + '.inmotionhosting.com' return args def stop_cmu(): """ Kills the PID of /opt/cmu_ded/PID :return: Above. """ if os.path.exists('/opt/cmu_ded/PID'): pid = open('/opt/cmu_ded/PID', 'r').read() try: os.kill(int(pid), signal.SIGTERM) print "Killed proc %s for cmu_ded" % pid except OSError as e: if e.errno == 3: print e.message pass os.remove('/opt/cmu_ded/PID') print "Removed cmu_ded PID file." exit(0) def spawn_daemon(args): """ Two threads are required. Spawn the first one for the parrent proc and the second for cmu_ded's main function. If it errors out, catch it and print that the fork has failed. Ignoring SIGHUP so that we can log out. :return: Runs main in the background. """ # Ignoring SIGHUP, This allows you to log out and the proc continues to run. signal.signal(signal.SIGHUP, signal.SIG_IGN) try: pid = os.fork() if pid > 0: # parent process, return and keep running return except OSError, e: print "fork #1 failed: %d (%s)" % (e.errno, e.strerror) exit(1) os.setsid() # This is the fork for the cmu_ded proc. # Dumping into /opt/cmu_ded/PID try: pid = os.fork() if pid > 0: # exit from second parent exit(0) except OSError, e: print "fork #2 failed: %d (%s)" % (e.errno, e.strerror) exit(1) # do stuff main(args) # all done os._exit(os.EX_OK) def call_watcher(): """ Calling cmuwatcher's main function so that we can watch cmu_ded run, even though its running in the background. :return: Prints whats in /opt/cmu_ded/logs/cmu.debug """ # Ignoring ControlC. try: cmuwatcher.main() except KeyboardInterrupt: print "\n\n[*] Closing cmuwatcher. You can watch the process again by calling cmuwatcher.py" print "[*] You can also tail /opt/cmu_ded/logs/cmu.debug for the same info." def main(args): """ Main function of this program. Interpreting the args and executing from there. :return: Returns nothing. """ print_info = args['daemon'] or args['reset'] logger = setup_logging(print_info=print_info) if args['verbose']: logger.setLevel(logging.DEBUG) logger.info(splash_page()) open('/opt/cmu_ded/PID', 'a').write(str(os.getpid())) cpanel_move_user = Libs.cmuded.CMUDed(dev_mode=dev_mode, logger=logger) if args['reset']: cpanel_move_user.reset() if os.path.exists("/opt/cmu_ded/PID"): os.remove("/opt/cmu_ded/PID") exit(0) if args['restart']: cpanel_move_user.reset() cpanel_move_user.setup() # Recreating the loghandler since its been removed. file_handler = logging.FileHandler('/opt/cmu_ded/logs/cmu.debug') file_format = logging.Formatter('%(asctime)s %(levelname)10s :: %(message)s') file_handler.setFormatter(file_format) logger.addHandler(file_handler) if args['resume']: cpanel_move_user.load() # Creating a shell. shell = Libs.tbSSH.TbSSH(args['user'], args['server'], args['port'], sup_sshkey=args['ssh_key'], sup_password=args['password'], logger=logger, rsyncspeed=args['rsyncspeed']) if shell is not None: logger.info("Shell is open!") cpanel_move_user.ssh_connection = shell cpanel_move_user.reseller_user = args['user'] # Start of the move is here. Logging to the remote server. cpanel_move_user.log_start_migration(str(args), shell.host, socket.gethostname()) try: if cpanel_move_user.start_move(): cpanel_move_user.send_str() cpanel_move_user.cleanup() shell.close() except Exception as e: # General catchall Exception. str_content = "An error on cmu_ded.py. Below is the exception raised. \n\n" trace_error = traceback.format_exc() logger.setLevel(logging.DEBUG) cpanel_move_user.critical(trace_error) if not dev_mode: send_email('str@imhadmin.net', "cmu_ded for %s" % socket.gethostname(), str_content + trace_error) pass # Migration is not running at this point, letting the log server know. cpanel_move_user.log_end_migration() if os.path.exists("/opt/cmu_ded/PID"): os.remove("/opt/cmu_ded/PID") if __name__ == '__main__': args = parse_arguments() # Stop trumps all. if args['stop']: stop_cmu() exit() # Checking for sys.argv is more than just the program. if os.path.exists("/opt/cmu_ded/PID") and not args['resume']: print "!!! PID file exists, are you sure cmu_ded isn't already running?" exit(1) elif not args['reset']: grab_input(args) if args['daemon'] or args['reset']: main(args) else: # Trying to run the main proc as a Daemon. spawn_daemon(args) call_watcher()