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
--- /dev/null
+Thierry Parmentelat <thierry.parmentelat@inria.fr>
+
+As of March 31 2015, the code should be mostly ready for django-1.7,
+with the following restrictions
+
+* migrations : django-1.7 comes with its own native migrations system
+ and so south is not needed/recommended any longer. So for now we have a
+ version of such native migrations that does a one-shot setup of a db
+ schema but this is stored in
+
+ portal/native_migrations
+
+ instead of the standard location
+
+ portal/migrations
+
+ because this one is still expected to hold south code with earlier djangos
+ You might need to rename native_migrations/ into migrations/ before
+ running manage.py migrate in the first place
+
+* testing quite a few issues related to 1.7 have been addressed but it
+ would be presomptuous to state that things were tested very
+ thoroughly, far from that.
+
+ So please use with care and let meknow of any additional issues
+
+
+
+
+
import time
import datetime
from myslice.configengine import ConfigEngine
+from myslice.settings import logger
+
config = ConfigEngine()
if config.activity and config.activity.apikey :
def logWrite(request, action, message, objects = None):
if not apikey :
- print "===============>> activity: no apikey"
+ logger.info("===============>> activity: no apikey")
return
if not secret :
- print "===============>> activity: no secret"
+ logger.info("===============>> 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)
+ logger.info("===============>> activity: {} <{}> {}".format(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 ""
+ logger.error("===============>> activity: connection to {} impossible, could not log action".format(server))
+ logger.error(e.strerror)
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()
from myslice.settings import config, logger, DEBUG
+from unfold.sessioncache import SessionCache
+
# Name my backend 'ManifoldBackend'
class ManifoldBackend:
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']}
+ session_auth = {'AuthMethod': 'session', 'session': session['session']}
+ api.auth = session_auth
self.api = api
# Get account details
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']))
-
- 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()
+ logger.debug("PERSON : {}".format(person))
+ #logger.info("{} {} <{}> logged in"\
+ # .format(person['config']['first_name'], person['config']['last_name'], person['config']['email']))
+
+ SessionCache().store_auth(request, session_auth)
+
+ 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
+ logger.error(traceback.format_exc())
return None
try:
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
+from myslice.settings import logger
+
import activity.user
# hard question : where should we redirect requests to logout if user is not logged in ?
# check that we're indeed logged in
if not request.user.is_authenticated():
return HttpResponseRedirect ('/')
- print "LOGGING OUT"
+ logger.info("LOGGING OUT")
# log user activity
activity.user.logout(request)
# Manifold API Python interface
-import copy, xmlrpclib, ssl
-from myslice.settings import config, logger, DEBUG
+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
+from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
+
+from unfold.sessioncache import SessionCache
-debug_deep=False
-#debug_deep=True
+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(self.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:
+ logger.error("===== xmlrpc catch-all exception: {}".format(error))
+ import traceback
+ logger.error(traceback.format_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())))
result = manifold_api.forward(query.to_dict())
if result['code'] == 2:
# this is gross; at the very least we need to logout()
# but most importantly there is a need to refine that test, since
# code==2 does not necessarily mean an expired session
# XXX only if we know it is the issue
- del request.session['manifold']
+ SessionCache().end_session(request)
# 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}
return result['value']
def execute_query(request, query):
- if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
+
+ manifold_api_session_auth = SessionCache().get_auth(request)
+ if not manifold_api_session_auth:
request.session.flush()
#raise Exception, "User not authenticated"
host = request.get_host()
return redirect('/')
- manifold_api_session_auth = request.session['manifold']['auth']
-
return _execute_query(request, query, manifold_api_session_auth)
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 manifoldresult import ManifoldException
from manifold.util.log import Log
-from myslice.settings import config, logger, DEBUG
+from unfold.sessioncache import SessionCache
+
+from myslice.settings import config, logger
# register activity
import activity.slice
# expecting a POST
if request.method != 'POST':
- logger.error("MANIFOLDPROXY unexpected method %s -- exiting" % request.method)
- return HttpResponse ({"ret":0}, mimetype="application/json")
+ logger.error("MANIFOLDPROXY unexpected method {} -- exiting".format(request.method))
+ return HttpResponse ({"ret":0}, content_type="application/json")
# we only support json for now
# if needed in the future we should probably cater for
# format_in : how is the query encoded in POST
# format_out: how to serve the results
if format != 'json':
- logger.error("MANIFOLDPROXY unexpected format %s -- exiting" % format)
- return HttpResponse ({"ret":0}, mimetype="application/json")
+ logger.error("MANIFOLDPROXY unexpected format {} -- exiting".format(format))
+ return HttpResponse ({"ret":0}, content_type="application/json")
try:
# translate incoming POST request into a query object
- #logger.debug("MANIFOLDPROXY request.POST %s" % request.POST)
+ #logger.debug("MANIFOLDPROXY request.POST {}".format(request.POST))
manifold_query = Query()
#manifold_query = ManifoldQuery()
admin_user, admin_password = config.manifold_admin_user_password()
manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
else:
- if 'manifold' in request.session:
- manifold_api_session_auth = request.session['manifold']['auth']
- else:
- return HttpResponse (json.dumps({'code':0,'value':[]}), mimetype="application/json")
+ manifold_api_session_auth = SessionCache().get_auth(request)
+ if not manifold_api_session_auth:
+ return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
if debug_empty and manifold_query.action.lower()=='get':
- return HttpResponse (json.dumps({'code':0,'value':[]}), mimetype="application/json")
+ return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
# actually forward
manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
#
# resource reservation
if (manifold_query.action.lower() == 'update') :
- print result['value'][0]
+ logger.debug(result['value'][0])
if 'resource' in result['value'][0] :
for resource in result['value'][0]['resource'] :
activity.slice.resource(request,
json_answer=json.dumps(result)
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
- except Exception,e:
- logger.error("MANIFOLDPROXY %s" % e)
+ except Exception as e:
+ logger.error("MANIFOLDPROXY {}".format(e))
import traceback
- traceback.print_exc()
- return HttpResponse ({"ret":0}, mimetype="application/json")
+ logger.error(traceback.format_exc())
+ return HttpResponse ({"ret":0}, content_type="application/json")
####################
# see CSRF_FAILURE_VIEW in settings.py
# this however turns out disappointing/not very informative
failure_answer=[ "csrf_failure" ]
def csrf_failure(request, reason=""):
- print "CSRF failure with reason '%s'"%reason
- return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")
+ logger.error("CSRF failure with reason '{}'".format(reason))
+ return HttpResponseForbidden (json.dumps (failure_answer), content_type="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 django.contrib import messages
+from myslice.settings import logger
+
debug=False
#debug=True
# 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'])
+ logger.warning(("METADATA WARNING - {} {}".format(request,result['description'])))
elif result['code'] == 2:
# messages.error(request, result['description'])
- print ("METADATA ERROR -",request,result['description'])
+ logger.error(("METADATA ERROR - {} {}".format(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:
+ logger.debug("Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon")
return field
__import__(component)
u.append( url(r'^%s/' % component, include('%s.urls' % component)) )
except Exception, e:
- logger.info("Cannot load component (%s): %s" % (component, e))
+ logger.error("Cannot load component ({}): {}".format(component, e))
else:
- logger.info("Loaded component %s" % component)
+ logger.info("Loaded component {}".format(component))
return u
ROOT = os.path.realpath(os.path.dirname(__file__) + '/..')
except:
import traceback
- traceback.print_exc()
+ logger.error(traceback.format_exc())
from myslice.configengine import ConfigEngine
# our django project
'myslice',
# the core of the UI
- 'auth',
+ 'localauth',
'manifoldapi',
'unfold',
# plugins
'plugins',
# views - more or less stable
'ui',
- # managing database migrations
- 'south',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# FORGE Plugin app
# 'django.contrib.admindocs',
'portal',
]
+# with django-1.7 we leave south and use native migrations
+# managing database migrations
+import django
+major, minor, _, _, _ = django.VERSION
+if major == 1 and minor <= 6:
+ INSTALLED_APPS.append('south')
+
# this app won't load in a build environment
-if not building: INSTALLED_APPS.append ('rest')
+if not building:
+ INSTALLED_APPS.append ('rest')
for component in components.list() :
INSTALLED_APPS.append(component)
for aux in auxiliaries:
if os.path.isdir(os.path.join(ROOT,aux)):
- print("Using devel auxiliary",aux)
+ logger.info("Using devel auxiliary {}".format(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 unfold.plugin import Plugin
+from myslice.settings import logger
+
class QueryGrid (Plugin):
"""A plugin for displaying a query as a list
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'
+ logger.warning('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 unfold.plugin import Plugin
+from myslice.settings import logger
+
class QueryTable (Plugin):
"""A plugin for displaying a query as a list
_columns = columns
_hidden_columns = []
elif self.query:
- print "self.query.fields = ", self.query_all.fields
+ logger.debug("self.query.fields = {}".format(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
+ logger.debug(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
+ logger.debug("_columns={}".format(_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
+ logger.debug("self.columns {}".format(self.columns))
+ logger.debug("self.hidden_columns {}".format(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'
+ logger.warning('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',[])
this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
break;
case STATE_SET_IN_PENDING:
- this.set_checkbox_from_data(data.key, true);
+ this.set_checkbox_from_data(data.value, true);
this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_ADDED);
break;
case STATE_SET_OUT_PENDING:
- this.set_checkbox_from_data(data.key, false);
+ this.set_checkbox_from_data(data.value, false);
this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_REMOVED);
break;
}
value: new_lease
}
manifold.raise_event($scope.instance.options.query_lease_uuid, FIELD_STATE_CHANGED, data);
+
/* Add to local cache also, unless we listen to events from outside */
- if (!(resource_urn in $scope._leases_by_resource))
+ if (!(resource_urn in $scope._leases_by_resource)){
$scope._leases_by_resource[resource_urn] = [];
+ /* Add the resource of the selected timeslot to the pending list */
+ data_resource = {
+ state: STATE_SET,
+ key : null,
+ op : STATE_SET_ADD,
+ value: resource_urn
+ };
+ manifold.raise_event($scope.instance.options.query_uuid, FIELD_STATE_CHANGED, data_resource);
+ }
$scope._leases_by_resource[resource_urn].push(new_lease);
+
}
$scope._remove_lease = function(other)
manifold.raise_event($scope.instance.options.query_lease_uuid, FIELD_STATE_CHANGED, data);
/* Remove from local cache also, unless we listen to events from outside */
$scope._leases_by_resource[other.resource] = $.grep($scope._leases_by_resource[other.resource], function(x) { return x != other; });
-
+ /* Last lease removed for this resource -> remove the resource from the list */
+ if($scope._leases_by_resource.hasOwnProperty(other.resource) && $scope._leases_by_resource[other.resource].length == 0){
+ /* remove resource from the list of selected resources */
+ data_resource = {
+ state: STATE_SET,
+ key : null,
+ op : STATE_SET_REMOVE,
+ value: other.resource
+ };
+ manifold.raise_event($scope.instance.options.query_uuid, FIELD_STATE_CHANGED, data_resource);
+
+ }
}
$scope.select = function(index, model_lease, model_resource)
from unfold.plugin import Plugin
+from myslice.settings import logger
+
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
+ logger.info("called univbris plugin")
def template_file (self):
try:
return "univbris_welcome.html"
- except Exception:
- print "error template"
+ except Exception as e:
+ logger.error("error template {}".format(e))
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/univbris.js',
],
'css_files': [
# 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 unfold.plugin import Plugin
+from myslice.settings import logger
+
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'
+ logger.warning('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 unfold.plugin import Plugin
+from myslice.settings import logger
+
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'
+ logger.warning('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 unfold.plugin import Plugin
+from myslice.settings import logger
+
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
+ logger.info("called univbris topo plugin")
def template_file (self):
- try:
- return "univbris_topology.html"
- except:
- print "error template"
+ try:
+ return "univbris_topology.html"
+ except Exception as e :
+ logger.error("error template {}".format(e))
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 unfold.plugin import Plugin
+from myslice.settings import logger
+
class UnivbrisVtam (Plugin):
def __init__ (self, query=None, query_all=None, sync_query=None,
checkboxes=False, columns=None,
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'
+ logger.warning('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 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 unfold.page import Page
-from ui.topmenu import topmenu_items_live, the_user
+import json, os, re, itertools, time
+from OpenSSL import crypto
+from Crypto.PublicKey import RSA
+
#
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
-from myslice.configengine import ConfigEngine
-from myslice.theme import ThemeView
+#
+from manifold.core.query import Query
+from manifoldapi.manifoldapi import execute_query
+
+from unfold.loginrequired import LoginRequiredAutoLogoutView
+from unfold.page import Page
+from ui.topmenu import topmenu_items_live, the_user
+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.account import Account, get_expiration
-#
-import json, os, re, itertools, time
-from OpenSSL import crypto
-from Crypto.PublicKey import RSA
+
+from myslice.settings import logger
+from myslice.configengine import ConfigEngine
+from myslice.theme import ThemeView
# requires login
class AccountView(LoginRequiredAutoLogoutView, ThemeView):
if user_email == request.user.email:
authorize_query = True
else:
- print "SECURITY: %s tried to update %s" % (user_email, request.user.email)
+ logger.error("SECURITY: {} tried to update {}".format(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
+ except Exception as e:
+ logger.error("exception in account_process {}".format(e))
for account_detail in account_details:
for platform_detail in platform_details:
messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
else:
raise Exception,"Keys are not matching"
- except Exception, e:
+ except Exception as 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
+ logger.error("Exception in accountview {}".format(e))
return HttpResponseRedirect("/portal/account/")
else:
messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
messages.success(request, 'All Credentials cleared')
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
+ except Exception as e:
+ logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
return HttpResponseRedirect("/portal/account/")
from myslice.theme import ThemeView
from myslice.configengine import ConfigEngine
-
+from myslice.settings import logger
theme = ThemeView()
pi_status = True
return pi_status
- except Exception,e:
- print "Exception in actions.py in authority_check_pis %s" % e
+ except Exception as e:
+ logger.error("Exception in actions.py in authority_check_pis {}".format(e))
return None
results = execute_query(request,query)
newpis = authority_get_pis (request, authority_hrn)
return newpis
- except Exception,e:
- print "Exception in actions.py in authority_add_pis %s" % e
+ except Exception as e:
+ logger.error("Exception in actions.py in authority_add_pis {}".format(e))
return None
results = execute_query(request,query)
newpis = authority_get_pis (request, authority_hrn)
return newpis
- except Exception,e:
- print "Exception in actions.py in authority_remove_pis %s" % e
+ except Exception as e:
+ logger.error("Exception in actions.py in authority_remove_pis {}".format(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
+ logger.info("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'
else:
return None
- except Exception,e:
- print "Exception in actions.py in clear_user_creds %s" % e
+ except Exception as e:
+ logger.error("Exception in actions.py in clear_user_creds {}".format(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
+ logger.debug("#### actions.py is_pi authority_hrn = {}".format(authority_hrn))
try:
# CACHE PB with fields
page = Page(wsgi_request)
query = Query().get('myslice:user').select(user_fields).filter_by('user_hrn','==',user_hrn)
#query = Query.get('myslice:user').filter_by('user_hrn', '==', user_hrn).select('pi_authorities')
results = execute_query(wsgi_request, query)
- #print "is_pi results = ", results
for user_detail in results:
if authority_hrn in user_detail['pi_authorities']:
return True
- except Exception,e:
- print "Exception in actions.py in is_pi %s" % e
+ except Exception as e:
+ logger.error("Exception in actions.py in is_pi {}".format(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
+ logger.info("sfa_add_auth results={}".format(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"
+ logger.info("$$$$$$$$$$$$$$$ 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"
+ logger.info("$$$$$$$$$$$$$$$$ 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
+ logger.info("$$$$$$$$$$$$$ get_request_by_authority auth_hrns = {}".format(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"
+ logger.info("ADD Authority")
sfa_add_authority(wsgi_request, sfa_authority_params)
request_status['SFA authority'] = {'status': True }
PendingAuthority.objects.get(id=request['id']).delete()
ids = filter(None, kwargs['id'].split('/'))
status = portal_validate_request(request, ids)
json_answer = json.dumps(status)
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
def reject_action(request, **kwargs):
ids = filter(None, kwargs['id'].split('/'))
status = portal_reject_request(request, ids)
json_answer = json.dumps(status)
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
def portal_reject_request(wsgi_request, request_ids):
msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
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"
+ except Exception as e:
+ logger.error("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 = EmailMultiAlternatives(subject, text_content, sender, [user_email])
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"
+ except Exception as e:
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
PendingSlice.objects.get(id=request['id']).delete()
msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
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"
+ except Exception as e:
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
PendingAuthority.objects.get(id=request['id']).delete()
msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
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"
+ except Exception as e:
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
return results
msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
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"
+ except Exception as e:
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
def create_pending_project(wsgi_request, request):
msg = EmailMultiAlternatives(subject, text_content, sender, [request['email']])
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"
+ except Exception as e:
+ logger.error("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
+ logger.info('Create iotlab user : {} {}'.format(r.status_code, r.text))
return r.text
def create_user(wsgi_request, request, namespace = None, as_admin = False):
'config' : json.dumps(account_config),
}
manifold_add_account(wsgi_request, account_params)
- except Exception, e:
- print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email'])
+ except Exception as e:
+ logger.error("Failed creating manifold account on platform {} for user: {}".format('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"
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
import traceback
- traceback.print_exc()
+ logger.error(traceback.format_exc())
from ui.topmenu import topmenu_items_live, the_user
-from myslice.theme import ThemeView
+from myslice.theme import ThemeView
+from myslice.settings import logger
+
#This view requires login
class DashboardView (LoginRequiredAutoLogoutView, ThemeView):
#messages.info(self.request, 'You have logged in')
page = Page(self.request)
- print "Dashboard page"
+ logger.info("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
+ logger.debug("SLICE QUERY")
+ logger.debug("-" * 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 unfold.loginrequired import FreeAccessView
-#
-from manifold.core.query import Query
-from manifoldapi.manifoldapi import execute_query, execute_admin_query
-from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, make_request_user, create_user
-#
-from unfold.page import Page
-from ui.topmenu import topmenu_items_live, the_user
-#
+import json
+import os
+import re
+import itertools
+
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
-from myslice.theme import ThemeView
-from portal.models import PendingUser, PendingAuthority
from django.core.mail import EmailMultiAlternatives, send_mail
from django.contrib.sites.models import Site
-#
-import json, os, re, itertools
+from manifold.core.query import Query
+from manifoldapi.manifoldapi import execute_query, execute_admin_query
+
+from unfold.loginrequired import FreeAccessView
+
+from portal.actions import (
+ manifold_update_user, manifold_update_account, manifold_add_account,
+ manifold_delete_account, sfa_update_user, authority_get_pi_emails,
+ make_request_user, create_user)
+from portal.models import PendingUser, PendingAuthority
+
+from unfold.page import Page
+from ui.topmenu import topmenu_items_live, the_user
+
+from myslice.theme import ThemeView
+from myslice.settings import logger
+
def ValuesQuerySetToDict(vqs):
return [item for item in vqs]
# User is enabled in PLE
if 'enabled' in result and result['enabled']==True:
return True
- except Exception, e:
- print "Exception in myplc query = ",e
+ except Exception as e:
+ logger.error("Exception in myplc query = {}".format(e))
return False
#page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
for key, value in kwargs.iteritems():
- #print "%s = %s" % (key, value)
if key == "hash_code":
hash_code=value
if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):
# msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
# 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"
+ #except Exception as e:
+ # logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
# import traceback
- # traceback.print_exc()
+ # logger.error(traceback.format_exc())
PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
else:
# this program; see the file COPYING. If not, write to the Free Software
# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+# TODO: Remove these automated forms and use html templates and views like any other page !
+
from django import forms
-from portal.models import PendingUser, PendingSlice
#from crispy_forms.helper import FormHelper
#from crispy_forms.layout import Submit
from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36
from django.template import loader
-# TODO: Remove these automated forms and use html templates and views like any other page !
from django.contrib.auth.hashers import identify_hasher
+
+from portal.models import PendingUser, PendingSlice
+
+from myslice.settings import logger
+
# adapted from https://sourcegraph.com/github.com/fusionbox/django-authtools/symbols/python/authtools/forms
def is_password_unusable(pw):
subject = ''.join(subject.splitlines())
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"
+ except Exception as e:
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
class SetPasswordForm(forms.Form):
+import time
+import json
+
# this somehow is not used anymore - should it not be ?
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.shortcuts import render
-
from unfold.loginrequired import FreeAccessView
+from ui.topmenu import topmenu_items, the_user
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query
-
from manifoldapi.manifoldresult import ManifoldResult
-from ui.topmenu import topmenu_items, the_user
-from myslice.configengine import ConfigEngine
+from myslice.configengine import ConfigEngine
from myslice.theme import ThemeView
+
from portal.account import Account, get_expiration
from portal.models import PendingSlice
from portal.actions import authority_check_pis
-import json, time
import activity.user
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:
- print "LOGGING IN"
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))
+import json
+
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from portal.actions import is_pi, authority_check_pis
from myslice.theme import ThemeView
-import json
+from myslice.settings import logger
+
class InstitutionView (LoginRequiredAutoLogoutView, ThemeView):
template_name = 'institution.html'
else:
env['person'] = None
- print "BEFORE ####------#### is_pi"
+ logger.debug("BEFORE ####------#### is_pi")
pi = is_pi(self.request, '$user_hrn', env['user_details']['parent_authority'])
- print "is_pi = ",is_pi
+ logger.debug("is_pi = {}".format(is_pi))
env['theme'] = self.theme
env['section'] = "Institution"
from portal.actions import authority_get_pi_emails, manifold_add_user,manifold_add_account, create_pending_user
from myslice.theme import ThemeView
+from myslice.settings import logger
import activity.institution
msg.send()
except Exception, e:
- print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+ logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
import traceback
- traceback.print_exc()
+ logger.error(traceback.format_exc())
self.template_name = 'join_complete.html'
# log institution activity
+import json
# this somehow is not used anymore - should it not be ?
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query
from manifoldapi.manifoldresult import ManifoldResult
-from myslice.configengine import ConfigEngine
+from myslice.configengine import ConfigEngine
from myslice.theme import ThemeView
-import json
+from myslice.settings import logger
class ManagementAboutView (FreeAccessView, ThemeView):
template_name = 'management-tab-about.html'
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
+ logger.info("**************________ management about = {}".format(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',
+import json
+
from django.template import RequestContext
from django.shortcuts import render_to_response
from portal.actions import get_requests
from myslice.theme import ThemeView
-
-import json
+from myslice.settings import logger
class ManagementRequestsView (LoginRequiredView, ThemeView):
template_name = "management-tab-requests.html"
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']
+ logger.info("SFA PLATFORM > {}".format(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"
+ logger.warning("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.
try:
for pa in pi_authorities_tmp:
pi_authorities |= set(pa['pi_authorities'])
- except:
- print 'No pi_authorities'
+ except Exception as e:
+ logger.error('No pi_authorities')
pi_credential_authorities = pi_authorities & credential_authorities
pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
+import os
+import re
+import itertools
+import json
+
from unfold.loginrequired import LoginRequiredAutoLogoutView
-#
+
from manifold.core.query import Query
from manifoldapi.manifoldapi import execute_query, execute_admin_query
from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account
-from portal.actions import sfa_update_user, authority_get_pis, authority_add_pis, authority_remove_pis,authority_check_pis ,clear_user_creds
-#
+from portal.actions import (
+ sfa_update_user, authority_get_pis, authority_add_pis,
+ authority_remove_pis,authority_check_pis ,clear_user_creds )
+
from unfold.page import Page
from ui.topmenu import topmenu_items_live, the_user
-#
+
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from myslice.theme import ThemeView
-#
-import json, os, re, itertools
# requires login
class UserView(LoginRequiredAutoLogoutView, ThemeView):
page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css","css/jquery-ui.css" ] )
for key, value in kwargs.iteritems():
- #print "%s = %s" % (key, value)
if key == "email":
selected_email=value
#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
--- /dev/null
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Institution',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('name', models.TextField()),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='PendingAuthority',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('site_name', models.TextField()),
+ ('site_authority', models.TextField()),
+ ('site_abbreviated_name', models.TextField()),
+ ('site_url', models.TextField()),
+ ('site_latitude', models.TextField()),
+ ('site_longitude', models.TextField()),
+ ('address_line1', models.TextField()),
+ ('address_line2', models.TextField()),
+ ('address_line3', models.TextField()),
+ ('address_city', models.TextField()),
+ ('address_postalcode', models.TextField()),
+ ('address_state', models.TextField()),
+ ('address_country', models.TextField()),
+ ('authority_hrn', models.TextField()),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='PendingJoin',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('user_hrn', models.TextField()),
+ ('email', models.TextField()),
+ ('project_name', models.TextField(null=True)),
+ ('authority_hrn', models.TextField()),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='PendingProject',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('project_name', models.TextField()),
+ ('user_hrn', models.TextField()),
+ ('email', models.TextField()),
+ ('authority_hrn', models.TextField(null=True)),
+ ('purpose', models.TextField(default=b'NA')),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='PendingSlice',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('slice_name', models.TextField()),
+ ('user_hrn', models.TextField()),
+ ('authority_hrn', models.TextField(null=True)),
+ ('number_of_nodes', models.TextField(default=0)),
+ ('type_of_nodes', models.TextField(default=b'NA')),
+ ('purpose', models.TextField(default=b'NA')),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='PendingUser',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('first_name', models.TextField()),
+ ('last_name', models.TextField()),
+ ('email', models.EmailField(max_length=75)),
+ ('password', models.TextField()),
+ ('user_hrn', models.TextField()),
+ ('public_key', models.TextField()),
+ ('private_key', models.TextField()),
+ ('authority_hrn', models.TextField()),
+ ('login', models.TextField()),
+ ('pi', models.TextField()),
+ ('email_hash', models.TextField()),
+ ('status', models.TextField()),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ ]
from myslice.configengine import ConfigEngine
from myslice.theme import ThemeView
+from myslice.settings import logger
# View for 1 platform and its details
class PlatformView(FreeAccessView, ThemeView):
page.add_js_files ( [ "js/common.functions.js" ] )
for key, value in kwargs.iteritems():
- print "%s = %s" % (key, value)
+ logger.debug("{} = {}".format(key, value))
if key == "platformname":
platformname=value
+import json
+import time
+import re
+
from django.shortcuts import render
from django.contrib.sites.models import Site
from portal.models import PendingProject, PendingJoin
from myslice.theme import ThemeView
-
-import json, time, re
+from myslice.settings import logger
class ProjectRequestView(LoginRequiredAutoLogoutView, ThemeView):
template_name = 'projectrequest_view.html'
errors.append('Project name is mandatory')
if not errors:
- print "is_pi on auth_hrn = ", user_authority
+ logger.info("is_pi on auth_hrn = {}".format(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:
-import os.path, re
+import os.path
+import re
import json
from random import randint
from hashlib import md5
from portal.actions import create_pending_user
from myslice.theme import ThemeView
+from myslice.settings import logger
import activity.user
# 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
+ logger.info("RegistrationView authorities = {}".format(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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ 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 #################"
+ logger.debug("############ BREAKPOINT C #################")
return render(wsgi_request, self.template,template_env)
from django.http import *
-def response_mimetype(request):
+def response_content_type(request):
if "application/json" in request.META['HTTP_ACCEPT']:
return "application/json"
slicedata_received = json_to_rest('http://survivor.lab.netmode.ntua.gr:4567/reputation/json', dict_to_send )
- return HttpResponse(json.dumps(slicedata_received), content_type = response_mimetype(self.request))
+ return HttpResponse(json.dumps(slicedata_received), content_type = response_content_type(self.request))
slices_users = []
-
\ No newline at end of file
+
page.add_js_files ( [ "js/common.functions.js" ] )
for key, value in kwargs.iteritems():
- print "%s = %s" % (key, value)
if key == "urn":
resource_urn=value
+import json
+import time
+import re
+
from django.shortcuts import render
from django.contrib.sites.models import Site
-
from unfold.page import Page
from manifold.core.query import Query
from ui.topmenu import topmenu_items_live, the_user
from myslice.theme import ThemeView
-
-import json, time, re
+from myslice.settings import logger
import activity.user
# pi = "is_pi"
pi = authority_check_pis (wsgi_request, user_email)
- print "SLICEREQUESTVIEW.PY ----- pi=",pi
+ logger.debug("SLICEREQUESTVIEW.PY ----- pi= {}".format(pi))
# Page rendering
page = Page(wsgi_request)
+import json
+
from django.template import RequestContext
from django.shortcuts import render_to_response
+from django.views.generic.base import TemplateView
+from django.http import HttpResponse
+from django.shortcuts import render
from manifold.core.query import Query, AnalyzedQuery
from manifoldapi.manifoldapi import execute_query
-import json
-from django.views.generic.base import TemplateView
from unfold.loginrequired import LoginRequiredView
-from django.http import HttpResponse
-from django.shortcuts import render
-
from unfold.page import Page
from myslice.configengine import ConfigEngine
from plugins.univbrisfvf import UnivbrisFvf
from plugins.univbrisfvfo import UnivbrisFvfo
from plugins.univbristopo import UnivbrisTopo
-from plugins.univbrisvtam import UnivbrisVtam as UnivbrisVtamPlugin
+from plugins.univbrisvtam import UnivbrisVtam as UnivbrisVtamPlugin
from plugins.univbrisvtamform import UnivbrisVtamForm
from plugins.columns_editor import ColumnsEditor
from plugins.lists.simplelist import SimpleList
from myslice.theme import ThemeView
+from myslice.settings import logger
class SliceResourceView (LoginRequiredView, ThemeView):
template_name = "slice-resource-view.html"
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
+ logger.debug("SLICE RES VIEW fields = {}".format(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 myslice.theme import ThemeView
from myslice.configengine import ConfigEngine
+from myslice.settings import logger
from sfa.planetlab.plxrn import hash_loginbase
try:
for resources in current_resources:
list_res = resources['resource']
- #print "list_b4"
- #print list_res
for res in list_res:
split_list = res.split('+') # split the resource urn
- #print "list_after"
- #print split_list
if [s for s in split_list if 'ple' in s]: # find ple resources
res_hrn = split_list[-1] # last element is resource hrn
ple_resource_list.append(res_hrn)
nitos_resource_list.append(res_hrn)
- except Exception,e:
- print "Exception in slicetabexperiment.py in OneLab resource search %s" % e
+ except Exception as e:
+ logger.error("Exception in slicetabexperiment.py in OneLab resource search {}".format(e))
- #print "list of ple res hrns"
- #print ple_resource_list
- #print "list of nit_paris res hrns"
- #print nitos_paris_resource_list
- #print "list of iotLab res hrns"
- #print iotlab_resource_list
- #print "list of nitos res hrns"
- #print nitos_resource_list
+ #logger.debug("list of ple res hrns")
+ #logger.debug(ple_resource_list)
+ #logger.debug("list of nit_paris res hrns")
+ #logger.debug(nitos_paris_resource_list)
+ #logger.debug("list of iotLab res hrns")
+ #logger.debug(iotlab_resource_list)
+ #logger.debug("list of nitos res hrns")
+ #logger.debug(nitos_resource_list)
all_users = list()
#get all iotlab users
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
+ logger.error("There is a problem in getting iotlab users {}".format(e.reason))
#getting the login from email
slice_url="<a href='"+val.slice_url+"' target='_blank'>"+val.slice_url+"</a>";
}
- slice_row = "<tr><td>Description:</b></td><td>"+val.slice_description+"</td></tr>";
- slice_row += "<tr><td>url:</td><td><a href='"+val.slice_url+" target='_blank'>"+val.slice_url+"</a></td></tr>";
- slice_row += "<tr><td>users:</td><td>"+user_length+"</td></tr>";
+ // slice_row = "<tr><td>Description:</b></td><td>"+val.slice_description+"</td></tr>";
+ // slice_row += "<tr><td>url:</td><td><a href='"+val.slice_url+" target='_blank'>"+val.slice_url+"</a></td></tr>";
+ slice_row = "<tr><td>users:</td><td>"+user_length+"</td></tr>";
//slice_row += "<tr><td>resources:</td><td>"+nodes_length+"</td></tr>";
- slice_row += "<tr><td>created:</td><td>"+val.created+"</td></tr>";
+ //slice_row += "<tr><td>created:</td><td>"+val.created+"</td></tr>";
slice_row += "<tr><td>last update:</td><td>"+val.slice_last_updated+"</td></tr>";
- slice_row += "<tr><td>expires:</td><td>"+val.slice_expires+"</td></tr>";
+ //slice_row += "<tr><td>expires:</td><td>"+val.slice_expires+"</td></tr>";
table_slices.push(slice_row);
});
$("div#slice-info").html("<table>" + table_slices.join( "" ) + "</table>");
});
+ $('button#renewslices').click(function() {
+ var now = new Date();
+ /* In Javascript getMonth() gives month[0] = january, month[1] = february, and so on... */
+ var month = now.getMonth()+2;
+ var one_month_later = now.getFullYear()+"-"+month+"-"+now.getDate()+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
+ $.post("/update/slice/",{'filters':{'slice_hrn':'{{slice}}'},'params':{'expires':one_month_later}}, function(data) {
+ if(data.success){
+ mysliceAlert('Success: slice renewed','success', true);
+ }
+ else{
+ mysliceAlert('Rest Error for: '+data.error,'warning', true);
+ }
+ });
+ });
+ $('button#deleteslices').click(function() {
+ if (confirm('Are you sure? It will remove the slice permanently.')) {
+ $.post("/delete/slice/",{'filters':{'slice_hrn':'{{slice}}'}}, function(data) {
+ if(data.success){
+ localStorage.clear();
+ var user_email = [];
+ user_email.push ('{{username}}');
+ $.post("/credentials/clear/",{'emails':user_email}, function(data) {
+ }); // post credentials clear
+ mysliceAlert('Success: slice deleted','success', true);
+ }else{
+ mysliceAlert('Rest Error for: '+data.error,'warning', true);
+ }
+ window.location.replace("/");
+ });
+ }
+ else {
+ return false;
+ }
+ });
});
+
</script>
+
+<div>
+ <button id="renewslices" type="button" class="btn btn-primary"><span class="glyphicon glyphicon-refresh"></span> Renew slice</button>
+ <button id="deleteslices" type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Delete slice</button>
+</div>
def get_context_data(self, **kwargs):
page = Page(self.request)
- #print "UNIVBRIS page"
metadata = page.get_metadata()
page.expose_js_metadata()
from manifoldapi.manifoldapi import execute_query
from manifold.core.query import Query
from unfold.page import Page
+
from myslice.theme import ThemeView
+from myslice.settings import logger
class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
template_name = "validate_pending.html"
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']
+ logger.info("SFA PLATFORM > {}".format(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"
+ logger.warning("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
+ logger.debug("USER ACCOUNT {}".format(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()
+ logger.debug("CONFIG KEYS {}".format(config.keys()))
if 'authority_credentials' in config:
- print "***", config['authority_credentials'].keys()
+ logger.debug("*** AC {}".format(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()
+ logger.debug("*** DAC {}".format(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
+ logger.debug('credential_authorities = {}'.format(credential_authorities))
+ logger.debug('credential_authorities_expired = {}'.format(credential_authorities_expired))
# # Using cache manifold-tables to get the list of authorities faster
# all_authorities_query = Query.get('authority').select('name', 'authority_hrn')
try:
for pa in pi_authorities_tmp:
pi_authorities |= set(pa['pi_authorities'])
- except:
- print 'No pi_authorities'
+ except Exception as e:
+ logger.error('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
+ logger.debug("testing")
+ logger.debug(ctx_my_authorities)
context['my_authorities'] = ctx_my_authorities
context['sub_authorities'] = ctx_sub_authorities
context['delegation_authorities'] = ctx_delegation_authorities
config.close()
else:
return 0
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
def pres_view_animation(request, constraints, id):
}]
json_answer = json.dumps(cmd)
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
def pres_view_static(request, constraints, id):
#constraints = "']date_created':1262325600"
}]
json_answer = json.dumps(cmd)
- return HttpResponse (json_answer, mimetype="application/json")
+ return HttpResponse (json_answer, content_type="application/json")
-from manifold.core.query import Query
-from manifoldapi.manifoldapi import execute_query
-from portal.actions import is_pi
+import decimal
+import datetime
+import json
from django.http import HttpResponse
+from manifold.core.query import Query
+from manifoldapi.manifoldapi import execute_query
-import decimal
-import datetime
-import json
+from portal.actions import is_pi
+
+from myslice.settings import logger
# handles serialization of datetime in json
DateEncoder = lambda obj: obj.strftime("%B %d, %Y %H:%M:%S") if isinstance(obj, datetime.datetime) else None
# 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
+ logger.debug("key of object = {}".format(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)
+ logger.debug("param: {} : {}".format(k, v))
query.set({k : v})
- print "query = ",query
+ logger.debug("query = {}".format(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)
+ logger.debug("param: {} : {}".format(k, v))
query.set({k : v})
- print "query = ",query
+ logger.debug("query = {}".format(query))
else:
raise Exception, "Params are required for update"
elif request.method == 'GET':
#return error('only post request is supported')
req_items = request.GET
- print req_items
- for el in req_items.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))
if el[0].startswith('filters'):
o.filters[el[0][8:-1]] = el[1]
elif el[0].startswith('fields'):
- print req_items.getlist('fields[]')
o.setFields(req_items.getlist('fields[]'))
elif el[0].startswith('options'):
o.options = req_items.getlist('options[]')
error = "Error in delete return value"
except Exception, e:
error = str(e)
- #print "Exception : ",e
if error is not None:
ret = { "ret" : 1, "error" : error }
elif not results :
+import os
+import json
+import ConfigParser
+
+from django.shortcuts import render_to_response
+from django.http import HttpResponse
+
from sfa.trust.certificate import Keypair, Certificate
from sfa.client.sfaserverproxy import SfaServerProxy
from sfa.client.return_value import ReturnValue
from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
+
from manifold.core.query import Query
from manifold.models import db
from manifold.models.platform import Platform
from manifold.models.user import User
-from django.shortcuts import render_to_response
-
from unfold.loginrequired import LoginRequiredView
-from rest import ObjectRequest, error
-
-from string import join
-
-from django.http import HttpResponse
-from rest import error
-import os,json
-
-import ConfigParser
+from myslice.settings import logger
def dispatch(request, method):
Config = ConfigParser.ConfigParser()
from manifoldapi.manifoldapi import execute_admin_query
for pf in platforms:
platform = get_platform_config(pf)
- print platform
+ logger.debug("platform={}".format(platform))
if 'sm' in platform and len(platform['sm']) > 0:
- print 'sm'
+ logger.debug('sm')
server_url = platform['sm']
if 'rm' in platform and len(platform['rm']) > 0:
- print 'rm'
+ logger.debug('rm')
server_url = platform['rm']
if 'registry' in platform and len(platform['registry']) > 0:
- print 'registry'
+ logger.debug('registry')
server_url = platform['registry']
if not Config.has_option('monitor', 'cert') :
+from rest import ObjectRequest, error, success
+
from django.views.generic.base import TemplateView
from django.shortcuts import render_to_response
+from django.http import HttpResponse
from unfold.loginrequired import LoginRequiredView
-from django.http import HttpResponse
from manifold.core.query import Query, AnalyzedQuery
from manifoldapi.manifoldapi import execute_query
-from rest import ObjectRequest, error, success
-
-from string import join
-
-import json
-
+from myslice.settings import logger
def dispatch(request, object_type, object_name):
elif request.method == 'GET':
#return error('only post request is supported')
req_items = request.GET
- print req_items
+ logger.debug(req_items)
for el in req_items.items():
- print "#===============>",el
+ logger.debug("#===============> {}".format(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])
+ logger.debug("#======> 0 {}".format(el[0]))
+ logger.debug("#======> 1 {}".format(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
+ logger.debug("o.params = {}".format(o.params))
elif el[0].startswith('fields'):
o.fields=req_items.getlist('fields[]')
# tmp
from trashutils import lorem, hard_wired_slice_names
+from myslice.settings import logger
+
@login_required
def tab_view (request):
- print "request", request.__class__
- print request
+ logger.info("request {}".format(request.__class__))
+ logger.info("{}".format(request))
prelude=Prelude( js_files='js/bootstrap.js', css_files='css/bootstrap.css')
tab_env = {'title':'Page for playing with Tabs',
from ui.topmenu import topmenu_items_live, the_user
+from myslice.settings import logger
+
class TopmenuValidationView (TemplateView):
# mention a user name in the URL as .../trash/simpletopmenuvalidation/ple.inria.thierry_parmentelat
# define {js,css}_{files,chunks}
prelude_env = page.prelude_env()
-# print prelude_env.keys()
+# logger.info(prelude_env.keys())
# for k in [ 'js_files' ] :
-# print 'prelude_env',prelude_env,k,prelude_env[k]
+# logger.info('prelude_env {} {} {}'.format(prelude_env,k,prelude_env[k]))
template_env.update(prelude_env)
result=render_to_response ('view-unfold1.html',template_env,
# a set of utilities to help make the global layout consistent across views
+from myslice.settings import logger
+
def the_user (request):
"retrieves logged in user's email, or empty string"
if not request.user.is_authenticated ():
def topmenu_items_static (current, request):
has_user=request.user.is_authenticated()
result=[]
- print request.user
+ logger.debug("request user = {}".format(request.user))
if has_user:
result.append({'label':'Dashboard', 'href': '/portal/dashboard/'})
result.append({'label':'Request a slice', 'href': '/portal/slice_request/'})
# tmp - transition phase
def topmenu_items (current, request):
- print "WARNING -- please now use topmenu_items_live (label, page) toplevel_items is deprecated -- WARNING"
+ logger.warning("WARNING -- please now use topmenu_items_live (label, page) toplevel_items is deprecated -- WARNING")
return topmenu_items_static (current, request)
# integrated helper function for an animated menu
+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 unfold.plugin import Plugin
+from myslice.settings import logger
+
class Composite (Plugin):
"""a simple base class for plugins that contain/arrange a set of other plugins
def __init__ (self, sons=None, active_domid=None, *args, **kwds):
Plugin.__init__ (self, *args, **kwds)
- self.sons= sons if sons else []
- self.active_domid=active_domid
+ self.sons = sons if sons else []
+ self.active_domid = active_domid
# make sure this is valid, unset otherwise, so we always have exactly one active
self.check_active_domid()
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))
- self.active_domid=None
+ logger.warning("WARNING: {} has {} valid son(s) for being active - expecting 1, resetting"\
+ .format(self,len(matches)))
+ self.active_domid = None
def insert (self, plugin):
self.sons.append(plugin)
# {% for son in sons %} {{ son.rendered }} ...
def is_active (son,rank):
# if active_domid is not specified, make the first one active
- if not self.active_domid: return rank==0
- return son.domid==self.active_domid
- ranks=range(len(self.sons))
+ if not self.active_domid:
+ return rank==0
+ return son.domid == self.active_domid
+ ranks = range(len(self.sons))
env = { 'sons':
[ { 'rendered': son.render(request),
'rank': rank,
from manifoldapi.manifoldresult import ManifoldException
+from myslice.settings import logger
+
###
# IMPORTANT NOTE
# the implementation of the classes in this file rely on redefining 'dispatch'
def logout_on_manifold_exception (fun_that_returns_httpresponse):
def wrapped (request, *args, **kwds):
-# print 'wrapped by logout_on_manifold_exception'
try:
return fun_that_returns_httpresponse(request,*args, **kwds)
except ManifoldException, manifold_result:
return HttpResponseRedirect ('/')
except Exception, e:
# xxx we need to sugarcoat this error message in some error template...
- print "Unexpected exception",e
+ logger.error("Unexpected exception {}".format(e))
import traceback
- traceback.print_exc()
+ logger.error(traceback.format_exc())
return HttpResponseRedirect ('/')
return wrapped
from manifoldapi.metadata import MetaData
from unfold.prelude import Prelude
-
+from unfold.sessioncache import SessionCache
+
from myslice.configengine import ConfigEngine
+from myslice.settings import logger
# decorator to deflect calls on this Page to its prelude
def to_prelude (method):
# needs to be called explicitly and only when metadata is actually required
# in particular user needs to be logged
def get_metadata (self):
- # look in session's cache - we don't want to retrieve this for every request
- session=self.request.session
-
- if 'manifold' not in session:
- session['manifold'] = {}
- manifold = session['manifold']
-
- # if cached, use it
- if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
- if debug: print "Page.get_metadata: return cached value"
- return manifold['metadata']
+ cached_metadata = SessionCache().get_metadata(self.request)
+ if cached_metadata and isinstance(cached_metadata, MetaData):
+ logger.debug("Page.get_metadata: return cached value")
+ return cached_metadata
metadata_auth = {'AuthMethod':'anonymous'}
- metadata=MetaData (metadata_auth)
+ metadata = MetaData (metadata_auth)
metadata.fetch(self.request)
- # store it for next time
- manifold['metadata']=metadata
- if debug: print "Page.get_metadata: return new value"
+ SessionCache().store_metadata(self.request, metadata)
+ logger.debug("Page.get_metadata: return new value")
return metadata
def expose_js_metadata (self):
from unfold.page import Page
from unfold.prelude import Prelude
+from myslice.settings import logger
+
####################
# set DEBUG to
# . False : silent
# . [ 'SliceList', 'TabbedView' ] : to debug these classes
# . True : to debug all plugin
-DEBUG= False
-#DEBUG= [ 'SimpleList' ]
-#DEBUG=True
+DEBUG = False
+#DEBUG = [ 'SimpleList' ]
+#DEBUG = True
# decorator to deflect calls on Plugin to its Prelude through self.page.prelude
def to_prelude (method):
def actual (self, *args, **kwds):
if not self.page: # jordan
return None
- prelude_method=Prelude.__dict__[method.__name__]
- return prelude_method(self.page.prelude,*args, **kwds)
+ prelude_method = Prelude.__dict__[method.__name__]
+ return prelude_method(self.page.prelude, *args, **kwds)
return actual
class Plugin:
# using a simple incremental scheme to generate domids for now
# we just need this to be unique in a page
- domid=0
+ domid = 0
# when a domid is not set by the caller, we name plugins after their respective class as well,
# so as to limit name clashes between different views
# and maybe xxx we should just enforce that...
def newdomid(self):
Plugin.domid += 1
- return "plugin-%s-%d"%(self.__class__.__name__.lower(),Plugin.domid)
+ return "plugin-{}-{}".format(self.__class__.__name__.lower(), Plugin.domid)
##########
# Constructor
**settings):
self.page = page
# callers can provide their domid for css'ing
- if not domid: domid=self.newdomid()
- self.domid=domid
+ if not domid:
+ domid=self.newdomid()
+ self.domid = domid
# title is shown when togglable
#if not title: title="Plugin title for %s"%domid
- self.title=title
- self.classname=self._py_classname()
- self.plugin_classname=self._js_classname()
- self.visible=visible
- if togglable is None: self.togglable=self.default_togglable()
- else: self.togglable=togglable
- if toggled is None: self.toggled=self.default_toggled()
- else: self.toggled=toggled
- if outline_complete is None: self.outline_complete=self.default_outline_complete()
- else: self.outline_complete=outline_complete
- if outline_body is None: self.outline_body=self.default_outline_body()
- else: self.outline_body=outline_body
+ self.title = title
+ self.classname = self._py_classname()
+ self.plugin_classname = self._js_classname()
+ self.visible = visible
+ if togglable is None: self.togglable = self.default_togglable()
+ else: self.togglable = togglable
+ if toggled is None: self.toggled = self.default_toggled()
+ else: self.toggled = toggled
+ if outline_complete is None: self.outline_complete = self.default_outline_complete()
+ else: self.outline_complete = outline_complete
+ if outline_body is None: self.outline_body = self.default_outline_body()
+ else: self.outline_body = outline_body
# 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)
+ setattr(self, k, v)
+ if self.need_debug():
+ logger.debug("{} init - subclass setting {}".format(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
+ logger.debug("{} init dbg .... BEG".format(self.classname))
+ for (k, v) in self.__dict__.items():
+ logger.debug("dbg {}:{}".format(k, v))
+ logger.debug("{} init dbg .... END".format(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 setting_json (self, setting):
# TMP: js world expects plugin_uuid
- if setting=='plugin_uuid':
- value=self.domid
- elif setting=='query_uuid':
- try: value=self.query.query_uuid
- except: return '%s:"undefined"'%setting
+ if setting == 'plugin_uuid':
+ value = self.domid
+ elif setting == 'query_uuid':
+ try: value = self.query.query_uuid
+ except: return '{}:"undefined"'.format(setting)
else:
- value=getattr(self,setting,None)
- if value is None: value = "unknown-setting-%s"%setting
+ value = getattr(self,setting,None)
+ if value is None:
+ value = "unknown-setting-%s"%setting
# first try to use to_json method (json.dumps not working on class instances)
- try: value_json=value.to_json()
- except: value_json=json.dumps(value,separators=(',',':'))
- return "%s:%s"%(setting,value_json)
+ try: value_json = value.to_json()
+ except: value_json = json.dumps(value,separators=(',',':'))
+ return "{}:{}".format(setting, value_json)
# expose in json format to js the list of fields as described in json_settings_list()
# and add plugin_uuid: domid in the mix
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"
+ logger.debug("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 += "}"
plugin_content = self.render_content (request)
# shove this into plugin.html
env = {}
- env ['plugin_content']= plugin_content
+ env['plugin_content'] = plugin_content
env.update(self.__dict__)
# translate high-level 'toggled' into 4 different booleans
self.need_toggle = False
- if self.toggled=='persistent':
+ if self.toggled == 'persistent':
# start with everything turned off and let the js callback do its job
- env.update({'persistent_toggle':True,'display_hide_button':False,
- 'display_show_button':False,'display_body':False})
- elif self.toggled==False:
- env.update({'persistent_toggle':False,'display_hide_button':False,
- 'display_show_button':True,'display_body':False})
+ env.update({'persistent_toggle' : True, 'display_hide_button' : False,
+ 'display_show_button' : False, 'display_body' : False})
+ elif self.toggled == False:
+ env.update({'persistent_toggle' : False, 'display_hide_button' : False,
+ 'display_show_button' : True, 'display_body' : False})
else:
- env.update({'persistent_toggle':False,'display_hide_button':True,
- 'display_show_button':False,'display_body':True})
+ 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()
+ logger.debug("rendering plugin.html with env keys {}".format(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:
+ logger.debug("{} -> {}".format(k, v))
result = render_to_string ('plugin.html',env)
# export this only for relevant plugins
"""Should return an HTML fragment"""
template = self.template_file()
# start with a fresh one
- env={}
+ env = {}
# add our own settings as defaults
env.update(self.__dict__)
# then the things explicitly defined in template_env()
env.update(self.template_env(request))
if not isinstance (env,dict):
raise Exception, "%s.template_env returns wrong type"%self.classname
- result=render_to_string (template, env)
+ 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 "env=%s"%env
- #print result
- print "%s.render_content: END --------------------"%self.classname
+ logger.debug("{}.render_content: BEG --------------------".format(self.classname))
+ logger.debug("template={}".format(template))
+ logger.debug("env.keys={}".format(env.keys()))
+ logger.debug("{}.render_content: END --------------------".format(self.classname))
return result
# or from the result of self.requirements()
def handle_requirements (self, request):
try:
- d=self.requirements()
+ d = self.requirements()
for (k,v) in d.iteritems():
if self.need_debug():
- print "%s: handling requirement %s"%(self.classname,v)
+ logger.debug("{}: handling requirement {}".format(self.classname, v))
# e.g. js_files -> add_js_files
- method_name='add_'+k
- method=Page.__dict__[method_name]
- method(self.page,v)
+ method_name = 'add_' + k
+ method = Page.__dict__[method_name]
+ method(self.page, v)
except AttributeError:
# most likely the object does not have that method defined, which is fine
pass
except:
import traceback
- traceback.print_exc()
+ logger.log(traceback.format_exc())
pass
#################### requirements/prelude management
from django.template.loader import render_to_string
+from myslice.settings import logger
+
debug=False
# the need for js_init_chunks is because we need to have the plugins initialized
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)
+ logger.debug(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),)
+ logger.debug("prelude has {} js_files, {} css files, ({}+{}) js chunks and {} css_chunks"\
+ .format (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 }
--- /dev/null
+import uuid
+
+from manifold.util.singleton import Singleton
+
+from myslice.settings import logger
+
+# the key attached to the session object, where we store
+# the uuid attached to that session in this cache
+cache_key = 'cached_uuid'
+
+class _SessionExtension(object):
+ """
+ This object holds all the data we need to attach to a django session object
+ """
+
+ def __init__(self):
+ self.metadata = None
+ self.auth = None
+
+ def __repr__(self):
+ result = "<SessionExtension"
+ if self.metadata: result += " .metadata"
+ if self.auth: result += " .auth"
+ result += ">"
+ return result
+
+class SessionCache(dict):
+ """
+ As of django1.7, the session object as attached to a django request
+ gets JSON-serialized instead of pickled
+ This breaks our previous or passing data from request to request across
+ a given session - in particular for metadata and auth/session keys
+ Not that the problem is more with metadata as this is a class instance
+ and JSON cannot handle that
+ So instead we decorate the session object with a UID and retrieve all the rest
+ from the present - singleton - cache instance
+ """
+
+ __metaclass__ = Singleton
+
+ def get_auth(self, request):
+ """
+ Get the auth previously attached to the request's session, or None
+ """
+ result = self._get(request, 'auth')
+ return result
+
+ def store_auth(self, request, auth):
+ """
+ Store the auth object attached to this request's session
+ create that extension if needed
+ """
+ return self._store(request, 'auth', auth)
+
+ def get_metadata(self, request):
+ """
+ retrieve metadata attached to this request's session, or None
+ """
+ return self._get(request, 'metadata')
+
+ def store_metadata(self, request, metadata):
+ """
+ Store the metadata object attached to this request's session
+ create that extension if needed
+ """
+ return self._store(request, 'metadata', metadata)
+
+ def _get(self, request, key):
+ "internal - retrieve key - do not create anything"
+ session = request.session
+ logger.debug("sessioncache._get_{} session={}".format(key, SessionCache._debug_session(session)))
+# self._debug(request)
+ if cache_key not in session:
+ return None
+ cached_uuid = session[cache_key]
+ if cached_uuid not in self:
+ return None
+ extension = self[cached_uuid]
+ return getattr(extension, key)
+
+ def _store(self, request, key, value):
+ "internal - set key, attach and create extension if needed"
+ session = request.session
+ if cache_key not in session:
+ session[cache_key] = uuid.uuid1().int
+ cached_uuid = session[cache_key]
+ if cached_uuid not in self:
+ self[cached_uuid] = _SessionExtension()
+ extension = self[cached_uuid]
+ setattr(extension, key, value)
+ logger.debug("sessioncache._store_{} session={}".format(key, SessionCache._debug_session(session)))
+# self._debug(request)
+
+ def end_session(self, request):
+ """
+ Clear all data related to this request's session has we are logging out
+ This is for garbage collection
+ """
+ session = request.session
+ logger.debug("SessionCache.end_session() {}".format(self._debug_session(session)))
+ if cache_key not in session:
+ return
+ cached_uuid = session[cache_key]
+ if cached_uuid in self:
+ del self[cached_uuid]
+
+ def _debug(self, request):
+ session = request.session
+ logger.debug("SessionCache: ---------- with session {}".format(self._debug_session(session)))
+ for k,v in self.iteritems():
+ logger.debug("SessionCache {} -> {}".format(k,v))
+ if cache_key not in session:
+ return
+ cached_uuid = session[cache_key]
+ if cached_uuid not in self:
+ return
+ extension = self[cached_uuid]
+ logger.debug("SessionCache: found extension {}".format(extension))
+ logger.debug("SessionCache: ----------")
+
+ @staticmethod
+ def _debug_session(session):
+ result = ""
+ result += "{} x {}".format(session, session.keys())
+ if cache_key in session:
+ result += " <{} = {}>".format(cache_key, session[cache_key])
+ return result
+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)