Ejemplo n.º 1
0
def configure():
    email = session['user_email']
    user = User.query.filter_by(email=email).first()

    if user is None:
        flash("User not found")
        return redirect(url_for('logout'))

    if user.entity is not None and user.entity.deployed:
        enabled = False
        form = DisabledConfigurationForm(request.form)
    else:
        enabled = True
        form = ConfigurationForm(request.form)

    if user.entity is not None and user.entity.logo is not None:
        logo_available = True
    else:
        logo_available = False

    if request.method == 'POST' and form.validate():
        if not enabled:
            flash("You can not change the entity once deployed.")
            return render_template('configuration.html', form=form, enabled=enabled,logo_available=logo_available)

        # Exract data from the form
        logo = request.files['logo']
        logo_data = logo.stream.read()
        logo_ext = (logo.name or '').split('.')[-1]
        if len(logo_ext) not in (3,4):
            # That's not an extension
            logo_ext  = 'jpeg'
        name = form.name.data
        base_url = form.base_url.data
        link_url = form.link_url.data
        google_analytics_number = form.google_analytics_number.data
               
        logo_available = True

        # Create entity
        if user.entity is None:
            entity = Entity(name, base_url)
            entity.logo = logo_data
            entity.logo_ext = logo_ext
            entity.link_url = link_url
            entity.google_analytics_number = google_analytics_number
            user.entity = entity
        
        # Update
        else:
            if logo_data is not None and logo_data != '': 
                user.entity.logo = logo_data
                user.entity.logo_ext = logo_ext
            if name is not None : user.entity.name = name
            if base_url is not None : user.entity.base_url = base_url
            if link_url is not None : user.entity.link_url = link_url
            if google_analytics_number is not None :
                user.entity.google_analytics_number = google_analytics_number
            
        # Save
        db.session.add(user)
        db.session.commit()
     
        flash('Configuration saved.', 'success')
        
        if request.form.get('action','') == 'savedeploy':
            return redirect(url_for('deploy'))

    else:
         # Get user
        email = session['user_email']
        user = User.query.filter_by(email=email).first()
        if user is None:
            return redirect(url_for('logout'))
        entity = user.entity
        if entity is not None:
            form.name.data = entity.name
            form.base_url.data = entity.base_url
            form.link_url.data = entity.link_url
            form.google_analytics_number.data = entity.google_analytics_number
    return render_template('configuration.html', form=form, enabled=enabled, logo_available=logo_available)
Ejemplo n.º 2
0
 def __call__(self, form, field):
     if Entity.url_exists(session['user_email'], field.data):
         raise validators.ValidationError(self.message)
Ejemplo n.º 3
0
def configure():
    email = session['user_email']
    user = User.query.filter_by(email=email).first()

    if user is None:
        flash("User not found")
        return redirect(url_for('logout'))

    if user.entity is not None and user.entity.deployed:
        enabled = False
        form = DisabledConfigurationForm(request.form)
    else:
        enabled = True
        form = ConfigurationForm(request.form)

    if user.entity is not None and user.entity.logo is not None:
        logo_available = True
    else:
        logo_available = False

    if request.method == 'POST' and form.validate():
        if not enabled:
            flash("You can not change the entity once deployed.")
            return render_template('configuration.html',
                                   form=form,
                                   enabled=enabled,
                                   logo_available=logo_available)

        # Exract data from the form
        logo = request.files['logo']
        logo_data = logo.stream.read()
        logo_ext = (logo.name or u'').split('.')[-1]
        if len(logo_ext) not in (3, 4):
            # That's not an extension
            logo_ext = u'jpeg'
        name = form.name.data
        base_url = form.base_url.data
        link_url = form.link_url.data
        google_analytics_number = form.google_analytics_number.data

        logo_available = True

        # Create entity
        if user.entity is None:
            entity = Entity(name, base_url)
            entity.logo = logo_data
            entity.logo_ext = logo_ext
            entity.link_url = link_url
            entity.google_analytics_number = google_analytics_number
            user.entity = entity

        # Update
        else:
            if logo_data is not None and logo_data != '':
                user.entity.logo = logo_data
                user.entity.logo_ext = logo_ext
            if name is not None: user.entity.name = name
            if base_url is not None: user.entity.base_url = base_url
            if link_url is not None: user.entity.link_url = link_url
            if google_analytics_number is not None:
                user.entity.google_analytics_number = google_analytics_number

        # Save
        db.session.add(user)
        db.session.commit()

        flash('Configuration saved.', 'success')

        if request.form.get('action', '') == 'savedeploy':
            return redirect(url_for('deploy'))

    else:
        # Get user
        email = session['user_email']
        user = User.query.filter_by(email=email).first()
        if user is None:
            return redirect(url_for('logout'))
        entity = user.entity
        if entity is not None:
            form.name.data = entity.name
            form.base_url.data = entity.base_url
            form.link_url.data = entity.link_url
            form.google_analytics_number.data = entity.google_analytics_number
    return render_template('configuration.html',
                           form=form,
                           enabled=enabled,
                           logo_available=logo_available)
Ejemplo n.º 4
0
    def run(self):
        """Loop of the task manager. pops a job in each iteration and executes
        the task until no tasks remain in the queue. The task manager will
        remain executing and awaiting for a task/job until _shutdown is true.
        This avoids concurrency problems: no more than one task will be executed
        at the same time.
        """
        
        while not self._shutdown:
            try:
                task = self.queue.get(timeout=0.1)
            except Queue.Empty:
                continue

            print "Processing task: ", task['task_id']
            output = task['output']
            output.write('Starting process...')
            self.task_status[task['task_id']] = TaskManager.STATUS_STARTED
            try:

                ######################################
                # 
                # 1. Prepare the system
                # 
                output.write('[done]\nPreparing requirements...')
                user = User.query.filter_by(email=task[u'email']).first()
                entity = user.entity

                #
                # Write the logo to disc
                # 
                tmp_logo = tempfile.NamedTemporaryFile()
                tmp_logo.write(user.entity.logo)
                tmp_logo.flush()
               
                # 
                # Prepare the parameters
                # 
                settings =  deploymentsettings.DEFAULT_DEPLOYMENT_SETTINGS.copy()
                
                settings[Creation.BASE_URL]       = 'w/' + entity.base_url

                settings[Creation.LOGO_PATH]      = tmp_logo.name

                settings[Creation.DB_NAME]        = 'wcloud%s' % entity.id
                settings[Creation.DB_USER]        = app.config['DB_USERNAME']
                settings[Creation.DB_PASSWD]      = app.config['DB_PASSWORD']

                settings[Creation.ADMIN_USER]     = task['admin_user']
                settings[Creation.ADMIN_NAME]     = task['admin_name']
                settings[Creation.ADMIN_PASSWORD] = task['admin_password']
                settings[Creation.ADMIN_MAIL]     = task['admin_email']

                last_port = Entity.last_port()
                if last_port is None: 
                    last_port = deploymentsettings.MIN_PORT

                settings[Creation.START_PORTS] =  last_port + 1
                settings[Creation.SYSTEM_IDENTIFIER] = user.entity.name
                settings[Creation.ENTITY_LINK] = user.entity.link_url

                #########################################################
                # 
                # 2. Create the full WebLab-Deusto environment
                # 
                output.write("[Done]\nCreating deployment directory...")
                results = weblab_create(task['directory'] ,
                                        settings,
                                        task['stdout'],
                                        task['stderr'],
                                        task['exit_func'])
                time.sleep(0.5)
                
                settings.update(task)

                ##########################################################
                # 
                # 3. Configure the web server
                # 
                output.write("[Done]\nConfiguring web server...")
                
                # Create Apache configuration
                with open(os.path.join(app.config['DIR_BASE'],
                            deploymentsettings.APACHE_CONF_NAME), 'a') as f:
                    conf_dir = results['apache_file']
                    f.write('Include "%s"\n' % conf_dir) 
                
                # Reload apache
                opener = urllib2.build_opener(urllib2.ProxyHandler({}))
                print(opener.open('http://127.0.0.1:%s/' % app.config['APACHE_RELOADER_PORT']).read())
                
                ##########################################################
                # 
                # 4. Register and start the new WebLab-Deusto instance
                #
                output.write("[Done]\nRegistering and starting instance...")
                
                global response
                response = None
                is_error = False
                def register():
                    global response
                    import urllib2
                    import traceback
                    try:
                        url = 'http://127.0.0.1:%s/deployments/' % app.config['WEBLAB_STARTER_PORT']
                        req = urllib2.Request(url, json.dumps({'name' : entity.base_url}), {'Content-Type': 'application/json'})
                        response = opener.open(req).read()
                    except:
                        is_error = True
                        response = "There was an error registering or starting the service. Contact the administrator"
                        traceback.print_exc()

                print "Executing 'register' in other thread...",
                t = threading.Thread(target=register)
                t.start()
                while t.isAlive() and response is None:
                    time.sleep(1)
                    output.write(".")
                print "Ended. is_error=%s; response=%s" % (is_error, response)

                if is_error:
                    raise Exception(response)

                ##########################################################
                # 
                # 5. Service deployed. Configure the response
                #
                
                output.write("[Done]\n\nCongratulations, your system is ready!")
                task['url'] = task['url_root'] + entity.base_url
                self.task_status[task['task_id']] = TaskManager.STATUS_FINISHED
                
                # 
                # Save in database data like last port
                # Note: this is thread-safe since the task manager is 
                # monothread
                user.entity.start_port_number = results['start_port']
                user.entity.end_port_number = results['end_port']
                
                # Save
                db.session.add(user)
                db.session.commit()
                
            except:
                import traceback
                print(traceback.format_exc())
                self.task_status[task['task_id']] = TaskManager.STATUS_ERROR

                # Revert changes:
                # 
                # 1. Delete the directory 
                shutil.rmtree(task['directory'], ignore_errors=True)