def chg_slv_state(slaves, opt): """Function: chg_slv_state Description: Starts or stops all of the slaves in array of slave class instances. Arguments: (input) slaves -> List of slave instances. (input) opt -> stop|start - Stops or starts the slave(s). """ slaves = list(slaves) if opt == "stop": for slv in slaves: slv.stop_slave() slv.upd_slv_status() elif opt == "start": for slv in slaves: slv.start_slave() slv.upd_slv_status() else: gen_libs.prt_msg("Error", "No option selected to stop/start rep.")
def run_optimize(server, dbs, tbl, **kwargs): """Function: run_optimize Description: Calls the optimize table command and print the results. Arguments: (input) server -> Server instance. (input) dbs -> Database name. (input) tbl -> Table name. (input) **kwargs: sys_dbs -> List of system databases to skip. """ global PRT_TEMPLATE if dbs not in list(kwargs.get("sys_dbs", [])): for item in mysql_libs.optimize_tbl(server, dbs, tbl): if item["Msg_type"] == "note" and item["Msg_text"] == \ "Table does not support optimize, doing recreate + \ analyze instead": continue else: print(PRT_TEMPLATE.format(dbs, tbl), end="") gen_libs.prt_msg(item["Msg_type"], item["Msg_text"])
def rep_msg_chk(rep_stat, prt_lvl=1, **kwargs): """Function: rep_msg_chk Description: Print data if the infoMessage field is present. Arguments: (input) rep_stat -> Member document from replSetGetStatus. (input) prt_lvl -> Integer - Level at which to print message. """ rep_stat = dict(rep_stat) if rep_stat.get("infoMessage"): gen_libs.prt_msg("Error Message", rep_stat.get("infoMessage"), prt_lvl)
def rep_health_chk(rep_stat, prt_all=False, prt_lvl=1, **kwargs): """Function: rep_health_chk Description: Checks the replication health status for a member. Arguments: (input) rep_stat -> Member document from replSetGetStatus. (input) prt_all -> True|False - To print all or just errors. (input) prt_lvl -> Integer - Level at which to print message. """ rep_stat = dict(rep_stat) if not rep_stat.get("health"): gen_libs.prt_msg("Health", "Bad", prt_lvl) elif prt_all: gen_libs.prt_msg("Health", "Good", prt_lvl)
def run_check(server, dbs, tbl, **kwargs): """Function: run_check Description: Calls the check table command and print the results. Arguments: (input) server -> Server instance. (input) dbs -> Database name. (input) tbl -> Table name. """ global PRT_TEMPLATE for item in mysql_libs.check_tbl(server, dbs, tbl): print(PRT_TEMPLATE.format(dbs, tbl), end="") gen_libs.prt_msg(item["Msg_type"], item["Msg_text"])
def rep_state_chk(rep_stat, prt_all=False, prt_lvl=1, **kwargs): """Function: rep_state_chk Description: Checks the state for a member. Requires the member document from a "replSetGetStatus" command to be passed to the function. Arguments: (input) rep_stat -> Member document from replSetGetStatus. (input) prt_all -> True|False - To print all or just errors. (input) prt_lvl -> Integer - Level at which to print message. """ # Good state is 1 (Primary), 2 (Secondary), 7 (Abriter). good_state = [1, 2, 7] rep_stat = dict(rep_stat) if rep_stat.get("state") not in good_state or prt_all: gen_libs.prt_msg("State", rep_stat.get("state"), prt_lvl) gen_libs.prt_msg("State Msg", rep_stat.get("stateStr"), prt_lvl + 1)
def run_analyze(server, dbs, tbl, **kwargs): """Function: run_analyze Description: Calls the analyze table command and prints the results. Arguments: (input) server -> Server instance. (input) dbs -> Database name. (input) tbl -> Table name. (input) **kwargs: sys_dbs -> List of system databases to skip. """ global PRT_TEMPLATE if dbs not in list(kwargs.get("sys_dbs", [])): for item in mysql_libs.analyze_tbl(server, dbs, tbl): print(PRT_TEMPLATE.format(dbs, tbl), end="") gen_libs.prt_msg(item["Msg_type"], item["Msg_text"])
def run_program(args_array, func_dict, **kwargs): """Function: run_program Description: Creates class instance(s) and controls flow of the program. Arguments: (input) args_array -> Dict of command line options and values. (input) func_dict -> Dictionary list of functions and options. """ args_array = dict(args_array) func_dict = dict(func_dict) server = gen_libs.load_module(args_array["-c"], args_array["-d"]) # Only pass authorization mechanism if present. auth_mech = { "auth_mech": server.auth_mech } if hasattr(server, "auth_mech") else {} coll = mongo_class.Coll(server.name, server.user, server.japd, host=server.host, port=server.port, db="local", coll="system.replset", auth=server.auth, conf_file=server.conf_file, auth_db=server.auth_db, use_arg=server.use_arg, use_uri=server.use_uri, **auth_mech) status = coll.connect() if status[0]: # Is replication setup. if coll.coll_cnt() != 0: # Get replica set name if not in config. if server.repset: rep_set = server.repset else: rep_set = coll.coll_find1().get("_id") repinst = mongo_class.RepSet(server.name, server.user, server.japd, host=server.host, port=server.port, auth=server.auth, repset=rep_set, repset_hosts=server.repset_hosts, auth_db=server.auth_db, use_arg=server.use_arg, use_uri=server.use_uri, **auth_mech) status2 = repinst.connect() if status2[0]: _call_func(args_array, func_dict, repinst) mongo_libs.disconnect([repinst]) else: print("run_program.RepSet: Connection failure: %s" % (status2[1])) else: gen_libs.prt_msg("Error", "No replication found.", 0) mongo_libs.disconnect([coll]) else: print("run_program.Coll: Connection failure: %s" % (status[1]))
def chk_mem_rep_lag(rep_status, **kwargs): """Function: chk_mem_rep_lag Description: Process each member in the replication set and check for replication lag. Arguments: (input) rep_status -> Member document from replSetGetStatus. (input) **kwargs: json -> True|False - JSON format. ofile -> file name - Name of output file. db_tbl -> database:collection - Name of db and collection. class_cfg -> Server class configuration settings. mail -> Mail instance. args_array -> Array of command line options and values. suf -> Primary|Freshest Secondary who has latest date time. optdt -> Primary|Best Oplog date time. (output) status -> Tuple on connection status. status[0] - True|False - Connection successful. status[1] - Error message if connection failed. """ t_format = "%Y-%m-%d %H:%M:%S" rep_status = dict(rep_status) json_fmt = kwargs.get("json", False) outdata = { "Application": "Mongo Replication", "RepSet": rep_status.get("set"), "Master": get_master(rep_status).get("name"), "AsOf": datetime.datetime.strftime(datetime.datetime.now(), t_format), "Slaves": [] } # Process each member in replica set. for member in rep_status.get("members"): # Ignore if member is Primary or Abriter. if member.get("state") in [1, 7]: continue # Fetch rep lag time. if member.get("optime"): sec_ago = gen_libs.get_secs(kwargs["optdt"] - member.get("optimeDate")) outdata["Slaves"].append({ "Name": member.get("name"), "SyncTo": datetime.datetime.strftime(member.get("optimeDate"), t_format), "LagTime": sec_ago }) else: gen_libs.prt_msg("Warning", "No replication info available.", 0) if json_fmt: status = _process_json(outdata, **kwargs) else: status = _process_std(outdata, **kwargs) return status
def _process_non_json(server, args_array, outdata, mode, **kwargs): """Function: _process_non_json Description: Private function for status to process non-json format data. Arguments: (input) server -> Server instance. (input) args_array -> Dictionary of command line options. (input) outdata -> Dictionary of performance data. (input) mode -> File write mode. (input) **kwargs: ofile -> file name - Name of output file. mail -> Mail instance. """ args_array = dict(args_array) outdata = dict(outdata) ofile = kwargs.get("ofile", None) mail = kwargs.get("mail", None) pdata = "" for key, value in outdata.items(): pdata += "{}: {}".format(key, value) + "\n" if not args_array.get("-z", False): print("\nDatabase Status Check for Server: %s" % (server.name)) gen_libs.prt_msg("Uptime (days)", server.days_up, 0) gen_libs.prt_msg("Memory", "", 0) gen_libs.prt_msg("Max Mem", server.max_mem_mb, 1) gen_libs.prt_msg("Current Mem", server.cur_mem_mb, 1) gen_libs.prt_msg("Percent Used", server.prct_mem, 1) gen_libs.prt_msg("Connections", "", 0) gen_libs.prt_msg("Max Connections", server.max_conn, 1) gen_libs.prt_msg("Current Connections", server.cur_conn, 1) gen_libs.prt_msg("Percent Used", server.prct_conn, 1) if ofile: gen_libs.write_file(ofile, mode, pdata) if mail: mail.add_2_msg(pdata) mail.send_mail(use_mailx=args_array.get("-u", False))