Exemple #1
0
def rename_ap_on_wlc(controller,
                     ap_name,
                     ap_mac_address,
                     netconfig,
                     options,
                     quiet,
                     apgroup='default-group',
                     dry_run=False,
                     timeout=600,
                     dur=200):
    """
    set the name of the ap in wlc and optionally the apgroup
    """
    wlc = None
    try:
        # log onto wlc
        wlc = netconfig.get(controller)
        if not dry_run:
            wlc.connect()
            while timeout > 0:
                try:
                    success = set_name_and_group(wlc, ap_name, ap_mac_address,
                                                 apgroup)
                    break
                except:
                    logging.info("... access point hasn't shown up yet")
                sleep(dur)
                timeout = timeout - dur
            if timeout <= 0:
                raise Exception, 'could not assign %s (%s) to group %s' % (
                    ap_name, ap_mac_address, apgroup)
    except Exception, e:
        raise e
Exemple #2
0
 def get(self,
         non_blocking=False,
         poll_time=0.01,
         no_ack=False,
         prefetch_count=1):
     while self.consuming:
         try:
             msg = None
             if not non_blocking:
                 msg = self.queue.blpop(self.key)
             else:
                 msg = self.queue.lpop(self.key)
             if msg:
                 yield msg[1]
         except Exception, e:
             logging.error("%s %s" % (type(e), e))
         sleep(poll_time)
Exemple #3
0
 def get(self,
         non_blocking=False,
         poll_time=0.01,
         no_ack=False,
         prefetch_count=1):
     """
     generator for picking things off the queue. if non_blocking, then exit as soon as there's nothing left in the queue, otherwise keep on picking things off every poll_time seconds.
     """
     while self.consuming:
         try:
             msg = None
             if not non_blocking:
                 msg = self.queue.blpop(self.key)
             else:
                 msg = self.queue.lpop(self.key)
             if msg:
                 yield msg[1]
         except Exception, e:
             logging.error("%s %s" % (type(e), e))
         sleep(poll_time)
Exemple #4
0
def get_pyamqp_connection(*hosts, **kwargs):
    #port=5672, virtual_host='/', user='******', password='******', backoff=1, *hosts ):
    # support for RR of amqp hosts
    # reorg connection order based on last_idx
    last = 0
    if 'host_index' in kwargs and kwargs['host_index']:
        try:
            last = int(kwargs['host_index'])
        except:
            pass
    items = []
    end = []
    for i, h in enumerate(hosts):
        if i < last:
            end.append((i, h))
        else:
            items.append((i, h))
    items = items + end
    for idx, connection in items:
        try:
            this_host, _tmp, this_port = connection.partition(':')
            this_port = int(this_port) if not this_port == '' else int(
                kwargs['port'])
            logging.debug("connecting to message broker %s:%s/%s" %
                          (this_host, this_port, kwargs['virtual_host']))
            this = '%s:%s' % (this_host, this_port)
            conn = amqp.Connection(host=this,
                                   virtual_host=kwargs['virtual_host'],
                                   userid=kwargs['user'],
                                   password=kwargs['password'])
            chan = get_pyamqp_channel(conn)
            chan.access_request(kwargs['virtual_host'],
                                active=True,
                                write=True,
                                read=True)
            return conn, chan, idx
        except Exception, e:
            logging.warn("connecting to queue failed: %s" % (e, ))
            sleep(1)
Exemple #5
0
    # reload it!
    try:
        yield 'reloading %s' % device.hostname
        device.system.reload()
    except EOF, e:
        # this error is fine
        pass
    except TimeoutException, e:
        pass

    # check to make sure it comes back up
    n = now()
    try_until = n + timedelta(seconds=wait)
    success = False

    sleep(delay)
    while n < try_until:
        try:
            yield message_per_loop
            netconfig.connect(device, **options)
            success = True
            break
        except:
            pass
        sleep(delay)
        n = now()

    # darn!
    if not success:
        raise Exception, 'device did not come back up after firmware upgrade'
Exemple #6
0
                        raise NotImplementedError, 'unsupported serialisation %s' % format
                    if body == END_MARKER:
                        self.consuming = False
                    else:
                        yield body
                # exit if we don't have anything!
                elif non_blocking:
                    break
            except Exception, e:
                logging.error("%s %s" % (type(e), e))
            finally:
                if msg and no_ack == False:
                    self.chan.basic_ack(msg.delivery_tag)

            # don't thrash
            sleep(poll_time)

        return

    def _consume(self, msg):
        # logging.warn( 'consuming msg: %s' % (msg,) )
        body = None
        if msg:
            body = msg.body
            if self.format == 'pickle':
                body = pickle.loads(msg.body)
            elif self.format == 'json':
                body = json.loads(msg.body)
            else:
                raise NotImplementedError, 'unknown serialisation format %s' % self.format
            if body == END_MARKER:
Exemple #7
0
    def start(self, *args, **kwargs):

        self.working = True
        initial = True

        # run it!
        try:

            while self.working:

                verbose = kwargs['verbose'] if 'verbose' in kwargs else False

                if ( 'foreground' in kwargs and kwargs['foreground'] == False ) \
                    or ( 'daemonise' in kwargs and kwargs['daemonise'] == True ):

                    if not 'logfile' in kwargs:
                        raise IOError, 'logfile required for daemons'
                    elif kwargs['logfile'] == None:
                        raise IOError, 'logfile required for daemons'

                    # create daemon
                    context = DaemonContext()
                    # print "PIDFILE %s" % kwargs['pidfile']
                    if 'pidfile' in kwargs and not kwargs['pidfile'] == None:
                        context.pidfile = FileLock(kwargs['pidfile'])
                    if 'uid' in kwargs and not kwargs['uid'] == None:
                        context.uid = getpwnam(kwargs['uid']).pw_uid
                    if 'gid' in kwargs and not kwargs['gid'] == None:
                        context.gid = getgrnam(kwargs['gid']).gr_gid

                    # add signal maps
                    context.signal_map = {
                        signal.SIGTERM: self.terminate,
                        signal.SIGHUP: self.reload,
                    }
                    try:
                        with context:
                            if initial:
                                create_loggers(file=kwargs['logfile'],
                                               verbose=verbose)
                            self.run(*args, **kwargs)
                    except Exception, e:
                        raise e

                    sys.exit(0)

                else:

                    if initial:
                        if not 'logfile' in kwargs:
                            kwargs['logfile'] = None
                        create_loggers(file=kwargs['logfile'], verbose=verbose)

                    # associate signal maps
                    signal.signal(signal.SIGTERM, self.terminate)
                    signal.signal(signal.SIGHUP, self.reload)

                    self.run(*args, **kwargs)

                initial = False

                logging.info('respawning')
                sleep(5)

        except KeyboardInterrupt, e:
            logging.info('ctrl-c received')
            self.working = False
            self.terminate(None, None)
Exemple #8
0
def set_name_and_group(wlc,
                       name,
                       mac_address,
                       apgroup,
                       options={},
                       wait=200,
                       delay=15):
    """ configure the supplied access point (mac address) to given name and apgroup on the wlc """

    if not wlc.is_connected():
        wlc.connect()

    # ensure we see the access point first
    found = False
    logging.debug('looking for access point with mac address %s' %
                  (mac_address, ))
    for i in wlc.prompt.tell('show ap summary'):
        logging.debug(" > %s" % (i, ))
        if search(mac_address, i):
            found = True
    if not found:
        raise Exception, 'access point %s not available on wireless controller' % (
            mac_address, )

    # config the ap name
    cmd = 'ap name %s %s' % (name, mac_address)
    logging.warn("CMD: %s" % cmd)
    if wlc.prompt.ask(cmd, cursor=wlc.prompt.cursor('mode', 'config')):
        logging.debug('renamed access point %s to %s' % (
            mac_address,
            name,
        ))

    # TODO: not falling through....

    cmd = 'ap static-ip disable %s' % (name, )
    if wlc.prompt.ask(cmd,
                      cursor=wlc.prompt.cursor('mode', 'config'),
                      interact={
                          'question': 'y',
                          'yes_no': 'y\n'
                      }):
        logging.debug('removed static-ip configuration from ap')

    # config group
    if wlc.prompt.ask('ap group-name %s %s' % (apgroup, name),
                      cursor=wlc.prompt.cursor('mode', 'config'),
                      interact={
                          'question': 'y',
                          'yes_no': 'y\n'
                      }):
        logging.debug(
            'configured access point for %s group, rebooting access-point...' %
            (apgroup, ))

    # make sure ap comes back up
    while wait > 0:
        for i in wlc.prompt.tell('show ap summary',
                                 cursor=wlc.prompt.cursor('mode', 'exec')):
            if search(mac_address, i):
                logging.debug('done')
                return True
        sleep(delay)
        wait = wait - delay

    raise Exception, 'the access point could not be found'