def create_interface(**kwargs):
    field_mapper = {
        "device_id": "device_id",
        "address": "address",
        "bandwidth": "bandwidth",
        "bia": "bia",
        "crc": "crc",
        "delay": "delay",
        "description": "description",
        "duplex": "duplex",
        "encapsulation": "encapsulation",
        "hardware_type": "hardware_type",
        "interface": "interface",
        "ip_address": "ip_address",
        "mtu": "mtu",
        "speed": "speed"
    }

    check = check_interface_exist(kwargs["device_id"], kwargs["interface"])
    payload = payload_builder(field_mapper, **kwargs)
    if not check:
        # New Interface will be created...
        interface = Interface(**payload)
        db.session.add(interface)
        return interface
    else:
        # Existing interface will be updated...
        for k, v in payload.items():
            setattr(check, k, v)
    db.session.commit()
    return check
Exemplo n.º 2
0
def machine_interface_create(id):
    machine = Machine.query.get(id)
    if not machine:
        flash("Machine does not exist", "error")
        return redirect(url_for('.get_machines_admin'))

    if not machine.check_permission(g.user, 'admin'):
        flash('Permission denied', 'error')
        return redirect(url_for('.get_machines_admin'))

    form = validations.InterfaceForm(request.form)
    if form.validate():
        new_intf = Interface(identifier=form.identifier.data,
                             mac=form.mac.data,
                             dhcpv4=True,
                             static_ipv4=form.reserved_ipv4.data,
                             machine_id=machine.id)
        db.session.add(new_intf)
        try:
            db.session.commit()
            flash('Interface added successfully', 'success')
        except IntegrityError as e:
            db.session.rollback()
            flash('Integrity Error: either MAC or reserved IP not unique',
                  'error')
            return redirect(url_for('.machine_admin', id=machine.id))
    else:
        flash_form_errors(form)

    return redirect(url_for('.machine_admin', id=machine.id))
def upgrade():
    bind = op.get_bind()
    session = Session(bind=bind)

    s = sa.sql.text('SELECT id, mac FROM machine').\
        columns(id=sa.Integer, mac=sa.String)
    for id, mac in session.execute(s):
        if mac and mac != '':
            intf = Interface(machine_id=id, mac=mac)
            session.add(intf)

    session.commit()
Exemplo n.º 4
0
def create_machines_admin():
    logger.info("Machine created by %s" % g.user.username)

    if not g.user.admin:
        flash('Permission denied', 'error')
        return redirect(url_for('.get_machines_admin'))

    logger.info("Machine added by %s" % g.user.username)
    form = validations.CreateMachineForm(request.form)
    validations.CreateMachineForm.populate_choices(form, g)
    if form.validate():
        # XXX: Think about adding a new object for PDU and Serial
        logger.info("after validation")
        new_machine = Machine(name=form.name.data,
                              bmc_id=form.bmc_id.data,
                              bmc_info=form.bmc_info.data,
                              pdu=form.pdu.data,
                              pdu_port=form.pdu_port.data,
                              serial=form.serial.data,
                              serial_port=form.serial_port.data,
                              netboot_enabled=False)
        db.session.add(new_machine)
        try:
            db.session.commit()
            flash('Machine added successfully', 'success')
        except IntegrityError as e:
            db.session.rollback()
            flash('Integrity Error: either name or MAC are not unique',
                  'error')
            return redirect(url_for('.get_machines_admin'))

        db.session.refresh(new_machine)

        for mac_field in form.macs:
            mac = mac_field.data
            if mac and mac != '':
                new_interface = Interface(machine_id=new_machine.id, mac=mac)
                db.session.add(new_interface)
                try:
                    db.session.commit()
                except IntegrityError as e:
                    db.session.rollback()
                    flash('Integrity Error: failed to add mac: %s' % mac,
                          'error')

    else:
        flash_form_errors(form)

    return redirect(url_for('.get_machines_admin'))
Exemplo n.º 5
0
 def post(self):
     if not session.get('username'):
         return redirect(url_for('login'))
     form = InterForm()
     project, models = get_pro_mo()
     if form.validate_on_submit and request.method == "POST":
         project_name = request.form.get('project')
         model_name = request.form.get('model')
         interface_name = request.form.get('interface_name')
         interface_url = request.form.get('interface_url')
         interface_meth = request.form.get('interface_meth')
         interface_par = request.form.get('interface_par')
         interface_bas = request.form.get('interface_bas')
         if project_name == None or model_name == None or interface_name == '' or interface_url == '' or interface_meth == '':
             flash(u'请完整填写接口的各项信息')
             return render_template('add_interface.html',
                                    form=form,
                                    projects=project,
                                    models=models)
         user_id = User.query.filter_by(
             username=session.get('username')).first().id
         project_id = Project.query.filter_by(
             project_name=project_name).first().id
         models_id = Model.query.filter_by(model_name=model_name).first().id
         try:
             new_interface = Interface(model_id=models_id,
                                       projects_id=project_id,
                                       Interface_name=interface_name,
                                       Interface_url=interface_url,
                                       Interface_meth=interface_meth,
                                       Interface_par=interface_par,
                                       Interface_back=interface_bas,
                                       Interface_user_id=user_id)
             db.session.add(new_interface)
             db.session.commit()
             flash(u'添加成功')
             return redirect(url_for('interface'))
         except:
             flash(u'添加失败')
             return render_template('add_interface.html',
                                    form=form,
                                    projects=project,
                                    models=models)
     return render_template('add_interface.html',
                            form=form,
                            projects=project,
                            models=models)
Exemplo n.º 6
0
def subnet():
    data = request.get_json(force=True)
    try:
        subnet_schema.validate(data)
    except SchemaError as e:
        return str(e), 400

    hwaddr = data['mac']
    if not hwaddr:
        abort(400)

    interface = Interface.by_mac(hwaddr)
    if not interface:
        abort(404)

    if not interface.network:
        abort(404)

    use_static = True if interface.static_ipv4 else False
    use_reserved = True if not use_static and interface.reserved_ipv4 else False

    expected_subnet = None
    if use_reserved:
        expected_subnet = ipaddress.IPv4Network(interface.network.reserved_net)

    logger.info('expected_subnet: %s' % expected_subnet)

    if expected_subnet is None:
        return jsonify({'subnetId': None}), 200

    response = {}

    for subnet in data['subnets']:
        net = ipaddress.IPv4Network((subnet['prefix'], subnet['prefixLen']))
        if net.overlaps(expected_subnet):
            response['subnetId'] = subnet['subnetId']
            logger.info('matched subnet: %s' % subnet)
            break

    return jsonify(response), 200
Exemplo n.º 7
0
def seen():
    data = request.get_json(force=True)
    try:
        seen_schema.validate(data)
    except SchemaError as e:
        return str(e), 400

    interface = Interface.by_mac(data['mac'])
    if interface:
        # Already assigned, don't care.
        return "", 200

    options = {o['option']: o['value'] for o in data['options']}

    info = {}

    info['mac_vendor'] = mac_vendor(data['mac'])

    if 12 in options:
        # hostname option
        info['hostname'] = options[12]

    if 93 in options:
        # processor architecture as per rfc4578
        code = options[93]
        info['arch_code'] = code
        info['arch'] = DHCP_ARCH_CODES.get(code, 'unknown')

    discovered_mac = DiscoveredMAC.by_mac(data['mac'])
    if discovered_mac:
        discovered_mac.info = info
        discovered_mac.last_seen = datetime.utcnow()
        db.session.commit()
    else:
        discovered_mac = DiscoveredMAC(mac=data['mac'], info=info)
        db.session.add(discovered_mac)
        db.session.commit()

    return "", 202
Exemplo n.º 8
0
def index():
    hwaddr = request.args.get('hwaddr')
    if not hwaddr:
        abort(400)

    machine = Machine.by_mac(hwaddr)
    if not machine:
        abort(404)

    interface = Interface.by_mac(hwaddr)
    if not interface:
        abort(404)

    # query param ?hwaddr=
    # response:
    # {
    #   "ipv4": "",
    #   "next-server": "",
    #   "options": [
    #     { "option": number, "value": "" }
    #   ]
    # }
    # option 67 is bootfile
    data = {
        'options': []
    }

    if machine.netboot_enabled:
        data['next-server'] = app.config['DHCP_TFTP_PROXY_HOST']
        data['options'].append({'option': 67, 'value': app.config['DHCP_DEFAULT_BOOTFILE']})

    use_static = True if interface.static_ipv4 else False

    if interface.reserved_ipv4 and not use_static:
        data['ipv4'] = interface.reserved_ipv4

    return jsonify(data), 200
Exemplo n.º 9
0
 def dispatch_request(self):
     if not session.get('username'):
         return redirect(url_for('login'))
     if request.method == 'POST':
         file = request.files['myfile']
         if file and '.' in file.filename and file.filename.split(
                 '.')[1] == 'xlsx':
             filename = 'jiekou.xlsx'
             file.save(filename)
             jiekou_bianhao, interface_name, project_nam, model_nam, interface_url, interface_meth, interface_par, interface_bas = pasre_inter(
                 filename)
             try:
                 for i in range(len(jiekou_bianhao)):
                     projects_id = Project.query.filter_by(
                         project_name=project_nam[i]).first().id
                     model_id = Model.query.filter_by(
                         model_name=project_nam[i]).first().id
                     new_interface = Interface(
                         projects_id=projects_id,
                         model_id=model_id,
                         Interface_name=str(interface_name[i]),
                         Interface_url=str(interface_url[i]),
                         Interface_meth=str(interface_meth[i]),
                         Interface_par=(interface_par[i]),
                         Interface_back=str(interface_bas[i]),
                         Interface_user_id=User.query.filter_by(
                             username=session.get('username')).first().id)
                     db.session.add(new_interface)
                 db.session.commit()
                 flash(u'导入成功')
                 return redirect(url_for('interface'))
             except:
                 flash(u'导入失败,请检查格式是否正确')
                 return render_template('daoru.html')
         flash(u'导入失败')
         return render_template('daoru.html')
     return render_template('daoru.html')
Exemplo n.º 10
0
    def Save(self, data):
        model = Interface()
        model.Id = data.get("Id", u'')
        model.Name = data.get("Name", u'')
        model.Monitor_id = data.get("Monitor", u'')
        model.Editor_id = data.get("Editor", u'')

        interface = self.Get(model.Id)
        status = self.Status(model, interface)
        if status is ModelStatus.New:
            model.Id = None
            model.save()
        elif status is ModelStatus.Modified:
            model.save()

        return model