myfiles: force
@git ls-files | egrep -v 'insert(_|-)above|third-party/|to-be-integrated/'
+pyfiles: force
+ @git ls-files | grep '\.py$$'
+
# in general it's right to rely on the contents as reported by git
tags: force
$(MAKE-SILENT) myfiles | xargs etags
# The secret is a 64 chars string that is used to sign the request
# The generated signature is a SHA256 hes digest
+from __future__ import print_function
+
import urllib, urllib2
import threading
import hmac
def logWrite(request, action, message, objects = None):
if not apikey :
- print "===============>> activity: no apikey"
+ print("===============>> activity: no apikey")
return
if not secret :
- print "===============>> activity: no secret"
+ print("===============>> activity: no secret")
return
timestamp = time.mktime(datetime.datetime.today().timetuple())
try :
result = urllib2.urlopen(server, urllib.urlencode(log))
- print "===============>> activity: %s <%s> %s" % (action, request.user,message)
+ print("===============>> activity: %s <%s> %s" % (action, request.user,message))
content = result.read()
except urllib2.URLError as e:
- print "===============>> activity: connection to " + server + " impossible, could not log action"
- print e.strerror
- print ""
+ print("===============>> activity: connection to " + server + " impossible, could not log action")
+ print(e.strerror)
+ print("")
def log(request, action, message, objects = None):
# Create a new thread in Daemon mode to send the log entry
#
# sign the request with the secret key
def sign(secret, message):
- return hmac.new(secret, msg=message, digestmod=hashlib.sha256).hexdigest()
\ No newline at end of file
+ return hmac.new(secret, msg=message, digestmod=hashlib.sha256).hexdigest()
sessions_result = api.forward(Query.create('local:session').to_dict())
sessions = sessions_result.ok_value()
if not sessions:
- logger.error("GetSession failed", sessions_result.error())
+ logger.error("GetSession failed: {}".format(sessions_result.error()))
return
session = sessions[0]
- logger.debug("SESSION : %s" % session)
+ logger.debug("SESSION : {}".format(session))
# Change to session authentication
api.auth = {'AuthMethod': 'session', 'session': session['session']}
persons_result = api.forward(Query.get('local:user').to_dict())
persons = persons_result.ok_value()
if not persons:
- logger.error("GetPersons failed",persons_result.error())
+ logger.error("GetPersons failed: {}".format(persons_result.error()))
return
person = persons[0]
- logger.debug("PERSON : %s" % person)
- #logger.info("%s %s <%s> logged in" % (person['config']['first_name'], person['config']['last_name'], person['config']['email']))
+ logger.debug("PERSON : {}".format(person))
+ #logger.info("{} {} <{}> logged in"\
+ # .format(person['config']['first_name'], person['config']['last_name'], person['config']['email']))
request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
- except ManifoldException, e:
- logger.error("Manifold Auth Backend: %s" % e.manifold_result)
- except Exception, e:
- logger.error("Manifold Auth Backend: %s" % e)
- #import traceback
- #traceback.print_exc()
+ except ManifoldException as e:
+ logger.error("ManifoldException in Auth Backend: {}".format(e.manifold_result))
+ except Exception as e:
+ logger.error("Exception in Manifold Auth Backend: {}".format(e))
+ import traceback
+ traceback.print_exc()
return None
try:
+from __future__ import print_function
+
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
# check that we're indeed logged in
if not request.user.is_authenticated():
return HttpResponseRedirect ('/')
- print "LOGGING OUT"
+ print("LOGGING OUT")
# log user activity
activity.user.logout(request)
# Manifold API Python interface
-import copy, xmlrpclib, ssl
-from myslice.settings import config, logger, DEBUG
+from __future__ import print_function
+
+import copy
+import xmlrpclib
+import ssl
from django.contrib import messages
from django.shortcuts import redirect
-from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
+
from manifold.core.result_value import ResultValue
-debug_deep=False
-#debug_deep=True
+from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
+
+from myslice.settings import config, logger
class ManifoldAPI:
# Manifold uses a self signed certificate
# https://www.python.org/dev/peps/pep-0476/
if hasattr(ssl, '_create_unverified_context'):
- self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True, context=ssl._create_unverified_context())
+ self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
+ context=ssl._create_unverified_context())
else :
self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
def func(*args, **kwds):
import time
-
start = time.time()
+
+ # the message to display
+ auth_message = "<AuthMethod not set in {}>".format(auth) if 'AuthMethod' not in self.auth \
+ else "[session]" if self.auth['AuthMethod'] == 'session' \
+ else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
+ else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
+ else "[???]" + "{}".format(self.auth)
+ end_message = "MANIFOLD {}( {}( {} ) ) with auth={} to {}"\
+ .format(methodName,
+ args[0]['action'] or '',
+ args[0]['object'] or '',
+ auth_message,
+ self.url)
try:
-
- #logger.debug("MANIFOLD %s( %s( %s ) ) to %s" % (methodName, args[0]['action'], args[0]['object'], self.url))
-
- if ('Username' in self.auth) :
- username = self.auth['Username']
- else :
- username = "-"
-
args += ({ 'authentication': self.auth },)
-
result = getattr(self.server, methodName)(*args, **kwds)
-
- logger.debug("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" %
- (methodName,
- args[0]['action'] or '',
- args[0]['object'] or '',
- username,
- self.url,
- (time.time() - start),
- args))
-
+ logger.debug("{} executed in {} seconds -> {}"\
+ .format(end_message, time.time() - start, truncate_result(result)))
return ResultValue(**result)
- except Exception, error:
- if True:
- print "===== xmlrpc catch-all exception:", error
- import traceback
- traceback.print_exc(limit=3)
+ except Exception as error:
+ print("===== xmlrpc catch-all exception:", error)
+ import traceback
+ traceback.print_exc(limit=3)
if "Connection refused" in error:
raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
- output="%s answered %s" % (self.url,error)))
+ output="{} answered {}".format(self.url, error)))
# otherwise
- logger.error("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" %
- (methodName,
- args[0]['action'] or '',
- args[0]['object'] or '',
- username,
- self.url,
- (time.time() - start),
- args))
- logger.error("MANIFOLD %s", error)
- raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE, output = "%s" % error) )
+ logger.error("{} FAILED - executed in {} seconds"\
+ .format(end_message, time.time() - start))
+ logger.error("MANIFOLD {}".format(error))
+ raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
+ output = "{}".format(error)))
return func
manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
- logger.debug("MANIFOLD QUERY : %s" % " ".join(str(query).split()))
- #logger.debug("MANIFOLD DICT : %s" % query.to_dict())
+ logger.debug("MANIFOLD QUERY : {}".format(" ".join(str(query).split())))
+ #logger.debug("MANIFOLD DICT : {}".format(query.to_dict()))
result = manifold_api.forward(query.to_dict())
if result['code'] == 2:
# this is gross; at the very least we need to logout()
del request.session['manifold']
# Flush django session
request.session.flush()
- #raise Exception, 'Error running query: %r' % result
+ #raise Exception, 'Error running query: {}'.format(result)
if result['code'] == 1:
- log.warning("MANIFOLD : %s" % result['description'])
+ log.warning("MANIFOLD : {}".format(result['description']))
# XXX Handle errors
#Error running query: {'origin': [0, 'XMLRPCAPI'], 'code': 2, 'description': 'No such session: No row was found for one()', 'traceback': 'Traceback (most recent call last):\n File "/usr/local/lib/python2.7/dist-packages/manifold/core/xmlrpc_api.py", line 68, in xmlrpc_forward\n user = Auth(auth).check()\n File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 245, in check\n return self.auth_method.check()\n File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 95, in check\n raise AuthenticationFailure, "No such session: %s" % e\nAuthenticationFailure: No such session: No row was found for one()\n', 'type': 2, 'ts': None, 'value': None}
def execute_admin_query(request, query):
admin_user, admin_password = config.manifold_admin_user_password()
+ if not admin_user or not admin_password:
+ logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
+Some functions won't work properly until you do so""")
admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
return _execute_query(request, query, admin_auth)
+from __future__ import print_function
+
import json
import os.path
#
# resource reservation
if (manifold_query.action.lower() == 'update') :
- print result['value'][0]
+ print(result['value'][0])
if 'resource' in result['value'][0] :
for resource in result['value'][0]['resource'] :
activity.slice.resource(request,
# this however turns out disappointing/not very informative
failure_answer=[ "csrf_failure" ]
def csrf_failure(request, reason=""):
- print "CSRF failure with reason '%s'"%reason
+ print("CSRF failure with reason '%s'"%reason)
return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")
+# black magic to define enums
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
SERVER_UNREACHABLE=3,
)
+def truncate(result, length=50):
+ plain = "{}".format(result)
+ if len(plain) <= length-3:
+ return plain
+ else:
+ return plain[:(length-3)]+'...'
+
_messages_ = { -1 : "Unknown", 0: "OK", 1: "Session Expired", 2: "Not Implemented", 3: "Backend server unreachable"}
+def truncate_result(result, length=50):
+ self = result
+ code = self['code']
+ result = "[MFresult {} (code={})".format(_messages_.get(code, "???"), code)
+ if code == 0:
+ value = self['value']
+ if isinstance(value, list):
+ result += " [value=list with {} elts]".format(len(value))
+ elif isinstance(value, dict):
+ result += " [value=dict with keys {}]".format(value.keys())
+ else:
+ result += " [value={}: {}]".format(type(value).__name__, value)
+ elif 'output' in self:
+ result += " [output={}]".format(self['output'])
+ else:
+ result += "<no output>"
+ result += "]"
+ return truncate(result, 60)
+
# being a dict this can be used with json.dumps
class ManifoldResult (dict):
def __init__ (self, code=ManifoldCode.SUCCESS, value=None, output=""):
- self['code']=code
- self['value']=value
- self['output']=output
+ self['code'] = code
+ self['value'] = value
+ self['output'] = output
self['description'] = '' # Jordan: needed by javascript code
def from_json (self, json_string):
d=json.dumps(json_string)
- for k in ['code','value','output']:
- self[k]=d[k]
+ for k in ['code', 'value', 'output']:
+ self[k] = d[k]
# raw accessors
- def code (self): return self['code']
- def output (self): return self['output']
+ def code (self):
+ return self['code']
+ def output (self):
+ return self['output']
# this returns None if there's a problem, the value otherwise
def ok_value (self):
- if self['code']==ManifoldCode.SUCCESS:
+ if self['code'] == ManifoldCode.SUCCESS:
return self['value']
# both data in a single string
def error (self):
- return "code=%s -- %s"%(self['code'],self['output'])
+ return "code={} -- {}".format(self['code'], self['output'])
def __repr__ (self):
- code=self['code']
- result="[MFresult %s (code=%s)"%(_messages_.get(code,"???"),code)
- if code==0:
- value=self['value']
- if isinstance(value,list): result += " [value=list with %d elts]"%len(value)
- elif isinstance(value,dict): result += " [value=dict with keys %s]"%value.keys()
- else: result += " [value=%s: %s]"%(type(value).__name__,value)
- else:
- result += " [output=%s]"%self['output']
- result += "]"
- return result
+ return truncate_result(self, 60)
# probably simpler to use a single class and transport the whole result there
# instead of a clumsy set of derived classes
def __init__ (self, manifold_result):
self.manifold_result=manifold_result
def __repr__ (self):
- return "Manifold Exception %s"%(self.manifold_result.error())
+ return "<Manifold Exception {}>".format(self.manifold_result.error())
+from __future__ import print_function
+
import json
import os.path
# xxx need a way to export error messages to the UI
if result['code'] == 1: # warning
# messages.warning(request, result['description'])
- print ("METADATA WARNING -",request,result['description'])
+ print(("METADATA WARNING -",request,result['description']))
elif result['code'] == 2:
# messages.error(request, result['description'])
- print ("METADATA ERROR -",request,result['description'])
+ print(("METADATA ERROR -",request,result['description']))
# XXX FAIL HERE XXX
return
return self.hash_by_object[object]['column'].sort()
def get_field_type(self, object, field):
- if debug: print "Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon"
+ if debug: print("Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon")
return field
# our django project
'myslice',
# the core of the UI
- 'auth',
+ 'localauth',
'manifoldapi',
'unfold',
# plugins
for aux in auxiliaries:
if os.path.isdir(os.path.join(ROOT,aux)):
- print("Using devel auxiliary",aux)
+ print(("Using devel auxiliary",aux))
INSTALLED_APPS.append(aux)
ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.
}
}
-AUTHENTICATION_BACKENDS = ('auth.manifoldbackend.ManifoldBackend',
+AUTHENTICATION_BACKENDS = ('localauth.manifoldbackend.ManifoldBackend',
'django.contrib.auth.backends.ModelBackend')
### the view to redirect malformed (i.e. with a wrong CSRF) incoming requests
# admin.autodiscover()
# to enable insert_above stuff
-from django.template.loader import add_to_builtins
+# add_to_builtins has changed location with django-1.7
+# also note this will probably go away some day
+try:
+ from django.template.loader import add_to_builtins
+except:
+ from django.template.base import add_to_builtins
add_to_builtins('insert_above.templatetags.insert_tags')
from settings import auxiliaries, INSTALLED_APPS
# seems to be what login_required uses to redirect ...
(r'^accounts/login/$', portal.homeview.HomeView.as_view()),
(r'^login/?$', portal.homeview.HomeView.as_view()),
- (r'^logout/?$', 'auth.views.logout_user'),
+ (r'^logout/?$', 'localauth.views.logout_user'),
#
# the manifold proxy
(r'^manifold/proxy/(?P<format>\w+)/?$', 'manifoldapi.manifoldproxy.proxy'),
def __init__ (self, **settings):
Plugin.__init__(self, **settings)
- print "SETTINGS", settings
assert 'page' in settings, "You should specify page"
assert 'object' in settings, "You should specify object"
+from __future__ import print_function
+
from unfold.plugin import Plugin
class QueryGrid (Plugin):
if self.checkboxes:
# we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
if 'aoColumns' in self.datatables_options:
- print 'WARNING: querygrid uses aoColumnDefs, your aoColumns spec. is discarded'
+ print('WARNING: querygrid uses aoColumnDefs, your aoColumns spec. is discarded')
del self.datatables_options['aoColumns']
# set aoColumnDefs in datatables_options - might already have stuff in there
aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
+from __future__ import print_function
+
from unfold.plugin import Plugin
class QueryTable (Plugin):
_columns = columns
_hidden_columns = []
elif self.query:
- print "self.query.fields = ", self.query_all.fields
+ print("self.query.fields = ", self.query_all.fields)
# Columns displayed by default
if self.default_fields is not None:
_columns = [field for field in self.default_fields if not field == 'urn']
if query_all:
# We need a list because sets are not JSON-serializable
if self.default_fields is not None:
- print self.query_all.fields
+ print(self.query_all.fields)
_hidden_columns = list(self.query_all.fields - set(self.default_fields))
else:
_hidden_columns = list(self.query_all.fields - self.query.fields)
_columns = []
_hidden_columns = []
- print "_columns=", _columns
+ print("_columns=", _columns)
self.columns = { self.mapping.get(c, c) : c for c in _columns }
self.hidden_columns = { self.mapping.get(c, c) : c for c in _hidden_columns }
- print "self.columns", self.columns
- print "self.hidden_columns", self.hidden_columns
+ print("self.columns", self.columns)
+ print("self.hidden_columns", self.hidden_columns)
self.init_key=init_key
self.datatables_options=datatables_options
if self.checkboxes:
# we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
if 'aoColumns' in self.datatables_options:
- print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+ print('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
del self.datatables_options['aoColumns']
# set aoColumnDefs in datatables_options - might already have stuff in there
aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
+from __future__ import print_function
+
from unfold.plugin import Plugin
class Univbris(Plugin):
def __init__ (self, query=None, **settings):
Plugin.__init__ (self, **settings)
self.query=query
- self.query_uuid = query.query_uuid if query else None
- print "called univbris plugin"
+ self.query_uuid = query.query_uuid if query else None
+ print("called univbris plugin")
def template_file (self):
try:
return "univbris_welcome.html"
except Exception:
- print "error template"
+ print("error template")
def requirements (self):
reqs = {
'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
"js/manifold.js", "js/manifold-query.js",
"js/unfold-helper.js",
- 'js/univbris.js',
+ 'js/univbris.js',
],
'css_files': [
'css/univbris.css',
# query_uuid will pass self.query results to the javascript
# and will be available as "record" in :
# on_new_record: function(record)
- return ['plugin_uuid', 'domid', 'query_uuid','init_key',]
+ return ['plugin_uuid', 'domid', 'query_uuid', 'init_key', ]
def export_json_settings (self):
return True
+from __future__ import print_function
+
from unfold.plugin import Plugin
class UnivbrisFoam (Plugin):
# Until we have a proper way to access queries in Python
self.query_all = query_all
self.query_all_uuid = query_all.query_uuid if query_all else None
- self.sync_query_uuid = sync_query.query_uuid if sync_query else None
+ self.sync_query_uuid = sync_query.query_uuid if sync_query else None
self.checkboxes = checkboxes
# XXX We need to have some hidden columns until we properly handle dynamic queries
if columns is not None:
self.columns=columns
self.hidden_columns = []
elif self.query:
- self.columns = list (['testbed','head node id/port','tail node id/port','link type','selected'])
- #replace production
+ self.columns = list (['testbed','head node id/port','tail node id/port','link type','selected'])
+ #replace production
#self.columns = self.query.fields
if query_all:
#replace production
- self.hidden_columns = []
- # We need a list because sets are not JSON-serializable
+ self.hidden_columns = []
+ # We need a list because sets are not JSON-serializable
#self.hidden_columns = #list(self.query_all.fields - self.query.fields)
else:
self.hidden_columns = []
if self.checkboxes:
# we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
if 'aoColumns' in self.datatables_options:
- print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+ print('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
del self.datatables_options['aoColumns']
# set aoColumnDefs in datatables_options - might already have stuff in there
aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
+from __future__ import print_function
+
from unfold.plugin import Plugin
class UnivbrisFv (Plugin):
self.columns=columns
self.hidden_columns = []
elif self.query:
- self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
- #replace production
+ self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
+ #replace production
#self.columns = self.query.fields
if query_all:
#replace production
- self.hidden_columns = []
- # We need a list because sets are not JSON-serializable
+ self.hidden_columns = []
+ # We need a list because sets are not JSON-serializable
#self.hidden_columns = #list(self.query_all.fields - self.query.fields)
else:
self.hidden_columns = []
self.columns = []
self.hidden_columns = []
- self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
+ self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
self.init_key=init_key
self.datatables_options=datatables_options
# if checkboxes were required, we tell datatables about this column's type
if self.checkboxes:
# we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
if 'aoColumns' in self.datatables_options:
- print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+ print('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
del self.datatables_options['aoColumns']
# set aoColumnDefs in datatables_options - might already have stuff in there
aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
def requirements (self):
reqs = {
'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
- "js/dataTables.js", "js/dataTables.bootstrap.js", "js/with-datatables.js", "js/jquery.jeditable.js",
+ "js/dataTables.js", "js/dataTables.bootstrap.js",
+ "js/with-datatables.js", "js/jquery.jeditable.js",
"js/manifold.js", "js/manifold-query.js",
"js/unfold-helper.js",
# querytable.js needs to be loaded after dataTables.js as it extends
# dataTableExt.afnSortData
- # "js/jquery-ui.min.js" "js/jquery.dataTables.editable.js", "js/jquery.validate.js",
+ # "js/jquery-ui.min.js" "js/jquery.dataTables.editable.js", "js/jquery.validate.js",
"js/univbrisfv.js",#"js/univbrisfv.js",
] ,
'css_files': [ "css/dataTables.bootstrap.css",
+from __future__ import print_function
+
from unfold.plugin import Plugin
class UnivbrisTopo(Plugin):
def __init__ (self, query=None, **settings):
Plugin.__init__ (self, **settings)
self.query=query
- self.query_uuid = query.query_uuid if query else None
- print "called univbris topo plugin"
+ self.query_uuid = query.query_uuid if query else None
+ print("called univbris topo plugin")
def template_file (self):
- try:
- return "univbris_topology.html"
- except:
- print "error template"
+ try:
+ return "univbris_topology.html"
+ except:
+ print("error template")
def requirements (self):
reqs = {
- 'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
- "js/manifold.js", "js/manifold-query.js",
- "js/unfold-helper.js",
+ 'js_files' : [
+ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
+ "js/manifold.js", "js/manifold-query.js",
+ "js/unfold-helper.js",
'js/univbristopo.js', 'js/d3.v2.min.js','js/tooltip.topology.js',
],
'css_files': [
+from __future__ import print_function
+
from unfold.plugin import Plugin
class UnivbrisVtam (Plugin):
datatables_options={}, **settings):
Plugin.__init__ (self, **settings)
self.query = query
- self.query_uuid = query.query_uuid if query else None
+ self.query_uuid = query.query_uuid if query else None
# Until we have a proper way to access queries in Python
self.query_all = query_all
self.query_all_uuid = query_all.query_uuid if query_all else None
- self.sync_query_uuid = sync_query.query_uuid if sync_query else None
+ self.sync_query_uuid = sync_query.query_uuid if sync_query else None
self.checkboxes = checkboxes
# XXX We need to have some hidden columns until we properly handle dynamic queries
if columns is not None:
self.columns=columns
self.hidden_columns = []
elif self.query:
- self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
- #replace production
+ self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
+ #replace production
#self.columns = self.query.fields
if query_all:
#replace production
- self.hidden_columns = []
- # We need a list because sets are not JSON-serializable
+ self.hidden_columns = []
+ # We need a list because sets are not JSON-serializable
#self.hidden_columns = #list(self.query_all.fields - self.query.fields)
else:
self.hidden_columns = []
self.columns = []
self.hidden_columns = []
- self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
+ self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
self.init_key=init_key
self.datatables_options=datatables_options
# if checkboxes were required, we tell datatables about this column's type
if self.checkboxes:
# we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
if 'aoColumns' in self.datatables_options:
- print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+ print('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
del self.datatables_options['aoColumns']
# set aoColumnDefs in datatables_options - might already have stuff in there
aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
+from __future__ import print_function
+
from unfold.loginrequired import LoginRequiredAutoLogoutView
#
#
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query
-from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds
+from portal.actions import (
+ manifold_update_user, manifold_update_account, manifold_add_account,
+ manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds )
#
from unfold.page import Page
from ui.topmenu import topmenu_items_live, the_user
from django.contrib import messages
from django.contrib.auth.decorators import login_required
-from myslice.configengine import ConfigEngine
+from myslice.configengine import ConfigEngine
from myslice.theme import ThemeView
from portal.account import Account, get_expiration
if user_email == request.user.email:
authorize_query = True
else:
- print "SECURITY: %s tried to update %s" % (user_email, request.user.email)
+ print("SECURITY: %s tried to update %s" % (user_email, request.user.email))
messages.error(request, 'You are not authorized to modify another user.')
return HttpResponseRedirect("/portal/account/")
except Exception,e:
- print "Exception = %s" % e
+ print("Exception = %s" % e)
for account_detail in account_details:
for platform_detail in platform_details:
raise Exception,"Keys are not matching"
except Exception, e:
messages.error(request, 'Error: An error occured during the update of your public key at the Registry, or your public key is not matching the one stored.')
- print "Exception in accountview ", e
+ print("Exception in accountview ", e)
return HttpResponseRedirect("/portal/account/")
else:
messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
else:
messages.error(request, 'Delete error: Credentials are not stored in the server')
except Exception,e:
- print "Exception in accountview.py in clear_user_creds %s" % e
+ print("Exception in accountview.py in clear_user_creds %s" % e)
messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
return HttpResponseRedirect("/portal/account/")
+from __future__ import print_function
+
from django.http import HttpResponse
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query,execute_admin_query
return pi_status
except Exception,e:
- print "Exception in actions.py in authority_check_pis %s" % e
+ print("Exception in actions.py in authority_check_pis %s" % e)
return None
newpis = authority_get_pis (request, authority_hrn)
return newpis
except Exception,e:
- print "Exception in actions.py in authority_add_pis %s" % e
+ print("Exception in actions.py in authority_add_pis %s" % e)
return None
newpis = authority_get_pis (request, authority_hrn)
return newpis
except Exception,e:
- print "Exception in actions.py in authority_remove_pis %s" % e
+ print("Exception in actions.py in authority_remove_pis %s" % e)
return None
def authority_get_pi_emails(request, authority_hrn):
pi_users = authority_get_pis(request,authority_hrn)
- print "pi_users = %s" % pi_users
+ print("pi_users = %s" % pi_users)
if any(pi['pi_users'] == None or not pi['pi_users'] for pi in pi_users):
#theme.template_name = 'email_default_recipients.txt'
return None
except Exception,e:
- print "Exception in actions.py in clear_user_creds %s" % e
+ print("Exception in actions.py in clear_user_creds %s" % e)
return None
def is_pi(wsgi_request, user_hrn, authority_hrn):
# authorities from user where user_hrn == "ple.upmc.jordan_auge"
- print "#### actions.py is_pi authority_hrn = ", authority_hrn
+ print("#### actions.py is_pi authority_hrn = ", authority_hrn)
try:
# CACHE PB with fields
page = Page(wsgi_request)
if authority_hrn in user_detail['pi_authorities']:
return True
except Exception,e:
- print "Exception in actions.py in is_pi %s" % e
+ print("Exception in actions.py in is_pi %s" % e)
return False
# SFA get record
# REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
query = Query.create('myslice:authority').set(authority_params).select('authority_hrn')
results = execute_query(request, query)
- print "sfa_add_auth results=",results
+ print("sfa_add_auth results=",results)
if not results:
raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn']
return results
return request
def make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins):
- print "$$$$$$$$$$$$$$$ make_request"
+ print("$$$$$$$$$$$$$$$ make_request")
requests = []
for user in pending_users:
requests.append(make_request_user(user))
return requests
def get_request_by_id(ids):
- print "$$$$$$$$$$$$$$$$ get_request_by_id"
+ print("$$$$$$$$$$$$$$$$ get_request_by_id")
sorted_ids = { 'user': [], 'slice': [], 'authority': [], 'project': [], 'join': [] }
for type__id in ids:
type, id = type__id.split('__')
return make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins)
def get_requests(authority_hrns=None):
- print "$$$$$$$$$$$$$ get_request_by_authority auth_hrns = ", authority_hrns
+ print("$$$$$$$$$$$$$ get_request_by_authority auth_hrns = ", authority_hrns)
if not authority_hrns:
## get those pending users who have confirmed their emails
pending_users = PendingUser.objects.filter(status__iexact = 'True')
#'pi' : None,
#'enabled' : True
}
- print "ADD Authority"
+ print("ADD Authority")
sfa_add_authority(wsgi_request, sfa_authority_params)
request_status['SFA authority'] = {'status': True }
PendingAuthority.objects.get(id=request['id']).delete()
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
# removing from Django portal_pendinguser
PendingUser.objects.get(id=request['id']).delete()
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
PendingSlice.objects.get(id=request['id']).delete()
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
PendingAuthority.objects.get(id=request['id']).delete()
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
return results
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
def create_pending_project(wsgi_request, request):
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
return results
iotlab_user_params1 = json.dumps(iotlab_user_params)
r=requests.post(url=URL_REST, data=iotlab_user_params1, headers=headers, auth=auth)
- print 'Create iotlab user : ', r.status_code, r.text
+ print('Create iotlab user : ', r.status_code, r.text)
return r.text
def create_user(wsgi_request, request, namespace = None, as_admin = False):
}
manifold_add_account(wsgi_request, account_params)
except Exception, e:
- print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email'])
+ print("Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email']))
try:
# Send an email: the recipients are the PI of the authority
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
import traceback
traceback.print_exc()
+from __future__ import print_function
+
import json
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query
#messages.info(self.request, 'You have logged in')
page = Page(self.request)
- print "Dashboard page"
+ print("Dashboard page")
# Slow...
#slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
testbed_query = Query().get('network').select('network_hrn','platform','version')
# root_authority = sub_authority[0]
# slice_query = Query().get(root_authority+':user').filter_by('user_hrn', '==', '$user_hrn').select('user_hrn', 'slice.slice_hrn')
# else:
- print "SLICE QUERY"
- print "-" * 80
+ print("SLICE QUERY")
+ print("-" * 80)
slice_query = Query().get('myslice:user').filter_by('user_hrn', '==', '$user_hrn').select('slices.slice_hrn')
page.enqueue_query(slice_query)
page.enqueue_query(testbed_query)
+from __future__ import print_function
+
from unfold.loginrequired import FreeAccessView
#
from manifold.core.query import Query
if 'enabled' in result and result['enabled']==True:
return True
except Exception, e:
- print "Exception in myplc query = ",e
+ print("Exception in myplc query = ",e)
return False
# this program; see the file COPYING. If not, write to the Free Software
# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+from __future__ import print_function
+
from django import forms
from portal.models import PendingUser, PendingSlice
#from crispy_forms.helper import FormHelper
email = loader.render_to_string(email_template_name, c)
send_mail(subject, email, from_email, [user.email])
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
class SetPasswordForm(forms.Form):
+from __future__ import print_function
+
# this somehow is not used anymore - should it not be ?
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
class HomeView (FreeAccessView, ThemeView):
template_name = 'home-view.html'
-
+
# expose this so we can mention the backend URL on the welcome page
def default_env (self):
- return {
+ return {
'MANIFOLD_URL':ConfigEngine().manifold_url(),
}
env = self.default_env()
env['theme'] = self.theme
env['section'] = "Dashboard"
-
+
username = request.POST.get('username')
password = request.POST.get('password')
-
+
# pass request within the token, so manifold session key can be attached to the request session.
- token = {'username': username, 'password': password, 'request': request}
+ token = {'username': username, 'password': password, 'request': request}
# our authenticate function returns either
# . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
manifoldresult = auth_result
# let's use ManifoldResult.__repr__
env['state']="%s"%manifoldresult
-
+
return render_to_response(self.template,env, context_instance=RequestContext(request))
# user was authenticated at the backend
elif auth_result is not None:
user=auth_result
if user.is_active:
login(request, user)
-
- if request.user.is_authenticated():
+
+ if request.user.is_authenticated():
env['person'] = self.request.user
env['username'] = self.request.user
-
+
# log user activity
activity.user.login(self.request)
-
+
## check user is pi or not
platform_details = {}
account_details = {}
# pi = "is_not_pi"
#else:
# pi = "is_pi"
- user_email = str(self.request.user)
+ user_email = str(self.request.user)
pi = authority_check_pis(self.request, user_email)
# check if the user has creds or not
env['pending_slices'] = pending_slices
env['pi'] = pi
- env['user_cred'] = user_cred
- else:
+ env['user_cred'] = user_cred
+ else:
env['person'] = None
return render_to_response(self.template,env, context_instance=RequestContext(request))
else:
activity.user.login(self.request, "notactive")
env['state'] = "Your account is not active, please contact the site admin."
env['layout_1_or_2']="layout-unfold2.html"
-
+
return render_to_response(self.template,env, context_instance=RequestContext(request))
# otherwise
else:
# log user activity
activity.user.login(self.request, "error")
env['state'] = "Your username and/or password were incorrect."
-
+
return render_to_response(self.template, env, context_instance=RequestContext(request))
def get (self, request, state=None):
env = self.default_env()
acc_auth_cred={}
if request.user.is_authenticated():
-
+
## check user is pi or not
platform_details = {}
account_details = {}
# pi = "is_not_pi"
#else:
# pi = "is_pi"
- user_email = str(self.request.user)
+ user_email = str(self.request.user)
pi = authority_check_pis(self.request, user_email)
# check if the user has creds or not
if acc_user_cred == {} or acc_user_cred == 'N/A':
pending_slices = []
for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
pending_slices.append(slices.slice_name)
-
+
env['pending_slices'] = pending_slices
env['pi'] = pi
- env['user_cred'] = user_cred
+ env['user_cred'] = user_cred
env['person'] = self.request.user
- else:
+ else:
env['person'] = None
env['theme'] = self.theme
if state: env['state'] = state
elif not env['username']: env['state'] = None
# use one or two columns for the layout - not logged in users will see the login prompt
-
+
# account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
# account_details = execute_query(self.request, account_query)
# for account_detail in account_details:
# acc_user_cred = account_config.get('delegated_user_credential','N/A')
# acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
# acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
-#
+#
# if 'N/A' not in acc_user_cred:
# exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
# if exp_date:
# user_exp_date = exp_date.group(1)
# user_cred_exp_list.append(user_exp_date)
-#
+#
# my_users = [{'cred_exp': t[0]}
# for t in zip(user_cred_exp_list)]
-#
-#
+#
+#
# if 'N/A' not in acc_slice_cred:
# for key, value in acc_slice_cred.iteritems():
# slice_list.append(key)
# if exp_date:
# exp_date = exp_date.group(1)
# slice_cred_exp_list.append(exp_date)
-#
+#
# my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
# for t in zip(slice_list, slice_cred_exp_list)]
-#
+#
# if 'N/A' not in acc_auth_cred:
# for key, value in acc_auth_cred.iteritems():
# auth_list.append(key)
# exp_date = exp_date.group(1)
# auth_cred_exp_list.append(exp_date)
-
+
return render_to_response(self.template, env, context_instance=RequestContext(request))
+from __future__ import print_function
+
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
else:
env['person'] = None
- print "BEFORE ####------#### is_pi"
+ print("BEFORE ####------#### is_pi")
pi = is_pi(self.request, '$user_hrn', env['user_details']['parent_authority'])
- print "is_pi = ",is_pi
+ print("is_pi = ",is_pi)
env['theme'] = self.theme
env['section'] = "Institution"
+from __future__ import print_function
+
import os.path, re
import json
from random import randint
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ print("Failed to send email, please check the mail templates and the SMTP configuration of your server")
import traceback
traceback.print_exc()
+from __future__ import print_function
+
# this somehow is not used anymore - should it not be ?
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
user_local_query = Query().get('local:user').select('config').filter_by('email','==',str(self.request.user))
user_local_details = execute_query(self.request, user_local_query)
user_authority = json.loads(user_local_details[0]['config']).get('authority')
- print "**************________ management about = ",user_authority
+ print("**************________ management about = ",user_authority)
# XXX Should be done using Metadata
# select column.name from local:object where table=='authority'
authority_query = Query().get('authority').select('authority_hrn', 'name', 'address', 'enabled','description',
+from __future__ import print_function
+
from django.template import RequestContext
from django.shortcuts import render_to_response
sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
sfa_platforms = execute_query(self.request, sfa_platforms_query)
for sfa_platform in sfa_platforms:
- print "SFA PLATFORM > ", sfa_platform['platform']
+ print("SFA PLATFORM > ", sfa_platform['platform'])
if not 'auth_type' in sfa_platform:
continue
auth = sfa_platform['auth_type']
all_authorities.append(auth)
platform_ids.append(sfa_platform['platform_id'])
- print "W: Hardcoding platform myslice"
+ print("W: Hardcoding platform myslice")
# There has been a tweak on how new platforms are referencing a
# so-called 'myslice' platform for storing authentication tokens.
# XXX This has to be removed in final versions.
for pa in pi_authorities_tmp:
pi_authorities |= set(pa['pi_authorities'])
except:
- print 'No pi_authorities'
+ print('No pi_authorities')
pi_credential_authorities = pi_authorities & credential_authorities
pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
#from django.core.validators import validate_email
-try:
- from django.contrib.auth import get_user_model
- User = get_user_model()
-except ImportError:
- from django.contrib.auth.models import User
+#try:
+# from django.contrib.auth import get_user_model
+# User = get_user_model()
+#except ImportError:
+# from django.contrib.auth.models import User
try:
from django.utils.timezone import now as datetime_now
+from __future__ import print_function
+
from django.template import RequestContext
from django.shortcuts import render_to_response
page.add_js_files ( [ "js/common.functions.js" ] )
for key, value in kwargs.iteritems():
- print "%s = %s" % (key, value)
+ print("%s = %s" % (key, value))
if key == "platformname":
platformname=value
+from __future__ import print_function
+
from django.shortcuts import render
from django.contrib.sites.models import Site
errors.append('Project name is mandatory')
if not errors:
- print "is_pi on auth_hrn = ", user_authority
+ print("is_pi on auth_hrn = ", user_authority)
if is_pi(wsgi_request, user_hrn, user_authority):
# PIs can directly create/join project in their own authority...
if 'join' in wsgi_request.POST:
+from __future__ import print_function
+
import os.path, re
import json
from random import randint
# REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
authorities_query = Query.get('authority').select('name', 'authority_hrn')
authorities = execute_admin_query(wsgi_request, authorities_query)
- print "RegistrationView authorities = ", authorities
+ print("RegistrationView authorities = ", authorities)
if authorities is not None:
# Remove the root authority from the list
matching = [s for s in authorities if "." in s['authority_hrn']]
authorities = sorted(matching, key=lambda k: k['authority_hrn'])
authorities = sorted(matching, key=lambda k: k['name'])
- print "############ BREAKPOINT 1 #################"
+ print("############ BREAKPOINT 1 #################")
# Page rendering
page = Page(wsgi_request)
page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css", "css/jquery.ui.combobox.css" ] )
page.expose_js_metadata()
- print "############ BREAKPOINT 2 #################"
+ print("############ BREAKPOINT 2 #################")
if method == 'POST':
reg_form = {}
# The form has been submitted
current_site = Site.objects.get_current()
current_site = current_site.domain
- print "############ BREAKPOINT 3 #################"
+ print("############ BREAKPOINT 3 #################")
post_email = wsgi_request.POST.get('email','').lower()
salt = randint(1,100000)
email_hash = md5(str(salt)+post_email).hexdigest()
'validation_link': current_site + '/portal/email_activation/'+ email_hash
}
- print "############ BREAKPOINT 4 #################"
+ print("############ BREAKPOINT 4 #################")
auth = wsgi_request.POST.get('org_name', None)
if auth is None or auth == "":
errors.append('Organization required: please select one or request its addition')
else:
- print "############ BREAKPOINT 5 #################"
+ print("############ BREAKPOINT 5 #################")
# Construct user_hrn from email (XXX Should use common code)
split_email = user_request['email'].split("@")[0]
return render(wsgi_request, self.template, {'theme': self.theme})
else:
- print "############ BREAKPOINT A #################"
+ print("############ BREAKPOINT A #################")
user_request = {}
## this is coming from onelab website onelab.eu
reg_form = {
}
# log user activity
activity.user.signup(self.request)
- print "############ BREAKPOINT B #################"
+ print("############ BREAKPOINT B #################")
template_env = {
#'topmenu_items': topmenu_items_live('Register', page),
template_env.update(user_request)
template_env.update(reg_form)
template_env.update(page.prelude_env ())
- print "############ BREAKPOINT C #################"
+ print("############ BREAKPOINT C #################")
return render(wsgi_request, self.template,template_env)
+from __future__ import print_function
+
from manifold.core.query import Query
from unfold.page import Page
page.add_js_files ( [ "js/common.functions.js" ] )
for key, value in kwargs.iteritems():
- print "%s = %s" % (key, value)
+ print("%s = %s" % (key, value))
if key == "urn":
resource_urn=value
+from __future__ import print_function
+
from django.shortcuts import render
from django.contrib.sites.models import Site
# pi = "is_pi"
pi = authority_check_pis (wsgi_request, user_email)
- print "SLICEREQUESTVIEW.PY ----- pi=",pi
+ print("SLICEREQUESTVIEW.PY ----- pi=",pi)
# Page rendering
page = Page(wsgi_request)
+from __future__ import print_function
+
from django.template import RequestContext
from django.shortcuts import render_to_response
slice_md = metadata.details_by_object('slice')
slice_fields = [column['name'] for column in slice_md['column']]
- print "SLICE RES VIEW fields = %s" % slice_fields
+ print("SLICE RES VIEW fields = %s" % slice_fields)
# TODO The query to run is embedded in the URL
# Example: select slice_hrn, resource.urn, lease.resource, lease.start_time, lease.end_time from slice where slice_hrn == "ple.upmc.myslicedemo"
main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
+from __future__ import print_function
+
# this somehow is not used anymore - should it not be ?
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
except Exception,e:
- print "Exception in slicetabexperiment.py in OneLab resource search %s" % e
+ print("Exception in slicetabexperiment.py in OneLab resource search %s" % e)
#print "list of ple res hrns"
#print ple_resource_list
res = urllib2.urlopen(req)
all_users = json.load(res)
except urllib2.URLError as e:
- print "There is a problem in getting iotlab users %s" % e.reason
+ print("There is a problem in getting iotlab users %s" % e.reason)
#getting the login from email
# this program; see the file COPYING. If not, write to the Free Software
# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+from __future__ import print_function
+
import json
from django.http import HttpResponseRedirect, HttpResponse
sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
sfa_platforms = execute_query(self.request, sfa_platforms_query)
for sfa_platform in sfa_platforms:
- print "SFA PLATFORM > ", sfa_platform['platform']
+ print("SFA PLATFORM > ", sfa_platform['platform'])
if not 'auth_type' in sfa_platform:
continue
auth = sfa_platform['auth_type']
all_authorities.append(auth)
platform_ids.append(sfa_platform['platform_id'])
- print "W: Hardcoding platform myslice"
+ print("W: Hardcoding platform myslice")
# There has been a tweak on how new platforms are referencing a
# so-called 'myslice' platform for storing authentication tokens.
# XXX This has to be removed in final versions.
#print "=" * 80
for user_account in user_accounts:
- print "USER ACCOUNT", user_account
+ print("USER ACCOUNT", user_account)
if user_account['auth_type'] == 'reference':
continue # we hardcoded the myslice platform...
config = json.loads(user_account['config'])
creds = []
- print "CONFIG KEYS", config.keys()
+ print("CONFIG KEYS", config.keys())
if 'authority_credentials' in config:
- print "***", config['authority_credentials'].keys()
+ print("***", config['authority_credentials'].keys())
for authority_hrn, credential in config['authority_credentials'].items():
#if credential is not expired:
credential_authorities.add(authority_hrn)
#else
# credential_authorities_expired.add(authority_hrn)
if 'delegated_authority_credentials' in config:
- print "***", config['delegated_authority_credentials'].keys()
+ print("***", config['delegated_authority_credentials'].keys())
for authority_hrn, credential in config['delegated_authority_credentials'].items():
#if credential is not expired:
credential_authorities.add(authority_hrn)
#else
# credential_authorities_expired.add(authority_hrn)
- print 'credential_authorities =', credential_authorities
- print 'credential_authorities_expired =', credential_authorities_expired
+ print('credential_authorities =', credential_authorities)
+ print('credential_authorities_expired =', credential_authorities_expired)
# # Using cache manifold-tables to get the list of authorities faster
# all_authorities_query = Query.get('authority').select('name', 'authority_hrn')
for pa in pi_authorities_tmp:
pi_authorities |= set(pa['pi_authorities'])
except:
- print 'No pi_authorities'
+ print('No pi_authorities')
# TODO: exception if no parent_authority
# try:
# for pa in pi_authorities_tmp:
dest[auth_hrn].append(request)
context = super(ValidatePendingView, self).get_context_data(**kwargs)
- print "testing"
- print ctx_my_authorities
+ print("testing")
+ print(ctx_my_authorities)
context['my_authorities'] = ctx_my_authorities
context['sub_authorities'] = ctx_sub_authorities
context['delegation_authorities'] = ctx_delegation_authorities
+from __future__ import print_function
+
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query
from portal.actions import is_pi
# What about key formed of multiple fields???
query = Query.get('local:object').filter_by('table', '==', self.type).select('key')
results = execute_query(self.request, query)
- print "key of object = %s" % results
+ print("key of object = %s" % results)
if results :
for r in results[0]['key'] :
self.id = r
if self.params :
for p in self.params :
for k,v in p.iteritems() :
- print "param: %s : %s" % (k,v)
+ print("param: %s : %s" % (k,v))
query.set({k : v})
- print "query = ",query
+ print("query = ",query)
else:
raise Exception, "Params are required for create"
return execute_query(self.request, query)
if self.params :
for p in self.params :
for k,v in p.iteritems() :
- print "param: %s : %s" % (k,v)
+ print("param: %s : %s" % (k,v))
query.set({k : v})
- print "query = ",query
+ print("query = ",query)
else:
raise Exception, "Params are required for update"
+from __future__ import print_function
+
from django.views.generic.base import TemplateView
from django.shortcuts import render_to_response
elif request.method == 'GET':
#return error('only post request is supported')
req_items = request.GET
- print req_items
- for el in req_items.items():
+ print(req_items)
+ for el in list(req_items.items()):
# Filters not used for create
if el[0].startswith('filters'):
o.filters[el[0][8:-1]] = el[1]
else :
return error('an error has occurred')
- except Exception, e:
+ except Exception as e:
return error(str(e))
+from __future__ import print_function
+
from django.shortcuts import render_to_response
from unfold.loginrequired import LoginRequiredView
if el[0].startswith('filters'):
o.filters[el[0][8:-1]] = el[1]
elif el[0].startswith('fields'):
- print req_items.getlist('fields[]')
+ print(req_items.getlist('fields[]'))
o.setFields(req_items.getlist('fields[]'))
elif el[0].startswith('options'):
o.options = req_items.getlist('options[]')
+from __future__ import print_function
+
from sfa.trust.certificate import Keypair, Certificate
from sfa.client.sfaserverproxy import SfaServerProxy
from sfa.client.return_value import ReturnValue
from manifoldapi.manifoldapi import execute_admin_query
for pf in platforms:
platform = get_platform_config(pf)
- print platform
+ print(platform)
if 'sm' in platform and len(platform['sm']) > 0:
- print 'sm'
+ print('sm')
server_url = platform['sm']
if 'rm' in platform and len(platform['rm']) > 0:
- print 'rm'
+ print('rm')
server_url = platform['rm']
if 'registry' in platform and len(platform['registry']) > 0:
- print 'registry'
+ print('registry')
server_url = platform['registry']
if not Config.has_option('monitor', 'cert') :
+from __future__ import print_function
+
from django.views.generic.base import TemplateView
from django.shortcuts import render_to_response
elif request.method == 'GET':
#return error('only post request is supported')
req_items = request.GET
- print req_items
+ print(req_items)
for el in req_items.items():
- print "#===============>",el
+ print("#===============>",el)
if el[0].startswith('filters'):
o.filters[el[0][8:-1]] = el[1]
elif el[0].startswith('params'):
- print "#======> 0 ", el[0]
- print "#======> 1 ", req_items.getlist(el[0])
+ print("#======> 0 ", el[0])
+ print("#======> 1 ", req_items.getlist(el[0]))
if (el[0][-2:] == '[]') :
# when receiving params[key][] = 'value1' ...
# when receiving params[key] = 'value'
o.params.append({el[0][7:-1]:el[1]})
- print "o.params = ",o.params
+ print("o.params = ",o.params)
elif el[0].startswith('fields'):
o.fields=req_items.getlist('fields[]')
+from __future__ import print_function
+
import os
from django.conf import settings
from django.utils.datastructures import SortedDict
matched_path = os.path.join(path, file)
if not all:
return matched_path
- print 'ThirdPartyFinder, adding',matched_path
+ print('ThirdPartyFinder, adding',matched_path)
matches.append(matched_path)
return matches
+from __future__ import print_function
+
from unfold.plugin import Plugin
class Composite (Plugin):
def check_active_domid(self):
matches= [ son for son in self.sons if son.domid==self.active_domid ]
if len(matches)!=1:
- print "WARNING: %s has %d valid son(s) for being active - expecting 1, resetting"%\
- (self,len(matches))
+ print("WARNING: %s has %d valid son(s) for being active - expecting 1, resetting"%\
+ (self,len(matches)))
self.active_domid=None
def insert (self, plugin):
+from __future__ import print_function
+
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
return HttpResponseRedirect ('/')
except Exception, e:
# xxx we need to sugarcoat this error message in some error template...
- print "Unexpected exception",e
+ print("Unexpected exception",e)
import traceback
traceback.print_exc()
return HttpResponseRedirect ('/')
+from __future__ import print_function
+
# the supervisor for Plugins
# keeps a handle on all present plugins for managing their queries in a consistent way
# it is expected to exist one such object for a given page
# if cached, use it
if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
- if debug: print "Page.get_metadata: return cached value"
+ if debug: print("Page.get_metadata: return cached value")
return manifold['metadata']
metadata_auth = {'AuthMethod':'anonymous'}
metadata.fetch(self.request)
# store it for next time
manifold['metadata']=metadata
- if debug: print "Page.get_metadata: return new value"
+ if debug: print("Page.get_metadata: return new value")
return metadata
def expose_js_metadata (self):
# so it should be specialized in real plugin classes
# like e.g. plugins.simplelist.SimpleList
+from __future__ import print_function
+
import json
from django.template.loader import render_to_string
# what comes from subclasses
for (k,v) in settings.iteritems():
setattr(self,k,v)
- if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
+ if self.need_debug(): print("%s init - subclass setting %s"%(self.classname,k))
# minimal debugging
if self.need_debug():
- print "%s init dbg .... BEG"%self.classname
- for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
- print "%s init dbg .... END"%self.classname
+ print("%s init dbg .... BEG"%self.classname)
+ for (k,v) in self.__dict__.items(): print("dbg %s:%s"%(k,v))
+ print("%s init dbg .... END"%self.classname)
# do this only once the structure is fine
if self.page: # I assume we can have a None page (Jordan)
self.page.record_plugin(self)
def settings_json (self):
exposed_settings=self.json_settings_list()
if 'query' in exposed_settings:
- print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
+ print("WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough")
result = "{"
result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
result += "}"
env.update({'persistent_toggle':False,'display_hide_button':True,
'display_show_button':False,'display_body':True})
if self.need_debug():
- print "rendering plugin.html with env keys %s"%env.keys()
+ print("rendering plugin.html with env keys %s"%env.keys())
for (k,v) in env.items():
- if "display" in k or "persistent" in k: print k,'->',v
+ if "display" in k or "persistent" in k: print(k,'->',v)
result = render_to_string ('plugin.html',env)
# export this only for relevant plugins
raise Exception, "%s.template_env returns wrong type"%self.classname
result=render_to_string (template, env)
if self.need_debug():
- print "%s.render_content: BEG --------------------"%self.classname
- print "template=%s"%template
- print "env.keys=%s"%env.keys()
+ print("%s.render_content: BEG --------------------"%self.classname)
+ print("template=%s"%template)
+ print("env.keys=%s"%env.keys())
#print "env=%s"%env
#print result
- print "%s.render_content: END --------------------"%self.classname
+ print("%s.render_content: END --------------------"%self.classname)
return result
# or from the result of self.requirements()
d=self.requirements()
for (k,v) in d.iteritems():
if self.need_debug():
- print "%s: handling requirement %s"%(self.classname,v)
+ print("%s: handling requirement %s"%(self.classname,v))
# e.g. js_files -> add_js_files
method_name='add_'+k
method=Page.__dict__[method_name]
+from __future__ import print_function
+
from types import StringTypes, ListType
from django.template.loader import render_to_string
result += ",".join( [ "%s->%s"%(k,len(getattr(self,k))) for k in Prelude.keys ] )
return result
def inspect (self,msg):
- print self.inspect_string(msg)
+ print(self.inspect_string(msg))
# first attempt was to use a simple dict like this
# env={}
env['all_js_chunks']= self.js_init_chunks + self.js_chunks
env['css_chunks']=self.css_chunks
if debug:
- print "prelude has %d js_files, %d css files, (%d+%d) js chunks and %d css_chunks"%\
- (len(self.js_files),len(self.css_files),len(self.js_init_chunks),len(self.js_chunks),len(self.css_chunks),)
+ print("prelude has %d js_files, %d css files, (%d+%d) js chunks and %d css_chunks"%\
+ (len(self.js_files),len(self.css_files),len(self.js_init_chunks),len(self.js_chunks),len(self.css_chunks),))
# render this with prelude.html and put the result in header_prelude
header_prelude = render_to_string ('prelude.html',env)
return { 'header_prelude' : header_prelude }
+from __future__ import print_function
+
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
"""
Tests that 1 + 1 always equals 2.
"""
- print 'test_basic is broken'
+ print('test_basic is broken')
return True
sl = SimpleList (visible=True)
- print 'rendering', sl.render()
+ print('rendering', sl.render())
self.assertEqual(1 + 1, 2)