Ejemplo n.º 1
0
    def monitor_events(self):
        self.log("Started CPS events listener...")
        interfaces_key = cps.key_from_name(
            'observed', 'dell-base-if-cmn/if/interfaces-state/interface')

        handle = cps.event_connect()
        cps.event_register(handle, interfaces_key)

        while True:
            o = cps.event_wait(handle)
            obj = cps_object.CPSObject(obj=o)

            # Monitor interfaces
            if interfaces_key == obj.get_key():

                list = []
                cps.get([
                    cps.key_from_name(
                        'observed',
                        'dell-base-if-cmn/if/interfaces-state/interface')
                ], list)
                # Ignore the first entry
                for entry in list[1:]:
                    # Construct a new object for each entry
                    get_obj = cps_object.CPSObject(obj=entry)
                    if (obj.get_attr_data("if/interfaces-state/interface/name")
                            == get_obj.get_attr_data(
                                "if/interfaces-state/interface/name")):

                        oper_status = get_obj.get_attr_data(
                            "if/interfaces-state/interface/oper-status")
                        # ...

                        new_list = []
                        cps.get([
                            cps.key_from_name(
                                'target',
                                'dell-base-if-cmn/if/interfaces/interface')
                        ], new_list)

                        # Ignore the first entry
                        for aux_entry in new_list[1:]:
                            # Construct a new object for each entry
                            get_aux_obj = cps_object.CPSObject(obj=aux_entry)

                            if (get_aux_obj.get_attr_data(
                                    "if/interfaces/interface/name") ==
                                    obj.get_attr_data(
                                        "if/interfaces-state/interface/name")):
                                if_name = get_aux_obj.get_attr_data(
                                    "if/interfaces/interface/name")
                                #enabled = get_aux_obj.get_attr_data("if/interfaces/interface/enabled")
                                Utils.cliLogger(if_name, 1)
                                Utils.cliLogger(0, 1)
                                interface = Interface(if_name, "", 0, "", "",
                                                      oper_status, "", "", "")
                                Utils.timeLogger(
                                    "EventHandler| CPS event Operstatus changed: "
                                )
                                q.put((dh.change_interface, (interface, ), {}))
Ejemplo n.º 2
0
def _register_ev(qual, obj):
    # Listen for cps/node-group events
    _key = cps.key_from_name(qual, obj)
    handle = cps.event_connect()

    cps.event_register(handle, _key)

    t = threading.Thread(target=_ev_wait_node_grp, args=(handle, )).start()
Ejemplo n.º 3
0
def monitor_media_event():
    handle = cps.event_connect()
    nas_if.log_info(" registering for media")
    cps.event_register(handle, cps.key_from_name('observed', 'base-pas/media'))

    while True:
        media = cps.event_wait(handle)
        obj = cps_object.CPSObject(obj=media)
        set_media_info(obj)
Ejemplo n.º 4
0
    def getData(self, threshold=None):
        if self.power_enabled == False:
            return 0, 0

        def getCpsValue(eType, data):
            return cps_utils.cps_attr_types_map.from_data(eType, data[eType])

        total = 0
        psuData = {}
        numFaults = 0
        cpsData = []
        fanTrayData = []
        cps.get([cps.key_from_name('observed', CPS_KEY)], cpsData)
        cps.get([cps.key_from_name('observed', CPS_FT_KEY)], fanTrayData)
        for e in cpsData:
            entity_data = e['data']
            eType = getCpsValue(CPS_TYPE, entity_data)
            if eType != 1:
                continue
            slot = getCpsValue(CPS_SLOT, entity_data)
            fan_tray_found = False
            for p in fanTrayData:
                fan_tray_data = p['data']
                if getCpsValue(CPS_FT_SLOT, fan_tray_data) == slot:
                    fan_tray_found = True
                    break
            if not fan_tray_found:
                continue
            present = ftPresent(getCpsValue(CPS_PRESENT, entity_data))
            state = opStatusToString(getCpsValue(CPS_STATE, entity_data))
            fault = getCpsValue(CPS_FAULT, entity_data)
            psuData[slot] = {PRESENT: present, STATE: state, FAULT: fault}
            total += 1
            if state != 'Up':
                numFaults += 1

        self.psuData = psuData
        if threshold is not None:
            self.threshold = threshold
        else:
            self.threshold = self.data
        self.timechk = time.time()

        return numFaults, total
Ejemplo n.º 5
0
def _send_obj_to_base(cps_obj,op):
    nas_if.log_info('Sending vlan sub interface object to base')
    in_obj = copy.deepcopy(cps_obj)
    in_obj.set_key(cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces/interface'))
    obj = in_obj.get()
    if 'operation' in obj:
        del obj['operation']
    upd = (op, obj)
    _ret = cps_utils.CPSTransaction([upd]).commit()
    if not _ret:
        nas_if.log_err('BASE transaction for vlan sub interface failed')
        return False
    return True
Ejemplo n.º 6
0
def _handle_global_vlan_config(obj):
    nas_if.log_info('Updating global default vlan container')
    in_obj = copy.deepcopy(obj)
    in_obj.set_key(cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces'))
    in_obj.root_path = 'dell-base-if-cmn/if/interfaces' + '/'
    obj = in_obj.get()
    if nas_comm.yang.get_value('op', 'attr_name') in obj['data']:
        del obj['data'][nas_comm.yang.get_value('op', 'attr_name')]
    upd = ('set', obj)
    _ret = cps_utils.CPSTransaction([upd]).commit()
    if not _ret:
        nas_if.log_err('Failed to update global default vlan scale/id')
        return False
    return True
Ejemplo n.º 7
0
    def getChassisMac():

        list = []
        # Obtain a list with objects from dell-base-if-cmn/if/interfaces/interface
        cps.get([cps.key_from_name('target', 'base-pas/chassis')], list)

        # Ignore the first entry
        for entry in list:
            # Construct a new object for each entry
            get_obj = cps_object.CPSObject(obj=entry)

            phys_address = get_obj.get_attr_data("base_mac_addresses")
            Utils.cliLogger("Chassis MAC: " + phys_address, 1)
            return phys_address
Ejemplo n.º 8
0
def _handle_global_vlan_config(obj):
    nas_if.log_err('Updating global default vlan mode')
    in_obj = copy.deepcopy(obj)
    in_obj.set_key(cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces'))
    in_obj.root_path = 'dell-base-if-cmn/if/interfaces' + '/'
    obj = in_obj.get()
    print obj
    if op_attr_name in obj['data']:
        del obj['data'][op_attr_name]
    upd = ('set', obj)
    _ret = cps_utils.CPSTransaction([upd]).commit()
    if not _ret:
        nas_if.log_err('Failed to update global default vlan mode')
        return False
    return True
Ejemplo n.º 9
0
    def getIfIndexFromName(name):

        list = []
        # Obtain a list with objects from dell-base-if-cmn/if/interfaces/interface
        cps.get([
            cps.key_from_name('target',
                              'dell-base-if-cmn/if/interfaces/interface')
        ], list)

        # Ignore the first entry
        for entry in list[1:]:
            # Construct a new object for each entry
            get_obj = cps_object.CPSObject(obj=entry)
            if (get_obj.get_attr_data("if/interfaces/interface/name") == name):
                return get_obj.get_attr_data(
                    "dell-base-if-cmn/if/interfaces/interface/if-index")
Ejemplo n.º 10
0
def test_all():
    #Get platform type from PAS and run appropriate test suite
    d = []
    cps.get([cps.key_from_name('observed','base-pas/chassis')], d)
    product_name = cps_attr_get(d[0]['data'], 'base-pas/chassis/product-name')

    if product_name not in test_suites:
        prGreen("Hybrid Group is not supported on platform " + str(product_name) + ", Bypass the test for this platform")
        return True

    tests = test_suites[product_name]

    idx = 1
    while(idx <= len(tests)):
        tests[idx]()
        #raw_input("Press Enter to continue...")
        idx += 1
Ejemplo n.º 11
0
def _send_obj_to_base(cps_obj, op):
    nas_if.log_info('Sending bridge object to base')
    in_obj = copy.deepcopy(cps_obj)
    in_obj.set_key(cps.key_from_name('target', 'bridge-domain/bridge'))
    obj = in_obj.get()

    if 'operation' in obj:
        del obj['operation']

    if op in ['update', 'add-member', 'delete-member']:
        op = 'set'

    upd = (op, obj)
    _ret = cps_utils.CPSTransaction([upd]).commit()
    if not _ret:
        nas_if.log_err('BASE transaction for vlan sub interface failed')
        return False
    return True
Ejemplo n.º 12
0
def _get_obj_from_input():
    if (len(sys.argv) < 2):
        return None

    _qual_list = cps.QUALIFIERS
    _obj = cps_object.CPSObject(module="cps", qual="target")

    _inp = sys.argv[1].lower()
    _lst = _inp.split(cps.PATH_SEP, 1)

    #Only 'qualifier' provided as first argument
    if len(_lst) == 1:
        in_qual = _lst[0]
        if in_qual not in cps.QUALIFIERS:
            print "\nCheck the qualifier, not a valid qualifier "
            return None
        #Second argument is the 'module'
        if len(sys.argv) == 3:
            _key = cps.key_from_name(in_qual, sys.argv[2])
        else:
            _key = cps.key_from_qual(in_qual)
        _obj.set_key(_key)
        print " Registering for " + _key
    else:
        try:
            _obj = cps_object.object_from_parameters(prog='cps_trace_events',
                                                     description="")
        except ValueError:
            return None
        _key = _obj.get_key()
        print " Registering for object ..."
        cps_utils.print_obj(_obj.get())
    print "----------------------------------"

    if ((_key == "") or (_key == None)):
        print "Check the object name, not a valid object\n"
        return None

    return _obj
Ejemplo n.º 13
0
    def __init__(self, module="", qual="target", data={}, obj={}):
        """
        Constructor to create a CPS object.
        @module - module key string, can be empty in case of
                  providing get object as parameter
        @qual - CPS qualifier (by default set to 'target')
        @data - data is a dictionary which can contain attr_str and
                values which will be added to object
        @obj  - object received from 'cps.get' function call, CPS object
                will be created from that object
        """

        self.obj = {'key': '', 'data': {}}
        self.root_path = ""
        self.embed_dict = {}
        self.properties = {}

        if module:
            self.root_path = module + "/"
            self.obj['key'] = cps.key_from_name(qual, module)
            self.root_path = module + "/"

        for key, val in data.items():
            self.add_attr(key, val)

        if len(obj) > 0:
            if 'key' not in obj or 'data' not in obj:
                return None
            self.obj = deepcopy(obj)
            if len(obj['data'].keys()) > 0:
                for key in obj['data'].keys():
                    if key != 'cps/key_data':
                        self.root_path = "/".join(key.split("/")[:-1]) + "/"
                        return

        if not self.obj['key']:
            raise ValueError(
                "Invalid Module Name or object doesn't have the key")
Ejemplo n.º 14
0
    def __init__(self, module="", qual="target", data={}, obj={}):
        """
        Constructor to create a CPS object.
        @module - module key string, can be empty in case of
                  providing get object as parameter
        @qual - CPS qualifier (by default set to 'target')
        @data - data is a dictionary which can contain attr_str and
                values which will be added to object
        @obj  - object received from 'cps.get' function call, CPS object
                will be created from that object
        """

        self.obj = {'key': '', 'data': {}}
        self.root_path = ""
        self.embed_dict = {}

        if module:
            self.root_path = module + "/"
            self.obj['key'] = cps.key_from_name(qual, module)
            self.root_path = module + "/"

        for key, val in data.items():
            self.add_attr(key, val)

        if len(obj) > 0:
            if 'key' not in obj or 'data' not in obj:
                return None
            self.obj = deepcopy(obj)
            if len(obj['data'].keys()) > 0:
                for key in obj['data'].keys():
                    if key != 'cps/key_data':
                        self.root_path = "/".join(key.split("/")[:-1]) + "/"
                        return

        if not self.obj['key']:
            raise ValueError(
                "Invalid Module Name or object doesn't have the key")
Ejemplo n.º 15
0
def main():
    '''Run the dhcp agent'''
    def get_cb(method, params):
        '''CPS get callback'''
        logging.debug("Get CB invoked with %s", "{}".format(params))
        fobj = cps_object.CPSObject(obj=params['filter'])
        params['list'].extend(agent.get(fobj.get()))
        return True

    def trans_cb(method, params):
        '''CPS transaction callback'''
        logging.debug("Trans CB invoked with %s", "{}".format(params))
        return agent.transaction(params['change'])

    agent = None
    cps_utils.add_attr_type('dhcp-agent/if/interfaces/interface/dhcp-server',
                            'ipv4')
    aparser = ArgumentParser(description=main.__doc__)
    aparser.add_argument(
        '--file',
        help='the file containing the dhcp agent config if used in mock mode',
        type=str)
    aparser.add_argument('--verbose', help='verbosity level', type=int)
    args = vars(aparser.parse_args())
    if args.get('verbose') is not None:
        logging.getLogger().setLevel(logging.DEBUG)
    agent = Agent(mock=args.get("file"))
    dict_cb = {"get": get_cb, "transaction": trans_cb}

    # disable cps pylint warnings - they are spurious
    # pylint: disable=no-member
    handle = cps.obj_init()
    # pylint: disable=no-member
    cps.obj_register(handle, cps.key_from_name("target", DHCPPATH_P), dict_cb)

    agent.main_loop()
Ejemplo n.º 16
0
import cps_utils
import ifindex_utils

import dn_base_ip_tool

from traceback import print_exc


iplink_cmd = '/sbin/ip'

_name_field = 'base-interface/entry/name'
_ifindex_field = 'base-interface/entry/ifindex'

_keys = {
    'base-interface/entry':
    cps.key_from_name('target', 'base-interface/entry'),
    cps.key_from_name('target', 'base-interface/entry'): 'base-interface/entry',
}


def _get_name_from_obj(obj):
    try:
        name = obj.get_attr_data(_name_field)
        if len(name) > 0:
            return name
    except:
        pass
    index = None
    try:
        index = obj.get_attr_data(_ifindex_field)
        return ifindex_utils.if_indextoname(index)
Ejemplo n.º 17
0

def get_cb(methods, params):
    return False


def trans_cb(methods, params):
    if params['operation'] == 'rpc':
        cmd = params['change']['data'][
            'base-switch/diag_shell/input/command'].decode("utf-8")
        resp = run_shell_cmd(cmd).encode("utf-8")
        params['change']['data']['base-switch/diag_shell/output/result'] = resp
    else:
        print "Invalid operation requested."

    return True

if __name__ == '__main__':
    if len(sys.argv) > 1:
        print run_shell_cmd(sys.argv[1])
        sys.exit(0)

    handle = cps.obj_init()
    d = {}
    d['get'] = get_cb
    d['transaction'] = trans_cb
    key = cps.key_from_name('target', 'base-switch/diag_shell')
    cps.obj_register(handle, key, d)
    while True:
        time.sleep(1)
    if params['operation'] == 'create':
        port = handle_create(obj,group_name)
        if port:
            params['change']['data']['cps/db-instance/port'] = ba.str_to_ba(str(port),len(str(port)))
            return True
        else:
            return False

    if params['operation'] == 'delete':
        return handle_delete(obj,group_name)

    return False

def get_db_cb(methods, params):
    return False

if __name__ == '__main__':

    handle = cps.obj_init()

    d = {}
    d['get'] = get_db_cb
    d['transaction'] = set_db_cb

    # Should create a new objet in cps model or use something internal
    cps.obj_register(handle, cps.key_from_name("target","cps/db-instance"), d)


    while True:
        time.sleep(1)
import cps
import cps_utils

#  Example   GET  request cps_get_response   =  []
cps.get([cps.key_from_name('observed', 'base-pas/chassis')], cps_get_response)

chassis_vendor_name = cps_attr_get(cps_get_response[0]['data'],
                                   'base-pas/chassis/vendor-name')
Ejemplo n.º 20
0
import cps
import subprocess
import sys
import time
import cps_object
import cps_utils
import socket
import binascii
import ifindex_utils

import dn_base_ip_tool

iplink_cmd = '/sbin/ip'

_keys = {
    'base-ip/ipv4': cps.key_from_name('target', 'base-ip/ipv4'),
    'base-ip/ipv6': cps.key_from_name('target', 'base-ip/ipv6'),
    'base-ip/ipv4/address':
    cps.key_from_name('target', 'base-ip/ipv4/address'),
    'base-ip/ipv6/address':
    cps.key_from_name('target', 'base-ip/ipv6/address'),
    cps.key_from_name('target', 'base-ip/ipv4'): 'base-ip/ipv4',
    cps.key_from_name('target', 'base-ip/ipv6'): 'base-ip/ipv6',
    cps.key_from_name('target', 'base-ip/ipv4/address'): 'base-ip/ipv4/address',
    cps.key_from_name('target', 'base-ip/ipv6/address'): 'base-ip/ipv6/address',
}


def get_next_index(d):
    count = 0
    while True:
Ejemplo n.º 21
0
# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.

import cps_object
import cps
import nas_common_header as nas_comm
import nas_os_if_utils as nas_if

hg_state_key = cps.key_from_name(
    'observed', 'base-pg/dell-pg/port-groups-state/hybrid-group-state')
hg_key = cps.key_from_name('target',
                           'base-pg/dell-pg/port-groups/hybrid-group')


def hg_attr(t):
    return 'dell-pg/port-groups/hybrid-group/' + t


def base_hg_attr(t):
    return 'base-pg/' + hg_attr(t)


def hg_state_attr(t):
    return 'dell-pg/port-groups-state/hybrid-group-state/' + t
Ejemplo n.º 22
0
# Python code block to register for events

import cps

# Create handle to connect to event service
handle = cps.event_connect()

# Regidter key with event service
cps.event_register(handle, cps.key_from_name('observed',
                                             'base-port/interface'))
while True:
    obj = cps.event_wait(handle)
    print obj
Ejemplo n.º 23
0
import cps_utils
import cps_object
import systemd.daemon
import dn_base_mcast_snoop_utils as mcast_utils
import dn_base_mcast_snoop as mcast_snoop
import time
import event_log as ev
import logging
import os as mcast_os
import threading

key_prefix = 'igmp-mld-snooping/rt/routing-state/control-plane-protocols/'
ip_types = {'igmp-snooping': 'ipv4', 'mld-snooping': 'ipv6'}

snoop_state_keys = {key_prefix + x + '/' + 'vlans/vlan': (
        cps.key_from_name('observed', key_prefix + x + '/' + 'vlans/vlan'), ip_types[x]) \
    for x in ip_types}

_igmp_keys = {
               "igmp-mld-snooping/rt/routing/control-plane-protocols/igmp-snooping/global":
               cps.key_from_name("target", "igmp-mld-snooping/rt/routing/control-plane-protocols/igmp-snooping/global"),
               "igmp-mld-snooping/rt/routing/control-plane-protocols/mld-snooping/global":
               cps.key_from_name("target", "igmp-mld-snooping/rt/routing/control-plane-protocols/mld-snooping/global"),
               "igmp-mld-snooping/rt/routing/control-plane-protocols/igmp-snooping/vlans/vlan":
               cps.key_from_name("target", "igmp-mld-snooping/rt/routing/control-plane-protocols/igmp-snooping/vlans/vlan"),
               "igmp-mld-snooping/rt/routing/control-plane-protocols/mld-snooping/vlans/vlan":
               cps.key_from_name("target", "igmp-mld-snooping/rt/routing/control-plane-protocols/mld-snooping/vlans/vlan"),
                "igmp-mld-snooping/rt/routing-state/control-plane-protocols/igmp-snooping/vlans/vlan":
                cps.key_from_name("observed", "igmp-mld-snooping/rt/routing-state/control-plane-protocols/igmp-snooping/vlans/vlan"),
                 "igmp-mld-snooping/rt/routing-state/control-plane-protocols/igmp-snooping/vlans":
                 cps.key_from_name("observed", "igmp-mld-snooping/rt/routing-state/control-plane-protocols/igmp-snooping/vlans")
Ejemplo n.º 24
0
def set_intf_rpc_cb(methods, params):
    if params['operation'] != 'rpc':
        nas_if.log_err('Operation '+str(params['operation'])+' not supported')
        return False
    cps_obj = cps_object.CPSObject(obj = params['change'])

    try:
        if def_vlan_mode_attr_name in params['change']['data']:
            return _handle_global_vlan_config(cps_obj)
    except:
        pass

    if_type = if_config.get_intf_type(cps_obj)
    if if_type == 'loopback':
        return _handle_loopback_intf(cps_obj, params)
    elif if_type == 'management':
        return False
    elif if_type == 'macvlan':
        return _handle_macvlan_intf(cps_obj, params)

    op = _get_op_id(cps_obj)
    if op is None:
        return False

    member_port = None
    try:
        member_port = cps_obj.get_attr_data('dell-if/if/interfaces/interface/member-ports/name')
    except ValueError:
        member_port = None

    have_fp_attr = True
    front_panel_port = None
    try:
        front_panel_port = cps_obj.get_attr_data(fp_port_attr_name)
    except ValueError:
        have_fp_attr = False

    if_name = nas_if.get_cps_attr(cps_obj, ifname_attr_name)
    nas_if.log_info('Logical interface configuration: op %s if_name %s if_type %s' % (
                     op, if_name if if_name != None else '-', if_type))
    if ((op == 'create' or (op == 'set' and have_fp_attr == True and front_panel_port is not None))
        and member_port is None):
        if op == 'set' and if_type is None:
            # For set operation, if front_panel_port is given, if_type should be front-panel
            if_type = 'front-panel'
        nas_if.log_info('Interface MAC address setup for type %s' % if_type)
        try:
            mac_addr = cps_obj.get_attr_data(mac_attr_name)
        except ValueError:
            mac_addr = None
        if mac_addr is None:
            nas_if.log_info('No mac address given in input object, get assigned mac address')
            try:
                param_list = get_alloc_mac_addr_params(if_type, cps_obj)
            except Exception:
                logging.exception('Failed to get params')
                return False
            if param_list != None:
                try:
                    mac_addr = ma.if_get_mac_addr(**param_list)
                except:
                    logging.exception('Failed to get mac address')
                    return False
                if mac_addr is None:
                    nas_if.log_err('Failed to get mac address')
                    return False
                if len(mac_addr) > 0:
                    nas_if.log_info('Assigned mac address: %s' % mac_addr)
                    cps_obj.add_attr(mac_attr_name, mac_addr)

    if op == 'set' or op == 'create':
        if have_fp_attr == True:
            subport_id = 0
            try:
                subport_id = cps_obj.get_attr_data(subport_attr_name)
            except ValueError:
                # use default value if no attribute found in object
                pass
            if front_panel_port is None:
                npu_id = None
                port_id = None
            else:
                try:
                    (npu_id, port_id, hw_port) = fp_utils.get_npu_port_from_fp(
                                                            front_panel_port, subport_id)
                except ValueError as inst:
                    nas_if.log_info(inst.args[0])
                    return False
                nas_if.log_info('Front panel port %d, NPU port %d' % (front_panel_port, port_id))
                in_phy_mode = if_config.get_intf_phy_mode(cps_obj)
                if in_phy_mode != None:
                    phy_mode = port_utils.hw_port_to_phy_mode(port_list, npu_id, hw_port)
                    if in_phy_mode != phy_mode:
                        nas_if.log_err('Input PHY mode %d mis-match with physical port mode %d' % (
                                       in_phy_mode, phy_mode))
                        return False
            cps_obj.add_attr(npu_attr_name, npu_id)
            cps_obj.add_attr(port_attr_name, port_id)

        try:
            if _if_update_config(op, cps_obj) == False:
                params['change'] = cps_obj.get()
                nas_if.log_err( "Interface update config failed during set or create ")
                return False
        except Exception:
            nas_if.log_err( "Interface update config failed during set or create ")
            logging.exception('Error:')

    module_name = nas_if.get_if_key()
    in_obj = copy.deepcopy(cps_obj)
    in_obj.set_key(cps.key_from_name('target', module_name))
    in_obj.root_path = module_name + '/'
    obj = in_obj.get()
    if op_attr_name in obj['data']:
        del obj['data'][op_attr_name]
    upd = (op, obj)
    trans = cps_utils.CPSTransaction([upd])
    ret_data = trans.commit()
    if ret_data == False:
        nas_if.log_err('Failed to commit request')
        ret_data = trans.get_objects()
        if len(ret_data) > 0 and 'change' in ret_data[0]:
            ret_obj = cps_object.CPSObject(obj = ret_data[0]['change'])
            try:
                ret_code = ret_obj.get_attr_data(retcode_attr_name)
                ret_str = ret_obj.get_attr_data(retstr_attr_name)
            except ValueError:
                nas_if.log_info('Return code and string not found from returned object')
                return False
            cps_obj.add_attr(retcode_attr_name, ret_code)
            cps_obj.add_attr(retstr_attr_name, ret_str)
            params['change'] = cps_obj.get()
        return False
    if op == 'delete':
        try:
            _if_update_config(op, in_obj)
        except:
            nas_if.log_err('update config failed for delete operation')
            logging.exception('Error:')
        return True
    if len(ret_data) == 0 or not 'change' in ret_data[0]:
        nas_if.log_err('Invalid return object from cps request')
        return False
    if (op == 'create' and member_port is None):
        ret_obj = cps_object.CPSObject(obj = ret_data[0]['change'])
        try:
            ifindex = ret_obj.get_attr_data(ifindex_attr_name)
        except ValueError:
            nas_if.log_err('Ifindex not found from returned object')
            return False
        cps_obj.add_attr(ifindex_attr_name, ifindex)

    params['change'] = cps_obj.get()
    return True
# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#

import threading

import cps
import cps_object
import cps_utils
import nas_front_panel_map as fp
import nas_phy_media as media
import nas_os_if_utils as nas_if

_media_key = cps.key_from_name('observed', 'base-pas/media')
_physical_key = cps.key_from_name('target', 'base-if-phy/physical')
_logical_if_key = cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces/interface')
_logical_if_state_key = cps.key_from_name('observed', 'dell-base-if-cmn/if/interfaces-state/interface')

def _get_obj_attr_value(obj, attr_name):
    try:
        value = obj.get_attr_data(attr_name)
        return value
    except:
        return None

def set_media_type_on_port_create(phy_obj):
    hwport = phy_obj.get_attr_data('hardware-port-id')
    if hwport <= 0:
        return
import   cps

handle   =  cps.event_connect()

cps.event_register(handle,   cps.key_from_name('observed','base-port/interface'))
while   True:
    obj  =  cps.event_wait(handle)
    print   obj
Ejemplo n.º 27
0
def sigterm_hdlr(signum, frame):
    global shutdwn
    shutdwn = True

if __name__ == '__main__':

    shutdwn = False

    # Install signal handlers.
    import signal
    signal.signal(signal.SIGTERM, sigterm_hdlr)

    # Wait for base MAC address to be ready. the script will wait until
    # chassis object is registered.
    chassis_key = cps.key_from_name('observed','base-pas/chassis')
    while cps.enabled(chassis_key)  == False:
        #wait for chassis object to be ready
        nas_if.log_err('Create Interface: Base MAC address is not yet ready')
        time.sleep(1)
    fp_utils.init()
    while cps.enabled(nas_comm.get_value(nas_comm.keys_id, 'physical_key'))  == False:
        nas_if.log_info('Create Interface: Physical port service is not ready')
        time.sleep(1)

    port_list = port_utils.get_phy_port_list()

    port_utils.phy_port_cache_init(port_list)


    handle = cps.obj_init()
Ejemplo n.º 28
0
if __name__ == '__main__':

    _qual = ["target", "observed", "proposed", "realtime"]

    if (len(sys.argv) < 2) or (len(sys.argv) > 3):
        cps_trace_usage()
        exit(1)

    in_qual = sys.argv[1].lower()
    if in_qual not in _qual:
        print "\nCheck the qualifier, not a valid qualifier "
        cps_trace_usage()
        exit(1)

    if len(sys.argv) > 2:
        _key = cps.key_from_name(in_qual, sys.argv[2])
    else:
        _key = cps.key_from_qual(in_qual)

    print "Key : " + _key

    if ((_key == "") or (_key == None)):
        print "Check the object name, not a valid object\n"
        exit(1)

    if len(sys.argv) > 2:
        print " Registering for " + in_qual + " " + sys.argv[2]
    else:
        print " Registering for " + in_qual

    handle = cps.event_connect()
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#

import cps
import cps_object
import cps_utils
import event_log as ev
import nas_front_panel_map as fp
import nas_os_if_utils as nas_if
import nas_fp_port_utils as fp_utils
import nas_common_header as nas_comm
import logging
import sys

_port_group_state_key = cps.key_from_name(
    'observed', 'base-pg/dell-pg/port-groups-state/port-group-state')
_port_group_key = cps.key_from_name('target',
                                    'base-pg/dell-pg/port-groups/port-group')
port_group_state_id_attr = 'dell-pg/port-groups/port-group'


def pg_state_attr(t):
    return 'dell-pg/port-groups-state/port-group-state/' + t


def pg_attr(t):
    return 'dell-pg/port-groups/port-group/' + t


def base_pg_attr(t):
    return 'base-pg/' + pg_attr(t)
Ejemplo n.º 30
0
# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED ON AN #AS IS* BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
#  LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#

import cps
import cps_object
import cps_utils

_ipv4_key = cps.key_from_name('target', 'base-ip/ipv4')
_ipv6_key = cps.key_from_name('target', 'base-ip/ipv6')


if __name__ == '__main__':
    # monitor ip change event
    handle = cps.event_connect()
    cps.event_register(handle, _ipv4_key)
    cps.event_register(handle, _ipv6_key)
    while True:
        o = cps.event_wait(handle)
        print o
        obj = cps_object.CPSObject(obj=o)
        cps_utils.print_obj(obj)
        if _ipv4_key == obj.get_key():
            print "IPv4 change event received"
Ejemplo n.º 31
0
import cps
import subprocess
import sys
import time
import cps_object
import cps_utils
import socket
import binascii
import ifindex_utils

import dn_base_ip_tool

iplink_cmd = '/sbin/ip'

_keys = {
    'base-ip/ipv4': cps.key_from_name('target', 'base-ip/ipv4'),
    'base-ip/ipv6': cps.key_from_name('target', 'base-ip/ipv6'),
    'base-ip/ipv4/address':
    cps.key_from_name('target', 'base-ip/ipv4/address'),
    'base-ip/ipv6/address':
    cps.key_from_name('target', 'base-ip/ipv6/address'),
    cps.key_from_name('target', 'base-ip/ipv4'): 'base-ip/ipv4',
    cps.key_from_name('target', 'base-ip/ipv6'): 'base-ip/ipv6',
    cps.key_from_name('target', 'base-ip/ipv4/address'): 'base-ip/ipv4/address',
    cps.key_from_name('target', 'base-ip/ipv6/address'): 'base-ip/ipv6/address',
}


def get_next_index(d):
    count = 0
    while True:
    global signum_caught
    signum_caught = signum


if __name__ == '__main__':

    import signal
    signal.signal(signal.SIGTERM, sig_handler)

    handle = cps.obj_init()

    tun_cb = {}
    tun_cb['get'] = get_tunnel_cb
    tun_cb['transaction'] = set_tunnel_cb

    cps.obj_register(handle, cps.key_from_name("target", "cps/tunnel"), tun_cb)

    db_cb = {}
    db_cb['get'] = get_db_cb
    db_cb['transaction'] = set_db_cb

    cps.obj_register(handle, cps.key_from_name("target", "cps/db-instance"),
                     db_cb)

    # WARNING systemd module not currently installed!!!
    #         Waiting for legal approval to bring systemd module into OPX.
    #import systemd.daemon
    #systemd.daemon.notify("READY=1")

    signal.pause()
Ejemplo n.º 33
0
import nas_acl

import cps
import cps_object
import cps_utils

import random
import time
import signal
import sys
import argparse

_KEY = 'acl-config/entry'

_key_for_status = cps.key_from_name('observed', _KEY)
_key_for_cfg = cps.key_from_name('target', _KEY)

_key_for_reload = cps.key_from_name('target', 'acl-config/reload')

_valid_match_fields_in = [
    'SRC_IP', 'DST_IP', 'IN_PORT', 'OUT_PORT', 'L4_SRC_PORT', 'L4_DST_PORT',
    'SRC_MAC', 'DST_MAC'
]

_valid_match_fields_eg = [
    'SRC_IP', 'DST_IP', 'IN_PORT', 'OUT_PORT', 'L4_SRC_PORT', 'L4_DST_PORT',
    'SRC_MAC', 'DST_MAC'
]

_default_table_prio = 110
Ejemplo n.º 34
0
 def create_cps_obj(cls, module, data={}, qual='target'):
     cps_obj = {
         'key': cps.key_from_name(qual, module),
         'data': data
     }
     return cps_obj
Ejemplo n.º 35
0
# permissions and limitations under the License.

import cps
import cps_object
import nas_os_if_utils as nas_if
import nas_mac_addr_utils as ma
import nas_if_config_obj as if_config
import nas_common_header as nas_comm

import logging
import time
import systemd.daemon
import threading

mac_attr_name = 'dell-if/if/interfaces/interface/phys-address'
_fp_port_key = cps.key_from_name('target','base-if-phy/front-panel-port')

def sigterm_hdlr(signum, frame):
    global shutdwn
    shutdwn = True

def get_mac_rpc_cb(methods, params):
    if params['operation'] != 'rpc':
        nas_if.log_err('Operation %s not supported' % params['operation'])
        return False
    cps_obj = cps_object.CPSObject(obj = params['change'])

    if_type = if_config.get_intf_type(cps_obj)
    if if_type == 'loopback' or if_type == 'management':
        nas_if.log_err('Interface type %s not supported' % if_type)
        return False
Ejemplo n.º 36
0
    global shutdown
    shutdown = False

    # Install signal handlers.
    import signal
    signal.signal(signal.SIGTERM, sigterm_hdlr)

    if len(sys.argv) > 1:
        print run_shell_cmd(sys.argv[1])
        sys.exit(0)

    handle = cps.obj_init()
    d = {}
    d['get'] = get_cb
    d['transaction'] = trans_cb
    key = cps.key_from_name('target', 'base-switch/diag_shell')
    cps.obj_register(handle, key, d)
 
    # Notify systemd: Daemon is ready
    systemd.daemon.notify("READY=1")

    # wait until a signal is received
    while False == shutdown:
        signal.pause()

    systemd.daemon.notify("STOPPING=1")
    # cleanup code here

    # No need to specifically call sys.exit(0).
    # That's the default behavior in Python.
Ejemplo n.º 37
0
# permissions and limitations under the License.

import os
import cps
import cps_object
import cps_utils
import nas_os_if_utils as nas_if
import bytearray_utils as ba
import event_log as ev

import xml.etree.ElementTree as ET
import nas_phy_media as media

import time

_media_key = cps.key_from_name('observed', 'base-media/media-info')

MEDIA_LIST = {}


class PHY_Media:
    def __init__(self, media_type, media_str, speed, autoneg, duplex):
        self.name = media_str
        self.id = media_type
        self.speed = speed
        self.autoneg = autoneg
        self.duplex = duplex
        self.supported_speed = []

    def add_supported_speed(self, speed):
        self.supported_speed.append(int(speed))
        exit(1)

    _in_op = sys.argv[1].lower();
    _in_qual = sys.argv[2].lower();

    _operation = ['set', 'create', 'delete']
    if _in_op not in _operation:
       print "\nCheck operation, supported operations (set/create/delete)\n"
       exit(1)

    _qual = ['target', 'observed', 'proposed', 'realtime']
    if _in_qual not in _qual:
       print "\nCheck qualifier, supported qualifiers (target/observed/proposed/realtime)\n"
       exit(1)

    _key = cps.key_from_name(_in_qual, sys.argv[3])

    if ((_key == "") or (_key  == None)):
        print "\nCheck the object name, not a valid object\n"
        exit(1)

    handle = cps.event_connect()
    print " sending event for...."
    _obj = cps_object.CPSObject(qual=_in_qual, module=sys.argv[3])

    for e in sys.argv[4:]:
        attr = e.split('=',1)
        _obj.add_attr(attr[0],attr[1])

    cur_obj = _obj.get()
    ev = {'operation':_in_op, 'key':cur_obj['key'], 'data':cur_obj['data']}
Ejemplo n.º 39
0
# not use this file except in compliance with the License. You may obtain
# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.

import cps
import cps_object
import cps_utils

_ipv4_key = cps.key_from_name('target', 'base-ip/ipv4')
_ipv6_key = cps.key_from_name('target', 'base-ip/ipv6')

if __name__ == '__main__':
    # monitor ip change event
    handle = cps.event_connect()
    cps.event_register(handle, _ipv4_key)
    cps.event_register(handle, _ipv6_key)
    while True:
        o = cps.event_wait(handle)
        print o
        obj = cps_object.CPSObject(obj=o)
        cps_utils.print_obj(obj)
        if _ipv4_key == obj.get_key():
            print "IPv4 change event received"
        elif _ipv6_key == obj.get_key():
Ejemplo n.º 40
0

import subprocess
import event_log as ev
import cps_object
import cps_utils
import cps


iplink_cmd = '/sbin/ip'

config_sad_key_prefix = 'eipsec/ipsec/sad/sad-entries'
config_sad_options_key_prefix = 'ipsec-sad/eipsec/ipsec/sad/sad-entries'
config_spd_key_prefix = 'spd/eipsec/ipsec/spd/spd-entries'

_ipsec_keys = {config_sad_key_prefix : cps.key_from_name('target', config_sad_key_prefix),
              config_spd_key_prefix : cps.key_from_name('target', config_spd_key_prefix),
              'eipsec/sad/sad-entries': cps.key_from_name('target', 'eipsec/sad/sad-entries'),
              'eipsec/spd/spd-entries': cps.key_from_name('target', 'eipsec/spd/spd-entries')
              }


def log_err(msg):
    ev.logging("BASE_IP",ev.ERR,"IPSEC-CONFIG-UTILS","","",0,msg)

def log_info(msg):
    ev.logging("BASE_IP",ev.INFO,"IPSEC-CONFIG-UTILS","","",0,msg)

def run_command(cmd, respose):
    """Method to run a command in shell"""
    try:
        exit(1)

    _in_op = sys.argv[1].lower()
    _in_qual = sys.argv[2].lower()

    _operation = ['set', 'create', 'delete']
    if _in_op not in _operation:
        print "\nCheck operation, supported operations (set/create/delete)\n"
        exit(1)

    _qual = ['target', 'observed', 'proposed', 'realtime']
    if _in_qual not in _qual:
        print "\nCheck qualifier, supported qualifiers (target/observed/proposed/realtime)\n"
        exit(1)

    _key = cps.key_from_name(_in_qual, sys.argv[3])

    if ((_key == "") or (_key == None)):
        print "\nCheck the object name, not a valid object\n"
        exit(1)

    handle = cps.event_connect()
    print " sending event for...."
    _obj = cps_object.CPSObject(qual=_in_qual, module=sys.argv[3])

    for e in sys.argv[4:]:
        attr = e.split('=', 1)
        _obj.add_attr(attr[0], attr[1])

    cur_obj = _obj.get()
    ev = {'operation': _in_op, 'key': cur_obj['key'], 'data': cur_obj['data']}
import   cps
import   cps_utils

#  Example   GET  request cps_get_response   =  []
cps.get([cps.key_from_name('observed','base-pas/chassis')], cps_get_response) 

chassis_vendor_name   =  cps_attr_get(cps_get_response[0]['data'],'base-pas/chassis/vendor-name')