Beispiel #1
0
def target_builds():
    """ Get a dict of targets and how many builds were done for each

        Returns:
            dict:   shortened target name as key and a list as value

        The value of each dict entry is a list in the form:
        [ count, title, color ], where only the first one is required

    """
    from meshkit import target_shorten
    db = current.globalenv['db']
    target_stats = {}

    count = db.build_log.target.count()
    target_stats_select = db().select(db.build_log.target,
                                      count,
                                      groupby=db.build_log.target)

    for row in target_stats_select:
        target_name = row.build_log.target
        target_builds = row._extra['COUNT(build_log.target)']
        if target_name:
            target_stats[target_shorten(target_name)] = [target_builds]

    return target_stats
Beispiel #2
0
def target_builds():
    """ Get a dict of targets and how many builds were done for each

        Returns:
            dict:   shortened target name as key and a list as value

        The value of each dict entry is a list in the form:
        [ count, title, color ], where only the first one is required

    """
    from meshkit import target_shorten
    db = current.globalenv['db']
    target_stats = {}

    count = db.build_log.target.count()
    target_stats_select = db().select(
        db.build_log.target, count, groupby=db.build_log.target
    )

    for row in target_stats_select:
        target_name = row.build_log.target
        target_builds = row._extra['COUNT(build_log.target)']
        if target_name:
            target_stats[target_shorten(target_name)] = [target_builds]

    return target_stats
Beispiel #3
0
def user_builds():
    """ Builds the user has done """

    if settings.https_enabled:
        request.requires_https()

    def delete_multiple(ids):
        if not ids:
            session.flash = T('Select at least one record.')
        else:
            for id in ids:
                db((db.imageconf.id_user == auth.user_id)
                   & (db.imageconf.id == id)).delete()
            pass
        pass
        return ''

    if len(request.args) > 2:
        if request.args[0] == "edit":
            redirect(URL(wizard, args=[request.args[2]]))

    fields = [
        db.imageconf.hostname, db.imageconf.target, db.imageconf.profile,
        db.imageconf.location
    ]

    db.imageconf.target.represent = lambda target, _: target_shorten(target)

    grid = SQLFORM.grid(db.imageconf.id_user == auth.user_id,
                        user_signature=False,
                        showbuttontext=False,
                        fields=fields,
                        create=False,
                        details=False,
                        paginate=100,
                        csv=False,
                        maxtextlength=50,
                        ui=settings.ui_grid,
                        selectable=[[
                            T('Delete'), lambda ids: delete_multiple(ids),
                            "btn w2p-confirm"
                        ]])

    heading = grid.elements('th')
    if heading:
        heading[0].append(
            INPUT(_type='checkbox',
                  _id="imageconf-check-all",
                  _class="grid-check-all",
                  _title=T('Check all')))

    return dict(grid=grid)
Beispiel #4
0
def wizard():
    import random
    import datetime
    import hashlib

    lang = T.accepted_language or 'en'

    # check if community and target are set, else redirect to the index page
    # todo
    # list of profiles
    if not session.target:
        redirect((URL('error')))

    session.target_short = target_shorten(session.target)

    session.profiles = get_profiles(
        config.buildroots_dir, session.target,
        os.path.join(request.folder, "static", "ajax"), True)

    # overwrite field defaults and requires before creating the SQLFORM

    if auth.user:
        user_defaults = db(
            db.user_defaults.id_auth_user == auth.user_id).select().first()
        ud_items = [
            'pubkeys', 'expert', 'location', 'nickname', 'name', 'email',
            'homepage', 'phone', 'note', 'password_hash'
        ]

        for k in ud_items:
            if k in user_defaults and user_defaults[k]:
                db.imageconf[k].default = user_defaults[k]

    db.imageconf.profile.requires = IS_IN_SET(
        session.profiles,
        zero=None,
        error_message=T('%(name)s is invalid') % dict(name=T('Profile')))
    db.imageconf.profile.default = session.profile

    db.imageconf.lanproto.requires = IS_IN_SET(
        config.lanprotos,
        error_message=T('%(name)s is invalid') %
        dict(name='LAN ' + T('Protocol')),
        zero=None)

    db.imageconf.wanproto.requires = IS_IN_SET(
        config.wanprotos,
        error_message=T('%(name)s is invalid') % dict(name=T('Wan Protocol')),
        zero=None)

    # add fields for wireless interfaces wifi0 to wifi2 by cloning them from
    # the db.wifi_interfaces table and adding custom names.

    wfields = []
    for i in range(3):
        for f in [
                'chan', 'dhcp', 'dhcprange', 'ipv4addr', 'ipv6addr', 'vap',
                'ipv6ra', 'enabled'
        ]:
            name = 'wifi%s%s' % (i, db.wifi_interfaces[f].name)
            # default = db.wifi_interfaces[f].default
            # wfields.append(db.wifi_interfaces[f].clone(name=name,
            # default=default))
            wfields.append(db.wifi_interfaces[f].clone(name=name))

    form = None
    id = None
    if auth.user and request.args(0):
        record = db.imageconf(request.args(0)) or redirect(
            URL('access_denied'))

        if record.id_user == auth.user_id:
            form = SQLFORM.factory(db.imageconf,
                                   table_name='imageconf',
                                   *wfields)
            id = request.args(0)
        else:
            # access denied
            redirect(URL('access_denied'))
    else:
        form = SQLFORM.factory(db.imageconf, table_name='imageconf', *wfields)

    # session.profiles = get_profiles(config.buildroots_dir, session.target,
    # os.path.join(request.folder, "static", "ajax"))
    defaultpkgs = get_defaultpkgs(
        config.buildroots_dir, session.target,
        os.path.join(request.folder, "static", "ajax"))
    # generate a static package list (this is only done once).
    # if package lists change delete the cache file in
    # static/package_lists/<target>
    create_package_list(
        config.buildroots_dir, session.target,
        os.path.join(request.folder, "static", "package_lists"))
    user_packagelist = ''
    ipv6_packages = ""

    session.url = URL(request.application,
                      request.controller,
                      'api/json/buildimage',
                      scheme=True,
                      host=True)
    if config.communitysupport:
        nodenumber = ''
        # Add meshwizard to defaultpackages
        defaultpkgs.append('meshwizard')
        session.communitysupport = True
    else:
        session.communitysupport = False
        nodenumber = False

    if not session.mail:
        session.mail = ''

    if session.ipv6:
        ipv6_packages = config.ipv6packages or ''
        if session.ipv6_config == 'auto-ipv6-random' or \
           session.ipv6_config == 'auto-ipv6-fromv4':
            ipv6_packages = ipv6_packages + ' auto-ipv6-ib'

    if form.process(session=None, formname='step2', keepvalues=True).accepted:
        session.profile = form.vars.profile
        session.noconf = form.vars.noconf or config.noconf
        session.rand = form.vars.rand
        session.id = form.vars.id
        session.hostname = get_hostname_from_form_vars(form.vars)
        session.lanipv4addr = form.vars.lanipv4addr or '192.168.1.1'
        session.location = session.location or '-'

        wifi_options = filter_wifi_interfaces(form.vars)

        # write id of logged in user:
        if auth.user:
            form.vars.id_user = auth.user_id

        # write current language
        form.vars.lang = lang

        # auto-set hostname if it is empty
        if not form.vars.hostname:
            form.vars.hostname = session.hostname

        if id:
            query = (db.imageconf.id == id)
            db(query).update(**db.imageconf._filter_fields(form.vars))
            session.id = id
        else:
            id = db.imageconf.insert(**db.imageconf._filter_fields(form.vars))
            session.id = id

        session.main_mesh_ip = None
        for i in wifi_options:
            if i["enabled"]:
                id_row = db.wifi_interfaces.insert(
                    id_build=id, **db.wifi_interfaces._filter_fields(i))
                if id_row:
                    row = db(db.wifi_interfaces.id == id_row).select().first()
                    row.update_record(id_build=id, enabled=True)
                if not session.main_mesh_ip:
                    if i["ipv4addr"]:
                        session.main_mesh_ip = i["ipv4addr"]

        db.commit()

        # schedule task
        scheduler.queue_task(build,
                             pvars=dict(id=id),
                             immediate=True,
                             task_name="build-%s" % id,
                             timeout=settings.scheduler['timeout'],
                             retry_failed=settings.scheduler['retry_failed'])
        redirect(URL('build'))

    elif form.errors:
        errormsg = ''
        for i in form.errors:
            errormsg = errormsg + "<li>" + str(form.errors[i]) + "</li>"
            response.flash = XML(
                T('Form has errors:') + "</br><ul>" + errormsg + "</ul>")
        session.profile = form.vars.profile or ''
        session.webif = form.vars.webif or ''
        session.wifiifsnr = form.vars.wifiifsnr or 1
        user_packagelist = form.vars.packages or ''

    hash = hashlib.md5(
        str(datetime.datetime.now()) +
        str(random.randint(1, 999999999))).hexdigest()

    community_packages = "%s %s" % (session.community_packages,
                                    config.add_defaultpackages)
    return dict(form=form,
                packages='',
                rand=hash,
                defaultpkgs=defaultpkgs,
                nodenumber=nodenumber,
                community_packages=community_packages,
                user_packagelist=user_packagelist,
                addpackages='',
                ipv6_packages=ipv6_packages,
                formhelpers=formhelpers,
                fh=formhelpers.customField(form, "imageconf"))
Beispiel #5
0
def user_builds():
    """ Builds the user has done """

    if settings.https_enabled:
        request.requires_https()

    def delete_multiple(ids):
        if not ids:
            session.flash = T('Select at least one record.')
        else:
            for id in ids:
                db(
                    (db.imageconf.id_user == auth.user_id) &
                    (db.imageconf.id == id)
                ).delete()
            pass
        pass
        return ''

    if len(request.args) > 2:
        if request.args[0] == "edit":
            redirect(URL(wizard, args=[request.args[2]]))

    fields = [
        db.imageconf.hostname,
        db.imageconf.target,
        db.imageconf.profile,
        db.imageconf.location
    ]

    db.imageconf.target.represent = lambda target, _: target_shorten(target)

    grid = SQLFORM.grid(
        db.imageconf.id_user == auth.user_id,
        user_signature=False,
        showbuttontext=False,
        fields=fields,
        create=False,
        details=False,
        paginate=100,
        csv=False,
        maxtextlength=50,
        ui=settings.ui_grid,
        selectable=[
            [
                T('Delete'),
                lambda ids: delete_multiple(ids),
                "btn w2p-confirm"
            ]
        ]
    )

    heading = grid.elements('th')
    if heading:
        heading[0].append(
            INPUT(
                _type='checkbox',
                _id="imageconf-check-all",
                _class="grid-check-all",
                _title=T('Check all')
            )
        )

    return dict(grid=grid)
Beispiel #6
0
def wizard():
    import random
    import datetime
    import hashlib

    lang = T.accepted_language or 'en'

    # check if community and target are set, else redirect to the index page
    # todo
    # list of profiles
    if not session.target:
        redirect((URL('error')))

    session.target_short = target_shorten(session.target)

    session.profiles = get_profiles(
        config.buildroots_dir,
        session.target,
        os.path.join(request.folder, "static", "ajax"),
        True
    )

    # overwrite field defaults and requires before creating the SQLFORM

    if auth.user:
        user_defaults = db(
            db.user_defaults.id_auth_user == auth.user_id).select(
        ).first(
        )
        ud_items = [
            'pubkeys',
            'expert',
            'location',
            'nickname',
            'name',
            'email',
            'homepage',
            'phone',
            'note',
            'password_hash']

        for k in ud_items:
            if k in user_defaults and user_defaults[k]:
                db.imageconf[k].default = user_defaults[k]

    db.imageconf.profile.requires = IS_IN_SET(
        session.profiles,
        zero=None,
        error_message=T('%(name)s is invalid') % dict(name=T('Profile'))
    )
    db.imageconf.profile.default = session.profile

    db.imageconf.lanproto.requires = IS_IN_SET(
        config.lanprotos,
        error_message=T('%(name)s is invalid') % dict(
            name='LAN ' + T('Protocol')),
        zero=None
    )

    db.imageconf.wanproto.requires = IS_IN_SET(
        config.wanprotos,
        error_message=T('%(name)s is invalid') % dict(name=T('Wan Protocol')),
        zero=None
    )

    # add fields for wireless interfaces wifi0 to wifi2 by cloning them from
    # the db.wifi_interfaces table and adding custom names.

    wfields = []
    for i in range(3):
        for f in ['chan', 'dhcp', 'dhcprange', 'ipv4addr', 'ipv6addr', 'vap',
                  'ipv6ra', 'enabled']:
            name = 'wifi%s%s' % (i, db.wifi_interfaces[f].name)
            # default = db.wifi_interfaces[f].default
            # wfields.append(db.wifi_interfaces[f].clone(name=name,
            # default=default))
            wfields.append(db.wifi_interfaces[f].clone(name=name))

    form = None
    id = None
    if auth.user and request.args(0):
        record = db.imageconf(
            request.args(0)) or redirect(URL('access_denied')
                                         )

        if record.id_user == auth.user_id:
            form = SQLFORM.factory(
                db.imageconf,
                table_name='imageconf',
                *wfields
            )
            id = request.args(0)
        else:
            # access denied
            redirect(URL('access_denied'))
    else:
        form = SQLFORM.factory(db.imageconf, table_name='imageconf', *wfields)

    # session.profiles = get_profiles(config.buildroots_dir, session.target,
    # os.path.join(request.folder, "static", "ajax"))
    defaultpkgs = get_defaultpkgs(
        config.buildroots_dir,
        session.target,
        os.path.join(request.folder, "static", "ajax")
    )
    # generate a static package list (this is only done once).
    # if package lists change delete the cache file in
    # static/package_lists/<target>
    create_package_list(
        config.buildroots_dir,
        session.target,
        os.path.join(request.folder, "static", "package_lists")
    )
    user_packagelist = ''
    ipv6_packages = ""

    session.url = URL(
        request.application,
        request.controller,
        'api/json/buildimage',
        scheme=True,
        host=True
    )
    if config.communitysupport:
        nodenumber = ''
        # Add meshwizard to defaultpackages
        defaultpkgs.append('meshwizard')
        session.communitysupport = True
    else:
        session.communitysupport = False
        nodenumber = False

    if not session.mail:
        session.mail = ''

    if session.ipv6:
        ipv6_packages = config.ipv6packages or ''
        if session.ipv6_config == 'auto-ipv6-random' or \
           session.ipv6_config == 'auto-ipv6-fromv4':
            ipv6_packages = ipv6_packages + ' auto-ipv6-ib'

    if form.process(session=None, formname='step2', keepvalues=True).accepted:
        session.profile = form.vars.profile
        session.noconf = form.vars.noconf or config.noconf
        session.rand = form.vars.rand
        session.id = form.vars.id
        session.hostname = get_hostname_from_form_vars(form.vars)
        session.lanipv4addr = form.vars.lanipv4addr or '192.168.1.1'
        session.location = session.location or '-'

        wifi_options = filter_wifi_interfaces(form.vars)

        # write id of logged in user:
        if auth.user:
            form.vars.id_user = auth.user_id

        # write current language
        form.vars.lang = lang

        # auto-set hostname if it is empty
        if not form.vars.hostname:
            form.vars.hostname = session.hostname

        if id:
            query = (db.imageconf.id == id)
            db(query).update(**db.imageconf._filter_fields(form.vars))
            session.id = id
        else:
            id = db.imageconf.insert(**db.imageconf._filter_fields(form.vars))
            session.id = id

        session.main_mesh_ip = None
        for i in wifi_options:
            if i["enabled"]:
                id_row = db.wifi_interfaces.insert(
                    id_build=id,
                    **db.wifi_interfaces._filter_fields(i)
                )
                if id_row:
                    row = db(db.wifi_interfaces.id == id_row).select().first()
                    row.update_record(id_build=id, enabled=True)
                if not session.main_mesh_ip:
                    if i["ipv4addr"]:
                        session.main_mesh_ip = i["ipv4addr"]

        db.commit()

        # schedule task
        scheduler.queue_task(
            build,
            pvars=dict(id=id),
            immediate=True,
            task_name="build-%s" % id,
            timeout=settings.scheduler['timeout'],
            retry_failed=settings.scheduler['retry_failed']
        )
        redirect(URL('build'))

    elif form.errors:
        errormsg = ''
        for i in form.errors:
            errormsg = errormsg + "<li>" + str(form.errors[i]) + "</li>"
            response.flash = XML(
                T('Form has errors:') + "</br><ul>" + errormsg + "</ul>")
        session.profile = form.vars.profile or ''
        session.webif = form.vars.webif or ''
        session.wifiifsnr = form.vars.wifiifsnr or 1
        user_packagelist = form.vars.packages or ''

    hash = hashlib.md5(str(datetime.datetime.now())
                       + str(random.randint(1, 999999999))).hexdigest()

    community_packages = "%s %s" % (
        session.community_packages,
        config.add_defaultpackages
    )
    return dict(
        form=form, packages='', rand=hash, defaultpkgs=defaultpkgs,
        nodenumber=nodenumber, community_packages=community_packages,
        user_packagelist=user_packagelist, addpackages='',
        ipv6_packages=ipv6_packages, formhelpers=formhelpers,
        fh=formhelpers.customField(form, "imageconf")
    )