code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # It's only just begun... # Current status: completely unusable, try the fence_cxs.py script for the moment. This Red # Hat compatible version is just in its' infancy. # Copyright 2011 Matt Clark # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com from fencing import * import XenAPI EC_BAD_SESSION = 1 # Find the status of the port given in the -u flag of options. def get_power_fn(session, options): uuid = options["-u"].lower() try: # Get a reference to the vm specified in the UUID parameter vm = session.xenapi.VM.get_by_uuid(uuid) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): status = record["power_state"] print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"] # Note that the VM can be in the following states (from the XenAPI document) # Halted: VM is offline and not using any resources. # Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running # Running: Running # Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-use while # We want to make sure that we only return the status "off" if the machine is actually halted as the status # is checked before a fencing action. Only when the machine is Halted is it not consuming resources which # may include whatever you are trying to protect with this fencing action. return (status=="Halted" and "off" or "on") except Exception, exn: print str(exn) return "Error" # Set the state of the port given in the -u flag of options. def set_power_fn(session, options): uuid = options["-u"].lower() action = options["-o"].lower() try: # Get a reference to the vm specified in the UUID parameter vm = session.xenapi.VM.get_by_uuid(uuid) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm) # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): # Start the VM session.xenapi.VM.start(vm, False, True) elif( action == "off" ): # Force shutdown the VM session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): # Force reboot the VM session.xenapi.VM.hard_reboot(vm) except Exception, exn: print str(exn); # Function to populate an array of virtual machines and their status def get_outlet_list(session, options): result = {} try: # Return an array of all the VM's on the host vms = session.xenapi.VM.get_all() for vm in vms: # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] uuid = record["uuid"] status = record["power_state"] result[uuid] = (name, status) print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); return result # Function to initiate the XenServer session via the XenAPI library. def connect_and_login(options): url = options["-s"] username = options["-l"] password = options["-p"] try: # Create the XML RPC session to the specified URL. session = XenAPI.Session(url); # Login using the supplied credentials. session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); # http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity # the exit value should be 1. It doesn't say anything about failed logins, so # until I hear otherwise it is best to keep this exit the same to make sure that # anything calling this script (that uses the same information in the web page # above) knows that this is an error condition, not a msg signifying a down port. sys.exit(EC_BAD_SESSION); return session; def main(): device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action", "login", "passwd", "passwd_script", "test", "separator", "no_login", "no_password", "power_timeout", "shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ] atexit.register(atexit_handler) options=process_input(device_opt) options = check_input(device_opt, options) docs = { } docs["shortdesc"] = "Fence agent for Citrix XenServer" docs["longdesc"] = "fence_cxs_redhat" show_docs(options, docs) xenSession = connect_and_login(options) # Operate the fencing device result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list) sys.exit(result) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, getopt, time, os import pexpect, re import telnetlib import atexit import __main__ ## do not add code here. #BEGIN_VERSION_GENERATION RELEASE_VERSION="3.0.17" BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)" REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved." #END_VERSION_GENERATION LOG_MODE_VERBOSE = 100 LOG_MODE_QUIET = 0 EC_GENERIC_ERROR = 1 EC_BAD_ARGS = 2 EC_LOGIN_DENIED = 3 EC_CONNECTION_LOST = 4 EC_TIMED_OUT = 5 EC_WAITING_ON = 6 EC_WAITING_OFF = 7 EC_STATUS = 8 EC_STATUS_HMC = 9 TELNET_PATH = "/usr/bin/telnet" SSH_PATH = "/usr/bin/ssh" SSL_PATH = "/usr/sbin/fence_nss_wrapper" all_opt = { "help" : { "getopt" : "h", "longopt" : "help", "help" : "-h, --help Display this help and exit", "required" : "0", "shortdesc" : "Display help and exit", "order" : 54 }, "version" : { "getopt" : "V", "longopt" : "version", "help" : "-V, --version Output version information and exit", "required" : "0", "shortdesc" : "Display version information and exit", "order" : 53 }, "quiet" : { "getopt" : "q", "help" : "", "order" : 50 }, "verbose" : { "getopt" : "v", "longopt" : "verbose", "help" : "-v, --verbose Verbose mode", "required" : "0", "shortdesc" : "Verbose mode", "order" : 51 }, "debug" : { "getopt" : "D:", "longopt" : "debug-file", "help" : "-D, --debug-file=<debugfile> Debugging to output file", "required" : "0", "shortdesc" : "Write debug information to given file", "order" : 52 }, "delay" : { "getopt" : "f:", "longopt" : "delay", "help" : "--delay <seconds> Wait X seconds before fencing is started", "required" : "0", "shortdesc" : "Wait X seconds before fencing is started", "default" : "0", "order" : 200 }, "agent" : { "getopt" : "", "help" : "", "order" : 1 }, "web" : { "getopt" : "", "help" : "", "order" : 1 }, "action" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, reboot (default), off or on", "required" : "1", "shortdesc" : "Fencing Action", "default" : "reboot", "order" : 1 }, "io_fencing" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, enable or disable", "required" : "1", "shortdesc" : "Fencing Action", "default" : "disable", "order" : 1 }, "ipaddr" : { "getopt" : "a:", "longopt" : "ip", "help" : "-a, --ip=<ip> IP address or hostname of fencing device", "required" : "1", "shortdesc" : "IP Address or Hostname", "order" : 1 }, "ipport" : { "getopt" : "u:", "longopt" : "ipport", "help" : "-u, --ipport=<port> TCP port to use", "required" : "0", "shortdesc" : "TCP port to use for connection with device", "order" : 1 }, "login" : { "getopt" : "l:", "longopt" : "username", "help" : "-l, --username=<name> Login name", "required" : "?", "shortdesc" : "Login Name", "order" : 1 }, "no_login" : { "getopt" : "", "help" : "", "order" : 1 }, "no_password" : { "getopt" : "", "help" : "", "order" : 1 }, "passwd" : { "getopt" : "p:", "longopt" : "password", "help" : "-p, --password=<password> Login password or passphrase", "required" : "0", "shortdesc" : "Login password or passphrase", "order" : 1 }, "passwd_script" : { "getopt" : "S:", "longopt" : "password-script=", "help" : "-S, --password-script=<script> Script to run to retrieve password", "required" : "0", "shortdesc" : "Script to retrieve password", "order" : 1 }, "identity_file" : { "getopt" : "k:", "longopt" : "identity-file", "help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ", "required" : "0", "shortdesc" : "Identity file for ssh", "order" : 1 }, "module_name" : { "getopt" : "m:", "longopt" : "module-name", "help" : "-m, --module-name=<module> DRAC/MC module name", "required" : "0", "shortdesc" : "DRAC/MC module name", "order" : 1 }, "drac_version" : { "getopt" : "d:", "longopt" : "drac-version", "help" : "-d, --drac-version=<version> Force DRAC version to use", "required" : "0", "shortdesc" : "Force DRAC version to use", "order" : 1 }, "hmc_version" : { "getopt" : "H:", "longopt" : "hmc-version", "help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)", "required" : "0", "shortdesc" : "Force HMC version to use (3 or 4)", "default" : "4", "order" : 1 }, "ribcl" : { "getopt" : "r:", "longopt" : "ribcl-version", "help" : "-r, --ribcl-version=<version> Force ribcl version to use", "required" : "0", "shortdesc" : "Force ribcl version to use", "order" : 1 }, "login_eol_lf" : { "getopt" : "", "help" : "", "order" : 1 }, "cmd_prompt" : { "getopt" : "c:", "longopt" : "command-prompt", "help" : "-c, --command-prompt=<prompt> Force command prompt", "shortdesc" : "Force command prompt", "required" : "0", "order" : 1 }, "secure" : { "getopt" : "x", "longopt" : "ssh", "help" : "-x, --ssh Use ssh connection", "shortdesc" : "SSH connection", "required" : "0", "order" : 1 }, "ssl" : { "getopt" : "z", "longopt" : "ssl", "help" : "-z, --ssl Use ssl connection", "required" : "0", "shortdesc" : "SSL connection", "order" : 1 }, "port" : { "getopt" : "n:", "longopt" : "plug", "help" : "-n, --plug=<id> Physical plug number on device or\n" + " name of virtual machine", "required" : "1", "shortdesc" : "Physical plug number or name of virtual machine", "order" : 1 }, "switch" : { "getopt" : "s:", "longopt" : "switch", "help" : "-s, --switch=<id> Physical switch number on device", "required" : "0", "shortdesc" : "Physical switch number on device", "order" : 1 }, "partition" : { "getopt" : "n:", "help" : "-n <id> Name of the partition", "required" : "0", "shortdesc" : "Partition name", "order" : 1 }, "managed" : { "getopt" : "s:", "help" : "-s <id> Name of the managed system", "required" : "0", "shortdesc" : "Managed system name", "order" : 1 }, "test" : { "getopt" : "T", "help" : "", "order" : 1, "obsolete" : "use -o status instead" }, "exec" : { "getopt" : "e:", "longopt" : "exec", "help" : "-e, --exec=<command> Command to execute", "required" : "0", "shortdesc" : "Command to execute", "order" : 1 }, "vmware_type" : { "getopt" : "d:", "longopt" : "vmware_type", "help" : "-d, --vmware_type=<type> Type of VMware to connect", "required" : "0", "shortdesc" : "Type of VMware to connect", "order" : 1 }, "vmware_datacenter" : { "getopt" : "s:", "longopt" : "vmware-datacenter", "help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter", "required" : "0", "shortdesc" : "Show only machines in specified datacenter", "order" : 2 }, "snmp_version" : { "getopt" : "d:", "longopt" : "snmp-version", "help" : "-d, --snmp-version=<ver> Specifies SNMP version to use", "required" : "0", "shortdesc" : "Specifies SNMP version to use (1,2c,3)", "order" : 1 }, "community" : { "getopt" : "c:", "longopt" : "community", "help" : "-c, --community=<community> Set the community string", "required" : "0", "shortdesc" : "Set the community string", "order" : 1}, "snmp_auth_prot" : { "getopt" : "b:", "longopt" : "snmp-auth-prot", "help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)", "required" : "0", "shortdesc" : "Set authentication protocol (MD5|SHA)", "order" : 1}, "snmp_sec_level" : { "getopt" : "E:", "longopt" : "snmp-sec-level", "help" : "-E, --snmp-sec-level=<level> Set security level\n"+ " (noAuthNoPriv|authNoPriv|authPriv)", "required" : "0", "shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)", "order" : 1}, "snmp_priv_prot" : { "getopt" : "B:", "longopt" : "snmp-priv-prot", "help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)", "required" : "0", "shortdesc" : "Set privacy protocol (DES|AES)", "order" : 1}, "snmp_priv_passwd" : { "getopt" : "P:", "longopt" : "snmp-priv-passwd", "help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password", "required" : "0", "shortdesc" : "Set privacy protocol password", "order" : 1}, "snmp_priv_passwd_script" : { "getopt" : "R:", "longopt" : "snmp-priv-passwd-script", "help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password", "required" : "0", "shortdesc" : "Script to run to retrieve privacy password", "order" : 1}, "inet4_only" : { "getopt" : "4", "longopt" : "inet4-only", "help" : "-4, --inet4-only Forces agent to use IPv4 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv4 addresses only", "order" : 1 }, "inet6_only" : { "getopt" : "6", "longopt" : "inet6-only", "help" : "-6, --inet6-only Forces agent to use IPv6 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv6 addresses only", "order" : 1 }, "udpport" : { "getopt" : "u:", "longopt" : "udpport", "help" : "-u, --udpport UDP/TCP port to use", "required" : "0", "shortdesc" : "UDP/TCP port to use for connection with device", "order" : 1}, "separator" : { "getopt" : "C:", "longopt" : "separator", "help" : "-C, --separator=<char> Separator for CSV created by 'list' operation", "default" : ",", "required" : "0", "shortdesc" : "Separator for CSV created by operation list", "order" : 100 }, "login_timeout" : { "getopt" : "y:", "longopt" : "login-timeout", "help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login", "default" : "5", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after login", "order" : 200 }, "shell_timeout" : { "getopt" : "Y:", "longopt" : "shell-timeout", "help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command", "default" : "3", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after issuing command", "order" : 200 }, "power_timeout" : { "getopt" : "g:", "longopt" : "power-timeout", "help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF", "default" : "20", "required" : "0", "shortdesc" : "Test X seconds for status change after ON/OFF", "order" : 200 }, "power_wait" : { "getopt" : "G:", "longopt" : "power-wait", "help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF", "default" : "0", "required" : "0", "shortdesc" : "Wait X seconds after issuing ON/OFF", "order" : 200 }, "missing_as_off" : { "getopt" : "M", "longopt" : "missing-as-off", "help" : "--missing-as-off Missing port returns OFF instead of failure", "required" : "0", "shortdesc" : "Missing port returns OFF instead of failure", "order" : 200 }, "retry_on" : { "getopt" : "F:", "longopt" : "retry-on", "help" : "--retry-on <attempts> Count of attempts to retry power on", "default" : "1", "required" : "0", "shortdesc" : "Count of attempts to retry power on", "order" : 200 }, "session_url" : { "getopt" : "s:", "longopt" : "session-url", "help" : "-s, --session-url URL to connect to XenServer on.", "required" : "1", "shortdesc" : "The URL of the XenServer host.", "order" : 1}, "vm_name" : { "getopt" : "n:", "longopt" : "vm-name", "help" : "-n, --vm-name Name of the VM to fence.", "required" : "0", "shortdesc" : "The name of the virual machine to fence.", "order" : 1}, "uuid" : { "getopt" : "U:", "longopt" : "uuid", "help" : "-U, --uuid UUID of the VM to fence.", "required" : "0", "shortdesc" : "The UUID of the virtual machine to fence.", "order" : 1} } common_opt = [ "retry_on", "delay" ] class fspawn(pexpect.spawn): def log_expect(self, options, pattern, timeout): result = self.expect(pattern, timeout) if options["log"] >= LOG_MODE_VERBOSE: options["debug_fh"].write(self.before + self.after) return result def atexit_handler(): try: sys.stdout.close() os.close(1) except IOError: sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0])) sys.exit(EC_GENERIC_ERROR) def version(command, release, build_date, copyright_notice): print command, " ", release, " ", build_date if len(copyright_notice) > 0: print copyright_notice def fail_usage(message = ""): if len(message) > 0: sys.stderr.write(message+"\n") sys.stderr.write("Please use '-h' for usage\n") sys.exit(EC_GENERIC_ERROR) def fail(error_code): message = { EC_LOGIN_DENIED : "Unable to connect/login to fencing device", EC_CONNECTION_LOST : "Connection lost", EC_TIMED_OUT : "Connection timed out", EC_WAITING_ON : "Failed: Timed out waiting to power ON", EC_WAITING_OFF : "Failed: Timed out waiting to power OFF", EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available", EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used" }[error_code] + "\n" sys.stderr.write(message) sys.exit(EC_GENERIC_ERROR) def usage(avail_opt): global all_opt print "Usage:" print "\t" + os.path.basename(sys.argv[0]) + " [options]" print "Options:" sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) for key, value in sorted_list: if len(value["help"]) != 0: print " " + value["help"] def metadata(avail_opt, options, docs): global all_opt sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) print "<?xml version=\"1.0\" ?>" print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >" print "<longdesc>" + docs["longdesc"] + "</longdesc>" if docs.has_key("vendorurl"): print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>" print "<parameters>" for option, value in sorted_list: if all_opt[option].has_key("shortdesc"): print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">" default = "" if all_opt[option].has_key("default"): default = "default=\""+str(all_opt[option]["default"])+"\"" elif options.has_key("-" + all_opt[option]["getopt"][:-1]): if options["-" + all_opt[option]["getopt"][:-1]]: try: default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\"" except TypeError: ## @todo/@note: Currently there is no clean way how to handle lists ## we can create a string from it but we can't set it on command line default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\"" elif options.has_key("-" + all_opt[option]["getopt"]): default = "default=\"true\" " mixed = all_opt[option]["help"] ## split it between option and help text res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed) if (None != res): mixed = res.group(1) mixed = mixed.replace("<", "&lt;").replace(">", "&gt;") print "\t\t<getopt mixed=\"" + mixed + "\" />" if all_opt[option]["getopt"].count(":") > 0: print "\t\t<content type=\"string\" "+default+" />" else: print "\t\t<content type=\"boolean\" "+default+" />" print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>" print "\t</parameter>" print "</parameters>" print "<actions>" print "\t<action name=\"on\" />" print "\t<action name=\"off\" />" print "\t<action name=\"reboot\" />" print "\t<action name=\"status\" />" print "\t<action name=\"list\" />" print "\t<action name=\"monitor\" />" print "\t<action name=\"metadata\" />" print "</actions>" print "</resource-agent>" def process_input(avail_opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### avail_opt.extend(common_opt) ## ## Set standard environment ##### os.putenv("LANG", "C") os.putenv("LC_ALL", "C") ## ## Prepare list of options for getopt ##### getopt_string = "" longopt_list = [ ] for k in avail_opt: if all_opt.has_key(k): getopt_string += all_opt[k]["getopt"] else: fail_usage("Parse error: unknown option '"+k+"'") if all_opt.has_key(k) and all_opt[k].has_key("longopt"): if all_opt[k]["getopt"].endswith(":"): longopt_list.append(all_opt[k]["longopt"] + "=") else: longopt_list.append(all_opt[k]["longopt"]) ## Compatibility layer if avail_opt.count("module_name") == 1: getopt_string += "n:" longopt_list.append("plug=") ## ## Read options from command line or standard input ##### if len(sys.argv) > 1: try: opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list) except getopt.GetoptError, error: fail_usage("Parse error: " + error.msg) ## Transform longopt to short one which are used in fencing agents ##### old_opt = opt opt = { } for o in dict(old_opt).keys(): if o.startswith("--"): for x in all_opt.keys(): if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o: opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o] else: opt[o] = dict(old_opt)[o] ## Compatibility Layer ##### z = dict(opt) if z.has_key("-T") == 1: z["-o"] = "status" if z.has_key("-n") == 1: z["-m"] = z["-n"] opt = z ## ##### else: opt = { } name = "" for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] ## Compatibility Layer ###### if name == "blade": name = "port" elif name == "option": name = "action" elif name == "fm": name = "port" elif name == "hostname": name = "ipaddr" elif name == "modulename": name = "module_name" elif name == "action" and 1 == avail_opt.count("io_fencing"): name = "io_fencing" elif name == "port" and 1 == avail_opt.count("drac_version"): name = "module_name" ## ###### if avail_opt.count(name) == 0: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") continue if all_opt[name]["getopt"].endswith(":"): opt["-"+all_opt[name]["getopt"].rstrip(":")] = value elif ((value == "1") or (value.lower() == "yes")): opt["-"+all_opt[name]["getopt"]] = "1" return opt ## ## This function checks input and answers if we want to have same answers ## in each of the fencing agents. It looks for possible errors and run ## password script to set a correct password ###### def check_input(device_opt, opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### device_opt.extend([x for x in common_opt if device_opt.count(x) == 0]) options = dict(opt) options["device_opt"] = device_opt ## Set requirements that should be included in metadata ##### if device_opt.count("login") and device_opt.count("no_login") == 0: all_opt["login"]["required"] = "1" else: all_opt["login"]["required"] = "0" ## In special cases (show help, metadata or version) we don't need to check anything ##### if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"): return options; ## Set default values ##### for opt in device_opt: if all_opt[opt].has_key("default"): getopt = "-" + all_opt[opt]["getopt"].rstrip(":") if 0 == options.has_key(getopt): options[getopt] = all_opt[opt]["default"] options["-o"]=options["-o"].lower() if options.has_key("-v"): options["log"] = LOG_MODE_VERBOSE else: options["log"] = LOG_MODE_QUIET if 0 == device_opt.count("io_fencing"): if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") else: if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0): fail_usage("Failed: You have to set login name") if 0 == options.has_key("-a") and 0 == options.has_key("-s"): fail_usage("Failed: You have to enter fence address") if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"): if 0 == options.has_key("-n") and 0 == options.has_key("-U"): fail_usage("Failed: You must specify either UUID or VM name") if (device_opt.count("no_password") == 0): if 0 == device_opt.count("identity_file"): if 0 == (options.has_key("-p") or options.has_key("-S")): fail_usage("Failed: You have to enter password or password script") else: if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")): fail_usage("Failed: You have to enter password, password script or identity file") if 0 == options.has_key("-x") and 1 == options.has_key("-k"): fail_usage("Failed: You have to use identity file together with ssh connection (-x)") if 1 == options.has_key("-k"): if 0 == os.path.isfile(options["-k"]): fail_usage("Failed: Identity file " + options["-k"] + " does not exist") if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")): fail_usage("Failed: You have to enter plug number") if options.has_key("-S"): options["-p"] = os.popen(options["-S"]).read().rstrip() if options.has_key("-D"): try: options["debug_fh"] = file (options["-D"], "w") except IOError: fail_usage("Failed: Unable to create file "+options["-D"]) if options.has_key("-v") and options.has_key("debug_fh") == 0: options["debug_fh"] = sys.stderr if options.has_key("-R"): options["-P"] = os.popen(options["-R"]).read().rstrip() if options.has_key("-u") == False: if options.has_key("-x"): options["-u"] = 22 elif options.has_key("-z"): options["-u"] = 443 elif device_opt.count("web"): options["-u"] = 80 else: options["-u"] = 23 return options def wait_power_status(tn, options, get_power_fn): for dummy in xrange(int(options["-g"])): if get_power_fn(tn, options) != options["-o"]: time.sleep(1) else: return 1 return 0 def show_docs(options, docs = None): device_opt = options["device_opt"] if docs == None: docs = { } docs["shortdesc"] = "Fence agent" docs["longdesc"] = "" ## Process special options (and exit) ##### if options.has_key("-h"): usage(device_opt) sys.exit(0) if options.has_key("-o") and options["-o"].lower() == "metadata": metadata(device_opt, options, docs) sys.exit(0) if options.has_key("-V"): print __main__.RELEASE_VERSION, __main__.BUILD_DATE print __main__.REDHAT_COPYRIGHT sys.exit(0) def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None): result = 0 ## Process options that manipulate fencing device ##### if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")): print "N/A" return elif (options["-o"] == "list" and get_outlet_list == None): ## @todo: exception? ## This is just temporal solution, we will remove default value ## None as soon as all existing agent will support this operation print "NOTICE: List option is not working on this device yet" return elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")): outlets = get_outlet_list(tn, options) ## keys can be numbers (port numbers) or strings (names of VM) for o in outlets.keys(): (alias, status) = outlets[o] if options["-o"] != "monitor": print o + options["-C"] + alias return if options["-o"] in ["off", "reboot"]: time.sleep(int(options["-f"])) status = get_power_fn(tn, options) if status != "on" and status != "off": fail(EC_STATUS) if options["-o"] == "enable": options["-o"] = "on" if options["-o"] == "disable": options["-o"] = "off" if options["-o"] == "on": if status == "on": print "Success: Already ON" else: power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): power_on = True break if power_on: print "Success: Powered ON" else: fail(EC_WAITING_ON) elif options["-o"] == "off": if status == "off": print "Success: Already OFF" else: set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): print "Success: Powered OFF" else: fail(EC_WAITING_OFF) elif options["-o"] == "reboot": if status != "off": options["-o"] = "off" set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 0: fail(EC_WAITING_OFF) options["-o"] = "on" power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 1: power_on = True break if power_on == False: # this should not fail as not was fenced succesfully sys.stderr.write('Timed out waiting to power ON\n') print "Success: Rebooted" elif options["-o"] == "status": print "Status: " + status.upper() if status.upper() == "OFF": result = 2 elif options["-o"] == "monitor": 1 return result def fence_login(options): force_ipvx="" if (options.has_key("-6")): force_ipvx="-6 " if (options.has_key("-4")): force_ipvx="-4 " if (options["device_opt"].count("login_eol_lf")): login_eol = "\n" else: login_eol = "\r\n" try: re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE) re_pass = re.compile("password", re.IGNORECASE) if options.has_key("-z"): command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"]) try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: ## SSL telnet is part of the fencing package sys.stderr.write(str(ex) + "\n") sys.exit(EC_GENERIC_ERROR) elif options.has_key("-x") and 0 == options.has_key("-k"): command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) if options.has_key("telnet_over_ssh"): #This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt) result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") # Host identity confirm conn.log_expect(options, re_login, int(options["-y"])) conn.sendline(options["-l"]) conn.log_expect(options, re_pass, int(options["-y"])) else: result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, "ssword:", int(options["-y"])) conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) elif options.has_key("-x") and 1 == options.has_key("-k"): command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"])) if result != 0: if options.has_key("-p"): conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) else: fail_usage("Failed: You have to enter passphrase (-p) for identity file") else: try: conn = fspawn(TELNET_PATH) conn.send("set binary\n") conn.send("open %s -%s\n"%(options["-a"], options["-u"])) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) conn.log_expect(options, re_login, int(options["-y"])) conn.send(options["-l"] + login_eol) conn.log_expect(options, re_pass, int(options["-Y"])) conn.send(options["-p"] + login_eol) conn.log_expect(options, options["-c"], int(options["-Y"])) except pexpect.EOF: fail(EC_LOGIN_DENIED) except pexpect.TIMEOUT: fail(EC_LOGIN_DENIED) return conn
Python
#!/usr/bin/python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# ############################################################################# # It's only just begun... # Current status: completely usable. This script is now working well and, # has a lot of functionality as a result of the fencing.py library and the # XenAPI libary. ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com from fencing import * import XenAPI EC_BAD_SESSION = 1 # Find the status of the port given in the -U flag of options. def get_power_fn(session, options): if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): status = record["power_state"] if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"] # Note that the VM can be in the following states (from the XenAPI document) # Halted: VM is offline and not using any resources. # Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running # Running: Running # Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while # We want to make sure that we only return the status "off" if the machine is actually halted as the status # is checked before a fencing action. Only when the machine is Halted is it not consuming resources which # may include whatever you are trying to protect with this fencing action. return (status=="Halted" and "off" or "on") except Exception, exn: print str(exn) return "Error" # Set the state of the port given in the -U flag of options. def set_power_fn(session, options): action = options["-o"].lower() if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm) # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): # Start the VM session.xenapi.VM.start(vm, False, True) elif( action == "off" ): # Force shutdown the VM session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): # Force reboot the VM session.xenapi.VM.hard_reboot(vm) except Exception, exn: print str(exn); # Function to populate an array of virtual machines and their status def get_outlet_list(session, options): result = {} if options.has_key("-v"): verbose = True else: verbose = False try: # Return an array of all the VM's on the host vms = session.xenapi.VM.get_all() for vm in vms: # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] uuid = record["uuid"] status = record["power_state"] result[uuid] = (name, status) if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); return result # Function to initiate the XenServer session via the XenAPI library. def connect_and_login(options): url = options["-s"] username = options["-l"] password = options["-p"] try: # Create the XML RPC session to the specified URL. session = XenAPI.Session(url); # Login using the supplied credentials. session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); # http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity # the exit value should be 1. It doesn't say anything about failed logins, so # until I hear otherwise it is best to keep this exit the same to make sure that # anything calling this script (that uses the same information in the web page # above) knows that this is an error condition, not a msg signifying a down port. sys.exit(EC_BAD_SESSION); return session; # return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then # this is tried first as this is the only properly unique identifier. # Exceptions are not handled in this function, code that calls this must be ready to handle them. def return_vm_reference(session, options): if options.has_key("-v"): verbose = True else: verbose = False # Case where the UUID has been specified if options.has_key("-U"): uuid = options["-U"].lower() # When using the -n parameter for name, we get an error message (in verbose # mode) that tells us that we didn't find a VM. To immitate that here we # need to catch and re-raise the exception produced by get_by_uuid. try: return session.xenapi.VM.get_by_uuid(uuid) except Exception,exn: if verbose: print "No VM's found with a UUID of \"%s\"" %uuid raise # Case where the vm_name has been specified if options.has_key("-n"): vm_name = options["-n"] vm_arr = session.xenapi.VM.get_by_name_label(vm_name) # Need to make sure that we only have one result as the vm_name may # not be unique. Average case, so do it first. if len(vm_arr) == 1: return vm_arr[0] else: if len(vm_arr) == 0: if verbose: print "No VM's found with a name of \"%s\"" %vm_name # NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find # a VM with the specified UUID. This should make the output look fairly # consistent. raise Exception("NAME_INVALID") else: if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name raise Exception("MULTIPLE_VMS_FOUND") # We should never get to this case as the input processing checks that either the UUID or # the name parameter is set. Regardless of whether or not a VM is found the above if # statements will return to the calling function (either by exception or by a reference # to the VM). raise Exception("VM_LOGIC_ERROR") def main(): device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action", "login", "passwd", "passwd_script", "vm_name", "test", "separator", "no_login", "no_password", "power_timeout", "shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ] atexit.register(atexit_handler) options=process_input(device_opt) options = check_input(device_opt, options) docs = { } docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines." docs["longdesc"] = "\ fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \ It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \ to a XenServer host. Once the session is established, further XML-RPC \ commands are issued in order to switch on, switch off, restart and query \ the status of virtual machines running on the host." show_docs(options, docs) xenSession = connect_and_login(options) # Operate the fencing device result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list) sys.exit(result) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, getopt, time, os import pexpect, re import telnetlib import atexit import __main__ ## do not add code here. #BEGIN_VERSION_GENERATION RELEASE_VERSION="3.0.17" BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)" REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved." #END_VERSION_GENERATION LOG_MODE_VERBOSE = 100 LOG_MODE_QUIET = 0 EC_GENERIC_ERROR = 1 EC_BAD_ARGS = 2 EC_LOGIN_DENIED = 3 EC_CONNECTION_LOST = 4 EC_TIMED_OUT = 5 EC_WAITING_ON = 6 EC_WAITING_OFF = 7 EC_STATUS = 8 EC_STATUS_HMC = 9 TELNET_PATH = "/usr/bin/telnet" SSH_PATH = "/usr/bin/ssh" SSL_PATH = "/usr/sbin/fence_nss_wrapper" all_opt = { "help" : { "getopt" : "h", "longopt" : "help", "help" : "-h, --help Display this help and exit", "required" : "0", "shortdesc" : "Display help and exit", "order" : 54 }, "version" : { "getopt" : "V", "longopt" : "version", "help" : "-V, --version Output version information and exit", "required" : "0", "shortdesc" : "Display version information and exit", "order" : 53 }, "quiet" : { "getopt" : "q", "help" : "", "order" : 50 }, "verbose" : { "getopt" : "v", "longopt" : "verbose", "help" : "-v, --verbose Verbose mode", "required" : "0", "shortdesc" : "Verbose mode", "order" : 51 }, "debug" : { "getopt" : "D:", "longopt" : "debug-file", "help" : "-D, --debug-file=<debugfile> Debugging to output file", "required" : "0", "shortdesc" : "Write debug information to given file", "order" : 52 }, "delay" : { "getopt" : "f:", "longopt" : "delay", "help" : "--delay <seconds> Wait X seconds before fencing is started", "required" : "0", "shortdesc" : "Wait X seconds before fencing is started", "default" : "0", "order" : 200 }, "agent" : { "getopt" : "", "help" : "", "order" : 1 }, "web" : { "getopt" : "", "help" : "", "order" : 1 }, "action" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, reboot (default), off or on", "required" : "1", "shortdesc" : "Fencing Action", "default" : "reboot", "order" : 1 }, "io_fencing" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, enable or disable", "required" : "1", "shortdesc" : "Fencing Action", "default" : "disable", "order" : 1 }, "ipaddr" : { "getopt" : "a:", "longopt" : "ip", "help" : "-a, --ip=<ip> IP address or hostname of fencing device", "required" : "1", "shortdesc" : "IP Address or Hostname", "order" : 1 }, "ipport" : { "getopt" : "u:", "longopt" : "ipport", "help" : "-u, --ipport=<port> TCP port to use", "required" : "0", "shortdesc" : "TCP port to use for connection with device", "order" : 1 }, "login" : { "getopt" : "l:", "longopt" : "username", "help" : "-l, --username=<name> Login name", "required" : "?", "shortdesc" : "Login Name", "order" : 1 }, "no_login" : { "getopt" : "", "help" : "", "order" : 1 }, "no_password" : { "getopt" : "", "help" : "", "order" : 1 }, "passwd" : { "getopt" : "p:", "longopt" : "password", "help" : "-p, --password=<password> Login password or passphrase", "required" : "0", "shortdesc" : "Login password or passphrase", "order" : 1 }, "passwd_script" : { "getopt" : "S:", "longopt" : "password-script=", "help" : "-S, --password-script=<script> Script to run to retrieve password", "required" : "0", "shortdesc" : "Script to retrieve password", "order" : 1 }, "identity_file" : { "getopt" : "k:", "longopt" : "identity-file", "help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ", "required" : "0", "shortdesc" : "Identity file for ssh", "order" : 1 }, "module_name" : { "getopt" : "m:", "longopt" : "module-name", "help" : "-m, --module-name=<module> DRAC/MC module name", "required" : "0", "shortdesc" : "DRAC/MC module name", "order" : 1 }, "drac_version" : { "getopt" : "d:", "longopt" : "drac-version", "help" : "-d, --drac-version=<version> Force DRAC version to use", "required" : "0", "shortdesc" : "Force DRAC version to use", "order" : 1 }, "hmc_version" : { "getopt" : "H:", "longopt" : "hmc-version", "help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)", "required" : "0", "shortdesc" : "Force HMC version to use (3 or 4)", "default" : "4", "order" : 1 }, "ribcl" : { "getopt" : "r:", "longopt" : "ribcl-version", "help" : "-r, --ribcl-version=<version> Force ribcl version to use", "required" : "0", "shortdesc" : "Force ribcl version to use", "order" : 1 }, "login_eol_lf" : { "getopt" : "", "help" : "", "order" : 1 }, "cmd_prompt" : { "getopt" : "c:", "longopt" : "command-prompt", "help" : "-c, --command-prompt=<prompt> Force command prompt", "shortdesc" : "Force command prompt", "required" : "0", "order" : 1 }, "secure" : { "getopt" : "x", "longopt" : "ssh", "help" : "-x, --ssh Use ssh connection", "shortdesc" : "SSH connection", "required" : "0", "order" : 1 }, "ssl" : { "getopt" : "z", "longopt" : "ssl", "help" : "-z, --ssl Use ssl connection", "required" : "0", "shortdesc" : "SSL connection", "order" : 1 }, "port" : { "getopt" : "n:", "longopt" : "plug", "help" : "-n, --plug=<id> Physical plug number on device or\n" + " name of virtual machine", "required" : "1", "shortdesc" : "Physical plug number or name of virtual machine", "order" : 1 }, "switch" : { "getopt" : "s:", "longopt" : "switch", "help" : "-s, --switch=<id> Physical switch number on device", "required" : "0", "shortdesc" : "Physical switch number on device", "order" : 1 }, "partition" : { "getopt" : "n:", "help" : "-n <id> Name of the partition", "required" : "0", "shortdesc" : "Partition name", "order" : 1 }, "managed" : { "getopt" : "s:", "help" : "-s <id> Name of the managed system", "required" : "0", "shortdesc" : "Managed system name", "order" : 1 }, "test" : { "getopt" : "T", "help" : "", "order" : 1, "obsolete" : "use -o status instead" }, "exec" : { "getopt" : "e:", "longopt" : "exec", "help" : "-e, --exec=<command> Command to execute", "required" : "0", "shortdesc" : "Command to execute", "order" : 1 }, "vmware_type" : { "getopt" : "d:", "longopt" : "vmware_type", "help" : "-d, --vmware_type=<type> Type of VMware to connect", "required" : "0", "shortdesc" : "Type of VMware to connect", "order" : 1 }, "vmware_datacenter" : { "getopt" : "s:", "longopt" : "vmware-datacenter", "help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter", "required" : "0", "shortdesc" : "Show only machines in specified datacenter", "order" : 2 }, "snmp_version" : { "getopt" : "d:", "longopt" : "snmp-version", "help" : "-d, --snmp-version=<ver> Specifies SNMP version to use", "required" : "0", "shortdesc" : "Specifies SNMP version to use (1,2c,3)", "order" : 1 }, "community" : { "getopt" : "c:", "longopt" : "community", "help" : "-c, --community=<community> Set the community string", "required" : "0", "shortdesc" : "Set the community string", "order" : 1}, "snmp_auth_prot" : { "getopt" : "b:", "longopt" : "snmp-auth-prot", "help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)", "required" : "0", "shortdesc" : "Set authentication protocol (MD5|SHA)", "order" : 1}, "snmp_sec_level" : { "getopt" : "E:", "longopt" : "snmp-sec-level", "help" : "-E, --snmp-sec-level=<level> Set security level\n"+ " (noAuthNoPriv|authNoPriv|authPriv)", "required" : "0", "shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)", "order" : 1}, "snmp_priv_prot" : { "getopt" : "B:", "longopt" : "snmp-priv-prot", "help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)", "required" : "0", "shortdesc" : "Set privacy protocol (DES|AES)", "order" : 1}, "snmp_priv_passwd" : { "getopt" : "P:", "longopt" : "snmp-priv-passwd", "help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password", "required" : "0", "shortdesc" : "Set privacy protocol password", "order" : 1}, "snmp_priv_passwd_script" : { "getopt" : "R:", "longopt" : "snmp-priv-passwd-script", "help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password", "required" : "0", "shortdesc" : "Script to run to retrieve privacy password", "order" : 1}, "inet4_only" : { "getopt" : "4", "longopt" : "inet4-only", "help" : "-4, --inet4-only Forces agent to use IPv4 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv4 addresses only", "order" : 1 }, "inet6_only" : { "getopt" : "6", "longopt" : "inet6-only", "help" : "-6, --inet6-only Forces agent to use IPv6 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv6 addresses only", "order" : 1 }, "udpport" : { "getopt" : "u:", "longopt" : "udpport", "help" : "-u, --udpport UDP/TCP port to use", "required" : "0", "shortdesc" : "UDP/TCP port to use for connection with device", "order" : 1}, "separator" : { "getopt" : "C:", "longopt" : "separator", "help" : "-C, --separator=<char> Separator for CSV created by 'list' operation", "default" : ",", "required" : "0", "shortdesc" : "Separator for CSV created by operation list", "order" : 100 }, "login_timeout" : { "getopt" : "y:", "longopt" : "login-timeout", "help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login", "default" : "5", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after login", "order" : 200 }, "shell_timeout" : { "getopt" : "Y:", "longopt" : "shell-timeout", "help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command", "default" : "3", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after issuing command", "order" : 200 }, "power_timeout" : { "getopt" : "g:", "longopt" : "power-timeout", "help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF", "default" : "20", "required" : "0", "shortdesc" : "Test X seconds for status change after ON/OFF", "order" : 200 }, "power_wait" : { "getopt" : "G:", "longopt" : "power-wait", "help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF", "default" : "0", "required" : "0", "shortdesc" : "Wait X seconds after issuing ON/OFF", "order" : 200 }, "missing_as_off" : { "getopt" : "M", "longopt" : "missing-as-off", "help" : "--missing-as-off Missing port returns OFF instead of failure", "required" : "0", "shortdesc" : "Missing port returns OFF instead of failure", "order" : 200 }, "retry_on" : { "getopt" : "F:", "longopt" : "retry-on", "help" : "--retry-on <attempts> Count of attempts to retry power on", "default" : "1", "required" : "0", "shortdesc" : "Count of attempts to retry power on", "order" : 200 }, "session_url" : { "getopt" : "s:", "longopt" : "session-url", "help" : "-s, --session-url URL to connect to XenServer on.", "required" : "1", "shortdesc" : "The URL of the XenServer host.", "order" : 1}, "vm_name" : { "getopt" : "n:", "longopt" : "vm-name", "help" : "-n, --vm-name Name of the VM to fence.", "required" : "0", "shortdesc" : "The name of the virual machine to fence.", "order" : 1}, "uuid" : { "getopt" : "U:", "longopt" : "uuid", "help" : "-U, --uuid UUID of the VM to fence.", "required" : "0", "shortdesc" : "The UUID of the virtual machine to fence.", "order" : 1} } common_opt = [ "retry_on", "delay" ] class fspawn(pexpect.spawn): def log_expect(self, options, pattern, timeout): result = self.expect(pattern, timeout) if options["log"] >= LOG_MODE_VERBOSE: options["debug_fh"].write(self.before + self.after) return result def atexit_handler(): try: sys.stdout.close() os.close(1) except IOError: sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0])) sys.exit(EC_GENERIC_ERROR) def version(command, release, build_date, copyright_notice): print command, " ", release, " ", build_date if len(copyright_notice) > 0: print copyright_notice def fail_usage(message = ""): if len(message) > 0: sys.stderr.write(message+"\n") sys.stderr.write("Please use '-h' for usage\n") sys.exit(EC_GENERIC_ERROR) def fail(error_code): message = { EC_LOGIN_DENIED : "Unable to connect/login to fencing device", EC_CONNECTION_LOST : "Connection lost", EC_TIMED_OUT : "Connection timed out", EC_WAITING_ON : "Failed: Timed out waiting to power ON", EC_WAITING_OFF : "Failed: Timed out waiting to power OFF", EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available", EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used" }[error_code] + "\n" sys.stderr.write(message) sys.exit(EC_GENERIC_ERROR) def usage(avail_opt): global all_opt print "Usage:" print "\t" + os.path.basename(sys.argv[0]) + " [options]" print "Options:" sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) for key, value in sorted_list: if len(value["help"]) != 0: print " " + value["help"] def metadata(avail_opt, options, docs): global all_opt sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) print "<?xml version=\"1.0\" ?>" print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >" print "<longdesc>" + docs["longdesc"] + "</longdesc>" if docs.has_key("vendorurl"): print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>" print "<parameters>" for option, value in sorted_list: if all_opt[option].has_key("shortdesc"): print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">" default = "" if all_opt[option].has_key("default"): default = "default=\""+str(all_opt[option]["default"])+"\"" elif options.has_key("-" + all_opt[option]["getopt"][:-1]): if options["-" + all_opt[option]["getopt"][:-1]]: try: default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\"" except TypeError: ## @todo/@note: Currently there is no clean way how to handle lists ## we can create a string from it but we can't set it on command line default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\"" elif options.has_key("-" + all_opt[option]["getopt"]): default = "default=\"true\" " mixed = all_opt[option]["help"] ## split it between option and help text res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed) if (None != res): mixed = res.group(1) mixed = mixed.replace("<", "&lt;").replace(">", "&gt;") print "\t\t<getopt mixed=\"" + mixed + "\" />" if all_opt[option]["getopt"].count(":") > 0: print "\t\t<content type=\"string\" "+default+" />" else: print "\t\t<content type=\"boolean\" "+default+" />" print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>" print "\t</parameter>" print "</parameters>" print "<actions>" print "\t<action name=\"on\" />" print "\t<action name=\"off\" />" print "\t<action name=\"reboot\" />" print "\t<action name=\"status\" />" print "\t<action name=\"list\" />" print "\t<action name=\"monitor\" />" print "\t<action name=\"metadata\" />" print "</actions>" print "</resource-agent>" def process_input(avail_opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### avail_opt.extend(common_opt) ## ## Set standard environment ##### os.putenv("LANG", "C") os.putenv("LC_ALL", "C") ## ## Prepare list of options for getopt ##### getopt_string = "" longopt_list = [ ] for k in avail_opt: if all_opt.has_key(k): getopt_string += all_opt[k]["getopt"] else: fail_usage("Parse error: unknown option '"+k+"'") if all_opt.has_key(k) and all_opt[k].has_key("longopt"): if all_opt[k]["getopt"].endswith(":"): longopt_list.append(all_opt[k]["longopt"] + "=") else: longopt_list.append(all_opt[k]["longopt"]) ## Compatibility layer if avail_opt.count("module_name") == 1: getopt_string += "n:" longopt_list.append("plug=") ## ## Read options from command line or standard input ##### if len(sys.argv) > 1: try: opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list) except getopt.GetoptError, error: fail_usage("Parse error: " + error.msg) ## Transform longopt to short one which are used in fencing agents ##### old_opt = opt opt = { } for o in dict(old_opt).keys(): if o.startswith("--"): for x in all_opt.keys(): if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o: opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o] else: opt[o] = dict(old_opt)[o] ## Compatibility Layer ##### z = dict(opt) if z.has_key("-T") == 1: z["-o"] = "status" if z.has_key("-n") == 1: z["-m"] = z["-n"] opt = z ## ##### else: opt = { } name = "" for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] ## Compatibility Layer ###### if name == "blade": name = "port" elif name == "option": name = "action" elif name == "fm": name = "port" elif name == "hostname": name = "ipaddr" elif name == "modulename": name = "module_name" elif name == "action" and 1 == avail_opt.count("io_fencing"): name = "io_fencing" elif name == "port" and 1 == avail_opt.count("drac_version"): name = "module_name" ## ###### if avail_opt.count(name) == 0: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") continue if all_opt[name]["getopt"].endswith(":"): opt["-"+all_opt[name]["getopt"].rstrip(":")] = value elif ((value == "1") or (value.lower() == "yes")): opt["-"+all_opt[name]["getopt"]] = "1" return opt ## ## This function checks input and answers if we want to have same answers ## in each of the fencing agents. It looks for possible errors and run ## password script to set a correct password ###### def check_input(device_opt, opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### device_opt.extend([x for x in common_opt if device_opt.count(x) == 0]) options = dict(opt) options["device_opt"] = device_opt ## Set requirements that should be included in metadata ##### if device_opt.count("login") and device_opt.count("no_login") == 0: all_opt["login"]["required"] = "1" else: all_opt["login"]["required"] = "0" ## In special cases (show help, metadata or version) we don't need to check anything ##### if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"): return options; ## Set default values ##### for opt in device_opt: if all_opt[opt].has_key("default"): getopt = "-" + all_opt[opt]["getopt"].rstrip(":") if 0 == options.has_key(getopt): options[getopt] = all_opt[opt]["default"] options["-o"]=options["-o"].lower() if options.has_key("-v"): options["log"] = LOG_MODE_VERBOSE else: options["log"] = LOG_MODE_QUIET if 0 == device_opt.count("io_fencing"): if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") else: if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0): fail_usage("Failed: You have to set login name") if 0 == options.has_key("-a") and 0 == options.has_key("-s"): fail_usage("Failed: You have to enter fence address") if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"): if 0 == options.has_key("-n") and 0 == options.has_key("-U"): fail_usage("Failed: You must specify either UUID or VM name") if (device_opt.count("no_password") == 0): if 0 == device_opt.count("identity_file"): if 0 == (options.has_key("-p") or options.has_key("-S")): fail_usage("Failed: You have to enter password or password script") else: if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")): fail_usage("Failed: You have to enter password, password script or identity file") if 0 == options.has_key("-x") and 1 == options.has_key("-k"): fail_usage("Failed: You have to use identity file together with ssh connection (-x)") if 1 == options.has_key("-k"): if 0 == os.path.isfile(options["-k"]): fail_usage("Failed: Identity file " + options["-k"] + " does not exist") if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")): fail_usage("Failed: You have to enter plug number") if options.has_key("-S"): options["-p"] = os.popen(options["-S"]).read().rstrip() if options.has_key("-D"): try: options["debug_fh"] = file (options["-D"], "w") except IOError: fail_usage("Failed: Unable to create file "+options["-D"]) if options.has_key("-v") and options.has_key("debug_fh") == 0: options["debug_fh"] = sys.stderr if options.has_key("-R"): options["-P"] = os.popen(options["-R"]).read().rstrip() if options.has_key("-u") == False: if options.has_key("-x"): options["-u"] = 22 elif options.has_key("-z"): options["-u"] = 443 elif device_opt.count("web"): options["-u"] = 80 else: options["-u"] = 23 return options def wait_power_status(tn, options, get_power_fn): for dummy in xrange(int(options["-g"])): if get_power_fn(tn, options) != options["-o"]: time.sleep(1) else: return 1 return 0 def show_docs(options, docs = None): device_opt = options["device_opt"] if docs == None: docs = { } docs["shortdesc"] = "Fence agent" docs["longdesc"] = "" ## Process special options (and exit) ##### if options.has_key("-h"): usage(device_opt) sys.exit(0) if options.has_key("-o") and options["-o"].lower() == "metadata": metadata(device_opt, options, docs) sys.exit(0) if options.has_key("-V"): print __main__.RELEASE_VERSION, __main__.BUILD_DATE print __main__.REDHAT_COPYRIGHT sys.exit(0) def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None): result = 0 ## Process options that manipulate fencing device ##### if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")): print "N/A" return elif (options["-o"] == "list" and get_outlet_list == None): ## @todo: exception? ## This is just temporal solution, we will remove default value ## None as soon as all existing agent will support this operation print "NOTICE: List option is not working on this device yet" return elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")): outlets = get_outlet_list(tn, options) ## keys can be numbers (port numbers) or strings (names of VM) for o in outlets.keys(): (alias, status) = outlets[o] if options["-o"] != "monitor": print o + options["-C"] + alias return if options["-o"] in ["off", "reboot"]: time.sleep(int(options["-f"])) status = get_power_fn(tn, options) if status != "on" and status != "off": fail(EC_STATUS) if options["-o"] == "enable": options["-o"] = "on" if options["-o"] == "disable": options["-o"] = "off" if options["-o"] == "on": if status == "on": print "Success: Already ON" else: power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): power_on = True break if power_on: print "Success: Powered ON" else: fail(EC_WAITING_ON) elif options["-o"] == "off": if status == "off": print "Success: Already OFF" else: set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): print "Success: Powered OFF" else: fail(EC_WAITING_OFF) elif options["-o"] == "reboot": if status != "off": options["-o"] = "off" set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 0: fail(EC_WAITING_OFF) options["-o"] = "on" power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 1: power_on = True break if power_on == False: # this should not fail as not was fenced succesfully sys.stderr.write('Timed out waiting to power ON\n') print "Success: Rebooted" elif options["-o"] == "status": print "Status: " + status.upper() if status.upper() == "OFF": result = 2 elif options["-o"] == "monitor": 1 return result def fence_login(options): force_ipvx="" if (options.has_key("-6")): force_ipvx="-6 " if (options.has_key("-4")): force_ipvx="-4 " if (options["device_opt"].count("login_eol_lf")): login_eol = "\n" else: login_eol = "\r\n" try: re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE) re_pass = re.compile("password", re.IGNORECASE) if options.has_key("-z"): command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"]) try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: ## SSL telnet is part of the fencing package sys.stderr.write(str(ex) + "\n") sys.exit(EC_GENERIC_ERROR) elif options.has_key("-x") and 0 == options.has_key("-k"): command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) if options.has_key("telnet_over_ssh"): #This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt) result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") # Host identity confirm conn.log_expect(options, re_login, int(options["-y"])) conn.sendline(options["-l"]) conn.log_expect(options, re_pass, int(options["-y"])) else: result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, "ssword:", int(options["-y"])) conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) elif options.has_key("-x") and 1 == options.has_key("-k"): command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"])) if result != 0: if options.has_key("-p"): conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) else: fail_usage("Failed: You have to enter passphrase (-p) for identity file") else: try: conn = fspawn(TELNET_PATH) conn.send("set binary\n") conn.send("open %s -%s\n"%(options["-a"], options["-u"])) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) conn.log_expect(options, re_login, int(options["-y"])) conn.send(options["-l"] + login_eol) conn.log_expect(options, re_pass, int(options["-Y"])) conn.send(options["-p"] + login_eol) conn.log_expect(options, options["-c"], int(options["-Y"])) except pexpect.EOF: fail(EC_LOGIN_DENIED) except pexpect.TIMEOUT: fail(EC_LOGIN_DENIED) return conn
Python
#!/usr/bin/env python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com import sys, string, getopt import XenAPI def usage(): print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]" print "Where:-" print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"." print " -h : Print this help message." print " -l : The username for the XenServer host." print " -p : The password for the XenServer host." print " -s : The URL of the web interface on the XenServer host." print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return" print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\"" print " then the UUID must be specified." # Process command line options and populate the config array def process_opts(): config = { "action" : "status", "session_url" : "", "session_user" : "", "session_pass" : "", "uuid" : "", "name" : "", "verbose" : False } # If we have at least one argument then we want to parse the command line using getopts if len(sys.argv) > 1: try: opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="]) except getopt.GetoptError, err: # We got an unrecognised option, so print he help message and exit print str(err) usage() sys.exit(1) for opt, arg in opts: if opt in ("-v", "--verbose"): config["verbose"] = True elif opt in ("-a", "--action"): config["action"] = clean_action(arg) elif opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-s", "--session-url"): config["session_url"] = arg elif opt in ("-l", "--login-name"): config["session_user"] = arg elif opt in ("-n", "--name"): config["name"] = arg elif opt in ("-p", "--password"): config["session_pass"] = arg elif opt in ("-U", "--uuid"): config["uuid"] = arg.lower() else: assert False, "unhandled option" # Otherwise process stdin for parameters. This is to handle the Red Hat clustering # mechanism where by fenced passes in name/value pairs instead of using command line # options. else: for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] name = clean_param_name(name) if name == "action": value = clean_action(value) if name in config: config[name] = value else: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ): print "You must specify the session url, username and password."; usage(); sys.exit(2); return config # why, well just to be nice. Given an action will return the corresponding # value that the rest of the script uses. def clean_action(action): if action.lower() in ("on", "poweron", "powerup"): return "on" elif action.lower() in ("off", "poweroff", "powerdown"): return "off" elif action.lower() in ("reboot", "reset", "restart"): return "reboot" elif action.lower() in ("status", "powerstatus", "list"): return "status" else: print "Bad action", action usage() exit(4) # why, well just to be nice. Given a parameter will return the corresponding # value that the rest of the script uses. def clean_param_name(name): if name.lower() in ("action", "operation", "op"): return "action" elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"): return "session_user" elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"): return "session_pass" elif name.lower() in ("session_url", "url", "session-url"): return "session_url" else: # we should never get here as getopt should handle the checking of this input. print "Bad parameter specified", name usage() exit(5) # Print the power status of a VM. If no UUID is given, then all VM's are queried def get_power_status(session, uuid = "", name = ""): try: # If the UUID hasn't been set, then output the status of all # valid virtual machines. if( len(uuid) > 0 ): vms = [session.xenapi.VM.get_by_uuid(uuid)] elif( len(name) > 0 ): vms = session.xenapi.VM.get_by_name_label(name) else: vms = session.xenapi.VM.get_all() for vm in vms: record = session.xenapi.VM.get_record(vm); # We only want to print out the status for actual virtual machines. The above get_all function # returns any templates and also the control domain. This is one of the reasons the process # takes such a long time to list all VM's. Hopefully there is a way to filter this in the # request packet in the future. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); def set_power_status(session, uuid, name, action): try: vm = None if( len(uuid) > 0 ): vm = session.xenapi.VM.get_by_uuid(uuid) elif( len(name) > 0 ): vm_arr = session.xenapi.VM.get_by_name_label(name) if( len(vm_arr) == 1 ): vm = vm_arr[0] else raise Exception("Multiple VM's have that name. Use UUID instead.") if( vm != None ): record = session.xenapi.VM.get_record(vm); if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): session.xenapi.VM.start(vm, False, True) elif( action == "off" ): session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): session.xenapi.VM.hard_reboot(vm) else: raise Exception("Bad power status"); except Exception, exn: print str(exn); def main(): config = process_opts(); session = session_start(config["session_url"]); session_login(session, config["session_user"], config["session_pass"]); if( config["action"] == "status" ): get_power_status(session, config["uuid"], config["name"]) else: if( config["verbose"] ): print "Power status before action" get_power_status(session, config["uuid"]) set_power_status(session, config["uuid"], config["name"], config["action"]) if( config["verbose"] ): print "Power status after action" get_power_status(session, config["uuid"]) # Function to initiate the session with the XenServer system def session_start(url): try: session = XenAPI.Session(url); except Exception, exn: print str(exn); sys.exit(3); return session; def session_login(session, username, password): try: session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); sys.exit(3); if __name__ == "__main__": main() # vim:set ts=4 sw=4
Python
#!/usr/bin/env python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com import sys, string, getopt import XenAPI def usage(): print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]" print "Where:-" print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"." print " -h : Print this help message." print " -l : The username for the XenServer host." print " -p : The password for the XenServer host." print " -s : The URL of the web interface on the XenServer host." print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return" print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\"" print " then the UUID must be specified." # Process command line options and populate the config array def process_opts(): config = { "action" : "status", "session_url" : "", "session_user" : "", "session_pass" : "", "uuid" : "", "name" : "", "verbose" : False } # If we have at least one argument then we want to parse the command line using getopts if len(sys.argv) > 1: try: opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="]) except getopt.GetoptError, err: # We got an unrecognised option, so print he help message and exit print str(err) usage() sys.exit(1) for opt, arg in opts: if opt in ("-v", "--verbose"): config["verbose"] = True elif opt in ("-a", "--action"): config["action"] = clean_action(arg) elif opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-s", "--session-url"): config["session_url"] = arg elif opt in ("-l", "--login-name"): config["session_user"] = arg elif opt in ("-n", "--name"): config["name"] = arg elif opt in ("-p", "--password"): config["session_pass"] = arg elif opt in ("-U", "--uuid"): config["uuid"] = arg.lower() else: assert False, "unhandled option" # Otherwise process stdin for parameters. This is to handle the Red Hat clustering # mechanism where by fenced passes in name/value pairs instead of using command line # options. else: for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] name = clean_param_name(name) if name == "action": value = clean_action(value) if name in config: config[name] = value else: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ): print "You must specify the session url, username and password."; usage(); sys.exit(2); return config # why, well just to be nice. Given an action will return the corresponding # value that the rest of the script uses. def clean_action(action): if action.lower() in ("on", "poweron", "powerup"): return "on" elif action.lower() in ("off", "poweroff", "powerdown"): return "off" elif action.lower() in ("reboot", "reset", "restart"): return "reboot" elif action.lower() in ("status", "powerstatus", "list"): return "status" else: print "Bad action", action usage() exit(4) # why, well just to be nice. Given a parameter will return the corresponding # value that the rest of the script uses. def clean_param_name(name): if name.lower() in ("action", "operation", "op"): return "action" elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"): return "session_user" elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"): return "session_pass" elif name.lower() in ("session_url", "url", "session-url"): return "session_url" else: # we should never get here as getopt should handle the checking of this input. print "Bad parameter specified", name usage() exit(5) # Print the power status of a VM. If no UUID is given, then all VM's are queried def get_power_status(session, uuid = "", name = ""): try: # If the UUID hasn't been set, then output the status of all # valid virtual machines. if( len(uuid) > 0 ): vms = [session.xenapi.VM.get_by_uuid(uuid)] elif( len(name) > 0 ): vms = session.xenapi.VM.get_by_name_label(name) else: vms = session.xenapi.VM.get_all() for vm in vms: record = session.xenapi.VM.get_record(vm); # We only want to print out the status for actual virtual machines. The above get_all function # returns any templates and also the control domain. This is one of the reasons the process # takes such a long time to list all VM's. Hopefully there is a way to filter this in the # request packet in the future. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); def set_power_status(session, uuid, name, action): try: vm = None if( len(uuid) > 0 ): vm = session.xenapi.VM.get_by_uuid(uuid) elif( len(name) > 0 ): vm_arr = session.xenapi.VM.get_by_name_label(name) if( len(vm_arr) == 1 ): vm = vm_arr[0] else raise Exception("Multiple VM's have that name. Use UUID instead.") if( vm != None ): record = session.xenapi.VM.get_record(vm); if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): session.xenapi.VM.start(vm, False, True) elif( action == "off" ): session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): session.xenapi.VM.hard_reboot(vm) else: raise Exception("Bad power status"); except Exception, exn: print str(exn); def main(): config = process_opts(); session = session_start(config["session_url"]); session_login(session, config["session_user"], config["session_pass"]); if( config["action"] == "status" ): get_power_status(session, config["uuid"], config["name"]) else: if( config["verbose"] ): print "Power status before action" get_power_status(session, config["uuid"]) set_power_status(session, config["uuid"], config["name"], config["action"]) if( config["verbose"] ): print "Power status after action" get_power_status(session, config["uuid"]) # Function to initiate the session with the XenServer system def session_start(url): try: session = XenAPI.Session(url); except Exception, exn: print str(exn); sys.exit(3); return session; def session_login(session, username, password): try: session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); sys.exit(3); if __name__ == "__main__": main() # vim:set ts=4 sw=4
Python
#!/usr/bin/python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# ############################################################################# # It's only just begun... # Current status: completely usable. This script is now working well and, # has a lot of functionality as a result of the fencing.py library and the # XenAPI libary. ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com from fencing import * import XenAPI EC_BAD_SESSION = 1 # Find the status of the port given in the -U flag of options. def get_power_fn(session, options): if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): status = record["power_state"] if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"] # Note that the VM can be in the following states (from the XenAPI document) # Halted: VM is offline and not using any resources. # Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running # Running: Running # Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while # We want to make sure that we only return the status "off" if the machine is actually halted as the status # is checked before a fencing action. Only when the machine is Halted is it not consuming resources which # may include whatever you are trying to protect with this fencing action. return (status=="Halted" and "off" or "on") except Exception, exn: print str(exn) return "Error" # Set the state of the port given in the -U flag of options. def set_power_fn(session, options): action = options["-o"].lower() if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm) # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): # Start the VM session.xenapi.VM.start(vm, False, True) elif( action == "off" ): # Force shutdown the VM session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): # Force reboot the VM session.xenapi.VM.hard_reboot(vm) except Exception, exn: print str(exn); # Function to populate an array of virtual machines and their status def get_outlet_list(session, options): result = {} if options.has_key("-v"): verbose = True else: verbose = False try: # Return an array of all the VM's on the host vms = session.xenapi.VM.get_all() for vm in vms: # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] uuid = record["uuid"] status = record["power_state"] result[uuid] = (name, status) if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); return result # Function to initiate the XenServer session via the XenAPI library. def connect_and_login(options): url = options["-s"] username = options["-l"] password = options["-p"] try: # Create the XML RPC session to the specified URL. session = XenAPI.Session(url); # Login using the supplied credentials. session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); # http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity # the exit value should be 1. It doesn't say anything about failed logins, so # until I hear otherwise it is best to keep this exit the same to make sure that # anything calling this script (that uses the same information in the web page # above) knows that this is an error condition, not a msg signifying a down port. sys.exit(EC_BAD_SESSION); return session; # return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then # this is tried first as this is the only properly unique identifier. # Exceptions are not handled in this function, code that calls this must be ready to handle them. def return_vm_reference(session, options): if options.has_key("-v"): verbose = True else: verbose = False # Case where the UUID has been specified if options.has_key("-U"): uuid = options["-U"].lower() # When using the -n parameter for name, we get an error message (in verbose # mode) that tells us that we didn't find a VM. To immitate that here we # need to catch and re-raise the exception produced by get_by_uuid. try: return session.xenapi.VM.get_by_uuid(uuid) except Exception,exn: if verbose: print "No VM's found with a UUID of \"%s\"" %uuid raise # Case where the vm_name has been specified if options.has_key("-n"): vm_name = options["-n"] vm_arr = session.xenapi.VM.get_by_name_label(vm_name) # Need to make sure that we only have one result as the vm_name may # not be unique. Average case, so do it first. if len(vm_arr) == 1: return vm_arr[0] else: if len(vm_arr) == 0: if verbose: print "No VM's found with a name of \"%s\"" %vm_name # NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find # a VM with the specified UUID. This should make the output look fairly # consistent. raise Exception("NAME_INVALID") else: if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name raise Exception("MULTIPLE_VMS_FOUND") # We should never get to this case as the input processing checks that either the UUID or # the name parameter is set. Regardless of whether or not a VM is found the above if # statements will return to the calling function (either by exception or by a reference # to the VM). raise Exception("VM_LOGIC_ERROR") def main(): device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action", "login", "passwd", "passwd_script", "vm_name", "test", "separator", "no_login", "no_password", "power_timeout", "shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ] atexit.register(atexit_handler) options=process_input(device_opt) options = check_input(device_opt, options) docs = { } docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines." docs["longdesc"] = "\ fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \ It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \ to a XenServer host. Once the session is established, further XML-RPC \ commands are issued in order to switch on, switch off, restart and query \ the status of virtual machines running on the host." show_docs(options, docs) xenSession = connect_and_login(options) # Operate the fencing device result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list) sys.exit(result) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, getopt, time, os import pexpect, re import telnetlib import atexit import __main__ ## do not add code here. #BEGIN_VERSION_GENERATION RELEASE_VERSION="3.0.17" BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)" REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved." #END_VERSION_GENERATION LOG_MODE_VERBOSE = 100 LOG_MODE_QUIET = 0 EC_GENERIC_ERROR = 1 EC_BAD_ARGS = 2 EC_LOGIN_DENIED = 3 EC_CONNECTION_LOST = 4 EC_TIMED_OUT = 5 EC_WAITING_ON = 6 EC_WAITING_OFF = 7 EC_STATUS = 8 EC_STATUS_HMC = 9 TELNET_PATH = "/usr/bin/telnet" SSH_PATH = "/usr/bin/ssh" SSL_PATH = "/usr/sbin/fence_nss_wrapper" all_opt = { "help" : { "getopt" : "h", "longopt" : "help", "help" : "-h, --help Display this help and exit", "required" : "0", "shortdesc" : "Display help and exit", "order" : 54 }, "version" : { "getopt" : "V", "longopt" : "version", "help" : "-V, --version Output version information and exit", "required" : "0", "shortdesc" : "Display version information and exit", "order" : 53 }, "quiet" : { "getopt" : "q", "help" : "", "order" : 50 }, "verbose" : { "getopt" : "v", "longopt" : "verbose", "help" : "-v, --verbose Verbose mode", "required" : "0", "shortdesc" : "Verbose mode", "order" : 51 }, "debug" : { "getopt" : "D:", "longopt" : "debug-file", "help" : "-D, --debug-file=<debugfile> Debugging to output file", "required" : "0", "shortdesc" : "Write debug information to given file", "order" : 52 }, "delay" : { "getopt" : "f:", "longopt" : "delay", "help" : "--delay <seconds> Wait X seconds before fencing is started", "required" : "0", "shortdesc" : "Wait X seconds before fencing is started", "default" : "0", "order" : 200 }, "agent" : { "getopt" : "", "help" : "", "order" : 1 }, "web" : { "getopt" : "", "help" : "", "order" : 1 }, "action" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, reboot (default), off or on", "required" : "1", "shortdesc" : "Fencing Action", "default" : "reboot", "order" : 1 }, "io_fencing" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, enable or disable", "required" : "1", "shortdesc" : "Fencing Action", "default" : "disable", "order" : 1 }, "ipaddr" : { "getopt" : "a:", "longopt" : "ip", "help" : "-a, --ip=<ip> IP address or hostname of fencing device", "required" : "1", "shortdesc" : "IP Address or Hostname", "order" : 1 }, "ipport" : { "getopt" : "u:", "longopt" : "ipport", "help" : "-u, --ipport=<port> TCP port to use", "required" : "0", "shortdesc" : "TCP port to use for connection with device", "order" : 1 }, "login" : { "getopt" : "l:", "longopt" : "username", "help" : "-l, --username=<name> Login name", "required" : "?", "shortdesc" : "Login Name", "order" : 1 }, "no_login" : { "getopt" : "", "help" : "", "order" : 1 }, "no_password" : { "getopt" : "", "help" : "", "order" : 1 }, "passwd" : { "getopt" : "p:", "longopt" : "password", "help" : "-p, --password=<password> Login password or passphrase", "required" : "0", "shortdesc" : "Login password or passphrase", "order" : 1 }, "passwd_script" : { "getopt" : "S:", "longopt" : "password-script=", "help" : "-S, --password-script=<script> Script to run to retrieve password", "required" : "0", "shortdesc" : "Script to retrieve password", "order" : 1 }, "identity_file" : { "getopt" : "k:", "longopt" : "identity-file", "help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ", "required" : "0", "shortdesc" : "Identity file for ssh", "order" : 1 }, "module_name" : { "getopt" : "m:", "longopt" : "module-name", "help" : "-m, --module-name=<module> DRAC/MC module name", "required" : "0", "shortdesc" : "DRAC/MC module name", "order" : 1 }, "drac_version" : { "getopt" : "d:", "longopt" : "drac-version", "help" : "-d, --drac-version=<version> Force DRAC version to use", "required" : "0", "shortdesc" : "Force DRAC version to use", "order" : 1 }, "hmc_version" : { "getopt" : "H:", "longopt" : "hmc-version", "help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)", "required" : "0", "shortdesc" : "Force HMC version to use (3 or 4)", "default" : "4", "order" : 1 }, "ribcl" : { "getopt" : "r:", "longopt" : "ribcl-version", "help" : "-r, --ribcl-version=<version> Force ribcl version to use", "required" : "0", "shortdesc" : "Force ribcl version to use", "order" : 1 }, "login_eol_lf" : { "getopt" : "", "help" : "", "order" : 1 }, "cmd_prompt" : { "getopt" : "c:", "longopt" : "command-prompt", "help" : "-c, --command-prompt=<prompt> Force command prompt", "shortdesc" : "Force command prompt", "required" : "0", "order" : 1 }, "secure" : { "getopt" : "x", "longopt" : "ssh", "help" : "-x, --ssh Use ssh connection", "shortdesc" : "SSH connection", "required" : "0", "order" : 1 }, "ssl" : { "getopt" : "z", "longopt" : "ssl", "help" : "-z, --ssl Use ssl connection", "required" : "0", "shortdesc" : "SSL connection", "order" : 1 }, "port" : { "getopt" : "n:", "longopt" : "plug", "help" : "-n, --plug=<id> Physical plug number on device or\n" + " name of virtual machine", "required" : "1", "shortdesc" : "Physical plug number or name of virtual machine", "order" : 1 }, "switch" : { "getopt" : "s:", "longopt" : "switch", "help" : "-s, --switch=<id> Physical switch number on device", "required" : "0", "shortdesc" : "Physical switch number on device", "order" : 1 }, "partition" : { "getopt" : "n:", "help" : "-n <id> Name of the partition", "required" : "0", "shortdesc" : "Partition name", "order" : 1 }, "managed" : { "getopt" : "s:", "help" : "-s <id> Name of the managed system", "required" : "0", "shortdesc" : "Managed system name", "order" : 1 }, "test" : { "getopt" : "T", "help" : "", "order" : 1, "obsolete" : "use -o status instead" }, "exec" : { "getopt" : "e:", "longopt" : "exec", "help" : "-e, --exec=<command> Command to execute", "required" : "0", "shortdesc" : "Command to execute", "order" : 1 }, "vmware_type" : { "getopt" : "d:", "longopt" : "vmware_type", "help" : "-d, --vmware_type=<type> Type of VMware to connect", "required" : "0", "shortdesc" : "Type of VMware to connect", "order" : 1 }, "vmware_datacenter" : { "getopt" : "s:", "longopt" : "vmware-datacenter", "help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter", "required" : "0", "shortdesc" : "Show only machines in specified datacenter", "order" : 2 }, "snmp_version" : { "getopt" : "d:", "longopt" : "snmp-version", "help" : "-d, --snmp-version=<ver> Specifies SNMP version to use", "required" : "0", "shortdesc" : "Specifies SNMP version to use (1,2c,3)", "order" : 1 }, "community" : { "getopt" : "c:", "longopt" : "community", "help" : "-c, --community=<community> Set the community string", "required" : "0", "shortdesc" : "Set the community string", "order" : 1}, "snmp_auth_prot" : { "getopt" : "b:", "longopt" : "snmp-auth-prot", "help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)", "required" : "0", "shortdesc" : "Set authentication protocol (MD5|SHA)", "order" : 1}, "snmp_sec_level" : { "getopt" : "E:", "longopt" : "snmp-sec-level", "help" : "-E, --snmp-sec-level=<level> Set security level\n"+ " (noAuthNoPriv|authNoPriv|authPriv)", "required" : "0", "shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)", "order" : 1}, "snmp_priv_prot" : { "getopt" : "B:", "longopt" : "snmp-priv-prot", "help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)", "required" : "0", "shortdesc" : "Set privacy protocol (DES|AES)", "order" : 1}, "snmp_priv_passwd" : { "getopt" : "P:", "longopt" : "snmp-priv-passwd", "help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password", "required" : "0", "shortdesc" : "Set privacy protocol password", "order" : 1}, "snmp_priv_passwd_script" : { "getopt" : "R:", "longopt" : "snmp-priv-passwd-script", "help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password", "required" : "0", "shortdesc" : "Script to run to retrieve privacy password", "order" : 1}, "inet4_only" : { "getopt" : "4", "longopt" : "inet4-only", "help" : "-4, --inet4-only Forces agent to use IPv4 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv4 addresses only", "order" : 1 }, "inet6_only" : { "getopt" : "6", "longopt" : "inet6-only", "help" : "-6, --inet6-only Forces agent to use IPv6 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv6 addresses only", "order" : 1 }, "udpport" : { "getopt" : "u:", "longopt" : "udpport", "help" : "-u, --udpport UDP/TCP port to use", "required" : "0", "shortdesc" : "UDP/TCP port to use for connection with device", "order" : 1}, "separator" : { "getopt" : "C:", "longopt" : "separator", "help" : "-C, --separator=<char> Separator for CSV created by 'list' operation", "default" : ",", "required" : "0", "shortdesc" : "Separator for CSV created by operation list", "order" : 100 }, "login_timeout" : { "getopt" : "y:", "longopt" : "login-timeout", "help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login", "default" : "5", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after login", "order" : 200 }, "shell_timeout" : { "getopt" : "Y:", "longopt" : "shell-timeout", "help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command", "default" : "3", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after issuing command", "order" : 200 }, "power_timeout" : { "getopt" : "g:", "longopt" : "power-timeout", "help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF", "default" : "20", "required" : "0", "shortdesc" : "Test X seconds for status change after ON/OFF", "order" : 200 }, "power_wait" : { "getopt" : "G:", "longopt" : "power-wait", "help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF", "default" : "0", "required" : "0", "shortdesc" : "Wait X seconds after issuing ON/OFF", "order" : 200 }, "missing_as_off" : { "getopt" : "M", "longopt" : "missing-as-off", "help" : "--missing-as-off Missing port returns OFF instead of failure", "required" : "0", "shortdesc" : "Missing port returns OFF instead of failure", "order" : 200 }, "retry_on" : { "getopt" : "F:", "longopt" : "retry-on", "help" : "--retry-on <attempts> Count of attempts to retry power on", "default" : "1", "required" : "0", "shortdesc" : "Count of attempts to retry power on", "order" : 200 }, "session_url" : { "getopt" : "s:", "longopt" : "session-url", "help" : "-s, --session-url URL to connect to XenServer on.", "required" : "1", "shortdesc" : "The URL of the XenServer host.", "order" : 1}, "vm_name" : { "getopt" : "n:", "longopt" : "vm-name", "help" : "-n, --vm-name Name of the VM to fence.", "required" : "0", "shortdesc" : "The name of the virual machine to fence.", "order" : 1}, "uuid" : { "getopt" : "U:", "longopt" : "uuid", "help" : "-U, --uuid UUID of the VM to fence.", "required" : "0", "shortdesc" : "The UUID of the virtual machine to fence.", "order" : 1} } common_opt = [ "retry_on", "delay" ] class fspawn(pexpect.spawn): def log_expect(self, options, pattern, timeout): result = self.expect(pattern, timeout) if options["log"] >= LOG_MODE_VERBOSE: options["debug_fh"].write(self.before + self.after) return result def atexit_handler(): try: sys.stdout.close() os.close(1) except IOError: sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0])) sys.exit(EC_GENERIC_ERROR) def version(command, release, build_date, copyright_notice): print command, " ", release, " ", build_date if len(copyright_notice) > 0: print copyright_notice def fail_usage(message = ""): if len(message) > 0: sys.stderr.write(message+"\n") sys.stderr.write("Please use '-h' for usage\n") sys.exit(EC_GENERIC_ERROR) def fail(error_code): message = { EC_LOGIN_DENIED : "Unable to connect/login to fencing device", EC_CONNECTION_LOST : "Connection lost", EC_TIMED_OUT : "Connection timed out", EC_WAITING_ON : "Failed: Timed out waiting to power ON", EC_WAITING_OFF : "Failed: Timed out waiting to power OFF", EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available", EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used" }[error_code] + "\n" sys.stderr.write(message) sys.exit(EC_GENERIC_ERROR) def usage(avail_opt): global all_opt print "Usage:" print "\t" + os.path.basename(sys.argv[0]) + " [options]" print "Options:" sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) for key, value in sorted_list: if len(value["help"]) != 0: print " " + value["help"] def metadata(avail_opt, options, docs): global all_opt sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) print "<?xml version=\"1.0\" ?>" print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >" print "<longdesc>" + docs["longdesc"] + "</longdesc>" if docs.has_key("vendorurl"): print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>" print "<parameters>" for option, value in sorted_list: if all_opt[option].has_key("shortdesc"): print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">" default = "" if all_opt[option].has_key("default"): default = "default=\""+str(all_opt[option]["default"])+"\"" elif options.has_key("-" + all_opt[option]["getopt"][:-1]): if options["-" + all_opt[option]["getopt"][:-1]]: try: default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\"" except TypeError: ## @todo/@note: Currently there is no clean way how to handle lists ## we can create a string from it but we can't set it on command line default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\"" elif options.has_key("-" + all_opt[option]["getopt"]): default = "default=\"true\" " mixed = all_opt[option]["help"] ## split it between option and help text res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed) if (None != res): mixed = res.group(1) mixed = mixed.replace("<", "&lt;").replace(">", "&gt;") print "\t\t<getopt mixed=\"" + mixed + "\" />" if all_opt[option]["getopt"].count(":") > 0: print "\t\t<content type=\"string\" "+default+" />" else: print "\t\t<content type=\"boolean\" "+default+" />" print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>" print "\t</parameter>" print "</parameters>" print "<actions>" print "\t<action name=\"on\" />" print "\t<action name=\"off\" />" print "\t<action name=\"reboot\" />" print "\t<action name=\"status\" />" print "\t<action name=\"list\" />" print "\t<action name=\"monitor\" />" print "\t<action name=\"metadata\" />" print "</actions>" print "</resource-agent>" def process_input(avail_opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### avail_opt.extend(common_opt) ## ## Set standard environment ##### os.putenv("LANG", "C") os.putenv("LC_ALL", "C") ## ## Prepare list of options for getopt ##### getopt_string = "" longopt_list = [ ] for k in avail_opt: if all_opt.has_key(k): getopt_string += all_opt[k]["getopt"] else: fail_usage("Parse error: unknown option '"+k+"'") if all_opt.has_key(k) and all_opt[k].has_key("longopt"): if all_opt[k]["getopt"].endswith(":"): longopt_list.append(all_opt[k]["longopt"] + "=") else: longopt_list.append(all_opt[k]["longopt"]) ## Compatibility layer if avail_opt.count("module_name") == 1: getopt_string += "n:" longopt_list.append("plug=") ## ## Read options from command line or standard input ##### if len(sys.argv) > 1: try: opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list) except getopt.GetoptError, error: fail_usage("Parse error: " + error.msg) ## Transform longopt to short one which are used in fencing agents ##### old_opt = opt opt = { } for o in dict(old_opt).keys(): if o.startswith("--"): for x in all_opt.keys(): if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o: opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o] else: opt[o] = dict(old_opt)[o] ## Compatibility Layer ##### z = dict(opt) if z.has_key("-T") == 1: z["-o"] = "status" if z.has_key("-n") == 1: z["-m"] = z["-n"] opt = z ## ##### else: opt = { } name = "" for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] ## Compatibility Layer ###### if name == "blade": name = "port" elif name == "option": name = "action" elif name == "fm": name = "port" elif name == "hostname": name = "ipaddr" elif name == "modulename": name = "module_name" elif name == "action" and 1 == avail_opt.count("io_fencing"): name = "io_fencing" elif name == "port" and 1 == avail_opt.count("drac_version"): name = "module_name" ## ###### if avail_opt.count(name) == 0: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") continue if all_opt[name]["getopt"].endswith(":"): opt["-"+all_opt[name]["getopt"].rstrip(":")] = value elif ((value == "1") or (value.lower() == "yes")): opt["-"+all_opt[name]["getopt"]] = "1" return opt ## ## This function checks input and answers if we want to have same answers ## in each of the fencing agents. It looks for possible errors and run ## password script to set a correct password ###### def check_input(device_opt, opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### device_opt.extend([x for x in common_opt if device_opt.count(x) == 0]) options = dict(opt) options["device_opt"] = device_opt ## Set requirements that should be included in metadata ##### if device_opt.count("login") and device_opt.count("no_login") == 0: all_opt["login"]["required"] = "1" else: all_opt["login"]["required"] = "0" ## In special cases (show help, metadata or version) we don't need to check anything ##### if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"): return options; ## Set default values ##### for opt in device_opt: if all_opt[opt].has_key("default"): getopt = "-" + all_opt[opt]["getopt"].rstrip(":") if 0 == options.has_key(getopt): options[getopt] = all_opt[opt]["default"] options["-o"]=options["-o"].lower() if options.has_key("-v"): options["log"] = LOG_MODE_VERBOSE else: options["log"] = LOG_MODE_QUIET if 0 == device_opt.count("io_fencing"): if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") else: if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0): fail_usage("Failed: You have to set login name") if 0 == options.has_key("-a") and 0 == options.has_key("-s"): fail_usage("Failed: You have to enter fence address") if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"): if 0 == options.has_key("-n") and 0 == options.has_key("-U"): fail_usage("Failed: You must specify either UUID or VM name") if (device_opt.count("no_password") == 0): if 0 == device_opt.count("identity_file"): if 0 == (options.has_key("-p") or options.has_key("-S")): fail_usage("Failed: You have to enter password or password script") else: if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")): fail_usage("Failed: You have to enter password, password script or identity file") if 0 == options.has_key("-x") and 1 == options.has_key("-k"): fail_usage("Failed: You have to use identity file together with ssh connection (-x)") if 1 == options.has_key("-k"): if 0 == os.path.isfile(options["-k"]): fail_usage("Failed: Identity file " + options["-k"] + " does not exist") if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")): fail_usage("Failed: You have to enter plug number") if options.has_key("-S"): options["-p"] = os.popen(options["-S"]).read().rstrip() if options.has_key("-D"): try: options["debug_fh"] = file (options["-D"], "w") except IOError: fail_usage("Failed: Unable to create file "+options["-D"]) if options.has_key("-v") and options.has_key("debug_fh") == 0: options["debug_fh"] = sys.stderr if options.has_key("-R"): options["-P"] = os.popen(options["-R"]).read().rstrip() if options.has_key("-u") == False: if options.has_key("-x"): options["-u"] = 22 elif options.has_key("-z"): options["-u"] = 443 elif device_opt.count("web"): options["-u"] = 80 else: options["-u"] = 23 return options def wait_power_status(tn, options, get_power_fn): for dummy in xrange(int(options["-g"])): if get_power_fn(tn, options) != options["-o"]: time.sleep(1) else: return 1 return 0 def show_docs(options, docs = None): device_opt = options["device_opt"] if docs == None: docs = { } docs["shortdesc"] = "Fence agent" docs["longdesc"] = "" ## Process special options (and exit) ##### if options.has_key("-h"): usage(device_opt) sys.exit(0) if options.has_key("-o") and options["-o"].lower() == "metadata": metadata(device_opt, options, docs) sys.exit(0) if options.has_key("-V"): print __main__.RELEASE_VERSION, __main__.BUILD_DATE print __main__.REDHAT_COPYRIGHT sys.exit(0) def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None): result = 0 ## Process options that manipulate fencing device ##### if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")): print "N/A" return elif (options["-o"] == "list" and get_outlet_list == None): ## @todo: exception? ## This is just temporal solution, we will remove default value ## None as soon as all existing agent will support this operation print "NOTICE: List option is not working on this device yet" return elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")): outlets = get_outlet_list(tn, options) ## keys can be numbers (port numbers) or strings (names of VM) for o in outlets.keys(): (alias, status) = outlets[o] if options["-o"] != "monitor": print o + options["-C"] + alias return if options["-o"] in ["off", "reboot"]: time.sleep(int(options["-f"])) status = get_power_fn(tn, options) if status != "on" and status != "off": fail(EC_STATUS) if options["-o"] == "enable": options["-o"] = "on" if options["-o"] == "disable": options["-o"] = "off" if options["-o"] == "on": if status == "on": print "Success: Already ON" else: power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): power_on = True break if power_on: print "Success: Powered ON" else: fail(EC_WAITING_ON) elif options["-o"] == "off": if status == "off": print "Success: Already OFF" else: set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): print "Success: Powered OFF" else: fail(EC_WAITING_OFF) elif options["-o"] == "reboot": if status != "off": options["-o"] = "off" set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 0: fail(EC_WAITING_OFF) options["-o"] = "on" power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 1: power_on = True break if power_on == False: # this should not fail as not was fenced succesfully sys.stderr.write('Timed out waiting to power ON\n') print "Success: Rebooted" elif options["-o"] == "status": print "Status: " + status.upper() if status.upper() == "OFF": result = 2 elif options["-o"] == "monitor": 1 return result def fence_login(options): force_ipvx="" if (options.has_key("-6")): force_ipvx="-6 " if (options.has_key("-4")): force_ipvx="-4 " if (options["device_opt"].count("login_eol_lf")): login_eol = "\n" else: login_eol = "\r\n" try: re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE) re_pass = re.compile("password", re.IGNORECASE) if options.has_key("-z"): command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"]) try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: ## SSL telnet is part of the fencing package sys.stderr.write(str(ex) + "\n") sys.exit(EC_GENERIC_ERROR) elif options.has_key("-x") and 0 == options.has_key("-k"): command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) if options.has_key("telnet_over_ssh"): #This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt) result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") # Host identity confirm conn.log_expect(options, re_login, int(options["-y"])) conn.sendline(options["-l"]) conn.log_expect(options, re_pass, int(options["-y"])) else: result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, "ssword:", int(options["-y"])) conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) elif options.has_key("-x") and 1 == options.has_key("-k"): command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"])) if result != 0: if options.has_key("-p"): conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) else: fail_usage("Failed: You have to enter passphrase (-p) for identity file") else: try: conn = fspawn(TELNET_PATH) conn.send("set binary\n") conn.send("open %s -%s\n"%(options["-a"], options["-u"])) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) conn.log_expect(options, re_login, int(options["-y"])) conn.send(options["-l"] + login_eol) conn.log_expect(options, re_pass, int(options["-Y"])) conn.send(options["-p"] + login_eol) conn.log_expect(options, options["-c"], int(options["-Y"])) except pexpect.EOF: fail(EC_LOGIN_DENIED) except pexpect.TIMEOUT: fail(EC_LOGIN_DENIED) return conn
Python
#!/usr/bin/python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# ############################################################################# # It's only just begun... # Current status: completely usable. This script is now working well and, # has a lot of functionality as a result of the fencing.py library and the # XenAPI libary. ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com from fencing import * import XenAPI EC_BAD_SESSION = 1 # Find the status of the port given in the -U flag of options. def get_power_fn(session, options): if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): status = record["power_state"] if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"] # Note that the VM can be in the following states (from the XenAPI document) # Halted: VM is offline and not using any resources. # Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running # Running: Running # Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while # We want to make sure that we only return the status "off" if the machine is actually halted as the status # is checked before a fencing action. Only when the machine is Halted is it not consuming resources which # may include whatever you are trying to protect with this fencing action. return (status=="Halted" and "off" or "on") except Exception, exn: print str(exn) return "Error" # Set the state of the port given in the -U flag of options. def set_power_fn(session, options): action = options["-o"].lower() if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm) # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): # Start the VM session.xenapi.VM.start(vm, False, True) elif( action == "off" ): # Force shutdown the VM session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): # Force reboot the VM session.xenapi.VM.hard_reboot(vm) except Exception, exn: print str(exn); # Function to populate an array of virtual machines and their status def get_outlet_list(session, options): result = {} if options.has_key("-v"): verbose = True else: verbose = False try: # Return an array of all the VM's on the host vms = session.xenapi.VM.get_all() for vm in vms: # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] uuid = record["uuid"] status = record["power_state"] result[uuid] = (name, status) if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); return result # Function to initiate the XenServer session via the XenAPI library. def connect_and_login(options): url = options["-s"] username = options["-l"] password = options["-p"] try: # Create the XML RPC session to the specified URL. session = XenAPI.Session(url); # Login using the supplied credentials. session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); # http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity # the exit value should be 1. It doesn't say anything about failed logins, so # until I hear otherwise it is best to keep this exit the same to make sure that # anything calling this script (that uses the same information in the web page # above) knows that this is an error condition, not a msg signifying a down port. sys.exit(EC_BAD_SESSION); return session; # return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then # this is tried first as this is the only properly unique identifier. # Exceptions are not handled in this function, code that calls this must be ready to handle them. def return_vm_reference(session, options): if options.has_key("-v"): verbose = True else: verbose = False # Case where the UUID has been specified if options.has_key("-U"): uuid = options["-U"].lower() # When using the -n parameter for name, we get an error message (in verbose # mode) that tells us that we didn't find a VM. To immitate that here we # need to catch and re-raise the exception produced by get_by_uuid. try: return session.xenapi.VM.get_by_uuid(uuid) except Exception,exn: if verbose: print "No VM's found with a UUID of \"%s\"" %uuid raise # Case where the vm_name has been specified if options.has_key("-n"): vm_name = options["-n"] vm_arr = session.xenapi.VM.get_by_name_label(vm_name) # Need to make sure that we only have one result as the vm_name may # not be unique. Average case, so do it first. if len(vm_arr) == 1: return vm_arr[0] else: if len(vm_arr) == 0: if verbose: print "No VM's found with a name of \"%s\"" %vm_name # NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find # a VM with the specified UUID. This should make the output look fairly # consistent. raise Exception("NAME_INVALID") else: if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name raise Exception("MULTIPLE_VMS_FOUND") # We should never get to this case as the input processing checks that either the UUID or # the name parameter is set. Regardless of whether or not a VM is found the above if # statements will return to the calling function (either by exception or by a reference # to the VM). raise Exception("VM_LOGIC_ERROR") def main(): device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action", "login", "passwd", "passwd_script", "vm_name", "test", "separator", "no_login", "no_password", "power_timeout", "shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ] atexit.register(atexit_handler) options=process_input(device_opt) options = check_input(device_opt, options) docs = { } docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines." docs["longdesc"] = "\ fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \ It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \ to a XenServer host. Once the session is established, further XML-RPC \ commands are issued in order to switch on, switch off, restart and query \ the status of virtual machines running on the host." show_docs(options, docs) xenSession = connect_and_login(options) # Operate the fencing device result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list) sys.exit(result) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, getopt, time, os import pexpect, re import telnetlib import atexit import __main__ ## do not add code here. #BEGIN_VERSION_GENERATION RELEASE_VERSION="3.0.17" BUILD_DATE="(built Thu Oct 7 07:06:21 UTC 2010)" REDHAT_COPYRIGHT="Copyright (C) Red Hat, Inc. 2004-2010 All rights reserved." #END_VERSION_GENERATION LOG_MODE_VERBOSE = 100 LOG_MODE_QUIET = 0 EC_GENERIC_ERROR = 1 EC_BAD_ARGS = 2 EC_LOGIN_DENIED = 3 EC_CONNECTION_LOST = 4 EC_TIMED_OUT = 5 EC_WAITING_ON = 6 EC_WAITING_OFF = 7 EC_STATUS = 8 EC_STATUS_HMC = 9 TELNET_PATH = "/usr/bin/telnet" SSH_PATH = "/usr/bin/ssh" SSL_PATH = "/usr/sbin/fence_nss_wrapper" all_opt = { "help" : { "getopt" : "h", "longopt" : "help", "help" : "-h, --help Display this help and exit", "required" : "0", "shortdesc" : "Display help and exit", "order" : 54 }, "version" : { "getopt" : "V", "longopt" : "version", "help" : "-V, --version Output version information and exit", "required" : "0", "shortdesc" : "Display version information and exit", "order" : 53 }, "quiet" : { "getopt" : "q", "help" : "", "order" : 50 }, "verbose" : { "getopt" : "v", "longopt" : "verbose", "help" : "-v, --verbose Verbose mode", "required" : "0", "shortdesc" : "Verbose mode", "order" : 51 }, "debug" : { "getopt" : "D:", "longopt" : "debug-file", "help" : "-D, --debug-file=<debugfile> Debugging to output file", "required" : "0", "shortdesc" : "Write debug information to given file", "order" : 52 }, "delay" : { "getopt" : "f:", "longopt" : "delay", "help" : "--delay <seconds> Wait X seconds before fencing is started", "required" : "0", "shortdesc" : "Wait X seconds before fencing is started", "default" : "0", "order" : 200 }, "agent" : { "getopt" : "", "help" : "", "order" : 1 }, "web" : { "getopt" : "", "help" : "", "order" : 1 }, "action" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, reboot (default), off or on", "required" : "1", "shortdesc" : "Fencing Action", "default" : "reboot", "order" : 1 }, "io_fencing" : { "getopt" : "o:", "longopt" : "action", "help" : "-o, --action=<action> Action: status, enable or disable", "required" : "1", "shortdesc" : "Fencing Action", "default" : "disable", "order" : 1 }, "ipaddr" : { "getopt" : "a:", "longopt" : "ip", "help" : "-a, --ip=<ip> IP address or hostname of fencing device", "required" : "1", "shortdesc" : "IP Address or Hostname", "order" : 1 }, "ipport" : { "getopt" : "u:", "longopt" : "ipport", "help" : "-u, --ipport=<port> TCP port to use", "required" : "0", "shortdesc" : "TCP port to use for connection with device", "order" : 1 }, "login" : { "getopt" : "l:", "longopt" : "username", "help" : "-l, --username=<name> Login name", "required" : "?", "shortdesc" : "Login Name", "order" : 1 }, "no_login" : { "getopt" : "", "help" : "", "order" : 1 }, "no_password" : { "getopt" : "", "help" : "", "order" : 1 }, "passwd" : { "getopt" : "p:", "longopt" : "password", "help" : "-p, --password=<password> Login password or passphrase", "required" : "0", "shortdesc" : "Login password or passphrase", "order" : 1 }, "passwd_script" : { "getopt" : "S:", "longopt" : "password-script=", "help" : "-S, --password-script=<script> Script to run to retrieve password", "required" : "0", "shortdesc" : "Script to retrieve password", "order" : 1 }, "identity_file" : { "getopt" : "k:", "longopt" : "identity-file", "help" : "-k, --identity-file=<filename> Identity file (private key) for ssh ", "required" : "0", "shortdesc" : "Identity file for ssh", "order" : 1 }, "module_name" : { "getopt" : "m:", "longopt" : "module-name", "help" : "-m, --module-name=<module> DRAC/MC module name", "required" : "0", "shortdesc" : "DRAC/MC module name", "order" : 1 }, "drac_version" : { "getopt" : "d:", "longopt" : "drac-version", "help" : "-d, --drac-version=<version> Force DRAC version to use", "required" : "0", "shortdesc" : "Force DRAC version to use", "order" : 1 }, "hmc_version" : { "getopt" : "H:", "longopt" : "hmc-version", "help" : "-H, --hmc-version=<version> Force HMC version to use: 3, 4 (default)", "required" : "0", "shortdesc" : "Force HMC version to use (3 or 4)", "default" : "4", "order" : 1 }, "ribcl" : { "getopt" : "r:", "longopt" : "ribcl-version", "help" : "-r, --ribcl-version=<version> Force ribcl version to use", "required" : "0", "shortdesc" : "Force ribcl version to use", "order" : 1 }, "login_eol_lf" : { "getopt" : "", "help" : "", "order" : 1 }, "cmd_prompt" : { "getopt" : "c:", "longopt" : "command-prompt", "help" : "-c, --command-prompt=<prompt> Force command prompt", "shortdesc" : "Force command prompt", "required" : "0", "order" : 1 }, "secure" : { "getopt" : "x", "longopt" : "ssh", "help" : "-x, --ssh Use ssh connection", "shortdesc" : "SSH connection", "required" : "0", "order" : 1 }, "ssl" : { "getopt" : "z", "longopt" : "ssl", "help" : "-z, --ssl Use ssl connection", "required" : "0", "shortdesc" : "SSL connection", "order" : 1 }, "port" : { "getopt" : "n:", "longopt" : "plug", "help" : "-n, --plug=<id> Physical plug number on device or\n" + " name of virtual machine", "required" : "1", "shortdesc" : "Physical plug number or name of virtual machine", "order" : 1 }, "switch" : { "getopt" : "s:", "longopt" : "switch", "help" : "-s, --switch=<id> Physical switch number on device", "required" : "0", "shortdesc" : "Physical switch number on device", "order" : 1 }, "partition" : { "getopt" : "n:", "help" : "-n <id> Name of the partition", "required" : "0", "shortdesc" : "Partition name", "order" : 1 }, "managed" : { "getopt" : "s:", "help" : "-s <id> Name of the managed system", "required" : "0", "shortdesc" : "Managed system name", "order" : 1 }, "test" : { "getopt" : "T", "help" : "", "order" : 1, "obsolete" : "use -o status instead" }, "exec" : { "getopt" : "e:", "longopt" : "exec", "help" : "-e, --exec=<command> Command to execute", "required" : "0", "shortdesc" : "Command to execute", "order" : 1 }, "vmware_type" : { "getopt" : "d:", "longopt" : "vmware_type", "help" : "-d, --vmware_type=<type> Type of VMware to connect", "required" : "0", "shortdesc" : "Type of VMware to connect", "order" : 1 }, "vmware_datacenter" : { "getopt" : "s:", "longopt" : "vmware-datacenter", "help" : "-s, --vmware-datacenter=<dc> VMWare datacenter filter", "required" : "0", "shortdesc" : "Show only machines in specified datacenter", "order" : 2 }, "snmp_version" : { "getopt" : "d:", "longopt" : "snmp-version", "help" : "-d, --snmp-version=<ver> Specifies SNMP version to use", "required" : "0", "shortdesc" : "Specifies SNMP version to use (1,2c,3)", "order" : 1 }, "community" : { "getopt" : "c:", "longopt" : "community", "help" : "-c, --community=<community> Set the community string", "required" : "0", "shortdesc" : "Set the community string", "order" : 1}, "snmp_auth_prot" : { "getopt" : "b:", "longopt" : "snmp-auth-prot", "help" : "-b, --snmp-auth-prot=<prot> Set authentication protocol (MD5|SHA)", "required" : "0", "shortdesc" : "Set authentication protocol (MD5|SHA)", "order" : 1}, "snmp_sec_level" : { "getopt" : "E:", "longopt" : "snmp-sec-level", "help" : "-E, --snmp-sec-level=<level> Set security level\n"+ " (noAuthNoPriv|authNoPriv|authPriv)", "required" : "0", "shortdesc" : "Set security level (noAuthNoPriv|authNoPriv|authPriv)", "order" : 1}, "snmp_priv_prot" : { "getopt" : "B:", "longopt" : "snmp-priv-prot", "help" : "-B, --snmp-priv-prot=<prot> Set privacy protocol (DES|AES)", "required" : "0", "shortdesc" : "Set privacy protocol (DES|AES)", "order" : 1}, "snmp_priv_passwd" : { "getopt" : "P:", "longopt" : "snmp-priv-passwd", "help" : "-P, --snmp-priv-passwd=<pass> Set privacy protocol password", "required" : "0", "shortdesc" : "Set privacy protocol password", "order" : 1}, "snmp_priv_passwd_script" : { "getopt" : "R:", "longopt" : "snmp-priv-passwd-script", "help" : "-R, --snmp-priv-passwd-script Script to run to retrieve privacy password", "required" : "0", "shortdesc" : "Script to run to retrieve privacy password", "order" : 1}, "inet4_only" : { "getopt" : "4", "longopt" : "inet4-only", "help" : "-4, --inet4-only Forces agent to use IPv4 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv4 addresses only", "order" : 1 }, "inet6_only" : { "getopt" : "6", "longopt" : "inet6-only", "help" : "-6, --inet6-only Forces agent to use IPv6 addresses only", "required" : "0", "shortdesc" : "Forces agent to use IPv6 addresses only", "order" : 1 }, "udpport" : { "getopt" : "u:", "longopt" : "udpport", "help" : "-u, --udpport UDP/TCP port to use", "required" : "0", "shortdesc" : "UDP/TCP port to use for connection with device", "order" : 1}, "separator" : { "getopt" : "C:", "longopt" : "separator", "help" : "-C, --separator=<char> Separator for CSV created by 'list' operation", "default" : ",", "required" : "0", "shortdesc" : "Separator for CSV created by operation list", "order" : 100 }, "login_timeout" : { "getopt" : "y:", "longopt" : "login-timeout", "help" : "--login-timeout <seconds> Wait X seconds for cmd prompt after login", "default" : "5", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after login", "order" : 200 }, "shell_timeout" : { "getopt" : "Y:", "longopt" : "shell-timeout", "help" : "--shell-timeout <seconds> Wait X seconds for cmd prompt after issuing command", "default" : "3", "required" : "0", "shortdesc" : "Wait X seconds for cmd prompt after issuing command", "order" : 200 }, "power_timeout" : { "getopt" : "g:", "longopt" : "power-timeout", "help" : "--power-timeout <seconds> Test X seconds for status change after ON/OFF", "default" : "20", "required" : "0", "shortdesc" : "Test X seconds for status change after ON/OFF", "order" : 200 }, "power_wait" : { "getopt" : "G:", "longopt" : "power-wait", "help" : "--power-wait <seconds> Wait X seconds after issuing ON/OFF", "default" : "0", "required" : "0", "shortdesc" : "Wait X seconds after issuing ON/OFF", "order" : 200 }, "missing_as_off" : { "getopt" : "M", "longopt" : "missing-as-off", "help" : "--missing-as-off Missing port returns OFF instead of failure", "required" : "0", "shortdesc" : "Missing port returns OFF instead of failure", "order" : 200 }, "retry_on" : { "getopt" : "F:", "longopt" : "retry-on", "help" : "--retry-on <attempts> Count of attempts to retry power on", "default" : "1", "required" : "0", "shortdesc" : "Count of attempts to retry power on", "order" : 200 }, "session_url" : { "getopt" : "s:", "longopt" : "session-url", "help" : "-s, --session-url URL to connect to XenServer on.", "required" : "1", "shortdesc" : "The URL of the XenServer host.", "order" : 1}, "vm_name" : { "getopt" : "n:", "longopt" : "vm-name", "help" : "-n, --vm-name Name of the VM to fence.", "required" : "0", "shortdesc" : "The name of the virual machine to fence.", "order" : 1}, "uuid" : { "getopt" : "U:", "longopt" : "uuid", "help" : "-U, --uuid UUID of the VM to fence.", "required" : "0", "shortdesc" : "The UUID of the virtual machine to fence.", "order" : 1} } common_opt = [ "retry_on", "delay" ] class fspawn(pexpect.spawn): def log_expect(self, options, pattern, timeout): result = self.expect(pattern, timeout) if options["log"] >= LOG_MODE_VERBOSE: options["debug_fh"].write(self.before + self.after) return result def atexit_handler(): try: sys.stdout.close() os.close(1) except IOError: sys.stderr.write("%s failed to close standard output\n"%(sys.argv[0])) sys.exit(EC_GENERIC_ERROR) def version(command, release, build_date, copyright_notice): print command, " ", release, " ", build_date if len(copyright_notice) > 0: print copyright_notice def fail_usage(message = ""): if len(message) > 0: sys.stderr.write(message+"\n") sys.stderr.write("Please use '-h' for usage\n") sys.exit(EC_GENERIC_ERROR) def fail(error_code): message = { EC_LOGIN_DENIED : "Unable to connect/login to fencing device", EC_CONNECTION_LOST : "Connection lost", EC_TIMED_OUT : "Connection timed out", EC_WAITING_ON : "Failed: Timed out waiting to power ON", EC_WAITING_OFF : "Failed: Timed out waiting to power OFF", EC_STATUS : "Failed: Unable to obtain correct plug status or plug is not available", EC_STATUS_HMC : "Failed: Either unable to obtaion correct plug status, partition is not available or incorrect HMC version used" }[error_code] + "\n" sys.stderr.write(message) sys.exit(EC_GENERIC_ERROR) def usage(avail_opt): global all_opt print "Usage:" print "\t" + os.path.basename(sys.argv[0]) + " [options]" print "Options:" sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) for key, value in sorted_list: if len(value["help"]) != 0: print " " + value["help"] def metadata(avail_opt, options, docs): global all_opt sorted_list = [ (key, all_opt[key]) for key in avail_opt ] sorted_list.sort(lambda x, y: cmp(x[1]["order"], y[1]["order"])) print "<?xml version=\"1.0\" ?>" print "<resource-agent name=\"" + os.path.basename(sys.argv[0]) + "\" shortdesc=\"" + docs["shortdesc"] + "\" >" print "<longdesc>" + docs["longdesc"] + "</longdesc>" if docs.has_key("vendorurl"): print "<vendor-url>" + docs["vendorurl"] + "</vendor-url>" print "<parameters>" for option, value in sorted_list: if all_opt[option].has_key("shortdesc"): print "\t<parameter name=\"" + option + "\" unique=\"1\" required=\"" + all_opt[option]["required"] + "\">" default = "" if all_opt[option].has_key("default"): default = "default=\""+str(all_opt[option]["default"])+"\"" elif options.has_key("-" + all_opt[option]["getopt"][:-1]): if options["-" + all_opt[option]["getopt"][:-1]]: try: default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\"" except TypeError: ## @todo/@note: Currently there is no clean way how to handle lists ## we can create a string from it but we can't set it on command line default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\"" elif options.has_key("-" + all_opt[option]["getopt"]): default = "default=\"true\" " mixed = all_opt[option]["help"] ## split it between option and help text res = re.compile("^(.*--\S+)\s+", re.IGNORECASE | re.S).search(mixed) if (None != res): mixed = res.group(1) mixed = mixed.replace("<", "&lt;").replace(">", "&gt;") print "\t\t<getopt mixed=\"" + mixed + "\" />" if all_opt[option]["getopt"].count(":") > 0: print "\t\t<content type=\"string\" "+default+" />" else: print "\t\t<content type=\"boolean\" "+default+" />" print "\t\t<shortdesc lang=\"en\">" + all_opt[option]["shortdesc"] + "</shortdesc>" print "\t</parameter>" print "</parameters>" print "<actions>" print "\t<action name=\"on\" />" print "\t<action name=\"off\" />" print "\t<action name=\"reboot\" />" print "\t<action name=\"status\" />" print "\t<action name=\"list\" />" print "\t<action name=\"monitor\" />" print "\t<action name=\"metadata\" />" print "</actions>" print "</resource-agent>" def process_input(avail_opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### avail_opt.extend(common_opt) ## ## Set standard environment ##### os.putenv("LANG", "C") os.putenv("LC_ALL", "C") ## ## Prepare list of options for getopt ##### getopt_string = "" longopt_list = [ ] for k in avail_opt: if all_opt.has_key(k): getopt_string += all_opt[k]["getopt"] else: fail_usage("Parse error: unknown option '"+k+"'") if all_opt.has_key(k) and all_opt[k].has_key("longopt"): if all_opt[k]["getopt"].endswith(":"): longopt_list.append(all_opt[k]["longopt"] + "=") else: longopt_list.append(all_opt[k]["longopt"]) ## Compatibility layer if avail_opt.count("module_name") == 1: getopt_string += "n:" longopt_list.append("plug=") ## ## Read options from command line or standard input ##### if len(sys.argv) > 1: try: opt, args = getopt.gnu_getopt(sys.argv[1:], getopt_string, longopt_list) except getopt.GetoptError, error: fail_usage("Parse error: " + error.msg) ## Transform longopt to short one which are used in fencing agents ##### old_opt = opt opt = { } for o in dict(old_opt).keys(): if o.startswith("--"): for x in all_opt.keys(): if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o: opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o] else: opt[o] = dict(old_opt)[o] ## Compatibility Layer ##### z = dict(opt) if z.has_key("-T") == 1: z["-o"] = "status" if z.has_key("-n") == 1: z["-m"] = z["-n"] opt = z ## ##### else: opt = { } name = "" for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] ## Compatibility Layer ###### if name == "blade": name = "port" elif name == "option": name = "action" elif name == "fm": name = "port" elif name == "hostname": name = "ipaddr" elif name == "modulename": name = "module_name" elif name == "action" and 1 == avail_opt.count("io_fencing"): name = "io_fencing" elif name == "port" and 1 == avail_opt.count("drac_version"): name = "module_name" ## ###### if avail_opt.count(name) == 0: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") continue if all_opt[name]["getopt"].endswith(":"): opt["-"+all_opt[name]["getopt"].rstrip(":")] = value elif ((value == "1") or (value.lower() == "yes")): opt["-"+all_opt[name]["getopt"]] = "1" return opt ## ## This function checks input and answers if we want to have same answers ## in each of the fencing agents. It looks for possible errors and run ## password script to set a correct password ###### def check_input(device_opt, opt): global all_opt global common_opt ## ## Add options which are available for every fence agent ##### device_opt.extend([x for x in common_opt if device_opt.count(x) == 0]) options = dict(opt) options["device_opt"] = device_opt ## Set requirements that should be included in metadata ##### if device_opt.count("login") and device_opt.count("no_login") == 0: all_opt["login"]["required"] = "1" else: all_opt["login"]["required"] = "0" ## In special cases (show help, metadata or version) we don't need to check anything ##### if options.has_key("-h") or options.has_key("-V") or (options.has_key("-o") and options["-o"].lower() == "metadata"): return options; ## Set default values ##### for opt in device_opt: if all_opt[opt].has_key("default"): getopt = "-" + all_opt[opt]["getopt"].rstrip(":") if 0 == options.has_key(getopt): options[getopt] = all_opt[opt]["default"] options["-o"]=options["-o"].lower() if options.has_key("-v"): options["log"] = LOG_MODE_VERBOSE else: options["log"] = LOG_MODE_QUIET if 0 == device_opt.count("io_fencing"): if 0 == ["on", "off", "reboot", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") else: if 0 == ["enable", "disable", "status", "list", "monitor"].count(options["-o"].lower()): fail_usage("Failed: Unrecognised action '" + options["-o"] + "'") if (0 == options.has_key("-l")) and device_opt.count("login") and (device_opt.count("no_login") == 0): fail_usage("Failed: You have to set login name") if 0 == options.has_key("-a") and 0 == options.has_key("-s"): fail_usage("Failed: You have to enter fence address") if (0 == ["list", "monitor"].count(options["-o"].lower())) and device_opt.count("vm_name") and device_opt.count("uuid"): if 0 == options.has_key("-n") and 0 == options.has_key("-U"): fail_usage("Failed: You must specify either UUID or VM name") if (device_opt.count("no_password") == 0): if 0 == device_opt.count("identity_file"): if 0 == (options.has_key("-p") or options.has_key("-S")): fail_usage("Failed: You have to enter password or password script") else: if 0 == (options.has_key("-p") or options.has_key("-S") or options.has_key("-k")): fail_usage("Failed: You have to enter password, password script or identity file") if 0 == options.has_key("-x") and 1 == options.has_key("-k"): fail_usage("Failed: You have to use identity file together with ssh connection (-x)") if 1 == options.has_key("-k"): if 0 == os.path.isfile(options["-k"]): fail_usage("Failed: Identity file " + options["-k"] + " does not exist") if (0 == ["list", "monitor"].count(options["-o"].lower())) and (0 == options.has_key("-n")) and (device_opt.count("port")): fail_usage("Failed: You have to enter plug number") if options.has_key("-S"): options["-p"] = os.popen(options["-S"]).read().rstrip() if options.has_key("-D"): try: options["debug_fh"] = file (options["-D"], "w") except IOError: fail_usage("Failed: Unable to create file "+options["-D"]) if options.has_key("-v") and options.has_key("debug_fh") == 0: options["debug_fh"] = sys.stderr if options.has_key("-R"): options["-P"] = os.popen(options["-R"]).read().rstrip() if options.has_key("-u") == False: if options.has_key("-x"): options["-u"] = 22 elif options.has_key("-z"): options["-u"] = 443 elif device_opt.count("web"): options["-u"] = 80 else: options["-u"] = 23 return options def wait_power_status(tn, options, get_power_fn): for dummy in xrange(int(options["-g"])): if get_power_fn(tn, options) != options["-o"]: time.sleep(1) else: return 1 return 0 def show_docs(options, docs = None): device_opt = options["device_opt"] if docs == None: docs = { } docs["shortdesc"] = "Fence agent" docs["longdesc"] = "" ## Process special options (and exit) ##### if options.has_key("-h"): usage(device_opt) sys.exit(0) if options.has_key("-o") and options["-o"].lower() == "metadata": metadata(device_opt, options, docs) sys.exit(0) if options.has_key("-V"): print __main__.RELEASE_VERSION, __main__.BUILD_DATE print __main__.REDHAT_COPYRIGHT sys.exit(0) def fence_action(tn, options, set_power_fn, get_power_fn, get_outlet_list = None): result = 0 ## Process options that manipulate fencing device ##### if (options["-o"] == "list") and (0 == options["device_opt"].count("port")) and (0 == options["device_opt"].count("partition")) and (0 == options["device_opt"].count("uuid")): print "N/A" return elif (options["-o"] == "list" and get_outlet_list == None): ## @todo: exception? ## This is just temporal solution, we will remove default value ## None as soon as all existing agent will support this operation print "NOTICE: List option is not working on this device yet" return elif (options["-o"] == "list") or ((options["-o"] == "monitor") and 1 == options["device_opt"].count("port")): outlets = get_outlet_list(tn, options) ## keys can be numbers (port numbers) or strings (names of VM) for o in outlets.keys(): (alias, status) = outlets[o] if options["-o"] != "monitor": print o + options["-C"] + alias return if options["-o"] in ["off", "reboot"]: time.sleep(int(options["-f"])) status = get_power_fn(tn, options) if status != "on" and status != "off": fail(EC_STATUS) if options["-o"] == "enable": options["-o"] = "on" if options["-o"] == "disable": options["-o"] = "off" if options["-o"] == "on": if status == "on": print "Success: Already ON" else: power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): power_on = True break if power_on: print "Success: Powered ON" else: fail(EC_WAITING_ON) elif options["-o"] == "off": if status == "off": print "Success: Already OFF" else: set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn): print "Success: Powered OFF" else: fail(EC_WAITING_OFF) elif options["-o"] == "reboot": if status != "off": options["-o"] = "off" set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 0: fail(EC_WAITING_OFF) options["-o"] = "on" power_on = False for i in range(1,1 + int(options["-F"])): set_power_fn(tn, options) time.sleep(int(options["-G"])) if wait_power_status(tn, options, get_power_fn) == 1: power_on = True break if power_on == False: # this should not fail as not was fenced succesfully sys.stderr.write('Timed out waiting to power ON\n') print "Success: Rebooted" elif options["-o"] == "status": print "Status: " + status.upper() if status.upper() == "OFF": result = 2 elif options["-o"] == "monitor": 1 return result def fence_login(options): force_ipvx="" if (options.has_key("-6")): force_ipvx="-6 " if (options.has_key("-4")): force_ipvx="-4 " if (options["device_opt"].count("login_eol_lf")): login_eol = "\n" else: login_eol = "\r\n" try: re_login = re.compile("(login\s*: )|(Login Name: )|(username: )|(User Name :)", re.IGNORECASE) re_pass = re.compile("password", re.IGNORECASE) if options.has_key("-z"): command = '%s %s %s %s' % (SSL_PATH, force_ipvx, options["-a"], options["-u"]) try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: ## SSL telnet is part of the fencing package sys.stderr.write(str(ex) + "\n") sys.exit(EC_GENERIC_ERROR) elif options.has_key("-x") and 0 == options.has_key("-k"): command = '%s %s %s@%s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) if options.has_key("telnet_over_ssh"): #This is for stupid ssh servers (like ALOM) which behave more like telnet (ignore name and display login prompt) result = conn.log_expect(options, [ re_login, "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") # Host identity confirm conn.log_expect(options, re_login, int(options["-y"])) conn.sendline(options["-l"]) conn.log_expect(options, re_pass, int(options["-y"])) else: result = conn.log_expect(options, [ "ssword:", "Are you sure you want to continue connecting (yes/no)?" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, "ssword:", int(options["-y"])) conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) elif options.has_key("-x") and 1 == options.has_key("-k"): command = '%s %s %s@%s -i %s -p %s' % (SSH_PATH, force_ipvx, options["-l"], options["-a"], options["-k"], options["-u"]) if options.has_key("ssh_options"): command += ' ' + options["ssh_options"] try: conn = fspawn(command) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) result = conn.log_expect(options, [ options["-c"], "Are you sure you want to continue connecting (yes/no)?", "Enter passphrase for key '"+options["-k"]+"':" ], int(options["-y"])) if result == 1: conn.sendline("yes") conn.log_expect(options, [ options["-c"], "Enter passphrase for key '"+options["-k"]+"':"] , int(options["-y"])) if result != 0: if options.has_key("-p"): conn.sendline(options["-p"]) conn.log_expect(options, options["-c"], int(options["-y"])) else: fail_usage("Failed: You have to enter passphrase (-p) for identity file") else: try: conn = fspawn(TELNET_PATH) conn.send("set binary\n") conn.send("open %s -%s\n"%(options["-a"], options["-u"])) except pexpect.ExceptionPexpect, ex: sys.stderr.write(str(ex) + "\n") sys.stderr.write("Due to limitations, binary dependencies on fence agents " "are not in the spec file and must be installed separately." + "\n") sys.exit(EC_GENERIC_ERROR) conn.log_expect(options, re_login, int(options["-y"])) conn.send(options["-l"] + login_eol) conn.log_expect(options, re_pass, int(options["-Y"])) conn.send(options["-p"] + login_eol) conn.log_expect(options, options["-c"], int(options["-Y"])) except pexpect.EOF: fail(EC_LOGIN_DENIED) except pexpect.TIMEOUT: fail(EC_LOGIN_DENIED) return conn
Python
#!/usr/bin/env python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com import sys, string, getopt import XenAPI def usage(): print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]" print "Where:-" print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"." print " -h : Print this help message." print " -l : The username for the XenServer host." print " -p : The password for the XenServer host." print " -s : The URL of the web interface on the XenServer host." print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return" print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\"" print " then the UUID must be specified." # Process command line options and populate the config array def process_opts(): config = { "action" : "status", "session_url" : "", "session_user" : "", "session_pass" : "", "uuid" : "", "name" : "", "verbose" : False } # If we have at least one argument then we want to parse the command line using getopts if len(sys.argv) > 1: try: opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="]) except getopt.GetoptError, err: # We got an unrecognised option, so print he help message and exit print str(err) usage() sys.exit(1) for opt, arg in opts: if opt in ("-v", "--verbose"): config["verbose"] = True elif opt in ("-a", "--action"): config["action"] = clean_action(arg) elif opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-s", "--session-url"): config["session_url"] = arg elif opt in ("-l", "--login-name"): config["session_user"] = arg elif opt in ("-n", "--name"): config["name"] = arg elif opt in ("-p", "--password"): config["session_pass"] = arg elif opt in ("-U", "--uuid"): config["uuid"] = arg.lower() else: assert False, "unhandled option" # Otherwise process stdin for parameters. This is to handle the Red Hat clustering # mechanism where by fenced passes in name/value pairs instead of using command line # options. else: for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] name = clean_param_name(name) if name == "action": value = clean_action(value) if name in config: config[name] = value else: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ): print "You must specify the session url, username and password."; usage(); sys.exit(2); return config # why, well just to be nice. Given an action will return the corresponding # value that the rest of the script uses. def clean_action(action): if action.lower() in ("on", "poweron", "powerup"): return "on" elif action.lower() in ("off", "poweroff", "powerdown"): return "off" elif action.lower() in ("reboot", "reset", "restart"): return "reboot" elif action.lower() in ("status", "powerstatus", "list"): return "status" else: print "Bad action", action usage() exit(4) # why, well just to be nice. Given a parameter will return the corresponding # value that the rest of the script uses. def clean_param_name(name): if name.lower() in ("action", "operation", "op"): return "action" elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"): return "session_user" elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"): return "session_pass" elif name.lower() in ("session_url", "url", "session-url"): return "session_url" else: # we should never get here as getopt should handle the checking of this input. print "Bad parameter specified", name usage() exit(5) # Print the power status of a VM. If no UUID is given, then all VM's are queried def get_power_status(session, uuid = "", name = ""): try: # If the UUID hasn't been set, then output the status of all # valid virtual machines. if( len(uuid) > 0 ): vms = [session.xenapi.VM.get_by_uuid(uuid)] elif( len(name) > 0 ): vms = session.xenapi.VM.get_by_name_label(name) else: vms = session.xenapi.VM.get_all() for vm in vms: record = session.xenapi.VM.get_record(vm); # We only want to print out the status for actual virtual machines. The above get_all function # returns any templates and also the control domain. This is one of the reasons the process # takes such a long time to list all VM's. Hopefully there is a way to filter this in the # request packet in the future. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); def set_power_status(session, uuid, name, action): try: vm = None if( len(uuid) > 0 ): vm = session.xenapi.VM.get_by_uuid(uuid) elif( len(name) > 0 ): vm_arr = session.xenapi.VM.get_by_name_label(name) if( len(vm_arr) == 1 ): vm = vm_arr[0] else raise Exception("Multiple VM's have that name. Use UUID instead.") if( vm != None ): record = session.xenapi.VM.get_record(vm); if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): session.xenapi.VM.start(vm, False, True) elif( action == "off" ): session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): session.xenapi.VM.hard_reboot(vm) else: raise Exception("Bad power status"); except Exception, exn: print str(exn); def main(): config = process_opts(); session = session_start(config["session_url"]); session_login(session, config["session_user"], config["session_pass"]); if( config["action"] == "status" ): get_power_status(session, config["uuid"], config["name"]) else: if( config["verbose"] ): print "Power status before action" get_power_status(session, config["uuid"]) set_power_status(session, config["uuid"], config["name"], config["action"]) if( config["verbose"] ): print "Power status after action" get_power_status(session, config["uuid"]) # Function to initiate the session with the XenServer system def session_start(url): try: session = XenAPI.Session(url); except Exception, exn: print str(exn); sys.exit(3); return session; def session_login(session, username, password): try: session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); sys.exit(3); if __name__ == "__main__": main() # vim:set ts=4 sw=4
Python
#!/usr/bin/env python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com import sys, string, getopt import XenAPI def usage(): print "Usage: fence_cxs [-hv] [-a <action>] -l <login username> -p <login password> -s <session url> [-u <UUID>]" print "Where:-" print " -a : Specifies the action to perfom. Can be any of \"on|off|reboot|status|list\". Defaults to \"status\"." print " -h : Print this help message." print " -l : The username for the XenServer host." print " -p : The password for the XenServer host." print " -s : The URL of the web interface on the XenServer host." print " -U : The UUID of the virtual machine to fence or query. Defaults to the empty string which will return" print " the status of all hosts when action is set to \"status\". If the action is set to \"on|off|reboot\"" print " then the UUID must be specified." # Process command line options and populate the config array def process_opts(): config = { "action" : "status", "session_url" : "", "session_user" : "", "session_pass" : "", "uuid" : "", "name" : "", "verbose" : False } # If we have at least one argument then we want to parse the command line using getopts if len(sys.argv) > 1: try: opts, args = getopt.getopt(sys.argv[1:], "a:hl:n:s:p:U:v", ["help", "verbose", "action=", "session-url=", "login-name=", "name=", "password=", "uuid="]) except getopt.GetoptError, err: # We got an unrecognised option, so print he help message and exit print str(err) usage() sys.exit(1) for opt, arg in opts: if opt in ("-v", "--verbose"): config["verbose"] = True elif opt in ("-a", "--action"): config["action"] = clean_action(arg) elif opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-s", "--session-url"): config["session_url"] = arg elif opt in ("-l", "--login-name"): config["session_user"] = arg elif opt in ("-n", "--name"): config["name"] = arg elif opt in ("-p", "--password"): config["session_pass"] = arg elif opt in ("-U", "--uuid"): config["uuid"] = arg.lower() else: assert False, "unhandled option" # Otherwise process stdin for parameters. This is to handle the Red Hat clustering # mechanism where by fenced passes in name/value pairs instead of using command line # options. else: for line in sys.stdin.readlines(): line = line.strip() if ((line.startswith("#")) or (len(line) == 0)): continue (name, value) = (line + "=").split("=", 1) value = value[:-1] name = clean_param_name(name) if name == "action": value = clean_action(value) if name in config: config[name] = value else: sys.stderr.write("Parse error: Ignoring unknown option '"+line+"'\n") if( config["session_url"] == "" or config["session_user"] == "" or config["session_pass"] == "" ): print "You must specify the session url, username and password."; usage(); sys.exit(2); return config # why, well just to be nice. Given an action will return the corresponding # value that the rest of the script uses. def clean_action(action): if action.lower() in ("on", "poweron", "powerup"): return "on" elif action.lower() in ("off", "poweroff", "powerdown"): return "off" elif action.lower() in ("reboot", "reset", "restart"): return "reboot" elif action.lower() in ("status", "powerstatus", "list"): return "status" else: print "Bad action", action usage() exit(4) # why, well just to be nice. Given a parameter will return the corresponding # value that the rest of the script uses. def clean_param_name(name): if name.lower() in ("action", "operation", "op"): return "action" elif name.lower() in ("session_user", "login", "login-name", "login_name", "user", "username", "session-user"): return "session_user" elif name.lower() in ("session_pass", "pass", "passwd", "password", "session-pass"): return "session_pass" elif name.lower() in ("session_url", "url", "session-url"): return "session_url" else: # we should never get here as getopt should handle the checking of this input. print "Bad parameter specified", name usage() exit(5) # Print the power status of a VM. If no UUID is given, then all VM's are queried def get_power_status(session, uuid = "", name = ""): try: # If the UUID hasn't been set, then output the status of all # valid virtual machines. if( len(uuid) > 0 ): vms = [session.xenapi.VM.get_by_uuid(uuid)] elif( len(name) > 0 ): vms = session.xenapi.VM.get_by_name_label(name) else: vms = session.xenapi.VM.get_all() for vm in vms: record = session.xenapi.VM.get_record(vm); # We only want to print out the status for actual virtual machines. The above get_all function # returns any templates and also the control domain. This is one of the reasons the process # takes such a long time to list all VM's. Hopefully there is a way to filter this in the # request packet in the future. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); def set_power_status(session, uuid, name, action): try: vm = None if( len(uuid) > 0 ): vm = session.xenapi.VM.get_by_uuid(uuid) elif( len(name) > 0 ): vm_arr = session.xenapi.VM.get_by_name_label(name) if( len(vm_arr) == 1 ): vm = vm_arr[0] else raise Exception("Multiple VM's have that name. Use UUID instead.") if( vm != None ): record = session.xenapi.VM.get_record(vm); if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): session.xenapi.VM.start(vm, False, True) elif( action == "off" ): session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): session.xenapi.VM.hard_reboot(vm) else: raise Exception("Bad power status"); except Exception, exn: print str(exn); def main(): config = process_opts(); session = session_start(config["session_url"]); session_login(session, config["session_user"], config["session_pass"]); if( config["action"] == "status" ): get_power_status(session, config["uuid"], config["name"]) else: if( config["verbose"] ): print "Power status before action" get_power_status(session, config["uuid"]) set_power_status(session, config["uuid"], config["name"], config["action"]) if( config["verbose"] ): print "Power status after action" get_power_status(session, config["uuid"]) # Function to initiate the session with the XenServer system def session_start(url): try: session = XenAPI.Session(url); except Exception, exn: print str(exn); sys.exit(3); return session; def session_login(session, username, password): try: session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); sys.exit(3); if __name__ == "__main__": main() # vim:set ts=4 sw=4
Python
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================ # Copyright (C) 2006 XenSource Inc. #============================================================================ # # Parts of this file are based upon xmlrpclib.py, the XML-RPC client # interface included in the Python distribution. # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- import gettext import xmlrpclib import httplib import socket translation = gettext.translation('xen-xm', fallback = True) class Failure(Exception): def __init__(self, details): try: # If this failure is MESSAGE_PARAMETER_COUNT_MISMATCH, then we # correct the return values here, to account for the fact that we # transparently add the session handle as the first argument. if details[0] == 'MESSAGE_PARAMETER_COUNT_MISMATCH': details[2] = str(int(details[2]) - 1) details[3] = str(int(details[3]) - 1) self.details = details except Exception, exn: self.details = ['INTERNAL_ERROR', 'Client-side: ' + str(exn)] def __str__(self): try: return translation.ugettext(self.details[0]) % self._details_map() except TypeError, exn: return "Message database broken: %s.\nXen-API failure: %s" % \ (exn, str(self.details)) except Exception, exn: import sys print >>sys.stderr, exn return "Xen-API failure: %s" % str(self.details) def _details_map(self): return dict([(str(i), self.details[i]) for i in range(len(self.details))]) _RECONNECT_AND_RETRY = (lambda _ : ()) class UDSHTTPConnection(httplib.HTTPConnection): """ Stupid hacked up HTTPConnection subclass to allow HTTP over Unix domain sockets. """ def connect(self): path = self.host.replace("_", "/") self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(path) class UDSHTTP(httplib.HTTP): _connection_class = UDSHTTPConnection class UDSTransport(xmlrpclib.Transport): def make_connection(self, host): return UDSHTTP(host) class Session(xmlrpclib.ServerProxy): """A server proxy and session manager for communicating with Xend using the Xen-API. Example: session = Session('http://localhost:9363/') session.login_with_password('me', 'mypassword') session.xenapi.VM.start(vm_uuid) session.xenapi.session.logout() For now, this class also supports the legacy XML-RPC API, using session.xend.domain('Domain-0') and similar. This support will disappear once there is a working Xen-API replacement for every call in the legacy API. """ def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=1): xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose, allow_none) self._session = None self.last_login_method = None self.last_login_params = None def xenapi_request(self, methodname, params): if methodname.startswith('login'): self._login(methodname, params) return None else: retry_count = 0 while retry_count < 3: full_params = (self._session,) + params result = _parse_result(getattr(self, methodname)(*full_params)) if result == _RECONNECT_AND_RETRY: retry_count += 1 if self.last_login_method: self._login(self.last_login_method, self.last_login_params) else: raise xmlrpclib.Fault(401, 'You must log in') else: return result raise xmlrpclib.Fault( 500, 'Tried 3 times to get a valid session, but failed') def _login(self, method, params): result = _parse_result(getattr(self, 'session.%s' % method)(*params)) if result == _RECONNECT_AND_RETRY: raise xmlrpclib.Fault( 500, 'Received SESSION_INVALID when logging in') self._session = result self.last_login_method = method self.last_login_params = params def __getattr__(self, name): if name == 'xenapi': return _Dispatcher(self.xenapi_request, None) elif name.startswith('login'): return lambda *params: self._login(name, params) else: return xmlrpclib.ServerProxy.__getattr__(self, name) def xapi_local(): return Session("http://_var_xapi_xapi/", transport=UDSTransport()) def _parse_result(result): if type(result) != dict or 'Status' not in result: raise xmlrpclib.Fault(500, 'Missing Status in response from server' + result) if result['Status'] == 'Success': if 'Value' in result: return result['Value'] else: raise xmlrpclib.Fault(500, 'Missing Value in response from server') else: if 'ErrorDescription' in result: if result['ErrorDescription'][0] == 'SESSION_INVALID': return _RECONNECT_AND_RETRY else: raise Failure(result['ErrorDescription']) else: raise xmlrpclib.Fault( 500, 'Missing ErrorDescription in response from server') # Based upon _Method from xmlrpclib. class _Dispatcher: def __init__(self, send, name): self.__send = send self.__name = name def __repr__(self): if self.__name: return '<XenAPI._Dispatcher for %s>' % self.__name else: return '<XenAPI._Dispatcher>' def __getattr__(self, name): if self.__name is None: return _Dispatcher(self.__send, name) else: return _Dispatcher(self.__send, "%s.%s" % (self.__name, name)) def __call__(self, *args): return self.__send(self.__name, args)
Python
#!/usr/bin/python # ############################################################################# # Copyright 2011 Matt Clark # This file is part of fence-xenserver # # fence-xenserver is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # fence-xenserver is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com ############################################################################# ############################################################################# # It's only just begun... # Current status: completely usable. This script is now working well and, # has a lot of functionality as a result of the fencing.py library and the # XenAPI libary. ############################################################################# # Please let me know if you are using this script so that I can work out # whether I should continue support for it. mattjclark0407 at hotmail dot com from fencing import * import XenAPI EC_BAD_SESSION = 1 # Find the status of the port given in the -U flag of options. def get_power_fn(session, options): if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): status = record["power_state"] if verbose: print "UUID:", record["uuid"], "NAME:", record["name_label"], "POWER STATUS:", record["power_state"] # Note that the VM can be in the following states (from the XenAPI document) # Halted: VM is offline and not using any resources. # Paused: All resources have been allocated but the VM itself is paused and its vCPUs are not running # Running: Running # Paused: VM state has been saved to disk and it is nolonger running. Note that disks remain in-Use while # We want to make sure that we only return the status "off" if the machine is actually halted as the status # is checked before a fencing action. Only when the machine is Halted is it not consuming resources which # may include whatever you are trying to protect with this fencing action. return (status=="Halted" and "off" or "on") except Exception, exn: print str(exn) return "Error" # Set the state of the port given in the -U flag of options. def set_power_fn(session, options): action = options["-o"].lower() if options.has_key("-v"): verbose = True else: verbose = False try: # Get a reference to the vm specified in the UUID or vm_name parameter vm = return_vm_reference(session, options) # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm) # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): if( action == "on" ): # Start the VM session.xenapi.VM.start(vm, False, True) elif( action == "off" ): # Force shutdown the VM session.xenapi.VM.hard_shutdown(vm) elif( action == "reboot" ): # Force reboot the VM session.xenapi.VM.hard_reboot(vm) except Exception, exn: print str(exn); # Function to populate an array of virtual machines and their status def get_outlet_list(session, options): result = {} if options.has_key("-v"): verbose = True else: verbose = False try: # Return an array of all the VM's on the host vms = session.xenapi.VM.get_all() for vm in vms: # Query the VM for its' associated parameters record = session.xenapi.VM.get_record(vm); # Check that we are not trying to manipulate a template or a control # domain as they show up as VM's with specific properties. if not(record["is_a_template"]) and not(record["is_control_domain"]): name = record["name_label"] uuid = record["uuid"] status = record["power_state"] result[uuid] = (name, status) if verbose: print "UUID:", record["uuid"], "NAME:", name, "POWER STATUS:", record["power_state"] except Exception, exn: print str(exn); return result # Function to initiate the XenServer session via the XenAPI library. def connect_and_login(options): url = options["-s"] username = options["-l"] password = options["-p"] try: # Create the XML RPC session to the specified URL. session = XenAPI.Session(url); # Login using the supplied credentials. session.xenapi.login_with_password(username, password); except Exception, exn: print str(exn); # http://sources.redhat.com/cluster/wiki/FenceAgentAPI says that for no connectivity # the exit value should be 1. It doesn't say anything about failed logins, so # until I hear otherwise it is best to keep this exit the same to make sure that # anything calling this script (that uses the same information in the web page # above) knows that this is an error condition, not a msg signifying a down port. sys.exit(EC_BAD_SESSION); return session; # return a reference to the VM by either using the UUID or the vm_name. If the UUID is set then # this is tried first as this is the only properly unique identifier. # Exceptions are not handled in this function, code that calls this must be ready to handle them. def return_vm_reference(session, options): if options.has_key("-v"): verbose = True else: verbose = False # Case where the UUID has been specified if options.has_key("-U"): uuid = options["-U"].lower() # When using the -n parameter for name, we get an error message (in verbose # mode) that tells us that we didn't find a VM. To immitate that here we # need to catch and re-raise the exception produced by get_by_uuid. try: return session.xenapi.VM.get_by_uuid(uuid) except Exception,exn: if verbose: print "No VM's found with a UUID of \"%s\"" %uuid raise # Case where the vm_name has been specified if options.has_key("-n"): vm_name = options["-n"] vm_arr = session.xenapi.VM.get_by_name_label(vm_name) # Need to make sure that we only have one result as the vm_name may # not be unique. Average case, so do it first. if len(vm_arr) == 1: return vm_arr[0] else: if len(vm_arr) == 0: if verbose: print "No VM's found with a name of \"%s\"" %vm_name # NAME_INVALID used as the XenAPI throws a UUID_INVALID if it can't find # a VM with the specified UUID. This should make the output look fairly # consistent. raise Exception("NAME_INVALID") else: if verbose: print "Multiple VM's have the name \"%s\", use UUID instead" %vm_name raise Exception("MULTIPLE_VMS_FOUND") # We should never get to this case as the input processing checks that either the UUID or # the name parameter is set. Regardless of whether or not a VM is found the above if # statements will return to the calling function (either by exception or by a reference # to the VM). raise Exception("VM_LOGIC_ERROR") def main(): device_opt = [ "help", "version", "agent", "quiet", "verbose", "debug", "action", "login", "passwd", "passwd_script", "vm_name", "test", "separator", "no_login", "no_password", "power_timeout", "shell_timeout", "login_timeout", "power_wait", "session_url", "uuid" ] atexit.register(atexit_handler) options=process_input(device_opt) options = check_input(device_opt, options) docs = { } docs["shortdesc"] = "XenAPI based fencing for the Citrix XenServer virtual machines." docs["longdesc"] = "\ fence_cxs is an I/O Fencing agent used on Citrix XenServer hosts. \ It uses the XenAPI, supplied by Citrix, to establish an XML-RPC sesssion \ to a XenServer host. Once the session is established, further XML-RPC \ commands are issued in order to switch on, switch off, restart and query \ the status of virtual machines running on the host." show_docs(options, docs) xenSession = connect_and_login(options) # Operate the fencing device result = fence_action(xenSession, options, set_power_fn, get_power_fn, get_outlet_list) sys.exit(result) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from bottle import Bottle, request, response import json app = Bottle() #curl -v -X GET -H "Content-type: application/json" -H "Accept: application/json" -G -d "lat=-27.061611&lon=-55.62703" localhost:10080/ferias @app.get('/ferias') def ferias_get(): lat = request.query.lat or False lon = request.query.lon or False if lat and lon: libro1 = { 'id': 'localhost:10080/ferias/5', 'nombre': 'nombre5', 'direccion': 'direccion5', 'ciudad': 'ciudad5', 'pais': 'pais5', 'marcas': ('nike','puma'), 'precios': (10000,20000,30000), 'productos': ('zapatos','medias') } libro2 = { 'id': 'localhost:10080/ferias/7', 'nombre': 'nombre7', 'direccion': 'dirreccion7', 'ciudad': 'ciudad7', 'pais': 'pais7', 'marcas': ('adidas','fila'), 'precios': (40000,50000,60000), 'productos': ('zapatos','medias') } libro3 = { 'id': 'localhost:10080/ferias/9', 'nombre': 'nombre9', 'direccion': 'dirreccion9', 'ciudad': 'ciudad9', 'pais': 'pais9', 'marcas': ('adidas','fila'), 'precios': (40000,50000,60000), 'productos': ('zapatos','medias') } else: libro1 = { 'id': 'localhost:10080/ferias/1', 'nombre': 'nombre1', 'direccion': 'direccion1', 'ciudad': 'ciudad1', 'pais': 'pais1', 'marcas': ('nike','puma'), 'precios': (10000,20000,30000), 'productos': ('zapatos','medias') } libro2 = { 'id': 'localhost:10080/ferias/2', 'nombre': 'nombre2', 'direccion': 'dirreccion2', 'ciudad': 'ciudad2', 'pais': 'pais2', 'marcas': ('adidas','fila'), 'precios': (40000,50000,60000), 'productos': ('zapatos','medias') } libro3 = { 'id': 'localhost:10080/ferias/3', 'nombre': 'nombre3', 'direccion': 'dirreccion3', 'ciudad': 'ciudad3', 'pais': 'pais3', 'marcas': ('adidas','fila'), 'precios': (40000,50000,60000), 'productos': ('zapatos','medias') } response.content_type = 'application/json; charset=UTF-8' data = [libro1,libro2,libro3] return json.dumps(data) app.run(server='gae')
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file and with no dependencies other than the Python Standard Library. Homepage and documentation: http://bottlepy.org/ Copyright (c) 2014, Marcel Hellkamp. License: MIT (see LICENSE for details) """ from __future__ import with_statement __author__ = 'Marcel Hellkamp' __version__ = '0.13-dev' __license__ = 'MIT' # The gevent and eventlet server adapters need to patch some modules before # they are imported. This is why we parse the commandline parameters here but # handle them later if __name__ == '__main__': from optparse import OptionParser _cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app") _opt = _cmd_parser.add_option _opt("--version", action="store_true", help="show version number.") _opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.") _opt("-s", "--server", default='wsgiref', help="use SERVER as backend.") _opt("-p", "--plugin", action="append", help="install additional plugin/s.") _opt("--debug", action="store_true", help="start server in debug mode.") _opt("--reload", action="store_true", help="auto-reload on file changes.") _cmd_options, _cmd_args = _cmd_parser.parse_args() if _cmd_options.server: if _cmd_options.server.startswith('gevent'): import gevent.monkey; gevent.monkey.patch_all() elif _cmd_options.server.startswith('eventlet'): import eventlet; eventlet.monkey_patch() import base64, cgi, email.utils, functools, hmac, imp, itertools, mimetypes,\ os, re, subprocess, sys, tempfile, threading, time, warnings from datetime import date as datedate, datetime, timedelta from tempfile import TemporaryFile from traceback import format_exc, print_exc from inspect import getargspec from unicodedata import normalize try: from simplejson import dumps as json_dumps, loads as json_lds except ImportError: # pragma: no cover try: from json import dumps as json_dumps, loads as json_lds except ImportError: try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds except ImportError: def json_dumps(data): raise ImportError("JSON support requires Python 2.6 or simplejson.") json_lds = json_dumps # We now try to fix 2.5/2.6/3.1/3.2 incompatibilities. # It ain't pretty but it works... Sorry for the mess. py = sys.version_info py3k = py >= (3, 0, 0) py25 = py < (2, 6, 0) py31 = (3, 1, 0) <= py < (3, 2, 0) # Workaround for the missing "as" keyword in py3k. def _e(): return sys.exc_info()[1] # Workaround for the "print is a keyword/function" Python 2/3 dilemma # and a fallback for mod_wsgi (resticts stdout/err attribute access) try: _stdout, _stderr = sys.stdout.write, sys.stderr.write except IOError: _stdout = lambda x: sys.stdout.write(x) _stderr = lambda x: sys.stderr.write(x) # Lots of stdlib and builtin differences. if py3k: import http.client as httplib import _thread as thread from urllib.parse import urljoin, SplitResult as UrlSplitResult from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote urlunquote = functools.partial(urlunquote, encoding='latin1') from http.cookies import SimpleCookie from collections import MutableMapping as DictMixin import pickle from io import BytesIO from configparser import ConfigParser basestring = str unicode = str json_loads = lambda s: json_lds(touni(s)) callable = lambda x: hasattr(x, '__call__') imap = map def _raise(*a): raise a[0](a[1]).with_traceback(a[2]) else: # 2.x import httplib import thread from urlparse import urljoin, SplitResult as UrlSplitResult from urllib import urlencode, quote as urlquote, unquote as urlunquote from Cookie import SimpleCookie from itertools import imap import cPickle as pickle from StringIO import StringIO as BytesIO from ConfigParser import SafeConfigParser as ConfigParser if py25: msg = "Python 2.5 support may be dropped in future versions of Bottle." warnings.warn(msg, DeprecationWarning) from UserDict import DictMixin def next(it): return it.next() bytes = str else: # 2.6, 2.7 from collections import MutableMapping as DictMixin unicode = unicode json_loads = json_lds eval(compile('def _raise(*a): raise a[0], a[1], a[2]', '<py3fix>', 'exec')) # Some helpers for string/byte handling def tob(s, enc='utf8'): return s.encode(enc) if isinstance(s, unicode) else bytes(s) def touni(s, enc='utf8', err='strict'): if isinstance(s, bytes): return s.decode(enc, err) else: return unicode(s or ("" if s is None else s)) tonat = touni if py3k else tob # 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense). # 3.1 needs a workaround. if py31: from io import TextIOWrapper class NCTextIOWrapper(TextIOWrapper): def close(self): pass # Keep wrapped buffer open. # A bug in functools causes it to break if the wrapper is an instance method def update_wrapper(wrapper, wrapped, *a, **ka): try: functools.update_wrapper(wrapper, wrapped, *a, **ka) except AttributeError: pass # These helpers are used at module level and need to be defined first. # And yes, I know PEP-8, but sometimes a lower-case classname makes more sense. def depr(message, strict=False): warnings.warn(message, DeprecationWarning, stacklevel=3) def makelist(data): # This is just to handy if isinstance(data, (tuple, list, set, dict)): return list(data) elif data: return [data] else: return [] class DictProperty(object): """ Property that maps to a key in a local dict-like attribute. """ def __init__(self, attr, key=None, read_only=False): self.attr, self.key, self.read_only = attr, key, read_only def __call__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter, self.key = func, self.key or func.__name__ return self def __get__(self, obj, cls): if obj is None: return self key, storage = self.key, getattr(obj, self.attr) if key not in storage: storage[key] = self.getter(obj) return storage[key] def __set__(self, obj, value): if self.read_only: raise AttributeError("Read-Only property.") getattr(obj, self.attr)[self.key] = value def __delete__(self, obj): if self.read_only: raise AttributeError("Read-Only property.") del getattr(obj, self.attr)[self.key] class cached_property(object): """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value class lazy_attribute(object): """ A property that caches itself to the class object. """ def __init__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter = func def __get__(self, obj, cls): value = self.getter(cls) setattr(cls, self.__name__, value) return value ############################################################################### # Exceptions and Events ######################################################## ############################################################################### class BottleException(Exception): """ A base class for exceptions used by bottle. """ pass ############################################################################### # Routing ###################################################################### ############################################################################### class RouteError(BottleException): """ This is a base class for all routing related exceptions """ class RouteReset(BottleException): """ If raised by a plugin or request handler, the route is reset and all plugins are re-applied. """ class RouterUnknownModeError(RouteError): pass class RouteSyntaxError(RouteError): """ The route parser found something not supported by this router. """ class RouteBuildError(RouteError): """ The route could not be built. """ def _re_flatten(p): """ Turn all capturing groups in a regular expression pattern into non-capturing groups. """ if '(' not in p: return p return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p) class Router(object): """ A Router is an ordered collection of route->target pairs. It is used to efficiently match WSGI requests against a number of routes and return the first target that satisfies the request. The target may be anything, usually a string, ID or callable object. A route consists of a path-rule and a HTTP method. The path-rule is either a static path (e.g. `/contact`) or a dynamic path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax and details on the matching order are described in docs:`routing`. """ default_pattern = '[^/]+' default_filter = 're' #: The current CPython regexp implementation does not allow more #: than 99 matching groups per regular expression. _MAX_GROUPS_PER_PATTERN = 99 def __init__(self, strict=False): self.rules = [] # All rules in order self._groups = {} # index of regexes to find them in dyna_routes self.builder = {} # Data structure for the url builder self.static = {} # Search structure for static routes self.dyna_routes = {} self.dyna_regexes = {} # Search structure for dynamic routes #: If true, static routes are no longer checked first. self.strict_order = strict self.filters = { 're': lambda conf: (_re_flatten(conf or self.default_pattern), None, None), 'int': lambda conf: (r'-?\d+', int, lambda x: str(int(x))), 'float': lambda conf: (r'-?[\d.]+', float, lambda x: str(float(x))), 'path': lambda conf: (r'.+?', None, None)} def add_filter(self, name, func): """ Add a filter. The provided function is called with the configuration string as parameter and must return a (regexp, to_python, to_url) tuple. The first element is a string, the last two are callables or None. """ self.filters[name] = func rule_syntax = re.compile('(\\\\*)' '(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)' '|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)' '(?::((?:\\\\.|[^\\\\>]+)+)?)?)?>))') def _itertokens(self, rule): offset, prefix = 0, '' for match in self.rule_syntax.finditer(rule): prefix += rule[offset:match.start()] g = match.groups() if len(g[0])%2: # Escaped wildcard prefix += match.group(0)[len(g[0]):] offset = match.end() continue if prefix: yield prefix, None, None name, filtr, conf = g[4:7] if g[2] is None else g[1:4] yield name, filtr or 'default', conf or None offset, prefix = match.end(), '' if offset <= len(rule) or prefix: yield prefix+rule[offset:], None, None def add(self, rule, method, target, name=None): """ Add a new rule or replace the target for an existing rule. """ anons = 0 # Number of anonymous wildcards found keys = [] # Names of keys pattern = '' # Regular expression pattern with named groups filters = [] # Lists of wildcard input filters builder = [] # Data structure for the URL builder is_static = True for key, mode, conf in self._itertokens(rule): if mode: is_static = False if mode == 'default': mode = self.default_filter mask, in_filter, out_filter = self.filters[mode](conf) if not key: pattern += '(?:%s)' % mask key = 'anon%d' % anons anons += 1 else: pattern += '(?P<%s>%s)' % (key, mask) keys.append(key) if in_filter: filters.append((key, in_filter)) builder.append((key, out_filter or str)) elif key: pattern += re.escape(key) builder.append((None, key)) self.builder[rule] = builder if name: self.builder[name] = builder if is_static and not self.strict_order: self.static.setdefault(method, {}) self.static[method][self.build(rule)] = (target, None) return try: re_pattern = re.compile('^(%s)$' % pattern) re_match = re_pattern.match except re.error: raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e())) if filters: def getargs(path): url_args = re_match(path).groupdict() for name, wildcard_filter in filters: try: url_args[name] = wildcard_filter(url_args[name]) except ValueError: raise HTTPError(400, 'Path has wrong format.') return url_args elif re_pattern.groupindex: def getargs(path): return re_match(path).groupdict() else: getargs = None flatpat = _re_flatten(pattern) whole_rule = (rule, flatpat, target, getargs) if (flatpat, method) in self._groups: if DEBUG: msg = 'Route <%s %s> overwrites a previously defined route' warnings.warn(msg % (method, rule), RuntimeWarning) self.dyna_routes[method][self._groups[flatpat, method]] = whole_rule else: self.dyna_routes.setdefault(method, []).append(whole_rule) self._groups[flatpat, method] = len(self.dyna_routes[method]) - 1 self._compile(method) def _compile(self, method): all_rules = self.dyna_routes[method] comborules = self.dyna_regexes[method] = [] maxgroups = self._MAX_GROUPS_PER_PATTERN for x in range(0, len(all_rules), maxgroups): some = all_rules[x:x+maxgroups] combined = (flatpat for (_, flatpat, _, _) in some) combined = '|'.join('(^%s$)' % flatpat for flatpat in combined) combined = re.compile(combined).match rules = [(target, getargs) for (_, _, target, getargs) in some] comborules.append((combined, rules)) def build(self, _name, *anons, **query): """ Build an URL by filling the wildcards in a rule. """ builder = self.builder.get(_name) if not builder: raise RouteBuildError("No route with that name.", _name) try: for i, value in enumerate(anons): query['anon%d'%i] = value url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder]) return url if not query else url+'?'+urlencode(query) except KeyError: raise RouteBuildError('Missing URL argument: %r' % _e().args[0]) def match(self, environ): """ Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). """ verb = environ['REQUEST_METHOD'].upper() path = environ['PATH_INFO'] or '/' if verb == 'HEAD': methods = ['PROXY', verb, 'GET', 'ANY'] else: methods = ['PROXY', verb, 'ANY'] for method in methods: if method in self.static and path in self.static[method]: target, getargs = self.static[method][path] return target, getargs(path) if getargs else {} elif method in self.dyna_regexes: for combined, rules in self.dyna_regexes[method]: match = combined(path) if match: target, getargs = rules[match.lastindex - 1] return target, getargs(path) if getargs else {} # No matching route found. Collect alternative methods for 405 response allowed = set([]) nocheck = set(methods) for method in set(self.static) - nocheck: if path in self.static[method]: allowed.add(verb) for method in set(self.dyna_regexes) - allowed - nocheck: for combined, rules in self.dyna_regexes[method]: match = combined(path) if match: allowed.add(method) if allowed: allow_header = ",".join(sorted(allowed)) raise HTTPError(405, "Method not allowed.", Allow=allow_header) # No matching route and no alternative method found. We give up raise HTTPError(404, "Not found: " + repr(path)) class Route(object): """ This class wraps a route callback along with route specific metadata and configuration and applies Plugins on demand. It is also responsible for turing an URL path rule into a regular expression usable by the Router. """ def __init__(self, app, rule, method, callback, name=None, plugins=None, skiplist=None, **config): #: The application this route is installed to. self.app = app #: The path-rule string (e.g. ``/wiki/:page``). self.rule = rule #: The HTTP method as a string (e.g. ``GET``). self.method = method #: The original callback with no plugins applied. Useful for introspection. self.callback = callback #: The name of the route (if specified) or ``None``. self.name = name or None #: A list of route-specific plugins (see :meth:`Bottle.route`). self.plugins = plugins or [] #: A list of plugins to not apply to this route (see :meth:`Bottle.route`). self.skiplist = skiplist or [] #: Additional keyword arguments passed to the :meth:`Bottle.route` #: decorator are stored in this dictionary. Used for route-specific #: plugin configuration and meta-data. self.config = ConfigDict().load_dict(config) @cached_property def call(self): """ The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.""" return self._make_callback() def reset(self): """ Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied. """ self.__dict__.pop('call', None) def prepare(self): """ Do all on-demand work immediately (useful for debugging).""" self.call def all_plugins(self): """ Yield all Plugins affecting this route. """ unique = set() for p in reversed(self.app.plugins + self.plugins): if True in self.skiplist: break name = getattr(p, 'name', False) if name and (name in self.skiplist or name in unique): continue if p in self.skiplist or type(p) in self.skiplist: continue if name: unique.add(name) yield p def _make_callback(self): callback = self.callback for plugin in self.all_plugins(): try: if hasattr(plugin, 'apply'): callback = plugin.apply(callback, self) else: callback = plugin(callback) except RouteReset: # Try again with changed configuration. return self._make_callback() if not callback is self.callback: update_wrapper(callback, self.callback) return callback def get_undecorated_callback(self): """ Return the callback. If the callback is a decorated function, try to recover the original function. """ func = self.callback func = getattr(func, '__func__' if py3k else 'im_func', func) closure_attr = '__closure__' if py3k else 'func_closure' while hasattr(func, closure_attr) and getattr(func, closure_attr): func = getattr(func, closure_attr)[0].cell_contents return func def get_callback_args(self): """ Return a list of argument names the callback (most likely) accepts as keyword arguments. If the callback is a decorated function, try to recover the original function before inspection. """ return getargspec(self.get_undecorated_callback())[0] def get_config(self, key, default=None): """ Lookup a config field and return its value, first checking the route.config, then route.app.config.""" for conf in (self.config, self.app.conifg): if key in conf: return conf[key] return default def __repr__(self): cb = self.get_undecorated_callback() return '<%s %r %r>' % (self.method, self.rule, cb) ############################################################################### # Application Object ########################################################### ############################################################################### class Bottle(object): """ Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications. :param catchall: If true (default), handle all exceptions. Turn off to let debugging middleware handle exceptions. """ def __init__(self, catchall=True, autojson=True): #: A :class:`ConfigDict` for app specific configuration. self.config = ConfigDict() self.config._on_change = functools.partial(self.trigger_hook, 'config') self.config.meta_set('autojson', 'validate', bool) self.config.meta_set('catchall', 'validate', bool) self.config['catchall'] = catchall self.config['autojson'] = autojson #: A :class:`ResourceManager` for application files self.resources = ResourceManager() self.routes = [] # List of installed :class:`Route` instances. self.router = Router() # Maps requests to :class:`Route` instances. self.error_handler = {} # Core plugins self.plugins = [] # List of installed plugins. if self.config['autojson']: self.install(JSONPlugin()) self.install(TemplatePlugin()) #: If true, most exceptions are caught and returned as :exc:`HTTPError` catchall = DictProperty('config', 'catchall') __hook_names = 'before_request', 'after_request', 'app_reset', 'config' __hook_reversed = 'after_request' @cached_property def _hooks(self): return dict((name, []) for name in self.__hook_names) def add_hook(self, name, func): """ Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of its outcome. app_reset Called whenever :meth:`Bottle.reset` is called. """ if name in self.__hook_reversed: self._hooks[name].insert(0, func) else: self._hooks[name].append(func) def remove_hook(self, name, func): """ Remove a callback from a hook. """ if name in self._hooks and func in self._hooks[name]: self._hooks[name].remove(func) return True def trigger_hook(self, __name, *args, **kwargs): """ Trigger a hook and return a list of results. """ return [hook(*args, **kwargs) for hook in self._hooks[__name][:]] def hook(self, name): """ Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.""" def decorator(func): self.add_hook(name, func) return func return decorator def mount(self, prefix, app, **options): """ Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI application. All other parameters are passed to the underlying :meth:`route` call. """ segments = [p for p in prefix.split('/') if p] if not segments: raise ValueError('Empty path prefix.') path_depth = len(segments) def mountpoint_wrapper(): try: request.path_shift(path_depth) rs = HTTPResponse([]) def start_response(status, headerlist, exc_info=None): if exc_info: _raise(*exc_info) rs.status = status for name, value in headerlist: rs.add_header(name, value) return rs.body.append body = app(request.environ, start_response) if body and rs.body: body = itertools.chain(rs.body, body) rs.body = body or rs.body return rs finally: request.path_shift(-path_depth) options.setdefault('skip', True) options.setdefault('method', 'PROXY') options.setdefault('mountpoint', {'prefix': prefix, 'target': app}) options['callback'] = mountpoint_wrapper self.route('/%s/<:re:.*>' % '/'.join(segments), **options) if not prefix.endswith('/'): self.route('/' + '/'.join(segments), **options) def merge(self, routes): """ Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed. """ if isinstance(routes, Bottle): routes = routes.routes for route in routes: self.add_route(route) def install(self, plugin): """ Add a plugin to the list of plugins and prepare it for being applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. """ if hasattr(plugin, 'setup'): plugin.setup(self) if not callable(plugin) and not hasattr(plugin, 'apply'): raise TypeError("Plugins must be callable or implement .apply()") self.plugins.append(plugin) self.reset() return plugin def uninstall(self, plugin): """ Uninstall plugins. Pass an instance to remove a specific plugin, a type object to remove all plugins that match that type, a string to remove all plugins with a matching ``name`` attribute or ``True`` to remove all plugins. Return the list of removed plugins. """ removed, remove = [], plugin for i, plugin in list(enumerate(self.plugins))[::-1]: if remove is True or remove is plugin or remove is type(plugin) \ or getattr(plugin, 'name', True) == remove: removed.append(plugin) del self.plugins[i] if hasattr(plugin, 'close'): plugin.close() if removed: self.reset() return removed def reset(self, route=None): """ Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected. """ if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] else: routes = [self.routes[route]] for route in routes: route.reset() if DEBUG: for route in routes: route.prepare() self.trigger_hook('app_reset') def close(self): """ Close the application and all installed plugins. """ for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() def run(self, **kwargs): """ Calls :func:`run` with the same parameters. """ run(self, **kwargs) def match(self, environ): """ Search for a matching route and return a (:class:`Route` , urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise :exc:`HTTPError` (404/405) on a non-match.""" return self.router.match(environ) def get_url(self, routename, **kargs): """ Return a string that matches a named route """ scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/' location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location) def add_route(self, route): """ Add a route object, but do not change the :data:`Route.app` attribute.""" self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare() def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`). """ if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.add_route(route) return callback return decorator(callback) if callback else decorator def get(self, path=None, method='GET', **options): """ Equals :meth:`route`. """ return self.route(path, method, **options) def post(self, path=None, method='POST', **options): """ Equals :meth:`route` with a ``POST`` method parameter. """ return self.route(path, method, **options) def put(self, path=None, method='PUT', **options): """ Equals :meth:`route` with a ``PUT`` method parameter. """ return self.route(path, method, **options) def delete(self, path=None, method='DELETE', **options): """ Equals :meth:`route` with a ``DELETE`` method parameter. """ return self.route(path, method, **options) def patch(self, path=None, method='PATCH', **options): """ Equals :meth:`route` with a ``PATCH`` method parameter. """ return self.route(path, method, **options) def error(self, code=500): """ Decorator: Register an output handler for a HTTP error code""" def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper def default_error_handler(self, res): return tob(template(ERROR_PAGE_TEMPLATE, e=res)) def _handle(self, environ): path = environ['bottle.raw_path'] = environ['PATH_INFO'] if py3k: try: environ['PATH_INFO'] = path.encode('latin1').decode('utf8') except UnicodeError: return HTTPError(400, 'Invalid path string. Expected UTF-8') try: environ['bottle.app'] = self request.bind(environ) response.bind() try: self.trigger_hook('before_request') route, args = self.router.match(environ) environ['route.handle'] = route environ['bottle.route'] = route environ['route.url_args'] = args return route.call(**args) finally: self.trigger_hook('after_request') except HTTPResponse: return _e() except RouteReset: route.reset() return self._handle(environ) except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise stacktrace = format_exc() environ['wsgi.errors'].write(stacktrace) return HTTPError(500, "Internal Server Error", _e(), stacktrace) def _cast(self, out, peek=None): """ Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes """ # Empty output is done here if not out: if 'Content-Length' not in response: response['Content-Length'] = 0 return [] # Join lists of byte or unicode strings. Mixed lists are NOT supported if isinstance(out, (tuple, list))\ and isinstance(out[0], (bytes, unicode)): out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' # Encode unicode strings if isinstance(out, unicode): out = out.encode(response.charset) # Byte Strings are just returned if isinstance(out, bytes): if 'Content-Length' not in response: response['Content-Length'] = len(out) return [out] # HTTPError or HTTPException (recursive, because they may wrap anything) # TODO: Handle these explicitly in handle() or make them iterable. if isinstance(out, HTTPError): out.apply(response) out = self.error_handler.get(out.status_code, self.default_error_handler)(out) return self._cast(out) if isinstance(out, HTTPResponse): out.apply(response) return self._cast(out.body) # File-like objects. if hasattr(out, 'read'): if 'wsgi.file_wrapper' in request.environ: return request.environ['wsgi.file_wrapper'](out) elif hasattr(out, 'close') or not hasattr(out, '__iter__'): return WSGIFileWrapper(out) # Handle Iterables. We peek into them to detect their inner type. try: iout = iter(out) first = next(iout) while not first: first = next(iout) except StopIteration: return self._cast('') except HTTPResponse: first = _e() except (KeyboardInterrupt, SystemExit, MemoryError): raise except: if not self.catchall: raise first = HTTPError(500, 'Unhandled exception', _e(), format_exc()) # These are the inner types allowed in iterator or generator objects. if isinstance(first, HTTPResponse): return self._cast(first) elif isinstance(first, bytes): new_iter = itertools.chain([first], iout) elif isinstance(first, unicode): encoder = lambda x: x.encode(response.charset) new_iter = imap(encoder, itertools.chain([first], iout)) else: msg = 'Unsupported response type: %s' % type(first) return self._cast(HTTPError(500, msg)) if hasattr(out, 'close'): new_iter = _closeiter(new_iter, out.close) return new_iter def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(_e())), html_escape(format_exc())) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info()) return [tob(err)] def __call__(self, environ, start_response): """ Each instance of :class:'Bottle' is a WSGI application. """ return self.wsgi(environ, start_response) def __enter__(self): """ Use this application as default for all module-level shortcuts. """ default_app.push(self) return self def __exit__(self, exc_type, exc_value, traceback): default_app.pop() ############################################################################### # HTTP and WSGI Tools ########################################################## ############################################################################### class BaseRequest(object): """ A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only. Adding new attributes to a request actually adds them to the environ dictionary (as 'bottle.request.ext.<name>'). This is the recommended way to store and access request-specific data. """ __slots__ = ('environ', ) #: Maximum size of memory buffer for :attr:`body` in bytes. MEMFILE_MAX = 102400 def __init__(self, environ=None): """ Wrap a WSGI environ dictionary. """ #: The wrapped WSGI environ dictionary. This is the only real attribute. #: All other attributes actually are read-only properties. self.environ = {} if environ is None else environ self.environ['bottle.request'] = self @DictProperty('environ', 'bottle.app', read_only=True) def app(self): """ Bottle application handling this request. """ raise RuntimeError('This request is not connected to an application.') @DictProperty('environ', 'bottle.route', read_only=True) def route(self): """ The bottle :class:`Route` object that matches this request. """ raise RuntimeError('This request is not connected to a route.') @DictProperty('environ', 'route.url_args', read_only=True) def url_args(self): """ The arguments extracted from the URL. """ raise RuntimeError('This request is not connected to a route.') @property def path(self): """ The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case). """ return '/' + self.environ.get('PATH_INFO','').lstrip('/') @property def method(self): """ The ``REQUEST_METHOD`` value as an uppercase string. """ return self.environ.get('REQUEST_METHOD', 'GET').upper() @DictProperty('environ', 'bottle.request.headers', read_only=True) def headers(self): """ A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers. """ return WSGIHeaderDict(self.environ) def get_header(self, name, default=None): """ Return the value of a request header, or a given default value. """ return self.headers.get(name, default) @DictProperty('environ', 'bottle.request.cookies', read_only=True) def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values() return FormsDict((c.key, c.value) for c in cookies) def get_cookie(self, key, default=None, secret=None): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value. """ value = self.cookies.get(key) if secret and value: dec = cookie_decode(value, secret) # (key, value) tuple or None return dec[1] if dec and dec[0] == key else default return value or default @DictProperty('environ', 'bottle.request.query', read_only=True) def query(self): """ The :attr:`query_string` parsed into a :class:`FormsDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`. """ get = self.environ['bottle.get'] = FormsDict() pairs = _parse_qsl(self.environ.get('QUERY_STRING', '')) for key, value in pairs: get[key] = value return get @DictProperty('environ', 'bottle.request.forms', read_only=True) def forms(self): """ Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is returned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`. """ forms = FormsDict() for name, item in self.POST.allitems(): if not isinstance(item, FileUpload): forms[name] = item return forms @DictProperty('environ', 'bottle.request.params', read_only=True) def params(self): """ A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`. """ params = FormsDict() for key, value in self.query.allitems(): params[key] = value for key, value in self.forms.allitems(): params[key] = value return params @DictProperty('environ', 'bottle.request.files', read_only=True) def files(self): """ File uploads parsed from `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`FileUpload`. """ files = FormsDict() for name, item in self.POST.allitems(): if isinstance(item, FileUpload): files[name] = item return files @DictProperty('environ', 'bottle.request.json', read_only=True) def json(self): """ If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. """ ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0] if ctype == 'application/json': b = self._get_body_string() if not b: return None return json_loads(b) return None def _iter_body(self, read, bufsize): maxread = max(0, self.content_length) while maxread: part = read(min(maxread, bufsize)) if not part: break yield part maxread -= len(part) @staticmethod def _iter_chunked(read, bufsize): err = HTTPError(400, 'Error while parsing chunked transfer body.') rn, sem, bs = tob('\r\n'), tob(';'), tob('') while True: header = read(1) while header[-2:] != rn: c = read(1) header += c if not c: raise err if len(header) > bufsize: raise err size, _, _ = header.partition(sem) try: maxread = int(tonat(size.strip()), 16) except ValueError: raise err if maxread == 0: break buff = bs while maxread > 0: if not buff: buff = read(min(maxread, bufsize)) part, buff = buff[:maxread], buff[maxread:] if not part: raise err yield part maxread -= len(part) if read(2) != rn: raise err @DictProperty('environ', 'bottle.request.body', read_only=True) def _body(self): body_iter = self._iter_chunked if self.chunked else self._iter_body read_func = self.environ['wsgi.input'].read body, body_size, is_temp_file = BytesIO(), 0, False for part in body_iter(read_func, self.MEMFILE_MAX): body.write(part) body_size += len(part) if not is_temp_file and body_size > self.MEMFILE_MAX: body, tmp = TemporaryFile(mode='w+b'), body body.write(tmp.getvalue()) del tmp is_temp_file = True self.environ['wsgi.input'] = body body.seek(0) return body def _get_body_string(self): """ read body until content-length or MEMFILE_MAX into a string. Raise HTTPError(413) on requests that are to large. """ clen = self.content_length if clen > self.MEMFILE_MAX: raise HTTPError(413, 'Request to large') if clen < 0: clen = self.MEMFILE_MAX + 1 data = self.body.read(clen) if len(data) > self.MEMFILE_MAX: # Fail fast raise HTTPError(413, 'Request to large') return data @property def body(self): """ The HTTP request body as a seek-able file-like object. Depending on :attr:`MEMFILE_MAX`, this is either a temporary file or a :class:`io.BytesIO` instance. Accessing this property for the first time reads and replaces the ``wsgi.input`` environ variable. Subsequent accesses just do a `seek(0)` on the file object. """ self._body.seek(0) return self._body @property def chunked(self): """ True if Chunked transfer encoding was. """ return 'chunked' in self.environ.get('HTTP_TRANSFER_ENCODING', '').lower() #: An alias for :attr:`query`. GET = query @DictProperty('environ', 'bottle.request.post', read_only=True) def POST(self): """ The values of :attr:`forms` and :attr:`files` combined into a single :class:`FormsDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads). """ post = FormsDict() # We default to application/x-www-form-urlencoded for everything that # is not multipart and take the fast path (also: 3.1 workaround) if not self.content_type.startswith('multipart/'): pairs = _parse_qsl(tonat(self._get_body_string(), 'latin1')) for key, value in pairs: post[key] = value return post safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if key in self.environ: safe_env[key] = self.environ[key] args = dict(fp=self.body, environ=safe_env, keep_blank_values=True) if py31: args['fp'] = NCTextIOWrapper(args['fp'], encoding='utf8', newline='\n') elif py3k: args['encoding'] = 'utf8' data = cgi.FieldStorage(**args) self['_cgi.FieldStorage'] = data #http://bugs.python.org/issue18394#msg207958 data = data.list or [] for item in data: if item.filename: post[item.name] = FileUpload(item.file, item.name, item.filename, item.headers) else: post[item.name] = item.value return post @property def url(self): """ The full request URI including hostname and scheme. If your app lives behind a reverse proxy or load balancer and you get confusing results, make sure that the ``X-Forwarded-Host`` header is set correctly. """ return self.urlparts.geturl() @DictProperty('environ', 'bottle.request.urlparts', read_only=True) def urlparts(self): """ The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server. """ env = self.environ http = env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http') host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST') if not host: # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients. host = env.get('SERVER_NAME', '127.0.0.1') port = env.get('SERVER_PORT') if port and port != ('80' if http == 'http' else '443'): host += ':' + port path = urlquote(self.fullpath) return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '') @property def fullpath(self): """ Request path including :attr:`script_name` (if present). """ return urljoin(self.script_name, self.path.lstrip('/')) @property def query_string(self): """ The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string. """ return self.environ.get('QUERY_STRING', '') @property def script_name(self): """ The initial portion of the URL's `path` that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes. """ script_name = self.environ.get('SCRIPT_NAME', '').strip('/') return '/' + script_name + '/' if script_name else '/' def path_shift(self, shift=1): """ Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) """ script = self.environ.get('SCRIPT_NAME','/') self['SCRIPT_NAME'], self['PATH_INFO'] = path_shift(script, self.path, shift) @property def content_length(self): """ The request body length as an integer. The client is responsible to set this header. Otherwise, the real length of the body is unknown and -1 is returned. In this case, :attr:`body` will be empty. """ return int(self.environ.get('CONTENT_LENGTH') or -1) @property def content_type(self): """ The Content-Type header as a lowercase-string (default: empty). """ return self.environ.get('CONTENT_TYPE', '').lower() @property def is_xhr(self): """ True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do). """ requested_with = self.environ.get('HTTP_X_REQUESTED_WITH','') return requested_with.lower() == 'xmlhttprequest' @property def is_ajax(self): """ Alias for :attr:`is_xhr`. "Ajax" is not the right term. """ return self.is_xhr @property def auth(self): """ HTTP authentication data as a (user, password) tuple. This implementation currently supports basic (not digest) authentication only. If the authentication happened at a higher level (e.g. in the front web-server or a middleware), the password field is None, but the user field is looked up from the ``REMOTE_USER`` environ variable. On any errors, None is returned. """ basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION','')) if basic: return basic ruser = self.environ.get('REMOTE_USER') if ruser: return (ruser, None) return None @property def remote_route(self): """ A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients. """ proxy = self.environ.get('HTTP_X_FORWARDED_FOR') if proxy: return [ip.strip() for ip in proxy.split(',')] remote = self.environ.get('REMOTE_ADDR') return [remote] if remote else [] @property def remote_addr(self): """ The client IP as a string. Note that this information can be forged by malicious clients. """ route = self.remote_route return route[0] if route else None def copy(self): """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """ return Request(self.environ.copy()) def get(self, value, default=None): return self.environ.get(value, default) def __getitem__(self, key): return self.environ[key] def __delitem__(self, key): self[key] = ""; del(self.environ[key]) def __iter__(self): return iter(self.environ) def __len__(self): return len(self.environ) def keys(self): return self.environ.keys() def __setitem__(self, key, value): """ Change an environ value and clear all caches that depend on it. """ if self.environ.get('bottle.request.readonly'): raise KeyError('The environ dictionary is read-only.') self.environ[key] = value todelete = () if key == 'wsgi.input': todelete = ('body', 'forms', 'files', 'params', 'post', 'json') elif key == 'QUERY_STRING': todelete = ('query', 'params') elif key.startswith('HTTP_'): todelete = ('headers', 'cookies') for key in todelete: self.environ.pop('bottle.request.'+key, None) def __repr__(self): return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url) def __getattr__(self, name): """ Search in self.environ for additional user defined attributes. """ try: var = self.environ['bottle.request.ext.%s'%name] return var.__get__(self) if hasattr(var, '__get__') else var except KeyError: raise AttributeError('Attribute %r not defined.' % name) def __setattr__(self, name, value): if name == 'environ': return object.__setattr__(self, name, value) self.environ['bottle.request.ext.%s'%name] = value def _hkey(s): return s.title().replace('_','-') class HeaderProperty(object): def __init__(self, name, reader=None, writer=str, default=''): self.name, self.default = name, default self.reader, self.writer = reader, writer self.__doc__ = 'Current value of the %r header.' % name.title() def __get__(self, obj, _): if obj is None: return self value = obj.headers.get(self.name, self.default) return self.reader(value) if self.reader else value def __set__(self, obj, value): obj.headers[self.name] = self.writer(value) def __delete__(self, obj): del obj.headers[self.name] class BaseResponse(object): """ Storage class for a response body as well as headers and cookies. This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers. :param body: The response body as one of the supported types. :param status: Either an HTTP status code (e.g. 200) or a status line including the reason phrase (e.g. '200 OK'). :param headers: A dictionary or a list of name-value pairs. Additional keyword arguments are added to the list of headers. Underscores in the header name are replaced with dashes. """ default_status = 200 default_content_type = 'text/html; charset=UTF-8' # Header blacklist for specific response codes # (rfc2616 section 10.2.3 and 10.3.5) bad_headers = { 204: set(('Content-Type',)), 304: set(('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Range', 'Content-Type', 'Content-Md5', 'Last-Modified'))} def __init__(self, body='', status=None, headers=None, **more_headers): self._cookies = None self._headers = {} self.body = body self.status = status or self.default_status if headers: if isinstance(headers, dict): headers = headers.items() for name, value in headers: self.add_header(name, value) if more_headers: for name, value in more_headers.items(): self.add_header(name, value) def copy(self, cls=None): """ Returns a copy of self. """ cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output()) return copy def __iter__(self): return iter(self.body) def close(self): if hasattr(self.body, 'close'): self.body.close() @property def status_line(self): """ The HTTP status line as a string (e.g. ``404 Not Found``).""" return self._status_line @property def status_code(self): """ The HTTP status code as an integer (e.g. 404).""" return self._status_code def _set_status(self, status): if isinstance(status, int): code, status = status, _HTTP_STATUS_LINES.get(status) elif ' ' in status: status = status.strip() code = int(status.split()[0]) else: raise ValueError('String status line without a reason phrase.') if not 100 <= code <= 999: raise ValueError('Status code out of range.') self._status_code = code self._status_line = str(status or ('%d Unknown' % code)) def _get_status(self): return self._status_line status = property(_get_status, _set_status, None, ''' A writeable property to change the HTTP response status. It accepts either a numeric code (100-999) or a string with a custom reason phrase (e.g. "404 Brain not found"). Both :data:`status_line` and :data:`status_code` are updated accordingly. The return value is always a status string. ''') del _get_status, _set_status @property def headers(self): """ An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers. """ hdict = HeaderDict() hdict.dict = self._headers return hdict def __contains__(self, name): return _hkey(name) in self._headers def __delitem__(self, name): del self._headers[_hkey(name)] def __getitem__(self, name): return self._headers[_hkey(name)][-1] def __setitem__(self, name, value): self._headers[_hkey(name)] = [str(value)] def get_header(self, name, default=None): """ Return the value of a previously defined header. If there is no header with that name, return a default value. """ return self._headers.get(_hkey(name), [default])[-1] def set_header(self, name, value): """ Create a new response header, replacing any previously defined headers with the same name. """ self._headers[_hkey(name)] = [str(value)] def add_header(self, name, value): """ Add an additional response header, not removing duplicates. """ self._headers.setdefault(_hkey(name), []).append(str(value)) def iter_headers(self): """ Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. """ return self.headerlist @property def headerlist(self): """ WSGI conform list of (header, value) tuples. """ out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: bad_headers = self.bad_headers[self._status_code] headers = [h for h in headers if h[0] not in bad_headers] out += [(name, val) for name, vals in headers for val in vals] if self._cookies: for c in self._cookies.values(): out.append(('Set-Cookie', c.OutputString())) return out content_type = HeaderProperty('Content-Type') content_length = HeaderProperty('Content-Length', reader=int) expires = HeaderProperty('Expires', reader=lambda x: datetime.utcfromtimestamp(parse_date(x)), writer=lambda x: http_date(x)) @property def charset(self, default='UTF-8'): """ Return the charset specified in the content-type header (default: utf8). """ if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return default def set_cookie(self, name, value, secret=None, **options): """ Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that are supported by :class:`cookie.Morsel`, including: :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (default: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: current path) :param secure: limit the cookie to HTTPS connections (default: off). :param httponly: prevents client-side javascript to read this cookie (default: off, requires Python 2.6 or newer). If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side. """ if not self._cookies: self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((name, value), secret)) elif not isinstance(value, basestring): raise TypeError('Secret key missing for non-string Cookie.') if len(value) > 4096: raise ValueError('Cookie value to long.') self._cookies[name] = value for key, value in options.items(): if key == 'max_age': if isinstance(value, timedelta): value = value.seconds + value.days * 24 * 3600 if key == 'expires': if isinstance(value, (datedate, datetime)): value = value.timetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) self._cookies[name][key.replace('_', '-')] = value def delete_cookie(self, key, **kwargs): """ Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie. """ kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs) def __repr__(self): out = '' for name, value in self.headerlist: out += '%s: %s\n' % (name.title(), value.strip()) return out def _local_property(): ls = threading.local() def fget(_): try: return ls.var except AttributeError: raise RuntimeError("Request context not initialized.") def fset(_, value): ls.var = value def fdel(_): del ls.var return property(fget, fset, fdel, 'Thread-local property') class LocalRequest(BaseRequest): """ A thread-local subclass of :class:`BaseRequest` with a different set of attributes for each thread. There is usually only one global instance of this class (:data:`request`). If accessed during a request/response cycle, this instance always refers to the *current* request (even on a multithreaded server). """ bind = BaseRequest.__init__ environ = _local_property() class LocalResponse(BaseResponse): """ A thread-local subclass of :class:`BaseResponse` with a different set of attributes for each thread. There is usually only one global instance of this class (:data:`response`). Its attributes are used to build the HTTP response at the end of the request/response cycle. """ bind = BaseResponse.__init__ _status_line = _local_property() _status_code = _local_property() _cookies = _local_property() _headers = _local_property() body = _local_property() Request = BaseRequest Response = BaseResponse class HTTPResponse(Response, BottleException): def __init__(self, body='', status=None, headers=None, **more_headers): super(HTTPResponse, self).__init__(body, status, headers, **more_headers) def apply(self, other): other._status_code = self._status_code other._status_line = self._status_line other._headers = self._headers other._cookies = self._cookies other.body = self.body class HTTPError(HTTPResponse): default_status = 500 def __init__(self, status=None, body=None, exception=None, traceback=None, **options): self.exception = exception self.traceback = traceback super(HTTPError, self).__init__(body, status, **options) ############################################################################### # Plugins ###################################################################### ############################################################################### class PluginError(BottleException): pass class JSONPlugin(object): name = 'json' api = 2 def __init__(self, json_dumps=json_dumps): self.json_dumps = json_dumps def apply(self, callback, _): dumps = self.json_dumps if not dumps: return callback def wrapper(*a, **ka): try: rv = callback(*a, **ka) except HTTPError: rv = _e() if isinstance(rv, dict): #Attempt to serialize, raises exception on failure json_response = dumps(rv) #Set content type only if serialization successful response.content_type = 'application/json' return json_response elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict): rv.body = dumps(rv.body) rv.content_type = 'application/json' return rv return wrapper class TemplatePlugin(object): """ This plugin applies the :func:`view` decorator to all routes with a `template` config parameter. If the parameter is a tuple, the second element must be a dict with additional options (e.g. `template_engine`) or default variables for the template. """ name = 'template' api = 2 def apply(self, callback, route): conf = route.config.get('template') if isinstance(conf, (tuple, list)) and len(conf) == 2: return view(conf[0], **conf[1])(callback) elif isinstance(conf, str): return view(conf)(callback) else: return callback #: Not a plugin, but part of the plugin API. TODO: Find a better place. class _ImportRedirect(object): def __init__(self, name, impmask): """ Create a virtual package that redirects imports (see PEP 302). """ self.name = name self.impmask = impmask self.module = sys.modules.setdefault(name, imp.new_module(name)) self.module.__dict__.update({'__file__': __file__, '__path__': [], '__all__': [], '__loader__': self}) sys.meta_path.append(self) def find_module(self, fullname, path=None): if '.' not in fullname: return packname = fullname.rsplit('.', 1)[0] if packname != self.name: return return self def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] modname = fullname.rsplit('.', 1)[1] realname = self.impmask % modname __import__(realname) module = sys.modules[fullname] = sys.modules[realname] setattr(self.module, modname, module) module.__loader__ = self return module ############################################################################### # Common Utilities ############################################################# ############################################################################### class MultiDict(DictMixin): """ This dict stores multiple values per key, but behaves exactly like a normal dict in that it returns only the newest value for any given key. There are special methods available to access the full list of values. """ def __init__(self, *a, **k): self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items()) def __len__(self): return len(self.dict) def __iter__(self): return iter(self.dict) def __contains__(self, key): return key in self.dict def __delitem__(self, key): del self.dict[key] def __getitem__(self, key): return self.dict[key][-1] def __setitem__(self, key, value): self.append(key, value) def keys(self): return self.dict.keys() if py3k: def values(self): return (v[-1] for v in self.dict.values()) def items(self): return ((k, v[-1]) for k, v in self.dict.items()) def allitems(self): return ((k, v) for k, vl in self.dict.items() for v in vl) iterkeys = keys itervalues = values iteritems = items iterallitems = allitems else: def values(self): return [v[-1] for v in self.dict.values()] def items(self): return [(k, v[-1]) for k, v in self.dict.items()] def iterkeys(self): return self.dict.iterkeys() def itervalues(self): return (v[-1] for v in self.dict.itervalues()) def iteritems(self): return ((k, v[-1]) for k, v in self.dict.iteritems()) def iterallitems(self): return ((k, v) for k, vl in self.dict.iteritems() for v in vl) def allitems(self): return [(k, v) for k, vl in self.dict.iteritems() for v in vl] def get(self, key, default=None, index=-1, type=None): """ Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. :param type: If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned. """ try: val = self.dict[key][index] return type(val) if type else val except Exception: pass return default def append(self, key, value): """ Add a new value to the list of values for this key. """ self.dict.setdefault(key, []).append(value) def replace(self, key, value): """ Replace the list of values with a single value. """ self.dict[key] = [value] def getall(self, key): """ Return a (possibly empty) list of values for a key. """ return self.dict.get(key) or [] #: Aliases for WTForms to mimic other multi-dict APIs (Django) getone = get getlist = getall class FormsDict(MultiDict): """ This :class:`MultiDict` subclass is used to store request form data. Additionally to the normal dict-like item access methods (which return unmodified data as native strings), this container also supports attribute-like access to its values. Attributes are automatically de- or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing attributes default to an empty string. """ #: Encoding used for attribute values. input_encoding = 'utf8' #: If true (default), unicode strings are first encoded with `latin1` #: and then decoded to match :attr:`input_encoding`. recode_unicode = True def _fix(self, s, encoding=None): if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI return s.encode('latin1').decode(encoding or self.input_encoding) elif isinstance(s, bytes): # Python 2 WSGI return s.decode(encoding or self.input_encoding) else: return s def decode(self, encoding=None): """ Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary. """ copy = FormsDict() enc = copy.input_encoding = encoding or self.input_encoding copy.recode_unicode = False for key, value in self.allitems(): copy.append(self._fix(key, enc), self._fix(value, enc)) return copy def getunicode(self, name, default=None, encoding=None): """ Return the value as a unicode string, or the default. """ try: return self._fix(self[name], encoding) except (UnicodeError, KeyError): return default def __getattr__(self, name, default=unicode()): # Without this guard, pickle generates a cryptic TypeError: if name.startswith('__') and name.endswith('__'): return super(FormsDict, self).__getattr__(name) return self.getunicode(name, default=default) class HeaderDict(MultiDict): """ A case-insensitive version of :class:`MultiDict` that defaults to replace the old value instead of appending it. """ def __init__(self, *a, **ka): self.dict = {} if a or ka: self.update(*a, **ka) def __contains__(self, key): return _hkey(key) in self.dict def __delitem__(self, key): del self.dict[_hkey(key)] def __getitem__(self, key): return self.dict[_hkey(key)][-1] def __setitem__(self, key, value): self.dict[_hkey(key)] = [str(value)] def append(self, key, value): self.dict.setdefault(_hkey(key), []).append(str(value)) def replace(self, key, value): self.dict[_hkey(key)] = [str(value)] def getall(self, key): return self.dict.get(_hkey(key)) or [] def get(self, key, default=None, index=-1): return MultiDict.get(self, _hkey(key), default, index) def filter(self, names): for name in [_hkey(n) for n in names]: if name in self.dict: del self.dict[name] class WSGIHeaderDict(DictMixin): """ This dict-like class wraps a WSGI environ dict and provides convenient access to HTTP_* fields. Keys and values are native strings (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI environment contains non-native string values, these are de- or encoded using a lossless 'latin1' character set. The API will remain stable even on changes to the relevant PEPs. Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one that uses non-native strings.) """ #: List of keys that do not have a ``HTTP_`` prefix. cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH') def __init__(self, environ): self.environ = environ def _ekey(self, key): """ Translate header field name to CGI/WSGI environ key. """ key = key.replace('-','_').upper() if key in self.cgikeys: return key return 'HTTP_' + key def raw(self, key, default=None): """ Return the header value as is (may be bytes or unicode). """ return self.environ.get(self._ekey(key), default) def __getitem__(self, key): return tonat(self.environ[self._ekey(key)], 'latin1') def __setitem__(self, key, value): raise TypeError("%s is read-only." % self.__class__) def __delitem__(self, key): raise TypeError("%s is read-only." % self.__class__) def __iter__(self): for key in self.environ: if key[:5] == 'HTTP_': yield key[5:].replace('_', '-').title() elif key in self.cgikeys: yield key.replace('_', '-').title() def keys(self): return [x for x in self] def __len__(self): return len(self.keys()) def __contains__(self, key): return self._ekey(key) in self.environ class ConfigDict(dict): """ A dict-like configuration storage with additional support for namespaces, validators, meta-data, on_change listeners and more. """ __slots__ = ('_meta', '_on_change') def __init__(self): self._meta = {} self._on_change = lambda name, value: None def load_config(self, filename): """ Load values from an ``*.ini`` style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). """ conf = ConfigParser() conf.read(filename) for section in conf.sections(): for key, value in conf.items(section): if section not in ('DEFAULT', 'bottle'): key = section + '.' + key self[key] = value return self def load_dict(self, source, namespace=''): """ Load values from a dictionary structure. Nesting can be used to represent namespaces. >>> c = ConfigDict() >>> c.load_dict({'some': {'namespace': {'key': 'value'} } }) {'some.namespace.key': 'value'} """ for key, value in source.items(): if isinstance(key, str): nskey = (namespace + '.' + key).strip('.') if isinstance(value, dict): self.load_dict(value, namespace=nskey) else: self[nskey] = value else: raise TypeError('Key has type %r (not a string)' % type(key)) return self def update(self, *a, **ka): """ If the first parameter is a string, all keys are prefixed with this namespace. Apart from that it works just as the usual dict.update(). Example: ``update('some.namespace', key='value')`` """ prefix = '' if a and isinstance(a[0], str): prefix = a[0].strip('.') + '.' a = a[1:] for key, value in dict(*a, **ka).items(): self[prefix+key] = value def setdefault(self, key, value): if key not in self: self[key] = value def __setitem__(self, key, value): if not isinstance(key, str): raise TypeError('Key has type %r (not a string)' % type(key)) value = self.meta_get(key, 'filter', lambda x: x)(value) if key in self and self[key] is value: return self._on_change(key, value) dict.__setitem__(self, key, value) def __delitem__(self, key): self._on_change(key, None) dict.__delitem__(self, key) def meta_get(self, key, metafield, default=None): """ Return the value of a meta field for a key. """ return self._meta.get(key, {}).get(metafield, default) def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. This triggers the on-change handler for existing keys. """ self._meta.setdefault(key, {})[metafield] = value if key in self: self[key] = self[key] def meta_list(self, key): """ Return an iterable of meta field names defined for a key. """ return self._meta.get(key, {}).keys() class AppStack(list): """ A stack-like list. Calling it returns the head of the stack. """ def __call__(self): """ Return the current default application. """ return self[-1] def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstance(value, Bottle): value = Bottle() self.append(value) return value class WSGIFileWrapper(object): def __init__(self, fp, buffer_size=1024*64): self.fp, self.buffer_size = fp, buffer_size for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'): if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr)) def __iter__(self): buff, read = self.buffer_size, self.read while True: part = read(buff) if not part: return yield part class _closeiter(object): """ This only exists to be able to attach a .close method to iterators that do not support attribute assignment (most of itertools). """ def __init__(self, iterator, close=None): self.iterator = iterator self.close_callbacks = makelist(close) def __iter__(self): return iter(self.iterator) def close(self): for func in self.close_callbacks: func() class ResourceManager(object): """ This class manages a list of search paths and helps to find and open application-bound resources (files). :param base: default value for :meth:`add_path` calls. :param opener: callable used to open resources. :param cachemode: controls which lookups are cached. One of 'all', 'found' or 'none'. """ def __init__(self, base='./', opener=open, cachemode='all'): self.opener = opener self.base = base self.cachemode = cachemode #: A list of search paths. See :meth:`add_path` for details. self.path = [] #: A cache for resolved paths. ``res.cache.clear()`` clears the cache. self.cache = {} def add_path(self, path, base=None, index=None, create=False): """ Add a new path to the list of search paths. Return False if the path does not exist. :param path: The new search path. Relative paths are turned into an absolute and normalized form. If the path looks like a file (not ending in `/`), the filename is stripped off. :param base: Path used to absolutize relative search paths. Defaults to :attr:`base` which defaults to ``os.getcwd()``. :param index: Position within the list of search paths. Defaults to last index (appends to the list). The `base` parameter makes it easy to reference files installed along with a python module or package:: res.add_path('./resources/', __file__) """ base = os.path.abspath(os.path.dirname(base or self.base)) path = os.path.abspath(os.path.join(base, os.path.dirname(path))) path += os.sep if path in self.path: self.path.remove(path) if create and not os.path.isdir(path): os.makedirs(path) if index is None: self.path.append(path) else: self.path.insert(index, path) self.cache.clear() return os.path.exists(path) def __iter__(self): """ Iterate over all existing files in all registered paths. """ search = self.path[:] while search: path = search.pop() if not os.path.isdir(path): continue for name in os.listdir(path): full = os.path.join(path, name) if os.path.isdir(full): search.append(full) else: yield full def lookup(self, name): """ Search for a resource and return an absolute file path, or `None`. The :attr:`path` list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups. """ if name not in self.cache or DEBUG: for path in self.path: fpath = os.path.join(path, name) if os.path.isfile(fpath): if self.cachemode in ('all', 'found'): self.cache[name] = fpath return fpath if self.cachemode == 'all': self.cache[name] = None return self.cache[name] def open(self, name, mode='r', *args, **kwargs): """ Find a resource and return a file object, or raise IOError. """ fname = self.lookup(name) if not fname: raise IOError("Resource %r not found." % name) return self.opener(fname, mode=mode, *args, **kwargs) class FileUpload(object): def __init__(self, fileobj, name, filename, headers=None): """ Wrapper for file uploads. """ #: Open file(-like) object (BytesIO buffer or temporary file) self.file = fileobj #: Name of the upload form field self.name = name #: Raw filename as sent by the client (may contain unsafe characters) self.raw_filename = filename #: A :class:`HeaderDict` with additional headers (e.g. content-type) self.headers = HeaderDict(headers) if headers else HeaderDict() content_type = HeaderProperty('Content-Type') content_length = HeaderProperty('Content-Length', reader=int, default=-1) @cached_property def filename(self): """ Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as 'empty'. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, if possible. Whitespace is replaced by a single dash. Leading or tailing dots or dashes are removed. The filename is limited to 255 characters. """ fname = self.raw_filename if not isinstance(fname, unicode): fname = fname.decode('utf8', 'ignore') fname = normalize('NFKD', fname).encode('ASCII', 'ignore').decode('ASCII') fname = os.path.basename(fname.replace('\\', os.path.sep)) fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip() fname = re.sub(r'[-\s]+', '-', fname).strip('.-') return fname[:255] or 'empty' def _copy_file(self, fp, chunk_size=2**16): read, write, offset = self.file.read, fp.write, self.file.tell() while 1: buf = read(chunk_size) if not buf: break write(buf) self.file.seek(offset) def save(self, destination, overwrite=False, chunk_size=2**16): """ Save file to disk or copy its content to an open file(-like) object. If *destination* is a directory, :attr:`filename` is added to the path. Existing files are not overwritten by default (IOError). :param destination: File path, directory or file(-like) object. :param overwrite: If True, replace existing files. (default: False) :param chunk_size: Bytes to read at a time. (default: 64kb) """ if isinstance(destination, basestring): # Except file-likes here if os.path.isdir(destination): destination = os.path.join(destination, self.filename) if not overwrite and os.path.exists(destination): raise IOError('File exists.') with open(destination, 'wb') as fp: self._copy_file(fp, chunk_size) else: self._copy_file(destination, chunk_size) ############################################################################### # Application Helper ########################################################### ############################################################################### def abort(code=500, text='Unknown Error.'): """ Aborts execution and causes a HTTP error. """ raise HTTPError(code, text) def redirect(url, code=None): """ Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version. """ if not code: code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302 res = response.copy(cls=HTTPResponse) res.status = code res.body = "" res.set_header('Location', urljoin(request.url, url)) raise res def _file_iter_range(fp, offset, bytes, maxread=1024*1024): """ Yield chunks from a range in a file. No chunk is bigger than maxread.""" fp.seek(offset) while bytes > 0: part = fp.read(min(bytes, maxread)) if not part: break bytes -= len(part) yield part def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'): """ Open a file in a safe way and return :exc:`HTTPResponse` with status code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``, ``Content-Length`` and ``Last-Modified`` headers are set if possible. Special support for ``If-Modified-Since``, ``Range`` and ``HEAD`` requests. :param filename: Name or path of the file to send. :param root: Root path for file lookups. Should be an absolute directory path. :param mimetype: Defines the content-type header (default: guess from file extension) :param download: If True, ask the browser to open a `Save as...` dialog instead of opening the file with the associated program. You can specify a custom filename as a string. If not specified, the original filename is used (default: False). :param charset: The charset to use for files with a ``text/*`` mime-type. (default: UTF-8) """ root = os.path.abspath(root) + os.sep filename = os.path.abspath(os.path.join(root, filename.strip('/\\'))) headers = dict() if not filename.startswith(root): return HTTPError(403, "Access denied.") if not os.path.exists(filename) or not os.path.isfile(filename): return HTTPError(404, "File does not exist.") if not os.access(filename, os.R_OK): return HTTPError(403, "You do not have permission to access this file.") if mimetype == 'auto': mimetype, encoding = mimetypes.guess_type(filename) if encoding: headers['Content-Encoding'] = encoding if mimetype: if mimetype[:5] == 'text/' and charset and 'charset' not in mimetype: mimetype += '; charset=%s' % charset headers['Content-Type'] = mimetype if download: download = os.path.basename(filename if download == True else download) headers['Content-Disposition'] = 'attachment; filename="%s"' % download stats = os.stat(filename) headers['Content-Length'] = clen = stats.st_size lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime)) headers['Last-Modified'] = lm ims = request.environ.get('HTTP_IF_MODIFIED_SINCE') if ims: ims = parse_date(ims.split(";")[0].strip()) if ims is not None and ims >= int(stats.st_mtime): headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) return HTTPResponse(status=304, **headers) body = '' if request.method == 'HEAD' else open(filename, 'rb') headers["Accept-Ranges"] = "bytes" ranges = request.environ.get('HTTP_RANGE') if 'HTTP_RANGE' in request.environ: ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen)) if not ranges: return HTTPError(416, "Requested Range Not Satisfiable") offset, end = ranges[0] headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen) headers["Content-Length"] = str(end-offset) if body: body = _file_iter_range(body, offset, end-offset) return HTTPResponse(body, status=206, **headers) return HTTPResponse(body, **headers) ############################################################################### # HTTP Utilities and MISC (TODO) ############################################### ############################################################################### def debug(mode=True): """ Change the debug level. There is only one debug level supported at the moment.""" global DEBUG if mode: warnings.simplefilter('default') DEBUG = bool(mode) def http_date(value): if isinstance(value, (datedate, datetime)): value = value.utctimetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) if not isinstance(value, basestring): value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) return value def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError, OverflowError): return None def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" try: method, data = header.split(None, 1) if method.lower() == 'basic': user, pwd = touni(base64.b64decode(tob(data))).split(':',1) return user, pwd except (KeyError, ValueError): return None def parse_range_header(header, maxlen=0): """ Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.""" if not header or header[:6] != 'bytes=': return ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r] for start, end in ranges: try: if not start: # bytes=-100 -> last 100 bytes start, end = max(0, maxlen-int(end)), maxlen elif not end: # bytes=100- -> all but the first 99 bytes start, end = int(start), maxlen else: # bytes=100-200 -> bytes 100-200 (inclusive) start, end = int(start), min(int(end)+1, maxlen) if 0 <= start < end <= maxlen: yield start, end except ValueError: pass def _parse_qsl(qs): r = [] for pair in qs.replace(';','&').split('&'): if not pair: continue nv = pair.split('=', 1) if len(nv) != 2: nv.append('') key = urlunquote(nv[0].replace('+', ' ')) value = urlunquote(nv[1].replace('+', ' ')) r.append((key, value)) return r def _lscmp(a, b): """ Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix. """ return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) def cookie_encode(data, key): """ Encode and sign a pickle-able object. Return a (byte) string """ msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(tob(key), msg).digest()) return tob('!') + sig + tob('?') + msg def cookie_decode(data, key): """ Verify and decode an encoded string. Return an object or None.""" data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())): return pickle.loads(base64.b64decode(msg)) return None def cookie_is_encoded(data): """ Return True if the argument looks like a encoded cookie.""" return bool(data.startswith(tob('!')) and tob('?') in data) def html_escape(string): """ Escape HTML special characters ``&<>`` and quotes ``'"``. """ return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')\ .replace('"','&quot;').replace("'",'&#039;') def html_quote(string): """ Escape and quote a string to be used as an HTTP attribute.""" return '"%s"' % html_escape(string).replace('\n','&#10;')\ .replace('\r','&#13;').replace('\t','&#9;') def yieldroutes(func): """ Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/<x>/<y>' c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>' d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>' """ path = '/' + func.__name__.replace('__','/').lstrip('/') spec = getargspec(func) argc = len(spec[0]) - len(spec[3] or []) path += ('/<%s>' * argc) % tuple(spec[0][:argc]) yield path for arg in spec[0][argc:]: path += '/<%s>' % arg yield path def path_shift(script_name, path_info, shift=1): """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) """ if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if 0 < shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif 0 > shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info def auth_basic(check, realm="private", text="Access denied"): """ Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter. """ def decorator(func): @functools.wraps(func) def wrapper(*a, **ka): user, password = request.auth or (None, None) if user is None or not check(user, password): err = HTTPError(401, text) err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm) return err return func(*a, **ka) return wrapper return decorator # Shortcuts for common Bottle methods. # They all refer to the current default application. def make_default_app_wrapper(name): """ Return a callable that relays calls to the current default app. """ @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper route = make_default_app_wrapper('route') get = make_default_app_wrapper('get') post = make_default_app_wrapper('post') put = make_default_app_wrapper('put') delete = make_default_app_wrapper('delete') patch = make_default_app_wrapper('patch') error = make_default_app_wrapper('error') mount = make_default_app_wrapper('mount') hook = make_default_app_wrapper('hook') install = make_default_app_wrapper('install') uninstall = make_default_app_wrapper('uninstall') url = make_default_app_wrapper('get_url') ############################################################################### # Server Adapter ############################################################### ############################################################################### class ServerAdapter(object): quiet = False def __init__(self, host='127.0.0.1', port=8080, **options): self.options = options self.host = host self.port = int(port) def run(self, handler): # pragma: no cover pass def __repr__(self): args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args) class CGIServer(ServerAdapter): quiet = True def run(self, handler): # pragma: no cover from wsgiref.handlers import CGIHandler def fixed_environ(environ, start_response): environ.setdefault('PATH_INFO', '') return handler(environ, start_response) CGIHandler().run(fixed_environ) class FlupFCGIServer(ServerAdapter): def run(self, handler): # pragma: no cover import flup.server.fcgi self.options.setdefault('bindAddress', (self.host, self.port)) flup.server.fcgi.WSGIServer(handler, **self.options).run() class WSGIRefServer(ServerAdapter): def run(self, app): # pragma: no cover from wsgiref.simple_server import WSGIRequestHandler, WSGIServer from wsgiref.simple_server import make_server import socket class FixedHandler(WSGIRequestHandler): def address_string(self): # Prevent reverse DNS lookups please. return self.client_address[0] def log_request(*args, **kw): if not self.quiet: return WSGIRequestHandler.log_request(*args, **kw) handler_cls = self.options.get('handler_class', FixedHandler) server_cls = self.options.get('server_class', WSGIServer) if ':' in self.host: # Fix wsgiref for IPv6 addresses. if getattr(server_cls, 'address_family') == socket.AF_INET: class server_cls(server_cls): address_family = socket.AF_INET6 srv = make_server(self.host, self.port, app, server_cls, handler_cls) srv.serve_forever() class CherryPyServer(ServerAdapter): def run(self, handler): # pragma: no cover from cherrypy import wsgiserver self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.get('certfile') if certfile: del self.options['certfile'] keyfile = self.options.get('keyfile') if keyfile: del self.options['keyfile'] server = wsgiserver.CherryPyWSGIServer(**self.options) if certfile: server.ssl_certificate = certfile if keyfile: server.ssl_private_key = keyfile try: server.start() finally: server.stop() class WaitressServer(ServerAdapter): def run(self, handler): from waitress import serve serve(handler, host=self.host, port=self.port) class PasteServer(ServerAdapter): def run(self, handler): # pragma: no cover from paste import httpserver from paste.translogger import TransLogger handler = TransLogger(handler, setup_console_handler=(not self.quiet)) httpserver.serve(handler, host=self.host, port=str(self.port), **self.options) class MeinheldServer(ServerAdapter): def run(self, handler): from meinheld import server server.listen((self.host, self.port)) server.run(handler) class FapwsServer(ServerAdapter): """ Extremely fast webserver using libev. See http://www.fapws.org/ """ def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base, config port = self.port if float(config.SERVER_IDENT[-2:]) > 0.4: # fapws3 silently changed its API in 0.5 port = str(port) evwsgi.start(self.host, port) # fapws3 never releases the GIL. Complain upstream. I tried. No luck. if 'BOTTLE_CHILD' in os.environ and not self.quiet: _stderr("WARNING: Auto-reloading does not work with Fapws3.\n") _stderr(" (Fapws3 breaks python thread support)\n") evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('', app)) evwsgi.run() class TornadoServer(ServerAdapter): """ The super hyped asynchronous server by facebook. Untested. """ def run(self, handler): # pragma: no cover import tornado.wsgi, tornado.httpserver, tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port,address=self.host) tornado.ioloop.IOLoop.instance().start() class AppEngineServer(ServerAdapter): """ Adapter for Google App Engine. """ quiet = True def run(self, handler): from google.appengine.ext.webapp import util # A main() function in the handler script enables 'App Caching'. # Lets makes sure it is there. This _really_ improves performance. module = sys.modules.get('__main__') if module and not hasattr(module, 'main'): module.main = lambda: util.run_wsgi_app(handler) util.run_wsgi_app(handler) class TwistedServer(ServerAdapter): """ Untested. """ def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) if not reactor.running: reactor.run() class DieselServer(ServerAdapter): """ Untested. """ def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run() class GeventServer(ServerAdapter): """ Untested. Options: * `fast` (default: False) uses libevent's http server, but has some issues: No streaming, no pipelining, no SSL. * See gevent.wsgi.WSGIServer() documentation for more options. """ def run(self, handler): from gevent import wsgi, pywsgi, local if not isinstance(threading.local(), local.local): msg = "Bottle requires gevent.monkey.patch_all() (before import)" raise RuntimeError(msg) if not self.options.pop('fast', None): wsgi = pywsgi self.options['log'] = None if self.quiet else 'default' address = (self.host, self.port) server = wsgi.WSGIServer(address, handler, **self.options) if 'BOTTLE_CHILD' in os.environ: import signal signal.signal(signal.SIGINT, lambda s, f: server.stop()) server.serve_forever() class GeventSocketIOServer(ServerAdapter): def run(self,handler): from socketio import server address = (self.host, self.port) server.SocketIOServer(address, handler, **self.options).serve_forever() class GunicornServer(ServerAdapter): """ Untested. See http://gunicorn.org/configure.html for options. """ def run(self, handler): from gunicorn.app.base import Application config = {'bind': "%s:%d" % (self.host, int(self.port))} config.update(self.options) class GunicornApplication(Application): def init(self, parser, opts, args): return config def load(self): return handler GunicornApplication().run() class EventletServer(ServerAdapter): """ Untested. Options: * `backlog` adjust the eventlet backlog parameter which is the maximum number of queued connections. Should be at least 1; the maximum value is system-dependent. * `family`: (default is 2) socket family, optional. See socket documentation for available families. """ def run(self, handler): from eventlet import wsgi, listen, patcher if not patcher.is_monkey_patched(os): msg = "Bottle requires eventlet.monkey_patch() (before import)" raise RuntimeError(msg) socket_args = {} for arg in ('backlog', 'family'): try: socket_args[arg] = self.options.pop(arg) except KeyError: pass address = (self.host, self.port) try: wsgi.server(listen(address, **socket_args), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen(address), handler) class RocketServer(ServerAdapter): """ Untested. """ def run(self, handler): from rocket import Rocket server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler }) server.start() class BjoernServer(ServerAdapter): """ Fast server written in C: https://github.com/jonashaag/bjoern """ def run(self, handler): from bjoern import run run(handler, self.host, self.port) class AutoServer(ServerAdapter): """ Untested. """ adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer, WSGIRefServer] def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options).run(handler) except ImportError: pass server_names = { 'cgi': CGIServer, 'flup': FlupFCGIServer, 'wsgiref': WSGIRefServer, 'waitress': WaitressServer, 'cherrypy': CherryPyServer, 'paste': PasteServer, 'fapws3': FapwsServer, 'tornado': TornadoServer, 'gae': AppEngineServer, 'twisted': TwistedServer, 'diesel': DieselServer, 'meinheld': MeinheldServer, 'gunicorn': GunicornServer, 'eventlet': EventletServer, 'gevent': GeventServer, 'geventSocketIO':GeventSocketIOServer, 'rocket': RocketServer, 'bjoern' : BjoernServer, 'auto': AutoServer, } ############################################################################### # Application Control ########################################################## ############################################################################### def load(target, **namespace): """ Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')`` """ module, target = target.split(":", 1) if ':' in target else (target, None) if module not in sys.modules: __import__(module) if not target: return sys.modules[module] if target.isalnum(): return getattr(sys.modules[module], target) package_name = module.split('.')[0] namespace[package_name] = sys.modules[package_name] return eval('%s.%s' % (module, target), namespace) def load_app(target): """ Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter. """ global NORUN; NORUN, nr_old = True, NORUN tmp = default_app.push() # Create a new "default application" try: rv = load(target) # Import the target module return rv if callable(rv) else tmp finally: default_app.remove(tmp) # Remove the temporary added default application NORUN = nr_old _debug = debug def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter. """ if NORUN: return if reloader and not os.environ.get('BOTTLE_CHILD'): lockfile = None try: fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock') os.close(fd) # We only need this file to exist. We never write to it while os.path.exists(lockfile): args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' environ['BOTTLE_LOCKFILE'] = lockfile p = subprocess.Popen(args, env=environ) while p.poll() is None: # Busy wait... os.utime(lockfile, None) # I am alive! time.sleep(interval) if p.poll() != 3: if os.path.exists(lockfile): os.unlink(lockfile) sys.exit(p.poll()) except KeyboardInterrupt: pass finally: if os.path.exists(lockfile): os.unlink(lockfile) return try: if debug is not None: _debug(debug) app = app or default_app() if isinstance(app, basestring): app = load_app(app) if not callable(app): raise ValueError("Application is not callable: %r" % app) for plugin in plugins or []: if isinstance(plugin, basestring): plugin = load(plugin) app.install(plugin) if server in server_names: server = server_names.get(server) if isinstance(server, basestring): server = load(server) if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise ValueError("Unknown or unsupported server: %r" % server) server.quiet = server.quiet or quiet if not server.quiet: _stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server))) _stderr("Listening on http://%s:%d/\n" % (server.host, server.port)) _stderr("Hit Ctrl-C to quit.\n\n") if reloader: lockfile = os.environ.get('BOTTLE_LOCKFILE') bgcheck = FileCheckerThread(lockfile, interval) with bgcheck: server.run(app) if bgcheck.status == 'reload': sys.exit(3) else: server.run(app) except KeyboardInterrupt: pass except (SystemExit, MemoryError): raise except: if not reloader: raise if not getattr(server, 'quiet', quiet): print_exc() time.sleep(interval) sys.exit(3) class FileCheckerThread(threading.Thread): """ Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old. """ def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.daemon = True self.lockfile, self.interval = lockfile, interval #: Is one of 'reload', 'error' or 'exit' self.status = None def run(self): exists = os.path.exists mtime = lambda p: os.stat(p).st_mtime files = dict() for module in list(sys.modules.values()): path = getattr(module, '__file__', '') if path[-4:] in ('.pyo', '.pyc'): path = path[:-1] if path and exists(path): files[path] = mtime(path) while not self.status: if not exists(self.lockfile)\ or mtime(self.lockfile) < time.time() - self.interval - 5: self.status = 'error' thread.interrupt_main() for path, lmtime in list(files.items()): if not exists(path) or mtime(path) > lmtime: self.status = 'reload' thread.interrupt_main() break time.sleep(self.interval) def __enter__(self): self.start() def __exit__(self, exc_type, *_): if not self.status: self.status = 'exit' # silent exit self.join() return exc_type is not None and issubclass(exc_type, KeyboardInterrupt) ############################################################################### # Template Adapters ############################################################ ############################################################################### class TemplateError(HTTPError): def __init__(self, message): HTTPError.__init__(self, 500, message) class BaseTemplate(object): """ Base class and minimal API for template adapters """ extensions = ['tpl','html','thtml','stpl'] settings = {} #used in prepare() defaults = {} #used in render() def __init__(self, source=None, name=None, lookup=None, encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings. """ self.name = name self.source = source.read() if hasattr(source, 'read') else source self.filename = source.filename if hasattr(source, 'filename') else None self.lookup = [os.path.abspath(x) for x in lookup] if lookup else [] self.encoding = encoding self.settings = self.settings.copy() # Copy from class variable self.settings.update(settings) # Apply if not self.source and self.name: self.filename = self.search(self.name, self.lookup) if not self.filename: raise TemplateError('Template %s not found.' % repr(name)) if not self.source and not self.filename: raise TemplateError('No template specified.') self.prepare(**self.settings) @classmethod def search(cls, name, lookup=None): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if not lookup: depr('The template lookup path list should not be empty.', True) #0.12 lookup = ['.'] if os.path.isabs(name) and os.path.isfile(name): depr('Absolute template path names are deprecated.', True) #0.12 return os.path.abspath(name) for spath in lookup: spath = os.path.abspath(spath) + os.sep fname = os.path.abspath(os.path.join(spath, name)) if not fname.startswith(spath): continue if os.path.isfile(fname): return fname for ext in cls.extensions: if os.path.isfile('%s.%s' % (fname, ext)): return '%s.%s' % (fname, ext) @classmethod def global_config(cls, key, *args): """ This reads or sets the global settings stored in class.settings. """ if args: cls.settings = cls.settings.copy() # Make settings local to class cls.settings[key] = args[0] else: return cls.settings[key] def prepare(self, **options): """ Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings. """ raise NotImplementedError def render(self, *args, **kwargs): """ Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (args) or directly, as keywords (kwargs). """ raise NotImplementedError class MakoTemplate(BaseTemplate): def prepare(self, **options): from mako.template import Template from mako.lookup import TemplateLookup options.update({'input_encoding':self.encoding}) options.setdefault('format_exceptions', bool(DEBUG)) lookup = TemplateLookup(directories=self.lookup, **options) if self.source: self.tpl = Template(self.source, lookup=lookup, **options) else: self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) _defaults = self.defaults.copy() _defaults.update(kwargs) return self.tpl.render(**_defaults) class CheetahTemplate(BaseTemplate): def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) self.context.vars.update(self.defaults) self.context.vars.update(kwargs) out = str(self.tpl) self.context.vars.clear() return out class Jinja2Template(BaseTemplate): def prepare(self, filters=None, tests=None, globals={}, **kwargs): from jinja2 import Environment, FunctionLoader self.env = Environment(loader=FunctionLoader(self.loader), **kwargs) if filters: self.env.filters.update(filters) if tests: self.env.tests.update(tests) if globals: self.env.globals.update(globals) if self.source: self.tpl = self.env.from_string(self.source) else: self.tpl = self.env.get_template(self.filename) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) _defaults = self.defaults.copy() _defaults.update(kwargs) return self.tpl.render(**_defaults) def loader(self, name): fname = self.search(name, self.lookup) if not fname: return with open(fname, "rb") as f: return f.read().decode(self.encoding) class SimpleTemplate(BaseTemplate): def prepare(self, escape_func=html_escape, noescape=False, syntax=None, **ka): self.cache = {} enc = self.encoding self._str = lambda x: touni(x, enc) self._escape = lambda x: escape_func(touni(x, enc)) self.syntax = syntax if noescape: self._str, self._escape = self._escape, self._str @cached_property def co(self): return compile(self.code, self.filename or '<string>', 'exec') @cached_property def code(self): source = self.source if not source: with open(self.filename, 'rb') as f: source = f.read() try: source, encoding = touni(source), 'utf8' except UnicodeError: depr('Template encodings other than utf8 are no longer supported.') #0.11 source, encoding = touni(source, 'latin1'), 'latin1' parser = StplParser(source, encoding=encoding, syntax=self.syntax) code = parser.translate() self.encoding = parser.encoding return code def _rebase(self, _env, _name=None, **kwargs): _env['_rebase'] = (_name, kwargs) def _include(self, _env, _name=None, **kwargs): env = _env.copy() env.update(kwargs) if _name not in self.cache: self.cache[_name] = self.__class__(name=_name, lookup=self.lookup) return self.cache[_name].execute(env['_stdout'], env) def execute(self, _stdout, kwargs): env = self.defaults.copy() env.update(kwargs) env.update({'_stdout': _stdout, '_printlist': _stdout.extend, 'include': functools.partial(self._include, env), 'rebase': functools.partial(self._rebase, env), '_rebase': None, '_str': self._str, '_escape': self._escape, 'get': env.get, 'setdefault': env.setdefault, 'defined': env.__contains__ }) eval(self.co, env) if env.get('_rebase'): subtpl, rargs = env.pop('_rebase') rargs['base'] = ''.join(_stdout) #copy stdout del _stdout[:] # clear stdout return self._include(env, subtpl, **rargs) return env def render(self, *args, **kwargs): """ Render the template using keyword arguments as local variables. """ env = {}; stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout) class StplSyntaxError(TemplateError): pass class StplParser(object): """ Parser for stpl templates. """ _re_cache = {} #: Cache for compiled re patterns # This huge pile of voodoo magic splits python code into 8 different tokens. # 1: All kinds of python strings (trust me, it works) _re_tok = '((?m)[urbURB]?(?:\'\'(?!\')|""(?!")|\'{6}|"{6}' \ '|\'(?:[^\\\\\']|\\\\.)+?\'|"(?:[^\\\\"]|\\\\.)+?"' \ '|\'{3}(?:[^\\\\]|\\\\.|\\n)+?\'{3}' \ '|"{3}(?:[^\\\\]|\\\\.|\\n)+?"{3}))' _re_inl = _re_tok.replace('|\\n','') # We re-use this string pattern later # 2: Comments (until end of line, but not the newline itself) _re_tok += '|(#.*)' # 3,4: Keywords that start or continue a python block (only start of line) _re_tok += '|^([ \\t]*(?:if|for|while|with|try|def|class)\\b)' \ '|^([ \\t]*(?:elif|else|except|finally)\\b)' # 5: Our special 'end' keyword (but only if it stands alone) _re_tok += '|((?:^|;)[ \\t]*end[ \\t]*(?=(?:%(block_close)s[ \\t]*)?\\r?$|;|#))' # 6: A customizable end-of-code-block template token (only end of line) _re_tok += '|(%(block_close)s[ \\t]*(?=$))' # 7: And finally, a single newline. The 8th token is 'everything else' _re_tok += '|(\\r?\\n)' # Match the start tokens of code areas in a template _re_split = '(?m)^[ \t]*(\\\\?)((%(line_start)s)|(%(block_start)s))' # Match inline statements (may contain python strings) _re_inl = '%%(inline_start)s((?:%s|[^\'"\n]*?)+)%%(inline_end)s' % _re_inl default_syntax = '<% %> % {{ }}' def __init__(self, source, syntax=None, encoding='utf8'): self.source, self.encoding = touni(source, encoding), encoding self.set_syntax(syntax or self.default_syntax) self.code_buffer, self.text_buffer = [], [] self.lineno, self.offset = 1, 0 self.indent, self.indent_mod = 0, 0 def get_syntax(self): """ Tokens as a space separated string (default: <% %> % {{ }}) """ return self._syntax def set_syntax(self, syntax): self._syntax = syntax self._tokens = syntax.split() if not syntax in self._re_cache: names = 'block_start block_close line_start inline_start inline_end' etokens = map(re.escape, self._tokens) pattern_vars = dict(zip(names.split(), etokens)) patterns = (self._re_split, self._re_tok, self._re_inl) patterns = [re.compile(p%pattern_vars) for p in patterns] self._re_cache[syntax] = patterns self.re_split, self.re_tok, self.re_inl = self._re_cache[syntax] syntax = property(get_syntax, set_syntax) def translate(self): if self.offset: raise RuntimeError('Parser is a one time instance.') while True: m = self.re_split.search(self.source[self.offset:]) if m: text = self.source[self.offset:self.offset+m.start()] self.text_buffer.append(text) self.offset += m.end() if m.group(1): # Escape syntax line, sep, _ = self.source[self.offset:].partition('\n') self.text_buffer.append(m.group(2)+line+sep) self.offset += len(line+sep)+1 continue self.flush_text() self.read_code(multiline=bool(m.group(4))) else: break self.text_buffer.append(self.source[self.offset:]) self.flush_text() return ''.join(self.code_buffer) def read_code(self, multiline): code_line, comment = '', '' while True: m = self.re_tok.search(self.source[self.offset:]) if not m: code_line += self.source[self.offset:] self.offset = len(self.source) self.write_code(code_line.strip(), comment) return code_line += self.source[self.offset:self.offset+m.start()] self.offset += m.end() _str, _com, _blk1, _blk2, _end, _cend, _nl = m.groups() if code_line and (_blk1 or _blk2): # a if b else c code_line += _blk1 or _blk2 continue if _str: # Python string code_line += _str elif _com: # Python comment (up to EOL) comment = _com if multiline and _com.strip().endswith(self._tokens[1]): multiline = False # Allow end-of-block in comments elif _blk1: # Start-block keyword (if/for/while/def/try/...) code_line, self.indent_mod = _blk1, -1 self.indent += 1 elif _blk2: # Continue-block keyword (else/elif/except/...) code_line, self.indent_mod = _blk2, -1 elif _end: # The non-standard 'end'-keyword (ends a block) self.indent -= 1 elif _cend: # The end-code-block template token (usually '%>') if multiline: multiline = False else: code_line += _cend else: # \n self.write_code(code_line.strip(), comment) self.lineno += 1 code_line, comment, self.indent_mod = '', '', 0 if not multiline: break def flush_text(self): text = ''.join(self.text_buffer) del self.text_buffer[:] if not text: return parts, pos, nl = [], 0, '\\\n'+' '*self.indent for m in self.re_inl.finditer(text): prefix, pos = text[pos:m.start()], m.end() if prefix: parts.append(nl.join(map(repr, prefix.splitlines(True)))) if prefix.endswith('\n'): parts[-1] += nl parts.append(self.process_inline(m.group(1).strip())) if pos < len(text): prefix = text[pos:] lines = prefix.splitlines(True) if lines[-1].endswith('\\\\\n'): lines[-1] = lines[-1][:-3] elif lines[-1].endswith('\\\\\r\n'): lines[-1] = lines[-1][:-4] parts.append(nl.join(map(repr, lines))) code = '_printlist((%s,))' % ', '.join(parts) self.lineno += code.count('\n')+1 self.write_code(code) @staticmethod def process_inline(chunk): if chunk[0] == '!': return '_str(%s)' % chunk[1:] return '_escape(%s)' % chunk def write_code(self, line, comment=''): code = ' ' * (self.indent+self.indent_mod) code += line.lstrip() + comment + '\n' self.code_buffer.append(code) def template(*args, **kwargs): """ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). """ tpl = args[0] if args else None adapter = kwargs.pop('template_adapter', SimpleTemplate) lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) tplid = (id(lookup), tpl) if tplid not in TEMPLATES or DEBUG: settings = kwargs.pop('template_settings', {}) if isinstance(tpl, adapter): TEMPLATES[tplid] = tpl if settings: TEMPLATES[tplid].prepare(**settings) elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings) else: TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings) if not TEMPLATES[tplid]: abort(500, 'Template (%s) not found' % tpl) for dictarg in args[1:]: kwargs.update(dictarg) return TEMPLATES[tplid].render(kwargs) mako_template = functools.partial(template, template_adapter=MakoTemplate) cheetah_template = functools.partial(template, template_adapter=CheetahTemplate) jinja2_template = functools.partial(template, template_adapter=Jinja2Template) def view(tpl_name, **defaults): """ Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if isinstance(result, (dict, DictMixin)): tplvars = defaults.copy() tplvars.update(result) return template(tpl_name, **tplvars) elif result is None: return template(tpl_name, defaults) return result return wrapper return decorator mako_view = functools.partial(view, template_adapter=MakoTemplate) cheetah_view = functools.partial(view, template_adapter=CheetahTemplate) jinja2_view = functools.partial(view, template_adapter=Jinja2Template) ############################################################################### # Constants and Globals ######################################################## ############################################################################### TEMPLATE_PATH = ['./', './views/'] TEMPLATES = {} DEBUG = False NORUN = False # If set, run() does nothing. Used by load_app() #: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found') HTTP_CODES = httplib.responses HTTP_CODES[418] = "I'm a teapot" # RFC 2324 HTTP_CODES[428] = "Precondition Required" HTTP_CODES[429] = "Too Many Requests" HTTP_CODES[431] = "Request Header Fields Too Large" HTTP_CODES[511] = "Network Authentication Required" _HTTP_STATUS_LINES = dict((k, '%d %s'%(k,v)) for (k,v) in HTTP_CODES.items()) #: The default template used for error pages. Override with @error() ERROR_PAGE_TEMPLATE = """ %%try: %%from %s import DEBUG, request <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>Error: {{e.status}}</title> <style type="text/css"> html {background-color: #eee; font-family: sans-serif;} body {background-color: #fff; border: 1px solid #ddd; padding: 15px; margin: 15px;} pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;} </style> </head> <body> <h1>Error: {{e.status}}</h1> <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt> caused an error:</p> <pre>{{e.body}}</pre> %%if DEBUG and e.exception: <h2>Exception:</h2> <pre>{{repr(e.exception)}}</pre> %%end %%if DEBUG and e.traceback: <h2>Traceback:</h2> <pre>{{e.traceback}}</pre> %%end </body> </html> %%except ImportError: <b>ImportError:</b> Could not generate the error page. Please add bottle to the import path. %%end """ % __name__ #: A thread-safe instance of :class:`LocalRequest`. If accessed from within a #: request callback, this instance always refers to the *current* request #: (even on a multithreaded server). request = LocalRequest() #: A thread-safe instance of :class:`LocalResponse`. It is used to change the #: HTTP response for the *current* request. response = LocalResponse() #: A thread-safe namespace. Not used by Bottle. local = threading.local() # Initialize app stack (create first empty Bottle app) # BC: 0.6.4 and needed for run() app = default_app = AppStack() app.push() #: A virtual package that redirects import statements. #: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`. ext = _ImportRedirect('bottle.ext' if __name__ == '__main__' else __name__+".ext", 'bottle_%s').module if __name__ == '__main__': opt, args, parser = _cmd_options, _cmd_args, _cmd_parser if opt.version: _stdout('Bottle %s\n'%__version__) sys.exit(0) if not args: parser.print_help() _stderr('\nError: No application entry point specified.\n') sys.exit(1) sys.path.insert(0, '.') sys.modules.setdefault('bottle', sys.modules['__main__']) host, port = (opt.bind or 'localhost'), 8080 if ':' in host and host.rfind(']') < host.rfind(':'): host, port = host.rsplit(':', 1) host = host.strip('[]') run(args[0], host=host, port=int(port), server=opt.server, reloader=opt.reload, plugins=opt.plugin, debug=opt.debug) # THE END
Python
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' # Add the library location to the path import sys sys.path.insert(0, 'lib') import os import httplib2 import sessions from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build from apiclient.http import MediaUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import AccessTokenRefreshError from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') def SibPath(name): """Generate a path that is a sibling of this file. Args: name: Name of sibling file. Returns: Path to sibling file. """ return os.path.join(os.path.dirname(__file__), name) # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session-secret SESSION_SECRET = open(SibPath('session.secret')).read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials. The CredentialsProperty is provided by the Google API Python Client, and is used by the Storage classes to store OAuth 2.0 credentials in the data store.""" credentials = CredentialsProperty() def CreateService(service, version, creds): """Create a Google API service. Load an API service from a discovery document and authorize it with the provided credentials. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). creds: Credentials used to authorize service. Returns: Authorized Google API service. """ # Instantiate an Http instance http = httplib2.Http() # Authorize the Http instance with the passed credentials creds.authorize(http) # Build a service from the passed discovery document path return build(service, version, http=http) class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.ids = [] @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get('state')) class BaseDriveHandler(webapp.RequestHandler): """Base request handler for drive applications. Adds Authorization support for Drive. """ def CreateOAuthFlow(self): """Create OAuth2.0 flow controller This controller can be used to perform all parts of the OAuth 2.0 dance including exchanging an Authorization code. Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = flow_from_clientsecrets('client.json', scope='') # Dynamically set the redirect_uri based on the request URL. This is extremely # convenient for debugging to an alternative host without manually setting the # redirect URI. flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0] return flow def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. code = self.request.get('code') if not code: # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. users_service = CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. userid = users_service.userinfo().get().execute().get('id') # Store the user id in the user's cookie-based session. session = sessions.LilCookies(self, SESSION_SECRET) session.set_secure_cookie(name='userid', value=userid) # Store the credentials in the data store using the userid as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.redirect(uri) class MainPage(BaseDriveHandler): """Web handler for the main page. Handles requests and returns the user interface for Open With and Create cases. Responsible for parsing the state provided from the Drive UI and acting appropriately. """ def get(self): """Handle GET for Create New and Open With. This creates an authorized client, and checks whether a resource id has been passed or not. If a resource ID has been passed, this is the Open With use-case, otherwise it is the Create New use-case. """ # Fetch the credentials by extracting an OAuth 2.0 authorization code from # the request URL. If the code is not present, redirect to the OAuth 2.0 # authorization URL. creds = self.GetCodeCredentials() if not creds: return self.RedirectAuth() # Extract the numerical portion of the client_id from the stored value in # the OAuth flow. You could also store this value as a separate variable # somewhere. client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0] # Generate a state instance for the request, this includes the action, and # the file id(s) that have been sent from the Drive user interface. drive_state = DriveState.FromRequest(self.request) if drive_state.action == 'open': file_ids = [str(i) for i in drive_state.ids] else: file_ids = [''] self.RenderTemplate(file_ids=file_ids, client_id=client_id) def RenderTemplate(self, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ self.response.headers['Content-Type'] = 'text/html' self.response.out.write(template.render('index.html', context)) class ServiceHandler(BaseDriveHandler): """Web handler for the service to read and write to Drive.""" def post(self): """Called when HTTP POST requests are received by the web application. The POST body is JSON which is deserialized and used as values to create a new file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() # Create a new file data structure. resource = { 'title': data['title'], 'description': data['description'], 'mimeType': data['mimeType'], } try: # Make an insert request to create a new file. A MediaInMemoryUpload # instance is used to upload the file body. resource = service.files().insert( body=resource, media_body=MediaInMemoryUpload(data.get('content', ''), data['mimeType']), ).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(id=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: resp, f['content'] = service._http.request(downloadUrl) else: f['content'] = '' else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() def put(self): """Called when HTTP PUT requests are received by the web application. The PUT body is JSON which is deserialized and used as values to update a file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() try: # Create a new file data structure. resource = { 'title': data['title'] or 'Untitled Document', 'description': data['description'], 'mimeType': data['mimeType'], } # Make an update request to update the file. A MediaInMemoryUpload # instance is used to upload the file body. Because of a limitation, this # request must be made in two parts, the first to update the metadata, and # the second to update the body. resource = service.files().update( id=data['resource_id'], newRevision=False, body=resource, media_body=None, ).execute() resource = service.files().update( id=data['resource_id'], newRevision=True, body=None, media_body=MediaInMemoryUpload(data.get('content', ''), data['mimeType']), ).execute() # Respond with the updated file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def CreateDrive(self): """Create a drive client instance. The service can only ever retrieve the credentials from the session. """ # For the service, the session holds the credentials creds = self.GetSessionCredentials() if creds: # If the session contains credentials, use them to create a Drive service # instance. return CreateService('drive', 'v1', creds) else: # If no credentials could be loaded from the session, redirect the user to # the authorization page. self.RedirectAuth() def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.RespondJSON({'redirect': uri}) def RespondJSON(self, data): """Generate a JSON response and return it to the client. Args: data: The data that will be converted to JSON to return. """ self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(data)) def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body) class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] # Create an WSGI application suitable for running on App Engine application = webapp.WSGIApplication( [('/', MainPage), ('/svc', ServiceHandler)], # XXX Set to False in production. debug=True ) def main(): """Main entry point for executing a request with this handler.""" run_wsgi_app(application) if __name__ == "__main__": main()
Python
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import base64 import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs parse_qs # placate pyflakes except ImportError: # fall back for Python 2.5 from cgi import parse_qs try: from hashlib import sha1 sha = sha1 except ImportError: # hashlib was added in Python 2.5 import sha import _version __version__ = _version.__version__ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, unicode): if not isinstance(s, str): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') except UnicodeDecodeError, le: raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s def to_utf8(s): return to_unicode(s).encode('utf-8') def to_unicode_if_string(s): if isinstance(s, basestring): return to_unicode(s) else: return s def to_utf8_if_string(s): if isinstance(s, basestring): return to_utf8(s) else: return s def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, basestring): return to_unicode(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ] def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, basestring): return to_utf8(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ] def escape(s): """Escape a URL including any /.""" return urllib.quote(s.encode('utf-8'), safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = OAUTH_VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None, body='', is_form_encoded=False): if url is not None: self.url = to_unicode(url) self.method = method if parameters is not None: for k, v in parameters.iteritems(): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v self.body = body self.is_form_encoded = is_form_encoded @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" d = {} for k, v in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError, e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urllib.urlencode(items) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, body='', is_form_encoded=False): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_POST_CONTENT_TYPE) is_form_encoded = \ headers.get('Content-Type') == 'application/x-www-form-urlencoded' if is_form_encoded and body: parameters = parse_qs(body) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=is_form_encoded) req.sign_request(self.method, self.consumer, self.token) schema, rest = urllib.splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' host, rest = urllib.splithost(rest) realm = schema + ':' + hierpart + host if is_form_encoded: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header(realm=realm)) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = OAUTH_VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) def _get_version(self, request): """Return the version of the request for this server.""" try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
Python
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 2.0 Do the OAuth 2.0 Web Server dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ['run'] import BaseHTTPServer import gflags import socket import sys from client import FlowExchangeError try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage): """Core code for a command-line application. Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. Returns: Credentials, the obtained credential. """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = 'oob' authorize_url = flow.step1_get_authorize_url(oauth_callback) print 'Go to the following link in your browser:' print authorize_url print if FLAGS.auth_local_webserver: print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter ' print '--noauth_local_webserver.' print code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '<client id>', 'userAgent': '<user agent>', 'scope': '<scope>' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import fcntl import logging import os import threading try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson from client import Storage as BaseStorage from client import Credentials logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or list of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ filename = os.path.realpath(os.path.expanduser(filename)) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly)) finally: _multistores_lock.release() if type(scope) is list: scope = ' '.join(scope) return multistore._get_storage(client_id, user_agent, scope) class _MultiStore(object): """A file backed store for multiple credentials.""" def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._filename = filename self._thread_lock = threading.Lock() self._file_handle = None self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # (client_id, user_agent, scope) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, client_id, user_agent, scope): self._multistore = multistore self._client_id = client_id self._user_agent = user_agent self._scope = scope def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential( self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(credentials, self._scope) def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() # Check to see if the file is writeable. if os.access(self._filename, os.W_OK): self._file_handle = open(self._filename, 'r+') fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_EX) else: # Cannot open in read/write mode. Open only in read mode. self._file_handle = open(self._filename, 'r') self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._filename) if os.path.getsize(self._filename) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" if not self._read_only: fcntl.lockf(self._file_handle.fileno(), fcntl.LOCK_UN) self._file_handle.close() self._thread_lock.release() def _locked_json_read(self): """Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON. """ assert self._thread_lock.locked() self._file_handle.seek(0) return simplejson.load(self._file_handle) def _locked_json_write(self, data): """Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written. """ assert self._thread_lock.locked() if self._read_only: return self._file_handle.seek(0) simplejson.dump(data, self._file_handle, sort_keys=True, indent=2) self._file_handle.truncate() def _refresh_data_cache(self): """Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store. """ self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. ' 'Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object. """ raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = { 'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2] } raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_credential(self, client_id, user_agent, scope): """Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present """ key = (client_id, user_agent, scope) return self._data.get(key, None) def _update_credential(self, cred, scope): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: cred: The OAuth2Credential to update/set scope: The scope(s) that this credential covers """ key = (cred.client_id, cred.user_agent, scope) self._data[key] = cred self._write() def _get_storage(self, client_id, user_agent, scope): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, client_id, user_agent, scope)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse HAS_OPENSSL = False try: from oauth2client.crypt import Signer from oauth2client.crypt import make_signed_jwt from oauth2client.crypt import verify_signed_jwt_with_certs HAS_OPENSSL = True except ImportError: pass try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl # Determine if we can write to the file system, and if we can use a local file # cache behing httplib2. if hasattr(os, 'tempnam'): # Put cache file in the director '.cache'. CACHED_HTTP = httplib2.Http('.cache') else: CACHED_HTTP = httplib2.Http() logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' class Error(Exception): """Base error for this module.""" pass class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" pass class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" pass class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ pass class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" pass class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" pass def _abstract(): raise NotImplementedError('You need to override this function') class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Crentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() def _to_json(self, strip): """Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. id_token: object, The identity of the resource owner. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ data = simplejson.loads(s) if 'token_expiry' in data and not isinstance(data['token_expiry'], datetime.datetime): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], data.get('id_token', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = datetime.datetime.utcnow() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. """ if not self.store: self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http: An instance of httplib2.Http.request or something that acts like it. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refresing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.error('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except: pass raise AccessTokenRefreshError(error_msg) def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not self.access_token: logger.info('Attempting refresh to obtain initial access_token') self._refresh(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} headers['authorization'] = 'OAuth ' + self.access_token if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent import logging logging.info(str(uri)) logging.info(str(headers)) resp, content = request_orig(uri, method, body, headers, redirections, connection_type) if resp.status == 401: logger.info('Refreshing due to a 401') self._refresh(request_orig) headers['authorization'] = 'OAuth ' + self.access_token return request_orig(uri, method, body, headers, redirections, connection_type) else: return (resp, content) http.request = new_request return http class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable that when passed a Credential will store the credential back to where it came from. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed.") class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion_type': self.assertion_type, 'assertion': assertion, 'grant_type': 'assertion', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() if HAS_OPENSSL: # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then # don't create the SignedJwtAssertionCredentials or the verify_id_token() # method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in P12 format. scope: string or list of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key. user_agent: string, HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. kwargs: kwargs, Additional parameters to add to the JWT token, for example prn=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( 'http://oauth.net/grant_type/jwt/1.0/bearer', user_agent, token_uri=token_uri, ) if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.private_key = private_key self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], data['private_key'], data['private_key_password'], data['scope'], data['user_agent'], data['token_uri'], data['kwargs'] ) retval.invalid = data['invalid'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logging.debug(str(payload)) return make_signed_jwt( Signer.from_string(self.private_key, self.private_key_password), payload) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = CACHED_HTTP resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = { 'access_type': 'offline', } self.params.update(kwargs) self.redirect_uri = None def step1_get_authorize_url(self, redirect_uri='oob'): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ self.redirect_uri = redirect_uri query = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, } query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def step2_exchange(self, code, http=None): """Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch """ if not (isinstance(code, str) or isinstance(code, unicode)): code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if simplejson.loads fails? d = simplejson.loads(content) access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token: %s' % content) return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, id_token=d.get('id_token', None)) else: logger.error('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except: pass raise FlowExchangeError(error_msg) def flow_from_clientsecrets(filename, scope, message=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) to request. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, None, # user_agent client_info['auth_uri'], client_info['token_uri']) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import threading try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None try: f = open(self._filename, 'r') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ f = open(self._filename, 'w') f.write(credentials.to_json()) f.close()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use OAuth 2.0 on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import httplib2 import logging import pickle import time try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson import clientsecrets from client import AccessTokenRefreshError from client import AssertionCredentials from client import Credentials from client import Flow from client import OAuth2WebServerFlow from client import Storage from google.appengine.api import memcache from google.appengine.api import users from google.appengine.api.app_identity import app_identity from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' class InvalidClientSecretsError(Exception): """The client_secrets.json file is malformed or missing required fields.""" pass class AppAssertionCredentials(AssertionCredentials): """Credentials object for App Engine Assertion Grants This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself. The algorithm used for generating the assertion is the Signed JSON Web Token (JWT) algorithm. Additional details can be found at the following link: http://self-issued.info/docs/draft-jones-json-web-token.html This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ def __init__(self, scope, audience='https://accounts.google.com/o/oauth2/token', assertion_type='http://oauth.net/grant_type/jwt/1.0/bearer', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for AppAssertionCredentials Args: scope: string, scope of the credentials being requested. audience: string, The audience, or verifier of the assertion. For convenience defaults to Google's audience. assertion_type: string, Type name that will identify the format of the assertion string. For convience, defaults to the JSON Web Token (JWT) assertion type string. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ self.scope = scope self.audience = audience self.app_name = app_identity.get_service_account_name() super(AppAssertionCredentials, self).__init__( assertion_type, None, token_uri) @classmethod def from_json(cls, json): data = simplejson.loads(json) retval = AccessTokenCredentials( data['scope'], data['audience'], data['assertion_type'], data['token_uri']) return retval def _generate_assertion(self): header = { 'typ': 'JWT', 'alg': 'RS256', } now = int(time.time()) claims = { 'aud': self.audience, 'scope': self.scope, 'iat': now, 'exp': now + 3600, 'iss': self.app_name, } jwt_components = [base64.b64encode(simplejson.dumps(seg)) for seg in [header, claims]] base_str = ".".join(jwt_components) key_name, signature = app_identity.sign_blob(base_str) jwt_components.append(base64.b64encode(signature)) return ".".join(jwt_components) class FlowProperty(db.Property): """App Engine datastore Property for Flow. Utility property that allows easy storage and retreival of an oauth2client.Flow""" # Tell what the user type is. data_type = Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, Flow): raise db.BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials """ # Tell what the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logging.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: cred = '' else: cred = cred.to_json() return db.Blob(cred) # For reading from datastore. def make_value_from_datastore(self, value): logging.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials def validate(self, value): value = super(CredentialsProperty, self).validate(value) logging.info("validate: Got type " + str(type(value))) if value is not None and not isinstance(value, Credentials): raise db.BadValueError('Property %s must be convertible ' 'to a Credentials instance (%s)' % (self.name, value)) #if value is not None and not isinstance(value, Credentials): # return None return value class StorageByKeyName(Storage): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name, cache=None): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty cache: memcache, a write-through cache to put in front of the datastore """ self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ if self._cache: json = self._cache.get(self._key_name) if json: return Credentials.new_from_json(json) credential = None entity = self._model.get_by_key_name(self._key_name) if entity is not None: credential = getattr(entity, self._property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) if self._cache: self._cache.set(self._key_name, credentials.to_json()) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json()) class CredentialsModel(db.Model): """Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsProperty() class OAuth2Decorator(object): """Utility for making OAuth 2.0 easier. Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods. Example: decorator = OAuth2Decorator( client_id='837...ent.com', client_secret='Qh...wwI', scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, client_id, client_secret, scope, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', message=None): """Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. message: Message to display if there are problems with the OAuth 2.0 configuration. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, None, auth_uri, token_uri) self.credentials = None self._request_handler = None self._message = message self._in_error = False def _display_error_message(self, request_handler): request_handler.response.out.write('<html><body>') request_handler.response.out.write(self._message) request_handler.response.out.write('</body></html>') def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return # Store the request URI in 'state' so we can use it later self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: method(request_handler, *args) except AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) return check_oauth def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() method(request_handler, *args) return setup_oauth def has_credentials(self): """True if for the logged in user there are valid access Credentials. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ return self.credentials is not None and not self.credentials.invalid def authorize_url(self): """Returns the URL to start the OAuth dance. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ callback = self._request_handler.request.relative_url('/oauth2callback') url = self.flow.step1_get_authorize_url(callback) user = users.get_current_user() memcache.set(user.user_id(), pickle.dumps(self.flow), namespace=OAUTH2CLIENT_NAMESPACE) return url def http(self): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. """ return self.credentials.authorize(httplib2.Http()) class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): """An OAuth2Decorator that builds from a clientsecrets file. Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator. Example: decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json') scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, filename, scope, message=None): """Constructor Args: filename: string, File name of client secrets. scope: string, Space separated list of scopes. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, client_info['auth_uri'], client_info['token_uri'], message) except clientsecrets.InvalidClientSecretsError: self._in_error = True if message is not None: self._message = message else: self._message = "Please configure your application for OAuth 2.0" def oauth2decorator_from_clientsecrets(filename, scope, message=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string, Space separated list of scopes. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message) class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: %s' % errormsg) else: user = users.get_current_user() flow = pickle.loads(memcache.get(user.user_id(), namespace=OAUTH2CLIENT_NAMESPACE)) # This code should be ammended with application specific error # handling. The following cases should be considered: # 1. What if the flow doesn't exist in memcache? Or is corrupt? # 2. What if the step2_exchange fails? if flow: credentials = flow.step2_exchange(self.request.params) StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').put(credentials) self.redirect(str(self.request.get('state'))) else: # TODO Add error handling here. pass application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)]) def main(): run_wsgi_app(application)
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import hashlib import logging import time from OpenSSL import crypto try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds class AppIdentityError(Exception): pass class Verifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was singed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return Verifier(pubkey) class Signer(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey, The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in P12 format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ pkey = crypto.load_pkcs12(key, password).get_privatekey() return Signer(pkey) def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logging.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed
Python
# Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
Python
import Cookie import datetime import time import email.utils import calendar import base64 import hashlib import hmac import re import logging # Ripped from the Tornado Framework's web.py # http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09 # # Tornado is licensed under the Apache Licence, Version 2.0 # (http://www.apache.org/licenses/LICENSE-2.0.html). # # Example: # from vendor.prayls.lilcookies import LilCookies # cookieutil = LilCookies(self, application_settings['cookie_secret']) # cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100) # cookieutil.get_secure_cookie(name = 'mykey') class LilCookies: @staticmethod def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s @staticmethod def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 @staticmethod def _signature_from_secret(cookie_secret, *parts): """ Takes a secret salt value to create a signature for values in the `parts` param.""" hash = hmac.new(cookie_secret, digestmod=hashlib.sha1) for part in parts: hash.update(part) return hash.hexdigest() @staticmethod def _signed_cookie_value(cookie_secret, name, value): """ Returns a signed value for use in a cookie. This is helpful to have in its own method if you need to re-use this function for other needs. """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp) return "|".join([value, timestamp, signature]) @staticmethod def _verified_cookie_value(cookie_secret, name, signed_value): """Returns the un-encrypted value given the signed value if it validates, or None.""" value = signed_value if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1]) if not LilCookies._time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None def __init__(self, handler, cookie_secret): """You must specify the cookie_secret to use any of the secure methods. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. """ if len(cookie_secret) < 45: raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret) self.handler = handler self.request = handler.request self.response = handler.response self.cookie_secret = cookie_secret def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" if name in self.cookies(): return self._cookies[name].value return default def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ name = LilCookies._utf8(name) value = LilCookies._utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp, localtime=False, usegmt=True) if path: new_cookie[name]["path"] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v # The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush. for vals in new_cookie.values(): self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None))) def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies().iterkeys(): self.clear_cookie(name) def set_secure_cookie(self, name, value, expires_days=30, **kwargs): """Signs and timestamps a cookie so it cannot be forged. To read a cookie set with this method, use get_secure_cookie(). """ value = LilCookies._signed_cookie_value(self.cookie_secret, name, value) self.set_cookie(name, value, expires_days=expires_days, **kwargs) def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None.""" if value is None: value = self.get_cookie(name) return LilCookies._verified_cookie_value(self.cookie_secret, name, value) def _cookie_signature(self, *parts): return LilCookies._signature_from_secret(self.cookie_secret)
Python
# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to encapsulate a single HTTP request. The classes implement a command pattern, with every object supporting an execute() method that does the actuall HTTP request. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'HttpRequest', 'RequestMockBuilder', 'HttpMock' 'set_user_agent', 'tunnel_patch' ] import StringIO import copy import gzip import httplib2 import mimeparse import mimetypes import os import urllib import urlparse import uuid from anyjson import simplejson from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email.parser import FeedParser from errors import BatchError from errors import HttpError from errors import ResumableUploadError from errors import UnexpectedBodyError from errors import UnexpectedMethodError from model import JsonModel class MediaUploadProgress(object): """Status of a resumable upload.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of upload completed, as a float.""" return float(self.resumable_progress) / float(self.total_size) class MediaUpload(object): """Describes a media object to upload. Base class that defines the interface of MediaUpload subclasses. """ def getbytes(self, begin, end): raise NotImplementedError() def size(self): raise NotImplementedError() def chunksize(self): raise NotImplementedError() def mimetype(self): return 'application/octet-stream' def resumable(self): return False def _to_json(self, strip=None): """Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) if strip is not None: for member in strip: del d[member] d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json() @classmethod def new_from_json(cls, s): """Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) class MediaFileUpload(MediaUpload): """A MediaUpload for a file. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed uploading images: media = MediaFileUpload('smiley.png', mimetype='image/png', chunksize=1000, resumable=True) service.objects().insert( bucket=buckets['items'][0]['id'], name='smiley.png', media_body=media).execute() """ def __init__(self, filename, mimetype=None, chunksize=10000, resumable=False): """Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._filename = filename self._size = os.path.getsize(filename) self._fd = None if mimetype is None: (mimetype, encoding) = mimetypes.guess_type(filename) self._mimetype = mimetype self._chunksize = chunksize self._resumable = resumable def mimetype(self): return self._mimetype def size(self): return self._size def chunksize(self): return self._chunksize def resumable(self): return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first. """ if self._fd is None: self._fd = open(self._filename, 'rb') self._fd.seek(begin) return self._fd.read(length) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(['_fd']) @staticmethod def from_json(s): d = simplejson.loads(s) return MediaFileUpload( d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable']) class HttpRequest(object): """Encapsulates a single HTTP request.""" def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request. """ self.uri = uri self.method = method self.body = body self.headers = headers or {} self.methodId = methodId self.http = http self.postproc = postproc self.resumable = resumable # Pull the multipart boundary out of the content-type header. major, minor, params = mimeparse.parse_mime_type( headers.get('content-type', 'application/json')) # Terminating multipart boundary get a trailing '--' appended. self.multipart_boundary = params.get('boundary', '').strip('"') + '--' # If this was a multipart resumable, the size of the non-media part. self.multipart_size = 0 # The resumable URI to send chunks to. self.resumable_uri = None # The bytes that have been uploaded. self.resumable_progress = 0 self.total_size = 0 if resumable is not None: if self.body is not None: self.multipart_size = len(self.body) else: self.multipart_size = 0 self.total_size = ( self.resumable.size() + self.multipart_size + len(self.multipart_boundary)) def execute(self, http=None): """Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. Returns: A deserialized object model of the response body as determined by the postproc. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: http = self.http if self.resumable: body = None while body is None: _, body = self.next_chunk(http) return body else: resp, content = http.request(self.uri, self.method, body=self.body, headers=self.headers) if resp.status >= 300: raise HttpError(resp, content, self.uri) return self.postproc(resp, content) def next_chunk(self, http=None): """Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload('smiley.png', mimetype='image/png', chunksize=1000, resumable=True) request = service.objects().insert( bucket=buckets['items'][0]['id'], name='smiley.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. """ if http is None: http = self.http if self.resumable_uri is None: start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() start_headers['X-Upload-Content-Length'] = str(self.resumable.size()) start_headers['Content-Length'] = '0' resp, content = http.request(self.uri, self.method, body="", headers=start_headers) if resp.status == 200 and 'location' in resp: self.resumable_uri = resp['location'] else: raise ResumableUploadError("Failed to retrieve starting URI.") if self.body: begin = 0 data = self.body else: begin = self.resumable_progress - self.multipart_size data = self.resumable.getbytes(begin, self.resumable.chunksize()) # Tack on the multipart/related boundary if we are at the end of the file. if begin + self.resumable.chunksize() >= self.resumable.size(): data += self.multipart_boundary headers = { 'Content-Range': 'bytes %d-%d/%d' % ( self.resumable_progress, self.resumable_progress + len(data) - 1, self.total_size), } resp, content = http.request(self.resumable_uri, 'PUT', body=data, headers=headers) if resp.status in [200, 201]: return None, self.postproc(resp, content) elif resp.status == 308: # A "308 Resume Incomplete" indicates we are not done. self.resumable_progress = int(resp['range'].split('-')[1]) + 1 if self.resumable_progress >= self.multipart_size: self.body = None if 'location' in resp: self.resumable_uri = resp['location'] else: raise HttpError(resp, content, self.uri) return MediaUploadProgress(self.resumable_progress, self.total_size), None def to_json(self): """Returns a JSON representation of the HttpRequest.""" d = copy.copy(self.__dict__) if d['resumable'] is not None: d['resumable'] = self.resumable.to_json() del d['http'] del d['postproc'] return simplejson.dumps(d) @staticmethod def from_json(s, http, postproc): """Returns an HttpRequest populated with info from a JSON object.""" d = simplejson.loads(s) if d['resumable'] is not None: d['resumable'] = MediaUpload.new_from_json(d['resumable']) return HttpRequest( http, postproc, uri=d['uri'], method=d['method'], body=d['body'], headers=d['headers'], methodId=d['methodId'], resumable=d['resumable']) class BatchHttpRequest(object): """Batches multiple HttpRequest objects into a single HTTP request.""" def __init__(self, callback=None, batch_uri=None): """Constructor for a BatchHttpRequest. Args: callback: callable, A callback to be called for each response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. batch_uri: string, URI to send batch requests to. """ if batch_uri is None: batch_uri = 'https://www.googleapis.com/batch' self._batch_uri = batch_uri # Global callback to be called for each individual response in the batch. self._callback = callback # A map from id to (request, callback) pairs. self._requests = {} # List of request ids, in the order in which they were added. self._order = [] # The last auto generated id. self._last_auto_id = 0 # Unique ID on which to base the Content-ID headers. self._base_id = None def _id_to_header(self, id_): """Convert an id to a Content-ID header value. Args: id_: string, identifier of individual request. Returns: A Content-ID header with the id_ encoded into it. A UUID is prepended to the value because Content-ID headers are supposed to be universally unique. """ if self._base_id is None: self._base_id = uuid.uuid4() return '<%s+%s>' % (self._base_id, urllib.quote(id_)) def _header_to_id(self, header): """Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _id_to_header() returns. Args: header: string, Content-ID header value. Returns: The extracted id value. Raises: BatchError if the header is not in the expected format. """ if header[0] != '<' or header[-1] != '>': raise BatchError("Invalid value for Content-ID: %s" % header) if '+' not in header: raise BatchError("Invalid value for Content-ID: %s" % header) base, id_ = header[1:-1].rsplit('+', 1) return urllib.unquote(id_) def _serialize_request(self, request): """Convert an HttpRequest object into a string. Args: request: HttpRequest, the request to serialize. Returns: The request as a string in application/http format. """ # Construct status line parsed = urlparse.urlparse(request.uri) request_line = urlparse.urlunparse( (None, None, parsed.path, parsed.params, parsed.query, None) ) status_line = request.method + ' ' + request_line + ' HTTP/1.1\n' major, minor = request.headers.get('content-type', 'text/plain').split('/') msg = MIMENonMultipart(major, minor) headers = request.headers.copy() # MIMENonMultipart adds its own Content-Type header. if 'content-type' in headers: del headers['content-type'] for key, value in headers.iteritems(): msg[key] = value msg['Host'] = parsed.netloc msg.set_unixfrom(None) if request.body is not None: msg.set_payload(request.body) body = msg.as_string(False) # Strip off the \n\n that the MIME lib tacks onto the end of the payload. if request.body is None: body = body[:-2] return status_line + body def _deserialize_response(self, payload): """Convert string into httplib2 response and content. Args: payload: string, headers and body as a string. Returns: A pair (resp, content) like would be returned from httplib2.request. """ # Strip off the status line status_line, payload = payload.split('\n', 1) protocol, status, reason = status_line.split(' ') # Parse the rest of the response parser = FeedParser() parser.feed(payload) msg = parser.close() msg['status'] = status # Create httplib2.Response from the parsed headers. resp = httplib2.Response(msg) resp.reason = reason resp.version = int(protocol.split('/', 1)[1].replace('.', '')) content = payload.split('\r\n\r\n', 1)[1] return resp, content def _new_id(self): """Create a new id. Auto incrementing number that avoids conflicts with ids already used. Returns: string, a new unique id. """ self._last_auto_id += 1 while str(self._last_auto_id) in self._requests: self._last_auto_id += 1 return str(self._last_auto_id) def add(self, request, callback=None, request_id=None): """Add a new request. Every callback added will be paired with a unique id, the request_id. That unique id will be passed back to the callback when the response comes back from the server. The default behavior is to have the library generate it's own unique id. If the caller passes in a request_id then they must ensure uniqueness for each request_id, and if they are not an exception is raised. Callers should either supply all request_ids or nevery supply a request id, to avoid such an error. Args: request: HttpRequest, Request to add to the batch. callback: callable, A callback to be called for this response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. request_id: string, A unique id for the request. The id will be passed to the callback with the response. Returns: None Raises: BatchError if a resumable request is added to a batch. KeyError is the request_id is not unique. """ if request_id is None: request_id = self._new_id() if request.resumable is not None: raise BatchError("Resumable requests cannot be used in a batch request.") if request_id in self._requests: raise KeyError("A request with this ID already exists: %s" % request_id) self._requests[request_id] = (request, callback) self._order.append(request_id) def execute(self, http=None): """Execute all the requests as a single batched HTTP request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. If one isn't supplied then use a http object from the requests in this batch. Returns: None Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: for request_id in self._order: request, callback = self._requests[request_id] if request is not None: http = request.http break if http is None: raise ValueError("Missing a valid http object.") msgRoot = MIMEMultipart('mixed') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # Add all the individual requests. for request_id in self._order: request, callback = self._requests[request_id] msg = MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._id_to_header(request_id) body = self._serialize_request(request) msg.set_payload(body) msgRoot.attach(msg) body = msgRoot.as_string() headers = {} headers['content-type'] = ('multipart/mixed; ' 'boundary="%s"') % msgRoot.get_boundary() resp, content = http.request(self._batch_uri, 'POST', body=body, headers=headers) if resp.status >= 300: raise HttpError(resp, content, self._batch_uri) # Now break up the response and process each one with the correct postproc # and trigger the right callbacks. boundary, _ = content.split(None, 1) # Prepend with a content-type header so FeedParser can handle it. header = 'Content-Type: %s\r\n\r\n' % resp['content-type'] content = header + content parser = FeedParser() parser.feed(content) respRoot = parser.close() if not respRoot.is_multipart(): raise BatchError("Response not in multipart/mixed format.") parts = respRoot.get_payload() for part in parts: request_id = self._header_to_id(part['Content-ID']) headers, content = self._deserialize_response(part.get_payload()) # TODO(jcgregorio) Remove this temporary hack once the server stops # gzipping individual response bodies. if content[0] != '{': gzipped_content = content content = gzip.GzipFile( fileobj=StringIO.StringIO(gzipped_content)).read() request, cb = self._requests[request_id] postproc = request.postproc response = postproc(resp, content) if cb is not None: cb(request_id, response) if self._callback is not None: self._callback(request_id, response) class HttpRequestMock(object): """Mock of HttpRequest. Do not construct directly, instead use RequestMockBuilder. """ def __init__(self, resp, content, postproc): """Constructor for HttpRequestMock Args: resp: httplib2.Response, the response to emulate coming from the request content: string, the response body postproc: callable, the post processing function usually supplied by the model class. See model.JsonModel.response() as an example. """ self.resp = resp self.content = content self.postproc = postproc if resp is None: self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) if 'reason' in self.resp: self.resp.reason = self.resp['reason'] def execute(self, http=None): """Execute the request. Same behavior as HttpRequest.execute(), but the response is mocked and not really from an HTTP request/response. """ return self.postproc(self.resp, self.content) class RequestMockBuilder(object): """A simple mock of HttpRequest Pass in a dictionary to the constructor that maps request methodIds to tuples of (httplib2.Response, content, opt_expected_body) that should be returned when that method is called. None may also be passed in for the httplib2.Response, in which case a 200 OK response will be generated. If an opt_expected_body (str or dict) is provided, it will be compared to the body and UnexpectedBodyError will be raised on inequality. Example: response = '{"data": {"id": "tag:google.c...' requestBuilder = RequestMockBuilder( { 'plus.activities.get': (None, response), } ) apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) Methods that you do not supply a response for will return a 200 OK with an empty string as the response content or raise an excpetion if check_unexpected is set to True. The methodId is taken from the rpcName in the discovery document. For more details see the project wiki. """ def __init__(self, responses, check_unexpected=False): """Constructor for RequestMockBuilder The constructed object should be a callable object that can replace the class HttpResponse. responses - A dictionary that maps methodIds into tuples of (httplib2.Response, content). The methodId comes from the 'rpcName' field in the discovery document. check_unexpected - A boolean setting whether or not UnexpectedMethodError should be raised on unsupplied method. """ self.responses = responses self.check_unexpected = check_unexpected def __call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Implements the callable interface that discovery.build() expects of requestBuilder, which is to build an object compatible with HttpRequest.execute(). See that method for the description of the parameters and the expected response. """ if methodId in self.responses: response = self.responses[methodId] resp, content = response[:2] if len(response) > 2: # Test the body against the supplied expected_body. expected_body = response[2] if bool(expected_body) != bool(body): # Not expecting a body and provided one # or expecting a body and not provided one. raise UnexpectedBodyError(expected_body, body) if isinstance(expected_body, str): expected_body = simplejson.loads(expected_body) body = simplejson.loads(body) if body != expected_body: raise UnexpectedBodyError(expected_body, body) return HttpRequestMock(resp, content, postproc) elif self.check_unexpected: raise UnexpectedMethodError(methodId) else: model = JsonModel(False) return HttpRequestMock(None, '{}', model.response) class HttpMock(object): """Mock of httplib2.Http""" def __init__(self, filename, headers=None): """ Args: filename: string, absolute filename to read response from headers: dict, header to return with response """ if headers is None: headers = {'status': '200 OK'} f = file(filename, 'r') self.data = f.read() f.close() self.headers = headers def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): return httplib2.Response(self.headers), self.data class HttpMockSequence(object): """Mock of httplib2.Http Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an httplib2.Http instance. http = HttpMockSequence([ ({'status': '401'}, ''), ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request("http://examples.com") There are special values you can pass in for content to trigger behavours that are helpful in testing. 'echo_request_headers' means return the request headers in the response body 'echo_request_headers_as_json' means return the request headers in the response body 'echo_request_body' means return the request body in the response body 'echo_request_uri' means return the request uri in the response body """ def __init__(self, iterable): """ Args: iterable: iterable, a sequence of pairs of (headers, body) """ self._iterable = iterable def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): resp, content = self._iterable.pop(0) if content == 'echo_request_headers': content = headers elif content == 'echo_request_headers_as_json': content = simplejson.dumps(headers) elif content == 'echo_request_body': content = body elif content == 'echo_request_uri': content = uri return httplib2.Response(resp), content def set_user_agent(http, user_agent): """Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if 'user-agent' in headers: headers['user-agent'] = user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http def tunnel_patch(http): """Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if method == 'PATCH': if 'oauth_token' in headers.get('authorization', ''): logging.warning( 'OAuth 1.0 request made with Credentials after tunnel_patch.') headers['x-http-method-override'] = "PATCH" method = 'POST' resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy import httplib2 import logging import oauth2 as oauth import urllib import urlparse from anyjson import simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Error occurred during request.""" pass class MissingParameter(Error): pass class CredentialsInvalidError(Error): pass def _abstract(): raise NotImplementedError('You need to override this function') def _oauth_uri(name, discovery, params): """Look up the OAuth URI from the discovery document and add query parameters based on params. name - The name of the OAuth URI to lookup, one of 'request', 'access', or 'authorize'. discovery - Portion of discovery document the describes the OAuth endpoints. params - Dictionary that is used to form the query parameters for the specified URI. """ if name not in ['request', 'access', 'authorize']: raise KeyError(name) keys = discovery[name]['parameters'].keys() query = {} for key in keys: if key in params: query[key] = params[key] return discovery[name]['url'] + '?' + urllib.urlencode(query) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. """ def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. """ def get(self): """Retrieve credential. Returns: apiclient.oauth.Credentials """ _abstract() def put(self, credentials): """Write a credential. Args: credentials: Credentials, the credentials to store. """ _abstract() class OAuthCredentials(Credentials): """Credentials object for OAuth 1.0a """ def __init__(self, consumer, token, user_agent): """ consumer - An instance of oauth.Consumer. token - An instance of oauth.Token constructed with the access token and secret. user_agent - The HTTP User-Agent to provide for this application. """ self.consumer = consumer self.token = token self.user_agent = user_agent self.store = None # True if the credentials have been revoked self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, "_invalid", False) def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: req = oauth.Request.from_consumer_and_token( self.consumer, self.token, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, self.token) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] # Update the stored credential if it becomes invalid. if response_code == 401: logging.info('Access token no longer valid: %s' % content) self._invalid = True if self.store is not None: self.store(self) raise CredentialsInvalidError("Credentials are no longer valid.") return resp, content http.request = new_request return http class TwoLeggedOAuthCredentials(Credentials): """Two Legged Credentials object for OAuth 1.0a. The Two Legged object is created directly, not from a flow. Once you authorize and httplib2.Http instance you can change the requestor and that change will propogate to the authorized httplib2.Http instance. For example: http = httplib2.Http() http = credentials.authorize(http) credentials.requestor = 'foo@example.info' http.request(...) credentials.requestor = 'bar@example.info' http.request(...) """ def __init__(self, consumer_key, consumer_secret, user_agent): """ Args: consumer_key: string, An OAuth 1.0 consumer key consumer_secret: string, An OAuth 1.0 consumer secret user_agent: string, The HTTP User-Agent to provide for this application. """ self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.user_agent = user_agent self.store = None # email address of the user to act on the behalf of. self._requestor = None @property def invalid(self): """True if the credentials are invalid, such as being revoked. Always returns False for Two Legged Credentials. """ return False def getrequestor(self): return self._requestor def setrequestor(self, email): self._requestor = email requestor = property(getrequestor, setrequestor, None, 'The email address of the user to act on behalf of') def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: # add in xoauth_requestor_id=self._requestor to the uri if self._requestor is None: raise MissingParameter( 'Requestor must be set before using TwoLeggedOAuthCredentials') parsed = list(urlparse.urlparse(uri)) q = parse_qsl(parsed[4]) q.append(('xoauth_requestor_id', self._requestor)) parsed[4] = urllib.urlencode(q) uri = urlparse.urlunparse(parsed) req = oauth.Request.from_consumer_and_token( self.consumer, None, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, None) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] if response_code == 401: logging.info('Access token no longer valid: %s' % content) # Do not store the invalid state of the Credentials because # being 2LO they could be reinstated in the future. raise CredentialsInvalidError("Credentials are invalid.") return resp, content http.request = new_request return http class FlowThreeLegged(Flow): """Does the Three Legged Dance for OAuth 1.0a. """ def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs): """ discovery - Section of the API discovery document that describes the OAuth endpoints. consumer_key - OAuth consumer key consumer_secret - OAuth consumer secret user_agent - The HTTP User-Agent that identifies the application. **kwargs - The keyword arguments are all optional and required parameters for the OAuth calls. """ self.discovery = discovery self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_agent = user_agent self.params = kwargs self.request_token = {} required = {} for uriinfo in discovery.itervalues(): for name, value in uriinfo['parameters'].iteritems(): if value['required'] and not name.startswith('oauth_'): required[name] = 1 for key in required.iterkeys(): if key not in self.params: raise MissingParameter('Required parameter %s not supplied' % key) def step1_get_authorize_url(self, oauth_callback='oob'): """Returns a URI to redirect to the provider. oauth_callback - Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If oauth_callback is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } body = urllib.urlencode({'oauth_callback': oauth_callback}) uri = _oauth_uri('request', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers, body=body) if resp['status'] != '200': logging.error('Failed to retrieve temporary authorization: %s', content) raise RequestError('Invalid response %s.' % resp['status']) self.request_token = dict(parse_qsl(content)) auth_params = copy.copy(self.params) auth_params['oauth_token'] = self.request_token['oauth_token'] return _oauth_uri('authorize', self.discovery, auth_params) def step2_exchange(self, verifier): """Exhanges an authorized request token for OAuthCredentials. Args: verifier: string, dict - either the verifier token, or a dictionary of the query parameters to the callback, which contains the oauth_verifier. Returns: The Credentials object. """ if not (isinstance(verifier, str) or isinstance(verifier, unicode)): verifier = verifier['oauth_verifier'] token = oauth.Token( self.request_token['oauth_token'], self.request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, token) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } uri = _oauth_uri('access', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers) if resp['status'] != '200': logging.error('Failed to retrieve access token: %s', content) raise RequestError('Invalid response %s.' % resp['status']) oauth_params = dict(parse_qsl(content)) token = oauth.Token( oauth_params['oauth_token'], oauth_params['oauth_token_secret']) return OAuthCredentials(consumer, token, self.user_agent)
Python
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import urllib from anyjson import simplejson from errors import HttpError FLAGS = gflags.FLAGS gflags.DEFINE_boolean('dump_request_response', False, 'Dump all http server requests and responses. ' ) def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if FLAGS.dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/1.0' if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if FLAGS.dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): body = simplejson.loads(content) if isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client for discovery based APIs A client library for Google's discovery based APIs. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'build', 'build_from_document' ] import copy import httplib2 import logging import os import random import re import uritemplate import urllib import urlparse import mimeparse import mimetypes try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl from apiclient.anyjson import simplejson from apiclient.errors import HttpError from apiclient.errors import InvalidJsonError from apiclient.errors import MediaUploadSizeError from apiclient.errors import UnacceptableMimeTypeError from apiclient.errors import UnknownApiNameOrVersion from apiclient.errors import UnknownLinkType from apiclient.http import HttpRequest from apiclient.http import MediaFileUpload from apiclient.http import MediaUpload from apiclient.model import JsonModel from apiclient.model import RawModel from apiclient.schema import Schemas from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart URITEMPLATE = re.compile('{[^}]*}') VARNAME = re.compile('[a-zA-Z0-9_-]+') DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/' '{api}/{apiVersion}/rest') DEFAULT_METHOD_DOC = 'A description of how to use this function' # Query parameters that work, but don't appear in discovery STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp', 'userip', 'strict'] RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while' ] def _fix_method_name(name): if name in RESERVED_WORDS: return name + '_' else: return name def _write_headers(self): # Utility no-op method for multipart media handling pass def _add_query_parameter(url, name, value): """Adds a query parameter to a url Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: parsed = list(urlparse.urlparse(url)) q = parse_qsl(parsed[4]) q.append((name, value)) parsed[4] = urllib.urlencode(q) return urlparse.urlunparse(parsed) def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') for c in key: if c.isalnum(): result.append(c) else: result.append('_') return ''.join(result) def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest): """Construct a Resource for interacting with an API. Construct a Resource object for interacting with an API. The serviceName and version are the names from the Discovery service. Args: serviceName: string, name of the service version: string, the version of the service discoveryServiceUrl: string, a URI Template that points to the location of the discovery service. It should have two parameters {api} and {apiVersion} that when filled in produce an absolute URI to the discovery document for that service. developerKey: string, key obtained from https://code.google.com/apis/console model: apiclient.Model, converts to and from the wire format requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP request Returns: A Resource object with methods for interacting with the service. """ params = { 'api': serviceName, 'apiVersion': version } if http is None: http = httplib2.Http() requested_url = uritemplate.expand(discoveryServiceUrl, params) # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment # variable that contains the network address of the client sending the # request. If it exists then add that to the request for the discovery # document to avoid exceeding the quota on discovery requests. if 'REMOTE_ADDR' in os.environ: requested_url = _add_query_parameter(requested_url, 'userIp', os.environ['REMOTE_ADDR']) logging.info('URL being requested: %s' % requested_url) resp, content = http.request(requested_url) if resp.status == 404: raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) if resp.status >= 400: raise HttpError(resp, content, requested_url) try: service = simplejson.loads(content) except ValueError, e: logging.error('Failed to parse as JSON: ' + content) raise InvalidJsonError() filename = os.path.join(os.path.dirname(__file__), 'contrib', serviceName, 'future.json') try: f = file(filename, 'r') future = f.read() f.close() except IOError: future = None return build_from_document(content, discoveryServiceUrl, future, http, developerKey, model, requestBuilder) def build_from_document( service, base, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest): """Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that is it given, as opposed to retrieving one over HTTP. Args: service: string, discovery document base: string, base URI for all HTTP requests, usually the discovery URI future: string, discovery document with future capabilities auth_discovery: dict, information about the authentication the API supports http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. developerKey: string, Key for controlling API usage, generated from the API Console. model: Model class instance that serializes and de-serializes requests and responses. requestBuilder: Takes an http request and packages it up to be executed. Returns: A Resource object with methods for interacting with the service. """ service = simplejson.loads(service) base = urlparse.urljoin(base, service['basePath']) if future: future = simplejson.loads(future) auth_discovery = future.get('auth', {}) else: future = {} auth_discovery = {} schema = Schemas(service) if model is None: features = service.get('features', []) model = JsonModel('dataWrapper' in features) resource = createResource(http, base, model, requestBuilder, developerKey, service, future, schema) def auth_method(): """Discovery information about the authentication the API uses.""" return auth_discovery setattr(resource, 'auth_discovery', auth_method) return resource def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A string representation of 'value' based on the schema_type. """ if schema_type == 'string': if type(value) == type('') or type(value) == type(u''): return value else: return str(value) elif schema_type == 'integer': return str(int(value)) elif schema_type == 'number': return str(float(value)) elif schema_type == 'boolean': return str(bool(value)).lower() else: if type(value) == type('') or type(value) == type(u''): return value else: return str(value) MULTIPLIERS = { "KB": 2 ** 10, "MB": 2 ** 20, "GB": 2 ** 30, "TB": 2 ** 40, } def _media_size_to_long(maxSize): """Convert a string media size, such as 10GB or 3TB into an integer.""" if len(maxSize) < 2: return 0 units = maxSize[-2:].upper() multiplier = MULTIPLIERS.get(units, 0) if multiplier: return int(maxSize[:-2]) * multiplier else: return int(maxSize) def createResource(http, baseUrl, model, requestBuilder, developerKey, resourceDesc, futureDesc, schema): class Resource(object): """A class for interacting with a resource.""" def __init__(self): self._http = http self._baseUrl = baseUrl self._model = model self._developerKey = developerKey self._requestBuilder = requestBuilder def createMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) pathUrl = methodDesc['path'] httpMethod = methodDesc['httpMethod'] methodId = methodDesc['id'] mediaPathUrl = None accept = [] maxSize = 0 if 'mediaUpload' in methodDesc: mediaUpload = methodDesc['mediaUpload'] mediaPathUrl = mediaUpload['protocols']['simple']['path'] mediaResumablePathUrl = mediaUpload['protocols']['resumable']['path'] accept = mediaUpload['accept'] maxSize = _media_size_to_long(mediaUpload.get('maxSize', '')) if 'parameters' not in methodDesc: methodDesc['parameters'] = {} for name in STACK_QUERY_PARAMETERS: methodDesc['parameters'][name] = { 'type': 'string', 'location': 'query' } if httpMethod in ['PUT', 'POST', 'PATCH']: methodDesc['parameters']['body'] = { 'description': 'The request body.', 'type': 'object', 'required': True, } if 'request' in methodDesc: methodDesc['parameters']['body'].update(methodDesc['request']) else: methodDesc['parameters']['body']['type'] = 'object' if 'mediaUpload' in methodDesc: methodDesc['parameters']['media_body'] = { 'description': 'The filename of the media request body.', 'type': 'string', 'required': False, } methodDesc['parameters']['body']['required'] = False argmap = {} # Map from method parameter name to query parameter name required_params = [] # Required parameters repeated_params = [] # Repeated parameters pattern_params = {} # Parameters that must match a regex query_params = [] # Parameters that will be used in the query string path_params = {} # Parameters that will be used in the base URL param_type = {} # The type of the parameter enum_params = {} # Allowable enumeration values for each parameter if 'parameters' in methodDesc: for arg, desc in methodDesc['parameters'].iteritems(): param = key2param(arg) argmap[param] = arg if desc.get('pattern', ''): pattern_params[param] = desc['pattern'] if desc.get('enum', ''): enum_params[param] = desc['enum'] if desc.get('required', False): required_params.append(param) if desc.get('repeated', False): repeated_params.append(param) if desc.get('location') == 'query': query_params.append(param) if desc.get('location') == 'path': path_params[param] = param param_type[param] = desc.get('type', 'string') for match in URITEMPLATE.finditer(pathUrl): for namematch in VARNAME.finditer(match.group(0)): name = key2param(namematch.group(0)) path_params[name] = name if name in query_params: query_params.remove(name) def method(self, **kwargs): for name in kwargs.iterkeys(): if name not in argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) for name in required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in pattern_params.iteritems(): if name in kwargs: if isinstance(kwargs[name], basestring): pvalues = [kwargs[name]] else: pvalues = kwargs[name] for pvalue in pvalues: if re.match(regex, pvalue) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, pvalue, regex)) for name, enums in enum_params.iteritems(): if name in kwargs: if kwargs[name] not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, kwargs[name], str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = param_type.get(key, 'string') # For repeated parameters we cast each member of the list. if key in repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in query_params: actual_query_params[argmap[key]] = cast_value if key in path_params: actual_path_params[argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey model = self._model # If there is no schema for the response then presume a binary blob. if 'response' not in methodDesc: model = RawModel() headers = {} headers, params, query, body = model.request(headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) resumable = None multipart_boundary = '' if media_filename: # Convert a simple filename into a MediaUpload object. if isinstance(media_filename, basestring): (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) media_upload = MediaFileUpload(media_filename, media_mime_type) elif isinstance(media_filename, MediaUpload): media_upload = media_filename else: raise TypeError('media_filename must be str or MediaUpload.') if media_upload.resumable(): resumable = media_upload # Check the maxSize if maxSize > 0 and media_upload.size() > maxSize: raise MediaUploadSizeError("Media larger than: %s" % maxSize) # Use the media path uri for media uploads if media_upload.resumable(): expanded_url = uritemplate.expand(mediaResumablePathUrl, params) else: expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if body is None: # This is a simple media upload headers['content-type'] = media_upload.mimetype() expanded_url = uritemplate.expand(mediaResumablePathUrl, params) if not media_upload.resumable(): body = media_upload.getbytes(0, media_upload.size()) else: # This is a multipart/related upload. msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_upload.mimetype().split('/')) msg['Content-Transfer-Encoding'] = 'binary' if media_upload.resumable(): # This is a multipart resumable upload, where a multipart payload # looks like this: # # --===============1678050750164843052== # Content-Type: application/json # MIME-Version: 1.0 # # {'foo': 'bar'} # --===============1678050750164843052== # Content-Type: image/png # MIME-Version: 1.0 # Content-Transfer-Encoding: binary # # <BINARY STUFF> # --===============1678050750164843052==-- # # In the case of resumable multipart media uploads, the <BINARY # STUFF> is large and will be spread across multiple PUTs. What we # do here is compose the multipart message with a random payload in # place of <BINARY STUFF> and then split the resulting content into # two pieces, text before <BINARY STUFF> and text after <BINARY # STUFF>. The text after <BINARY STUFF> is the multipart boundary. # In apiclient.http the HttpRequest will send the text before # <BINARY STUFF>, then send the actual binary media in chunks, and # then will send the multipart delimeter. payload = hex(random.getrandbits(300)) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() body, _ = body.split(payload) resumable = media_upload else: payload = media_upload.getbytes(0, media_upload.size()) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() multipart_boundary = msgRoot.get_boundary() headers['content-type'] = ('multipart/related; ' 'boundary="%s"') % multipart_boundary logging.info('URL being requested: %s' % url) return self._requestBuilder(self._http, model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId, resumable=resumable) docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] if len(argmap) > 0: docs.append('Args:\n') for arg in argmap.iterkeys(): if arg in STACK_QUERY_PARAMETERS: continue repeated = '' if arg in repeated_params: repeated = ' (repeated)' required = '' if arg in required_params: required = ' (required)' paramdesc = methodDesc['parameters'][argmap[arg]] paramdoc = paramdesc.get('description', 'A parameter') if '$ref' in paramdesc: docs.append( (' %s: object, %s%s%s\n The object takes the' ' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated, schema.prettyPrintByName(paramdesc['$ref']))) else: paramtype = paramdesc.get('type', 'string') docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, repeated)) enum = paramdesc.get('enum', []) enumDesc = paramdesc.get('enumDescriptions', []) if enum and enumDesc: docs.append(' Allowed values\n') for (name, desc) in zip(enum, enumDesc): docs.append(' %s - %s\n' % (name, desc)) if 'response' in methodDesc: docs.append('\nReturns:\n An object of the form\n\n ') docs.append(schema.prettyPrintSchema(methodDesc['response'])) setattr(method, '__doc__', ''.join(docs)) setattr(theclass, methodName, method) def createNextMethodFromFuture(theclass, methodName, methodDesc, futureDesc): """ This is a legacy method, as only Buzz and Moderator use the future.json functionality for generating _next methods. It will be kept around as long as those API versions are around, but no new APIs should depend upon it. """ methodName = _fix_method_name(methodName) methodId = methodDesc['id'] + '.next' def methodNext(self, previous): """Retrieve the next page of results. Takes a single argument, 'body', which is the results from the last call, and returns the next set of items in the collection. Returns: None if there are no more items in the collection. """ if futureDesc['type'] != 'uri': raise UnknownLinkType(futureDesc['type']) try: p = previous for key in futureDesc['location']: p = p[key] url = p except (KeyError, TypeError): return None url = _add_query_parameter(url, 'key', self._developerKey) headers = {} headers, params, query, body = self._model.request(headers, {}, {}, None) logging.info('URL being requested: %s' % url) resp, content = self._http.request(url, method='GET', headers=headers) return self._requestBuilder(self._http, self._model.response, url, method='GET', headers=headers, methodId=methodId) setattr(theclass, methodName, methodNext) def createNextMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) methodId = methodDesc['id'] + '.next' def methodNext(self, previous_request, previous_response): """Retrieves the next page of results. Args: previous_request: The request for the previous page. previous_response: The response from the request for the previous page. Returns: A request object that you can call 'execute()' on to request the next page. Returns None if there are no more items in the collection. """ # Retrieve nextPageToken from previous_response # Use as pageToken in previous_request to create new request. if 'nextPageToken' not in previous_response: return None request = copy.copy(previous_request) pageToken = previous_response['nextPageToken'] parsed = list(urlparse.urlparse(request.uri)) q = parse_qsl(parsed[4]) # Find and remove old 'pageToken' value from URI newq = [(key, value) for (key, value) in q if key != 'pageToken'] newq.append(('pageToken', pageToken)) parsed[4] = urllib.urlencode(newq) uri = urlparse.urlunparse(parsed) request.uri = uri logging.info('URL being requested: %s' % uri) return request setattr(theclass, methodName, methodNext) # Add basic methods to Resource if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if futureDesc: future = futureDesc['methods'].get(methodName, {}) else: future = None createMethod(Resource, methodName, methodDesc, future) # Add in nested resources if 'resources' in resourceDesc: def createResourceMethod(theclass, methodName, methodDesc, futureDesc): methodName = _fix_method_name(methodName) def methodResource(self): return createResource(self._http, self._baseUrl, self._model, self._requestBuilder, self._developerKey, methodDesc, futureDesc, schema) setattr(methodResource, '__doc__', 'A collection resource.') setattr(methodResource, '__is_resource__', True) setattr(theclass, methodName, methodResource) for methodName, methodDesc in resourceDesc['resources'].iteritems(): if futureDesc and 'resources' in futureDesc: future = futureDesc['resources'].get(methodName, {}) else: future = {} createResourceMethod(Resource, methodName, methodDesc, future) # Add <m>_next() methods to Resource if futureDesc and 'methods' in futureDesc: for methodName, methodDesc in futureDesc['methods'].iteritems(): if 'next' in methodDesc and methodName in resourceDesc['methods']: createNextMethodFromFuture(Resource, methodName + '_next', resourceDesc['methods'][methodName], methodDesc['next']) # Add _next() methods # Look for response bodies in schema that contain nextPageToken, and methods # that take a pageToken parameter. if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if 'response' in methodDesc: responseSchema = methodDesc['response'] if '$ref' in responseSchema: responseSchema = schema.get(responseSchema['$ref']) hasNextPageToken = 'nextPageToken' in responseSchema.get('properties', {}) hasPageToken = 'pageToken' in methodDesc.get('parameters', {}) if hasNextPageToken and hasPageToken: createNextMethod(Resource, methodName + '_next', resourceDesc['methods'][methodName], methodName) return Resource()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 1.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle import threading from apiclient.oauth import Storage as BaseStorage class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def get(self): """Retrieve Credential from file. Returns: apiclient.oauth.Credentials """ self._lock.acquire() try: f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() credentials.set_store(self.put) except: credentials = None self._lock.release() return credentials def put(self, credentials): """Write a pickled Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._lock.acquire() f = open(self._filename, 'w') f.write(pickle.dumps(credentials)) f.close() self._lock.release()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value)) class FlowThreeLeggedField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): print "In to_python", value if value is None: return None if isinstance(value, apiclient.oauth.FlowThreeLegged): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value))
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 1.0 Do the OAuth 1.0 Three Legged Dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ["run"] import BaseHTTPServer import gflags import logging import socket import sys from optparse import OptionParser from apiclient.oauth import RequestError try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage): """Core code for a command-line application. Args: flow: Flow, an OAuth 1.0 Flow to step through. storage: Storage, a Storage to store the credential in. Returns: Credentials, the obtained credential. Exceptions: RequestError: if step2 of the flow fails. Args: """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = 'oob' authorize_url = flow.step1_get_authorize_url(oauth_callback) print 'Go to the following link in your browser:' print authorize_url print if FLAGS.auth_local_webserver: print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter --noauth_local_webserver.' print if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'oauth_verifier' in httpd.query_params: code = httpd.query_params['oauth_verifier'] else: accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') code = raw_input('What is the verification code? ').strip() try: credentials = flow.step2_exchange(code) except RequestError: sys.exit('The authentication has failed.') storage.put(credentials) credentials.set_store(storage.put) print "You have successfully authenticated." return credentials
Python
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" if self.resp.get('content-type', '').startswith('application/json'): try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): reason = self.content else: reason = self.resp.reason return reason def __repr__(self): if self.uri: return '<HttpError %s when requesting %s returned "%s">' % ( self.resp.status, self.uri, self._get_reason()) else: return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(Error): """Error occured during resumable upload.""" pass class BatchError(Error): """Error occured during batch operations.""" pass class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from apiclient.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] def _prettyPrintSchema(self, schema, seen=None, dent=0): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" def __init__(self, schema, seen, dent=0): """Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % value, schema.get('description', '')) elif stype == 'integer': value = schema.get('default', 42) self.emitEnd('%d,' % value, schema.get('description', '')) elif stype == 'number': value = schema.get('default', 3.14) self.emitEnd('%f,' % value, schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson
Python
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
Python
#!/usr/bin/env python # Copyright (c) 2010, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # 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 THE COPYRIGHT # OWNER OR CONTRIBUTORS 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. """Module to enforce different constraints on flags. A validator represents an invariant, enforced over a one or more flags. See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual. """ __author__ = 'olexiy@google.com (Olexiy Oryeshko)' class Error(Exception): """Thrown If validator constraint is not satisfied.""" class Validator(object): """Base class for flags validators. Users should NOT overload these classes, and use gflags.Register... methods instead. """ # Used to assign each validator an unique insertion_index validators_count = 0 def __init__(self, checker, message): """Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user """ self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered (CL/18694236) self.insertion_index = Validator.validators_count def Verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._GetInputToCheckerFunction(flag_values) if not self.checker(param): raise Error(self.message) def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded') def PrintFlagsWithValues(self, flag_values): raise NotImplementedError('This method should be overloaded') def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator. """ raise NotImplementedError('This method should be overloaded') class SimpleValidator(Validator): """Validator behind RegisterValidator() method. Validates that a single flag passes its checker function. The checker function takes the flag value and returns True (if value looks fine) or, if flag value is not valid, either returns False or raises an Exception.""" def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name def GetFlagsNames(self): return [self.flag_name] def PrintFlagsWithValues(self, flag_values): return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value) def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag. """ return flag_values[self.flag_name].value class DictionaryValidator(Validator): """Validator behind RegisterDictionaryValidator method. Validates that flag values pass their common checker function. The checker function takes flag values and returns True (if values look fine) or, if values are not valid, either returns False or raises an Exception. """ def __init__(self, flag_names, checker, message): """Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names) def PrintFlagsWithValues(self, flag_values): prefix = 'flags ' flags_with_values = [] for key in self.flag_names: flags_with_values.append('%s=%s' % (key, flag_values[key].value)) return prefix + ', '.join(flags_with_values) def GetFlagsNames(self): return self.flag_names
Python
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. 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. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "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 DAN HAIM OR HIS CONTRIBUTORS 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, 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 DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import base64 import socket import struct import sys if getattr(socket, 'socket', None) is None: raise ImportError('socket.socket missing, proxy support unusable') PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 PROXY_TYPE_HTTP_NO_TUNNEL = 4 _defaultproxy = None _orgsocket = socket.socket class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified")) class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None self.__httptunnel = True def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def sendall(self, content, *args): """ override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed """ if not self.__httptunnel: content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args) def __rewriteproxy(self, header): """ rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. """ host, endpt = None, None hdrs = header.split("\r\n") for hdr in hdrs: if hdr.lower().startswith("host:"): host = hdr elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): endpt = hdr if host and endpt: hdrs.remove(host) hdrs.remove(endpt) host = host.split(" ")[1] endpt = endpt.split(" ") if (self.__proxy[4] != None and self.__proxy[5] != None): hdrs.insert(0, self.__getauthheader()) hdrs.insert(0, "Host: %s" % host) hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) return "\r\n".join(hdrs) def __getauthheader(self): auth = self.__proxy[4] + ":" + self.__proxy[5] return "Proxy-Authorization: Basic " + base64.b64encode(auth) def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1],portnum)) if destpair[1] == 443: self.__negotiatehttp(destpair[0],destpair[1]) else: self.__httptunnel = False elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
Python
""" iri2uri Converts an IRI to a URI. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" __history__ = """ """ import urlparse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF ), (0xE000, 0xF8FF ), (0xF900, 0xFDCF ), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD ), (0x20000, 0x2FFFD ), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD ), (0x50000, 0x5FFFD ), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD ), (0x80000, 0x8FFFD ), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD ), (0xB0000, 0xBFFFD ), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD ), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD ), (0x100000, 0x10FFFD) ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri ,unicode): (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri) authority = authority.encode('idna') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ u"ftp://ftp.is.co.za/rfc/rfc1808.txt", u"http://www.ietf.org/rfc/rfc2396.txt", u"ldap://[2001:db8::7]/c=GB?objectClass?one", u"mailto:John.Doe@example.com", u"news:comp.infosystems.www.servers.unix", u"tel:+1-816-555-1212", u"telnet://192.0.2.16:80/", u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """ Test that the right type of escaping is done for each part of the URI.""" self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}")) self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}")) self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}")) self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))) self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8'))) unittest.main()
Python
from __future__ import generators """ httplib2 A caching http interface that supports ETags and gzip to conserve bandwidth. Requires Python 2.3 or later Changelog: 2007-08-18, Rick: Modified so it's able to use a socks proxy if needed. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)", "James Antill", "Xavier Verges Farrero", "Jonathan Feinberg", "Blair Zajac", "Sam Ruby", "Louis Nyffenegger"] __license__ = "MIT" __version__ = "0.7.2" import re import sys import email import email.Utils import email.Message import email.FeedParser import StringIO import gzip import zlib import httplib import urlparse import base64 import os import copy import calendar import time import random import errno # remove depracated warning in python2.6 try: from hashlib import sha1 as _sha, md5 as _md5 except ImportError: import sha import md5 _sha = sha.new _md5 = md5.new import hmac from gettext import gettext as _ import socket try: from httplib2 import socks except ImportError: socks = None # Build the appropriate socket wrapper for ssl try: import ssl # python 2.6 ssl_SSLError = ssl.SSLError def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if disable_validation: cert_reqs = ssl.CERT_NONE else: cert_reqs = ssl.CERT_REQUIRED # We should be specifying SSL version 3 or TLS v1, but the ssl module # doesn't expose the necessary knobs. So we need to go with the default # of SSLv23. return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs) except (AttributeError, ImportError): ssl_SSLError = None def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if not disable_validation: raise CertificateValidationUnsupported( "SSL certificate validation is not supported without " "the ssl module installed. To avoid this error, install " "the ssl module, or explicity disable validation.") ssl_sock = socket.ssl(sock, key_file, cert_file) return httplib.FakeSocket(sock, ssl_sock) if sys.version_info >= (2,3): from iri2uri import iri2uri else: def iri2uri(uri): return uri def has_timeout(timeout): # python 2.6 if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'): return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT) return (timeout is not None) __all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error', 'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent', 'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError', 'debuglevel', 'ProxiesUnavailableError'] # The httplib debug level, set to a non-zero value to get debug output debuglevel = 0 # Python 2.3 support if sys.version_info < (2,4): def sorted(seq): seq.sort() return seq # Python 2.3 support def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items() if not hasattr(httplib.HTTPResponse, 'getheaders'): httplib.HTTPResponse.getheaders = HTTPResponse__getheaders # All exceptions raised here derive from HttpLib2Error class HttpLib2Error(Exception): pass # Some exceptions can be caught and optionally # be turned back into responses. class HttpLib2ErrorWithResponse(HttpLib2Error): def __init__(self, desc, response, content): self.response = response self.content = content HttpLib2Error.__init__(self, desc) class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass class RedirectLimit(HttpLib2ErrorWithResponse): pass class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class MalformedHeader(HttpLib2Error): pass class RelativeURIError(HttpLib2Error): pass class ServerNotFoundError(HttpLib2Error): pass class ProxiesUnavailableError(HttpLib2Error): pass class CertificateValidationUnsupported(HttpLib2Error): pass class SSLHandshakeError(HttpLib2Error): pass class NotSupportedOnThisPlatform(HttpLib2Error): pass class CertificateHostnameMismatch(SSLHandshakeError): def __init__(self, desc, host, cert): HttpLib2Error.__init__(self, desc) self.host = host self.cert = cert # Open Items: # ----------- # Proxy support # Are we removing the cached content too soon on PUT (only delete on 200 Maybe?) # Pluggable cache storage (supports storing the cache in # flat files by default. We need a plug-in architecture # that can support Berkeley DB and Squid) # == Known Issues == # Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator. # Does not handle Cache-Control: max-stale # Does not use Age: headers when calculating cache freshness. # The number of redirections to follow before giving up. # Note that only GET redirects are automatically followed. # Will also honor 301 requests by saving that info and never # requesting that URI again. DEFAULT_MAX_REDIRECTS = 5 # Default CA certificates file bundled with httplib2. CA_CERTS = os.path.join( os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt") # Which headers are hop-by-hop headers by default HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'] def _get_end2end_headers(response): hopbyhop = list(HOP_BY_HOP) hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')]) return [header for header in response.keys() if header not in hopbyhop] URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?") def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8]) def urlnorm(uri): (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri) authority = authority.lower() scheme = scheme.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path scheme = scheme.lower() defrag_uri = scheme + "://" + authority + request_uri return scheme, authority, request_uri, defrag_uri # Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/) re_url_scheme = re.compile(r'^\w+://') re_slash = re.compile(r'[?/:|]+') def safename(filename): """Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in. """ try: if re_url_scheme.match(filename): if isinstance(filename,str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename,unicode): filename=filename.encode('utf-8') filemd5 = _md5(filename).hexdigest() filename = re_url_scheme.sub("", filename) filename = re_slash.sub(",", filename) # limit length of filename if len(filename)>200: filename=filename[:200] return ",".join((filename, filemd5)) NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+') def _normalize_headers(headers): return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()]) def _parse_cache_control(headers): retval = {} if headers.has_key('cache-control'): parts = headers['cache-control'].split(',') parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")] parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")] retval = dict(parts_with_args + parts_wo_args) return retval # Whether to use a strict mode to parse WWW-Authenticate headers # Might lead to bad results in case of ill-formed header value, # so disabled by default, falling back to relaxed parsing. # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space # Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both: # \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"? WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$") WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$") UNQUOTE_PAIRS = re.compile(r'\\(.)') def _parse_www_authenticate(headers, headername='www-authenticate'): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headers.has_key(headername): try: authenticate = headers[headername].strip() www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED while authenticate: # Break off the scheme at the beginning of the line if headername == 'authentication-info': (auth_scheme, the_rest) = ('digest', authenticate) else: (auth_scheme, the_rest) = authenticate.split(" ", 1) # Now loop over all the key value pairs that come after the scheme, # being careful not to roll into the next scheme match = www_auth.search(the_rest) auth_params = {} while match: if match and len(match.groups()) == 3: (key, value, the_rest) = match.groups() auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')]) match = www_auth.search(the_rest) retval[auth_scheme.lower()] = auth_params authenticate = the_rest.strip() except ValueError: raise MalformedHeader("WWW-Authenticate") return retval def _entry_disposition(response_headers, request_headers): """Determine freshness from the Date, Expires and Cache-Control headers. We don't handle the following: 1. Cache-Control: max-stale 2. Age: headers are not used in the calculations. Not that this algorithm is simpler than you might think because we are operating as a private (non-shared) cache. This lets us ignore 's-maxage'. We can also ignore 'proxy-invalidate' since we aren't a proxy. We will never return a stale document as fresh as a design decision, and thus the non-implementation of 'max-stale'. This also lets us safely ignore 'must-revalidate' since we operate as if every server has sent 'must-revalidate'. Since we are private we get to ignore both 'public' and 'private' parameters. We also ignore 'no-transform' since we don't do any transformations. The 'no-store' parameter is handled at a higher level. So the only Cache-Control parameters we look at are: no-cache only-if-cached max-age min-fresh """ retval = "STALE" cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1: retval = "TRANSPARENT" if 'cache-control' not in request_headers: request_headers['cache-control'] = 'no-cache' elif cc.has_key('no-cache'): retval = "TRANSPARENT" elif cc_response.has_key('no-cache'): retval = "STALE" elif cc.has_key('only-if-cached'): retval = "FRESH" elif response_headers.has_key('date'): date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date'])) now = time.time() current_age = max(0, now - date) if cc_response.has_key('max-age'): try: freshness_lifetime = int(cc_response['max-age']) except ValueError: freshness_lifetime = 0 elif response_headers.has_key('expires'): expires = email.Utils.parsedate_tz(response_headers['expires']) if None == expires: freshness_lifetime = 0 else: freshness_lifetime = max(0, calendar.timegm(expires) - date) else: freshness_lifetime = 0 if cc.has_key('max-age'): try: freshness_lifetime = int(cc['max-age']) except ValueError: freshness_lifetime = 0 if cc.has_key('min-fresh'): try: min_fresh = int(cc['min-fresh']) except ValueError: min_fresh = 0 current_age += min_fresh if freshness_lifetime > current_age: retval = "FRESH" return retval def _decompressContent(response, new_content): content = new_content try: encoding = response.get('content-encoding', None) if encoding in ['gzip', 'deflate']: if encoding == 'gzip': content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read() if encoding == 'deflate': content = zlib.decompress(content) response['content-length'] = str(len(content)) # Record the historical presence of the encoding in a way the won't interfere. response['-content-encoding'] = response['content-encoding'] del response['content-encoding'] except IOError: content = "" raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content) return content def _updateCache(request_headers, response_headers, content, cache, cachekey): if cachekey: cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if cc.has_key('no-store') or cc_response.has_key('no-store'): cache.delete(cachekey) else: info = email.Message.Message() for key, value in response_headers.iteritems(): if key not in ['status','content-encoding','transfer-encoding']: info[key] = value # Add annotations to the cache to indicate what headers # are variant for this request. vary = response_headers.get('vary', None) if vary: vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header try: info[key] = request_headers[header] except KeyError: pass status = response_headers.status if status == 304: status = 200 status_header = 'status: %d\r\n' % status header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = "".join([status_header, header_str, content]) cache.set(cachekey, text) def _cnonce(): dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip() # For credentials we need two things, first # a pool of credential to try (not necesarily tied to BAsic, Digest, etc.) # Then we also need a list of URIs that have already demanded authentication # That list is tricky since sub-URIs can take the same auth, or the # auth scheme may change as you descend the tree. # So we also need each Auth instance to be able to tell us # how close to the 'top' it is. class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host self.credentials = credentials self.http = http def depth(self, request_uri): (scheme, authority, path, query, fragment) = parse_uri(request_uri) return request_uri[len(self.path):].count("/") def inscope(self, host, request_uri): # XXX Should we normalize the request_uri? (scheme, authority, path, query, fragment) = parse_uri(request_uri) return (host == self.host) and path.startswith(self.path) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header. Over-rise this in sub-classes.""" pass def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip() class DigestAuthentication(Authentication): """Only do qop='auth' and MD5, since that is all Apache currently implements""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['digest'] qop = self.challenge.get('qop', 'auth') self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None if self.challenge['qop'] is None: raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop)) self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper() if self.challenge['algorithm'] != 'MD5': raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]]) self.challenge['nc'] = 1 def request(self, method, request_uri, headers, content, cnonce = None): """Modify the request headers""" H = lambda x: _md5(x).hexdigest() KD = lambda s, d: H("%s:%s" % (s, d)) A2 = "".join([method, ":", request_uri]) self.challenge['cnonce'] = cnonce or _cnonce() request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'], '%08x' % self.challenge['nc'], self.challenge['cnonce'], self.challenge['qop'], H(A2) )) headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['nonce'], request_uri, self.challenge['algorithm'], request_digest, self.challenge['qop'], self.challenge['nc'], self.challenge['cnonce'], ) if self.challenge.get('opaque'): headers['authorization'] += ', opaque="%s"' % self.challenge['opaque'] self.challenge['nc'] += 1 def response(self, response, content): if not response.has_key('authentication-info'): challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {}) if 'true' == challenge.get('stale'): self.challenge['nonce'] = challenge['nonce'] self.challenge['nc'] = 1 return True else: updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {}) if updated_challenge.has_key('nextnonce'): self.challenge['nonce'] = updated_challenge['nextnonce'] self.challenge['nc'] = 1 return False class HmacDigestAuthentication(Authentication): """Adapted from Robert Sayre's code and DigestAuthentication above.""" __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['hmacdigest'] # TODO: self.challenge['domain'] self.challenge['reason'] = self.challenge.get('reason', 'unauthorized') if self.challenge['reason'] not in ['unauthorized', 'integrity']: self.challenge['reason'] = 'unauthorized' self.challenge['salt'] = self.challenge.get('salt', '') if not self.challenge.get('snonce'): raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty.")) self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1') if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1') if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm'])) if self.challenge['algorithm'] == 'HMAC-MD5': self.hashmod = _md5 else: self.hashmod = _sha if self.challenge['pw-algorithm'] == 'MD5': self.pwhashmod = _md5 else: self.pwhashmod = _sha self.key = "".join([self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(), ":", self.challenge['realm'] ]) self.key = self.pwhashmod.new(self.key).hexdigest().lower() def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist, ) def response(self, response, content): challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {}) if challenge.get('reason') in ['integrity', 'stale']: return True return False class WsseAuthentication(Authentication): """This is thinly tested and should not be relied upon. At this time there isn't any third party server to test against. Blogger and TypePad implemented this algorithm at one point but Blogger has since switched to Basic over HTTPS and TypePad has implemented it wrong, by never issuing a 401 challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'WSSE profile="UsernameToken"' iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( self.credentials[0], password_digest, cnonce, iso_now) class GoogleLoginAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): from urllib import urlencode Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') service = challenge['googlelogin'].get('service', 'xapi') # Bloggger actually returns the service in the challenge # For the rest we guess based on the URI if service == 'xapi' and request_uri.find("calendar") > 0: service = "cl" # No point in guessing Base or Spreadsheet #elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent']) resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'}) lines = content.split('\n') d = dict([tuple(line.split("=", 1)) for line in lines if line]) if resp.status == 403: self.Auth = "" else: self.Auth = d['Auth'] def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'GoogleLogin Auth=' + self.Auth AUTH_SCHEME_CLASSES = { "basic": BasicAuthentication, "wsse": WsseAuthentication, "digest": DigestAuthentication, "hmacdigest": HmacDigestAuthentication, "googlelogin": GoogleLoginAuthentication } AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"] class FileCache(object): """Uses a local directory as a store for cached files. Not really safe to use if multiple threads or processes are going to be running on the same cache. """ def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache): os.makedirs(self.cache) def get(self, key): retval = None cacheFullPath = os.path.join(self.cache, self.safe(key)) try: f = file(cacheFullPath, "rb") retval = f.read() f.close() except IOError: pass return retval def set(self, key, value): cacheFullPath = os.path.join(self.cache, self.safe(key)) f = file(cacheFullPath, "wb") f.write(value) f.close() def delete(self, key): cacheFullPath = os.path.join(self.cache, self.safe(key)) if os.path.exists(cacheFullPath): os.remove(cacheFullPath) class Credentials(object): def __init__(self): self.credentials = [] def add(self, name, password, domain=""): self.credentials.append((domain.lower(), name, password)) def clear(self): self.credentials = [] def iter(self, domain): for (cdomain, name, password) in self.credentials: if cdomain == "" or domain == cdomain: yield (name, password) class KeyCerts(Credentials): """Identical to Credentials except that name/password are mapped to key/cert.""" pass class ProxyInfo(object): """Collect information required to use a proxy.""" def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None): """The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000) """ self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass def astuple(self): return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass) def isgood(self): return (self.proxy_host != None) and (self.proxy_port != None) class HTTPConnectionWithTimeout(httplib.HTTPConnection): """ HTTPConnection subclass that supports timeouts All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None): httplib.HTTPConnection.__init__(self, host, port, strict) self.timeout = timeout self.proxy_info = proxy_info def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( 'Proxy support missing but proxy use was requested!') msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg class HTTPSConnectionWithTimeout(httplib.HTTPSConnection): """ This class allows communication via SSL. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict) self.timeout = timeout self.proxy_info = proxy_info if ca_certs is None: ca_certs = CA_CERTS self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # The following two methods were adapted from https_wrapper.py, released # with the Google Appengine SDK at # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py # under the following license: # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def _GetValidHostsForCert(self, cert): """Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs. """ if 'subjectAltName' in cert: return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns'] else: return [x[0][1] for x in cert['subject'] if x[0][0].lower() == 'commonname'] def _ValidateCertificateHostname(self, cert, hostname): """Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate. """ hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace('.', '\.').replace('*', '[^.]*') if re.search('^%s$' % (host_re,), hostname, re.I): return True return False def connect(self): "Connect to a host on a given (SSL) port." msg = "getaddrinfo returns an empty list" for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( self.host, self.port, 0, socket.SOCK_STREAM): try: if self.proxy_info and self.proxy_info.isgood(): sock = socks.socksocket(family, socktype, proto) sock.setproxy(*self.proxy_info.astuple()) else: sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if has_timeout(self.timeout): sock.settimeout(self.timeout) sock.connect((self.host, self.port)) self.sock =_ssl_wrap_socket( sock, self.key_file, self.cert_file, self.disable_ssl_certificate_validation, self.ca_certs) if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) if not self.disable_ssl_certificate_validation: cert = self.sock.getpeercert() hostname = self.host.split(':', 0)[0] if not self._ValidateCertificateHostname(cert, hostname): raise CertificateHostnameMismatch( 'Server presented certificate that does not match ' 'host %s: %s' % (hostname, cert), hostname, cert) except ssl_SSLError, e: if sock: sock.close() if self.sock: self.sock.close() self.sock = None # Unfortunately the ssl module doesn't seem to provide any way # to get at more detailed error information, in particular # whether the error is due to certificate validation or # something else (such as SSL protocol mismatch). if e.errno == ssl.SSL_ERROR_SSL: raise SSLHandshakeError(e) else: raise except (socket.timeout, socket.gaierror): raise except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg SCHEME_TO_CONNECTION = { 'http': HTTPConnectionWithTimeout, 'https': HTTPSConnectionWithTimeout } # Use a different connection object for Google App Engine try: from google.appengine.api import apiproxy_stub_map if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None: raise ImportError # Bail out; we're not actually running on App Engine. from google.appengine.api.urlfetch import fetch from google.appengine.api.urlfetch import InvalidURLError from google.appengine.api.urlfetch import DownloadError from google.appengine.api.urlfetch import ResponseTooLargeError from google.appengine.api.urlfetch import SSLCertificateError class ResponseDict(dict): """Is a dictionary that also has a read() method, so that it can pass itself off as an httlib.HTTPResponse().""" def read(self): pass class AppEngineHttpConnection(object): """Emulates an httplib.HTTPConnection object, but actually uses the Google App Engine urlfetch library. This allows the timeout to be properly used on Google App Engine, and avoids using httplib, which on Google App Engine is just another wrapper around urlfetch. """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_certificate_validation=False): self.host = host self.port = port self.timeout = timeout if key_file or cert_file or proxy_info or ca_certs: raise NotSupportedOnThisPlatform() self.response = None self.scheme = 'http' self.validate_certificate = not disable_certificate_validation self.sock = True def request(self, method, url, body, headers): # Calculate the absolute URI, which fetch requires netloc = self.host if self.port: netloc = '%s:%s' % (self.host, self.port) absolute_uri = '%s://%s%s' % (self.scheme, netloc, url) try: response = fetch(absolute_uri, payload=body, method=method, headers=headers, allow_truncated=False, follow_redirects=False, deadline=self.timeout, validate_certificate=self.validate_certificate) self.response = ResponseDict(response.headers) self.response['status'] = str(response.status_code) self.response.status = response.status_code setattr(self.response, 'read', lambda : response.content) # Make sure the exceptions raised match the exceptions expected. except InvalidURLError: raise socket.gaierror('') except (DownloadError, ResponseTooLargeError, SSLCertificateError): raise httplib.HTTPException() def getresponse(self): if self.response: return self.response else: raise httplib.HTTPException() def set_debuglevel(self, level): pass def connect(self): pass def close(self): pass class AppEngineHttpsConnection(AppEngineHttpConnection): """Same as AppEngineHttpConnection, but for HTTPS URIs.""" def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None): AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file, strict, timeout, proxy_info) self.scheme = 'https' # Update the connection classes to use the Googel App Engine specific ones. SCHEME_TO_CONNECTION = { 'http': AppEngineHttpConnection, 'https': AppEngineHttpsConnection } except ImportError: pass class Http(object): """An HTTP client that handles: - all methods - caching - ETags - compression, - HTTPS - Basic - Digest - WSSE and more. """ def __init__(self, cache=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): """ The value of proxy_info is a ProxyInfo instance. If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout ca_certs is the path of a file containing root CA certificates for SSL server certificate validation. By default, a CA cert file bundled with httplib2 is used. If disable_ssl_certificate_validation is true, SSL cert validation will not be performed. """ self.proxy_info = proxy_info self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # Map domain name to an httplib connection self.connections = {} # The location of the cache, for now a directory # where cached responses are held. if cache and isinstance(cache, basestring): self.cache = FileCache(cache) else: self.cache = cache # Name/password self.credentials = Credentials() # Key/cert self.certificates = KeyCerts() # authorization objects self.authorizations = [] # If set to False then no redirects are followed, even safe ones. self.follow_redirects = True # Which HTTP methods do we apply optimistic concurrency to, i.e. # which methods get an "if-match:" etag header added to them. self.optimistic_concurrency_methods = ["PUT", "PATCH"] # If 'follow_redirects' is True, and this is set to True then # all redirecs are followed, including unsafe ones. self.follow_all_redirects = False self.ignore_etag = False self.force_exception_to_status_code = False self.timeout = timeout def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, 'www-authenticate') for cred in self.credentials.iter(host): for scheme in AUTH_SCHEME_ORDER: if challenges.has_key(scheme): yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self) def add_credentials(self, name, password, domain=""): """Add a name and password that will be used any time a request requires authentication.""" self.credentials.add(name, password, domain) def add_certificate(self, key, cert, domain): """Add a key and cert that will be used any time a request requires authentication.""" self.certificates.add(key, cert, domain) def clear_credentials(self): """Remove all the names and passwords that are used for authentication""" self.credentials.clear() self.authorizations = [] def _conn_request(self, conn, request_uri, method, body, headers): for i in range(2): try: if conn.sock is None: conn.connect() conn.request(method, request_uri, body, headers) except socket.timeout: raise except socket.gaierror: conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except ssl_SSLError: conn.close() raise except socket.error, e: err = 0 if hasattr(e, 'args'): err = getattr(e, 'args')[0] else: err = e.errno if err == errno.ECONNREFUSED: # Connection refused raise except httplib.HTTPException: # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. if conn.sock is None: if i == 0: conn.close() conn.connect() continue else: conn.close() raise if i == 0: conn.close() conn.connect() continue try: response = conn.getresponse() except (socket.error, httplib.HTTPException): if i == 0: conn.close() conn.connect() continue else: raise else: content = "" if method == "HEAD": response.close() else: content = response.read() response = Response(response) if method != "HEAD": content = _decompressContent(response, content) break return (response, content) def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey): """Do the actual request using the connection object and also follow one level of redirects if necessary""" auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)] auth = auths and sorted(auths)[0][1] or None if auth: auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers) if auth: if auth.response(response, body): auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers ) response._stale_digest = 1 if response.status == 401: for authorization in self._auth_from_challenge(host, request_uri, headers, response, content): authorization.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers, ) if response.status != 401: self.authorizations.append(authorization) authorization.response(response, body) break if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303): if self.follow_redirects and response.status in [300, 301, 302, 303, 307]: # Pick out the location header and basically start from the beginning # remembering first to strip the ETag header and decrement our 'depth' if redirections: if not response.has_key('location') and response.status != 300: raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content) # Fix-up relative redirects (which violate an RFC 2616 MUST) if response.has_key('location'): location = response['location'] (scheme, authority, path, query, fragment) = parse_uri(location) if authority == None: response['location'] = urlparse.urljoin(absolute_uri, location) if response.status == 301 and method in ["GET", "HEAD"]: response['-x-permanent-redirect-url'] = response['location'] if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) if headers.has_key('if-none-match'): del headers['if-none-match'] if headers.has_key('if-modified-since'): del headers['if-modified-since'] if response.has_key('location'): location = response['location'] old_response = copy.deepcopy(response) if not old_response.has_key('content-location'): old_response['content-location'] = absolute_uri redirect_method = method if response.status in [302, 303]: redirect_method = "GET" body = None (response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1) response.previous = old_response else: raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content) elif response.status in [200, 203] and method in ["GET", "HEAD"]: # Don't cache 206's since we aren't going to handle byte range requests if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) return (response, content) def _normalize_headers(self, headers): return _normalize_headers(headers) # Need to catch and rebrand some exceptions # Then need to optionally turn all exceptions into status codes # including all socket.* and httplib.* exceptions. def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The 'body' is the entity body to be sent with the request. It is a string object. Any extra headers that are to be sent with the request should be provided in the 'headers' dictionary. The maximum number of redirect to follow before raising an exception is 'redirections. The default is 5. The return value is a tuple of (response, content), the first being and instance of the 'Response' class, the second being a string that contains the response entity body. """ try: if headers is None: headers = {} else: headers = self._normalize_headers(headers) if not headers.has_key('user-agent'): headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__ uri = iri2uri(uri) (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) domain_port = authority.split(":")[0:2] if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http': scheme = 'https' authority = domain_port[0] conn_key = scheme+":"+authority if conn_key in self.connections: conn = self.connections[conn_key] else: if not connection_type: connection_type = SCHEME_TO_CONNECTION[scheme] certs = list(self.certificates.iter(authority)) if issubclass(connection_type, HTTPSConnectionWithTimeout): if certs: conn = self.connections[conn_key] = connection_type( authority, key_file=certs[0][0], cert_file=certs[0][1], timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info) conn.set_debuglevel(debuglevel) if 'range' not in headers and 'accept-encoding' not in headers: headers['accept-encoding'] = 'gzip, deflate' info = email.Message.Message() cached_value = None if self.cache: cachekey = defrag_uri cached_value = self.cache.get(cachekey) if cached_value: # info = email.message_from_string(cached_value) # # Need to replace the line above with the kludge below # to fix the non-existent bug not fixed in this # bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html try: info, content = cached_value.split('\r\n\r\n', 1) feedparser = email.FeedParser.FeedParser() feedparser.feed(info) info = feedparser.close() feedparser._parse = None except IndexError: self.cache.delete(cachekey) cachekey = None cached_value = None else: cachekey = None if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers: # http://www.w3.org/1999/04/Editing/ headers['if-match'] = info['etag'] if method not in ["GET", "HEAD"] and self.cache and cachekey: # RFC 2616 Section 13.10 self.cache.delete(cachekey) # Check the vary header in the cache to see if this request # matches what varies in the cache. if method in ['GET', 'HEAD'] and 'vary' in info: vary = info['vary'] vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header value = info[key] if headers.get(header, None) != value: cached_value = None break if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers: if info.has_key('-x-permanent-redirect-url'): # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "") (response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1) response.previous = Response(info) response.previous.fromcache = True else: # Determine our course of action: # Is the cached entry fresh or stale? # Has the client requested a non-cached response? # # There seems to be three possible answers: # 1. [FRESH] Return the cache entry w/o doing a GET # 2. [STALE] Do the GET (but add in cache validators if available) # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request entry_disposition = _entry_disposition(info, headers) if entry_disposition == "FRESH": if not cached_value: info['status'] = '504' content = "" response = Response(info) if cached_value: response.fromcache = True return (response, content) if entry_disposition == "STALE": if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers: headers['if-none-match'] = info['etag'] if info.has_key('last-modified') and not 'last-modified' in headers: headers['if-modified-since'] = info['last-modified'] elif entry_disposition == "TRANSPARENT": pass (response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) if response.status == 304 and method == "GET": # Rewrite the cache entry with the new end-to-end headers # Take all headers that are in response # and overwrite their values in info. # unless they are hop-by-hop, or are listed in the connection header. for key in _get_end2end_headers(response): info[key] = response[key] merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) response = merged_response response.status = 200 response.fromcache = True elif response.status == 200: content = new_content else: self.cache.delete(cachekey) content = new_content else: cc = _parse_cache_control(headers) if cc.has_key('only-if-cached'): info['status'] = '504' response = Response(info) content = "" else: (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) except Exception, e: if self.force_exception_to_status_code: if isinstance(e, HttpLib2ErrorWithResponse): response = e.response content = e.content response.status = 500 response.reason = str(e) elif isinstance(e, socket.timeout): content = "Request Timeout" response = Response( { "content-type": "text/plain", "status": "408", "content-length": len(content) }) response.reason = "Request Timeout" else: content = str(e) response = Response( { "content-type": "text/plain", "status": "400", "content-length": len(content) }) response.reason = "Bad Request" else: raise return (response, content) class Response(dict): """An object more like email.Message than httplib.HTTPResponse.""" """Is this response from our local cache""" fromcache = False """HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """ version = 11 "Status code returned by server. " status = 200 """Reason phrase returned by server.""" reason = "Ok" previous = None def __init__(self, info): # info is either an email.Message or # an httplib.HTTPResponse object. if isinstance(info, httplib.HTTPResponse): for key, value in info.getheaders(): self[key.lower()] = value self.status = info.status self['status'] = str(self.status) self.reason = info.reason self.version = info.version elif isinstance(info, email.Message.Message): for key, value in info.items(): self[key] = value self.status = int(self['status']) else: for key, value in info.iteritems(): self[key] = value self.status = int(self.get('status', self.status)) def __getattr__(self, name): if name == 'dict': return self else: raise AttributeError, name
Python
#!/usr/bin/env python # # Copyright (c) 2002, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # 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 THE COPYRIGHT # OWNER OR CONTRIBUTORS 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: Chad Lester # Design and style contributions by: # Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, # Eric Veach, Laurence Gonsalves, Matthew Springer # Code reorganized a bit by Craig Silverstein """This module is used to define and parse command line flags. This module defines a *distributed* flag-definition policy: rather than an application having to define all flags in or near main(), each python module defines flags that are useful to it. When one python module imports another, it gains access to the other's flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.) Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it's seen on the command line. IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a 'FlagValues' object (typically the global FlagValues FLAGS, defined here). The 'FlagValues' object can scan the command line arguments and pass flag arguments to the corresponding 'Flag' objects for value-checking and type conversion. The converted flag values are available as attributes of the 'FlagValues' object. Code can access the flag through a FlagValues object, for instance gflags.FLAGS.myflag. Typically, the __main__ module passes the command line arguments to gflags.FLAGS for parsing. At bottom, this module calls getopt(), so getopt functionality is supported, including short- and long-style flags, and the use of -- to terminate flags. Methods defined by the flag module will throw 'FlagsError' exceptions. The exception argument will be a human-readable string. FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag. DEFINE_string: takes any input, and interprets it as a string. DEFINE_bool or DEFINE_boolean: typically does not take an argument: say --myflag to set FLAGS.myflag to true, or --nomyflag to set FLAGS.myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=1 or --myflag=false or --myflag=f or --myflag=0 DEFINE_float: takes an input and interprets it as a floating point number. Takes optional args lower_bound and upper_bound; if the number specified on the command line is out of range, it will raise a FlagError. DEFINE_integer: takes an input and interprets it as an integer. Takes optional args lower_bound and upper_bound as for floats. DEFINE_enum: takes a list of strings which represents legal values. If the command-line value is not in this list, raise a flag error. Otherwise, assign to FLAGS.flag as a string. DEFINE_list: Takes a comma-separated list of strings on the commandline. Stores them in a python list object. DEFINE_spaceseplist: Takes a space-separated list of strings on the commandline. Stores them in a python list object. Example: --myspacesepflag "foo bar baz" DEFINE_multistring: The same as DEFINE_string, except the flag can be specified more than once on the commandline. The result is a python list object (list of strings), even if the flag is only on the command line once. DEFINE_multi_int: The same as DEFINE_integer, except the flag can be specified more than once on the commandline. The result is a python list object (list of ints), even if the flag is only on the command line once. SPECIAL FLAGS: There are a few flags that have special meaning: --help prints a list of all the flags in a human-readable fashion --helpshort prints a list of all key flags (see below). --helpxml prints a list of all flags, in XML format. DO NOT parse the output of --help and --helpshort. Instead, parse the output of --helpxml. For more info, see "OUTPUT FOR --helpxml" below. --flagfile=foo read flags from file foo. --undefok=f1,f2 ignore unrecognized option errors for f1,f2. For boolean flags, you should use --undefok=boolflag, and --boolflag and --noboolflag will be accepted. Do not use --undefok=noboolflag. -- as in getopt(), terminates flag-processing FLAGS VALIDATORS: If your program: - requires flag X to be specified - needs flag Y to match a regular expression - or requires any more general constraint to be satisfied then validators are for you! Each validator represents a constraint over one flag, which is enforced starting from the initial parsing of the flags and until the program terminates. Also, lower_bound and upper_bound for numerical flags are enforced using flag validators. Howto: If you want to enforce a constraint over one flag, use gflags.RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS) After flag values are initially parsed, and after any change to the specified flag, method checker(flag_value) will be executed. If constraint is not satisfied, an IllegalFlagValue exception will be raised. See RegisterValidator's docstring for a detailed explanation on how to construct your own checker. EXAMPLE USAGE: FLAGS = gflags.FLAGS gflags.DEFINE_integer('my_version', 0, 'Version number.') gflags.DEFINE_string('filename', None, 'Input file name', short_name='f') gflags.RegisterValidator('my_version', lambda value: value % 2 == 0, message='--my_version must be divisible by 2') gflags.MarkFlagAsRequired('filename') NOTE ON --flagfile: Flags may be loaded from text files in addition to being specified on the commandline. Any flags you don't feel like typing, throw them in a file, one flag per line, for instance: --myflag=myvalue --nomyboolean_flag You then specify your file with the special flag '--flagfile=somefile'. You CAN recursively nest flagfile= tokens OR use multiple files on the command line. Lines beginning with a single hash '#' or a double slash '//' are comments in your flagfile. Any flagfile=<file> will be interpreted as having a relative path from the current working directory rather than from the place the file was included from: myPythonScript.py --flagfile=config/somefile.cfg If somefile.cfg includes further --flagfile= directives, these will be referenced relative to the original CWD, not from the directory the including flagfile was found in! The caveat applies to people who are including a series of nested files in a different dir than they are executing out of. Relative path names are always from CWD, not from the directory of the parent include flagfile. We do now support '~' expanded directory names. Absolute path names ALWAYS work! EXAMPLE USAGE: FLAGS = gflags.FLAGS # Flag names are globally defined! So in general, we need to be # careful to pick names that are unlikely to be used by other libraries. # If there is a conflict, we'll get an error at import time. gflags.DEFINE_string('name', 'Mr. President', 'your name') gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) gflags.DEFINE_boolean('debug', False, 'produces debugging output') gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') def main(argv): try: argv = FLAGS(argv) # parse flags except gflags.FlagsError, e: print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if FLAGS.debug: print 'non-flag arguments:', argv print 'Happy Birthday', FLAGS.name if FLAGS.age is not None: print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender) if __name__ == '__main__': main(sys.argv) KEY FLAGS: As we already explained, each module gains access to all flags defined by all the other modules it transitively imports. In the case of non-trivial scripts, this means a lot of flags ... For documentation purposes, it is good to identify the flags that are key (i.e., really important) to a module. Clearly, the concept of "key flag" is a subjective one. When trying to determine whether a flag is key to a module or not, assume that you are trying to explain your module to a potential user: which flags would you really like to mention first? We'll describe shortly how to declare which flags are key to a module. For the moment, assume we know the set of key flags for each module. Then, if you use the app.py module, you can use the --helpshort flag to print only the help for the flags that are key to the main module, in a human-readable format. NOTE: If you need to parse the flag help, do NOT use the output of --help / --helpshort. That output is meant for human consumption, and may be changed in the future. Instead, use --helpxml; flags that are key for the main module are marked there with a <key>yes</key> element. The set of key flags for a module M is composed of: 1. Flags defined by module M by calling a DEFINE_* function. 2. Flags that module M explictly declares as key by using the function DECLARE_key_flag(<flag_name>) 3. Key flags of other modules that M specifies by using the function ADOPT_module_key_flags(<other_module>) This is a "bulk" declaration of key flags: each flag that is key for <other_module> becomes key for the current module too. Notice that if you do not use the functions described at points 2 and 3 above, then --helpshort prints information only about the flags defined by the main module of our script. In many cases, this behavior is good enough. But if you move part of the main module code (together with the related flags) into a different module, then it is nice to use DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort lists all relevant flags (otherwise, your code refactoring may confuse your users). Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own pluses and minuses: DECLARE_key_flag is more targeted and may lead a more focused --helpshort documentation. ADOPT_module_key_flags is good for cases when an entire module is considered key to the current script. Also, it does not require updates to client scripts when a new flag is added to the module. EXAMPLE USAGE 2 (WITH KEY FLAGS): Consider an application that contains the following three files (two auxiliary modules and a main module) File libfoo.py: import gflags gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') ... some code ... File libbar.py: import gflags gflags.DEFINE_string('bar_gfs_path', '/gfs/path', 'Path to the GFS files for libbar.') gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', 'Email address for bug reports about module libbar.') gflags.DEFINE_boolean('bar_risky_hack', False, 'Turn on an experimental and buggy optimization.') ... some code ... File myscript.py: import gflags import libfoo import libbar gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') # Declare that all flags that are key for libfoo are # key for this module too. gflags.ADOPT_module_key_flags(libfoo) # Declare that the flag --bar_gfs_path (defined in libbar) is key # for this module. gflags.DECLARE_key_flag('bar_gfs_path') ... some code ... When myscript is invoked with the flag --helpshort, the resulted help message lists information about all the key flags for myscript: --num_iterations, --num_replicas, --rpc2, and --bar_gfs_path. Of course, myscript uses all the flags declared by it (in this case, just --num_replicas) or by any of the modules it transitively imports (e.g., the modules libfoo, libbar). E.g., it can access the value of FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key flag for myscript. OUTPUT FOR --helpxml: The --helpxml flag generates output with the following structure: <?xml version="1.0"?> <AllFlags> <program>PROGRAM_BASENAME</program> <usage>MAIN_MODULE_DOCSTRING</usage> (<flag> [<key>yes</key>] <file>DECLARING_MODULE</file> <name>FLAG_NAME</name> <meaning>FLAG_HELP_MESSAGE</meaning> <default>DEFAULT_FLAG_VALUE</default> <current>CURRENT_FLAG_VALUE</current> <type>FLAG_TYPE</type> [OPTIONAL_ELEMENTS] </flag>)* </AllFlags> Notes: 1. The output is intentionally similar to the output generated by the C++ command-line flag library. The few differences are due to the Python flags that do not have a C++ equivalent (at least not yet), e.g., DEFINE_list. 2. New XML elements may be added in the future. 3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can pass for this flag on the command-line. E.g., for a flag defined using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. 4. CURRENT_FLAG_VALUE is produced using str(). This means that the string 'false' will be represented in the same way as the boolean False. Using repr() would have removed this ambiguity and simplified parsing, but would have broken the compatibility with the C++ command-line flags. 5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of flags: lower_bound, upper_bound (for flags that specify bounds), enum_value (for enum flags), list_separator (for flags that consist of a list of values, separated by a special token). 6. We do not provide any example here: please use --helpxml instead. This module requires at least python 2.2.1 to run. """ import cgi import getopt import os import re import string import struct import sys # pylint: disable-msg=C6204 try: import fcntl except ImportError: fcntl = None try: # Importing termios will fail on non-unix platforms. import termios except ImportError: termios = None import gflags_validators # pylint: enable-msg=C6204 # Are we running under pychecker? _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): """Returns the name of the module that's calling into this module.""" return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): """Returns: (module object, module name) for this module.""" return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): """The base class for all flags errors.""" pass class DuplicateFlag(FlagsError): """Raised if there is a flag naming conflict.""" pass class CantOpenFlagFileError(FlagsError): """Raised if flagfile fails to open: doesn't exist, wrong permissions, etc.""" pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): """Special case of DuplicateFlag -- SWIG flag value can't be set to None. This can be raised when a duplicate flag is created. Even if allow_override is True, we still abort if the new value is None, because it's currently impossible to pass None default value back to SWIG. See FlagValues.SetDefault for details. """ pass class DuplicateFlagError(DuplicateFlag): """A DuplicateFlag whose message cites the conflicting definitions. A DuplicateFlagError conveys more information than a DuplicateFlag, namely the modules where the conflicting definitions occur. This class was created to avoid breaking external modules which depend on the existing DuplicateFlags interface. """ def __init__(self, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. """ self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): """The flag command line argument is illegal.""" pass class UnrecognizedFlag(FlagsError): """Raised if a flag is unrecognized.""" pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value # of the flag and its argument, if any, allowing handling of unrecognized flags # in an exception handler. # If flagvalue is the empty string, then this exception is an due to a # reference to a flag that was not already defined. class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) # Global variable used by expvar _exported_flags = {} _help_width = 80 # width of help output def GetHelpWidth(): """Returns: an integer, the width of help lines that is used in TextWrap.""" if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable if columns >= 40: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): """Removes a common space prefix from the lines of a multiline text. If the first line does not start with a space, it is left as it is and only in the remaining lines a common space prefix is being searched for. That means the first line will stay untouched. This is especially useful to turn doc strings into help texts. This is because some people prefer to have the doc comment start already after the apostrophe and then align the following lines while others have the apostrophes on a separate line. The function also drops trailing empty lines and ignores empty lines following the initial content line while calculating the initial common whitespace. Args: text: text to work on Returns: the resulting text """ text_lines = text.splitlines() # Drop trailing empty lines while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: # We got some content, is the first line starting with a space? if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] # Calculate length of common leading whitespace (only over content lines) common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) # If we have a common space prefix, drop it from all lines if space_prefix_len: for index in xrange(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): """Wraps a given text to a maximum line length and returns it. We turn lines that only contain whitespace into empty lines. We keep new lines and tabs (e.g., we do not treat tabs as spaces). Args: text: text to wrap length: maximum length of a line, includes indentation if this is None then use GetHelpWidth() indent: indent for all but first line firstline_indent: indent for first line; if None, fall back to indent tabs: replacement for tabs Returns: wrapped text Raises: FlagsError: if indent not shorter than length FlagsError: if firstline_indent not shorter than length """ # Get defaults where callee used None if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') # In line we will be holding the current line which is to be started # with indent (or firstline_indent if available) and then appended # with words. if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') # If the callee does not care about tabs we simply convert them to # spaces If callee wanted tabs to be single space then we do that # already here. if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) # Split the text into lines and the lines with the regex above. The # resulting lines are collected in result[]. For each split we get the # spaces, the tabs and the next non white space (e.g. next word). result = [] for text_line in text.splitlines(): # Store result length so we can find out whether processing the next # line gave any new content old_result_len = len(result) # Process next line with line_regex. For optimization we do an rstrip(). # - process tabs (changes either line or word, see below) # - process word (first try to squeeze on line, then wrap or force wrap) # Spaces found on the line are ignored, they get added while wrapping as # needed. for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): # If tabs weren't converted to spaces, handle them now if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] # Add the tabs, if that means adding whitespace, just add it at # the line, the rstrip() code while shorten the line down if # necessary if tabs_are_whitespace: line += tabs * len(current_tabs) else: # if not all tab replacement is whitespace we prepend it to the word word = tabs * len(current_tabs) + word # Handle the case where word cannot be squeezed onto current last line if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' # No space left on line or can we append a space? if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # Add word and shorten it up to allowed line length. Restart next # line with indent and repeat, or add a space if we're done (word # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: A pair consisting of (1) module object and (2) module name (a string). Returns (None, None) if the module could not be identified. """ # The use of .items() (instead of .iteritems()) is NOT a mistake: if # a parallel thread imports a module while we iterate over # .iteritems() (not nice, but possible), we get a RuntimeError ... # Hence, we use the slightly slower but safer .items(). for name, module in sys.modules.items(): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': # Pick a more informative name for the main module. name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): """Returns: string, name of the module from which execution started.""" # First, try to use the same logic used by _GetCallingModuleObjectAndName(), # i.e., call _GetModuleObjectAndName(). For that we first need to # find the dictionary that the main module uses to store the # globals. # # That's (normally) the same dictionary object that the deepest # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues: """Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: gflags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. """ def __init__(self): # Since everything in this class is so heavily overloaded, the only # way of defining and using fields is to access __dict__ directly. # Dictionary: flag name (string) -> Flag object. self.__dict__['__flags'] = {} # Dictionary: module name (string) -> list of Flag objects that are defined # by that module. self.__dict__['__flags_by_module'] = {} # Dictionary: module id (int) -> list of Flag objects that are defined by # that module. self.__dict__['__flags_by_module_id'] = {} # Dictionary: module name (string) -> list of Flag objects that are # key for that module. self.__dict__['__key_flags_by_module'] = {} # Set if we should use new style gnu_getopt rather than getopt when parsing # the args. Only possible with Python 2.3+ self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): """Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): """Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): """Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ key_flags_by_module = self.KeyFlagsByModuleDict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module, flags in self.FlagsByModuleDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from """ for flag_name, flag in flag_values.FlagDict().iteritems(): # Each flags with shortname appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError) with double flag registration, we # perform a check to make sure that the entry we're looking at is # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): """Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove. """ for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): """Retrieves the Flag object for the flag --name.""" return self.FlagDict()[name] def __getattr__(self, name): """Retrieves the 'value' attribute of the flag --name.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): """Sets the 'value' attribute of the flag --name.""" fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().itervalues(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corresponding Flag object (it is still registered under the longer name). Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under some name. """ flag_dict = self.FlagDict() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True # The flag cannot be registered under any other name, so we do not # need to do a full search through the values of self.FlagDict(). return False def __delattr__(self, flag_name): """Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer('foo', 1, 'Integer flag.') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there is no registered flag named flag_name. """ fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): # If the Flag object indicated by flag_name is no longer # registered (please see the docstring of _FlagIsRegistered), then # we delete the occurrences of the flag object in all our internal # dictionaries. self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): """Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object. """ for unused_module, flags_in_module in flags_by_module_dict.iteritems(): # while (as opposed to if) takes care of multiple occurrences of a # flag in the list for the same module. while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): """Changes the default value of the named flag object.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): """Returns True if name is a value (flag) in the dict.""" return name in self.FlagDict() has_key = __contains__ # a synonym for __contains__() def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be converted to a list. Returns: The list of arguments not parsed as options, including argv[0] Raises: FlagsError: on any parsing error """ # Support any sequence type that can be converted to a list argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() # This pre parses the argv list for --flagfile=<> options. argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Correct the argv to support the google style of passing boolean # parameters. Boolean parameters may be passed by using --mybool, # --nomybool, --mybool=(true|false|1|0). getopt does not support # having options that may or may not have a parameter. We replace # instances of the short form --mybool and --nomybool with their # full forms: --mybool=(true|false). original_argv = list(argv) # list() makes a copy shortest_matches = None for name, flag in fl.items(): if not flag.boolean: continue if shortest_matches is None: # Determine the smallest allowable prefix for all flag names shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] # Replace all occurrences of this boolean with extended forms for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) # Loop over all of the flags, building up the lists of short options # and long options that will be passed to getopt. Short options are # specified as a string of letters, each letter followed by a colon # if it takes an argument. Long options are stored in an array of # strings. Each string ends with an '=' if it takes an argument. for name, flag in fl.items(): longopts.append(name + "=") if len(name) == 1: # one-letter option: allow short flag type also shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] # In case --undefok is specified, loop to pick up unrecognized # options one by one. unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError, e: if not e.opt or e.opt in fl: # Not an unrecognized option, re-raise the exception as a FlagsError raise FlagsError(e) # Remove offender from args and try again for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # We should have found the option, so we don't expect to get # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will # accept --nonoboolflag here. We are choosing not to do the conversion # from noboolflag -> boolflag because of the ambiguity that flag names # can start with 'no'. undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): # long option name = name[2:] short_option = 0 else: # short option name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) # If there were unrecognized options, raise an exception unless # the options were named via --undefok. for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: # if using gnu_getopt just return the program name + remainder of argv. ret_val = argv[:1] + unparsed_args else: # unparsed_args becomes the first non-flag detected by getopt to # the end of argv. Because argv may have been modified above, # return original_argv for this region. ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): """Resets the values to the point before FLAGS(argv) was called.""" for f in self.FlagDict().values(): f.Unparse() def RegisteredFlags(self): """Returns: a list of the names and short names of all registered flags.""" return list(self.FlagDict()) def FlagValuesDict(self): """Returns: a dictionary that maps flag names to flag values.""" flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp() def GetHelp(self, prefix=''): """Generates a help string for all known flags.""" helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', _SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. self.__RenderFlagList( self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): """Generates a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): """Generates a help string for a given module.""" flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): """Describe the key flags of the main module. Returns: string describing the key flags of a module. """ return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # It's possible this flag got deleted or overridden since being # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): """Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None. """ value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): """Returns: dictionary; maps flag names to their shortest unique prefix.""" # Sort the list of flag names sorted_flags = [] for name, flag in fl.items(): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() # For each name in the sorted list, determine the shortest unique # prefix by comparing itself to the next name and to the previous # name (the latter check uses cached info from the previous loop). shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): # curr longer than next or no more chars in common shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: # curr shorter than (or equal to) next shortest_matches[curr] = curr prev_idx = curr_idx + 1 # next will need at least one more char return shortest_matches def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): """Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError, e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing obeys normal flag semantics. If True, --flagfile parsing instead follows gnu_getopt semantics. *** WARNING *** force_gnu=False may become the future default! Returns: A new list which has the original list combined with what we read from any flagfile(s). References: Global gflags.FLAG class instance. This function should be called before the normal FLAGS(argv) call. This function scans the input list for a flag that looks like: --flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list between the first item of the list and any subsequent items in the list. Note that your application's flags are still defined the usual way using gflags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> Flags from the command line argv _should_ always take precedence! --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile. It will be processed after the parent flag file is done. --> For duplicate flags, first one we hit should "win". --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. """ parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): # This handles the case of -(-)flagfile foo. In this case the # next arg really is part of this one. if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: # This handles the case of (-)-flagfile=foo. flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) # Stop parsing after '--', like getopt and gnu_getopt. if current_arg == '--': break # Stop parsing after a non-flag, like getopt. if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags """ s = '' for flag in self.FlagDict().values(): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): """Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags """ out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) # Get list of key flags for the main module. key_flags = self._GetKeyFlagsForModule(_GetMainModule()) # Sort flags by declaring module name and next by flag name. flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) # end of FlagValues definition # The global FlagValues instance FLAGS = FlagValues() def _StrOrUnicode(value): """Converts value to a python string or, if necessary, unicode-string.""" try: return str(value) except UnicodeEncodeError: return unicode(value) def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" s = cgi.escape(s) # Escape <, >, and & # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag: """Information about a command-line flag. 'Flag' objects define the following fields: .name - the name for this flag .default - the default value for this flag .default_as_str - default value as repr'd string, e.g., "'true'" (or None) .value - the most recent parsed value of this flag; set by Parse() .help - a help string or None if no help is available .short_name - the single letter alias for this flag (or None) .boolean - if 'true', this flag does not accept arguments .present - true if this flag was parsed from command line flags. .parser - an ArgumentParser object .serializer - an ArgumentSerializer object .allow_override - the flag may be redefined without raising an error The only public method of a 'Flag' object is Parse(), but it is typically only called by a 'FlagValues' object. The Parse() method is a thin wrapper around the 'ArgumentParser' Parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, a FlagsError is raised. Parse() is also called during __init__ to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the __main__ module neglects to parse the command line arguments. The .present attribute is cleared after __init__ parsing. If the default value is set to None, then the __init__ parsing step is skipped and the .value attribute is initialized to None. Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag. """ def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError, e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): """Changes the default value (and current value too) for this Flag.""" # We can't allow a None override because it may end up not being # passed to C++ code when we're overriding C++ flags. So we # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check # validators). # The simplest solution I see is to make this method private. # Another approach would be to store reference to the corresponding # FlagValues with each flag, but this seems to be an overkill. if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): """Returns: a string that describes the type of this Flag.""" # NOTE: we use strings, and not the types.*Type constants because # our flags can have more exotic types, e.g., 'comma separated list # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): """Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. module_name: A string, the name of the module that defines this flag. is_key: A boolean, True iff this flag is key for main module. indent: A string that is prepended to each generated line. """ outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) # Print flag features that are relevant for all flags. _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) # The default flag value can either be represented as a string like on the # command line, or as a Python object. We serialize this value in the # latter case in order to remain consistent. if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) # Print extra flag features this flag may have. self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): """Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line. """ # Usually, the parser knows the extra details about the flag, so # we just forward the call to it. self.parser.WriteCustomInfoInXMLFormat(outfile, indent) # End of Flag definition class _ArgumentParserCache(type): """Metaclass used to cache and share argument parsers among flags.""" _instances = {} def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args) class ArgumentParser(object): """Base class used to parse and convert arguments. The Parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal. Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values. Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only. """ __metaclass__ = _ArgumentParserCache syntactic_help = "" def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer: """Base class for generating string representations of a flag value.""" def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) # Flags validators def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: string, name of the flag to be checked. checker: method to validate the flag. input - value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). See file's docstring for examples. output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags_validators.Error(desired_error_message). message: error text to be shown to the user if checker returns False. If checker raises gflags_validators.Error, message from the raised Error will be shown. flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): """Enforce lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser). Provides lower and upper bounds, and help text to display. name: string, name of the flag flag_values: FlagValues """ if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) # The DEFINE functions are explained in mode details in the module doc string. def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser that is used to parse the flag arguments. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object the flag will be registered with. serializer: ArgumentSerializer that serializes the flag value. args: Dictionary with extra keyword args that are passes to the Flag __init__. """ DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): """Declares a flag as key for the calling module. Internal function. User code should call DECLARE_key_flag or ADOPT_module_key_flags instead. Args: flag_names: A list of strings that are names of already-registered Flag objects. flag_values: A FlagValues object that the flags listed in flag_names have registered with (the value of the flag_values argument from the DEFINE_* calls that defined those flags). This should almost never need to be overridden. key_flag_values: A FlagValues object that (among possibly many other things) keeps track of the key flags for each module. Default None means "same as flag_values". This should almost never need to be overridden. Raises: UnrecognizedFlagError: when we refer to a flag that was not defined yet. """ key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --help). Sample usage: gflags.DECLARED_key_flag('flag_1') Args: flag_name: A string, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) flag_values: A FlagValues object. This should almost never need to be overridden. """ if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: FlagsError: When given an argument that is a module name (a string), instead of a module object. """ # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import # types for such a tiny use. if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) # If module is this flag module, take _SPECIAL_FLAGS into account. if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # As we associate flags with _GetCallingModuleObjectAndName(), the # special flags defined in this module are incorrectly registered with # a different module. So, we can't use _GetKeyFlagsForModule. # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in _SPECIAL_FLAGS.FlagDict().values()], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): """Parser of boolean values.""" def Convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): """Basic boolean flag. Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name. For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox. """ def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): """ HelpFlag is a special boolean flag that prints usage information and raises a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --help flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) class HelpXMLFlag(BooleanFlag): """Similar to HelpFlag, but generates output in XML format.""" def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): """ HelpshortFlag is a special boolean flag that prints usage information for the "main" module, and rasies a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --helpshort flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): """Parser of numeric values. Parsed value may be bounded to a given upper and lower bound. """ def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): """Parser of floating point values. Parsed value may be bounded to a given upper and lower bound. """ number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): """Parser of an integer value. Parsed value may be bounded to a given upper and lower bound. """ number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): """Parser of a string enum value (a string value from a given set). If enum_values (see below) is not specified, any string is allowed. """ def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): """Basic enum flag; its value can be any string from list of enum_values.""" def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): """Base class for a parser of lists of strings. To extend, inherit from this class; from the subclass __init__, call BaseListParser.__init__(self, token, name) where token is a character used to tokenize, and name is a description of the separator. """ def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): """Parser for a comma-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): """Parser for a whitespace-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings.""" parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. """ parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): """A flag that can appear multiple time on the command-line. The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line. See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here: * The default value may be either a single value or a list of values. A single value is interpreted as the [value] singleton list. * The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value """ def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary integers. Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
Python
COMPONENTS = [ "AdaBoost", "AutoInvert", "AutoMlpClassifier", "BiggestCcExtractor", "BinarizeByHT", "BinarizeByOtsu", "BinarizeByRange", "BinarizeBySauvola", "BitDataset", "BitNN", "BookStore", "CascadedMLP", "CenterFeatureMap", "ConnectedComponentSegmenter", "CurvedCutSegmenter", "CurvedCutWithCcSegmenter", "Degradation", "DeskewGrayPageByRAST", "DeskewPageByRAST", "DocClean", "DpSegmenter", "EnetClassifier", "EuclideanDistances", "KnnClassifier", "LatinClassifier", "Linerec", "LinerecExtracted", "MetaLinerec", "NullLinerec", "OcroFST", "OldBookStore", "PageFrameRAST", "Pages", "RaggedDataset8", "RaveledExtractor", "RmBig", "RmHalftone", "RmUnderline", "RowDataset8", "ScaledImageExtractor", "SegmentLineByCCS", "SegmentLineByGCCS", "SegmentLineByProjection", "SegmentPageBy1CP", "SegmentPageByMorphTrivial", "SegmentPageByRAST", "SegmentPageByRAST1", "SegmentPageByVORONOI", "SegmentPageByXYCUTS", "SegmentWords", "SimpleFeatureMap", "SimpleGrouper", "SkelSegmenter", "SmartBookStore", "SqliteBuffer", "SqliteDataset", "StandardExtractor", "StandardGrouper", "StandardPreprocessing", "TextImageSegByLogReg", "adaboost", "biggestcc", "bitdataset", "bitnn", "cfmap", "cmlp", "dpseg", "edist", "enet", "knn", "latin", "linerec", "linerec_extracted", "mappedmlp", "metalinerec", "mlp", "nulllinerec", "raggeddataset8", "raveledfe", "rowdataset8", "scaledfe", "sfmap", "simplegrouper", "sqlitebuffer", "sqliteds", ]
Python
# Django settings for ocradmin project. import os import sys import socket import subprocess as sp # Ensure celery/lazy loading Django models play nice import djcelery djcelery.setup_loader() SITE_ROOT = os.path.abspath(os.path.dirname(__file__)) # add lib dir to pythonpath sys.path.insert(0, os.path.join(SITE_ROOT, "lib")) # flag whether we're on a server. Really need a better way of doing this. # ocr1 is the db master SERVER = False MASTERNAME = "ocr1" if os.environ.get("OCR_SERVER") and SITE_ROOT.find("/dev/") == -1: # WSGI can't print to stdout, so map # it to stderr sys.stdout = sys.stderr SERVER = True # don't run in debug mode on the servers DEBUG = TEMPLATE_DEBUG = not SERVER # Path to some random binary tools BIN_PATH = "%s/bin" % SITE_ROOT # get architecture for the system we're running # on - this is mainly for choosing the correct # executable for the isri tools in bin/ ARCH = sp.Popen( ["uname -m"], shell=True, stdout=sp.PIPE ).communicate()[0].strip() # add bin the env path os.environ["PATH"] = "%s:%s" % ( os.path.join(BIN_PATH, ARCH), os.environ.get("PATH", "") ) NODETREE_PERSISTANT_CACHER = "ocradmin.nodelib.cache.PersistantFileCacher" #NODETREE_PERSISTANT_CACHER = "ocradmin.nodelib.cache.MongoDBCacher" NODETREE_USER_MAX_CACHE = 10 # Maximum cache size, in Megabytes ADMINS = ( ) MANAGERS = ADMINS DATABASE_HOST = "localhost" if not SERVER else MASTERNAME DATABASE_NAME = "ocr_testing" # if DEBUG else "ocr_production" DATABASE_USER = "ocr_testing" # if DEBUG else "ocr_production" DATABASES = { 'default' : { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : DATABASE_NAME, 'USER' : DATABASE_USER, 'PASSWORD' : 'changeme', 'HOST' : DATABASE_HOST, }, } if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'ocr_testing' } # celery settings CELERY_RESULT_BACKEND = "database" CELERY_RESULT_DBURI = "mysql://celery:celery@localhost/celeryresults" BROKER_HOST = "localhost" if not SERVER else MASTERNAME BROKER_PORT = 5672 BROKER_VHOST = "/" BROKER_USER = "guest" BROKER_PASSWORD = "guest" CELERYD_LOG_LEVEL = "INFO" CELERYD_LOG_FILE = "%s/log/celeryd.log" % SITE_ROOT CELERYBEAT_LOG_LEVEL = "INFO" CELERYBEAT_LOG_FILE = "%s/log/celerybeat.log" % SITE_ROOT TRACK_STARTED = True SEND_EVENTS = True # User Celery's test_runner. This sets ALWAYS_EAGER to True so # that tasks skip the DB infrastructure and run locally TEST_RUNNER = "celery_test_runner.CeleryTestSuiteRunner" # tagging stuff FORCE_LOWERCASE_TAGS = True MAX_TAG_LENGTH = 50 # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Europe/London' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-gb' # Login URL LOGIN_URL = "/accounts/login/" LOGIN_REDIRECT_URL = "/ocr/binarize/" SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = "%s/media" % SITE_ROOT if not SERVER else "/media/share" DOCUMENT_ROOT = "%s/documents" % MEDIA_ROOT # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" ADMIN_MEDIA_ROOT = "%s/media" % SITE_ROOT if not SERVER else "/media/share" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # Base path for transitory files TEMP_PATH = "temp" # Base path for user project files. USER_FILES_PATH = "files" # Size for thumbnails THUMBNAIL_SIZE = (256, 256) # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/admin_media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'vg@k)$%0#dn=xdelu613c6)y%yhxs)6himtf0l(i)dcpq_9jzp' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( # 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) ROOT_URLCONF = 'ocradmin.urls' # Static root media/css/etc STATIC_ROOT = "%s/static" % SITE_ROOT STATIC_URL = "/static/" TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. "%s/templates" % SITE_ROOT, ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'autoslug', 'djcelery', 'filebrowser', 'documents', 'batch', 'core', 'ocrmodels', 'presets', 'nodelib', 'ocrtasks', 'projects', 'tagging', 'test_utils', 'compress', ) SERIALIZATION_MODULES = { 'python' : 'wadofstuff.django.serializers.python', 'json' : 'wadofstuff.django.serializers.json' } # Fedora Repository settings FEDORA_ROOT = 'http://localhost:8080/fedora/' FEDORA_USER = 'fedoraAdmin' FEDORA_PASSWORD = 'fedora' FEDORA_PIDSPACE = 'simplerepo' FEDORA_IMAGE_NAME = "IMAGE" FEDORA_TRANSCRIPT_NAME = "TRANSCRIPT" COMPRESS_ROOT = STATIC_ROOT COMPRESS_URL = STATIC_URL COMPRESS_AUTO = True # total hack around csstidy not working with CSS3 gradients, but us # still wanting to use file concatenation CSSTIDY_BINARY = "cp" CSSTIDY_ARGUMENTS = "" COMPRESS_CSS_FILTERS = None COMPRESS_CSS = { "standard": { "source_filenames": ( "css/appmenu.css", "css/layout-default.css", "css/forms.css", "css/projectbrowser.css", "css/list_widget.css", "css/messages.css", "css/clean.css", "css/documents.css", "css/jquery.lightbox-0.5.css", ), "output_filename": "css/min/standard.css", "extra_context": { "media": "screen", } }, "nodetree": { "source_filenames": ( "css/nodetree.css", "css/preset_manager.css", ), "output_filename": "css/min/nodetree.css", "extra_context": { "media": "screen", } }, "viewers": { "source_filenames": ( "css/viewer.css", "css/image_viewer.css", "css/text_viewer.css", ), "output_filename": "css/min/viewers.css", "extra_context": { "media": "screen", } }, "document_edit": { "source_filenames": ( "css/document_editor.css", "css/spellcheck.css", ), "output_filename": "css/min/document_edit.css", "extra_context": { "media": "screen", } }, } COMPRESS_JS = { "jquery": { "source_filenames": ( "js/jquery/jquery-1.7.1.min.js", "js/jquery/jquery-ui-1.8.4.custom.min.js", "js/jquery/jquery.cookie.js", "js/jquery/jquery.globalstylesheet.js", "js/jquery/jquery.text-overflow.min.js", "js/jquery/jquery.titlecase.js", "js/jquery/jquery.tmpl.js", "js/jquery/jquery.rightClick.js", "js/jquery/jquery.mousewheel.js", "js/jquery/jquery.layout-latest.js", "js/jquery/jquery.hoverIntent.min.js", "js/jquery/jquery.hotkeys.js", "js/jquery/jquery.lightbox-0.5-mod.js", ), "output_filename": "js/min/jquery-lib.min.js", }, "global": { "source_filenames": ( "js/appmenu.js", "js/ocr_js/global.js", "js/utils/json2.js", "js/ocr_js/ajax_uploader.js", "js/status_bar.js", ), "output_filename": "js/min/global.min.js", }, "layout" : { "source_filenames": ( "js/ocr_js/layout.js", ), "output_filename": "js/min/layout.min.js", }, "ocrjs": { "source_filenames": ( "js/ocr_js/base.js", "js/layout_manager.js", "js/ocr_js/helpers.js", "js/ocr_js/constants.js", "js/ocr_js/task_watcher.js", ), "output_filename": "js/min/ocrjs.min.js", }, "projectbrowser": { "source_filenames": ( "js/abstract_data_source.js", "js/project_data_source.js", "js/abstract_list_widget.js", "js/project_list_widget.js", "js/projectbrowser.js", ), "output_filename": "js/min/projectbrowser.min.js", }, "undostack": { "source_filenames": ( "js/ocr_js/undo/command.js", "js/ocr_js/undo/macro.js", "js/ocr_js/undo/stack.js", ), "output_filename": "js/min/undostack.min.js", }, "nodetree": { "source_filenames": ( "js/jquery/jquery.svg.js", "js/jquery/jquery.svgdom.min.js", "js/ocr_js/nodetree/svg_helper.js", "js/ocr_js/nodetree/cable.js", "js/ocr_js/nodetree/plug.js", "js/ocr_js/nodetree/node.js", "js/ocr_js/nodetree/tree.js", "js/ocr_js/nodetree/parameters.js", "js/ocr_js/nodetree/context_menu.js", "js/ocr_js/nodetree/gui_manager.js", "js/ocr_js/nodetree/state_manager.js", "js/ocr_js/nodegui/crop_gui.js", "js/ocr_js/nodegui/manualseg_gui.js", "js/ocr_js/nodegui/blockout_gui.js", "js/ocr_js/nodetree/cable.js", "js/preset_manager.js", "js/crypto/bencode.js", "js/crypto/md5.js", ), "output_filename": "js/min/nodetree.min.js", }, "viewers": { "source_filenames": ( "js/ocr_js/dziviewer/plugin.js", "js/ocr_js/dziviewer/point.js", "js/ocr_js/dziviewer/size.js", "js/ocr_js/dziviewer/rect.js", "js/ocr_js/dziviewer/tilesource.js", "js/ocr_js/dziviewer/loader.js", "js/ocr_js/dziviewer/drawer.js", "js/ocr_js/dziviewer/cache.js", "js/ocr_js/dziviewer/viewport.js", "js/ocr_js/dziviewer/viewer.js", "js/hocr_utils.js", "js/text_viewer.js", "js/hocr_viewer.js", "js/utils/stats.js", "js/ocr_js/hocr_formatter.js", ), "output_filename": "js/min/viewers.min.js", }, "document_edit": { "source_filenames": ( "js/jquery/jquery.address.js", "js/ocr_js/hocr_editor/editor.js", "js/ocr_js/hocr_editor/hocrdoc.js", "js/ocr_js/hocr_editor/spellcheck/suggestion_list.js", "js/ocr_js/hocr_editor/spellcheck/spellchecker.js", ), "output_filename": "js/min/document_edit.min.js", }, }
Python
from django.db import models # Create your models here.
Python
""" Useful functions and classes for nodes to use. """ from __future__ import absolute_import import os import re import tempfile import subprocess as sp from lxml import etree from HTMLParser import HTMLParser from . import cache, exceptions class HTMLContentHandler(HTMLParser): def __init__(self): HTMLParser.__init__(self) self._data = [] self._ctag = None self._cattrs = None def data(self): return "".join(self._data) def content_data(self, data, tag, attrs): """ABC method. Does nothing by default.""" return data def parsefile(self, filename): with open(filename, "r") as f: for line in f.readlines(): self.feed(line) return self.data() def parse(self, string): self._data = [] self.feed(string) return self.data() def handle_decl(self, decl): self._data.append("<!%s>" % decl) def handle_comment(self, comment): self._data.append("<!-- %s -->" % comment) def handle_starttag(self, tag, attrs): """Simple add the tag to the data stack.""" self._ctag = tag self._cattrs = attrs self._data.append( "<%s %s>" % (tag, " ".join(["%s='%s'" % a for a in attrs]))) def handle_data(self, data): self._data.append(self.content_data( data, self._ctag, self._cattrs)) def handle_endtag(self, tag): self._data.append("</%s>" % tag) class HocrToTextHelper(HTMLParser): """ Get text from a HOCR document. """ def __init__(self): HTMLParser.__init__(self) self._text = [] self._gotline = False def parsefile(self, filename): self._text = [] with open(filename, "r") as f: for line in f.readlines(): self.feed(line) return "\n".join(self._text) def parse(self, string): self._text = [] self.feed(string) return "\n".join(self._text) def handle_starttag(self, tag, attrs): for name, val in attrs: if name == "class" and val.find("ocr_line") != -1: self._gotline = True if tag.lower() == "br": self._text.append("\n") elif tag.lower() == "p": self._text.append("\n\n") def handle_data(self, data): if self._gotline: self._text.append(data) def handle_endtag(self, tag): self._gotline = False def merge_hocr(hocrlist): """Merge several HOCR files (i.e. representing individual columns) into one page file.""" raise NotImplementedError def hocr_from_data(pagedata): """ Return an HOCR document (as a string). """ from django.template import Template, Context with open(os.path.join(os.path.dirname(__file__), "hocr_template.html"), "r") as tmpl: t = Template(tmpl.read()) return unicode(t.render(Context(pagedata))) def hocr_from_abbyy(abbyyxml): """ Apply some XSL to transform Abbyy XML to HOCR. """ with open(os.path.join(os.path.dirname(__file__), "abbyy2hocr.xsl"), "r") as tmpl: with open(abbyyxml, "r") as abbyy: xsl = etree.parse(tmpl) xml = etree.parse(abbyy) transform = etree.XSLT(xsl) return unicode(transform(xml)) def get_cacher(settings): cache_path = settings.NODETREE_PERSISTANT_CACHER.split('.') # Allow for Python 2.5 relative paths if len(cache_path) > 1: cache_module_name = '.'.join(cache_path[:-1]) else: cache_module_name = '.' cache_module = __import__(cache_module_name, {}, {}, cache_path[-1]) cacher = getattr(cache_module, cache_path[-1]) return cacher def get_dzi_cacher(settings): try: cachebase = get_cacher(settings) cacher = cache.DziFileCacher cacher.__bases__ = (cachebase,) except ImportError: raise exceptions.ImproperlyConfigured( "Error importing base cache module '%s'" % settings.NODETREE_PERSISTANT_CACHER) return cacher def lookup_model_file(modelname): """ Lookup the filename of a model from its database name. """ from ocradmin.ocrmodels.models import OcrModel mod = OcrModel.objects.get(name=modelname) assert os.path.exists(mod.file.path), \ "Model file does not exist: %s" % mod.file.path return mod.file.path.encode() def get_binary(binname): """ Try and find where Tesseract is installed. """ bin = sp.Popen(["which", binname], stdout=sp.PIPE).communicate()[0].strip() if bin and os.path.exists(bin): return bin for path in ["/usr/local/bin", "/usr/bin"]: binpath = os.path.join(path, binname) if os.path.exists(binpath): return binpath # fallback... return binname def set_progress(logger, progress_func, step, end, granularity=5): """ Call a progress function, if supplied. Only call every 5 steps. Also set the total todo, i.e. the number of lines to process. """ if progress_func is None: return if not (step and end): return if step != end and step % granularity != 0: return perc = min(100.0, round(float(step) / float(end), 2) * 100) progress_func(perc, end) def check_aborted(method): def wrapper(*args, **kwargs): instance = args[0] if instance.abort_func is not None: if instance.abort_func(): instance.logger.warning("Aborted") raise AbortedAction(method.func_name) return method(*args, **kwargs) return wrapper def convert_to_temp_image(imagepath, suffix="tif"): """ Convert PNG to TIFF with GraphicsMagick. This seems more reliable than PIL, which seems to have problems with Group4 TIFF encoders. """ with tempfile.NamedTemporaryFile(suffix=".%s" % suffix) as tmp: tmp.close() retcode = sp.call(["convert", imagepath, tmp.name]) if not retcode == 0: raise ExternalToolError( "convert failed to create TIFF file with errno %d" % retcode) return tmp.name def fix_preset_db_naming(): """Convert old nodetree naming to new scheme.""" from ocradmin.presets import models regex = "\"([A-Za-z0-9]+)::([A-Za-z0-9]+)\"" def repl(match): modname = match.group(1).lower() if modname == "utils": modname = "util" return "\"%s.%s\"" % (modname, match.group(2)) for p in models.Preset.objects.all(): p.data = re.sub(regex, repl, p.data) p.save()
Python
""" Stages under which nodes are categorized. Listed in this module to avoid typing the wrong string. """ INPUT = "input" OUTPUT = "output" FILTER_BINARY = "filter_binary" FILTER_GRAY = "filter_gray" BINARIZE = "binarize" PAGE_SEGMENT = "page_segment" RECOGNIZE = "recognize" UTILS = "utils" POST = "post_process"
Python
""" Utility class for displaying node scripts. """ import os import re import sys import pydot import json import tempfile class DotError(StandardError): """Dot problems.""" # http://www.graphviz.org/doc/info/lang.html RAW_NAME_RE = r"(^[A-Za-z_][a-zA-Z0-9_]*$)|(^-?([.[0-9]+|[0-9]+(.[0-9]*)?)$)" def conditional_quote(name): if re.match(RAW_NAME_RE, name) is None: return "\"%s\"" % name return name def get_node_positions(nodedict, aspect=None): """ Build the pydot graph. """ g = pydot.Dot(margin="0.1", ranksep="0.7", nodesep="1.5") if aspect is not None: g.set_aspect(round(aspect)) for name, node in nodedict.iteritems(): n = pydot.Node(name, width="0.5", fixedsize="0.5") g.add_node(n) for name, node in nodedict.iteritems(): for i in node["inputs"]: try: src = g.get_node(conditional_quote(i)) if isinstance(src, list): src = src[0] dst = g.get_node(conditional_quote(name)) if isinstance(dst, list): dst = dst[0] g.add_edge(pydot.Edge(src, dst)) except IndexError: print "Input %s not found" % i # dot doesn't seem to work on < 4 nodes... prevent it from # by just throwing an error if len(nodedict) < 4: raise DotError("Dot breaks with less than 4 nodes.") with tempfile.NamedTemporaryFile(delete=False, suffix=".dot") as t: t.close() g.write_dot(t.name) g = pydot.graph_from_dot_file(t.name) print "Wrote dot file %s" % t.name out = {} for name, node in nodedict.iteritems(): gn = g.get_node(conditional_quote(name)) if isinstance(gn, list): gn = gn[0] out[name] = [int(float(d)) \ for d in gn.get_pos().replace('"', "").split(",")] return out if __name__ == "__main__": nodes = {} with open(sys.argv[1], "r") as f: nodes = json.load(f) print get_node_positions(nodes)
Python
""" OCR-specific nodetree cacher classes. """ import os import shutil from contextlib import contextmanager from nodetree import cache from ocradmin.vendor import deepzoom import hashlib import bencode from pymongo import Connection import gridfs class UnsupportedCacheTypeError(StandardError): pass class BaseCacher(cache.BasicCacher): cachetype = "memory" def __init__(self, path="", key="", **kwargs): super(BaseCacher, self).__init__(**kwargs) self._key = key self._path = path def set_cache(self, n, data): pass def get_cache(self, n): pass def has_cache(self, n): return False def get_path(self, n): hash = hashlib.md5(bencode.bencode(n.hash_value())).hexdigest() return os.path.join(self._path, self._key, n.label, hash) def clear(self): pass def clear_cache(self, n): pass def size(self): pass class PersistantFileCacher(BaseCacher): """ Store data in files for persistance. """ cachetype = "file" def read_node_data(self, node, path): """ Get the file data under path and return it. """ readpath = os.path.join(path, node.get_file_name()) self.logger.debug("Reading %s cache: %s", self.cachetype, readpath) with self.get_read_handle(readpath) as fh: return node.reader(fh) def write_node_data(self, node, path, data): filepath = os.path.join(path, node.get_file_name()) self.logger.info("Writing %s cache: %s", self.cachetype, filepath) if data is not None: with self.get_write_handle(filepath) as fh: node.writer(fh, data) def get_cache(self, n): path = self.get_path(n) if self.has_cache(n): return self.read_node_data(n, path) @contextmanager def get_read_handle(self, readpath): try: h = open(readpath, "rb") yield h finally: h.close() @contextmanager def get_write_handle(self, filepath): if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath), 0777) try: h = open(filepath, "wb") yield h finally: h.close() def set_cache(self, n, data): self.write_node_data(n, self.get_path(n), data) def has_cache(self, n): return os.path.exists(os.path.join(self.get_path(n), n.get_file_name())) def clear(self): shutil.rmtree(os.path.join(self._path, self._key), True) def clear_cache(self, n): if self.has_cache(n): path = self.get_path(n) fpath = os.path.join(path, n.get_file_name()) os.unlink(fpath) try: os.rmdir(path) except OSError, (errno, strerr): if errno != 39: raise def size(self): folder = os.path.join(self._path, self._key) size = 0 for (path, dirs, files) in os.walk(folder): for file in files: filename = os.path.join(path, file) size += os.path.getsize(filename) return size class MongoDBCacher(PersistantFileCacher): """ Write data to MongoDB instead of the FS. """ cachetype = "MongoDB" def __init__(self, *args, **kwargs): super(MongoDBCacher, self).__init__(*args, **kwargs) self._db = getattr(Connection(), self._key) self._fs = gridfs.GridFS(self._db) @contextmanager def get_read_handle(self, readpath): try: yield self._fs.get_last_version(readpath) finally: pass @contextmanager def get_write_handle(self, filepath): try: h = self._fs.new_file(filename=filepath, encoding="utf-8") yield h finally: h.close() def has_cache(self, n): return self._fs.exists(filename=os.path.join(self.get_path(n), n.get_file_name())) def clear_cache(self, n): if self.has_cache(n): path = self.get_path(n) filepath = os.path.join(path, n.get_file_name()) gridout = self._fs.get_last_version(filepath) self._fs.delete(gridout._id) def clear(self): self._db.drop_collection("fs.files") self._db.drop_collection("fs.chunks") class DziFileCacher(PersistantFileCacher): """ Write a DZI after having written a PNG. """ def write_node_data(self, node, path, data): super(DziFileCacher, self).write_node_data(node, path, data) filepath = os.path.join(path, node.get_file_name()) if not filepath.endswith(".png"): return with self.get_read_handle(filepath) as fh: if not os.path.exists(path): os.makedirs(path) creator = deepzoom.ImageCreator(tile_size=512, tile_overlap=2, tile_format="png", image_quality=1, resize_filter="nearest") creator.create(fh, "%s.dzi" % os.path.splitext(filepath)[0]) def clear_cache(self, n): super(DziFileCacher, self).clear_cache(n) if self.has_cache(n): path = self.get_path(n) fpath = os.path.join(path, n.get_file_name()) if fpath.endswith(".png"): dzipath = "%s.dzi" % os.path.splitext(filepath)[0] os.unlink(fpath) try: os.rmdir(path) except OSError, (errno, strerr): if errno != 39: raise def clear(self): super(DziFileCacher, self).clear() if os.path.exists(os.path.join(self._path, self._key)): shutil.rmtree(os.path.join(self._path, self._key)) class TestMockCacher(BaseCacher): """ Mock cacher that doesn't do anything. """ pass
Python
""" Test the scripts. """ import os import glob from django.test import TestCase from django.utils import simplejson as json from django.conf import settings from ocradmin.core.tests import testutils from nodetree import script, node, exceptions import numpy from ocradmin.nodelib import nodes VALID_SCRIPTDIR = "nodelib/scripts/valid" INVALID_SCRIPTDIR = "nodelib/scripts/invalid" class ScriptsTest(TestCase): fixtures = ["ocrmodels/fixtures/test_fixtures.json"] def setUp(self): """ Setup OCR tests. These run directly, not via views. """ testutils.symlink_model_fixtures() self.validscripts = {} self.invalidscripts = {} for fname in os.listdir(VALID_SCRIPTDIR): if fname.endswith("json"): with open(os.path.join(VALID_SCRIPTDIR, fname), "r") as f: self.validscripts[fname] = json.load(f) for fname in os.listdir(INVALID_SCRIPTDIR): if fname.endswith("json"): with open(os.path.join(INVALID_SCRIPTDIR, fname), "r") as f: self.invalidscripts[fname] = json.load(f) def tearDown(self): """ Cleanup a test. """ pass def test_valid_scripts(self): """ Test the supposedly valid script don't raise errors. """ for name, nodes in self.validscripts.iteritems(): if name.startswith("invalid"): continue s = script.Script(nodes) terms = s.get_terminals() self.assertTrue(len(terms) > 0, msg="No terminal nodes found.") # check we get an expected type from evaling the nodes for n in terms: out = n.eval() self.assertIn(type(out), (unicode, dict, list, numpy.ndarray), msg="Unexpected output type for node %s: %s" % ( n.name, type(out))) def test_invalid_scripts(self): """ Test supposedly invalid script DO raise errors. """ for name, nodes in self.invalidscripts.iteritems(): if not name.startswith("invalid"): continue s = script.Script(nodes) terms = s.get_terminals() self.assertTrue(len(terms) > 0, msg="No terminal nodes found.") # check we get an expected type from evaling the nodes for n in terms: self.assertRaises(exceptions.ValidationError, n.eval)
Python
""" Nodetree related exceptions. """ class ExternalToolError(StandardError): """Errors with external command-line tools etc.""" class AbortedAction(StandardError): """Exception to raise when execution is aborted.""" class ImproperlyConfigured(StandardError): """Something is configured wrong"""
Python
""" Tesseract Recogniser """ from __future__ import absolute_import import os import shutil import codecs import tempfile import subprocess as sp from nodetree import node, exceptions, utils as nodeutils from . import base from .. import stages, utils, exceptions from ocradmin.ocrmodels.models import OcrModel from ocrolib import numpy class TesseractRecognizer(base.CommandLineRecognizerNode): """ Recognize an image using Tesseract. """ stage = stages.RECOGNIZE binary = "tesseract" @nodeutils.ClassProperty @classmethod def parameters(cls): return [ dict( name="language_model", value="Tesseract Default Lang", choices=[m.name for m in \ OcrModel.objects.filter(app="tesseract", type="lang")], ) ] def validate(self): """ Check we're in a good state. """ super(TesseractRecognizer, self).validate() if self._params.get("language_model", "").strip() == "": raise exceptions.ValidationError("no language model given: %s" % self._params, self) def prepare(self): """ Extract the lmodel to a temporary directory. This is cleaned up in the destructor. """ if not hasattr(self, "_tessdata") is None: modpath = utils.lookup_model_file(self._params["language_model"]) self.unpack_tessdata(modpath) self._tesseract = utils.get_binary("tesseract") self.logger.debug("Using Tesseract: %s" % self._tesseract) @utils.check_aborted def get_transcript(self, line): """ Recognise each individual line by writing it as a temporary PNG, converting it to Tiff, and calling Tesseract on the image. Unfortunately I can't get the current stable Tesseract 2.04 to support anything except TIFFs. """ with tempfile.NamedTemporaryFile(suffix=".png") as tmp: tmp.close() self.write_binary(tmp.name, line) tiff = utils.convert_to_temp_image(tmp.name, "tif") text = self.process_line(tiff) os.unlink(tmp.name) os.unlink(tiff) return text def unpack_tessdata(self, lmodelpath): """ Unpack the tar-gzipped Tesseract language files into a temporary directory and set TESSDATA_PREFIX environ var to point at it. """ # might as well make this even less efficient! self.logger.debug("Unpacking tessdata: %s" % lmodelpath) import tarfile self._tessdata = tempfile.mkdtemp() + "/" datapath = os.path.join(self._tessdata, "tessdata") os.mkdir(datapath) # let this throw an exception if it fails. tgz = tarfile.open(lmodelpath, "r:*") self._lang = os.path.splitext(tgz.getnames()[0])[0] tgz.extractall(path=datapath) tgz.close() # set environ var where tesseract picks up the tessdata dir # this DOESN'T include the "tessdata" part os.environ["TESSDATA_PREFIX"] = self._tessdata @utils.check_aborted def process_line(self, imagepath): """ Run Tesseract on the TIFF image, using YET ANOTHER temporary file to gather the output, which is then read back in. If you think this seems horribly inefficient you'd be right, but Tesseract's external interface is quite inflexible. TODO: Fix hardcoded path to Tesseract. """ if not hasattr(self, "_tessdata"): self.init_converter() lines = [] with tempfile.NamedTemporaryFile() as tmp: tmp.close() # args with page-seg mode: 5=line tessargs = [self._tesseract, imagepath, tmp.name, "-psm", "7"] if self._lang is not None: tessargs.extend(["-l", self._lang]) proc = sp.Popen(tessargs, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! TESSERACT CONVERSION ERROR %d: %s !!!" % (proc.returncode, err) # read and delete Tesseract's temp text file # whilst writing to our file with open(tmp.name + ".txt", "r") as txt: lines = [line.rstrip() for line in txt.readlines()] if lines and lines[-1] == "": lines = lines[:-1] os.unlink(txt.name) return " ".join(lines) def cleanup(self): """ Cleanup temporarily-extracted lmodel directory. """ if hasattr(self, "_tessdata") and os.path.exists(self._tessdata): try: self.logger.debug( "Cleaning up temp tessdata folder: %s" % self._tessdata) shutil.rmtree(self._tessdata) except OSError, (errno, strerr): self.logger.error( "RmTree raised error: %s, %s" % (errno, strerr)) class TesseractPageSeg(TesseractRecognizer): """ Recognize an image using Tesseract, including segmentation. """ intypes = [numpy.ndarray] def __init__(self, *args, **kwargs): super(TesseractPageSeg, self).__init__(*args, **kwargs) self._configtmp = None def get_command(self, outfile, image): """Simple tesseract command line""" args = [self.binary, image, os.path.splitext(outfile)[0]] if self._lang is not None: args.extend(["-l", self._lang]) args.append(self._configtmp) return args def prepare(self): super(TesseractPageSeg, self).prepare() # write a temp config file specifying the output format configtmp = tempfile.NamedTemporaryFile(delete=False) configtmp.write("tessedit_create_hocr\t\t1") configtmp.close() self._configtmp = configtmp.name def cleanup(self): super(TesseractPageSeg, self).prepare() os.unlink(self._configtmp) def process(self, binary): """ Convert a full page. """ self.prepare() hocr = None with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as tmp: tmp.close() with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as btmp: btmp.close() self.write_binary(btmp.name, binary) args = self.get_command(tmp.name, btmp.name) self.logger.debug("Running: '%s'", " ".join(args)) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: print err return u"!!! %s TESSERACT ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) with codecs.open(tmp.name, "r", "utf8") as tread: hocr = tread.read() os.unlink(tmp.name) os.unlink(btmp.name) utils.set_progress(self.logger, self.progress_func, 100, 100) self.cleanup() return hocr
Python
""" Cuneiform Recogniser """ from __future__ import absolute_import import os import shutil import tempfile import subprocess as sp from nodetree import node import numpy from . import base from .. import utils, stages, types class AbbyyRecognizer(base.CommandLineRecognizerNode): """ Recognize an image using Abbyy Finereader. """ binary = "abbyyocr" stage = stages.RECOGNIZE intypes = [numpy.ndarray] parameters = [ dict(name="single_column", type="bool", value=False), dict(name="invert_image", type="bool", value=False), dict(name="no_despeckle", type="bool", value=False), ] def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ args = [self.binary] if self._params.get("invert_image", False): args.append("--invertImage") if self._params.get("no_despeckle", False): args.append("--dontDespecleImage") if self._params.get("single_column", False): args.append("--singleColumnMode") args.extend(["-if", image, "-f", "XML", "-of", outfile]) return args def set_image_dpi(self, image): """ Hack to set 300 PPI on all images. This should hopefully prevent FR from using up thousands of pages of license if there's no resolution header available. """ p = sp.Popen(["convert", "-units", "PixelsPerInch", "-density", "300", image, image]) return p.wait() def process(self, binary): """ Convert a full page. """ hocr = "" with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.close() with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as btmp: btmp.close() self.write_binary(btmp.name, binary) self.set_image_dpi(btmp.name) args = self.get_command(tmp.name, btmp.name) self.logger.debug("Running: '%s'", " ".join(args)) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) hocr = utils.hocr_from_abbyy(tmp.name) os.unlink(tmp.name) os.unlink(btmp.name) utils.set_progress(self.logger, self.progress_func, 100, 100) return hocr
Python
""" Nodes for interoperating with Fedora Commons. """ import os import ocrolib from nodetree import node, exceptions from cStringIO import StringIO from . import base, util as utilnodes from .. import stages, utils from eulfedora.server import Repository from eulfedora.models import DigitalObject, FileDatastream from eulfedora.util import RequestFailed from PIL import Image class FedoraIOMixin(object): """Common Mixin for objects that require access to a Fedora Repository.""" parameters = [ dict(name="url", value="http://localhost:8080/fedora/"), dict(name="username", value="fedoraAdmin"), dict(name="password", value="fedora"), dict(name="pid", value=""), dict(name="dsid", value=""), ] def validate(self): super(FedoraIOMixin, self).validate() missing = [] for pname in [p["name"] for p in self.parameters]: if not self._params.get(pname, "").strip(): missing.append(pname) if missing: raise exceptions.ValidationError( "Missing parameter(s): %s" % ", ".join(missing), self) def get_fedora_proxy_class(dsid): fcm = "info:fedora/genrepo:File-1.0" return type("FedoraProxyObject", (DigitalObject,), dict( FILE_CONTENT_MODEL=fcm, CONTENT_MODELS=[fcm], DATASTREAM=FileDatastream(dsid, "Binary datastream", defaults={ "versionable": True, }) )) class FedoraImageIn(FedoraIOMixin, base.ImageGeneratorNode, base.GrayPngWriterMixin): stage = stages.INPUT intypes = [] outtype = ocrolib.numpy.ndarray def process(self): repo = Repository(self._params.get("url"), self._params.get("username"), self._params.get("password")) # Fixme... this is not the correct way of downloading a datastream! try: iodata = StringIO(repo.api.getDatastreamDissemination( self._params.get("pid"), self._params.get("dsid"))[0]) pil = Image.open(iodata) except IOError: raise exceptions.NodeError( "Error reading datastream contents as an image.", self) except RequestFailed: raise exceptions.NodeError( "Error communicating with Fedora Repository: 404", self) return ocrolib.numpy.asarray(pil) class FedoraImageOut(FedoraIOMixin, utilnodes.FileOut): """ Update/Input an image datastream to a Fedora Object """ stage = stages.OUTPUT outtype = type(None) parameters = FedoraIOMixin.parameters + [ dict(name="format", value="png", choices=[ "png", "jpeg", "tif", "gif" ]), ] def validate(self): missing = [] for pname in [p["name"] for p in self.parameters]: if not self._params.get(pname, "").strip(): missing.append(pname) if missing: raise exceptions.ValidationError( "Missing parameter(s): %s" % ", ".join(missing), self) def process(self, input): """ Write the input to the given path. """ if input is None: return #if not os.environ.get("NODETREE_WRITE_FILEOUT"): # return input repo = Repository(self._params.get("url"), self._params.get("username"), self._params.get("password")) try: buf = StringIO() Image.fromarray(input).save(buf, self._params.get("format").upper()) except IOError: raise exceptions.NodeError( "Error obtaining image buffer in format: %s" % self._params.get("format").upper(), self) pclass = get_fedora_proxy_class(self._params.get("dsid")) obj = repo.get_object(self._params.get("pid"), type=pclass) obj.DATASTREAM.content = buf obj.DATASTREAM.label = "Test Ingest Datastream 1" obj.DATASTREAM.mimetype = "image/%s" % self._params.get("format") obj.save() return input
Python
""" Storage node interfaces. """ from __future__ import absolute_import import os import re import io import codecs import tempfile import subprocess as sp from cStringIO import StringIO import hashlib from nodetree import node, writable_node, exceptions from . import base, util as utilnodes from .. import stages, types, utils from PIL import Image import ocrolib from ocradmin.projects.models import Project from eulfedora.util import RequestFailed class DocMixin(node.Node): """Base class for storage input interface.""" parameters = [ dict(name="project", value=""), dict(name="pid", value=""), ] def validate(self): project_pk = self._params.get("project") try: pk = int(project_pk) except ValueError: raise exceptions.ValidationError( "Project primary key not set.", self) val = self._params.get("pid") if not val.strip(): raise exceptions.ValidationError("Pid not set", self) super(DocMixin, self).validate() class DocWriter(DocMixin, utilnodes.FileOut): """Base class for storage output interface.""" stage = stages.OUTPUT outtype = type(None) parameters = [ dict(name="project", value=""), dict(name="pid", value=""), dict( name="attribute", value="", choices=["binary", "transcript"], ) ] def validate(self): project_pk = self._params.get("project") try: pk = int(project_pk) except ValueError: raise exceptions.ValidationError( "Project primary key not set.", self) val = self._params.get("pid") if not val.strip(): raise exceptions.ValidationError("Pid not set", self) def process(self, input): # TODO: Make robust if input is None or not os.environ.get("NODETREE_WRITE_FILEOUT"): return input project = Project.objects.get(pk=self._params.get("project")) storage = project.get_storage() doc = storage.get(self._params.get("pid")) attr = self._params.get("attribute") # FIXME: More memory processing... want to somehow make this # more efficient for large files # FIXME: This also seems to fail on a semi-random basis when # using a Fedora backend. #try: # memstream = StringIO() # self.input(0).writer(memstream, input) # memstream.flush() # memstream.seek(0) # storage.set_document_attr_content(doc, attr, memstream) # mimetype = "image/png" if attr == "binary" else "text/html" # storage.set_document_attr_mimetype(doc, attr, mimetype) # storage.set_document_attr_label(doc, attr, self.label) # doc.save() # return input #finally: # memstream.close() with tempfile.NamedTemporaryFile(delete=False, mode="w") as temp: self.input(0).writer(temp, input) temp.close() mimetype = "image/png" if attr == "binary" else "text/html" with open(temp.name, "rb") as rtemp: storage.set_document_attr_content(doc, attr, rtemp) storage.set_document_attr_mimetype(doc, attr, mimetype) storage.set_document_attr_label(doc, attr, self.label) doc.save() os.unlink(temp.name) return input class DocImageFileIn(DocMixin, base.GrayPngWriterMixin): """Read an image file from doc storage to grayscale.""" stage = stages.INPUT intypes = [] outtype = ocrolib.numpy.ndarray def process(self): # TODO: Make robust project = Project.objects.get(pk=self._params.get("project")) storage = project.get_storage() doc = storage.get(self._params.get("pid")) with doc.image_content as handle: pil = Image.open(handle) return ocrolib.numpy.asarray(pil.convert("L"))
Python
""" Generic base classes for other nodes. """ from __future__ import absolute_import import os import codecs import json import subprocess as sp from nodetree import node, writable_node, exceptions import ocrolib from PIL import Image from .. import stages, types, utils class ExternalToolError(StandardError): pass class TextWriterMixin(writable_node.WritableNodeMixin): """ Write text data. """ extension = ".txt" @classmethod def reader(cls, handle): """Read a text cache.""" utf8reader = codecs.getreader("utf_8")(handle) return utf8reader.read() @classmethod def writer(cls, handle, data): """Write a text cache.""" utf8writer = codecs.getwriter("utf_8")(handle) utf8writer.write(data) class JSONWriterMixin(writable_node.WritableNodeMixin): """ Functions for reading and writing a node's data in JSON format. """ extension = ".json" @classmethod def reader(cls, handle): """Read a cache from a given dir.""" return json.load(handle) @classmethod def writer(cls, handle, data): """Write a cache from a given dir.""" json.dump(data, handle, ensure_ascii=False) class PngWriterMixin(writable_node.WritableNodeMixin): """ Object which writes/reads a PNG. """ extension = ".png" class BinaryPngWriterMixin(PngWriterMixin): """ Functions for reading and writing a node's data in binary PNG. """ @classmethod def reader(cls, handle): return ocrolib.numpy.asarray(Image.open(handle)) @classmethod def writer(cls, handle, data): pil = Image.fromarray(data) pil.save(handle, "PNG") class GrayPngWriterMixin(BinaryPngWriterMixin): """ Functions for reading and writing a node's data in binary PNG. """ abstract = True class LineRecognizerNode(node.Node, TextWriterMixin): """ Node which takes a binary and a segmentation and recognises text one line at a time. """ stage = stages.RECOGNIZE intypes = [ocrolib.numpy.ndarray, dict] outtype = types.HocrString abstract = True def init_converter(self): raise NotImplementedError def get_transcript(self): raise NotImplementedError def cleanup(self): pass def prepare(self): pass def process(self, binary, boxes): """ Recognize page text. input: tuple of binary, input boxes return: page data """ self.prepare() pageheight, pagewidth = binary.shape iulibbin = ocrolib.numpy2narray(binary) out = dict(bbox=[0, 0, pagewidth, pageheight], lines=[]) numlines = len(boxes.get("lines", [])) for i in range(numlines): set_progress(self.logger, self.progress_func, i, numlines) coords = boxes.get("lines")[i] iulibcoords = ( coords[0], pageheight - coords[3], coords[2], pageheight - coords[1]) lineimage = ocrolib.iulib.bytearray() ocrolib.iulib.extract_subimage(lineimage, iulibbin, *iulibcoords) out["lines"].append(dict( index=i+1, bbox=[coords[0], coords[1], coords[2], coords[3]], text=self.get_transcript(ocrolib.narray2numpy(lineimage)), )) set_progress(self.logger, self.progress_func, numlines, numlines) self.cleanup() return utils.hocr_from_data(out) class ColumnRecognizerNode(node.Node, TextWriterMixin): """ Node which takes a binary and a segmentation and recognises each column separately. """ stage = stages.RECOGNIZE intypes = [ocrolib.numpy.ndarray, dict] outtype = types.HocrString abstract = True def init_converter(self): raise NotImplementedError def get_transcript(self): raise NotImplementedError def cleanup(self): pass def prepare(self): pass def process(self, binary, boxes): """ Recognize page text. input: tuple of binary, input boxes return: page data """ self.prepare() pageheight, pagewidth = binary.shape iulibbin = ocrolib.numpy2narray(binary) out = [] # list of hocr strings numcols = len(boxes.get("columns", [])) for i in range(numcols): set_progress(self.logger, self.progress_func, i, numcols) coords = boxes.get("columns")[i] iulibcoords = ( coords[0], pageheight - coords[3], coords[2], pageheight - coords[1]) colimage = ocrolib.iulib.bytearray() ocrolib.iulib.extract_subimage(colimage, iulibbin, *iulibcoords) out.append(self.get_transcript(ocrolib.narray2numpy(colimage))) set_progress(self.logger, self.progress_func, numcols, numcols) self.cleanup() return utils.merge_hocr(out) def set_progress(logger, progress_func, step, end, granularity=5): """ Call a progress function, if supplied. Only call every 5 steps. Also set the total todo, i.e. the number of lines to process. """ if progress_func is None: return if not (step and end): return if step != end and step % granularity != 0: return perc = min(100.0, round(float(step) / float(end), 2) * 100) progress_func(perc, end) class CommandLineRecognizerNode(LineRecognizerNode): """ Generic recogniser based on a command line tool. """ binary = "unimplemented" abstract = True def validate(self): super(CommandLineRecognizerNode, self).validate() def get_command(self, *args, **kwargs): """ Get the command line for converting a given image. """ raise NotImplementedError @classmethod def write_binary(cls, path, data): """ Write a binary image. """ ocrolib.iulib.write_image_binary(path.encode(), ocrolib.numpy2narray(data)) @classmethod def write_packed(cls, path, data): """ Write a packed image. """ ocrolib.iulib.write_image_packed(path.encode(), ocrolib.pseg2narray(data)) @utils.check_aborted def get_transcript(self, line): """ Recognise each individual line by writing it as a temporary PNG and calling self.binary on the image. """ with tempfile.NamedTemporaryFile(suffix=".png") as tmp: tmp.close() self.write_binary(tmp.name, line) text = self.process_line(tmp.name) os.unlink(tmp.name) return text @utils.check_aborted def process_line(self, imagepath): """ Run OCR on image, using YET ANOTHER temporary file to gather the output, which is then read back in. """ lines = [] with tempfile.NamedTemporaryFile() as tmp: tmp.close() args = self.get_command(outfile=tmp.name, image=imagepath) if not os.path.exists(args[0]): raise ExternalToolError("Unable to find binary: '%s'" % args[0]) self.logger.info(args) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) # read and delete the temp text file # whilst writing to our file with open(tmp.name, "r") as txt: lines = [line.rstrip() for line in txt.readlines()] if lines and lines[-1] == "": lines = lines[:-1] os.unlink(txt.name) return unicode(" ".join(lines), "utf8") class ImageGeneratorNode(node.Node): """ Node which takes no input and returns an image. """ abstract = True def null_data(self): """ Return an empty numpy image. """ return ocrolib.numpy.zeros((640,480,3), dtype=ocrolib.numpy.uint8) class FileNode(node.Node): """ Node which reads or writes to a file path. """ abstract = True def validate(self): super(FileNode, self).validate() if self._params.get("path") is None: raise exceptions.ValidationError("'path' not set", self) if not os.path.exists(self._params.get("path", "")): raise exceptions.ValidationError("'path': file not found", self)
Python
""" Cuneiform Recogniser """ from __future__ import absolute_import import os import codecs import shutil import tempfile import subprocess as sp import numpy from nodetree import node from . import base from .. import stages, types, utils class CuneiformRecognizer(base.CommandLineRecognizerNode): """ Recognize an image using Cuneiform. """ binary = "cuneiform" stage = stages.RECOGNIZE intypes = [numpy.ndarray] parameters = [ dict(name="single_column", type="bool", value=False) ] def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ args = [self.binary, "-f", "hocr", "-o", outfile] if self._params.get("single_column", False): args.extend(["--singlecolumn"]) return args + [image] def process(self, binary): """ Convert a full page. """ hocr = None with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.close() with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as btmp: btmp.close() self.write_binary(btmp.name, binary) args = self.get_command(tmp.name, btmp.name) self.logger.debug("Running: '%s'", " ".join(args)) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: print err return u"!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) with codecs.open(tmp.name, "r", "utf8") as tread: hocr = tread.read() os.unlink(tmp.name) os.unlink(btmp.name) utils.set_progress(self.logger, self.progress_func, 100, 100) return hocr
Python
""" Nodes that use web services to do something. """ import json import httplib2 import urllib from BeautifulSoup import BeautifulSoup from nodetree import node, exceptions from . import base from .. import stages class WebServiceNodeError(exceptions.NodeError): pass class BaseWebService(node.Node, base.TextWriterMixin): """ Base class for web service nodes. """ abstract = True stage = stages.POST intypes = [unicode] outtype = unicode class MashapeProcessing(BaseWebService): """ Mashape entity extraction. """ stage = stages.POST baseurl = "http://text-processing.com/api/" parameters = [ dict(name="extract", value="phrases", choices=["phrases", "sentiment"]), ] def process(self, input): http = httplib2.Http() headers = {} body = dict(text=input[:10000].encode("utf8", "replace")) url = "%s/%s/" % (self.baseurl, self._params.get("extract", "phrases")) request, content = http.request(url, "POST", headers=headers, body=urllib.urlencode(body)) if request["status"] == "503": raise WebServiceNodeError("Daily limit exceeded", self) elif request["status"] == "400": raise WebServiceNodeError("No text, limit exceeded, or incorrect language", self) out = u"" try: data = json.loads(content) except ValueError: return content for key in ["GPE", "VP", "LOCATION", "NP", "DATE"]: keydata = data.get(key) if keydata is not None: out += "%s\n" % key for entity in keydata: out += " %s\n" % entity return out class DBPediaAnnotate(BaseWebService): """ Mashape entity extraction. """ stage = stages.POST baseurl = "http://spotlight.dbpedia.org/rest/annotate/" parameters = [ dict(name="confident", value=0.2), dict(name="support", value=20), ] def process(self, input): http = httplib2.Http() headers = {} body = dict( text=input.encode("utf8", "replace"), confidence=self._params.get("confident"), support=self._params.get("support"), ) url = "%s?%s" % (self.baseurl, urllib.urlencode(body)) request, content = http.request(url, "GET", headers=headers) if request["status"] != "200": raise WebServiceNodeError("A web service error occured. Status: %s" % request["status"], self) out = u"" soup = BeautifulSoup(content) for ref in soup.findAll("a"): out += "%s\n" % ref.text out += " %s\n\n" % ref.get("href") return out class OpenCalais(BaseWebService): """ OpenCalias sematic markup. """ stage = stages.POST baseurl = "http://api.opencalais.com/tag/rs/enrich" parameters = [ ] def process(self, input): http = httplib2.Http() headers = { "x-calais-licenseID": "dsza6q6zwa9nzvz9wbz7f6y5", "content-type": "text/raw", "Accept": "xml/rdf", "enableMetadataType": "GenericRelations", } request, content = http.request( self.baseurl, "POST", headers=headers, body=input.encode("utf8") ) if request["status"] != "200": raise WebServiceNodeError("A web service error occured. Status: %s" % request["status"], self) return content.decode("utf8")
Python
""" Nodes to perform random things. """ from __future__ import absolute_import import os import re import codecs import tempfile import subprocess as sp from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup from nodetree import node, writable_node, exceptions from . import base from .. import stages, types, utils class NoOp(node.Node, writable_node.WritableNodeMixin): stage = stages.UTILS def __init__(self, *args, **kwargs): super(NoOp, self).__init__(*args, **kwargs) self.intypes = [type(None)] self.outtype = type(None) def validate(self): if self.input(0): self.intypes = [self._inputs[0].outtype] self.outtype = self._inputs[0].outtype super(NoOp, self).validate() def set_input(self, num, n): """ Override the base set input to dynamically change our in and out types. """ super(NoOp, self).set_input(num, n) self.intypes = [self._inputs[num].outtype] self.outtype = self._inputs[num].outtype def first_active(self): return self._inputs[0].first_active() def process(self, input): return input class FindReplace(node.Node, base.TextWriterMixin): """ Find an replace stuff in input with output. """ stage = stages.UTILS intypes = [types.HocrString] outtype = types.HocrString parameters = [ dict(name="find", value=""), dict(name="replace", value=""), ] def __init__(self, *args, **kwargs): super(FindReplace, self).__init__(*args, **kwargs) self._findre = None self._replace = None def validate(self): super(FindReplace, self).validate() try: re.compile(self._params.get("find")) except Exception, err: raise exceptions.ValidationError("find: regular expression error: %s" % err, self) def content_data(self, data, tag, attrs): """Replace all content data.""" return self._findre.sub(self._replace, data) def process(self, xml): """ Run find/replace on input """ find = self._params.get("find", "") replace = self._params.get("replace", "") if find.strip() == "" or replace.strip() == "": return xml self._findre = re.compile(find) self._replace = replace parser = utils.HTMLContentHandler() parser.content_data = self.content_data return parser.parse(xml) class HocrToText(node.Node, base.TextWriterMixin): """ Convert HOCR to text. """ stage = stages.UTILS intypes = [unicode] outtype = unicode parameters = [] def process(self, input): soup = BeautifulSoup(input) raw = ''.join(soup.find("div", {"class":"ocr_page"}).findAll(text=True)) decode = BeautifulStoneSoup(raw, convertEntities=BeautifulStoneSoup.HTML_ENTITIES) return re.sub("[\n]{3,100}", "\n\n", decode.text) class TextFileIn(base.FileNode, base.TextWriterMixin): """ Read a text file. That's it. """ stage = stages.INPUT intypes = [] outtype = unicode parameters = [dict(name="path", value="", type="filepath")] def process(self): with open(self._params.get("path"), "r") as fh: return self.reader(fh) class Switch(node.Node, writable_node.WritableNodeMixin): """ Node which passes through its selected input. """ stage = stages.UTILS intypes = [object, object] outtype = type(None) parameters = [dict(name="input", value=0, type="switch")] def __init__(self, *args, **kwargs): self.arity = kwargs.get("arity", 2) self.intypes = [object for i in range(self.arity)] self.outtype = object super(Switch, self).__init__(*args, **kwargs) def active_input(self): """The active child node.""" input = int(self._params.get("input", 0)) return self._inputs[input] def validate_all(self): """Only validate active input.""" active = self.active_input() if active is not None: active.validate_all() self.validate() def early_eval(self): """Pass through the selected input.""" input = int(self._params.get("input", 0)) return self.eval_input(input) def set_input(self, num, n): """ Override the base set input to dynamically change our in and out types. """ super(Switch, self).set_input(num, n) input = int(self._params.get("input", 0)) if input == num: self.outtype = self._inputs[input].outtype def first_active(self): if self.arity > 0 and self.ignored: return self._inputs[self.passthrough].first_active() input = int(self._params.get("input", 0)) return self._inputs[input].first_active() def get_file_name(self): input = int(self._params.get("input", 0)) if self.input(input): return "%s%s" % (self.input(input), self.input(input).extension) return "%s%s" % (self.input(input), self.extension) def writer(self, fh, data): """ Pass through the writer function from the selected node. """ input = int(self._params.get("input", 0)) if self.input(input): return self.input(input).writer(fh, data) def reader(self, fh): """ Pass through the writer function from the selected node. """ input = int(self._params.get("input", 0)) if self.input(input): return self.input(input).reader(fh) class FileOut(node.Node, writable_node.WritableNodeMixin): """ A node that writes a file to disk. """ stage = stages.OUTPUT outtype = type(None) parameters = [ dict(name="path", value="", type="filepath"), dict(name="create_dir", value=False, type="bool"), ] def validate(self): """ Check params are OK. """ if self._params.get("path") is None: raise exceptions.ValidationError("'path' not set", self) def set_input(self, num, n): """ Override the base set input to dynamically change our in and out types. """ super(FileOut, self).set_input(num, n) self.outtype = self._inputs[num].outtype def null_data(self): """ Return the input. """ next = self.first_active() if next is not None: return next.eval() def get_file_name(self): if self.input(0): return "%s%s" % (self.input(0), self.input(0).extension) return "%s%s" % (self, self.extension) def writer(self, fh, data): """ Pass through the writer function from the selected node. """ if self.input(0): return self.input(0).writer(fh, data) def reader(self, fh): """ Pass through the writer function from the selected node. """ if self.input(0): return self.input(0).reader(fh) def process(self, input): """ Write the input to the given path. """ if input is None: return if not os.environ.get("NODETREE_WRITE_FILEOUT"): return input path = self._params.get("path") if not os.path.exists(os.path.dirname(path)) and self._params.get("create_dir", False): os.makedirs(os.path.dirname(path), 0777) with open(path, "w") as fh: self._inputs[0].writer(fh, input) return input class TextEvaluation(node.Node, base.TextWriterMixin): """ Evaluate two text inputs with ISRI accuracy program. """ stage = stages.UTILS intypes = [unicode, unicode] outtype = unicode parameters = [ dict(name="method", value="character", choices=["character", "word"]), ] def process(self, intext, gttext): with tempfile.NamedTemporaryFile(delete=False, mode="wb") as t1: with tempfile.NamedTemporaryFile(delete=False, mode="wb") as t2: self.writer(t1, gttext) self.writer(t2, intext) writer = codecs.getwriter("utf8")(sp.PIPE) method = self._params.get("method", "character") bin = "accuracy" if method == "character" else "wordacc" p = sp.Popen([bin, t1.name, t2.name], stdout=writer) report = p.communicate()[0] os.unlink(t1.name) os.unlink(t2.name) return unicode(report, "utf8", "replace") class TextDiff(node.Node, base.TextWriterMixin): """ Do a side-by-side. """ stage = stages.UTILS intypes = [unicode, unicode] outtype = unicode parameters = [dict(name="format", value="normal", choices=("normal", "side-by-side", "rcs"))] def process(self, intext, gttext): format = self._params.get("format", "normal") with tempfile.NamedTemporaryFile(delete=False, mode="wb") as t1: with tempfile.NamedTemporaryFile(delete=False, mode="wb") as t2: self.writer(t1, gttext) self.writer(t2, intext) writer = codecs.getwriter("utf8")(sp.PIPE) p = sp.Popen(["diff", "--%s" % format, t1.name, t2.name], stdout=writer) report = p.communicate()[0] os.unlink(t1.name) os.unlink(t2.name) return unicode(report, "utf8", "replace") class AbbyyXmlToHocr(node.Node, base.TextWriterMixin): """ Convert Abbyy XML to HOCR. """ stage = stages.UTILS intypes = [unicode] outtype = unicode parameters = [] def process(self, intext): out = "" with tempfile.NamedTemporaryFile(delete=False, mode="wb") as t1: self.writer(t1, intext) t1.close() out = utils.hocr_from_abbyy(t1.name) os.unlink(t1.name) return out
Python
from __future__ import absolute_import from nodetree import node, writable_node, exceptions from .base import GrayPngWriterMixin from .. import stages import numpy class Rotate90(node.Node, GrayPngWriterMixin): """ Rotate a Numpy image num*90 degrees counter-clockwise. """ stage = stages.FILTER_BINARY intypes = [numpy.ndarray] outtype = numpy.ndarray parameters = [{ "name": "num", "value": 1, }] def validate(self): super(Rotate90, self).validate() if not self._params.get("num"): raise exceptions.ValidationError("'num' is not set", self) try: num = int(self._params.get("num")) except ValueError: raise exceptions.ValidationError("'num' must be an integer", self) def process(self, image): return numpy.rot90(image, int(self._params.get("num", 1))) class Rotate90Gray(Rotate90): """ Grayscale version of above. """ stage = stages.FILTER_GRAY
Python
""" Experimental segmentation nodes. """ from __future__ import absolute_import from nodetree import node, writable_node import ocrolib from ocrolib import iulib, numpy from . import base from .. import stages class Rectangle(object): """ Rectangle class, Iulib-style. """ def __init__(self, x0, y0, x1, y1): """ Initialise a rectangle. """ self.x0 = x0 self.y0 = y0 self.x1 = x1 self.y1 = y1 def __repr__(self): return "<Rectangle: %d %d %d %d>" % ( self.x0, self.y0, self.x1, self.y1 ) def __eq__(self, rect): return self.x0 == rect.x0 and self.y0 == rect.y0 \ and self.x1 == rect.x1 and self.y1 == rect.y1 def __ne__(self, rect): return self.x0 != rect.x0 or self.y0 != rect.y0 \ or self.x1 != rect.x1 or self.y1 != rect.y1 def aspect(self): if self.empty(): return 1 return float(self.width()) / float(self.height()) def area(self): if self.empty(): return 0 return self.width() * self.height() def clone(self): return Rectangle(self.x0, self.y0, self.x1, self.y1) def empty(self): return self.x0 >= self.x1 and self.y0 >= self.y1 def pad_by(self, dx, dy): assert(not self.empty()) self.x0 -= dx self.y0 -= dy self.x1 += dx self.y0 += dy def shift_by(self, dx, dy): assert(not self.empty()) self.x0 += dx self.y0 += dy self.x1 += dx self.y0 += dy def width(self): return max(0, self.x1 - self.x0) def height(self): return max(0, self.y1 - self.y0) def include_point(self, x, y): if self.empty(): self.x0 = x self.y0 = y self.x1 = x + 1 self.y1 = y + 1 else: self.x0 = min(x, self.x0) self.y0 = min(y, self.y0) self.x1 = max(x + 1, self.x1) self.y1 = max(y + 1, self.y1) def include(self, rect): if self.empty(): self.x0 = rect.x0 self.y0 = rect.y0 self.x1 = rect.x1 self.y1 = rect.y1 else: self.x0 = min(self.x0, rect.x0) self.y0 = min(self.y0, rect.y0) self.x1 = max(self.x1, rect.x1) self.y1 = max(self.y1, rect.y1) def grow(self, dx, dy): return Rectangle(self.x0 - dx, self.y0 - dy, self.x1 + dx, self.y1 + dy) def overlaps(self, rect): return self.x0 <= rect.x1 and self.x1 >= rect.x0 \ and self.y0 <= rect.y1 and self.y1 >= rect.y0 def overlaps_x(self, rect): return self.x0 <= rect.x1 and self.x1 >= rect.x0 def overlaps_y(self, rect): return self.y0 <= rect.y1 and self.y1 >= rect.y0 def contains(self, x, y): return x >= self.x0 and x < self.x1 \ and y >= self.y0 and y < self.y1 def points(self): return (self.x0, self.y0, self.x1, self.y1,) def intersection(self, rect): if self.empty(): return self return Rectangle( max(self.x0, rect.x0), max(self.y0, rect.y0), min(self.x1, rect.x1), min(self.y1, rect.y1) ) def inclusion(self, rect): if self.empty(): return rect return Rectangle( min(self.x0, rect.x0), min(self.y0, rect.y0), max(self.x1, rect.x1), max(self.y1, rect.y1) ) def fraction_covered_by(self, rect): isect = self.intersection(rect) if self.area(): return isect.area() / float(self.area()) else: return -1 @classmethod def union_of(cls, *args): r = Rectangle(0, 0, 0, 0) for arg in args: r.include(arg) return r def r2i(rect): return iulib.rectangle(rect.x0, rect.y0, rect.x1, rect.y1) def i2r(rect): return Rectangle(rect.x0, rect.y0, rect.x1, rect.y1) def smooth(x,window_len=11,window='hanning'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. input: x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. output: the smoothed signal example: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string """ if x.ndim != 1: raise ValueError, "smooth only accepts 1 dimension arrays." if x.size < window_len: raise ValueError, "Input vector needs to be bigger than window size." if window_len<3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] #print(len(s)) if window == 'flat': #moving average w=numpy.ones(window_len,'d') else: w=eval('numpy.'+window+'(window_len)') y=numpy.convolve(w/w.sum(),s,mode='same') return y[window_len-1:-window_len+1] def not_char(rect): """ Perform basic validation on a rect to test if it *could* be a character box. """ return rect.area() < 4 or rect.area() > 10000 \ or rect.aspect() < 0.2 or rect.aspect() > 5 def horizontal_overlaps(rect, others, sorted=False): """ Get rects that overlap horizontally with the given rect. """ overlaps = [] for other in others: # Note: can optimise to prevent # going through the rest of the # array when we hit a non match if rect.overlaps_y(other): overlaps.append(other) return overlaps def get_average_line_height(top_bottoms): """ Tricksy - get height of median line? """ lheights = [b - t for t, b in top_bottoms] lhm = numpy.max(lheights) def weight(val): return 0 if val < (lhm / 2) else 1 weights = numpy.vectorize(weight)(lheights) return numpy.average(numpy.array(lheights), weights=weights) def remove_border(narray, average_char_height): """ Try and remove anything that's in a likely border region and return the subimage. """ na = iulib.numpy(narray) hpr = na.sum(axis=0) vpr = na.sum(axis=1) hhp = high_pass_median(hpr, 5.0 / average_char_height) vhp = high_pass_median(vpr, 5.0 / average_char_height) vidx = vhp.nonzero()[0] hidx = hhp.nonzero()[0] b = iulib.bytearray() iulib.extract_subimage(b, narray, int(vidx[0]), int(hidx[0]), int(vidx[-1]), int(hidx[-1])) return b def get_vertical_projection(narray): """ Accumulate image columns. """ return iulib.numpy(narray).sum(axis=1) def get_horizontal_projection(narray): """ Accumulate image rows. """ return iulib.numpy(narray).sum(axis=0) def high_pass_max(numpy_arr, maxscale): """ Remove everything below 1/2 of the median value. """ # remove noise max = numpy.max(numpy_arr) def hp(x, m): return 0 if x < m else x return numpy.vectorize(hp)(numpy_arr, max * maxscale) def high_pass_median(numpy_arr, medscale): """ Remove everything below 1/2 of the median value. """ # remove noise median = numpy.median(numpy_arr) def hp(x, m): return 0 if x < m else x return numpy.vectorize(hp)(numpy_arr, median * medscale) def get_lines_by_projection(narray, highpass=0.001): """ Extract regions of blackness. """ hpr = iulib.numpy(narray).sum(axis=0) hps = high_pass_max(hpr, highpass) regions = [] gotline = None count = 0 for val in hps: if val != 0: if gotline is None: gotline = count else: if not gotline is None: regions.append((gotline, count)) gotline = None count += 1 return regions def large_or_odd(rect, avg): """ An odd shape. """ return rect.area() > (100 * avg * avg) or rect.aspect() < 0.2 \ or rect.aspect() > 10 def strip_non_chars(narray, bboxes, average_height, inverted=True): """ Remove stuff that isn't looking like a character box. """ outboxes = [] color = 0 if inverted else 255 for box in bboxes: if large_or_odd(box, average_height): iulib.fill_rect(narray, box.x0, box.y0, box.x1, box.y1, color) else: outboxes.append(box) return outboxes def trimmed_mean(numpy_arr, lperc=0, hperc=0): """ Get a trimmed mean value from array, with low and high percentage ignored. """ alen = len(numpy_arr) return numpy_arr[(alen / 100 * lperc): (alen - (alen / 100 * hperc))].mean() class SegmentPageByHint(node.Node, base.JSONWriterMixin): """Segment a page using toplines and column hints""" stage = stages.PAGE_SEGMENT intypes = [ocrolib.numpy.ndarray] outtype = dict parameters = [ dict(name="toplines", value=0), dict(name="columns", value=1), dict(name="highpass", value=0.001, type="float"), ] def null_data(self): """ Return an empty list when ignored. """ return dict(columns=[], lines=[], paragraphs=[]) def process(self, input): """ Segment a binary image. input: a binary image. return: a dictionary of box types: lines paragraphs columns images """ self.inarray = ocrolib.numpy2narray(input, type='B') self.init() for topline in range(int(self._params.get("toplines", 0))): self.get_header_line() self.columns.append(Rectangle.union_of(*self.textlines)) self.find_columns() self.find_lines() def flipud(r): return [r.x0, input.shape[0] - r.y1, r.x1, input.shape[0] - r.y0] return dict( lines=[flipud(r) for r in self.textlines], columns=[flipud(r) for r in self.columns], ) def init(self): """ Initialise on receipt of the input. """ # pointer to the region that remains # to be segmented - starts at the top self.topptr = self.inarray.dim(1) # obtain an inverted version of the array self.inverted = iulib.bytearray() self.inverted.copy(self.inarray) iulib.binary_invert(self.inverted) self.calc_bounding_boxes() # list of extracted line rectangles self.textlines = [] self.columns = [] def calc_bounding_boxes(self): """ Get bounding boxes if connected components. """ concomps = iulib.intarray() concomps.copy(self.inverted) iulib.label_components(concomps, False) bboxes = iulib.rectarray() iulib.bounding_boxes(bboxes, concomps) self.boxes = [] for i in range(bboxes.length()): if bboxes.at(i).area() > (self.inverted.dim(0) * self.inverted.dim(1) * 0.95): continue self.boxes.append(i2r(bboxes.at(i))) # get the average text height, excluding any %% self.avgheight = trimmed_mean(numpy.sort(numpy.array( [r.height() for r in self.boxes])), 5, 5) # remove large or weird boxes from the inverted images self.boxes = strip_non_chars(self.inverted, self.boxes, self.avgheight) def get_char_boxes(self, boxes): """ Get character boxes. """ return [b for b in boxes if not not_char(b)] def get_header_line(self): """ Get the first found line in an image. """ boxes = self.get_char_boxes(self.boxes) # eliminate boxes above our top-of-the-page # pointer boxes = [b for b in boxes if b.y1 <= self.topptr] # order boxes by y0 (distance from bottom) boxes.sort(lambda x, y: cmp(x.y1, y.y1)) # reverse so those nearest the top are first boxes.reverse() # get rects with overlap horizontally with # the topmost one # try a maximum of 20 lines until we find one with at least # 5 overlaps overlaps = [] maxcnt = 0 line = Rectangle(0, 0, 0, 0) while maxcnt < 200 and (len(overlaps) < 2 \ or line.height() < (self.avgheight * 1.5)): overlaps = horizontal_overlaps( boxes[maxcnt], boxes, sorted=False) line = Rectangle.union_of(*overlaps) maxcnt += 1 self.textlines.append(line) # set region of interest to below the top line self.topptr = line.y0 def get_possible_columns(self, projection): """ Extract regions of whiteness. """ regions = [] gotcol = None count = 0 for val in projection: if count == len(projection) - 1 and gotcol is not None: regions.append(Rectangle(gotcol, 0, count, self.topptr)) elif val != 0: if gotcol is None: gotcol = count else: if not gotcol is None: regions.append(Rectangle(gotcol, 0, count, self.topptr)) gotcol = None count += 1 return regions def filter_columns(self, rects, target): """ Filter a group of regions to match the target number, preserving those which seem the most likely to be 'good' """ if len(rects) <= target: return rects # add the x largest cols best = [] for col in sorted(rects, lambda x, y: cmp(y.area(), x.area())): best.append(col) if len(best) == target: break return best def find_columns(self): """ Get columns in a section of the image """ portion = iulib.bytearray() iulib.extract_subimage(portion, self.inverted, 0, 0, self.inverted.dim(0), self.topptr) projection = high_pass_median(iulib.numpy(portion).sum(axis=1), 0.20) posscols = self.get_possible_columns(projection) bestcols = self.filter_columns(posscols, int(self._params.get("columns", 1))) self.columns.extend(bestcols) def find_lines(self): """ Get lines in a section of the images. """ for colrect in self.columns: newrect = Rectangle(colrect.x0, 0, colrect.x1, self.topptr) if newrect.area() < 1: continue portion = iulib.bytearray() iulib.extract_subimage(portion, self.inverted, *newrect.points()) regions = get_lines_by_projection(portion, float(self._params.get("highpass"))) plines = [] for bottom, top in regions: height = top - bottom if height - self.avgheight < self.avgheight / 3: continue plines.append(Rectangle(colrect.x0, bottom, colrect.x1, top)) cpline = None clline = Rectangle(0, 0, 0, 0) charboxes = self.get_char_boxes(self.boxes) colboxes = [b for b in charboxes \ if b.overlaps(colrect.grow(10, 10))] colboxes.sort(lambda x, y: cmp(x.y1, y.y1)) colboxes.reverse() clines = [] for p in plines: clines.append(Rectangle(0, 0, 0, 0)) while colboxes: char = colboxes.pop(0) cline = Rectangle(0, 0, 0, 0) for i in range(len(plines)): pline = plines[i] if char.overlaps(pline): clines[i].include(char) self.textlines.extend(clines) def get_coords(coordstr): """ Return a list of rects from the coords string. """ if coordstr is None: return [] rstr = coordstr.split("~") rects = [] for r in rstr: points = r.split(",") if len(points) != 4: continue try: ints = [int(i) for i in points] assert len(ints) == 4 rects.append(Rectangle(*ints)) except ValueError: continue return rects def sanitise_coords(rectlist, width, height): """ Treat negative numbers as the outer bound. """ def sanitise(rect): rect.x0 = max(rect.x0, 0) rect.y0 = max(rect.y0, 0) if rect.x1 < 0: rect.x1 = width if rect.y1 < 0: rect.y1 = height if rect.x0 > width: rect.x0 = width - 1 if rect.y0 > height: rect.y0 = height - 1 if rect.x1 > width: rect.x1 = width if rect.y1 > height: rect.y1 = height return rect return [sanitise(rect) for rect in rectlist] def flip_coord(rect, height): return Rectangle(rect.x0, height - rect.y1, rect.x1, height - rect.y0) class SegmentPageManual(node.Node, base.JSONWriterMixin): """Segment a page using manual column definitions.""" stage = stages.PAGE_SEGMENT intypes = [ocrolib.numpy.ndarray] outtype = dict parameters = [ dict(name="boxes", value=""), ] def __init__(self, *args, **kwargs): super(SegmentPageManual, self).__init__(*args, **kwargs) self._regions = ocrolib.RegionExtractor() self._segmenter = ocrolib.SegmentPageByRAST1() def null_data(self): """ Return an empty list when ignored. """ return dict(columns=[], lines=[], paragraphs=[]) def process(self, binary): """ Segment a binary image. input: a binary image. return: a dictionary of box types: lines paragraphs columns images """ height = binary.shape[0] pstr = self._params.get("boxes", "") coords = [flip_coord(r, height) for r in get_coords(pstr)] if len(coords) == 0: coords.append(Rectangle(0, 0, binary.shape[1] - 1, binary.shape[0] - 1)) coords = sanitise_coords(coords, binary.shape[1], binary.shape[0]); boxes = {} for rect in coords: points = rect.points() col = ocrolib.iulib.bytearray() ocrolib.iulib.extract_subimage(col, ocrolib.numpy2narray(binary), *points) pout = self.segment_portion(col, points[0], points[1], points[3] - points[1]) for key, rects in pout.iteritems(): if boxes.get(key) is not None: boxes.get(key).extend(rects) else: boxes[key] = rects for key, rects in boxes.iteritems(): boxes[key] = [flip_coord(r, height).points() for r in rects] return boxes def segment_portion(self, portion, dx, dy, pheight): """ Segment a single-column chunk. """ page_seg = self._segmenter.segment(ocrolib.narray2numpy(portion)) return self.extract_boxes(self._regions, page_seg, dx, dy, pheight) @classmethod def extract_boxes(cls, regions, page_seg, dx, dy, pheight): """ Extract line/paragraph geoocrolib.metry info. """ out = dict(columns=[], lines=[], paragraphs=[]) #out = dict(lines=[], paragraphs=[]) exfuncs = dict(lines=regions.setPageLines, paragraphs=regions.setPageParagraphs) #columns=regions.setPageColumns) #page_seg = numpy.flipud(page_seg) for box, func in exfuncs.iteritems(): func(page_seg) for i in range(1, regions.length()): out[box].append(Rectangle(regions.x0(i) + dx, (pheight - regions.y1(i)) + dy, regions.x1(i) + dx, (pheight - regions.y0(i)) + dy)) return out class BlockOut(node.Node, base.BinaryPngWriterMixin): """Blockout sections of an image.""" stage = stages.FILTER_BINARY intypes = [numpy.ndarray] outtype = numpy.ndarray parameters = [dict(name="boxes", value=""),] def process(self, input): """ Blockout an image, using PIL. If any of the parameters are -1 or less, use the outer dimensions. """ height = input.shape[0] pstr = self._params.get("boxes", "") coords = get_coords(pstr) if len(coords) == 0: return input sancoords = sanitise_coords(coords, input.shape[1], input.shape[0]); flipcoords = [flip_coord(r, height) for r in sancoords] narray = ocrolib.numpy2narray(input) for rect in flipcoords: ocrolib.iulib.fill_rect(narray, rect.x0, rect.y0, rect.x1, rect.y1, 255) return ocrolib.narray2numpy(narray)
Python
from __future__ import absolute_import from . import ( abbyy, ocropus, tesseract, util, numpy, pil, ocrlab, cuneiform, web, fedora, storage)
Python
""" Ocropus OCR processing nodes. """ from __future__ import absolute_import import os import sys import json from nodetree import node, writable_node, exceptions from nodetree import utils as nodeutils import ocrolib from ocradmin.ocrmodels.models import OcrModel from . import base from .. import stages, utils class UnknownOcropusNodeType(Exception): pass class NoSuchNodeException(Exception): pass class OcropusNodeError(exceptions.NodeError): pass def makesafe(val): if isinstance(val, unicode): return val.encode() return val class GrayFileIn(base.ImageGeneratorNode, base.FileNode, base.GrayPngWriterMixin): """ A node that takes a file and returns a numpy object. """ stage = stages.INPUT intypes = [] outtype = ocrolib.numpy.ndarray parameters = [dict(name="path", value="", type="filepath")] def process(self): if not os.path.exists(self._params.get("path", "")): return self.null_data() return ocrolib.read_image_gray(makesafe(self._params.get("path"))) class Crop(node.Node, base.BinaryPngWriterMixin): """ Crop a PNG input. """ stage = stages.FILTER_BINARY intypes = [ocrolib.numpy.ndarray] outtype = ocrolib.numpy.ndarray parameters = [ dict(name="x0", value=-1), dict(name="y0", value=-1), dict(name="x1", value=-1), dict(name="y1", value=-1), ] def process(self, input): """ Crop an image, using IULIB. If any of the parameters are -1 or less, use the outer dimensions. """ x0, y0 = 0, 0 y1, x1 = input.shape try: x0 = int(self._params.get("x0", -1)) if x0 < 0: x0 = 0 except TypeError: pass try: y0 = int(self._params.get("y0", -1)) if y0 < 0: y0 = 0 except TypeError: pass try: x1 = int(self._params.get("x1", -1)) if x1 < 0: x1 = input.shape[1] except TypeError: pass try: y1 = int(self._params.get("y1", -1)) if y1 < 0: y1 = input.shape[0] except TypeError: pass # flip the coord system from HOCR to internal iy0 = input.shape[1] - y1 iy1 = input.shape[1] - y0i iulibbin = ocrolib.numpy2narray(input) out = ocrolib.iulib.bytearray() ocrolib.iulib.extract_subimage(out, iulibbin, x0, iy0, x1, iy1) return ocrolib.narray2numpy(out) class OcropusBase(node.Node): """ Wrapper around Ocropus component interface. """ abstract = True _comp = None def __init__(self, **kwargs): """ Initialise with the ocropus component. """ super(OcropusBase, self).__init__(**kwargs) def _set_p(self, p, v): """ Set a component param. """ self._comp.pset(makesafe(p), makesafe(v)) def __getstate__(self): """ Used when pickled. Here we simply ignore the internal component, which itself contains an unpickleable C++ type. """ return super(OcropusBase, self).__dict__ def validate(self): """ Check state of the inputs. """ self.logger.debug("%s: validating...", self) super(OcropusBase, self).validate() for i in range(len(self._inputs)): if self._inputs[i] is None: raise exceptions.ValidationError("missing input '%d'" % i, self) @nodeutils.ClassProperty @classmethod def parameters(cls): """ Get parameters from an Ocropus Node. """ def makesafe(v): if v is None: return 0 return v p = [] for i in range(cls._comp.plength()): n = cls._comp.pname(i) p.append(dict( name=n, value=makesafe(cls._comp.pget(n)), )) return p class OcropusBinarizeBase(OcropusBase, base.BinaryPngWriterMixin): """ Binarize an image with an Ocropus component. """ abstract = True stage = stages.BINARIZE intypes = [ocrolib.numpy.ndarray] outtype = ocrolib.numpy.ndarray def process(self, input): """ Perform binarization on an image. input: a grayscale image. return: a binary image. """ # NB. The Ocropus binarize function # returns a tuple: (binary, gray) # we ignore the latter. try: out = self._comp.binarize(input, type="B")[0] except (IndexError, TypeError, ValueError), err: raise OcropusNodeError(err.message, self) return out class OcropusSegmentPageBase(OcropusBase, base.JSONWriterMixin): """ Segment an image using Ocropus. """ abstract = True stage = stages.PAGE_SEGMENT intypes = [ocrolib.numpy.ndarray] outtype = dict def null_data(self): """ Return an empty list when ignored. """ return dict(columns=[], lines=[], paragraphs=[]) def process(self, input): """ Segment a binary image. input: a binary image. return: a dictionary of box types: lines paragraphs columns images """ out = dict(bbox=[0, 0, input.shape[1], input.shape[0]], columns=[], lines=[], paragraphs=[]) try: page_seg = self._comp.segment(input) except (IndexError, TypeError, ValueError), err: raise OcropusNodeError(err.message, self) regions = ocrolib.RegionExtractor() exfuncs = dict(lines=regions.setPageLines, paragraphs=regions.setPageParagraphs) # NB: These coordinates are relative to the TOP of the page # for some reason for box, func in exfuncs.iteritems(): func(page_seg) for i in range(1, regions.length()): out[box].append(( regions.x0(i), regions.y0(i), regions.x1(i), regions.y1(i))) return out class OcropusGrayscaleFilterBase(OcropusBase, base.GrayPngWriterMixin): """ Filter a binary image. """ abstract = True stage = stages.FILTER_GRAY intypes = [ocrolib.numpy.ndarray] outtype = ocrolib.numpy.ndarray def process(self, input): try: out = self._comp.cleanup_gray(input, type="B") except (IndexError, TypeError, ValueError), err: raise OcropusNodeError(err.message, self) return out class OcropusBinaryFilterBase(OcropusBase, base.BinaryPngWriterMixin): """ Filter a binary image. """ abstract = True stage = stages.FILTER_BINARY intypes = [ocrolib.numpy.ndarray] outtype = ocrolib.numpy.ndarray def process(self, input): try: out = self._comp.cleanup(input, type="B") except (IndexError, TypeError, ValueError), err: raise OcropusNodeError(err.message, self) return out class OcropusRecognizer(base.LineRecognizerNode): """ Ocropus Native text recogniser. """ @nodeutils.ClassProperty @classmethod def parameters(cls): return [ dict( name="character_model", value="Ocropus Default Char", choices=[m.name for m in \ OcrModel.objects.filter(app="ocropus", type="char")], ), dict( name="language_model", value="Ocropus Default Lang", choices=[m.name for m in \ OcrModel.objects.filter(app="ocropus", type="lang")], ) ] def validate(self): """ Check we're in a good state. """ super(OcropusRecognizer, self).validate() if self._params.get("character_model", "").strip() == "": raise exceptions.ValidationError("no character model given.", self) if self._params.get("language_model", "").strip() == "": raise exceptions.ValidationError("no language model given: %s" % self._params, self) def init_converter(self): """ Load the line-recogniser and the lmodel FST objects. """ try: self._linerec = ocrolib.RecognizeLine() cmodpath = utils.lookup_model_file(self._params["character_model"]) self.logger.debug("Loading char mod file: %s" % cmodpath) self._linerec.load_native(cmodpath) self._lmodel = ocrolib.OcroFST() lmodpath = utils.lookup_model_file(self._params["language_model"]) self.logger.debug("Loading lang mod file: %s" % lmodpath) self._lmodel.load(lmodpath) except (StandardError, RuntimeError): raise @utils.check_aborted def get_transcript(self, line): """ Run line-recognition on an ocrolib.iulib.bytearray images of a single line. """ if not hasattr(self, "_lmodel"): self.init_converter() fst = self._linerec.recognizeLine(line) # NOTE: This returns the cost - not currently used out, _ = ocrolib.beam_search_simple(fst, self._lmodel, 1000) return out class Manager(object): """ Interface to ocropus. """ _use_types = ( "IBinarize", "ISegmentPage", "ICleanupGray", "ICleanupBinary", ) _ignored = ( "StandardPreprocessing", ) @classmethod def get_components(cls, oftypes=None, withnames=None, exclude=None): """ Get a datastructure contraining all Ocropus components (possibly of a given type) and their default parameters. """ return cls._get_native_components(oftypes, withnames, exclude=exclude) @classmethod def get_node(cls, name, **kwargs): """ Get a node by the given name. """ klass = cls.get_node_class(name) return klass(**kwargs) @classmethod def get_node_class(cls, name, comps=None): """ Get a node class for the given name. """ # if we get a qualified name like # Ocropus::Recognizer, remove the # path, since we ASSume that we're # looking in the right module if name.find("::") != -1: name = name.split("::")[-1] # FIXME: This clearly sucks comp = None if comps is not None: for c in comps: if name == c.__class__.__name__: comp = c break else: comp = getattr(ocrolib, name)() if node is None: raise NoSuchNodeException(name) base = OcropusBase if comp.interface() == "IBinarize": base = OcropusBinarizeBase elif comp.interface() == "ISegmentPage": base = OcropusSegmentPageBase elif comp.interface() == "ICleanupGray": base = OcropusGrayscaleFilterBase elif comp.interface() == "ICleanupBinary": base = OcropusBinaryFilterBase else: raise UnknownOcropusNodeType("%s: '%s'" % (name, comp.interface())) # this is a bit weird # create a new class with the name '<OcropusComponentName>Node' # and the component as the inner _comp attribute return type("%s" % comp.__class__.__name__, (base,), dict( _comp=comp, __module__=__name__ )) @classmethod def get_nodes(cls, *oftypes, **kwargs): """ Get nodes of the given type. """ rawcomps = cls.get_components(oftypes=cls._use_types, exclude=cls._ignored) return [cls.get_node_class(comp.__class__.__name__, comps=rawcomps) \ for comp in rawcomps] @classmethod def _get_native_components(cls, oftypes=None, withnames=None, exclude=None): """ Get a datastructure contraining all Ocropus native components (possibly of a given type) and their default parameters. """ out = [] clist = ocrolib.ComponentList() for i in range(clist.length()): ckind = clist.kind(i) if oftypes and not \ ckind.lower() in [c.lower() for c in oftypes]: continue cname = clist.name(i) if withnames and not \ cname.lower() in [n.lower() for n in withnames]: continue if exclude and cname.lower() in [n.lower() for n in exclude]: continue compdict = dict(name=cname, type=ckind, parameters=[]) # TODO: Fix this heavy-handed exception handling which is # liable to mask genuine errors - it's needed because of # various inconsistencies in the Python/native component # wrappers. try: comp = getattr(ocrolib, cname)() except (AttributeError, AssertionError, IndexError): continue out.append(comp) return out # dynamically generate new nodes classes Manager.get_nodes()
Python
""" Image transformation nodes based on the Python Image Library (PIL). """ from __future__ import absolute_import import os from nodetree import node, exceptions import numpy from PIL import Image from . import base from .. import stages def image2array(im): if im.mode not in ("L", "F"): raise ValueError, "can only convert single-layer images" if im.mode == "L": a = numpy.fromstring(im.tostring(), numpy.uint8) else: a = numpy.fromstring(im.tostring(), numpy.float32) a.shape = im.size[1], im.size[0] return a def array2image(a): if a.dtype == numpy.uint8: mode = "L" elif a.dtype == numpy.float32: mode = "F" else: raise ValueError, "unsupported image mode" return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring()) class RGBFileIn(base.ImageGeneratorNode, base.BinaryPngWriterMixin): """Read a file with PIL.""" stage = stages.INPUT intypes = [] outtype = numpy.ndarray parameters = [dict(name="path", value="", type="filepath")] def process(self): path = self._params.get("path") if not os.path.exists(path): return self.null_data() return numpy.asarray(Image.open(path)) @classmethod def reader(cls, handle): return numpy.asarray(Image.open(handle)) @classmethod def writer(cls, handle, data): pil = Image.fromarray(data) pil.save(handle, "PNG") class PilScale(node.Node, base.BinaryPngWriterMixin): """Scale an image with PIL""" stage = stages.FILTER_GRAY intypes = [numpy.ndarray] outtype = numpy.ndarray parameters = [ dict(name="scale", value=1.0), dict(name="filter", value="NEAREST", choices=[ "NEAREST", "BILINEAR", "BICUBIC", "ANTIALIAS" ]), ] def validate(self): super(PilScale, self).validate() if not self._params.get("scale"): raise exceptions.ValidationError("'scale' is not set", self) try: num = float(self._params.get("scale")) except ValueError: raise exceptions.ValidationError("'float' must be a float", self) def process(self, image): """Scale image.""" scale = float(self._params.get("scale")) pil = Image.fromarray(image) dims = [int(dim * scale) for dim in pil.size] scaled = pil.resize(tuple(dims), getattr(Image, self._params.get("filter"))) return numpy.asarray(scaled.convert("L")) class PilCrop(node.Node, base.BinaryPngWriterMixin): """Crop an image with PIL.""" stage = stages.FILTER_GRAY intypes = [numpy.ndarray] outtype = numpy.ndarray parameters = [ dict(name="x0", value=-1), dict(name="y0", value=-1), dict(name="x1", value=-1), dict(name="y1", value=-1), ] def process(self, input): """ Crop an image, using IULIB. If any of the parameters are -1 or less, use the outer dimensions. """ x0, y0 = 0, 0 y1, x1 = input.shape try: x0 = int(self._params.get("x0", -1)) if x0 < 0: x0 = 0 except TypeError: pass try: y0 = int(self._params.get("y0", -1)) if y0 < 0: y0 = 0 except TypeError: pass try: x1 = int(self._params.get("x1", -1)) if x1 < 0: x1 = input.shape[1] except TypeError: pass try: y1 = int(self._params.get("y1", -1)) if y1 < 0: y1 = input.shape[0] except TypeError: pass pil = Image.fromarray(input) p2 = pil.crop((x0, y0, x1, y1)) self.logger.debug("Pil crop: %s", p2) n = numpy.asarray(p2.convert("L")) self.logger.debug("Numpy: %s", n) return n class RGB2Gray(node.Node, base.GrayPngWriterMixin): """ Convert (roughly) between a color image and BW. """ stage = stages.FILTER_GRAY intypes = [numpy.ndarray] outtype = numpy.ndarray parameters = [] def process(self, image): pil = Image.fromarray(image) return numpy.asarray(pil.convert("L")) class PilTest(node.Node): """ Test PIL OPs. """ stage = stages.FILTER_BINARY def validate(self): super(PilTest, self).validate() def process(self, image): """ No-op, for now. """ return image
Python
""" Custom types for node input/output. """ class HocrString(unicode): pass
Python
""" Object representing a batch operation, consisting of one or more OcrTasks. """ import datetime from django.db import models from django.contrib.auth.models import User from tagging.fields import TagField from ocradmin.projects.models import Project class Batch(models.Model): """ OCR Batch object. """ user = models.ForeignKey(User, related_name="batches") name = models.CharField(max_length=255) project = models.ForeignKey(Project, related_name="batches") script = models.TextField() task_type = models.CharField(max_length=100) description = models.TextField(blank=True) tags = TagField() created_on = models.DateTimeField(editable=False) updated_on = models.DateTimeField(blank=True, null=True, editable=False) def __unicode__(self): """ Unicode representation. """ return self.name def save(self): """ Override save to add timestamps. """ if not self.id: self.created_on = datetime.datetime.now() else: self.updated_on = datetime.datetime.now() super(Batch, self).save() def username(self): return self.user.username def subtasks(self): """ Alias for 'tasks', for use when serializing """ return self.tasks.all() def is_complete(self): """ Check whether all tasks are done. """ numrunning = self.tasks.exclude( status__in=("SUCCESS", "FAILURE", "ABORTED")).count() return numrunning == 0 def task_count(self): """ Return the number of contained tasks. """ return self.tasks.count() def estimate_progress(self): """ Aggregated percentage of how many tasks are complete. This is going to be a bit of an estimate and does not take account of stages where progress is difficult to measure, i.e. segmentation. """ totallines = 0 percentdone = 0 runningtasks = 0 tasks = self.tasks.all() for t in tasks: totallines += t.lines or 50 if totallines == 0: return 0 for t in tasks: lines = t.lines or 50 weight = float(lines) / float(totallines) if t.status in ("FAILURE", "ABORTED", "SUCCESS"): percentdone += (weight * 100) else: runningtasks += 1 percentdone += (weight * t.progress) done = min(100.0, percentdone) # if there are running tasks, never go above # 99% if runningtasks > 0: done -= 1.0 return max(0, done) def errored_tasks(self): """ Get all errored tasks. """ return self.tasks.filter(status="FAILURE") def inspection_url(self): """ URL for viewing results """ if self.task_type == "compare.groundtruth": return "/training/comparison/%d/" % self.pk elif self.task_type == "fedora.ingest": return "#" else: return "/batch/transcript/%d/" % self.pk def get_absolute_url(self): """URL to view an object detail""" return "/batch/show/%d/" % self.pk def get_delete_url(self): """url to update an object detail""" return "/batch/delete/%d/" % self.pk @classmethod def get_list_url(cls): """URL to view the object list""" return "/batch/list/"
Python
from django.conf.urls.defaults import * from ocradmin.batch import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('', (r'^abort/(?P<batch_pk>\d+)/?$', login_required(views.abort_batch)), (r'^create/?$', login_required(views.create)), (r'^delete/(?P<pk>\d+)/?$', login_required(views.batchdelete)), (r'^export_options/(?P<batch_pk>\d+)/?$', login_required(views.export_options)), (r'^latest/?$', login_required(views.latest)), (r'^list/?$', login_required(views.batchlist)), (r'^new/?$', login_required(views.new)), (r'^results/(?P<batch_pk>\d+)/?$', login_required(views.results)), (r'^results/(?P<batch_pk>\d+)/(?P<page_index>\d+)/?$', login_required(views.page_results)), (r'^retry/(?P<batch_pk>\d+)/?$', login_required(views.retry)), (r'^retry_errored/(?P<batch_pk>\d+)/?$', login_required(views.retry_errored)), (r'^show/(?P<batch_pk>\d+)/?$', login_required(views.show)), (r'^test/?$', login_required(views.test)), (r'^upload_files/?$', login_required(views.upload_files)), )
Python
from django.template import Library register = Library() @register.filter def get_range( value ): """ Filter - returns a list containing range made from given value Usage (in template): <ul>{% for i in 3|get_range %} <li>{{ i }}. Do something</li> {% endfor %}</ul> Results with the HTML: <ul> <li>0. Do something</li> <li>1. Do something</li> <li>2. Do something</li> </ul> Instead of 3 one may use the variable set in the views """ return range(value)
Python
from batch_tests import *
Python
""" OCR batch tests. """ import os import re import shutil from django.test import TestCase from django.test.client import Client from django.contrib.auth.models import User from django.conf import settings from ocradmin.presets.models import Preset from ocradmin.batch.models import Batch from ocradmin.ocrtasks.models import OcrTask from ocradmin.projects.models import Project from ocradmin.core.tests import testutils from django.utils import simplejson as json TESTFILE = "etc/simple.png" SCRIPT1 = "nodelib/scripts/valid/tesseract.json" SCRIPT2 = "nodelib/scripts/valid/ocropus.json" class BatchTest(TestCase): fixtures = [ "ocrtasks/fixtures/test_task.json", "transcripts/fixtures/test_transcript.json", "ocrmodels/fixtures/test_fixtures.json", "projects/fixtures/test_fixtures.json", "presets/fixtures/test_fixtures.json", "batch/fixtures/test_batch.json"] def setUp(self): """ Setup OCR tests. Creates a test user. """ with open(SCRIPT1, "r") as s1: self.script1 = s1.read() with open(SCRIPT2, "r") as s2: self.script2 = s2.read() testutils.symlink_model_fixtures() try: os.makedirs("media/files/test_user/test") except OSError, (errno, strerr): if errno == 17: pass try: os.symlink(os.path.abspath(TESTFILE), "media/files/test_user/test/%s" % os.path.basename(TESTFILE)) except OSError, (errno, strerr): if errno == 17: pass self.testuser = User.objects.create_user("test_user", "test@testing.com", "testpass") self.client = Client() self.client.login(username="test_user", password="testpass") self.project = Project.objects.all()[0] self.client.get("/projects/load/%s/" % self.project.pk) # create a document in project storage self.doc = self.project.get_storage().create_document("Test doc") with open(TESTFILE, "rb") as fhandle: self.doc.image_content = fhandle self.doc.image_mimetype = "image/png" self.doc.image_label = os.path.basename(TESTFILE) self.doc.save() def tearDown(self): """ Cleanup a test. """ self.testuser.delete() shutil.rmtree("media/files/test_user") self.doc.delete() def test_batch_new(self): """ Test the convert view as a standard GET (no processing.) """ self.assertEqual(self.client.get("/batch/new").status_code, 200) def test_batch_create(self): """ Test OCRing with minimal parameters. """ self._test_batch_action() def test_results_action(self): """ Test fetching task results. Assume a batch with pk 1 exists. """ pk = self._test_batch_action() r = self.client.get("/batch/results/%s" % pk) self.assert_(r.content, "No content returned") content = json.loads(r.content) self.assertEqual( content[0]["fields"]["tasks"][0]["fields"]["page_name"], self.doc.pid) return pk def test_page_results_page_action(self): """ Test fetching task results. Assume a page with offset 0 exists. """ pk = self._test_batch_action() r = self.client.get("/batch/results/%s/0/" % pk) self.assert_(r.content, "No content returned") content = json.loads(r.content) self.assertEqual( content[0]["fields"]["page_name"], self.doc.pid) def test_save_transcript(self): """ Test fetching task results. Assume a page with offset 0 exists. """ pk = self._test_batch_action() r = self.client.get("/batch/results/%s/0/" % pk) self.assert_(r.content, "No content returned") content = json.loads(r.content) self.assertEqual( content[0]["fields"]["page_name"], self.doc.pid) def test_show_action(self): """ Test viewing batch details. """ pk = self._test_batch_action() r = self.client.get("/batch/show/%s/" % pk) self.assertEqual(r.status_code, 200) def test_delete_action(self): """ Test viewing batch details. """ before = Batch.objects.count() r = self.client.post("/batch/delete/1/", follow=True) self.assertRedirects(r, "/batch/list/") self.assertEqual(before, Batch.objects.count() + 1) def test_builder_edit_task(self): task = OcrTask.objects.all()[0] r = self.client.get("/presets/builder/%s/" % task.page_name) self.assertEqual(r.status_code, 200) def _test_batch_action(self, params=None, headers={}): """ Testing actually OCRing a file. """ preset = Preset.objects.filter(profile__isnull=False)[0] if params is None: params = dict( name="Test Batch", user=self.testuser.pk, project=self.project.pk, task_type="run.batchitem", pid=self.doc.pid, preset=preset.id, ) r = self._get_batch_response(params, headers) # check the POST redirected as it should self.assertEqual(r.redirect_chain[0][1], 302) pkmatch = re.match(".+/batch/show/(\d+)/?", r.redirect_chain[0][0]) self.assertTrue(pkmatch != None) return pkmatch.groups()[0] def test_file_upload(self): """ Test uploading files to the server. """ with file(TESTFILE, "rb") as fh: params = {} params["file1"] = fh headers = {} r = self.client.post("/batch/upload_files/", params, **headers) #fh.close() content = json.loads(r.content) self.assertEqual(content, [os.path.join(self.project.slug, os.path.basename(TESTFILE))]) def _get_batch_response(self, params={}, headers={}): """ Post images for conversion with the given params, headers. """ headers["follow"] = True return self.client.post("/batch/create/", params, **headers)
Python
""" Celery tasks for Batch operations. """ import os import shutil from celery.contrib.abortable import AbortableTask from celery.task.sets import subtask from ocradmin.ocrtasks.decorators import register_handlers from ocradmin.ocrtasks.utils import get_progress_callback, get_abort_callback from django.utils import simplejson as json from nodetree import cache, node, script, exceptions from django.conf import settings from ocradmin.nodelib import stages, nodes from ocradmin.projects.models import Project from ocradmin.documents import status @register_handlers class DocBatchScriptTask(AbortableTask): name = "run.batchitem" ignore_result = True def run(self, project_pk, pid, scriptjson): """ Runs the convert action. """ project = Project.objects.get(pk=project_pk) storage = project.get_storage() doc = storage.get(pid) logger = self.get_logger() logger.debug("Running Document Batch Item: %s") # try and delete the existing binary dzi file dzipath = storage.document_attr_dzi_path(doc, "binary") dzifiles = os.path.splitext(dzipath)[0] + "_files" try: os.unlink(dzipath) shutil.rmtree(dzifiles) except OSError: pass progress_handler = get_progress_callback(self.request.id) abort_handler = get_abort_callback(self.request.id) progress_handler(0) tree = script.Script(json.loads(scriptjson), nodekwargs=dict( logger=logger, abort_func=abort_handler, progress_func=progress_handler)) logger.debug("Running tree: %s", json.dumps(tree.serialize(), indent=2)) try: # write out the binary... this should cache it's input os.environ["NODETREE_WRITE_FILEOUT"] = "1" doc.script_content = json.dumps(tree.serialize(), indent=2) doc.script_label = "%s.json" % os.path.splitext(doc.label)[0] doc.script_mimetype = "application/json" # set document metadata to indicate it's an OCR "draft" doc.ocr_status = status.RUNNING doc.save() # process the nodes [t.eval() for t in tree.get_terminals()] except Exception, err: logger.exception("Unhandled exception: %s", err) # set document metadata to indicate it's an OCR "draft" doc.ocr_status = status.ERROR else: # set document metadata to indicate it's an OCR "draft" doc.ocr_status = status.UNCORRECTED finally: doc.save()
Python
""" Batch-related views. """ import os import glob import tarfile import StringIO from django import forms from django.contrib.auth.decorators import login_required from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from django.conf import settings from django.db import transaction from django.http import HttpResponse, HttpResponseRedirect, \ HttpResponseServerError from django.shortcuts import render, get_object_or_404 from django.utils import simplejson as json from django.utils.encoding import smart_str from django.views.decorators.csrf import csrf_exempt from ocradmin.core import generic_views as gv from ocradmin.core import utils as ocrutils from ocradmin.core.decorators import project_required, saves_files from ocradmin.batch.models import Batch from ocradmin.ocrtasks.models import OcrTask from ocradmin.core.views import AppException from ocradmin.presets.models import Preset from ocradmin.nodelib import stages from nodetree import script, exceptions class BatchForm(forms.ModelForm): """ New project form. """ def __init__(self, *args, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) # change a widget attribute: self.fields['description'].widget.attrs["rows"] = 2 self.fields['description'].widget.attrs["cols"] = 40 class Meta: model = Batch exclude = ["script", "created_on", "updated_on"] widgets = dict( user=forms.HiddenInput(), project=forms.HiddenInput(), task_type=forms.HiddenInput(), ) class BatchListView(gv.GenericListView): """Specialised batch list view. Only returns batches for the current project.""" def get_queryset(self): qset = super(BatchListView, self).get_queryset() if not hasattr(self.request, "project"): return qset return qset.filter(project=self.request.project) batchlist = project_required(BatchListView.as_view( model=Batch, page_name="OCR Batches", fields=["name", "description", "user", "task_type", "created_on", "tasks.count"],)) batchdelete = gv.GenericDeleteView.as_view( model=Batch, page_name="Delete OCR Batch", success_url="/batch/list/",) @login_required @project_required def new(request): """ Present a new batch form. """ taskname = "run.batchitem" template = "batch/new.html" if not request.is_ajax() \ else "batch/includes/new_form.html" return render(request, template, _new_batch_context(request, taskname)) @project_required @transaction.commit_on_success def create(request): """Create a batch for document files in project storage.""" taskname = "run.batchitem" preset = get_object_or_404(Preset, pk=request.POST.get("preset", 0)) pids = request.POST.getlist("pid") form = BatchForm(request.POST) if not request.method == "POST" or not form.is_valid() or not pids: return render( request, "batch/new.html", _new_batch_context(request, taskname, form) ) batch = form.instance batch.script = preset.data batch.save() try: dispatch_batch(batch, pids) except StandardError: transaction.rollback() raise transaction.commit() return HttpResponseRedirect("/batch/show/%s/" % batch.pk) def dispatch_batch(batch, pids): """Dispatch a batch task.""" # hack - sort the incoming list of pids storage = batch.project.get_storage() pid = storage.sort_pidlist(storage.namespace, pids) options = dict(loglevel=60, retries=2) ocrtasks = [] for pid in pids: docscript = script_for_document(batch.script, batch.project, pid) tid = OcrTask.get_new_task_id() args = (batch.project.pk, pid, docscript,) kwargs = dict() ocrtask = OcrTask( task_id=tid, user=batch.user, batch=batch, project=batch.project, page_name=pid, # FIXME: This is wrong task_name=batch.task_type, status="INIT", args=args, kwargs=kwargs, ) ocrtask.save() ocrtasks.append(ocrtask) OcrTask.run_celery_task_multiple(batch.task_type, ocrtasks, **options) def results(request, batch_pk): """ Get results for a taskset. """ batch = get_object_or_404(Batch, pk=batch_pk) try: start = max(0, int(request.GET.get("start", 0))) except ValueError: start = 0 try: limit = max(1, int(request.GET.get("limit", 25))) except ValueError: limit = 25 statuses = request.GET.getlist("status") name = request.GET.get("name") if "ALL" in statuses: statuses = None response = HttpResponse(mimetype="application/json") json.dump(_serialize_batch(batch, start, limit, statuses, name), response, cls=DjangoJSONEncoder, ensure_ascii=False) return response def page_results(request, batch_pk, page_index): """ Get the results for a single page. """ batch = get_object_or_404(Batch, pk=batch_pk) try: page = batch.tasks.all().order_by("page_name")[int(page_index)] except Batch.DoesNotExist: raise pyserializer = serializers.get_serializer("python")() response = HttpResponse(mimetype="application/json") taskssl = pyserializer.serialize( [page], excludes=("transcripts", "args", "kwargs",), ) json.dump(taskssl, response, cls=DjangoJSONEncoder, ensure_ascii=False) return response @project_required def latest(request): """ View the latest batch. """ try: batch = Batch.objects.filter( user=request.user, project=request.session["project"] ).order_by("-created_on")[0] except (Batch.DoesNotExist, IndexError): return HttpResponseRedirect("/batch/list") return _show_batch(request, batch) @project_required def show(request, batch_pk): """ View a batch. """ batch = get_object_or_404( Batch, pk=batch_pk, project=request.session["project"] ) return _show_batch(request, batch) @csrf_exempt @project_required @saves_files def upload_files(request): """ Upload files to the server for batch-processing. """ mimetype = "application/json" if not request.POST.get("_iframe") \ else "text/html" relpath = request.session["project"].slug try: paths = _handle_upload(request, request.output_path) except AppException, err: return HttpResponse(json.dumps({"error": err.message}), mimetype="application/json") if not paths: return HttpResponse( json.dumps({"error": "no valid images found"}), mimetype="application/json") pathlist = [os.path.join(relpath, os.path.basename(p)) for p in paths] return HttpResponse(json.dumps(pathlist), mimetype=mimetype) def _show_batch(request, batch): """ View a (passed-in) batch. """ template = "batch/show.html" if not request.is_ajax() \ else "batch/includes/show_batch.html" fields = ["name","tags", "description","created_on"] context = dict(batch=batch, fields=fields) return render(request, template, context) @transaction.commit_on_success def abort_batch(request, batch_pk): """ Abort an entire batch. """ batch = get_object_or_404(Batch, pk=batch_pk) for task in batch.tasks.all(): task.abort() transaction.commit() if request.is_ajax(): return HttpResponse(json.dumps({"ok": True}), mimetype="application/json") else: return HttpResponseRedirect("/batch/show/%s/" % batch_pk) @transaction.commit_on_success def retry(request, batch_pk): """ Retry all tasks in a batch. """ batch = get_object_or_404(Batch, pk=batch_pk) for task in batch.tasks.all(): task.retry() transaction.commit() if request.is_ajax(): return HttpResponse(json.dumps({"ok": True}), mimetype="application/json") else: return HttpResponseRedirect("/batch/show/%s/" % batch_pk) @transaction.commit_on_success def retry_errored(request, batch_pk): """ Retry all errored tasks in a batch. """ batch = get_object_or_404(Batch, pk=batch_pk) for task in batch.errored_tasks(): task.retry() transaction.commit() if request.is_ajax(): return HttpResponse(json.dumps({"ok": True}), mimetype="application/json") else: return HttpResponseRedirect("/batch/show/%s/" % batch_pk) def test(request): """ Test action """ return render(request, "batch/test.html", {}) def export_options(request, batch_pk): """ Setup export. """ batch = get_object_or_404(Batch, pk=batch_pk) formats = {"text": "Plain Text", "json": "JSON", "hocr": "HOCR HTML"} template = "batch/export_options.html" if not request.is_ajax() \ else "batch/includes/export_form.html" context = dict( batch=batch, formats=formats ) return render(request, template, context) def _serialize_batch(batch, start=0, limit=25, statuses=None, name=None): """ Hack around the problem of serializing an object AND it's child objects. """ taskqset = batch.tasks.all() if statuses: taskqset = batch.tasks.filter(status__in=statuses) if name: taskqset = taskqset.filter(page_name__icontains=name) task_count = taskqset.count() pyserializer = serializers.get_serializer("python")() batchsl = pyserializer.serialize( [batch], extras=("estimate_progress", "is_complete",), relations={ "user": {"fields": ("username")}, "comparison": {"fields": ()}, }, ) taskssl = pyserializer.serialize( taskqset.order_by("page_name")[start:start + limit], excludes=("args", "kwargs", "traceback",), ) batchsl[0]["fields"]["tasks"] = taskssl batchsl[0]["extras"]["task_count"] = task_count return batchsl def _new_batch_context(request, tasktype, form=None): """ Template variables for a new batch form. """ # add available seg and bin presets to the context # work out the name of the batch - start with how # many other batches there are in the projects project = request.project batchname = "%s - Batch %d" % (project.name, project.batches.count() + 1) if form is None: form = BatchForm(initial=dict(name=batchname, user=request.user, project=project, task_type=tasktype)) docs = project.get_storage().list() presets = Preset.objects.filter(profile__isnull=False).order_by("name") return dict(form=form, presets=presets, docs=docs) def _get_batch_file_paths(request): """ Extract the full file paths from the POST data. """ dirpath = os.path.relpath(os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH )) filenames = request.POST.get("files", "").split(",") return [os.path.join(dirpath, f) for f in sorted(filenames)] def _handle_upload(request, outdir): """ Save files and extract parameters. How this happens depends on how the file was send - either multipart of as the whole POST body. """ if request.GET.get("inlinefile"): return _handle_streaming_upload(request, outdir) return _handle_multipart_upload(request, outdir) def _handle_streaming_upload(request, outdir): """ Handle an upload where the params are in GET and the whole of the POST body consists of the file. """ fpath = os.path.join(outdir, request.GET.get("inlinefile")) if not os.path.exists(outdir): os.makedirs(outdir, 0777) tmpfile = file(fpath, "wb") tmpfile.write(request.raw_post_data) tmpfile.close() return [fpath] def _handle_multipart_upload(request, outdir): """ Handle an upload where the file data is multipart encoded in the POST body, along with the params. """ if request.POST.get("png"): paths = [ocrutils.media_url_to_path(request.POST.get("png"))] else: paths = ocrutils.save_ocr_images(request.FILES.iteritems(), outdir) return paths def script_for_page_file(scriptjson, filepath, writepath): """ Modify the given script for a specific file. """ tree = script.Script(json.loads(scriptjson)) validate_batch_script(tree) # get the input node and replace it with out path input = tree.get_nodes_by_attr("stage", stages.INPUT)[0] input.set_param("path", filepath) # attach a fileout node to the binary input of the recognizer and # save it as a binary file rec = tree.get_nodes_by_attr("stage", stages.RECOGNIZE)[0] outpath = ocrutils.get_binary_path(filepath, writepath) outbin = tree.add_node("util.FileOut", "OutputBinary", params=[ ("path", os.path.abspath(outpath).encode()), ("create_dir", True)]) outbin.set_input(0, rec.input(0)) return json.dumps(tree.serialize(), indent=2) def script_for_document(scriptjson, project, pid): """ Modify the given script for a specific file. """ doc = project.get_storage().get(pid) tree = script.Script(json.loads(scriptjson)) validate_batch_script(tree) # get the input node and replace it with out path binname = ".bin".join(os.path.splitext(doc.image_label)) recname = os.path.splitext(doc.image_label)[0] + ".html" oldinput = tree.get_nodes_by_attr("stage", stages.INPUT)[0] rec = tree.get_nodes_by_attr("stage", stages.RECOGNIZE)[0] # assume the binary is the first input to the recogniser bin = rec.input(0) input = tree.new_node("storage.DocImageFileIn", doc.image_label, params=[("project", project.pk), ("pid", pid)]) recout = tree.add_node("storage.DocWriter", recname, params=[ ("project", project.pk), ("pid", pid), ("attribute", "transcript")]) binout = tree.add_node("storage.DocWriter", binname, params=[ ("project", project.pk), ("pid", pid), ("attribute", "binary")]) tree.replace_node(oldinput, input) recout.set_input(0, rec) binout.set_input(0, bin) return json.dumps(tree.serialize(), indent=2) def validate_batch_script(script): """Check everything is A-OK before starting.""" inputs = script.get_nodes_by_attr("stage", stages.INPUT) if not inputs: raise exceptions.ScriptError("No input stages found in script") if len(inputs) > 1: raise exceptions.ScriptError("More than one input found for batch script") recs = script.get_nodes_by_attr("stage", stages.RECOGNIZE) if not recs: raise exceptions.ScriptError("No recognize stages found in script")
Python
from django.db import models # Create your models here.
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^ls/?$', 'ocradmin.filebrowser.views.ls'), (r'^explore/?$', 'ocradmin.filebrowser.views.explore'), )
Python
# App for browsing the server. import os import time from stat import * from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.utils import simplejson from django.utils.simplejson.encoder import JSONEncoder class ExtJsonEncoder(JSONEncoder): def default(self, c): # Handles generators and iterators if hasattr(c, '__iter__'): return [i for i in c] # Handles closures and functors if hasattr(c, '__call__'): return c() return JSONEncoder.default(self, c) def entry_info(path): """ Return info on a directory entry. """ try: flist = os.listdir(path) except OSError, (errno, strerr): return {"error": "%s: %s" % (strerr, path)} except Exception, e: print e return {"error": "%s: %s" % (e.message, path)} stats = [] for entry in flist: if entry.startswith("."): continue type = "unknown" st = os.stat(os.path.join(path, entry)) mode = st[ST_MODE] if S_ISDIR(mode): type = "dir" elif S_ISLNK(mode): type = "link" elif S_ISREG(mode): type = "file" stats.append(( entry, type, st.st_size, st.st_atime, st.st_mtime, st.st_ctime )) return stats @login_required def ls(request): """ List a directory on the server. """ dir = request.GET.get("dir", "") root = os.path.relpath(os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH )) fulldir = os.path.join(root, dir) response = HttpResponse(mimetype="application/json") simplejson.dump(entry_info(fulldir), response) return response @login_required def explore(request): """ Browse the server file system. """ return render_to_response("filebrowser/explore.html", {}, context_instance=RequestContext(request))
Python
from django.conf.urls.defaults import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.contrib.auth.views import login, logout admin.autodiscover() import djcelery urlpatterns = patterns('', # Static media (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^accounts/login', login), (r'^accounts/logout', logout, {"next_page": "/ocr/"}), (r'^/?$', include('ocradmin.core.urls')), (r'^ocr/?', include('ocradmin.core.urls')), (r'^filebrowser/?', include('ocradmin.filebrowser.urls')), (r'^documents/?', include('ocradmin.documents.urls')), (r'^batch/?', include('ocradmin.batch.urls')), (r'^ocrtasks/?', include('ocradmin.ocrtasks.urls')), (r'^ocrmodels/?', include('ocradmin.ocrmodels.urls')), (r'^presets/?', include('ocradmin.presets.urls')), (r'^profiles/?', include('ocradmin.presets.profileurls')), (r'^projects/?', include('ocradmin.projects.urls')), (r'^celery/?', include('djcelery.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: #(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), )
Python
""" Class for Asyncronous OCR jobs. Wraps tasks that run on the Celery queue with more metadata and persistance. """ import datetime import uuid from django.db import models from picklefield import fields from ocradmin.batch.models import Batch from ocradmin.projects.models import Project from django.contrib.auth.models import User import celery from celery.contrib.abortable import AbortableAsyncResult class OcrTask(models.Model): """ OCR Task object. """ STATUS_CHOICES = ( ("INIT", "Initialising"), ("PENDING", "Pending"), ("STARTED", "Started"), ("RETRY", "Retry"), ("SUCCESS", "Success"), ("FAILURE", "Failure"), ) user = models.ForeignKey(User) batch = models.ForeignKey(Batch, related_name="tasks", blank=True, null=True) project = models.ForeignKey(Project, related_name="tasks", blank=True, null=True) task_id = models.CharField(max_length=100) task_name = models.CharField(max_length=100) page_name = models.CharField(max_length=255) status = models.CharField(max_length=20, choices=STATUS_CHOICES) lines = models.IntegerField(blank=True, null=True) progress = models.FloatField(default=0.0, blank=True, null=True) args = fields.PickledObjectField(blank=True, null=True) kwargs = fields.PickledObjectField(blank=True, null=True) error = fields.PickledObjectField(blank=True, null=True) traceback = models.TextField(blank=True, null=True) created_on = models.DateTimeField(editable=False) updated_on = models.DateTimeField(blank=True, null=True, editable=False) def save(self): if not self.id: self.created_on = datetime.datetime.now() else: self.updated_on = datetime.datetime.now() super(OcrTask, self).save() def abort(self): """ Abort a task. """ if not self.is_active(): return asyncres = AbortableAsyncResult(self.task_id) if self.is_abortable(): asyncres.abort() if asyncres.is_aborted(): self.status = "ABORTED" self.save() celery.task.control.revoke(self.task_id, terminate=True, signal="SIGTERM") def run(self, task_name=None, asyncronous=True, untracked=False, **kwargs): """ Run the task in a blocking manner and return the sync object. """ tname = task_name if task_name is not None else self.task_name if untracked: tname = "_%s" % tname celerytask = celery.registry.tasks[tname] func = celerytask.apply_async if asyncronous else celerytask.apply kwds = self.kwargs kwds.update(kwargs) return func(args=self.args, **kwds) def retry(self): """ Retry the Celery job. """ if self.is_abortable(): self.abort() self.task_id = self.get_new_task_id() self.status = "RETRY" self.progress = 0 self.save() self.kwargs["task_id"] = self.task_id celerytask = celery.registry.tasks[self.task_name] celerytask.apply_async(args=self.args, **self.kwargs) def is_batch_task(self): """ Whether task is part of a batch. """ return self.batch is None def is_revokable(self): """ Whether or not a given status allows revoking (cancelling) a task. """ return self.status in ("INIT", "PENDING") def is_abortable(self): """ Whether we can cancel execution. """ return self.status in ("STARTED", "RETRY") def is_active(self): """ The task is running or awaiting running. """ return self.status in ("INIT", "PENDING", "RETRY", "STARTED") @classmethod def run_celery_task(cls, taskname, args, taskkwargs={}, **kwargs): """ Run an arbitary Celery task. """ if kwargs.get("untracked", False): taskname = "_%s" % taskname task = celery.registry.tasks[taskname] func = task.apply_async if kwargs.get("asyncronous", False) \ else task.apply return func(args=args, kwargs=taskkwargs, **kwargs) @classmethod def run_celery_task_multiple(cls, taskname, tasks, **kwargs): """ Optimised method for running multiple Celery tasks (uses the same celery publisher.) """ if len(tasks) == 0: return [] celerytask = celery.registry.tasks[taskname] publisher = celerytask.get_publisher(connect_timeout=5) func = celerytask.apply_async if kwargs.get("asyncronous", True) \ else celerytask.apply results = [] try: for task in tasks: results.append(func(args=task.args, kwargs=task.kwargs, publisher=publisher, task_id=task.task_id, **kwargs)) finally: publisher.close() publisher.connection.close() return results @classmethod def revoke_celery_task(cls, task_id, kill=True): """ Kill a Celery task. """ celery.task.control.revoke(task_id, terminate=kill, signal="SIGTERM") @classmethod def get_celery_result(cls, task_id): """ Proxy for fetching Celery results. """ return celery.result.AsyncResult(task_id) @classmethod def get_new_task_id(cls): """ Get a unique id for a new page task, given it's file path. """ return str(uuid.uuid1()) def get_absolute_url(self): """URL to view an object detail""" return "/ocrtasks/detail/%d/" % self.pk def get_delete_url(self): """url to update an object detail""" return "/ocrtasks/delete/%d/" % self.pk @classmethod def get_list_url(cls): """URL to view the object list""" return "/ocrtasks/list/"
Python
""" Utilities for managing OcrTasks. """ from celery.contrib.abortable import AbortableAsyncResult from models import OcrTask def get_progress_callback(task_id): """ Closure for generating a function that refers to a task id in outer scope. """ def progress_func(progress, lines=None): """ Set progress for the given task. """ task = OcrTask.objects.get(task_id=task_id) task.progress = progress if lines is not None: task.lines = lines task.save() return progress_func def get_abort_callback(task_id): """ Closure for generating a function that takes no params but uses a task_id in outer scope. """ def abort_func(): """ Check whether the task in question has been aborted. """ asyncres = AbortableAsyncResult(task_id) return asyncres.is_aborted() return abort_func
Python
""" Utils for testing the Ocr Task wrapper. """ from celery.contrib.abortable import AbortableTask from decorators import register_handlers @register_handlers class TestTask(AbortableTask): """ Dummy task for running tests on. """ name = "testing.test" max_retries = None def run(self, a, b, **kwargs): return a + b
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.test.client import Client from ocradmin.core import utils as ocrutils from models import OcrTask from testutils import TestTask class OcrTaskTest(TestCase): fixtures = ["test_batch.json", "test_task.json"] def setUp(self): """ Setup OCR tests. Creates a test user. """ self.testuser = User.objects.create_user("test_user", "test@testing.com", "testpass") self.client = Client() self.client.login(username="test_user", password="testpass") def tearDown(self): """ Cleanup a test. """ self.testuser.delete() def test_ocrtasks_view(self): """ Test basic list view """ self.assertEqual(self.client.get("/ocrtasks/").status_code, 200) def test_ocrtasks_show(self): """ Test viewing task details. """ self.assertEqual(self.client.get("/ocrtasks/show/1/").status_code, 200) def test_generic_task(self): """ Test creating a task. """ args = (4, 5) task, async = self._start_test_task(args) self.assertEqual("SUCCESS", task.status) def test_task_retry(self): """ Test retrying a task. """ args = (4, 5) task, async = self._start_test_task(args) t1 = task.task_id r = self.client.post("/ocrtasks/retry/%d/" % task.id) task = OcrTask.objects.get(pk=task.pk) t2 = task.task_id self.assertEqual(r.status_code, 200) self.assertNotEqual(t1, t2) def _start_test_task(self, args): """ Create a test task and return both the wrapper object and the async object. """ tid = OcrTask.get_new_task_id() kwargs = dict(task_id=tid, loglevel=60,) task = OcrTask( task_id=tid, user=self.testuser, page_name="test", task_name=TestTask.name, status="INIT", args=args, kwargs=kwargs, ) task.save() async = TestTask.apply_async(args, **kwargs) task = OcrTask.objects.get(task_id=tid) return task, async
Python
from django.conf.urls.defaults import * from ocradmin.ocrtasks import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('', (r'^list/?$', login_required(views.tasklist)), (r'^detail/(?P<pk>\d+)/$', login_required(views.taskdetail)), (r'^delete/(?P<pk>\d+)?/?$', login_required(views.taskdelete)), (r'^show/(?P<pk>\d+)/$', login_required(views.show)), (r'^abort/(?P<task_pk>\d+)/?$', login_required(views.abort)), (r'^retry/(?P<task_pk>\d+)/?$', login_required(views.retry)), (r'^/?$', login_required(views.tasklist)), )
Python
""" Callbacks to run when certain celery signals are recieved in response to the ConvertPageTask. """ from ocradmin.ocrtasks.models import OcrTask from celery.datastructures import ExceptionInfo def on_task_sent(**kwargs): """ Update the database when a task is sent to the broker. """ task = OcrTask.objects.get(task_id=kwargs.get("task_id")) task.status = "PENDING" task.save() def on_task_prerun(**kwargs): """ Update the database when a task is about to run. """ task = OcrTask.objects.get(task_id=kwargs.get("task_id")) task.status = "STARTED" task.save() def on_task_postrun(**kwargs): """ Update the database when a task is finished. Create a new transcript entry with the retval of the task. """ task = OcrTask.objects.get(task_id=kwargs.get("task_id")) retval = kwargs.get("retval") if not isinstance(retval, ExceptionInfo): task.status = "SUCCESS" task.save() def on_task_failure(**kwargs): """ Store the exception and traceback when a task fails. """ task = OcrTask.objects.get(task_id=kwargs.get("task_id")) task.error = kwargs.get("exception") task.traceback = kwargs.get("traceback") task.status = "FAILURE" task.save()
Python
""" Decorator for registering Celery fun classes with wrapper handlers. """ from celery.registry import tasks from celery.signals import task_sent, task_prerun, \ task_postrun, task_failure from handlers import on_task_sent, on_task_prerun, \ on_task_postrun, on_task_failure def register_handlers(taskclass): task_sent.connect(on_task_sent, tasks[taskclass.name]) task_prerun.connect(on_task_prerun, tasks[taskclass.name]) task_postrun.connect(on_task_postrun, tasks[taskclass.name]) task_failure.connect(on_task_failure, tasks[taskclass.name]) return taskclass
Python
""" View the task objects that are created when submitting a celery task and updated by it's subsequent signals. """ from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.utils import simplejson as json from ocradmin.ocrtasks.models import OcrTask from ocradmin.core import generic_views as gv tasklist = gv.GenericListView.as_view( model=OcrTask, page_name="OCR Tasks", fields=["id", "page_name", "user", "status", "progress", "created_on"],) taskdelete = gv.GenericDeleteView.as_view( model=OcrTask, page_name="Delete OCR Task", success_url="/ocrtasks/list/",) taskdetail = gv.GenericDetailView.as_view( model=OcrTask, page_name="OCR Task", fields=["id", "page_name", "lines", "user", "batch", "created_on", "updated_on", "status", "progress"]) def show(request, pk): """ Show task details. """ task = get_object_or_404(OcrTask, pk=pk) context = dict( object=task, fields=["id","page_name", "lines", "user", "batch", "created_on", "updated_on", "status", "progress"] ) template = "ocrtasks/show.html" if not request.is_ajax() \ else "ocrtasks/includes/task_info.html" return render(request, template, context) def retry(request, task_pk): """ Retry a batch task. """ task = get_object_or_404(OcrTask, pk=task_pk) out = {"ok": True} try: task.retry() except StandardError, err: out = {"error": err.message} return HttpResponse(json.dumps(out), mimetype="application/json") def abort(request, task_pk): """ Abort a batch task. """ task = get_object_or_404(OcrTask, pk=task_pk) out = {"ok": True} try: task.abort() except StandardError, err: out = {"error": err.message} return HttpResponse(json.dumps(out), mimetype="application/json")
Python
""" Generic OCR helper functions and wrapper around various OCRopus and Tesseract tools. """ import os import re from datetime import datetime import subprocess as sp from PIL import Image from django.utils import simplejson from django.conf import settings from HTMLParser import HTMLParser from xml.parsers import expat from ocradmin.nodelib.utils import HocrToTextHelper class HocrParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.data = {} self.linecnt = 0 self.currline = None self.boxre = re.compile(".*?bbox (\d+) (\d+) (\d+) (\d+)") self.idre = re.compile("line_(\d+)") self.gotpage = False def parsefile(self, filename): self.data = {} with open(filename, "r") as f: for line in f.readlines(): self.feed(line) return self.data def parse(self, string): self.data = {} self.feed(string) return self.data def handle_starttag(self, tag, attrs): if tag == "div" and not self.gotpage: for attr in attrs: if attr[0] == "class" and attr[1].find("ocr_page") != -1: self.gotpage = True self.data["lines"] = [] break if self.gotpage: for attr in attrs: if attr[0] == "title": boxmatch = self.boxre.match(attr[1]) if boxmatch: dims = [int(i) for i in boxmatch.groups()] self.data.update(bbox=[dims[0], dims[1], dims[2], dims[3]]) namematch = re.match("image \"([^\"]+)", attr[1]) if namematch: self.data["page"] = namematch.groups()[0] elif tag == "span": for attr in attrs: if attr[0] == "class" and attr[1].find("ocr_line") != -1: self.currline = {} if self.currline is not None: for attr in attrs: if attr[0] == "title": boxmatch = self.boxre.match(attr[1]) if boxmatch: dims = [int(i) for i in boxmatch.groups()] self.currline.update(bbox=[dims[0], dims[1], dims[2], dims[3]]) if attr[0] == "id": idmatch = self.idre.match(attr[1]) if idmatch: self.currline.update(index=int(idmatch.groups()[0])) def handle_data(self, data): if self.currline is not None: self.currline["text"] = data def handle_endtag(self, tag): if tag == "span" and self.currline is not None \ and self.currline.get("text"): if not self.currline.get("index"): self.currline["index"] = self.linecnt self.linecnt += 1 self.data["lines"].append(self.currline.copy()) self.currline = None class FinereaderXmlParser(): """ Quicky parser for Finereader XML. Schema: http://www.abbyy.com/FineReader_xml/FineReader8-schema-v2.xml """ def __init__(self): self.data = dict(lines=[], columns=[]) self.linecnt = 0 self.currline = None self.gotpage = False self.parser = expat.ParserCreate() self.parser.StartElementHandler = self.handle_starttag self.parser.EndElementHandler = self.handle_endtag self.parser.CharacterDataHandler = self.handle_data def parsefile(self, filename): with open(filename, "r") as fh: self.parser.ParseFile(fh) return self.data def _attrs_to_box(self, attrs): return [int(attrs["l"]), int(attrs["t"]), int(attrs["r"]) - int(attrs["l"]), int(attrs["b"]) - int(attrs["t"])] def handle_starttag(self, tag, attrs): """Handle each new element""" if tag == "page" and not self.gotpage: self.gotpage = True self.data["bbox"] = [0, 0, attrs.get("width", 0), attrs.get("height", 0)] elif tag == "block" and attrs.get("blockType") == "Text": self.data["columns"].append(self._attrs_to_box(attrs)) elif tag == "line": if self.currline is None: self.currline = {} self.currline["bbox"] = self._attrs_to_box(attrs) self.currline["index"] = self.linecnt def handle_data(self, data): """Handle tag data""" if self.currline is not None: self.currline["text"] = data def handle_endtag(self, tag): """Handle tag end""" if tag == "line" and self.currline is not None \ and self.currline.get("text"): self.linecnt += 1 self.data["lines"].append(self.currline.copy()) self.currline = None class AppException(StandardError): """ Most generic app error. """ pass def get_refpage_path(refpage, filename): """ Get the path for a reference page file. Called from the model FileField's upload_to param. """ return os.path.join( "reference", refpage.project.slug, os.path.splitext(refpage.page_name)[0], filename) def get_binary_path(filename, targetdir): """ Get the binary path relative to the original image path. """ binname = "%s.bin.png" % os.path.splitext( os.path.basename(filename))[0] return os.path.join(targetdir, "binary", binname) def save_ocr_images(images, path): """ Save OCR images to the media directory... """ paths = [] if not os.path.exists(path): os.makedirs(path, 0777) try: os.chmod(path, 0777) except Exception: print "CHMOD FAILED: %s" % path for _, handle in images: filepath = os.path.join(path, handle.name) with open(filepath, "wb") as outfile: for chunk in handle.chunks(): outfile.write(chunk) paths.append(filepath) try: os.chmod(filepath, 0777) except Exception: print "CHMOD FAILED: %s" % filepath return paths def get_media_output_path(inpath, type, ext=".png"): """ Get an output path for a given type of input file. """ base = os.path.splitext(inpath)[0] return "%s_%s%s" % (base, type, ext) def get_ab_output_path(inpath): """ Get an output path appended with either _a or _b depending on what the given input, output paths are. This is so we can switch between two temp paths (and also to prevent the SeaDragon viewer from caching images. TODO: Make this work less horribly. """ outpath = inpath base, ext = os.path.splitext(inpath) smatch = re.match("(.+)_(\d+)$", base) if smatch: pre, inc = smatch.groups() outpath = "%s_%03d%s" % (pre, int(inc) + 1, ext) else: outpath = "%s_001%s" % (base, ext) return outpath def find_file_with_basename(pathbase): """ Get the first file with the given basename (full path minus the extension.) """ basename = os.path.basename(pathbase) dirname = os.path.dirname(pathbase) candidates = [fname for fname in os.listdir(dirname) \ if fname.startswith(basename)] if candidates: return os.path.join(dirname, candidates[0]) return pathbase def find_unscaled_path(path, strip_ab=False): """ Find the non-scaled path to a temp file. """ uspath = os.path.abspath(path.replace("_scaled", "", 1)) uspath = os.path.abspath(path.replace(".dzi", ".png", 1)) if strip_ab: uspath = os.path.abspath(path.replace("_a.png", ".png", 1)) uspath = os.path.abspath(path.replace("_b.png", ".png", 1)) if not os.path.exists(uspath): uspath = find_file_with_basename( os.path.splitext(uspath)[0]) return uspath def new_size_from_width(currentsize, width): """ Maintain aspect ratio when scaling to a new width. """ cw, ch = currentsize caspect = float(cw) / float(ch) return width, int(width / caspect) def scale_image(inpath, outpath, newsize, filter=Image.ANTIALIAS): """ Scale an on-disk image to a new size using PIL. """ try: pil = Image.open(inpath) scaled = pil.resize(newsize, filter) scaled.save(outpath, "PNG") except IOError, err: # fall back on GraphicsMagick if opening fails sp.call(["convert", inpath, "-resize", "%sx%s" % newsize, outpath]) def get_image_dims(inpath): """ Get dimensions WxH of an image file. """ try: pil = Image.open(inpath) return pil.size except IOError, err: # fall back on GraphicsMagick if opening fails return sp.Popen(["identify", inpath, "-format", '%w %h'], stdout=sp.PIPE).communicate()[0].split() def make_png(inpath, outdir=None): """ PIL has problems with some TIFFs so this is a quick way of converting an image. """ if inpath.lower().endswith(".png"): return inpath if outdir is None: outdir = os.path.dirname(inpath) fname = os.path.basename(inpath) outpath = "%s/%s.png" % (outdir, os.path.splitext(fname)[0]) if not os.path.exists(outpath): sp.call(["convert", inpath, outpath]) return outpath def get_dzi_path(filepath): """ Get a path for the DZI relative to a rendered output file. """ return "%s/dzi/%s.dzi" % (os.path.dirname(filepath), os.path.splitext(os.path.basename(filepath))[0]) def media_url_to_path(url): """ Substitute the MEDIA_URL for the MEDIA_ROOT. """ if url: url = os.path.abspath(url) url = url.replace(settings.MEDIA_URL, settings.MEDIA_ROOT + "/", 1) return os.path.abspath(url) def media_path_to_url(path): """ Substitute the MEDIA_ROOT for the MEDIA_URL. """ if path: path = os.path.abspath(path) return path.replace(settings.MEDIA_ROOT, settings.MEDIA_URL, 1) def output_to_text(hocrdata): """ Convert page json to plain text. """ # FIXME: Import parser = HocrToTextHelper() return parser.parse(hocrdata) def output_to_json(hocrdata, indent=4): """ Process raw json data to user output, with an indent. """ parser = HocrParser() data = parser.parse(hocrdata) return simplejson.dumps(data, indent=indent) def output_to_hocr(hocrdata): """ Convert page hocr. No-op currently. """ return hocrdata
Python
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from ocradmin.core import views urlpatterns = patterns('', (r'^/?$', 'ocradmin.core.views.index'), (r'^abort/(?P<task_id>[^\/]+)/?$', login_required(views.abort)), (r'^task_config/(?P<task_pk>\d+)/?$', login_required(views.task_config)), (r'^result/(?P<task_id>[^\/]+)/?$', login_required(views.result)), (r'^results/(?P<task_ids>[^\/]+)/?$', login_required(views.results)), (r'^update_task/(?P<pid>[^/]+)/?$', login_required(views.update_ocr_task)), (r'^test/?$', views.test), (r'^testparams/?$', views.testparams), (r'^testlayout/?$', views.testlayout), )
Python
import re from django.template import Library from django.conf import settings register = Library() @register.filter def formatattr(value): """Formats an object's nested attribute for display""" value = value.split(".")[-1] return " ".join([p.capitalize() for p in value.split("_")])
Python
import re import types from django.template import Library from django.conf import settings numeric_test = re.compile("^\d+$") register = Library() @register.filter def getattribute(value, argstr): """Gets an attribute of an object dynamically from a string name""" args = argstr.split(".") leads = args[:-1] arg = args[-1] for lead in leads: value = getattr(value, lead) if hasattr(value, str(arg)): val = getattr(value, arg) if isinstance(val, types.MethodType): return val() return val elif hasattr(value, 'has_key') and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) > int(arg): return value[int(arg)] else: return settings.TEMPLATE_STRING_IF_INVALID
Python
import time import utils def test_simple_binarize(): """ Test the Ocropus native binarizer. """ start = time.clock() wrap = utils.OcropusWrapper(params={"clean": "StandardPreprocessing"}) bin = wrap.get_page_binary("21.png") return time.clock() - start def test_sp_binarize(): """ Test custom Python StandardPreprocessing. """ start = time.clock() wrap = utils.OcropusWrapper() gray, bin = wrap.standard_preprocess("21.png") return time.clock() - start if __name__ == "__main__": simple = sum([test_simple_binarize() for i in range(0, 5)]) / 5.0 bespoke = sum([test_sp_binarize() for i in range(0, 5)]) / 5.0 print "Simple: %03f secs" % simple print "Bespoke: %03f secs" % bespoke
Python
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): path = urlquote(request.get_full_path()) if not request.session.get("project"): return HttpResponseRedirect("/projects/list/?next=%s" % path) request.project = request.session.get("project") return func(request, *args, **kwargs) return wrapper def saves_files(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): temp = request.path.startswith(("/nodelib/")) project = request.session.get("project") output_path = None if project is None: temp = True if temp: output_path = os.path.join( settings.MEDIA_ROOT, settings.TEMP_PATH, request.user.username, datetime.now().strftime("%Y%m%d%H%M%S") ) else: output_path = os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH, project.slug ) request.__class__.output_path = output_path return func(request, *args, **kwargs) return wrapper
Python
""" Generic base classes for template handling. These prevent having to write lots of boring code but it's necessary to read the docs to understand it: https://docs.djangoproject.com/en/1.3/topics/class-based-views/ https://docs.djangoproject.com/en/1.3/ref/class-based-views/ """ from django import http from django.views import generic from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from tagging.models import Tag, TaggedItem class JSONResponseMixin(object): def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" objects = context.get("object_list") if objects is None and context.get("object"): objects = [context.get("object")] elif objects is None: objects = context return serializers.serialize("json", objects) class HybridListView(JSONResponseMixin, generic.list.MultipleObjectTemplateResponseMixin, generic.list.BaseListView): def render_to_response(self, context): # Look for a 'format=json' GET argument if self.request.GET.get('format','html') == 'json': return JSONResponseMixin.render_to_response(self, context) else: return generic.list.\ MultipleObjectTemplateResponseMixin\ .render_to_response(self, context) class HybridDetailView(JSONResponseMixin, generic.detail.SingleObjectTemplateResponseMixin): def render_to_response(self, context): # Look for a 'format=json' GET argument if self.request.GET.get('format','html') == 'json': return JSONResponseMixin.render_to_response(self, context) else: return generic.detail.\ SingleObjectTemplateResponseMixin\ .render_to_response(self, context) class GenericListView(HybridListView): """ Generic detail view class. Subclasses must supply both 'model' and 'fields'. """ paginate_by = 20 page_name = "Objects" fields = ["id"] def get_queryset(self): order = self.request.GET.get("order", self.fields[0]) tag = self.request.GET.get("tag") try: self.paginate_by = max(int(self.request.GET.get("paginate_by", self.paginate_by)), 0) except ValueError: pass # if there's a tag present search by tagged item if tag: return TaggedItem.objects.get_by_model( self.model, tag).order_by(order) return self.model.objects.all().order_by(order) def get_template_names(self): names = [self.template_name] if self.template_name is not None \ else [] names.append("generic_list.html" if not self.request.is_ajax() \ else "includes/generic_list_body.html") return tuple(names) def get_context_data(self, **kwargs): context = super(GenericListView, self).get_context_data(**kwargs) context.update( page_name=self.page_name, fields=self.fields, model=self.model, tags=Tag.objects.usage_for_model(self.model, counts=True), tag=self.request.GET.get("tag"), order=self.request.GET.get("order", self.fields[0]) ) return context class GenericDetailView(HybridDetailView, generic.detail.BaseDetailView): """ Generic detail view class. Subclasses must supply both 'model' and 'fields'. """ page_name="Object Details" fields=["id"] def get_template_names(self): names = [self.template_name] if self.template_name is not None \ else [] names.append("generic_detail.html" if not self.request.is_ajax() \ else "includes/generic_detail_body.html") return tuple(names) def get_context_data(self, **kwargs): context = super(GenericDetailView, self).get_context_data(**kwargs) context.update( page_name=self.page_name, fields=self.fields, model=self.model, tags=Tag.objects.get_for_object(self.object), ) return context class GenericCreateView(generic.CreateView): """ Generic create view class. Subclasses must supply both 'model' and 'form_class'. """ page_name="New Object" enctype = "application/x-www-form-urlencoded" def get_template_names(self): names = [self.template_name] if self.template_name is not None \ else [] names.append("generic_create.html" if not self.request.is_ajax() \ else "includes/generic_create_body.html") return tuple(names) def get_initial(self, *args, **kwargs): initial = super(GenericCreateView, self).get_initial(*args, **kwargs) initial.update(user=self.request.user) return initial def get_form_kwargs(self, *args, **kwargs): form_kwargs = super(GenericCreateView, self).get_form_kwargs(*args, **kwargs) return form_kwargs def get_context_data(self, **kwargs): context = super(GenericCreateView, self).get_context_data(**kwargs) context.update( page_name=self.page_name, model=self.model, enctype=self.enctype ) return context class GenericEditView(generic.UpdateView): """ Generic edit view class. Subclasses must supply both 'model' and 'form_class'. """ page_name="Edit Object" enctype = "application/x-www-form-urlencoded" def get_template_names(self): names = [self.template_name] if self.template_name is not None \ else [] names.append("generic_edit.html" if not self.request.is_ajax() \ else "includes/generic_edit_body.html") return tuple(names) def get_initial(self, *args, **kwargs): initial = super(GenericEditView, self).get_initial(*args, **kwargs) initial.update(user=self.request.user) return initial def get_context_data(self, **kwargs): context = super(GenericEditView, self).get_context_data(**kwargs) context.update( page_name=self.page_name, model=self.model, tags=Tag.objects.get_for_object(self.object), enctype=self.enctype ) return context class GenericDeleteView(generic.DeleteView): """ Generic delete view class. Subclasses must supply both 'model' and 'success_url'. """ page_name="Delete Object" def get_template_names(self): names = [self.template_name] if self.template_name is not None \ else [] names.append("generic_delete.html" if not self.request.is_ajax() \ else "includes/generic_delete_body.html") return tuple(names) def get_context_data(self, **kwargs): context = super(GenericDeleteView, self).get_context_data(**kwargs) context.update( page_name=self.page_name, tags=Tag.objects.get_for_object(self.object), ) return context
Python
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
Python