+from __future__ import print_function
+
### utility to match command-line args to names
class Candidates:
def __init__ (self, names):
names=names.split()
for (input,expected) in tuples:
got=Candidates(names).only_match(input)
- if got==expected: print '.',
- else: print 'X FAIL','names[',names,'] input',input,'expected',expected,'got',got
+ if got==expected: print('.', end=' ')
+ else: print('X FAIL','names[',names,'] input',input,'expected',expected,'got',got)
if __name__ == '__main__':
test_candidates()
# a few utilities common to sfi and sfaadmin
+from __future__ import print_function
+
def optparse_listvalue_callback(option, opt, value, parser):
former=getattr(parser.values,option.dest)
if not former: former=[]
else: return "%d %s"%(how_many,names)
def terminal_render_default (record,options):
- print "%s (%s)" % (record['hrn'], record['type'])
+ print("%s (%s)" % (record['hrn'], record['type']))
def terminal_render_user (record, options):
- print "%s (User)"%record['hrn'],
+ print("%s (User)"%record['hrn'], end=' ')
if options.verbose and record.get('email', None):
- print "email='{}'".format(record['email']),
+ print("email='{}'".format(record['email']), end=' ')
if record.get('reg-pi-authorities', None):
- print " [PI at %s]"%(" and ".join(record['reg-pi-authorities'])),
+ print(" [PI at %s]"%(" and ".join(record['reg-pi-authorities'])), end=' ')
if record.get('reg-slices', None):
- print " [IN slices %s]"%(" and ".join(record['reg-slices'])),
+ print(" [IN slices %s]"%(" and ".join(record['reg-slices'])), end=' ')
user_keys=record.get('reg-keys',[])
if not options.verbose:
- print " [has %s]"%(terminal_render_plural(len(user_keys),"key"))
+ print(" [has %s]"%(terminal_render_plural(len(user_keys),"key")))
else:
- print ""
- for key in user_keys: print 8*' ',key.strip("\n")
+ print("")
+ for key in user_keys: print(8*' ',key.strip("\n"))
def terminal_render_slice (record, options):
- print "%s (Slice)"%record['hrn'],
+ print("%s (Slice)"%record['hrn'], end=' ')
if record.get('reg-researchers', None):
- print " [USERS %s]"%(" and ".join(record['reg-researchers'])),
+ print(" [USERS %s]"%(" and ".join(record['reg-researchers'])), end=' ')
# print record.keys()
- print ""
+ print("")
def terminal_render_authority (record, options):
- print "%s (Authority)"%record['hrn'],
+ print("%s (Authority)"%record['hrn'], end=' ')
if options.verbose and record.get('name'):
- print "name='{}'".format(record['name'])
+ print("name='{}'".format(record['name']))
if record.get('reg-pis', None):
- print " [PIS %s]"%(" and ".join(record['reg-pis'])),
- print ""
+ print(" [PIS %s]"%(" and ".join(record['reg-pis'])), end=' ')
+ print("")
def terminal_render_node (record, options):
- print "%s (Node)"%record['hrn']
+ print("%s (Node)"%record['hrn'])
### used in sfi list
+from __future__ import print_function
+
import threading
import traceback
import time
def f(name, n, sleep=1):
nums = []
for i in range(n, n+5):
- print "%s: %s" % (name, i)
+ print("%s: %s" % (name, i))
nums.append(i)
time.sleep(sleep)
return nums
def e(name, n, sleep=1):
nums = []
for i in range(n, n+3) + ['n', 'b']:
- print "%s: 1 + %s:" % (name, i)
+ print("%s: 1 + %s:" % (name, i))
nums.append(i + 1)
time.sleep(sleep)
return nums
#!/usr/bin/python
+from __future__ import print_function
+
import os
import sys
import copy
hrn = Xrn(xrn).get_hrn()
db_query = db_query.filter_by(hrn=hrn)
elif all and xrn:
- print "Use either -a or -x <xrn>, not both !!!"
+ print("Use either -a or -x <xrn>, not both !!!")
sys.exit(1)
elif not all and not xrn:
- print "Use either -a or -x <xrn>, one of them is mandatory !!!"
+ print("Use either -a or -x <xrn>, one of them is mandatory !!!")
sys.exit(1)
records = db_query.all()
if not records:
- print "No Record found"
+ print("No Record found")
sys.exit(1)
OK = []
NOK.append(record.hrn)
if not verbose:
- print "Users NOT having a PubKey: %s\n\
+ print("Users NOT having a PubKey: %s\n\
Users having a non RSA PubKey: %s\n\
Users having a GID/PubKey correpondence OK: %s\n\
-Users having a GID/PubKey correpondence Not OK: %s\n"%(len(NOKEY), len(ERROR), len(OK), len(NOK))
+Users having a GID/PubKey correpondence Not OK: %s\n"%(len(NOKEY), len(ERROR), len(OK), len(NOK)))
else:
- print "Users NOT having a PubKey: %s and are: \n%s\n\n\
+ print("Users NOT having a PubKey: %s and are: \n%s\n\n\
Users having a non RSA PubKey: %s and are: \n%s\n\n\
Users having a GID/PubKey correpondence OK: %s and are: \n%s\n\n\
-Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY),NOKEY, len(ERROR), ERROR, len(OK), OK, len(NOK), NOK)
+Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY),NOKEY, len(ERROR), ERROR, len(OK), OK, len(NOK), NOK))
def credential(self, xrn, type=None):
"""Invoke GetCredential"""
cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
- print cred
+ print(cred)
def import_registry(self):
auth_info = hierarchy.get_auth_info(hrn)
gid = auth_info.gid_object
except:
- print "Record: %s not found" % hrn
+ print("Record: %s not found" % hrn)
sys.exit(1)
# save to file
if not outfile:
"""Print contents of a GID file"""
gid_path = os.path.abspath(gidfile)
if not gid_path or not os.path.isfile(gid_path):
- print "No such gid file: %s" % gidfile
+ print("No such gid file: %s" % gidfile)
sys.exit(1)
gid = GID(filename=gid_path)
gid.dump(dump_parents=True)
def resources(self, rspec_version='GENI'):
"""Display the available resources at an aggregate"""
options = {'geni_rspec_version': rspec_version}
- print options
+ print(options)
resources = self.api.manager.ListResources(self.api, [], options)
- print resources
+ print(resources)
@add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
rspec_string = open(rspec).read()
options={}
manifest = self.api.manager.Allocate(self.api, slice_urn, [], rspec_string, options)
- print manifest
+ print(manifest)
@add_options('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
slice_urn=xrn.get_urn()
options={}
manifest = self.api.manager.provision(self.api, [slice_urn], [], options)
- print manifest
+ print(manifest)
return (full_name,SfaAdmin.CATEGORIES[full_name])
def summary_usage (self, category=None):
- print "Usage:", self.script_name + " category command [<options>]"
+ print("Usage:", self.script_name + " category command [<options>]")
if category and category in SfaAdmin.CATEGORIES:
categories=[category]
else:
categories=SfaAdmin.CATEGORIES
for c in categories:
cls=SfaAdmin.CATEGORIES[c]
- print "==================== category=%s"%c
+ print("==================== category=%s"%c)
names=cls.__dict__.keys()
names.sort()
for name in names:
if name.startswith('_'): continue
margin=15
format="%%-%ds"%margin
- print "%-15s"%name,
+ print("%-15s"%name, end=' ')
doc=getattr(method,'__doc__',None)
if not doc:
- print "<missing __doc__>"
+ print("<missing __doc__>")
continue
lines=[line.strip() for line in doc.split("\n")]
line1=lines.pop(0)
- print line1
- for extra_line in lines: print margin*" ",extra_line
+ print(line1)
+ for extra_line in lines: print(margin*" ",extra_line)
sys.exit(2)
def main(self):
command(*cmd_args, **cmd_kwds)
sys.exit(0)
except TypeError:
- print "Possible wrong number of arguments supplied"
+ print("Possible wrong number of arguments supplied")
#import traceback
#traceback.print_exc()
- print command.__doc__
+ print(command.__doc__)
parser.print_help()
sys.exit(1)
#raise
except Exception:
- print "Command failed, please check log for more info"
+ print("Command failed, please check log for more info")
raise
sys.exit(1)
# Thierry Parmentelat -- INRIA
-#
-# a minimal library for writing "lightweight" SFA clients
-#
+"""
+a minimal library for writing "lightweight" SFA clients
+"""
+
+from __future__ import print_function
# xxx todo
# this library should probably check for the expiration date of the various
openssl_command += [ "-in", self.my_gid_filename()]
openssl_command += [ "-out", filename ]
if subprocess.call(openssl_command) ==0:
- print "Successfully created %s"%filename
+ print("Successfully created %s"%filename)
else:
- print "Failed to create %s"%filename
+ print("Failed to create %s"%filename)
# Returns True if credential file is valid. Otherwise return false.
def validate_credential(self, filename):
+from __future__ import print_function
+
import sys, os.path
import pickle
import time
try:
import pygraphviz
except:
- print 'Warning, could not import pygraphviz, test mode only'
+ print('Warning, could not import pygraphviz, test mode only')
from optparse import OptionParser
def show (self):
entries=len(self.url2version)
- print "version cache from file %s has %d entries"%(self.filename,entries)
+ print("version cache from file %s has %d entries"%(self.filename,entries))
key_values=self.url2version.items()
def old_first (kv1,kv2): return int(kv1[1][0]-kv2[1][0])
key_values.sort(old_first)
(timestamp,version) = tuple
how_old = time.time()-timestamp
if how_old<=self.expires:
- print url,"-- %d seconds ago"%how_old
+ print(url,"-- %d seconds ago"%how_old)
else:
- print "OUTDATED",url,"(%d seconds ago, expires=%d)"%(how_old,self.expires)
+ print("OUTDATED",url,"(%d seconds ago, expires=%d)"%(how_old,self.expires))
# turns out we might have trailing slashes or not
def normalize (self, url):
# test mode when pygraphviz is not available
except:
entry=entries[0]
- print "GetVersion at %s returned %s"%(entry.url(),entry.get_version())
+ print("GetVersion at %s returned %s"%(entry.url(),entry.get_version()))
+from __future__ import print_function
+
import xmlrpclib
from datetime import datetime
import time
dummy_api.AddUserToSlice({'slice_id': 2, 'user_id': my_user_id})
# Display the list of users
-print dummy_api.GetUsers()
+print(dummy_api.GetUsers())
# Display the list of slices
-print dummy_api.GetSlices()
+print(dummy_api.GetSlices())
# this is designed to use a totally empty new directory
# so we demonstrate how to bootstrap the whole thing
+from __future__ import print_function
+
# init logging on console
import logging
console = logging.StreamHandler()
import sys
args=sys.argv[1:]
if len(args)!=1:
- print "Usage: %s directory"%sys.argv[0]
+ print("Usage: %s directory"%sys.argv[0])
sys.exit(1)
dir=args[0]
logger.debug('sfaclientsample: Using directory %s'%dir)
bootstrap.self_signed_cert()
server_proxy = bootstrap.server_proxy_simple(url)
server_version = server_proxy.GetVersion()
- print "miniclient: GetVersion at %s returned:"%(url)
- for (k,v) in server_version.iteritems(): print "miniclient: \tversion[%s]=%s"%(k,truncate(v))
+ print("miniclient: GetVersion at %s returned:"%(url))
+ for (k,v) in server_version.iteritems(): print("miniclient: \tversion[%s]=%s"%(k,truncate(v)))
# version_dict = {'type': 'SFA', 'version': '1', }
options [ 'geni_rspec_version' ] = version_dict
options [ 'call_id' ] = unique_call_id()
list_resources = bootstrap.server_proxy (aggregate_url).ListResources(credentials,options)
- print "miniclient: ListResources at %s returned : %s"%(aggregate_url,truncate(list_resources))
+ print("miniclient: ListResources at %s returned : %s"%(aggregate_url,truncate(list_resources)))
def list_slice_resources ():
bootstrap.bootstrap_my_gid()
options [ 'geni_slice_urn' ] = slice_urn
options [ 'call_id' ] = unique_call_id()
list_resources = bootstrap.server_proxy (aggregate_url).ListResources(credentials,options)
- print "miniclient: ListResources at %s for slice %s returned : %s"%(aggregate_url,slice_urn,truncate(list_resources))
+ print("miniclient: ListResources at %s for slice %s returned : %s"%(aggregate_url,slice_urn,truncate(list_resources)))
#!/usr/bin/env python
-from __future__ import with_statement
+from __future__ import print_function
+
import sys
import os
from lxml import etree as ET
if not rspecValidator(rspecXML):
error = rspecValidator.error_log.last_error
message = '%s (line %s)' % (error.message, error.line)
- print message
+ print(message)
else:
- print 'It is valid'
+ print('It is valid')
if __name__ == "__main__":
main()
+from __future__ import print_function
+
import types
# for get_key_from_incoming_ip
import tempfile
# record.__dict__ as received by the driver seems to be off
# anyway the driver should receive an object
# (and then extract __dict__ itself if needed)
- print "DO NOT REMOVE ME before driver.update, record={}".format(record)
+ print("DO NOT REMOVE ME before driver.update, record={}".format(record))
# as of June 2015: I suspect we could remove that print line above and replace it with
# augment_with_sfa_builtins(record)
# instead, that checks for these fields, like it is done above in List()
+from __future__ import print_function
+
# specialized Xrn class for NITOS
import re
from sfa.util.xrn import Xrn
#slice_name = NitosXrn(xrn="omf.nitos.aminesl",type='slice').nitos_slicename()
slicename = "giorgos_n"
hrn = slicename_to_hrn("pla", "nitos", slicename)
- print hrn
+ print(hrn)
+from __future__ import print_function
+
# specialized Xrn class for PlanetLab
import re
from sfa.util.xrn import Xrn, get_authority
if __name__ == '__main__':
for test in tests:
- print("{} - hash_loginbase -> {}".format(test, hash_loginbase(test)))
+ print(("{} - hash_loginbase -> {}".format(test, hash_loginbase(test))))
+from __future__ import print_function
+
from sfa.rspecs.elements.element import Element
from sfa.rspecs.elements.sliver import Sliver
sliver['type'] = sliver_elem.attrib['name']
#sliver['images'] = Iotlabv1DiskImage.get_images(sliver_elem)
- print>>sys.stderr, "\r\n \r\n SLABV1SLIVER.PY \t\t\t get_slivers sliver %s " %( sliver)
+ print("\r\n \r\n SLABV1SLIVER.PY \t\t\t get_slivers sliver %s " %( sliver), file=sys.stderr)
slivers.append(sliver)
return slivers
#!/usr/bin/python
+from __future__ import print_function
+
from lxml import etree
from StringIO import StringIO
from sfa.util.xrn import Xrn, urn_to_hrn
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
- print PGRSpecConverter.to_sfa_rspec(sys.argv[1])
+ print(PGRSpecConverter.to_sfa_rspec(sys.argv[1]))
#!/usr/bin/python
+from __future__ import print_function
+
from sfa.rspecs.pg_rspec_converter import PGRSpecConverter
from sfa.rspecs.sfa_rspec_converter import SfaRSpecConverter
from sfa.rspecs.rspec import RSpec
pg_rspec = 'test/protogeni.rspec'
sfa_rspec = 'test/nodes.rspec'
- print "converting pg rspec to sfa rspec"
- print RSpecConverter.to_sfa_rspec(pg_rspec)
+ print("converting pg rspec to sfa rspec")
+ print(RSpecConverter.to_sfa_rspec(pg_rspec))
- print "converting sfa rspec to pg rspec"
- print RSpecConverter.to_pg_rspec(sfa_rspec)
+ print("converting sfa rspec to pg rspec")
+ print(RSpecConverter.to_pg_rspec(sfa_rspec))
#!/usr/bin/python
+from __future__ import print_function
+
from sfa.util.xrn import hrn_to_urn
from sfa.rspecs.rspec import RSpec
from sfa.rspecs.version_manager import VersionManager
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
- print SfaRSpecConverter.to_pg_rspec(sys.argv[1])
+ print(SfaRSpecConverter.to_pg_rspec(sys.argv[1]))
+from __future__ import print_function
+
import os
from sfa.util.faults import InvalidRSpec, UnsupportedRSpecVersion
from sfa.rspecs.version import RSpecVersion
def show_by_string(self, string):
try:
- print self.get_version(string)
+ print(self.get_version(string))
except Exception as e:
- print e
+ print(e)
def show_by_schema(self, string):
try:
- print self.get_version_by_schema(string)
+ print(self.get_version_by_schema(string))
except Exception as e:
- print e
+ print(e)
if __name__ == '__main__':
manager = VersionManager()
- print manager
+ print(manager)
manager.show_by_string('sfa 1')
manager.show_by_string('protogeni 2')
manager.show_by_string('protogeni 2 advertisement')
+from __future__ import print_function
+
from copy import deepcopy
# Slivers
def get_sliver_attributes(self, hostname, node, network=None):
- print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes hostname %s " %(hostname)
+ print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes hostname %s " %(hostname), file=sys.stderr)
nodes = self.get_nodes({'component_id': '*%s*' %hostname})
attribs = []
- print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes-----------------nodes %s " %(nodes)
+ print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes-----------------nodes %s " %(nodes), file=sys.stderr)
if nodes is not None and isinstance(nodes, list) and len(nodes) > 0:
node = nodes[0]
#if node :
sliver = sliver[0]
attribs = sliver
#attribs = self.attributes_list(sliver)
- print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes----------NN------- sliver %s self.namespaces %s attribs %s " %(sliver, self.namespaces,attribs)
+ print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes----------NN------- sliver %s self.namespaces %s attribs %s " %(sliver, self.namespaces,attribs), file=sys.stderr)
return attribs
def get_slice_attributes(self, network=None):
if attributes is None: attributes=[]
# all nodes hould already be present in the rspec. Remove all
# nodes that done have slivers
- print>>sys.stderr, "\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers ----->get_node "
+ print("\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers ----->get_node ", file=sys.stderr)
for hostname in hostnames:
node_elems = self.get_nodes({'component_id': '*%s*' % hostname})
if not node_elems:
continue
sliver = {'type': requested_sliver_type,
'pl_tags': attributes}
- print>>sys.stderr, "\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers node_elem %s sliver_type %s \r\n \r\n " %(node_elem, sliver_type)
+ print("\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers node_elem %s sliver_type %s \r\n \r\n " %(node_elem, sliver_type), file=sys.stderr)
# remove available element
for available_elem in node_elem.xpath('./default:available | ./available'):
node_elem.remove(available_elem)
r = RSpec('/tmp/iotlab.rspec')
r.load_rspec_elements(Iotlabv1.elements)
r.namespaces = Iotlabv1.namespaces
- print r.get(RSpecElements.NODE)
+ print(r.get(RSpecElements.NODE))
+from __future__ import print_function
+
from copy import deepcopy
from lxml import etree
from sfa.rspecs.rspec_elements import *
r = RSpec('/tmp/resources.rspec')
r.load_rspec_elements(SFAv1.elements)
- print r.get(RSpecElements.NODE)
+ print(r.get(RSpecElements.NODE))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+from __future__ import print_function
+
from copy import deepcopy
from lxml import etree
import pprint
from sfa.rspecs.rspec import RSpec
from sfa.rspecs.rspec_elements import *
- print "main ofeliav1"
+ print("main ofeliav1")
if len(sys.argv)!=2:
r = RSpec('/tmp/resources.rspec')
else:
+from __future__ import print_function
+
from copy import deepcopy
from StringIO import StringIO
from sfa.util.xrn import Xrn
r = RSpec('/tmp/pg.rspec')
r.load_rspec_elements(PGv2.elements)
r.namespaces = PGv2.namespaces
- print r.get(RSpecElements.NODE)
+ print(r.get(RSpecElements.NODE))
+from __future__ import print_function
+
from copy import deepcopy
from lxml import etree
from sfa.rspecs.rspec_elements import *
r = RSpec('/tmp/resources.rspec')
r.load_rspec_elements(SFAv1.elements)
- print r.get(RSpecElements.NODE)
+ print(r.get(RSpecElements.NODE))
#!/usr/bin/python
+from __future__ import print_function
+
import sys
import os
import tempfile
try: return f(*args, **kwds)
except ConnectionKeyGIDMismatch:
# clean regen server keypair and try again
- print "cleaning keys and trying again"
+ print("cleaning keys and trying again")
clean_key_cred()
return f(args, kwds)
url = "http://%(addr)s:%(port)s" % locals()
if verbose:
- print "Contacting registry at: %(url)s" % locals()
+ print("Contacting registry at: %(url)s" % locals())
server = SfaServerProxy(url, keyfile, certfile)
return server
# check for existing credential
if not force and os.path.exists(credfile):
if verbose:
- print "Loading Credential from %(credfile)s " % locals()
+ print("Loading Credential from %(credfile)s " % locals())
cred = Credential(filename=credfile).save_to_string(save_parents=True)
else:
if verbose:
- print "Getting credential from registry"
+ print("Getting credential from registry")
# make sure node private key exists
node_pkey_file = config_dir + os.sep + "node.key"
node_gid_file = config_dir + os.sep + "node.gid"
registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile)
# get the trusted certs and save them in the right place
if verbose:
- print "Getting trusted certs from registry"
+ print("Getting trusted certs from registry")
trusted_certs = registry.get_trusted_certs(cred)
trusted_gid_names = []
for gid_str in trusted_certs:
trusted_gid_names.append(relative_filename)
gid_filename = trusted_certs_dir + os.sep + relative_filename
if verbose:
- print "Writing GID for %s as %s" % (gid.get_hrn(), gid_filename)
+ print("Writing GID for %s as %s" % (gid.get_hrn(), gid_filename))
gid.save_to_file(gid_filename, save_parents=True)
# remove old certs
for gid_name in all_gids_names:
if gid_name not in trusted_gid_names:
if verbose:
- print "Removing old gid ", gid_name
+ print("Removing old gid ", gid_name)
os.unlink(trusted_certs_dir + os.sep + gid_name)
@handle_gid_mismatch_exception
registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile)
if verbose:
- print "Getting current slices on this node"
+ print("Getting current slices on this node")
# get a list of slices on this node
from sfa.generic import Generic
generic=Generic.the_flavour()
return
if verbose:
- print "Getting gids for slices on this node from registry"
+ print("Getting gids for slices on this node from registry")
# get the gids
# and save them in the right palce
records = registry.GetGids(hrns, cred)
gid = record['gid']
slice_gid_filename = os.sep.join([vserver_path, "etc", "slice.gid"])
if verbose:
- print "Saving GID for %(slicename)s as %(slice_gid_filename)s" % locals()
+ print("Saving GID for %(slicename)s as %(slice_gid_filename)s" % locals())
GID(string=gid).save_to_file(slice_gid_filename, save_parents=True)
# save the node gid in /etc/sfa
node_gid_filename = os.sep.join([vserver_path, "etc", "node.gid"])
if verbose:
- print "Saving node GID for %(slicename)s as %(node_gid_filename)s" % locals()
+ print("Saving node GID for %(slicename)s as %(node_gid_filename)s" % locals())
node_gid.save_to_file(node_gid_filename, save_parents=True)
create_default_dirs()
if options.key:
if options.verbose:
- print "Getting the component's pkey"
+ print("Getting the component's pkey")
get_node_key(registry=options.registry, verbose=options.verbose)
if options.certs:
if options.verbose:
- print "Getting the component's trusted certs"
+ print("Getting the component's trusted certs")
get_trusted_certs(verbose=options.verbose)
if options.gids:
if options.verbose:
- print "Geting the component's GIDs"
+ print("Geting the component's GIDs")
get_gids(verbose=options.verbose)
def main():
+from __future__ import print_function
+
import sys
import traceback
def drop_table (self, tablename):
if self.table_exists (tablename):
- print >>sys.stderr, "%s: Dropping table %s"%(DBSchema.header,tablename)
+ print("%s: Dropping table %s"%(DBSchema.header,tablename), file=sys.stderr)
self.engine.execute ("drop table %s cascade"%tablename)
else:
- print >>sys.stderr, "%s: no need to drop table %s"%(DBSchema.header,tablename)
+ print("%s: no need to drop table %s"%(DBSchema.header,tablename), file=sys.stderr)
def handle_old_releases (self):
try:
# (.) we've just created the db, so it's either a fresh install, or
# (.) we come from a 'very old' depl.
# in either case, an import is required but there's nothing to clean up
- print >> sys.stderr,"%s: make sure to run import"%(DBSchema.header,)
+ print("%s: make sure to run import"%(DBSchema.header,), file=sys.stderr)
elif self.table_exists ('sfa_db_version'):
# we come from an 'old' version
self.drop_table ('records')
# we should be good here
pass
except:
- print >> sys.stderr, "%s: unknown exception"%(DBSchema.header,)
+ print("%s: unknown exception"%(DBSchema.header,), file=sys.stderr)
traceback.print_exc ()
# after this call the db schema and the version as known by migrate should
+from __future__ import print_function
+
from sfa.util.sfatime import utcparse, datetime_to_string
from types import StringTypes
from datetime import datetime
if format == 'text':
self.dump_text(dump_parents,sort=sort)
elif format == 'xml':
- print self.save_as_xml()
+ print(self.save_as_xml())
elif format == 'simple':
- print self.dump_simple()
+ print(self.dump_simple())
else:
raise Exception, "Invalid format %s" % format
def dump_text(self, dump_parents=False, sort=False):
- print 40*'='
- print "RECORD"
+ print(40*'=')
+ print("RECORD")
# print remaining fields
fields = self.fields()
if sort: fields.sort()
if callable (attrib): continue
# handle gid
if attrib_name == 'gid':
- print " gid:"
- print GID(string=attrib).dump_string(8, dump_parents)
+ print(" gid:")
+ print(GID(string=attrib).dump_string(8, dump_parents))
elif attrib_name in ['date created', 'last updated']:
- print " %s: %s" % (attrib_name, self.date_repr(attrib_name))
+ print(" %s: %s" % (attrib_name, self.date_repr(attrib_name)))
else:
- print " %s: %s" % (attrib_name, attrib)
+ print(" %s: %s" % (attrib_name, attrib))
def dump_simple(self):
return "%s"%self
# IN THE WORK.
#----------------------------------------------------------------------
+from __future__ import print_function
+
from sfa.trust.credential import Credential, append_sub, DEFAULT_CREDENTIAL_LIFETIME
from sfa.util.sfalogging import logger
from sfa.util.sfatime import SFATIME_FORMAT
result += "\nEnd XML\n"
except:
import traceback
- print "exc. Credential.dump_string / XML"
+ print("exc. Credential.dump_string / XML")
traceback.print_exc()
return result
##
#
+from __future__ import print_function
+
import functools
import os
import tempfile
return getattr(self,'filename',None)
def dump (self, *args, **kwargs):
- print self.dump_string(*args, **kwargs)
+ print(self.dump_string(*args, **kwargs))
def dump_string (self):
result=""
return getattr(self,'filename',None)
def dump (self, *args, **kwargs):
- print self.dump_string(*args, **kwargs)
+ print(self.dump_string(*args, **kwargs))
def dump_string (self,show_extensions=False):
result = ""
# Credentials are signed XML files that assign a subject gid privileges to an object gid
##
+from __future__ import print_function
+
import os, os.path
import subprocess
from types import StringTypes
#
# @param dump_parents If true, also dump the parent certificates
def dump (self, *args, **kwargs):
- print self.dump_string(*args, **kwargs)
+ print(self.dump_string(*args, **kwargs))
# SFA code ignores show_xml and disables printing the cred xml
def dump_string(self, dump_parents=False, show_xml=False):
result += "\nEnd XML\n"
except:
import traceback
- print "exc. Credential.dump_string / XML"
+ print("exc. Credential.dump_string / XML")
traceback.print_exc()
return result
# IN THE WORK.
#----------------------------------------------------------------------
+from __future__ import print_function
+
from sfa.util.sfalogging import logger
from sfa.trust.credential import Credential
from sfa.trust.abac_credential import ABACCredential
cred1 = CredentialFactory.createCred(credFile='/tmp/cred.xml')
cred2 = CredentialFactory.createCred(credString=c2)
- print "C1 = %s" % cred1
- print "C2 = %s" % cred2
+ print("C1 = %s" % cred1)
+ print("C2 = %s" % cred2)
c1s = cred1.dump_string()
- print "C1 = %s" % c1s
+ print("C1 = %s" % c1s)
# print "C2 = %s" % cred2.dump_string()
# descendant of the certificate class.
##
+from __future__ import print_function
+
import xmlrpclib
import uuid
# @param dump_parents If true, also dump the parents of the GID
def dump(self, *args, **kwargs):
- print self.dump_string(*args,**kwargs)
+ print(self.dump_string(*args,**kwargs))
def dump_string(self, indent=0, dump_parents=False):
result=" "*(indent-2) + "GID\n"
# implements SFA tickets
#
+from __future__ import print_function
+
import xmlrpclib
from sfa.trust.certificate import Certificate
self.gidObject = None
def dump(self, dump_parents=False):
- print "TICKET", self.get_subject()
+ print("TICKET", self.get_subject())
- print " gidCaller:"
+ print(" gidCaller:")
gidCaller = self.get_gid_caller()
if gidCaller:
gidCaller.dump(8, dump_parents)
- print " gidObject:"
+ print(" gidObject:")
gidObject = self.get_gid_object()
if gidObject:
gidObject.dump(8, dump_parents)
- print " attributes:"
+ print(" attributes:")
for attrname in self.get_attributes().keys():
- print " ", attrname, self.get_attributes()[attrname]
+ print(" ", attrname, self.get_attributes()[attrname])
- print " rspec:"
- print " ", self.get_rspec()
+ print(" rspec:")
+ print(" ", self.get_rspec())
if self.parent and dump_parents:
- print "PARENT",
+ print("PARENT", end=' ')
self.parent.dump(dump_parents)
+from __future__ import print_function
+
class prefixNode:
def __init__(self, prefix):
"""
if not node:
node = self.root
- print node.prefix
+ print(node.prefix)
for child in node.children:
- print child.prefix,
+ print(child.prefix, end=' ')
for child in node.children:
self.dump(child)
# IN THE WORK.
#----------------------------------------------------------------------
+from __future__ import print_function
+
import os, sys
import traceback
import logging, logging.handlers
if __name__ == '__main__':
- print 'testing sfalogging into logger.log'
+ print('testing sfalogging into logger.log')
logger1=_SfaLogger('logger.log', loggername='std(info)')
logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR)
logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]:
- print "====================",msg, logger.logger.handlers
+ print("====================",msg, logger.logger.handlers)
logger.enable_console()
logger.critical("logger.critical")
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
+from __future__ import print_function
+
from types import StringTypes
import time
import datetime
if __name__ == '__main__':
# checking consistency
- print 20*'X'
- print ("Should be close to zero: %s"%(datetime_to_epoch(datetime.datetime.utcnow())-time.time()))
- print 20*'X'
+ print(20*'X')
+ print(("Should be close to zero: %s"%(datetime_to_epoch(datetime.datetime.utcnow())-time.time())))
+ print(20*'X')
for input in [
'+2d',
'+3w',
'2014-05-28T15:18',
'2014-05-28T15:18:30',
]:
- print "input=%20s -> parsed %s"%(input,datetime_to_string(utcparse(input)))
+ print("input=%20s -> parsed %s"%(input,datetime_to_string(utcparse(input))))