Example #1
0
    def get(self, request, username='******'):

        if username == 'logged': username = '******'

        page = Page(request)

        # variables that will get passed to the view-unfold1.html template
        template_env = {}

        # write something of our own instead
        template_env['unfold_main'] = '<h1>Some title </h1>'

        # more general variables expected in the template
        template_env[
            'title'] = 'simple topmenuvalidation %(username)s' % locals()
        # the menu items on the top
        template_env['topmenu_items'] = topmenu_items_live('Slice', page)
        # so we can see who is logged
        template_env['username'] = the_user(request)

        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        prelude_env = page.prelude_env()

        #        logger.info(prelude_env.keys())
        #        for k in [ 'js_files' ] :
        #            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,
                                    context_instance=RequestContext(request))
        return result
Example #2
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)

        #        pres_view = PresView(page = page)
        pres_view = Raw(page=page,
                        html="<h1>PresView needs to be integrated</h1>")

        context = super(PresViewView, self).get_context_data(**kwargs)

        #context['ALL_STATIC'] = "all_static"
        context['unfold_main'] = pres_view.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Test view that combines various plugins'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('PresView', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
Example #3
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)

        # This will simulate fake records in order to test the plugin
        fake_query = Query.get('ping').select('hrn', 'src_hostname',
                                              'dst_hostname', 'delay')
        fake_query_all = Query.get('ping').select('hrn', 'src_hostname',
                                                  'dst_hostname', 'delay')

        generators = {
            'hrn': 'random_string',
            'src_hostname': 'random_string',
            'dst_hostname': 'random_string',
            'delay': 'random_int'
        }
        page.generate_records(fake_query, generators, 5)
        page.generate_records(fake_query_all, generators, 20)

        plugin = MadDash(query=fake_query, query_all=fake_query_all, page=page)
        context = super(MadDashView, self).get_context_data(**kwargs)
        context['unfold_main'] = plugin.render(self.request)
        context['title'] = 'Sandbox for MadDash plugin'
        context['topmenu_items'] = topmenu_items_live('maddash', page)
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
    def get (self, request, username='******'):

        if username=='logged': username='******'

        page=Page(request)

        # variables that will get passed to the view-unfold1.html template
        template_env = {}
        
        # write something of our own instead
        template_env ['unfold_main'] = '<h1>Some title </h1>'
        
        # more general variables expected in the template
        template_env [ 'title' ] = 'simple topmenuvalidation %(username)s'%locals()
        # the menu items on the top
        template_env [ 'topmenu_items' ] = topmenu_items_live('Slice', page) 
        # so we can see who is logged
        template_env [ 'username' ] = the_user (request) 
    
        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        prelude_env = page.prelude_env()

#        print prelude_env.keys()
#        for k in [ 'js_files' ] :
#            print 'prelude_env',prelude_env,k,prelude_env[k]

        template_env.update(prelude_env)
        result=render_to_response ('view-unfold1.html',template_env,
                                   context_instance=RequestContext(request))
        return result
Example #5
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)

        # This will simulate fake records in order to test the plugin
        fake_query = Query.get('ping').select('hrn', 'src_hostname', 'dst_hostname', 'delay')
        fake_query_all = Query.get('ping').select('hrn', 'src_hostname', 'dst_hostname', 'delay')

        generators = {
            'hrn': 'random_string',
            'src_hostname': 'random_string',
            'dst_hostname': 'random_string',
            'delay': 'random_int'
        }
        page.generate_records(fake_query, generators, 5)
        page.generate_records(fake_query_all, generators, 20)

        plugin = MadDash(query = fake_query, query_all = fake_query_all, page = page)
        context = super(MadDashView, self).get_context_data(**kwargs)
        context['unfold_main'] = plugin.render(self.request)
        context['title'] = 'Sandbox for MadDash plugin'
        context['topmenu_items'] = topmenu_items_live ('maddash', page)
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
Example #6
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        page.add_js_files(["js/common.functions.js"])
        platform_query = Query().get('local:platform').filter_by(
            'disabled', '==', '0').select('platform', 'platform_longname',
                                          'gateway_type')
        #platform_query  = Query().get('local:platform').select('platform','platform_longname','gateway_type')
        page.enqueue_query(platform_query)

        page.expose_js_metadata()
        platformlist = QueryTable(
            page=page,
            title='List',
            domid='checkboxes',
            # this is the query at the core of the slice list
            query=platform_query,
            query_all=platform_query,
            checkboxes=False,
            init_key='platform',
            datatables_options={
                'iDisplayLength': 10,
                'bLengthChange': True,
                'bAutoWidth': True,
            },
        )

        context = super(PlatformsView, self).get_context_data(**kwargs)
        context['person'] = self.request.user
        context['platforms'] = platformlist.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Platforms', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        context['theme'] = self.theme
        context.update(page.prelude_env())

        context['layout_1_or_2'] = "layout-unfold2.html" if not context[
            'username'] else "layout-unfold1.html"

        return context
Example #7
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)

        plugin = MyPlugin(page=page)
        context = super(MyPluginView, self).get_context_data(**kwargs)
        context['unfold_main'] = plugin.render(self.request)

        # more general variables expected in the template
        context['title'] = 'Sandbox for MyPlugin plugin'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('myplugin', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
Example #8
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)

        plugin = MyPlugin(page = page)
        context = super(MyPluginView, self).get_context_data(**kwargs)
        context['unfold_main'] = plugin.render(self.request)

        # more general variables expected in the template
        context['title'] = 'Sandbox for MyPlugin plugin'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('myplugin', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        page.add_js_files  ( [ "js/common.functions.js" ] )
        platform_query  = Query().get('local:platform').filter_by('disabled', '==', '0').select('platform','platform_longname','gateway_type')
        #platform_query  = Query().get('local:platform').select('platform','platform_longname','gateway_type')
        page.enqueue_query(platform_query)

        page.expose_js_metadata()
        platformlist = QueryTable(
            page  = page,
            title = 'List',
            domid = 'checkboxes',
            # this is the query at the core of the slice list
            query = platform_query,
            query_all = platform_query,
            checkboxes = False,
            init_key   = 'platform',
            datatables_options = { 
                'iDisplayLength': 10,
                'bLengthChange' : True,
                'bAutoWidth'    : True,
                },
        )

        context = super(PlatformsView, self).get_context_data(**kwargs)
        context['person']   = self.request.user
        context['platforms'] = platformlist.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Platforms', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context.update(page.prelude_env())

        context['layout_1_or_2']="layout-unfold2.html" if not context['username'] else "layout-unfold1.html"

        return context
Example #10
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)

#        pres_view = PresView(page = page)
        pres_view = Raw(page = page,html="<h1>PresView needs to be integrated</h1>")

        context = super(PresViewView, self).get_context_data(**kwargs)

        #context['ALL_STATIC'] = "all_static"
        context['unfold_main'] = pres_view.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Test view that combines various plugins'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('PresView', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        prelude_env = page.prelude_env()
        context.update(prelude_env)

        return context
Example #11
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        page.add_js_files  ( [ "js/common.functions.js" ] )

        for key, value in kwargs.iteritems():
            print "%s = %s" % (key, value)       
            if key == "platformname":
                platformname=value
                
        network_query  = Query().get('local:platform')\
            .filter_by('platform', '==', platformname)\
            .select('platform','platform_longname','gateway_type')
        page.enqueue_query(network_query)

        # ListResources of the platform
        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]
        resources = platformname + ':resource'
        query_resource_all = Query.get(resources).select(resource_fields)
        page.enqueue_query(query_resource_all)
        query_resource_default_fields = Query.get(resources).select('hrn','hostname', 'type','country')
        page.enqueue_query(query_resource_default_fields)

        page.expose_js_metadata()
        networklist = QueryTable(
            page  = page,
            title = 'List',
            domid = 'checkboxes',
            # this is the query at the core of the slice list
            query = network_query,
            query_all = network_query,
            checkboxes = False,
            datatables_options = {
            'iDisplayLength' : 25,
            'bLengthChange'  : True,
            },
        )

#        networklist = SimpleList(
#            title = None,
#            page  = page,
#            key   = 'platform',
#            query = network_query,
#        )
#
        # --------------------------------------------------------------------------
        # RESOURCES
        # for internal use in the querytable plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hrn'

        # the resources part is made of a Tabs (Geographic, List), 
        resources_as_gmap = GoogleMap(
            page       = page,
            title      = 'Geographic view',
            domid      = 'resources-map',
            # tab's sons preferably turn this off
            togglable  = False,
            query      = query_resource_default_fields,
            query_all  = query_resource_all,
            # this key is the one issued by google
            googlemap_api_key = ConfigEngine().googlemap_api_key(),
            # the key to use at init-time
            init_key   = main_query_init_key,
            checkboxes = False,
            # center on Paris
            latitude   = 49.,
            longitude  = 9,
            zoom       = 4,
        )
        resources_as_3dmap = SensLabMap(
            page       = page,
            title      = '3D Map',
            domid      = 'senslabmap',
            query      = query_resource_default_fields,
            query_all  = query_resource_all,
        )
        resources_as_list = QueryTable(
            page       = page,
            domid      = 'resources-list',
            title      = 'List view',
            # this is the query at the core of the slice list
            query      = query_resource_default_fields,
            query_all  = query_resource_all,
            init_key     = main_query_init_key,
            checkboxes = False,
            datatables_options = {
                'iDisplayLength': 25,
                'bLengthChange' : True,
                'bAutoWidth'    : True,
                },
            )
        resources_sons = [
             resources_as_gmap,
             resources_as_3dmap,
             resources_as_list,
             ]
        resources_area = Tabs ( page=page,
                                domid="resources",
                                togglable=True,
                                title="Resources",
                                outline_complete=True,
                                sons= resources_sons,
                                active_domid = 'resources-map',
                                persistent_active=True,
                                )

        context = super(PlatformView, self).get_context_data(**kwargs)
        context['person']   = self.request.user
        context['networks'] = networklist.render(self.request)
        context['resources'] = resources_area.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Platforms', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context.update(page.prelude_env())

        return context
Example #12
0
 def get_context_data(self, **kwargs):
     
     page = Page(self.request)
     metadata = page.get_metadata()
     page.expose_js_metadata()
 
     resource_md = metadata.details_by_object('resource')
     resource_fields = [column['name'] for column in resource_md['column']]
 
     user_md = metadata.details_by_object('user')
     user_fields = ['user_hrn'] # [column['name'] for column in user_md['column']]
 
 
 	#create new query to manifold----query is not called yet
 	#need to modify to get i2cat of resources also
     univbrisfoam_query=Query().get('ofelia-bristol-of:resource').select('urn')
     #print univbrisfoam_query #.select('urn')
 	#Query().get('ofelia-bristol-of:resource')
 	##custom query to communication between univbris plugins
     #univbris_query=Query()
         
 	#queue the query
     page.enqueue_query(univbrisfoam_query)
     #page.enqueue_query(univbris_query)
     page.expose_js_metadata()
 
 
 	#plugin which display a "gathering resources" message waiting for all resources to be returned by manifold
     univbriswelcome = Univbris(
         page  = page,
         title = 'univbris_welcome',
         domid = 'univbris_welcome',
         query = univbrisfoam_query,
     )
 	
 	#plugin which collects different openflow ports from maniford
     univbrisfoamlist = UnivbrisFoam(
         page  = page,
         title = 'univbris_foam_ports_selection',
         domid = 'univbris_foam_ports_selection',
         query = univbrisfoam_query,
         query_all = univbrisfoam_query,
 	    sync_query= univbrisfoam_query,
         checkboxes = False,
         datatables_options = { 
             'iDisplayLength': 10,
             'bLengthChange' : True,
             'bAutoWidth'    : True,
             },
     )
 
 	#plugin which manages the different flowspaces that the user creates, and also sends flowspaces to manifold
     univbrisfvlist = UnivbrisFv(
         page  = page,
         title = 'univbris_flowspace_selection',
         domid = 'univbris_flowspace_selection',
 	    query = None,
         query_all = None,
 	    sync_query= univbrisfoam_query,
         datatables_options = { 
             'iDisplayLength': 5,
             'bLengthChange' : True,
             'bAutoWidth'    : True,
             },
     )
 
 	#plugin which allows the definition the match criteria on a single PACKET flowspace
     univbrisfvform = UnivbrisFvf(
         page  = page,
         title = 'univbris_flowspace_form',
         domid = 'univbris_flowspace_form',
 	    query = None,
         query_all = None,
         datatables_options = { 
             'iDisplayLength': 3,
             'bLengthChange' : True,
             'bAutoWidth'    : True,
             },
     )
 
 	#plugin which allows the definition the match criteria on a single OPTICAL flowspace
 
     univbrisofvform = UnivbrisFvfo(
             page  = page,
             title = 'univbris_oflowspace_form',
             domid = 'univbris_oflowspace_form',
 	        query = None,
             query_all = None,
             datatables_options = { 
                 'iDisplayLength': 3,
                 'bLengthChange' : True,
                 'bAutoWidth'    : True,
                 },
         )
 
 
 	#plugin which display the gathered topology
     univbristopology = UnivbrisTopo(
             page  = page,
             title = 'univbris_topology',
             domid = 'univbris_topology',
             query = univbrisfoam_query,
         )
 	
 	#render plugins in each context within a single page, but not all plugins are visible at all time.
     context = super(UnivbrisView, self).get_context_data(**kwargs)
     context['person']   = self.request.user
     context['welcome'] = univbriswelcome.render(self.request)
     context['resources'] = univbrisfoamlist.render(self.request)
     context['flowspaces']= univbrisfvlist.render(self.request)
     context['oflowspaces_form']= univbrisofvform.render(self.request)
     context['flowspaces_form']= univbrisfvform.render(self.request)
     context['topology']=univbristopology.render(self.request)
 
     # XXX This is repeated in all pages
     # more general variables expected in the template
     context['title'] = 'Book OpenFlow resources'
     # the menu items on the top
     context['topmenu_items'] = topmenu_items_live('univbris', page)
     # so we can sho who is logged
     context['username'] = the_user(self.request)
     
     context.update(page.prelude_env())
     page.expose_js_metadata()
     
     
     # the page header and other stuff
     context.update(page.prelude_env())
     
     context['layout_1_or_2']="layout-unfold2.html" if not context['username'] else "layout-unfold1.html"
     
     return context
    def get_or_post  (self, request, method):
        errors = []

        # Using cache manifold-tables to get the list of authorities faster
        authorities_query = Query.get('authority').select('name', 'authority_hrn')
        
        #onelab_enabled_query = Query.get('local:platform').filter_by('platform', '==', 'ple').filter_by('disabled', '==', 'False')
        #onelab_enabled = not not execute_admin_query(request, onelab_enabled_query)
        #if onelab_enabled:
        if True:
            print "ONELAB ENABLED"
            #authorities_query = Query.get('ple:authority').select('name', 'authority_hrn').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc', 'ple.ibbtple', 'ple.nitos'])
            # Now using Cache 
        else:
            print "FIREXP ENABLED"

        authorities = execute_admin_query(request, authorities_query)
        if authorities is not None:
            authorities = sorted(authorities)
        # xxx tocheck - if authorities is empty, it's no use anyway
        # (users won't be able to validate the form anyway)

        page = Page(request)
        page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js" ] )
        page.add_css_files ( [ "css/onelab.css", "css/registration.css" ] )
        page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )

        print 'registration view, method',method

        user_query  = Query().get('local:user').select('user_id','email')
        user_details = execute_admin_query(self.request, user_query)

        if method == 'POST':
            # We shall use a form here

            #get_email = PendingUser.objects.get(email)
            reg_fname  = request.POST.get('firstname', '')
            reg_lname  = request.POST.get('lastname', '')
            #reg_aff   = request.POST.get('affiliation','')
            reg_auth   = request.POST.get('authority_hrn', '')
            #reg_login  = request.POST.get('login', '')
            reg_email  = request.POST.get('email','').lower()
            #prepare user_hrn 
            split_email = reg_email.split("@")[0] 
            split_email = split_email.replace(".", "_")
            user_hrn = reg_auth + '.' + split_email+ str(randint(1,1000000))
            
            UserModel = get_user_model()

            #POST value validation  
            if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
                errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
            if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
                errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
            # checking in django_db !!
            if PendingUser.objects.filter(email__iexact=reg_email):
                errors.append('Email is pending for validation. Please provide a new email address.')
            if UserModel._default_manager.filter(email__iexact=reg_email): 
                errors.append('This email is not usable. Please contact the administrator or try with another email.')
            for user_detail in user_details:
                if user_detail['email']==reg_email:
                    errors.append('Email already registered in Manifold. Please provide a new email address.')

# XXX TODO: Factorize with portal/accountview.py
            if 'generate' in request.POST['question']:
                from Crypto.PublicKey import RSA
                private = RSA.generate(1024)
                private_key = json.dumps(private.exportKey())
                public  = private.publickey()
                public_key = json.dumps(public.exportKey(format='OpenSSH'))

#                # Generate public and private keys using SFA Library
#                from sfa.trust.certificate  import Keypair
#                k = Keypair(create=True)
#                public_key = k.get_pubkey_string()
#                private_key = k.as_pem()
#                private_key = ''.join(private_key.split())
#                public_key = "ssh-rsa " + public_key
                # Saving to DB
                account_config = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
                auth_type = 'managed'
                #keypair = re.sub("\r", "", keypair)
                #keypair = re.sub("\n", "\\n", keypair)
                #keypair = keypair.rstrip('\r\n')
                #keypair = ''.join(keypair.split())
                #for sending email: removing existing double qoute 
                public_key = public_key.replace('"', '');
            else: 
                up_file = request.FILES['user_public_key']
                file_content =  up_file.read()
                file_name = up_file.name
                file_extension = os.path.splitext(file_name)[1]
                allowed_extension =  ['.pub','.txt']
                if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
                    account_config = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
                    account_config = re.sub("\r", "", account_config)
                    account_config = re.sub("\n", "\\n",account_config)
                    account_config = ''.join(account_config.split())
                    auth_type = 'user'
                    # for sending email
                    public_key = file_content
                    public_key = ''.join(public_key.split()) 
                else:
                    errors.append('Please upload a valid RSA public key.')

            #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
            #                email=reg_email, password=request.POST['password'], keypair=keypair)
            #b.save()
            #saving to django db 'portal_pendinguser' table
            if not errors:
                b = PendingUser(
                    first_name    = reg_fname, 
                    last_name     = reg_lname, 
                    #affiliation  = reg_aff,
                    authority_hrn = reg_auth,
                    #login         = reg_login,
                    email         = reg_email, 
                    password      = request.POST['password'],
                    keypair       = account_config,
                    pi            = '',
                )
                b.save()
                # saves the user to django auth_user table [needed for password reset]
                user = User.objects.create_user(reg_email, reg_email, request.POST['password'])
                #creating user to manifold local:user
                user_config = '{"firstname":"'+ reg_fname + '", "lastname":"'+ reg_lname + '", "authority":"'+ reg_auth + '"}'
                user_params = {'email': reg_email, 'password': request.POST['password'], 'config': user_config, 'status': 1}
                manifold_add_user(request,user_params)
                #creating local:account in manifold
                user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
                account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
                manifold_add_account(request,account_params)
 
                # Send email
                ctx = {
                    'first_name'    : reg_fname, 
                    'last_name'     : reg_lname, 
                    'authority_hrn' : reg_auth,
                    'email'         : reg_email,
                    'user_hrn'      : user_hrn,
                    'public_key'    : public_key,
                    }
                recipients = authority_get_pi_emails(request,reg_auth)
                # backup email: if authority_get_pi_emails fails
                recipients.append('*****@*****.**')
                
                msg = render_to_string('user_request_email.txt', ctx)
                send_mail("Onelab New User request for %s submitted"%reg_email, msg, '*****@*****.**', recipients)
                return render(request, 'user_register_complete.html') 

        template_env = {
          'topmenu_items': topmenu_items_live('Register', page),
          'errors': errors,
          'firstname': request.POST.get('firstname', ''),
          'lastname': request.POST.get('lastname', ''),
          #'affiliation': request.POST.get('affiliation', ''),
          'authority_hrn': request.POST.get('authority_hrn', ''),
          'email': request.POST.get('email', ''),
          'password': request.POST.get('password', ''),           
          'authorities': authorities,
          }
        template_env.update(page.prelude_env ())
        return render(request, 'registration_view.html',template_env)
Example #14
0
    def get_context_data(self, **kwargs):
        # We might have slices on different registries with different user accounts
        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
        #messages.info(self.request, 'You have logged in')
        page = Page(self.request)

        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')
        # DEMO GEC18 Query only PLE
        #        user_query  = Query().get('local:user').select('config','email')
        #        user_details = execute_query(self.request, user_query)

        # not always found in user_details...
        #        config={}
        #      for user_detail in user_details:
        #          #email = user_detail['email']
        #          if user_detail['config']:
        #              config = json.loads(user_detail['config'])
        #      user_detail['authority'] = config.get('authority',"Unknown Authority")
        #
        #        print user_detail
        #        if user_detail['authority'] is not None:
        #            sub_authority = user_detail['authority'].split('.')
        #            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:
        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)

        slicelist = SliceList(
            page=page,
            title="slices",
            warning_msg="<a href='../slice_request'>Request Slice</a>",
            query=slice_query,
        )
        testbedlist = TestbedList(
            page=page,
            title="testbeds",
            query=testbed_query,
        )

        context = super(DashboardView, self).get_context_data(**kwargs)
        context['person'] = self.request.user
        context['testbeds'] = testbedlist.render(self.request)
        context['slices'] = slicelist.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Dashboard'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Dashboard', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context['theme'] = self.theme

        page.expose_js_metadata()

        # the page header and other stuff
        context.update(page.prelude_env())

        return context
Example #15
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)
        page.add_js_files([
            "js/jquery.validate.js", "js/my_account.register.js",
            "js/my_account.edit_profile.js", "js/jquery-ui.js"
        ])
        page.add_css_files([
            "css/onelab.css", "css/account_view.css", "css/plugin.css",
            "css/jquery-ui.css"
        ])

        for key, value in kwargs.iteritems():
            if key == "email":
                selected_email = value

        user_query = Query().get('local:user').filter_by(
            'email', '==', selected_email).select('user_id', 'config', 'email',
                                                  'status')
        user_details = execute_admin_query(self.request, user_query)

        # not always found in user_details...
        config = {}
        for user_detail in user_details:
            user_id = user_detail['user_id']
            user_email = user_detail['email']
            # different significations of user_status
            if user_detail['status'] == 0:
                user_status = 'Disabled'
            elif user_detail['status'] == 1:
                user_status = 'Validation Pending'
            elif user_detail['status'] == 2:
                user_status = 'Enabled'
            else:
                user_status = 'N/A'
            #email = user_detail['email']
            if user_detail['config']:
                config = json.loads(user_detail['config'])
                authority_hrn = config.get('authority', 'Unknown Authority')

        platform_query = Query().get('local:platform').select(
            'platform_id', 'platform', 'gateway_type', 'disabled')
        account_query = Query().get('local:account').filter_by(
            'user_id', '==', user_id).select('user_id', 'platform_id',
                                             'auth_type', 'config')
        platform_details = execute_query(self.request, platform_query)
        account_details = execute_admin_query(self.request, account_query)

        # initial assignment needed for users having account.config = {}
        platform_name = ''
        account_type = ''
        account_usr_hrn = ''
        account_pub_key = ''
        account_priv_key = ''
        account_reference = ''
        my_users = ''
        my_slices = ''
        my_auths = ''
        ref_acc_list = ''
        principal_acc_list = ''
        user_status_list = []
        platform_name_list = []
        platform_name_secondary_list = []
        platform_access_list = []
        platform_no_access_list = []
        total_platform_list = []
        account_type_list = []
        account_type_secondary_list = []
        account_reference_list = []
        delegation_type_list = []
        user_cred_exp_list = []
        slice_list = []
        auth_list = []
        slice_cred_exp_list = []
        auth_cred_exp_list = []
        usr_hrn_list = []
        pub_key_list = []

        for platform_detail in platform_details:
            if 'sfa' in platform_detail['gateway_type']:
                total_platform = platform_detail['platform']
                total_platform_list.append(total_platform)

            for account_detail in account_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    platform_name = platform_detail['platform']
                    if 'config' in account_detail and account_detail[
                            'config'] is not '':
                        account_config = json.loads(account_detail['config'])
                        account_usr_hrn = account_config.get('user_hrn', 'N/A')
                        account_pub_key = account_config.get(
                            'user_public_key', 'N/A')
                        account_reference = account_config.get(
                            'reference_platform', 'N/A')

                    # credentials of myslice platform
                    if 'myslice' in platform_detail['platform']:
                        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')
                        #usr_hrn of myslice platform. used to check pi or no
                        account_usr_hrn_myslice = account_config.get(
                            'user_hrn', '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)
                                # get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>',
                                                     value)
                                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)
                                #get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>',
                                                     value)
                                if exp_date:
                                    exp_date = exp_date.group(1)
                                    auth_cred_exp_list.append(exp_date)

                            my_auths = [{
                                'auth_name': t[0],
                                'cred_exp': t[1]
                            } for t in zip(auth_list, auth_cred_exp_list)]

                    # for reference accounts
                    if 'reference' in account_detail['auth_type']:
                        account_type = 'Reference'
                        delegation = 'N/A'
                        platform_name_secondary_list.append(platform_name)
                        account_type_secondary_list.append(account_type)
                        account_reference_list.append(account_reference)
                        ref_acc_list = [{
                            'platform_name': t[0],
                            'account_type': t[1],
                            'account_reference': t[2]
                        } for t in zip(platform_name_secondary_list,
                                       account_type_secondary_list,
                                       account_reference_list)]

                    elif 'managed' in account_detail['auth_type']:
                        account_type = 'Principal'
                        delegation = 'Automatic'
                    else:
                        account_type = 'Principal'
                        delegation = 'Manual'
                    # for principal (auth_type=user/managed) accounts
                    if 'reference' not in account_detail['auth_type']:
                        platform_name_list.append(platform_name)
                        account_type_list.append(account_type)
                        delegation_type_list.append(delegation)
                        usr_hrn_list.append(account_usr_hrn)
                        pub_key_list.append(account_pub_key)
                        user_status_list.append(user_status)
                        # combining 5 lists into 1 [to render in the template]
                        principal_acc_list = [{
                            'platform_name': t[0],
                            'account_type': t[1],
                            'delegation_type': t[2],
                            'usr_hrn': t[3],
                            'usr_pubkey': t[4],
                            'user_status': t[5],
                        } for t in zip(platform_name_list, account_type_list,
                                       delegation_type_list, usr_hrn_list,
                                       pub_key_list, user_status_list)]
                    # to hide private key row if it doesn't exist
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        account_priv_key = account_config.get(
                            'user_private_key', 'N/A')
                    if 'sfa' in platform_detail['gateway_type']:
                        platform_access = platform_detail['platform']
                        platform_access_list.append(platform_access)

        # Removing the platform which already has access
        for platform in platform_access_list:
            total_platform_list.remove(platform)
        # we could use zip. this one is used if columns have unequal rows
        platform_list = [{
            'platform_no_access': t[0]
        } for t in itertools.izip_longest(total_platform_list)]

        ## check pi or no
        pi_status = self.request.session['user']['pi']

        context = super(UserView, self).get_context_data(**kwargs)
        context['principal_acc'] = principal_acc_list
        context['ref_acc'] = ref_acc_list
        context['platform_list'] = platform_list
        context['my_users'] = my_users
        context['my_slices'] = my_slices
        context['my_auths'] = my_auths
        context['user_status'] = user_status
        context['user_email'] = user_email
        context['firstname'] = config.get('firstname', "?")
        context['lastname'] = config.get('lastname', "?")
        context['fullname'] = context['firstname'] + ' ' + context['lastname']
        context['authority'] = config.get('authority', "Unknown Authority")
        context['user_private_key'] = account_priv_key
        context['pi'] = pi_status

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('My Account', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        context['theme'] = self.theme
        #        context ['firstname'] = config['firstname']
        prelude_env = page.prelude_env()
        context.update(prelude_env)
        return context
Example #16
0
    def get_context_data(self, **kwargs):
        # We might have slices on different registries with different user accounts 
        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn

        #messages.info(self.request, 'You have logged in')
        page = Page(self.request)

        print "Dashboard page"
        # Slow...
        #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
        testbed_query  = Query().get('network').select('network_hrn','platform','version')
        # DEMO GEC18 Query only PLE
#        user_query  = Query().get('local:user').select('config','email')
#        user_details = execute_query(self.request, user_query)

        # not always found in user_details...
#        config={}
  #      for user_detail in user_details:
  #          #email = user_detail['email']
  #          if user_detail['config']:
  #              config = json.loads(user_detail['config'])
  #      user_detail['authority'] = config.get('authority',"Unknown Authority")
#
#        print user_detail
#        if user_detail['authority'] is not None:
#            sub_authority = user_detail['authority'].split('.')
#            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:
        slice_query = Query().get('user').filter_by('user_hrn', '==', '$user_hrn').select('slice.slice_hrn')
        page.enqueue_query(slice_query)
        page.enqueue_query(testbed_query)

        slicelist = SliceList(
            page  = page,
            title = "slices",
            warning_msg = "<a href='../slice_request'>Request Slice</a>",
            query = slice_query,
        )
        testbedlist = TestbedList(
            page  = page,
            title = "testbeds",
            query = testbed_query,
        )
 
        context = super(DashboardView, self).get_context_data(**kwargs)
        context['person']   = self.request.user
        context['testbeds'] = testbedlist.render(self.request) 
        context['slices']   = slicelist.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Dashboard'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Dashboard', page) 
        # so we can sho who is logged
        context['username'] = the_user(self.request) 

        page.expose_js_metadata()

        # the page header and other stuff
        context.update(page.prelude_env())

        return context
Example #17
0
def dashboard_view(request):

    page = Page(request)

    slices_query = Query.get('slice').select('slice_hrn')
    #old#                                  # xxx filter : should filter on the slices the logged user can see
    #old#                                  # we don't have the user's hrn yet
    #old#                                  # in addition this currently returns all slices anyways
    #old#                                  # filter = ...
    #old#                                  sort='slice_hrn',)
    page.enqueue_query(slices_query)

    main_plugin = Stack(
        page=page,
        title="Putting stuff together",
        sons=[
            QueryCode(
                page=page,
                title="Vizualize your query",
                query=slices_query,
                toggled=False,
            ),
            QuickFilter(
                # we play with this one for demo purposes in dashboard.css
                domid='myquickfilter',
                page=page,
                title='play with filters',
                criterias=quickfilter_criterias,
                toggled=False,
            ),
            SliceList(  # setting visible attributes first
                page=page,
                title='Asynchroneous SliceList',
                header='slices list',
                with_datatables=False,
                # this is the query at the core of the slice list
                query=slices_query,
            ),
        ])

    # variables that will get passed to the view-unfold2.html template
    template_env = {}

    # define 'unfold_main' to the template engine
    template_env['unfold_main'] = main_plugin.render(request)

    # more general variables expected in the template
    template_env['title'] = 'Test view for a full request cycle'
    # the menu items on the top
    template_env['topmenu_items'] = topmenu_items_live('dashboard', page)
    # so we can sho who is logged
    template_env['username'] = the_user(request)

    #   ########## add another plugin with the same request, on the RHS pane
    #   will show up in the right-hand side area named 'related'
    related_plugin = SliceList(
        page=page,
        title='Same request, other layout',
        domid='sidelist',
        with_datatables=True,
        header='paginated slices',
        # share the query
        query=slices_query,
    )
    # likewise but on the side view
    template_env['unfold_margin'] = related_plugin.render(request)

    # add our own css in the mix
    #page.add_css_files ( 'css/dashboard.css')

    # the prelude object in page contains a summary of the requirements() for all plugins
    # define {js,css}_{files,chunks}
    prelude_env = page.prelude_env()
    template_env.update(prelude_env)
    return render_to_response('view-unfold2.html',
                              template_env,
                              context_instance=RequestContext(request))
Example #18
0
    def get (self,request, slicename=tmp_default_slice):
    
        page = Page(request)
        page.add_css_files ('css/slice-view.css')
        page.add_js_files  ( [ "js/common.functions.js" ] )
        page.add_js_chunks ('$(function() { messages.debug("sliceview: jQuery version " + $.fn.jquery); });')
        page.add_js_chunks ('$(function() { messages.debug("sliceview: users turned %s"); });'%("on" if do_query_users else "off"))
        page.add_js_chunks ('$(function() { messages.debug("sliceview: leases turned %s"); });'%("on" if do_query_leases else "off"))
        page.add_js_chunks ('$(function() { messages.debug("manifold URL %s"); });'%(ConfigEngine().manifold_url()))

        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]
    
        user_md = metadata.details_by_object('user')
        user_fields = ['user_hrn'] # [column['name'] for column in user_md['column']]
    
        # TODO The query to run is embedded in the URL
        main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
        main_query.select(
                'slice_hrn',
                #'resource.hrn', 'resource.urn', 
                'resource.hostname', 'resource.type', 
                'resource.network_hrn',
                'lease.urn',
                'user.user_hrn',
                #'application.measurement_point.counter'
        )
        # for internal use in the querytable plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hostname'
    
        query_resource_all = Query.get('resource').select(resource_fields)

        aq = AnalyzedQuery(main_query, metadata=metadata)
        page.enqueue_query(main_query, analyzed_query=aq)
        page.enqueue_query(query_resource_all)
        if do_query_users:
            # Required: the user must have an authority in its user.config
            # XXX Temporary solution
            user_query  = Query().get('local:user').select('config','email')
            user_details = execute_query(self.request, user_query)
            
            # not always found in user_details...
            config={}
#            for user_detail in user_details:
#                #email = user_detail['email']
#                if user_detail['config']:
#                    config = json.loads(user_detail['config'])
#            user_detail['authority'] = config.get('authority',"Unknown Authority")
#
#            if user_detail['authority'] is not None:
#                sub_authority = user_detail['authority'].split('.')
#                root_authority = sub_authority[0]
#                query_user_all = Query.get(root_authority+':user').select(user_fields)
#
#                # XXX TODO this filter doesn't work - to be improved in Manifold
#                #.filter_by('authority.authority_hrn', '=', user_detail['authority'])
#
#                page.enqueue_query(query_user_all)
#            else:
#                print "authority of the user is not in local:user db"
            query_user_all = Query.get('user').select(user_fields)
            #    query_user_all = None
    
        # ... and for the relations
        # XXX Let's hardcode resources for now
        sq_resource    = aq.subquery('resource')
        sq_user        = aq.subquery('user')
        sq_lease       = aq.subquery('lease')
        sq_measurement = aq.subquery('measurement')
        
    
        # Prepare the display according to all metadata
        # (some parts will be pending, others can be triggered by users).
        # 
        # For example slice measurements will not be requested by default...
    
        # Create the base layout (Stack)...
        main_stack = Stack (
            page=page,
            title="Slice %s"%slicename,
            sons=[],
        )
    
        # ... responsible for the slice properties...
    
        # a nice header
        main_stack.insert (
            Raw (page=page,
                 togglable=False, 
                 toggled=True,
                 html="<h2 class='well well-lg'> Slice %s</h2>"%slicename)
        )
    
        # --------------------------------------------------------------------------
        # QueryUpdater (Pending Operations)

        main_stack.insert(QueryUpdater(
            page                = page,
            title               = 'Pending operations',
            query               = main_query,
            togglable           = True,
            # start turned off, it will open up itself when stuff comes in
            toggled             = False, 
            domid               = 'pending',
            outline_complete    = True,
        ))

        # --------------------------------------------------------------------------
        # Filter Resources
       
# turn off for now -- see above
        filter_query_editor = QueryEditor(
            page  = page,
            query = sq_resource, 
            query_all = query_resource_all,
            title = "Select Columns",
            domid = 'select-columns',
            )
        filter_active_filters = ActiveFilters(
            page  = page,
            query = sq_resource,
            title = "Active Filters",
            )
        filters_area = Stack(
            page                = page,
            title               = 'Filter Resources',
            domid               = 'filters',
            sons                = [filter_query_editor, 
                                   filter_active_filters],
            togglable           = True,
            toggled             = 'persistent',
            outline_complete    = True, 
        )
        main_stack.insert (filters_area)

        # --------------------------------------------------------------------------
        # RESOURCES
        # the resources part is made of a Tabs (Geographic, List), 

        resources_as_gmap = GoogleMap(
            page       = page,
            title      = 'Geographic view',
            domid      = 'resources-map',
            # tab's sons preferably turn this off
            togglable  = False,
            query      = sq_resource,
            query_all  = query_resource_all,
            # this key is the one issued by google
            googlemap_api_key = ConfigEngine().googlemap_api_key(),
            # the key to use at init-time
            init_key   = main_query_init_key,
            checkboxes = True,
            # center on Paris
            latitude   = 49.,
            longitude  = 9,
            zoom       = 4,
        )

        resources_as_3dmap = SensLabMap(
            page       = page,
            title      = '3D Map',
            domid      = 'senslabmap',
            query      = sq_resource,
            query_all  = query_resource_all,
        )

        resources_as_list = QueryTable( 
            page       = page,
            domid      = 'resources-list',
            title      = 'List view',
            # this is the query at the core of the slice list
            query      = sq_resource,
            query_all  = query_resource_all,
            init_key     = main_query_init_key,
            checkboxes = True,
            datatables_options = { 
                'iDisplayLength': 25,
                'bLengthChange' : True,
                'bAutoWidth'    : True,
                },
            )

        if insert_grid:
            resources_as_grid = QueryGrid( 
                page       = page,
                domid      = 'resources-grid',
                title      = 'Grid view',
                # this is the query at the core of the slice list
                query      = sq_resource,
                query_all  = query_resource_all,
                init_key     = main_query_init_key,
                checkboxes = True,
                )

        

        #if do_query_leases:
        #    resources_as_scheduler = Scheduler(

        #        page        = page,
        #        title       = 'Scheduler',
        #        domid       = 'scheduler',
        #        query       = sq_resource,
        #        query_all_resources = query_resource_all,
        #        query_lease = sq_lease,

        #        )

        resources_as_scheduler2 = Scheduler2( 
            page       = page,
            domid      = 'scheduler',
            title      = 'Scheduler',
            # this is the query at the core of the slice list
            query = sq_resource,
            query_all_resources = query_resource_all,
            query_lease = sq_lease,
            )

       # with the new 'Filter' stuff on top, no need for anything but the querytable
        resources_as_list_area = resources_as_list 

        resources_sons = [
            resources_as_gmap, 
            resources_as_3dmap,
            resources_as_scheduler2,
            resources_as_list_area,
            ] if do_query_leases else [
            resources_as_gmap, 
            resources_as_3dmap,
            resources_as_list_area,
            resources_as_scheduler2,
            ]
        if insert_grid:
            resources_sons.append(resources_as_grid)

        resources_area = Tabs ( page=page, 
                                domid="resources",
                                togglable=True,
                                title="Resources",
                                outline_complete=True,
                                sons= resources_sons,

                                active_domid = 'scheduler',
                                persistent_active=True,
                                )
        main_stack.insert (resources_area)

        # --------------------------------------------------------------------------
        # USERS
    
        if do_query_users and query_user_all is not None:
            tab_users = Tabs(
                page                = page,
                domid               = 'users',
                outline_complete    = True,
                togglable           = True,
                title               = 'Users',
                active_domid        = 'users-list',
                )
            main_stack.insert(tab_users)
    
            tab_users.insert(QueryTable( 
                page        = page,
                title       = 'Users List',
                domid       = 'users-list',
                # tab's sons preferably turn this off
                togglable   = False,
                # this is the query at the core of the slice list
                query       = sq_user,
                query_all  = query_user_all,
                checkboxes  = True,
                datatables_options = { 
                    'iDisplayLength' : 25,
                    'bLengthChange'  : True,
                    'bAutoWidth'     : True,
                },
            ))

# DEMO    
        # --------------------------------------------------------------------------
        # MEASUREMENTS
        measurements_stats_cpu = SliceStat(
            title = "CPU Usage",
            domid = 'resources-stats-cpu',
            page  = page,
            stats = 'slice',
            key   = 'hrn',
            query = 'none',
            slicename = slicename,
            o = 'cpu'
        )
        
        measurements_stats_mem = SliceStat(
            title = "Memory Usage",
            domid = 'resources-stats-mem',
            page  = page,
            stats = 'slice',
            key   = 'hrn',
            query = 'none',
            slicename = slicename,
            o = 'mem'
        )
        
        measurements_stats_asb = SliceStat(
            title = "Traffic Sent",
            domid = 'resources-stats-asb',
            page  = page,
            stats = 'slice',
            key   = 'hrn',
            query = 'none',
            slicename = slicename,
            o = 'asb'
        )
        
        measurements_stats_arb = SliceStat(
            title = "Traffic Received",
            domid = 'resources-stats-arb',
            page  = page,
            stats = 'slice',
            key   = 'hrn',
            query = 'none',
            slicename = slicename,
            o = 'arb'
        )

        tab_measurements = Tabs ( page=page,
                                domid = "measurements",
                                togglable = True,
                                toggled = 'persistent',
                                title = "Measurements",
                                outline_complete=True,
                                sons = [ measurements_stats_cpu, measurements_stats_mem, measurements_stats_asb, measurements_stats_arb ],
                                active_domid = 'resources-stats-cpu',
                                persistent_active = True,
                                )
        main_stack.insert (tab_measurements)
        
#        tab_measurements = Tabs (
#            page                = page,
#            active_domid        = 'measurements-list',
#            outline_complete    = True,
#            togglable           = True,
#            title               = 'Measurements',
#            domid               = 'measurements',
#        )
#        main_stack.insert(tab_measurements)
#    
#        tab_measurements.insert(QueryTable( 
#            page        = page,
#            title       = 'Measurements',
#            domid       = 'measurements-list',
#            # tab's sons preferably turn this off
#            togglable   = False,
#            # this is the query at the core of the slice list
#            query       = sq_measurement,
#            # do NOT set checkboxes to False
#            # this table being otherwise empty, it just does not fly with dataTables
#            checkboxes  = True,
#            datatables_options = { 
#                'iDisplayLength' : 25,
#                'bLengthChange'  : True,
#                'bAutoWidth'     : True,
#            },
#        ))
#    
#        # --------------------------------------------------------------------------
#        # MESSAGES (we use transient=False for now)
        if insert_messages:
            main_stack.insert(Messages(
                    page   = page,
                    title  = "Runtime messages for slice %s"%slicename,
                    domid  = "msgs-pre",
                    levels = "ALL",
                    # plain messages are probably less nice for production but more reliable for development for now
                    transient = False,
                    # these make sense only in non-transient mode..
                    togglable = True,
                    toggled = 'persistent',
                    outline_complete = True,
                    ))
    
        # variables that will get passed to the view-unfold1.html template
        template_env = {}
        
        # define 'unfold_main' to the template engine - the main contents
        template_env [ 'unfold_main' ] = main_stack.render(request)
    
        # more general variables expected in the template
        template_env [ 'title' ] = '%(slicename)s'%locals()
        # the menu items on the top
        template_env [ 'topmenu_items' ] = topmenu_items_live('Slice', page) 
        # so we can sho who is logged
        template_env [ 'username' ] = the_user (request) 
    
        # don't forget to run the requests
        page.expose_js_metadata()
        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        template_env.update(page.prelude_env())

        return render_to_response ('view-unfold1.html',template_env,
                                   context_instance=RequestContext(request))
    def get_or_post  (self, request, method):
        # Using cache manifold-tables to get the list of authorities faster
        authorities_query = Query.get('authority').select('name', 'authority_hrn')
        authorities = execute_admin_query(request, authorities_query)
        if authorities is not None:
            authorities = sorted(authorities)

        user_query  = Query().get('local:user').select('email')
        user_email = execute_query(self.request, user_query)
        self.user_email = user_email[0].get('email')


        account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
        account_details = execute_query(self.request, account_query)

        platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
        platform_details = execute_query(self.request, platform_query)

        # getting user_hrn from local:account
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail['platform_id']:
                    # taking user_hrn only from myslice account
                    # NOTE: we should later handle accounts filter_by auth_type= managed OR user
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        user_hrn = account_config.get('user_hrn','N/A')
    
        #user_query  = Query().get('user').select('user_hrn').filter_by('user_hrn','==','$user_hrn')
        #user_hrn = execute_query(self.request, user_query)
        #self.user_hrn = user_hrn[0].get('user_hrn')
        
        
        page = Page(request)
        page.add_css_files ( [ "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )

        if method == 'POST':
            self.errors = []
    
            # The form has been submitted
            slice_name = request.POST.get('slice_name', '')
            authority_hrn = request.POST.get('authority_hrn', '')
            number_of_nodes = request.POST.get('number_of_nodes', '')
            purpose = request.POST.get('purpose', '')
            email = self.user_email
            #user_hrn = user_hrn
            cc_myself = True
            
            if (authority_hrn is None or authority_hrn == ''):
                self.errors.append('Please, select an authority')
            # What kind of slice name is valid?
            if (slice_name is None or slice_name == ''):
                self.errors.append('Slice Name is mandatory')
    
            if (purpose is None or purpose == ''):
                self.errors.append('Purpose is mandatory')
    
            if not self.errors:
                ctx = {
                    'email': email,
                    'slice_name': slice_name,
                    'authority_hrn': authority_hrn,
                    'number_of_nodes': number_of_nodes,
                    'purpose': purpose,
                }            
                s = PendingSlice(
                    slice_name      = slice_name,
                    user_hrn        = user_hrn,
                    authority_hrn   = authority_hrn,
                    number_of_nodes = number_of_nodes,
                    purpose         = purpose
                )
                s.save()
    
                # The recipients are the PI of the authority
                recipients = authority_get_pi_emails(request, authority_hrn)
    
                #if cc_myself:
                recipients.append('*****@*****.**')
                msg = render_to_string('slice-request-email.txt', ctx)
                #print "email, msg, email, recipients", email , msg, email, recipients 
                send_mail("Onelab user %s requested a slice"%email , msg, email, recipients)
    
                return render(request,'slice-request-ack-view.html') # Redirect after POST
     
        template_env = {
          'topmenu_items': topmenu_items_live('Request a slice', page),
          'errors': self.errors,
          'slice_name': request.POST.get('slice_name', ''),
          'authority_hrn': request.POST.get('authority_hrn', ''),
          'number_of_nodes': request.POST.get('number_of_nodes', ''),
          'purpose': request.POST.get('purpose', ''),
          'email': self.user_email,
          'user_hrn': user_hrn,
          'cc_myself': True,
          'authorities': authorities,
        }
        template_env.update(page.prelude_env ())
        return render(request, 'slicerequest_view.html',template_env)
Example #20
0
                    self.template_name = 'slice-request-done-view.html'
                else:
                    # Otherwise a request is sent to the PI
                    create_pending_slice(request, slice_request, user_email)
                    self.template_name = 'slice-request-ack-view.html'
                
                # log user activity
                activity.user.slice(request)
                return render_to_response(self.template, {'theme': self.theme, 'request':request}, context_instance=RequestContext(request))
                #return render(request, self.template, {'theme': self.theme}) # Redirect after POST
        else:
            slice_request = {}

        template_env = {
            'username': request.user.email,
            'topmenu_items': topmenu_items_live('Request a slice', page),
            'errors': errors,
            'slice_name': slice_name,
            #'purpose': purpose,
            'email': user_email,
            'user_hrn': user_hrn,
            #'url': url,
            'pi': pi,
            'authority_name': authority_name,        
            'authority_hrn': user_authority,        
            'cc_myself': True,
            'authorities': authorities,
            'theme': self.theme,
            'section': "Slice request",
            'request': request,
        }
Example #21
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)
        #page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
        #page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
        if self.request.is_secure():
            current_site = 'https://'
        else:
            current_site = 'http://'
        current_site += self.request.META['HTTP_HOST']

        for key, value in kwargs.iteritems():
            if key == "hash_code":
                hash_code = value

        #if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):
        if PendingUser.objects.filter(email_hash__iexact=hash_code):
            activation = 'success'
            pending_users = PendingUser.objects.filter(
                email_hash__iexact=hash_code)
            pending_user = pending_users[0]

            # AUTO VALIDATION of PLE enabled users (only for OneLab Portal)
            if self.theme == "onelab":
                # Auto-Validation of pending user, which is enabled in a trusted SFA Registry (example: PLE)
                # We could check in the Registry based on email, but it takes too long
                # as we currently need to do a Resolve on each user_hrn of the Registry in order to get its email
                # TODO in SFA XXX We need a Resolve based on email
                # TODO maybe we can use MyPLC API for PLE

                # by default user is not in PLE
                ple_user_enabled = False

                if pending_user:
                    # Auto Validation
                    if self.is_ple_enabled(pending_user):
                        pending_user_request = make_request_user(pending_user)
                        # Create user in SFA and Update in Manifold
                        create_user(self.request,
                                    pending_user_request,
                                    namespace='myslice',
                                    as_admin=True)
                        # Delete pending user
                        PendingUser.objects.filter(
                            email_hash__iexact=hash_code).delete()

                        # template user auto validated
                        activation = 'validated'

            PendingUser.objects.filter(email_hash__iexact=hash_code).update(
                status='True')
            u = {}
            u['first_name'] = pending_user.first_name
            u['last_name'] = pending_user.last_name
            u['authority_hrn'] = pending_user.authority_hrn
            u['email'] = pending_user.email
            u['user_hrn'] = pending_user.user_hrn
            u['pi'] = pending_user.pi
            u['public_key'] = pending_user.public_key
            u['current_site'] = current_site

            send_email_to_pis(self.request, u, 'user')
        else:
            activation = 'failed'

        context = super(ActivateEmailView, self).get_context_data(**kwargs)
        context['activation_status'] = activation
        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('My Account', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        #context['first_name'] = first_name
        #context['last_name'] = last_name
        #context['authority_hrn'] = authority_hrn
        #context['email'] = email
        #context['user_hrn'] = user_hrn
        context['theme'] = self.theme
        #        context ['firstname'] = config['firstname']
        prelude_env = page.prelude_env()
        context.update(prelude_env)
        return context
Example #22
0
    def get_or_post(self, request, method):
        errors = []
        # List authorities already in the Registry in order to avoid duplicates
        # Using cache manifold-tables to get the list of authorities faster
        authorities_query = Query.get("authority").select("name", "authority_hrn")
        authorities = execute_admin_query(request, authorities_query)
        if authorities is not None:
            authorities = sorted(authorities)
        root_authorities = sorted([a for a in authorities if "." not in a["authority_hrn"]])

        page = Page(request)
        page.add_js_files(["js/jquery.validate.js", "js/join.js"])
        page.add_css_files(["css/onelab.css", "css/registration.css"])
        page.add_css_files(["http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"])

        if method == "POST":
            # xxx tocheck - if authorities is empty, it's no use anyway
            # (users won't be able to validate the form anyway)

            # List local users in Manifold DB in order ot avoid duplicates
            user_query = Query().get("local:user").select("user_id", "email")
            list_users = execute_admin_query(self.request, user_query)

            reg_root_authority_hrn = request.POST.get("root_authority_hrn", "").lower()

            reg_site_name = request.POST.get("site_name", "")
            reg_site_authority = request.POST.get("site_authority", "").lower()
            reg_site_abbreviated_name = request.POST.get("site_abbreviated_name", "")
            reg_site_url = request.POST.get("site_url", "")
            reg_site_latitude = request.POST.get("site_latitude", "")
            reg_site_longitude = request.POST.get("site_longitude", "")

            reg_fname = request.POST.get("pi_first_name", "")
            reg_lname = request.POST.get("pi_last_name", "")
            reg_auth = reg_root_authority_hrn + "." + reg_site_authority
            reg_email = request.POST.get("pi_email", "").lower()
            reg_phone = request.POST.get("pi_phone", "")
            # prepare user_hrn
            split_email = reg_email.split("@")[0]
            split_email = split_email.replace(".", "_")
            user_hrn = reg_auth + "." + split_email + str(randint(1, 1000000))

            UserModel = get_user_model()

            reg_address_line1 = request.POST.get("address_line1", "")
            reg_address_line2 = request.POST.get("address_line2", "")
            reg_address_line3 = request.POST.get("address_line3", "")
            reg_address_city = request.POST.get("address_city", "")
            reg_address_postalcode = request.POST.get("address_postalcode", "")
            reg_address_state = request.POST.get("address_state", "")
            reg_address_country = request.POST.get("address_country", "")

            # POST value validation
            if re.search(r"^[\w+\s.@+-]+$", reg_fname) == None:
                errors.append("First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.")
            if re.search(r"^[\w+\s.@+-]+$", reg_lname) == None:
                errors.append("Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.")
            if re.search(r"^\w+$", reg_site_authority) == None:
                errors.append("Site Authority may contain only letters or numbers.")
            # checking in django_db !!
            if PendingUser.objects.filter(email__iexact=reg_email):
                errors.append("Email is pending for validation. Please provide a new email address.")
            if PendingAuthority.objects.filter(site_authority__iexact=reg_auth):
                errors.append("This site is pending for validation.")
            if PendingAuthority.objects.filter(site_name__iexact=reg_site_name):
                errors.append("This site is pending for validation.")

            if UserModel._default_manager.filter(email__iexact=reg_email):
                errors.append("This email is not usable. Please contact the administrator or try with another email.")
            for user_detail in list_users:
                if user_detail["email"] == reg_email:
                    errors.append("Email already registered in Manifold. Please provide a new email address.")

            # XXX TODO: Factorize with portal/accountview.py
            #            if 'generate' in request.POST['question']:
            from Crypto.PublicKey import RSA

            private = RSA.generate(1024)
            private_key = json.dumps(private.exportKey())
            public = private.publickey()
            public_key = json.dumps(public.exportKey(format="OpenSSH"))

            # Saving to DB
            account_config = (
                '{"user_public_key":'
                + public_key
                + ', "user_private_key":'
                + private_key
                + ', "user_hrn":"'
                + user_hrn
                + '"}'
            )
            auth_type = "managed"
            public_key = public_key.replace('"', "")

            if not errors:
                reg_password = request.POST["pi_password"]
                a = PendingAuthority(
                    site_name=reg_site_name,
                    site_authority=reg_root_authority_hrn + "." + reg_site_authority,
                    site_abbreviated_name=reg_site_abbreviated_name,
                    site_url=reg_site_url,
                    site_latitude=reg_site_latitude,
                    site_longitude=reg_site_longitude,
                    address_line1=reg_address_line1,
                    address_line2=reg_address_line2,
                    address_line3=reg_address_line3,
                    address_city=reg_address_city,
                    address_postalcode=reg_address_postalcode,
                    address_state=reg_address_state,
                    address_country=reg_address_country,
                    authority_hrn=reg_root_authority_hrn,
                )
                a.save()

                reg_password = request.POST["pi_password"]
                b = PendingUser(
                    first_name=reg_fname,
                    last_name=reg_lname,
                    authority_hrn=reg_auth,
                    email=reg_email,
                    password=reg_password,
                    keypair=account_config,
                    pi=reg_auth,
                )
                b.save()

                # saves the user to django auth_user table [needed for password reset]
                user = User.objects.create_user(reg_email, reg_email, reg_password)

                # creating user to manifold local:user
                user_config = (
                    '{"firstname":"' + reg_fname + '", "lastname":"' + reg_lname + '", "authority":"' + reg_auth + '"}'
                )
                user_params = {"email": reg_email, "password": reg_password, "config": user_config, "status": 1}
                manifold_add_user(request, user_params)
                # creating local:account in manifold
                user_id = user_detail["user_id"] + 1  # the user_id for the newly created user in local:user
                account_params = {
                    "platform_id": 5,
                    "user_id": user_id,
                    "auth_type": auth_type,
                    "config": account_config,
                }
                manifold_add_account(request, account_params)

                # Send email
                ctx = {
                    "first_name": reg_fname,
                    "last_name": reg_lname,
                    "authority_hrn": reg_auth,
                    "email": reg_email,
                    "user_hrn": user_hrn,
                    "public_key": public_key,
                }
                recipients = authority_get_pi_emails(request, reg_auth)

                # We don't need to send this email to user.
                # it's for the PI only
                # if ctx['cc_myself']:
                #    recipients.append(ctx['email'])

                msg = render_to_string("user_request_email.txt", ctx)
                send_mail(
                    "Onelab New Authority request for %s submitted" % reg_email, msg, "*****@*****.**", recipients
                )
                return render(request, "user_register_complete.html")

        template_env = {
            "topmenu_items": topmenu_items_live("join", page),
            "errors": errors,
            "pi_first_name": request.POST.get("pi_first_name", ""),
            "pi_last_name": request.POST.get("pi_last_name", ""),
            "pi_email": request.POST.get("pi_email", ""),
            "pi_phone": request.POST.get("pi_phone", ""),
            "pi_password": request.POST.get("pi_password", ""),
            "site_name": request.POST.get("site_name", ""),
            "site_authority": request.POST.get("site_authority", "").lower(),
            "site_abbreviated_name": request.POST.get("site_abbreviated_name", ""),
            "site_url": request.POST.get("site_url", ""),
            "site_latitude": request.POST.get("site_latitude", ""),
            "site_longitude": request.POST.get("site_longitude", ""),
            "address_line1": request.POST.get("address_line1", ""),
            "address_line2": request.POST.get("address_line2", ""),
            "address_line3": request.POST.get("address_line3", ""),
            "address_city": request.POST.get("address_city", ""),
            "address_postalcode": request.POST.get("address_postalcode", ""),
            "address_state": request.POST.get("address_state", ""),
            "address_country": request.POST.get("address_country", ""),
            "root_authority_hrn": request.POST.get("root_authority_hrn", "").lower(),
            "root_authorities": root_authorities,
            "authorities": authorities,
        }
        template_env.update(page.prelude_env())
        return render(request, "join_view.html", template_env)
Example #23
0
    def get (self, request, slicename='ple.inria.f14'):

        page=Page(request)
        page.expose_js_metadata()
        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]

        main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
        main_query.select(
                'slice_hrn',
                #'resource.hrn', 
                'resource.hostname', 'resource.type', 
                'resource.network_hrn',
                'lease.urn',
                'user.user_hrn',
                #'application.measurement_point.counter'
        )
        # for internal use in the querygrid plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hostname'
    
        query_resource_all = Query.get('resource').select(resource_fields)
        
        aq = AnalyzedQuery(main_query, metadata=metadata)
        page.enqueue_query(main_query, analyzed_query=aq)
        page.enqueue_query(query_resource_all)

        sq_resource    = aq.subquery('resource')

        resources_as_list = QueryGrid( 
            page       = page,
            domid      = 'resources-list',
            title      = 'List view',
            # this is the query at the core of the slice list
            query      = sq_resource,
            query_all  = query_resource_all,
            # safer to use 'hrn' as the internal unique key for this plugin
            init_key   = main_query_init_key,
            checkboxes = True,
            datatables_options = { 
                'iDisplayLength': 25,
                'bLengthChange' : True,
                'bAutoWidth'    : True,
                },
            )

        # variables that will get passed to the view-unfold1.html template
        template_env = {}
        
        # define 'unfold_main' to the template engine - the main contents
        template_env [ 'unfold_main' ] = resources_as_list.render(request)
    
        # more general variables expected in the template
        template_env [ 'title' ] = 'simple %(slicename)s'%locals()
        # the menu items on the top
        template_env [ 'topmenu_items' ] = topmenu_items_live('Slice', page) 
        # so we can sho who is logged
        template_env [ 'username' ] = the_user (request) 
    
        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        prelude_env = page.prelude_env()
        template_env.update(prelude_env)
        result=render_to_response ('view-unfold1.html',template_env,
                                   context_instance=RequestContext(request))
        return result
Example #24
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        page.add_js_files(["js/common.functions.js"])

        for key, value in kwargs.iteritems():
            logger.debug("{} = {}".format(key, value))
            if key == "platformname":
                platformname = value

        network_query  = Query().get('local:platform')\
            .filter_by('platform', '==', platformname)\
            .select('platform','platform_longname','gateway_type')
        page.enqueue_query(network_query)

        # ListResources of the platform
        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]
        resources = platformname + ':resource'
        query_resource_all = Query.get(resources).select(resource_fields)
        page.enqueue_query(query_resource_all)
        query_resource_default_fields = Query.get(resources).select(
            'hrn', 'hostname', 'type', 'country')
        page.enqueue_query(query_resource_default_fields)

        page.expose_js_metadata()
        networklist = QueryTable(
            page=page,
            title='List',
            domid='checkboxes',
            # this is the query at the core of the slice list
            query=network_query,
            query_all=network_query,
            checkboxes=False,
            datatables_options={
                'iDisplayLength': 25,
                'bLengthChange': True,
            },
        )

        #        networklist = SimpleList(
        #            title = None,
        #            page  = page,
        #            key   = 'platform',
        #            query = network_query,
        #        )
        #
        # --------------------------------------------------------------------------
        # RESOURCES
        # for internal use in the querytable plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hrn'

        # the resources part is made of a Tabs (Geographic, List),
        resources_as_gmap = GoogleMap(
            page=page,
            title='Geographic view',
            domid='resources-map',
            # tab's sons preferably turn this off
            togglable=False,
            query=query_resource_default_fields,
            query_all=query_resource_all,
            # this key is the one issued by google
            googlemap_api_key=ConfigEngine().googlemap_api_key(),
            # the key to use at init-time
            init_key=main_query_init_key,
            checkboxes=False,
            # center on Paris
            latitude=49.,
            longitude=9,
            zoom=4,
        )
        resources_as_3dmap = SensLabMap(
            page=page,
            title='3D Map',
            domid='senslabmap',
            query=query_resource_default_fields,
            query_all=query_resource_all,
        )
        resources_as_list = QueryTable(
            page=page,
            domid='resources-list',
            title='List view',
            # this is the query at the core of the slice list
            query=query_resource_default_fields,
            query_all=query_resource_all,
            init_key=main_query_init_key,
            checkboxes=False,
            datatables_options={
                'iDisplayLength': 25,
                'bLengthChange': True,
                'bAutoWidth': True,
            },
        )
        resources_sons = [
            resources_as_gmap,
            resources_as_3dmap,
            resources_as_list,
        ]
        resources_area = Tabs(
            page=page,
            domid="resources",
            togglable=True,
            title="Resources",
            outline_complete=True,
            sons=resources_sons,
            active_domid='resources-map',
            persistent_active=True,
        )

        context = super(PlatformView, self).get_context_data(**kwargs)
        context['person'] = self.request.user
        context['networks'] = networklist.render(self.request)
        context['resources'] = resources_area.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Platforms', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        context['theme'] = self.theme
        context.update(page.prelude_env())

        return context
Example #25
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        page.add_js_files  ( [ "js/common.functions.js" ] )
        #platform_query  = Query().get('local:platform').filter_by('disabled', '==', '0').select('platform','platform_longname','gateway_type')
        #platform_query  = Query().get('local:platform').select('platform','platform_longname','gateway_type')
        email_list = []
        status_list = []
        authority_list = []
        config={}

        user_query  = Query().get('local:user').select('email','status','config')
        user_details = execute_admin_query(self.request, user_query)

        for user in user_details:
            # get email
            email_list.append(user['email'])
            # get status
            if user['status'] == 0:
                user_status = 'Disabled'
            elif user['status'] == 1:
                user_status = 'Validation Pending'
            elif user['status'] == 2:
                user_status = 'Enabled'
            else:
                user_status = 'N/A'

            status_list.append(user_status)
            #get authority
            #if user['config']:
            user_config = json.loads(user['config'])
            user_authority = user_config.get('authority','N/A')
            authority_list.append(user_authority)
    
        user_list = [{'email': t[0], 'status': t[1], 'authority':t[2]}
            for t in zip(email_list, status_list, authority_list)]

            
        #page.enqueue_query(user_query)

        #page.expose_js_metadata()
        #userlist = QueryTable(
        #    page  = page,
        #    title = 'List',
        #    domid = 'checkboxes',
        #    # this is the query at the core of the slice list
        #    query = user_query,
        #    query_all = user_query,
        #    checkboxes = False,
        #    init_key   = 'user',
        #    datatables_options = { 
        #        'iDisplayLength': 10,
        #        'bLengthChange' : True,
        #        'bAutoWidth'    : True,
        #        },
        #)

        context = super(UsersView, self).get_context_data(**kwargs)
        context['person']   = self.request.user
        context['user_list'] = user_list

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Users in MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Users', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context.update(page.prelude_env())

        context['layout_1_or_2']="layout-unfold2.html" if not context['username'] else "layout-unfold1.html"

        return context
Example #26
0
    def get_context_data(self, **kwargs):
        page = Page(self.request)
        
        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
                
        resource_query  = Query().get('resource')\
            .filter_by('urn', '==', resource_urn)\
            .select('hostname','type','hrn','urn', 'latitude', 'longitude', 'country')
        page.enqueue_query(resource_query)

        page.expose_js_metadata()

        resourcelist = QueryTable(
            page  = page,
            title = 'List',
            domid = 'checkboxes',
            # this is the query at the core of the slice list
            query = resource_query,
            query_all = resource_query,
            checkboxes = False,
            datatables_options = {
            'iDisplayLength' : 25,
            'bLengthChange'  : True,
            },
        )
        resource_as_map = GoogleMap(
            page       = page,
            title      = 'Geographic view',
            domid      = 'resources-map',
            # tab's sons preferably turn this off
            togglable  = True,
            query      = resource_query,
            query_all  = resource_query,
            googlemap_api_key = ConfigEngine().googlemap_api_key(),
            checkboxes = False,
            # center on Paris
            #latitude   = 49.,
            #longitude  = 9,
            #zoom       = 4,
        )
#        resourcelist = SimpleList(
#            title = None,
#            page  = page,
#            key   = 'hrn',
#            query = resource_query,
#        )

        resource_stats = SliceStat(
            title = None,
            page  = page,
            stats = 'node',
            key   = 'hrn',
            query = resource_query
        )

        context = super(ResourceView, self).get_context_data(**kwargs)
        context['person']   = self.request.user
        context['resource'] = resourcelist.render(self.request)
        context['resource_as_map'] = resource_as_map.render(self.request)
        context['resource_stats'] = resource_stats.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Information about a resource'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live(None, page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context.update(page.prelude_env())

        return context
Example #27
0
    def get(self, request, slicename='ple.inria.f14'):

        page = Page(request)
        page.expose_js_metadata()
        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]

        main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
        main_query.select(
            'slice_hrn',
            #'resource.hrn',
            'resource.hostname',
            'resource.type',
            'resource.network_hrn',
            'lease.urn',
            'user.user_hrn',
            #'application.measurement_point.counter'
        )
        # for internal use in the querygrid plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hostname'

        query_resource_all = Query.get('resource').select(resource_fields)

        aq = AnalyzedQuery(main_query, metadata=metadata)
        page.enqueue_query(main_query, analyzed_query=aq)
        page.enqueue_query(query_resource_all)

        sq_resource = aq.subquery('resource')

        resources_as_list = QueryGrid(
            page=page,
            domid='resources-list',
            title='List view',
            # this is the query at the core of the slice list
            query=sq_resource,
            query_all=query_resource_all,
            # safer to use 'hrn' as the internal unique key for this plugin
            init_key=main_query_init_key,
            checkboxes=True,
            datatables_options={
                'iDisplayLength': 25,
                'bLengthChange': True,
                'bAutoWidth': True,
            },
        )

        # variables that will get passed to the view-unfold1.html template
        template_env = {}

        # define 'unfold_main' to the template engine - the main contents
        template_env['unfold_main'] = resources_as_list.render(request)

        # more general variables expected in the template
        template_env['title'] = 'simple %(slicename)s' % locals()
        # the menu items on the top
        template_env['topmenu_items'] = topmenu_items_live('Slice', page)
        # so we can sho who is logged
        template_env['username'] = the_user(request)

        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        prelude_env = page.prelude_env()
        template_env.update(prelude_env)
        result = render_to_response('view-unfold1.html',
                                    template_env,
                                    context_instance=RequestContext(request))
        return result
Example #28
0
def test_plugin_view(request):

    page = Page(request)

    page.expose_js_metadata()

    # variables that will get passed to this template
    template_env = {}

    slicename = 'ple.inria.heartbeat'
    main_query = Query.get('resource').filter_by(
        'slice_hrn', '=',
        slicename).select(['network', 'type', 'hrn', 'hostname', 'sliver'])
    # without an querytable, this would use use : run_it=False as nothing would listen to the results
    page.enqueue_query(
        main_query,  # run_it=False
    )

    main_plugin = \
        Stack (
        page=page,
        title='thestack',
        togglable=True,
        domid='stack',
        sons=[ \
        # make sure the 2 things work together

            Messages (
                    page=page,
                    title="Transient Runtime messages",
                    domid="messages-transient",
                    levels='ALL',
                    ),
            QueryTable (
                    page=page,
                    title="Slice %s - checkboxes"%slicename,
                    query=main_query,
                    domid="querytable",
                    checkboxes=True,
                    togglable=True,
                    ),
            Messages (
                    page=page,
                    title="Inline Runtime messages",
                    domid="messages",
                    levels='ALL',
                    togglable=True,
                    transient=False,
                    ),
            Raw (
                    page=page,
                    title="issue messages",
                    togglable=True,
                    html="""
<input type="button" id="bouton" value="Click me" />
""",
                    ),
            ])

    page.add_js_chunks("""
function issue_debug() {console.log("issue_debug");messages.debug("issue_debug");};
$(function(){$("#bouton").click(issue_debug);});
""")

    # define 'unfold_main' to the template engine
    template_env['unfold_main'] = main_plugin.render(request)

    # more general variables expected in the template
    template_env['title'] = 'Single Plugin View'
    template_env['topmenu_items'] = topmenu_items_live('plugin', page)
    template_env['username'] = the_user(request)

    # the prelude object in page contains a summary of the requirements() for all plugins
    # define {js,css}_{files,chunks}
    prelude_env = page.prelude_env()
    template_env.update(prelude_env)
    return render_to_response('view-unfold1.html',
                              template_env,
                              context_instance=RequestContext(request))
Example #29
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)
        page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
        page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )


        user_query  = Query().get('local:user').select('config','email','status')
        user_details = execute_query(self.request, user_query)
        
        # not always found in user_details...
        config={}
        for user_detail in user_details:
            # different significations of user_status
            if user_detail['status'] == 0: 
                user_status = 'Disabled'
            elif user_detail['status'] == 1:
                user_status = 'Validation Pending'
            elif user_detail['status'] == 2:
                user_status = 'Enabled'
            else:
                user_status = 'N/A'
            #email = user_detail['email']
            if user_detail['config']:
                config = json.loads(user_detail['config'])

        platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
        account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
        platform_details = execute_query(self.request, platform_query)
        account_details = execute_query(self.request, account_query)
       
        # initial assignment needed for users having account.config = {} 
        platform_name = ''
        account_type = ''
        account_usr_hrn = ''
        account_pub_key = ''
        account_priv_key = ''
        account_reference = ''
        my_users = ''
        my_slices = ''
        my_auths = ''
        ref_acc_list = ''
        principal_acc_list = ''
        user_status_list = []
        platform_name_list = []
        platform_name_secondary_list = []
        platform_access_list = []
        platform_no_access_list = []
        total_platform_list = []
        account_type_list = []
        account_type_secondary_list = []
        account_reference_list = []
        delegation_type_list = []
        user_cred_exp_list = []
        slice_list = []
        auth_list = []
        slice_cred_exp_list = []
        auth_cred_exp_list = []
        usr_hrn_list = []
        pub_key_list = []
          
        for platform_detail in platform_details:
            if 'sfa' in platform_detail['gateway_type']:
                total_platform = platform_detail['platform']
                total_platform_list.append(total_platform)
                
            for account_detail in account_details:
                if platform_detail['platform_id'] == account_detail['platform_id']:
                    platform_name = platform_detail['platform']
                    account_config = json.loads(account_detail['config'])
                    account_usr_hrn = account_config.get('user_hrn','N/A')
                    account_pub_key = account_config.get('user_public_key','N/A')
                    account_reference = account_config.get ('reference_platform','N/A')
                    # credentials of myslice platform
                    if 'myslice' in platform_detail['platform']:
                        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)
                                # get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>', value)
                                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)
                                #get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>', value)
                                if exp_date:
                                    exp_date = exp_date.group(1)
                                    auth_cred_exp_list.append(exp_date)

                            my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
                                for t in zip(auth_list, auth_cred_exp_list)]


                    # for reference accounts
                    if 'reference' in account_detail['auth_type']:
                        account_type = 'Reference'
                        delegation = 'N/A'
                        platform_name_secondary_list.append(platform_name)
                        account_type_secondary_list.append(account_type)
                        account_reference_list.append(account_reference)
                        ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]} 
                            for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
                       
                    elif 'managed' in account_detail['auth_type']:
                        account_type = 'Principal'
                        delegation = 'Automatic'
                    else:
                        account_type = 'Principal'
                        delegation = 'Manual'
                    # for principal (auth_type=user/managed) accounts
                    if 'reference' not in account_detail['auth_type']:
                        platform_name_list.append(platform_name)
                        account_type_list.append(account_type)
                        delegation_type_list.append(delegation)
                        usr_hrn_list.append(account_usr_hrn)
                        pub_key_list.append(account_pub_key)
                        user_status_list.append(user_status)
                        # combining 5 lists into 1 [to render in the template] 
                        principal_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'usr_hrn':t[3], 'usr_pubkey':t[4], 'user_status':t[5],} 
                            for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
                    # to hide private key row if it doesn't exist    
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        account_priv_key = account_config.get('user_private_key','N/A')
                    if 'sfa' in platform_detail['gateway_type']:
                        platform_access = platform_detail['platform']
                        platform_access_list.append(platform_access)
       
        # Removing the platform which already has access
        for platform in platform_access_list:
            total_platform_list.remove(platform)
        # we could use zip. this one is used if columns have unequal rows 
        platform_list = [{'platform_no_access': t[0]}
            for t in itertools.izip_longest(total_platform_list)]

        context = super(AccountView, self).get_context_data(**kwargs)
        context['principal_acc'] = principal_acc_list
        context['ref_acc'] = ref_acc_list
        context['platform_list'] = platform_list
        context['my_users'] = my_users
        context['my_slices'] = my_slices
        context['my_auths'] = my_auths
        context['user_status'] = user_status
        context['person']   = self.request.user
        context['firstname'] = config.get('firstname',"?")
        context['lastname'] = config.get('lastname',"?")
        context['fullname'] = context['firstname'] +' '+ context['lastname']
        context['authority'] = config.get('authority',"Unknown Authority")
        context['user_private_key'] = account_priv_key
        
        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Platforms connected to MySlice'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('My Account', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
#        context ['firstname'] = config['firstname']
        prelude_env = page.prelude_env()
        context.update(prelude_env)
        return context
Example #30
0
class JoinView(FreeAccessView, ThemeView):
    def post(self, request):
        return self.get_or_post(request, 'POST')

    def get(self, request):
        return self.get_or_post(request, 'GET')

    def get_or_post(self, request, method):
        errors = []
        # List authorities already in the Registry in order to avoid duplicates
        # Using cache manifold-tables to get the list of authorities faster
        authorities_query = Query.get('authority').select(
            'name', 'authority_hrn')
        authorities = execute_admin_query(request, authorities_query)
        if authorities is not None:
            authorities = sorted(authorities)
        root_authorities = sorted(
            [a for a in authorities if '.' not in a['authority_hrn']])

        page = Page(request)
        page.add_js_files(
            ["js/jquery.validate.js", "js/join.js", "js/jquery.qtip.min.js"])
        page.add_css_files([
            "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css"
        ])
        page.add_css_files([
            "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
        ])

        if method == 'POST':
            # xxx tocheck - if authorities is empty, it's no use anyway
            # (users won't be able to validate the form anyway)

            # List local users in Manifold DB in order ot avoid duplicates
            user_query = Query().get('local:user').select('user_id', 'email')
            list_users = execute_admin_query(self.request, user_query)

            reg_root_authority_hrn = request.POST.get('root_authority_hrn',
                                                      '').lower()

            reg_site_name = request.POST.get('site_name', '')
            reg_site_authority = request.POST.get('site_authority', '').lower()
            reg_site_abbreviated_name = request.POST.get(
                'site_abbreviated_name', '').lower()
            reg_site_url = request.POST.get('site_url', '')
            reg_site_latitude = request.POST.get('site_latitude', '')
            reg_site_longitude = request.POST.get('site_longitude', '')

            reg_fname = request.POST.get('pi_first_name', '')
            reg_lname = request.POST.get('pi_last_name', '')
            reg_auth = 'onelab.' + reg_site_abbreviated_name
            reg_email = request.POST.get('pi_email', '').lower()
            reg_phone = request.POST.get('pi_phone', '')
            #prepare user_hrn
            split_email = reg_email.split("@")[0]
            split_email = split_email.replace(".", "_")
            # Replace + by _ => more convenient for testing and validate with a real email
            split_email = split_email.replace("+", "_")
            user_hrn = reg_auth + '.' + split_email

            UserModel = get_user_model()

            reg_address_line1 = request.POST.get('address_line1', '')
            reg_address_line2 = request.POST.get('address_line2', '')
            reg_address_line3 = request.POST.get('address_line3', '')
            reg_address_city = request.POST.get('address_city', '')
            reg_address_postalcode = request.POST.get('address_postalcode', '')
            reg_address_state = request.POST.get('address_state', '')
            reg_address_country = request.POST.get('address_country', '')

            #POST value validation
            if (re.search(r'^[\w+\s.@+-]+$', reg_fname) == None):
                errors.append(
                    'First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.'
                )
            if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
                errors.append(
                    'Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.'
                )
            if (re.search(r'^[A-Za-z0-9_ ]*$', reg_site_name) == None):
                errors.append(
                    'Name of organization  may contain only letters, numbers, and underscore.'
                )
            if (re.search(r'^[A-Za-z ]*$', reg_address_city) == None):
                errors.append('City may contain only letters.')
            if (re.search(r'^[A-Za-z ]*$', reg_address_country) == None):
                errors.append('Country may contain only letters.')
            if (re.search(r'^[A-Za-z0-9]*$',
                          reg_site_abbreviated_name) == None):
                errors.append(
                    'Shortname  may contain only letters and numbers')
            if (re.search(r'^[0-9]*$', reg_phone) == None):
                errors.append('Phone number may contain only numbers.')
            #if (re.search(r'^\w+$', reg_site_authority) == None):
            #    errors.append('Site Authority may contain only letters or numbers.')
            # checking in django_db !!
            if PendingUser.objects.filter(email__iexact=reg_email):
                errors.append(
                    'Email is pending for validation. Please provide a new email address.'
                )
            if PendingAuthority.objects.filter(
                    site_abbreviated_name__iexact=reg_site_abbreviated_name):
                errors.append('This site is pending for validation.')
            #if PendingAuthority.objects.filter(site_name__iexact=reg_site_name):
            #    errors.append('This site is pending for validation.')

            if UserModel._default_manager.filter(email__iexact=reg_email):
                errors.append(
                    'This email is not usable. Please contact the administrator or try with another email.'
                )
            for user_detail in list_users:
                if user_detail['email'] == reg_email:
                    errors.append(
                        'Email already registered in Manifold. Please provide a new email address.'
                    )

# XXX TODO: Factorize with portal/accountview.py
# XXX TODO: Factorize with portal/registrationview.py
# XXX TODO: Factorize with portal/joinview.py
#            if 'generate' in request.POST['question']:
            from Crypto.PublicKey import RSA
            private = RSA.generate(1024)
            private_key = private.exportKey()
            public_key = private.publickey().exportKey(format='OpenSSH')
            # Saving to DB
            auth_type = 'managed'

            if not errors:
                reg_password = request.POST['pi_password']
                a = PendingAuthority(
                    site_name=reg_site_name,
                    site_authority=reg_auth,
                    site_abbreviated_name=reg_site_abbreviated_name,
                    site_url=reg_site_url,
                    site_latitude=reg_site_latitude,
                    site_longitude=reg_site_longitude,
                    address_line1=
                    reg_email,  # XXX field name must be renamed. Email needed 4 rejection email.
                    address_line2=reg_address_line2,
                    address_line3=reg_address_line3,
                    address_city=reg_address_city,
                    address_postalcode=reg_address_postalcode,
                    address_state=reg_address_state,
                    address_country=reg_address_country,
                    authority_hrn=reg_root_authority_hrn,
                )
                a.save()

                reg_password = request.POST['pi_password']
                salt = randint(1, 100000)

                if request.is_secure():
                    current_site = 'https://'
                else:
                    current_site = 'http://'
                current_site += request.META['HTTP_HOST']

                email_hash = md5(str(salt) + reg_email).hexdigest()
                user_request = {
                    'first_name':
                    reg_fname,
                    'last_name':
                    reg_lname,
                    'organization':
                    reg_site_name,
                    'authority_hrn':
                    reg_auth,
                    'email':
                    reg_email,
                    'password':
                    reg_password,
                    'public_key':
                    public_key,
                    'private_key':
                    private_key,
                    'current_site':
                    current_site,
                    'email_hash':
                    email_hash,
                    'user_hrn':
                    user_hrn,
                    'pi': [reg_auth],
                    'auth_type':
                    'managed',
                    'validation_link':
                    current_site + '/portal/email_activation/' + email_hash
                }

                create_pending_user(request, user_request, user_detail)
                # saves the user to django auth_user table [needed for password reset]
                #user = User.objects.create_user(reg_email, reg_email, reg_password)

                #creating user to manifold local:user
                #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}'
                #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1}
                #manifold_add_user(request,user_params)
                #creating local:account in manifold
                #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user
                #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config}
                #manifold_add_account(request,account_params)

                # Send email
                try:
                    ctx = {
                        'site_name': reg_site_name,
                        'authority_hrn':
                        reg_root_authority_hrn + '.' + reg_site_authority,
                        'site_abbreviated_name': reg_site_abbreviated_name,
                        'site_url': reg_site_url,
                        'address_city': reg_address_city,
                        'address_country': reg_address_country,
                        'first_name': reg_fname,
                        'last_name': reg_lname,
                        'authority_hrn': reg_auth,
                        'email': reg_email,
                        'user_hrn': user_hrn,
                        'public_key': public_key,
                    }

                    #recipients = authority_get_pi_emails(request,reg_auth)

                    self.template_name = 'authority_request_email.html'
                    html_content = render_to_string(self.template, ctx)

                    self.template_name = 'authority_request_email.txt'
                    text_content = render_to_string(self.template, ctx)

                    self.template_name = 'authority_request_email_subject.txt'
                    subject = render_to_string(self.template, ctx)
                    subject = subject.replace('\n', '')

                    #theme.template_name = 'email_default_sender.txt'
                    #sender =  render_to_string(theme.template, ctx)
                    #sender = sender.replace('\n', '')
                    sender = reg_email

                    msg = EmailMultiAlternatives(subject, text_content, sender,
                                                 ['*****@*****.**'])
                    msg.attach_alternative(html_content, "text/html")
                    msg.send()

                except Exception, e:
                    logger.error(
                        "Failed to send email, please check the mail templates and the SMTP configuration of your server"
                    )
                    import traceback
                    logger.error(traceback.format_exc())

                self.template_name = 'join_complete.html'
                # log institution activity
                activity.institution.joined(self.request)
                return render(request, self.template, {'theme': self.theme})
                #return render(request, 'user_register_complete.html')

        template_env = {
            'topmenu_items':
            topmenu_items_live('join', page),
            'errors':
            errors,
            'pi_first_name':
            request.POST.get('pi_first_name', ''),
            'pi_last_name':
            request.POST.get('pi_last_name', ''),
            'pi_email':
            request.POST.get('pi_email', ''),
            'pi_phone':
            request.POST.get('pi_phone', ''),
            'pi_password':
            request.POST.get('pi_password', ''),
            'site_name':
            request.POST.get('site_name', ''),
            'site_authority':
            request.POST.get('site_authority', '').lower(),
            'site_abbreviated_name':
            request.POST.get('site_abbreviated_name', ''),
            'site_url':
            request.POST.get('site_url', ''),
            'site_latitude':
            request.POST.get('site_latitude', ''),
            'site_longitude':
            request.POST.get('site_longitude', ''),
            'address_line1':
            request.POST.get('address_line1', ''),
            'address_line2':
            request.POST.get('address_line2', ''),
            'address_line3':
            request.POST.get('address_line3', ''),
            'address_city':
            request.POST.get('address_city', ''),
            'address_postalcode':
            request.POST.get('address_postalcode', ''),
            'address_state':
            request.POST.get('address_state', ''),
            'address_country':
            request.POST.get('address_country', ''),
            'root_authority_hrn':
            request.POST.get('root_authority_hrn', '').lower(),
            'root_authorities':
            root_authorities,
            'authorities':
            authorities,
            'theme':
            self.theme
        }
        template_env.update(page.prelude_env())
        # log institution activity
        activity.institution.join(self.request)
        return render(request, 'join_view.html', template_env)
Example #31
0
    def get(self, request, slicename=tmp_default_slice):

        page = Page(request)
        page.add_css_files('css/slice-view.css')
        page.add_js_files(["js/common.functions.js"])
        page.add_js_chunks(
            '$(function() { messages.debug("sliceview: jQuery version " + $.fn.jquery); });'
        )
        page.add_js_chunks(
            '$(function() { messages.debug("sliceview: users turned %s"); });'
            % ("on" if do_query_users else "off"))
        page.add_js_chunks(
            '$(function() { messages.debug("sliceview: leases turned %s"); });'
            % ("on" if do_query_leases else "off"))
        page.add_js_chunks(
            '$(function() { messages.debug("manifold URL %s"); });' %
            (ConfigEngine().manifold_url()))

        metadata = page.get_metadata()
        resource_md = metadata.details_by_object('resource')
        resource_fields = [column['name'] for column in resource_md['column']]

        user_md = metadata.details_by_object('user')
        user_fields = ['user_hrn'
                       ]  # [column['name'] for column in user_md['column']]

        # TODO The query to run is embedded in the URL
        main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
        main_query.select(
            'slice_hrn',
            #'resource.hrn', 'resource.urn',
            'resource.hostname',
            'resource.type',
            'resource.network_hrn',
            'lease.urn',
            'user.user_hrn',
            #'application.measurement_point.counter'
        )
        # for internal use in the querytable plugin;
        # needs to be a unique column present for each returned record
        main_query_init_key = 'hostname'

        query_resource_all = Query.get('resource').select(resource_fields)

        aq = AnalyzedQuery(main_query, metadata=metadata)
        page.enqueue_query(main_query, analyzed_query=aq)
        page.enqueue_query(query_resource_all)
        if do_query_users:
            # Required: the user must have an authority in its user.config
            # XXX Temporary solution
            user_query = Query().get('local:user').select('config', 'email')
            user_details = execute_query(self.request, user_query)

            # not always found in user_details...
            config = {}
            #            for user_detail in user_details:
            #                #email = user_detail['email']
            #                if user_detail['config']:
            #                    config = json.loads(user_detail['config'])
            #            user_detail['authority'] = config.get('authority',"Unknown Authority")
            #
            #            if user_detail['authority'] is not None:
            #                sub_authority = user_detail['authority'].split('.')
            #                root_authority = sub_authority[0]
            #                query_user_all = Query.get(root_authority+':user').select(user_fields)
            #
            #                # XXX TODO this filter doesn't work - to be improved in Manifold
            #                #.filter_by('authority.authority_hrn', '=', user_detail['authority'])
            #
            #                page.enqueue_query(query_user_all)
            #            else:
            #                print "authority of the user is not in local:user db"
            query_user_all = Query.get('user').select(user_fields)
            #    query_user_all = None

        # ... and for the relations
        # XXX Let's hardcode resources for now
        sq_resource = aq.subquery('resource')
        sq_user = aq.subquery('user')
        sq_lease = aq.subquery('lease')
        sq_measurement = aq.subquery('measurement')

        # Prepare the display according to all metadata
        # (some parts will be pending, others can be triggered by users).
        #
        # For example slice measurements will not be requested by default...

        # Create the base layout (Stack)...
        main_stack = Stack(
            page=page,
            title="Slice %s" % slicename,
            sons=[],
        )

        # ... responsible for the slice properties...

        # a nice header
        main_stack.insert(
            Raw(page=page,
                togglable=False,
                toggled=True,
                html="<h2 class='well well-lg'> Slice %s</h2>" % slicename))

        # --------------------------------------------------------------------------
        #DEPRECATED|        # QueryUpdater (Pending Operations)
        #DEPRECATED|
        #DEPRECATED|        main_stack.insert(QueryUpdater(
        #DEPRECATED|            page                = page,
        #DEPRECATED|            title               = 'Pending operations',
        #DEPRECATED|            query               = main_query,
        #DEPRECATED|            togglable           = True,
        #DEPRECATED|            # start turned off, it will open up itself when stuff comes in
        #DEPRECATED|            toggled             = False,
        #DEPRECATED|            domid               = 'pending',
        #DEPRECATED|            outline_complete    = True,
        #DEPRECATED|        ))

        # --------------------------------------------------------------------------
        # Filter Resources

        # turn off for now -- see above
        filter_query_editor = QueryEditor(
            page=page,
            query=sq_resource,
            query_all=query_resource_all,
            title="Select Columns",
            domid='select-columns',
        )
        filter_active_filters = ActiveFilters(
            page=page,
            query=sq_resource,
            title="Active Filters",
        )
        filters_area = Stack(
            page=page,
            title='Filter Resources',
            domid='filters',
            sons=[filter_query_editor, filter_active_filters],
            togglable=True,
            toggled='persistent',
            outline_complete=True,
        )
        main_stack.insert(filters_area)

        # --------------------------------------------------------------------------
        # RESOURCES
        # the resources part is made of a Tabs (Geographic, List),

        resources_as_gmap = GoogleMap(
            page=page,
            title='Geographic view',
            domid='resources-map',
            # tab's sons preferably turn this off
            togglable=False,
            query=sq_resource,
            query_all=query_resource_all,
            # this key is the one issued by google
            googlemap_api_key=ConfigEngine().googlemap_api_key(),
            # the key to use at init-time
            init_key=main_query_init_key,
            checkboxes=True,
            # center on Paris
            latitude=49.,
            longitude=9,
            zoom=4,
        )

        resources_as_3dmap = SensLabMap(
            page=page,
            title='3D Map',
            domid='senslabmap',
            query=sq_resource,
            query_all=query_resource_all,
        )

        resources_as_list = QueryTable(
            page=page,
            domid='resources-list',
            title='List view',
            # this is the query at the core of the slice list
            query=sq_resource,
            query_all=query_resource_all,
            init_key=main_query_init_key,
            checkboxes=True,
            datatables_options={
                'iDisplayLength': 25,
                'bLengthChange': True,
                'bAutoWidth': True,
            },
        )

        if insert_grid:
            resources_as_grid = QueryGrid(
                page=page,
                domid='resources-grid',
                title='Grid view',
                # this is the query at the core of the slice list
                query=sq_resource,
                query_all=query_resource_all,
                init_key=main_query_init_key,
                checkboxes=True,
            )

        if do_query_leases:
            resources_as_scheduler = Scheduler(
                page=page,
                title='Scheduler',
                domid='scheduler',
                query=sq_resource,
                query_all_resources=query_resource_all,
                query_lease=sq_lease,
            )

    # with the new 'Filter' stuff on top, no need for anything but the querytable
        resources_as_list_area = resources_as_list

        resources_sons = [
            resources_as_gmap,
            resources_as_3dmap,
            resources_as_scheduler,
            resources_as_list_area,
        ] if do_query_leases else [
            resources_as_gmap,
            resources_as_3dmap,
            resources_as_list_area,
        ]
        if insert_grid:
            resources_sons.append(resources_as_grid)

        resources_area = Tabs(
            page=page,
            domid="resources",
            togglable=True,
            title="Resources",
            outline_complete=True,
            sons=resources_sons,
            active_domid='resources-map',
            persistent_active=True,
        )
        main_stack.insert(resources_area)

        # --------------------------------------------------------------------------
        # USERS

        if do_query_users and query_user_all is not None:
            tab_users = Tabs(
                page=page,
                domid='users',
                outline_complete=True,
                togglable=True,
                title='Users',
                active_domid='users-list',
            )
            main_stack.insert(tab_users)

            tab_users.insert(
                QueryTable(
                    page=page,
                    title='Users List',
                    domid='users-list',
                    # tab's sons preferably turn this off
                    togglable=False,
                    # this is the query at the core of the slice list
                    query=sq_user,
                    query_all=query_user_all,
                    checkboxes=True,
                    datatables_options={
                        'iDisplayLength': 25,
                        'bLengthChange': True,
                        'bAutoWidth': True,
                    },
                ))

# DEMO
# --------------------------------------------------------------------------
# MEASUREMENTS
        measurements_stats_cpu = SliceStat(title="CPU Usage",
                                           domid='resources-stats-cpu',
                                           page=page,
                                           stats='slice',
                                           key='hrn',
                                           query='none',
                                           slicename=slicename,
                                           o='cpu')

        measurements_stats_mem = SliceStat(title="Memory Usage",
                                           domid='resources-stats-mem',
                                           page=page,
                                           stats='slice',
                                           key='hrn',
                                           query='none',
                                           slicename=slicename,
                                           o='mem')

        measurements_stats_asb = SliceStat(title="Traffic Sent",
                                           domid='resources-stats-asb',
                                           page=page,
                                           stats='slice',
                                           key='hrn',
                                           query='none',
                                           slicename=slicename,
                                           o='asb')

        measurements_stats_arb = SliceStat(title="Traffic Received",
                                           domid='resources-stats-arb',
                                           page=page,
                                           stats='slice',
                                           key='hrn',
                                           query='none',
                                           slicename=slicename,
                                           o='arb')

        tab_measurements = Tabs(
            page=page,
            domid="measurements",
            togglable=True,
            toggled='persistent',
            title="Measurements",
            outline_complete=True,
            sons=[
                measurements_stats_cpu, measurements_stats_mem,
                measurements_stats_asb, measurements_stats_arb
            ],
            active_domid='resources-stats-cpu',
            persistent_active=True,
        )
        main_stack.insert(tab_measurements)

        #        tab_measurements = Tabs (
        #            page                = page,
        #            active_domid        = 'measurements-list',
        #            outline_complete    = True,
        #            togglable           = True,
        #            title               = 'Measurements',
        #            domid               = 'measurements',
        #        )
        #        main_stack.insert(tab_measurements)
        #
        #        tab_measurements.insert(QueryTable(
        #            page        = page,
        #            title       = 'Measurements',
        #            domid       = 'measurements-list',
        #            # tab's sons preferably turn this off
        #            togglable   = False,
        #            # this is the query at the core of the slice list
        #            query       = sq_measurement,
        #            # do NOT set checkboxes to False
        #            # this table being otherwise empty, it just does not fly with dataTables
        #            checkboxes  = True,
        #            datatables_options = {
        #                'iDisplayLength' : 25,
        #                'bLengthChange'  : True,
        #                'bAutoWidth'     : True,
        #            },
        #        ))
        #
        #        # --------------------------------------------------------------------------
        #        # MESSAGES (we use transient=False for now)
        if insert_messages:
            main_stack.insert(
                Messages(
                    page=page,
                    title="Runtime messages for slice %s" % slicename,
                    domid="msgs-pre",
                    levels="ALL",
                    # plain messages are probably less nice for production but more reliable for development for now
                    transient=False,
                    # these make sense only in non-transient mode..
                    togglable=True,
                    toggled='persistent',
                    outline_complete=True,
                ))

        # variables that will get passed to the view-unfold1.html template
        template_env = {}

        # define 'unfold_main' to the template engine - the main contents
        template_env['unfold_main'] = main_stack.render(request)

        # more general variables expected in the template
        template_env['title'] = '%(slicename)s' % locals()
        # the menu items on the top
        template_env['topmenu_items'] = topmenu_items_live('Slice', page)
        # so we can sho who is logged
        template_env['username'] = the_user(request)

        template_env['theme'] = self.theme

        # don't forget to run the requests
        page.expose_js_metadata()
        # the prelude object in page contains a summary of the requirements() for all plugins
        # define {js,css}_{files,chunks}
        template_env.update(page.prelude_env())

        return render_to_response('view-unfold1.html',
                                  template_env,
                                  context_instance=RequestContext(request))
Example #32
0
    def get_context_data(self, **kwargs):
        pi = ""
        # We might have slices on different registries with different user accounts
        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn

        #messages.info(self.request, 'You have logged in')
        page = Page(self.request)

        ctx_my_authorities = {}
        ctx_delegation_authorities = {}
        ctx_sub_authorities = {}
        dest = {}

        # The user need to be logged in
        if the_user(self.request):
            # Who can a PI validate:
            # His own authorities + those he has credentials for.
            # In MySlice we need to look at credentials also.

            # XXX This will have to be asynchroneous. Need to implement barriers,
            # for now it will be sufficient to have it working statically

            # get user_id to later on query accounts
            # XXX Having real query plan on local tables would simplify all this
            # XXX $user_email is still not available for local tables
            #user_query = Query().get('local:user').filter_by('email', '==', '$user_email').select('user_id')
            user_query = Query().get('local:user').filter_by(
                'email', '==', the_user(self.request)).select('user_id')
            user, = execute_query(self.request, user_query)
            user_id = user['user_id']

            # Query manifold to learn about available SFA platforms for more information
            # In general we will at least have the portal
            # For now we are considering all registries
            all_authorities = []
            platform_ids = []
            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:
                logger.info("SFA PLATFORM > {}".format(
                    sfa_platform['platform']))
                if not 'auth_type' in sfa_platform:
                    continue
                auth = sfa_platform['auth_type']
                if not auth in all_authorities:
                    all_authorities.append(auth)
                platform_ids.append(sfa_platform['platform_id'])

            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.
            myslice_platforms_query = Query().get('local:platform').filter_by(
                'platform', '==', 'myslice').select('platform_id')
            myslice_platforms = execute_query(self.request,
                                              myslice_platforms_query)
            if myslice_platforms:
                myslice_platform, = myslice_platforms
                platform_ids.append(myslice_platform['platform_id'])

            # We can check on which the user has authoritity credentials = PI rights
            credential_authorities = set()
            credential_authorities_expired = set()

            # User account on these registries
            user_accounts_query = Query.get('local:account').filter_by(
                'user_id', '==',
                user_id).filter_by('platform_id', 'included',
                                   platform_ids).select('auth_type', 'config')
            user_accounts = execute_query(self.request, user_accounts_query)
            #print "=" * 80
            #print user_accounts
            #print "=" * 80
            for user_account in user_accounts:

                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 = []
                logger.debug("CONFIG KEYS {}".format(config.keys()))
                if 'authority_credentials' in config:
                    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:
                    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)

            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')
            #            all_authorities = execute_query(self.request, all_authorities_query)

            # ** Where am I a PI **
            # For this we need to ask SFA (of all authorities) = PI function
            pi_authorities_query = Query.get('myslice:user').filter_by(
                'user_hrn', '==', '$user_hrn').select('pi_authorities')
            pi_authorities_tmp = execute_query(self.request,
                                               pi_authorities_query)
            pi_authorities = set()
            try:
                for pa in pi_authorities_tmp:
                    pi_authorities |= set(pa['pi_authorities'])
            except Exception as e:
                logger.error('No pi_authorities')
# TODO: exception if no parent_authority
#             try:
#                 for pa in pi_authorities_tmp:
#                     pi_authorities |= set(pa['pi_authorities'])
#             except:

#            # include all sub-authorities of the PI
#            # if PI on ple, include all sub-auths ple.upmc, ple.inria and so on...
#            pi_subauthorities = set()
#            for authority in all_authorities:
#                authority_hrn = authority['authority_hrn']
#                for my_authority in pi_authorities:
#                    if authority_hrn.startswith(my_authority) and authority_hrn not in pi_subauthorities:
#                        pi_subauthorities.add(authority_hrn)

#print "pi_authorities =", pi_authorities
#print "pi_subauthorities =", pi_subauthorities

# My authorities + I have a credential
            pi_credential_authorities = pi_authorities & credential_authorities
            pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
            pi_expired_credential_authorities = pi_authorities & credential_authorities_expired
            # Authorities I've been delegated PI rights
            pi_delegation_credential_authorities = credential_authorities - pi_authorities
            pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities

            #print "pi_credential_authorities =", pi_credential_authorities
            #print "pi_no_credential_authorities =", pi_no_credential_authorities
            #print "pi_expired_credential_authorities =", pi_expired_credential_authorities
            #print "pi_delegation_credential_authorities = ", pi_delegation_credential_authorities
            #print "pi_delegation_expired_authorities = ", pi_delegation_expired_authorities

            # Summary intermediary
            pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities
            pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities

            #print "--"
            #print "pi_my_authorities = ", pi_my_authorities
            #print "pi_delegation_authorities = ", pi_delegation_authorities
            #print "pi_subauthorities = ", pi_subauthorities

            # Summary all
            queried_pending_authorities = pi_my_authorities | pi_delegation_authorities  #| pi_subauthorities
            #print "----"
            #print "queried_pending_authorities = ", queried_pending_authorities

            # iterate on the requests and check if the authority matches a prefix startswith an authority on which the user is PI
            requests = get_requests()
            #            requests = get_requests(queried_pending_authorities)
            for request in requests:
                auth_hrn = request['authority_hrn']
                for my_auth in pi_my_authorities:
                    if auth_hrn.startswith(my_auth):
                        dest = ctx_my_authorities
                        request['allowed'] = 'allowed'
                for my_auth in pi_delegation_authorities:
                    if auth_hrn.startswith(my_auth):
                        dest = ctx_delegation_authorities
                        request['allowed'] = 'allowed'
                if auth_hrn in pi_expired_credential_authorities:
                    request['allowed'] = 'expired'
                if 'allowed' not in request:
                    request['allowed'] = 'denied'
            #print "authority for this request", auth_hrn

#                if auth_hrn in pi_my_authorities:
#                    dest = ctx_my_authorities
#
#                    # define the css class
#                    if auth_hrn in pi_credential_authorities:
#                        request['allowed'] = 'allowed'
#                    elif auth_hrn in pi_expired_credential_authorities:
#                        request['allowed'] = 'expired'
#                    else: # pi_no_credential_authorities
#                        request['allowed'] = 'denied'
#
#                elif auth_hrn in pi_delegation_authorities:
#                    dest = ctx_delegation_authorities
#
#                    if auth_hrn in pi_delegation_credential_authorities:
#                        request['allowed'] = 'allowed'
#                    else: # pi_delegation_expired_authorities
#                        request['allowed'] = 'expired'
#
#                elif auth_hrn in pi_subauthorities:
#                    dest = ctx_sub_authorities
#
#                    if auth_hrn in pi_subauthorities:
#                        request['allowed'] = 'allowed'
#                    else: # pi_delegation_expired_authorities
#                        request['allowed'] = 'denied'
#
#                else:
#                    continue

                if not auth_hrn in dest:
                    dest[auth_hrn] = []
                dest[auth_hrn].append(request)

        context = super(ValidatePendingView, self).get_context_data(**kwargs)
        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

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Test view that combines various plugins'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('Validation', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        context['pi'] = "is_pi"
        context['theme'] = self.theme
        context['section'] = "Requests"
        # XXX We need to prepare the page for queries
        #context.update(page.prelude_env())

        return context
Example #33
0
def dashboard_view(request):

    page = Page(request)

    slices_query = Query.get("slice").select("slice_hrn")
    # old#                                  # xxx filter : should filter on the slices the logged user can see
    # old#                                  # we don't have the user's hrn yet
    # old#                                  # in addition this currently returns all slices anyways
    # old#                                  # filter = ...
    # old#                                  sort='slice_hrn',)
    page.enqueue_query(slices_query)

    main_plugin = Stack(
        page=page,
        title="Putting stuff together",
        sons=[
            QueryCode(page=page, title="Vizualize your query", query=slices_query, toggled=False),
            QuickFilter(
                # we play with this one for demo purposes in dashboard.css
                domid="myquickfilter",
                page=page,
                title="play with filters",
                criterias=quickfilter_criterias,
                toggled=False,
            ),
            SliceList(  # setting visible attributes first
                page=page,
                title="Asynchroneous SliceList",
                header="slices list",
                with_datatables=False,
                # this is the query at the core of the slice list
                query=slices_query,
            ),
        ],
    )

    # variables that will get passed to the view-unfold2.html template
    template_env = {}

    # define 'unfold_main' to the template engine
    template_env["unfold_main"] = main_plugin.render(request)

    # more general variables expected in the template
    template_env["title"] = "Test view for a full request cycle"
    # the menu items on the top
    template_env["topmenu_items"] = topmenu_items_live("dashboard", page)
    # so we can sho who is logged
    template_env["username"] = the_user(request)

    #   ########## add another plugin with the same request, on the RHS pane
    #   will show up in the right-hand side area named 'related'
    related_plugin = SliceList(
        page=page,
        title="Same request, other layout",
        domid="sidelist",
        with_datatables=True,
        header="paginated slices",
        # share the query
        query=slices_query,
    )
    # likewise but on the side view
    template_env["unfold_margin"] = related_plugin.render(request)

    # add our own css in the mix
    # page.add_css_files ( 'css/dashboard.css')

    # the prelude object in page contains a summary of the requirements() for all plugins
    # define {js,css}_{files,chunks}
    prelude_env = page.prelude_env()
    template_env.update(prelude_env)
    return render_to_response("view-unfold2.html", template_env, context_instance=RequestContext(request))
Example #34
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)
        #print "UNIVBRIS page"

        #create new query to manifold----query is not called yet
        #need to modify to get i2cat of resources also
        univbrisvtamform_query = Query().get(
            'ofelia-i2cat-vt:resource').select('hostname')
        #print univbrisfoam_query #.select('urn')

        #queue the query
        page.enqueue_query(univbrisvtamform_query)
        page.expose_js_metadata()

        #plugin which display a table where an experimenter will add VMs to according to his needs
        univbrisvtamplugin = UnivbrisVtamPlugin(
            page=page,
            title='univbris_vtam',
            domid='univbris_vtam',
            query=None,
        )

        #plugin which display a form where an experimenter will specify where a
        univbrisvtamform = UnivbrisVtamForm(
            page=page,
            title='univbris_vtam_form',
            domid='univbris_vtam_form',
            query=univbrisvtamform_query,
            query_all=None,
            datatables_options={
                'iDisplayLength': 3,
                'bLengthChange': True,
                'bAutoWidth': True,
            },
        )

        #render plugins in each context within a single page, but not all plugins are visible at all time.
        context = super(UnivbrisVtam, self).get_context_data(**kwargs)
        context['person'] = self.request.user
        #context['welcome'] = univbriswelcome.render(self.request)
        #context['resources'] = univbrisfoamlist.render(self.request)
        context['vms_list'] = univbrisvtamplugin.render(self.request)
        context['vm_form'] = univbrisvtamform.render(self.request)
        #context['oflowspaces_form']= univbrisofvform.render(self.request)
        #context['flowspaces_form']= univbrisfvform.render(self.request)
        #context['topology']=univbristopology.render(self.request)

        # XXX This is repeated in all pages
        # more general variables expected in the template
        context['title'] = 'Create New Virtual Machines'
        # the menu items on the top
        context['topmenu_items'] = topmenu_items_live('univbris', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)

        context.update(page.prelude_env())
        page.expose_js_metadata()

        # the page header and other stuff
        context.update(page.prelude_env())

        context['layout_1_or_2'] = "layout-unfold2.html" if not context[
            'username'] else "layout-unfold1.html"

        return context
Example #35
0
def test_plugin_view (request):

    page = Page(request)
    
    page.expose_js_metadata()

    # variables that will get passed to this template
    template_env = {}
    
    slicename='ple.inria.heartbeat'
    main_query = Query.get('resource').filter_by('slice_hrn', '=', slicename).select(['network','type','hrn','hostname','sliver'])
    # without an querytable, this would use use : run_it=False as nothing would listen to the results
    page.enqueue_query (main_query, # run_it=False
                        )

    main_plugin = \
        Stack (
        page=page,
        title='thestack',
        togglable=True,
        domid='stack',
        sons=[ \
        # make sure the 2 things work together
            Messages (
                    page=page,
                    title="Transient Runtime messages",
                    domid="messages-transient",
                    levels='ALL',
                    ),
            QueryTable (
                    page=page,
                    title="Slice %s - checkboxes"%slicename,
                    query=main_query,
                    domid="querytable",
                    checkboxes=True,
                    togglable=True,
                    ),
            Messages (
                    page=page,
                    title="Inline Runtime messages",
                    domid="messages",
                    levels='ALL',
                    togglable=True,
                    transient=False,
                    ),
            Raw (
                    page=page,
                    title="issue messages",
                    togglable=True,
                    html="""
<input type="button" id="bouton" value="Click me" />
""",
                    ),
            ])

    page.add_js_chunks ( """
function issue_debug() {console.log("issue_debug");messages.debug("issue_debug");};
$(function(){$("#bouton").click(issue_debug);});
""")

    # define 'unfold_main' to the template engine
    template_env [ 'unfold_main' ] = main_plugin.render(request)

    # more general variables expected in the template
    template_env [ 'title' ] = 'Single Plugin View' 
    template_env [ 'topmenu_items' ] = topmenu_items_live('plugin', page) 
    template_env [ 'username' ] = the_user (request) 

    # the prelude object in page contains a summary of the requirements() for all plugins
    # define {js,css}_{files,chunks}
    prelude_env = page.prelude_env()
    template_env.update(prelude_env)
    return render_to_response ('view-unfold1.html',template_env,
                               context_instance=RequestContext(request))