def set_output_verbosity(self, value): ''' debug HTTP activiti: True, False ''' try: pyrax.set_http_debug(value) except: logging.warn('cannot set_output_verbosity(%s)' % value)
def __init__(self, username, apikey, verbose): pyrax.set_setting("identity_type", "rackspace") pyrax.set_credentials(username, apikey) pyrax.set_http_debug(DEBUG) self.dns = pyrax.cloud_dns self.verbose = verbose self.domains = None if self.domains is not None: return self
def test_set_http_debug(self): pyrax.cloudservers = None sav = pyrax.connect_to_cloudservers pyrax.connect_to_cloudservers = self.orig_connect_to_cloudservers pyrax.cloudservers = pyrax.connect_to_cloudservers() pyrax.cloudservers.http_log_debug = False pyrax.set_http_debug(True) self.assertTrue(pyrax.cloudservers.http_log_debug) pyrax.set_http_debug(False) self.assertFalse(pyrax.cloudservers.http_log_debug) pyrax.connect_to_cloudservers = sav
def set_output_verbosity(self, value): ''' debug HTTP activiti: True, False ''' try: pyrax.set_http_debug(value) cmd_out = "http_debu: %s" % value self.r(0, cmd_out, INFO) except: tb = traceback.format_exc() self.r(1, tb, ERROR) return None
def _get_client(self): username = self.config['username'] api_key = self.config['api_key'] # Needs to be extracted to per-action region = self.config['region'].upper() pyrax.set_setting('identity_type', 'rackspace') pyrax.set_default_region(region) pyrax.set_credentials(username, api_key) debug = self.config.get('debug', False) if debug: pyrax.set_http_debug(True) pyrax.cloudservers = pyrax.connect_to_cloudservers(region=region) pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers(region=region) pyrax.cloud_dns = pyrax.connect_to_cloud_dns(region=region) return pyrax
def main(): # ######################################## # LOGGING utility.logging_start() # @UndefinedVariable logging.debug('starting') # ######################################## # CONFIGURATION cfg = Configuration.Instance() # @UndefinedVariable cfg.parsecli(sys.argv) logging.info("configuration: %s" % cfg) # ######################################## # DO STUFF # handle configuration if cfg.pyrax_http_debug: pyrax.set_http_debug(True) if cfg.pyrax_no_verify_ssl: # see: https://github.com/rackspace/pyrax/issues/187 pyrax.set_setting("verify_ssl", False) Cmd_Pyraxshell().cmdloop()
def main(): # check '~/.pyraxshell' and config files exist, create them if missing if not check_dir_home(): print ("This is the first time 'pyraxshell' runs, please, configure " "'%s' according to your needs" % CONFIG_FILE) #create db DB() Sessions.Instance().create_table_sessions() # @UndefinedVariable Sessions.Instance().create_table_commands() # @UndefinedVariable # create default configuration file Configuration.Instance() # @UndefinedVariable sys.exit(0) # ######################################## # VERSION CHECK if not version.check_version_file(): sys.exit(1) # ######################################## # LOGGING start_logging() logging.debug('starting') # from baseconfigfile import BaseConfigFile # bcf = BaseConfigFile() # ######################################## # ACCOUNTS accounts = Account.Instance() # @UnusedVariable @UndefinedVariable # config file is read by 'BaseConfigFile' constructor # ######################################## # CONFIGURATION cfg = Configuration.Instance() # @UndefinedVariable # override settings with CLI params cfg.parse_cli(sys.argv) logging.debug("configuration: %s" % cfg) # set user's log level if specified if not Configuration.Instance().log_level == None: # @UndefinedVariable l = logging.getLogger() for h in l.handlers: h.setLevel(cfg.log_level) # ######################################## # START SESSION Sessions.Instance().start_session() # @UndefinedVariable # Sessions.Instance().insert_table_commands('IN', 'OUT') # @UndefinedVariable # ######################################## # DO STUFF # handle configuration if cfg.pyrax_http_debug == True: pyrax.set_http_debug(True) if cfg.pyrax_no_verify_ssl == True: # see: https://github.com/rackspace/pyrax/issues/187 pyrax.set_setting("verify_ssl", False) # start notifier Notifier().start() # main loop Cmd_Pyraxshell().cmdloop()
# # 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 os import pyrax from pyrax import exc from pyrax import utils creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) pyrax.set_http_debug(True) cnw = pyrax.cloud_networks network_name = "SAMPLE_NETWORK" # Get the network created in the create_network sample script try: net = cnw.find_network_by_label(network_name) except exc.NetworkNotFound: msg = "The sample network was not found. Please run the 'create_network' " "script before running this script." print msg exit() print "Sample network:" print net print
except: print 'Unable to import pyrax' exit(1) # Import salt libs import salt.utils log = logging.getLogger(__name__) # TODO: Need to look into Salt error handling to reduce code duplication # specifically around if a LB or node does not exist # TODO: Move into config pyrax.set_setting("identity_type", "rackspace") pyrax.set_credentials("USERNAME", "APIKEY") pyrax.set_http_debug(False) clb = pyrax.cloud_loadbalancers def _get_lb(lb_id): lbs = clb.list() for lb in lbs: return lb if lb.id == lb_id else None def _get_node(lb, ip): node = [n for n in lb.nodes if n.address == ip] return node[0] if node else None def _get_private_ip(): # TODO: Find a better way to get servicenet IP return [ip for ip in __grains__['ipv4'] if ip.startswith('10.')][0]
def debug(self, debugging): pyrax.set_http_debug(debugging)
def test_set_http_debug(self): pyrax.cloudservers.http_log_debug = False pyrax.set_http_debug(True) self.assertTrue(pyrax.cloudservers.http_log_debug)
print e print "\n" print "Please install Pyrax from 'https://github.com/rackspace/pyrax'." import os import sys import multiprocessing username = raw_input('Please enter your USERNAME: '******'Please enter your APIKEY: ') my_region = raw_input("Please enter the container REGION: ") my_container = raw_input("Please enter the name of the CONTAINER: ") #Set identity pyrax.set_setting('identity_type', 'rackspace') pyrax.set_credentials(username, api_key, authenticate=True) pyrax.set_http_debug(hDebug) pyrax.set_default_region(my_region) pyrax.settings.set("region",my_region) cfiles = pyrax.connect_to_cloudfiles(region=my_region, public=isPublic) cont = cfiles.get_container(my_container) download_me = cont.get_object_names(full_listing=True) #list_to_download = cont.get_objects(limit=100) #download_me = [obj.name for obj in list_to_download] #Create directory to represent top level container if not os.path.exists(my_container): try: os.makedirs(my_container) except Exception as e: print e
def main(): # check '~/.pyraxshell' and config files exist, create them if missing if not check_dir_home(): print("This is the first time 'pyraxshell' runs, please, configure " "'%s' according to your needs" % CONFIG_FILE) #create db DB() Sessions.Instance().create_table_sessions() # @UndefinedVariable Sessions.Instance().create_table_commands() # @UndefinedVariable # create default configuration file Configuration.Instance() # @UndefinedVariable sys.exit(0) # ######################################## # VERSION CHECK if not version.check_version_file(): sys.exit(1) # ######################################## # LOGGING start_logging() logging.debug('starting') # from baseconfigfile import BaseConfigFile # bcf = BaseConfigFile() # ######################################## # ACCOUNTS accounts = Account.Instance() # @UnusedVariable @UndefinedVariable # config file is read by 'BaseConfigFile' constructor # ######################################## # CONFIGURATION cfg = Configuration.Instance() # @UndefinedVariable # override settings with CLI params cfg.parse_cli(sys.argv) logging.debug("configuration: %s" % cfg) # set user's log level if specified if not Configuration.Instance().log_level == None: # @UndefinedVariable l = logging.getLogger() for h in l.handlers: h.setLevel(cfg.log_level) # ######################################## # START SESSION Sessions.Instance().start_session() # @UndefinedVariable # Sessions.Instance().insert_table_commands('IN', 'OUT') # @UndefinedVariable # ######################################## # DO STUFF # handle configuration if cfg.pyrax_http_debug == True: pyrax.set_http_debug(True) if cfg.pyrax_no_verify_ssl == True: # see: https://github.com/rackspace/pyrax/issues/187 pyrax.set_setting("verify_ssl", False) # start notifier Notifier().start() # main loop Cmd_Pyraxshell().cmdloop()
elif LOGLEVEL == 'ERROR': log.setLevel(logging.ERROR) elif LOGLEVEL == 'CRITICAL': log.setLevel(logging.CRITICAL) elif LOGLEVEL == 'DEBUG': log.setLevel(logging.DEBUG) #set Pyrax HTTP debug to True hDebug = True else: log.setLevel(logging.INFO) #----------------------------------------------------------------- log.info("Preparing pyrax environment...") #Set identity authenticate to Rackspace pyrax.set_setting('identity_type', 'rackspace') pyrax.set_credentials(username, api_key, authenticate=True) pyrax.set_http_debug(hDebug) pyrax.set_setting('verify_ssl', False) #Create connection object for cloud files and 'get' our container targeted for draining try: #Create connection to specified region cfiles = pyrax.connect_to_cloudfiles(region=my_region, public=public) log.info("Successfully connected to region [%s]" % my_region) except Exception as e: log.error("Unable to connect to [%s] region!" % my_region) sys.exit(1) try: #Get the container we want to delete/drain cont = cfiles.get_container(my_container) log.info("Successfully performed GET on container [%s]" % my_container) except Exception as e:
def main(): parser = argparse.ArgumentParser(description="Run regularly scheduled images of a cloud server.") parser.add_argument("--username", "-u", help="The account's username") parser.add_argument("--api-key", "-k", help="The account's API key") parser.add_argument("--server-id", "-s", action="append", help="The ID of the server to back up. " "You may specify this parameter multiple times to back up multiple servers.") parser.add_argument("--backup-count", "-b", type=int, help="Number of backups to retain per server. " "After this limit is reached, the oldest backups will be deleted.") parser.add_argument("--persist", "-p", action="store_true", help="Store the values specified as " "parameters in this call to be used as the default in future runs.") args = parser.parse_args() settings = SettingsHolder(args) if isinstance(settings.instance_ids, basestring): settings.instance_ids = json.loads(settings.instance_ids) if args.persist: settings.save() if INTERACTIVE: if not settings.username: settings.username = raw_input("Please enter the account username: "******"Cannot continue without account username.") sys.exit() if not settings.api_key: settings.api_key = raw_input("Please enter the account API key: ") if not settings.api_key: logit("Cannot continue without account API key.") sys.exit() if not settings.instance_ids: print " ".join(["Please enter the ID of the server(s) to backup.", "You may enter more than one ID, separated by spaces."]) input_ids = raw_input() if not input_ids: logit("Cannot continue without ID of instance.") sys.exit() # Strip commas, in case they added them to the input input_ids = input_ids.replace(",", "") settings.instance_ids = [iid.strip() for iid in instance_ids.split(" ")] if not settings.backup_count: settings.backup_count = raw_input("How many backup images should be retained? ") if not settings.backup_count: logit("Cannot continue without backup count.") sys.exit() settings.backup_count = int(settings.backup_count) else: # All values must be defined to continue missing = settings.get_missing() if missing: logit("Could not continue; the following values are missing: %s" % missing) sys.exit() try: pyrax.set_credentials(settings.username, settings.api_key) except exc.AuthenticationFailed: logit("Unable to authenticate.") sys.exit() # Turn off debug output pyrax.set_http_debug(False) #TODO: add support for other regions cs_dfw = pyrax.connect_to_cloudservers("DFW") cs_ord = pyrax.connect_to_cloudservers("ORD") regions = (cs_dfw, cs_ord) now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") for instance_id in settings.instance_ids: for region in regions: try: instance = region.servers.get(instance_id) logit("Found instance '%s' in region '%s'" % (instance.name, region.client.region_name)) break except exc.ServerNotFound: continue image_name = "%s-%s" % (instance.name, now) images = region.images.list() backups = [image for image in images if image.name.startswith(instance.name)] # Sorting by name will result in the oldest first. backups.sort(lambda x,y: cmp(x.name, y.name)) to_delete = [] # Don't delete just yet; the image creation step below # could fail. while len(backups) >= settings.backup_count: to_delete.append(backups.pop(0)) try: instance.create_image(image_name) logit("Successfully created backup image: %s" % image_name) except exc.ServerClientException as e: logit("Unable to create image: %s" % e) continue for old_image in to_delete: old_image.delete() logit("Deleted old image: %s" % old_image.name)
# 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 __future__ import print_function import os import pyrax from pyrax import exc from pyrax import utils pyrax.set_setting("identity_type", "rackspace") creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) pyrax.set_http_debug(True) cnw = pyrax.cloud_networks network_name = "SAMPLE_NETWORK" # Get the network created in the create_network sample script try: net = cnw.find_network_by_label(network_name) except exc.NetworkNotFound: msg = ("The sample network was not found. Please run the 'create_network' " "script before running this script.") print(msg) exit() print("Sample network:") print(net)
if __name__ == '__main__': args = parse_args() logging.basicConfig(level=logging.DEBUG) log.info('Configured logging.') # Give credentials to pyrax. if 'localstorage' in args.storage_mode: pyrax.set_setting('identity_type', 'keystone') pyrax.set_setting('auth_endpoint', args.auth_endpoint) pyrax.set_http_debug(args.debug) pyrax.set_setting('verify_ssl', args.verify_ssl) pyrax.set_setting('region', args.region) pyrax.set_setting('tenant_id', args.tenant_id) pyrax.set_credentials( username=args.username, password=args.password ) log.info("Set settings and credentials on pyrax for local storage") else: pyrax.set_setting('identity_type', 'rackspace') pyrax.set_credentials( args.rackspace_username,