示例#1
0
    def update_defaults(self, data):
        self._validate_defaults(data)

        # update default switch attributes
        for item in data[SWITCHES]:
            try:
                switch = Switch.objects.get(topology_id=self._top.id,
                                            dummy=True,
                                            tier=item[TIER])
            except Switch.DoesNotExist:
                # if tier default does not exist, create one
                switch = Switch()
                switch.topology = self._top
                switch.dummy = True
                switch.name = DEFAULT
                switch.tier = item[TIER]

            switch.model = get_switch(item[MODEL])
            switch.image_profile = get_profile(item[IMAGE_PROFILE])
            switch.save()

        # update default link attributes
        for item in data[LINKS]:
            link = Link.objects.get(topology_id=self._top.id,
                                    dummy=True,
                                    src_ports=item[SRC_TIER],
                                    dst_ports=item[DST_TIER])
            link.link_type = item[LINK_TYPE]
            link.num_links = item[NUM_LINKS]
            link.save()
示例#2
0
def create_switches(user_uid, machine_id):
    switch = Switch()
    switch.name = request.form['name']
    switch.telemarie_id = machine_id
    db.session.add(switch)
    db.session.commit()
    return redirect(f'/switch/{user_uid}/{machine_id}')
def lambda_handler(event, context):
    try:
        print(event)
        command, param = validate(event)
        light = None
        commandObj = None
        response = "Something wrong with your query.  How may I help you?"

        switch = Switch()

        if command == SlackCommand.ASSIGNED:
            light = CustomerQuery(param)
            commandObj = AssignedCommand(light)
        elif command == SlackCommand.APPLIED:
            light = CustomerQuery(param)
            commandObj = AppliedCommand(light)
        elif command == SlackCommand.SUBMITTED:
            light = CustomerQuery(param)
            commandObj = SubmittedCommand(light)
        elif command == SlackCommand.ALLPUBLIC:
            light = NoParamQuery()
            commandObj = AllPublicCommand(light)
        elif command == SlackCommand.WORKER:
            light = SimpleQuery(param)
            commandObj = WorkerCommand(light)
        if light and commandObj:
            response = switch.execute(commandObj)
        return response
    except Exception as e:
        print(e)
        return str(e)
        #{"text": "Something goes wrong"}
    finally:
        print('Check complete at {}'.format(str(datetime.now())))
示例#4
0
    def add_topology(self, data, user):
        logger.debug("topology name = %s, model = %s", data[NAME],
                     data[MODEL_NAME])

        self._validate_defaults(data[DEFAULTS])

        self._top = Topology()
        self._top.name = data[NAME]
        self._top.model_name = data[MODEL_NAME]
        self._top.is_fabric = False
        self._top.updated_by = user
        self._top.save()

        # defaults object
        self._top.defaults = dict()
        self._top.defaults[SWITCHES] = list()
        self._top.defaults[LINKS] = list()

        # add topology default switches with dummy=True
        for item in data[DEFAULTS][SWITCHES]:
            if item[MODEL] == 1:
                raise IgniteException(ERR_CAN_NOT_ASSIGN_UNKOWN_MODEL)

            switch = Switch()
            switch.topology = self._top
            switch.dummy = True
            switch.name = DEFAULT
            switch.tier = item[TIER]
            switch.model = get_switch(item[MODEL])
            switch.image_profile = get_profile(item[IMAGE_PROFILE])
            switch.save()

            # add switch to topology defaults
            self._top.defaults[SWITCHES].append(switch)

        # add topology default links with dummy=True
        for item in data[DEFAULTS][LINKS]:
            link = Link()
            link.topology = self._top
            link.dummy = True
            link.src_ports = item[SRC_TIER]  # store tier name in ports
            link.dst_ports = item[DST_TIER]  # store tier name in ports
            link.link_type = item[LINK_TYPE]
            link.num_links = item[NUM_LINKS]
            link.save()

            # need tier names in link object while returning
            link.src_tier = link.src_ports
            link.dst_tier = link.dst_ports

            # add link to topology defaults
            self._top.defaults[LINKS].append(link)

        # new topology has no switches or links
        self._top.switches = list()
        self._top.links = list()

        return self._top
示例#5
0
文件: arista.py 项目: denniswa/nerds
def parse_switch(data):
    switch_data = data['tailf-ncs:device']

    switch = Switch()
    switch.name = hostname_clean(switch_data['address'])
    switch.version = eos_version(
        find('config.tailf-ned-arista-dcs:boot.system',
             switch_data,
             default=''))
    return switch
示例#6
0
    def update_defaults(self, data):
        self._validate_defaults(data)

        # update default switch attributes
        for item in data[SWITCHES]:
            try:
                switch = Switch.objects.get(topology_id=self._top.id, dummy=True, tier=item[TIER])
            except Switch.DoesNotExist:
                # if tier default does not exist, create one
                switch = Switch()
                switch.topology = self._top
                switch.dummy = True
                switch.name = DEFAULT
                switch.tier = item[TIER]

            switch.model = get_switch(item[MODEL])
            switch.image_profile = get_profile(item[IMAGE_PROFILE])
            switch.save()

        # update default link attributes
        for item in data[LINKS]:
            link = Link.objects.get(
                topology_id=self._top.id, dummy=True, src_ports=item[SRC_TIER], dst_ports=item[DST_TIER]
            )
            link.link_type = item[LINK_TYPE]
            link.num_links = item[NUM_LINKS]
            link.save()
示例#7
0
    def add_topology(self, data, user):
        logger.debug("topology name = %s, model = %s", data[NAME], data[MODEL_NAME])

        self._validate_defaults(data[DEFAULTS])

        self._top = Topology()
        self._top.name = data[NAME]
        self._top.model_name = data[MODEL_NAME]
        self._top.is_fabric = False
        self._top.updated_by = user
        self._top.save()

        # defaults object
        self._top.defaults = dict()
        self._top.defaults[SWITCHES] = list()
        self._top.defaults[LINKS] = list()

        # add topology default switches with dummy=True
        for item in data[DEFAULTS][SWITCHES]:
            if item[MODEL] == 1:
                raise IgniteException(ERR_CAN_NOT_ASSIGN_UNKOWN_MODEL)

            switch = Switch()
            switch.topology = self._top
            switch.dummy = True
            switch.name = DEFAULT
            switch.tier = item[TIER]
            switch.model = get_switch(item[MODEL])
            switch.image_profile = get_profile(item[IMAGE_PROFILE])
            switch.save()

            # add switch to topology defaults
            self._top.defaults[SWITCHES].append(switch)

        # add topology default links with dummy=True
        for item in data[DEFAULTS][LINKS]:
            link = Link()
            link.topology = self._top
            link.dummy = True
            link.src_ports = item[SRC_TIER]  # store tier name in ports
            link.dst_ports = item[DST_TIER]  # store tier name in ports
            link.link_type = item[LINK_TYPE]
            link.num_links = item[NUM_LINKS]
            link.save()

            # need tier names in link object while returning
            link.src_tier = link.src_ports
            link.dst_tier = link.dst_ports

            # add link to topology defaults
            self._top.defaults[LINKS].append(link)

        # new topology has no switches or links
        self._top.switches = list()
        self._top.links = list()

        return self._top
示例#8
0
def get_default_discovery_switch(fab_id, tier):
    logger.debug("creating default switch")

    switch_default = Switch()
    switch_default.topology_id = fab_id
    switch_default.dummy = True
    switch_default.name = DEFAULT
    switch_default.tier = tier
    switch_default.model = get_switch(1)
    switch_default.image_profile = image.get_profile(1)
    switch_default.save()
    logger.debug("default switch created")
    return switch_default
def create_model(seq_size, n_features, switch_size, switch_reg,
                 switch_activation, use_batch_norm, dropout_rate, conv_size,
                 lstm_size, optimizer):
    # create model
    model = Sequential()

    model.add(
        Switch(switch_size,
               kernel_regularizer=switch_reg,
               activation=switch_activation,
               input_shape=(seq_size, n_features)))
    if use_batch_norm:
        model.add(BatchNormalization())
    if dropout_rate > 0:
        model.add(Dropout(dropout_rate))

    model.add(Conv1D(conv_size, kernel_size=5, padding='valid', strides=1))
    model.add(MaxPooling1D(pool_size=4))
    if use_batch_norm:
        model.add(BatchNormalization())
    if dropout_rate > 0:
        model.add(Dropout(dropout_rate))

    model.add(LSTM(lstm_size))
    if use_batch_norm:
        model.add(BatchNormalization())
    if dropout_rate > 0:
        model.add(Dropout(dropout_rate))

    model.add(
        Switch(switch_size,
               kernel_regularizer=switch_reg,
               activation=switch_activation))
    if use_batch_norm:
        model.add(BatchNormalization())
    if dropout_rate > 0:
        model.add(Dropout(dropout_rate))

    model.add(Dense(1))
    if use_batch_norm:
        model.add(BatchNormalization())
    model.add(Activation('sigmoid'))

    # Compile model
    model.compile(loss='binary_crossentropy',
                  optimizer=optimizer,
                  metrics=['accuracy', precision, recall, fmeasure])
    return model
示例#10
0
def switch_generate(index: int, domain: str) -> None:
    hostname = 'edge%d.%s' % (index, domain)
    vendor = faker.word(ext_word_list=switch_vendors)
    model = faker.word(ext_word_list=switch_models)
    mgmt_group = 'AFINC'

    switch_properties = {
        'ip': '10.0.%d.1' % index,
        'mac_address': faker.mac_address(),
        'hostname': hostname,
        'vendor': vendor,
        'model': model,
        'version': faker.word(ext_word_list=switch_versions),
        'mgmt_group': mgmt_group
    }
    # noinspection PyTypeChecker
    switch = Switch.create_or_update(switch_properties)[0]
    print('\t%s: Upserted' % switch.hostname)

    #
    # Make sure the switch has uplinks
    if len(switch.routers.all()) < 2:
        routers = Router.nodes.all()

        while len(switch.routers.all()) < 2:
            uplink_router = random.choice(routers)
            switch.routers.connect(uplink_router)
            switch.refresh()
            print('\t\tuplink created -> %s' % uplink_router.hostname)
示例#11
0
文件: views.py 项目: salran40/POAP
    def post(self, request, format=None):
        serializer = SwitchSerializer(data=request.data)
        if serializer.is_valid():

            swi_object = Switch()
            swi_object.model = serializer.data['model']
            swi_object.name = serializer.data['name']
            swi_object.image = serializer.data['image']
            swi_object.slots = serializer.data['slots']
            swi_object.tier = serializer.data['tier']
            swi_object.line_cards = str(serializer.data['line_cards'])
            swi_object.save()

            serializer = SwitchGetSerializer(swi_object)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#12
0
def get_default_discovery_switch(fab_id, tier):
    logger.debug("creating default switch")

    switch_default = Switch()
    switch_default.topology_id = fab_id
    switch_default.dummy = True
    switch_default.name = DEFAULT
    switch_default.tier = tier
    switch_default.model = get_switch(1)
    switch_default.image_profile = image.get_profile(1)
    switch_default.save()
    logger.debug("default switch created")
    return switch_default
示例#13
0
    def post(self, request, format=None):
        serializer = SwitchSerializer(data=request.data)
        if serializer.is_valid():

            swi_object = Switch()
            swi_object.model = serializer.data['model']
            swi_object.name = serializer.data['name']
            swi_object.image = serializer.data['image']
            swi_object.slots = serializer.data['slots']
            swi_object.tier = serializer.data['tier']
            swi_object.line_cards = str(serializer.data['line_cards'])
            swi_object.save()
            
            serializer = SwitchGetSerializer(swi_object)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#14
0
def SaveSwitch(lst):
    try:
        logok = ''
        logero = ''
        first_sheet = lst.sheet_by_index(0)
        for r in range(1, first_sheet.nrows):
            m = ServerInfo.objects.get(IP=first_sheet.cell(r, 4).value).id
            chk = Switch.objects.filter(Server_id=m).exists()
            if chk == False:
                sv = Switch(
                    SwitchIP=first_sheet.cell(r, 0).value,
                    SwitchType=first_sheet.cell(r, 1).value,
                    SwitchPort=first_sheet.cell(r, 2).value,
                    SwitchLocation=first_sheet.cell(r, 3).value,
                    Server_id=m,
                )
                sv.save()
                logok += first_sheet.cell(r, 4).value.encode("utf-8") + '/'
            elif chk == True:
                logero += first_sheet.cell(r, 4).value.encode("utf-8") + '/'

        return {'y0': logok, 'y1': logero}
    except:
        return False
示例#15
0
    def _add_switch(self, tier, index=0):
        if not index:
            index = self._get_next_index(tier)

        # create new switch
        switch = Switch()
        switch.topology = self._top
        switch.dummy = False
        switch.tier = tier

        # get switch model from tier default
        default = Switch.objects.get(topology_id=self._top.id,
                                     tier=tier,
                                     dummy=True)
        switch.model = default.model

        # new switch name = fabric prefix (if any) + tier + index
        if self._top.is_fabric:
            switch.name = self._top.name + "_" + tier + str(index)
        else:
            switch.name = tier + str(index)

        switch.save()
        self._add_auto_links(switch)
示例#16
0
    def _add_switch(self, tier, index=0):
        if not index:
            index = self._get_next_index(tier)

        # create new switch
        switch = Switch()
        switch.topology = self._top
        switch.dummy = False
        switch.tier = tier

        # get switch model from tier default
        default = Switch.objects.get(topology_id=self._top.id, tier=tier, dummy=True)
        switch.model = default.model

        # new switch name = fabric prefix (if any) + tier + index
        if self._top.is_fabric:
            switch.name = self._top.name + "_" + tier + str(index)
        else:
            switch.name = tier + str(index)

        switch.save()
        self._add_auto_links(switch)
示例#17
0
    def post(self):
        switch_args = switch_parser.parse_args()

        if 'id' not in switch_args:
            highest = Switch.query.order_by(Switch.id).last()
            switch_id = highest + 1
        else:
            switch_id = switch_args['id']

        switch = Switch(id=switch_id,state=switch_args['state'],block_id=switch_args['block_id'])
        block = Block.query.filter_by(id=switch_args['block_id']).first()
        if not block:
            abort(404, "Block %d: not found." % switch_args['block_id'])
        block.switch_id = switch_id

        db.session.add(switch)
        db.session.commit()

        return switch, 201
示例#18
0
def testdb_command():
    db.drop_all()
    db.create_all()

    block1 = Block(id=1,
                   number=1,
                   line="green",
                   length=100.0,
                   grade=0.5,
                   speedLimit=55,
                   elevation=0.5,
                   cumulative_elevation=0.5,
                   occupancy=False)
    db.session.add(block1)

    tcBlock1 = TrackControllerBlock(id=1,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock1)

    block2 = Block(id=2,
                   number=2,
                   line="green",
                   length=100.0,
                   grade=1.0,
                   speedLimit=55,
                   elevation=1.0,
                   cumulative_elevation=1.5,
                   occupancy=False)
    db.session.add(block2)

    tcBlock2 = TrackControllerBlock(id=2,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock2)

    block3 = Block(id=3,
                   number=3,
                   line="green",
                   length=100.0,
                   grade=1.5,
                   speedLimit=55,
                   elevation=1.5,
                   cumulative_elevation=3.0,
                   occupancy=False)
    db.session.add(block3)

    tcBlock3 = TrackControllerBlock(id=3,
                                    occupancy=False,
                                    maintenance=False,
                                    broken=False)
    db.session.add(tcBlock3)

    switch1 = Switch(id=1, state=False)
    db.session.add(switch1)
    block1.switch = switch1

    crossing1 = Crossing(id=1, state=False)
    db.session.add(crossing1)
    block3.crossing = crossing1

    station1 = Station(id=1, name="Station 1")
    db.session.add(station1)
    block2.station = station1

    light1 = Light(id=1, state=False)
    db.session.add(light1)
    light2 = Light(id=2, state=False)
    db.session.add(light1)

    switch1.lights.append(light1)
    switch1.lights.append(light2)

    # block1.message = "hello"

    train1 = Train(id=1,
                   name="train1",
                   length=1000.0,
                   width=100.0,
                   height=100.0,
                   mass=1000.0,
                   crewCount=0,
                   passengerCount=0)
    db.session.add(train1)
    train1.front_block = block1
    # block1.train_id = block1.front_train.id

    msg1 = Message(id=1, text="50,GO")
    db.session.add(msg1)
    msg1.block = block1
    msg1.train = train1

    msg2 = Message(id=2, text="100,GO")
    db.session.add(msg2)
    msg2.block = block2

    msg3 = Message(id=3, text="0,STOP")
    db.session.add(msg3)
    msg3.block = block3

    request = CTCRequest(id=0, type=0, input="")
    db.session.add(request)

    db.session.commit()

    # user1 = User(username='******', password='******')
    # db.session.add(user1)
    #
    # chatroom1 = ChatRoom(name='Super Awesome Chat Room')
    # db.session.add(chatroom1)
    #
    # user1.created_rooms.append(chatroom1)
    #
    # message1 = Message(creator=user1.username,text="Hello, there!", chatroom=chatroom1.name)
    # db.session.add(message1)
    # db.session.commit()

    print('Initialized the testing database.')
示例#19
0
def add_discovered_switches(fab_id, tiers, switch_with_ip):
    from bootstrap import bootstrap
    logger.debug("Adding discovered switches in fabric")
    switch_id_details = dict()
    switch_id_details[SPINE] = dict()
    switch_id_details[LEAF] = dict()
    switch_id_details[CORE] = dict()
    switch_id_details[BORDER] = dict()
    for spine_switch in tiers[SPINE]:
        logger.debug("Adding spine switch:%s in fabric", spine_switch[0])
        switch = Switch()
        switch.tier = SPINE
        switch.name = spine_switch[0]
        switch.dummy = False
        switch.serial_num = spine_switch[1]
        find_duplicate([spine_switch[1]])
        switch.topology_id = fab_id
        switch.mgmt_ip = switch_with_ip[spine_switch[0]]
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                      match_type=DISCOVERY,
                                      discovery_rule=None,
                                      boot_time=timezone.now(),
                                      boot_status=BOOT_SUCCESS,
                                      model_type='')
        logger.debug("Spine added")
        switch_id_details[SPINE][spine_switch[0]] = switch.id
    for leaf_switch in tiers[LEAF]:
        logger.debug("Adding leaf switch:%s to fabric", leaf_switch[0])
        switch = Switch()
        switch.tier = LEAF
        switch.name = leaf_switch[0]
        switch.serial_num = leaf_switch[1]
        find_duplicate([leaf_switch[1]])
        switch.topology_id = fab_id
        switch.mgmt_ip = switch_with_ip[leaf_switch[0]]
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                      match_type=DISCOVERY,
                                      discovery_rule=None,
                                      boot_time=timezone.now(),
                                      boot_status=BOOT_SUCCESS,
                                      model_type='')
        logger.debug("Leaf added")
        switch_id_details[LEAF][leaf_switch[0]] = switch.id
    for core_switch in tiers[CORE]:
        logger.debug("Adding core switch:%s in fabric", core_switch)
        switch = Switch()
        switch.tier = CORE
        switch.name = core_switch
        switch.dummy = False
        switch.topology_id = fab_id
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                      match_type=DISCOVERY,
                                      discovery_rule=None,
                                      boot_time=timezone.now(),
                                      boot_status=BOOT_SUCCESS,
                                      model_type='')
        logger.debug("core added")
        switch_id_details[CORE][core_switch] = switch.id
    for border_switch in tiers[BORDER]:
        logger.debug("Adding border switch:%s in fabric", border_switch)
        switch = Switch()
        switch.tier = BORDER
        switch.name = border_switch
        switch.dummy = False
        switch.topology_id = fab_id
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                      match_type=DISCOVERY,
                                      discovery_rule=None,
                                      boot_time=timezone.now(),
                                      boot_status=BOOT_SUCCESS,
                                      model_type='')
        logger.debug("Border added")
        switch_id_details[BORDER][border_switch] = switch.id

    return switch_id_details
示例#20
0
def add_discovered_switches(fab_id, tiers, switch_with_ip):
    from bootstrap import bootstrap
    logger.debug("Adding discovered switches in fabric")
    switch_id_details = dict()
    switch_id_details[SPINE] = dict()
    switch_id_details[LEAF] = dict()
    switch_id_details[CORE] = dict()
    switch_id_details[BORDER] = dict()
    for spine_switch in tiers[SPINE]:
        logger.debug("Adding spine switch:%s in fabric", spine_switch[0])
        switch = Switch()
        switch.tier = SPINE
        switch.name = spine_switch[0]
        switch.dummy = False
        switch.serial_num = spine_switch[1]
        find_duplicate([spine_switch[1]])
        switch.topology_id = fab_id
        switch.mgmt_ip = switch_with_ip[spine_switch[0]]
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                     match_type=DISCOVERY,
                                     discovery_rule=None,
                                     boot_time=timezone.now(),
                                     boot_status=BOOT_SUCCESS,
                                     model_type='')
        logger.debug("Spine added")
        switch_id_details[SPINE][spine_switch[0]] = switch.id
    for leaf_switch in tiers[LEAF]:
        logger.debug("Adding leaf switch:%s to fabric", leaf_switch[0])
        switch = Switch()
        switch.tier = LEAF
        switch.name = leaf_switch[0]
        switch.serial_num = leaf_switch[1]
        find_duplicate([leaf_switch[1]])
        switch.topology_id = fab_id
        switch.mgmt_ip = switch_with_ip[leaf_switch[0]]
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                     match_type=DISCOVERY,
                                     discovery_rule=None,
                                     boot_time=timezone.now(),
                                     boot_status=BOOT_SUCCESS,
                                     model_type='')
        logger.debug("Leaf added")
        switch_id_details[LEAF][leaf_switch[0]] = switch.id
    for core_switch in tiers[CORE]:
        logger.debug("Adding core switch:%s in fabric", core_switch)
        switch = Switch()
        switch.tier = CORE
        switch.name = core_switch
        switch.dummy = False
        switch.topology_id = fab_id
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                     match_type=DISCOVERY,
                                     discovery_rule=None,
                                     boot_time=timezone.now(),
                                     boot_status=BOOT_SUCCESS,
                                     model_type='')
        logger.debug("core added")
        switch_id_details[CORE][core_switch] = switch.id
    for border_switch in tiers[BORDER]:
        logger.debug("Adding border switch:%s in fabric", border_switch)
        switch = Switch()
        switch.tier = BORDER
        switch.name = border_switch
        switch.dummy = False
        switch.topology_id = fab_id
        switch.model = SwitchModel.objects.get(id=1)
        switch.save()
        bootstrap.update_boot_detail(switch,
                                     match_type=DISCOVERY,
                                     discovery_rule=None,
                                     boot_time=timezone.now(),
                                     boot_status=BOOT_SUCCESS,
                                     model_type='')
        logger.debug("Border added")
        switch_id_details[BORDER][border_switch] = switch.id

    return switch_id_details