Esempio n. 1
0
    def __init__(self, file=None, host=None):
        """
Make a database writing librarian, listening to packets from host, and writing into the the sqlite3 file specified.
Defaults provided match my own personal environment.
If the database file is not found, or does not contain the appropriate tables and indexes, it is created
        """
        self.log = logging.getLogger("alexandria.Librarian")
        if file is None:
            file = config['library_file']
        try:
            self.conn = sqlite3.connect(file)
        except sqlite3.OperationalError as ex:
            self.log.error(ex)
            raise ex

        self.log.debug("library exists, validating schema")
        self.cur = self.conn.cursor()
        try:
            self.cur.execute('select * from karlnet_sensor')
        except sqlite3.OperationalError as ex:
            if string.find(str(ex), "no such table: karlnet_sensor") != -1:
                self.log.debug(
                    "karlnet_sensor table didn't exist, creating it!")
                self.cur.execute(config['create_sql'])
                self.cur.execute(config['create_index'])
        self.log.debug("library is valid, connecting to stomp")

        if host is None:
            host = config['stomp_host']
        self.stomp = Client(host=host)
        self.log.info(
            "Valid library and stomp is up, starting to write books!")
Esempio n. 2
0
 def __init__(self, host, port, destination):
     self.host = host
     self.port = port
     self.destination = destination
     self.stomp = Client(host, port)
     self.stomp.connect()
     self.stomp.subscribe(destination)
Esempio n. 3
0
def main():
    TOPIC_1 = '/topic/julian_1'
    TOPIC_2 = '/topic/remote_queue'

    SERVER = 'pcbunn.cacr.caltech.edu'
    PORT = 61613
    
    try:
        # Testing remote queue
        q = RemoteQueue(host=SERVER, port=PORT, destination=TOPIC_2)
        stomp_1 = Client(host=SERVER, port=PORT)
        stomp_1.connect()
        stomp_1.subscribe(destination=TOPIC_1)
        
        for i in range(4):
            stomp_1.put(i, destination=TOPIC_1)
            q.put(i+40)

        for j in range(4):
            message_1 = stomp_1.get(block=True)
            message_2 = q.get()
            print 'message_1 is ', message_1.body
            print 'message_2 is ', message_2

            #print 'ack'
            #stomp.ack(message)
            time.sleep(1.0)

    except Exception, err:
        print 'Error', err
        return
Esempio n. 4
0
    def connect(self, hostname='192.168.1.166', port=61613):
        # 通过simple方式连接JMS服务器
        # 指定hostname和port(tips:ActiveMQ支持多种协议连接stomp协议的默认端口为61613,这里不要写为61616)
        ConnectAMQ.__stompClient = Client(hostname, port)
        #stomp = Client()#如果是ActiveMQ和ActiveMQ客户端(本程序)在同一台机器可使用默认值:hostname="localhost",port=61613

        # 连接服务器
        ConnectAMQ.__stompClient.connect()
Esempio n. 5
0
def main():
    stomp = Client('10.200.10.194', 61624)
    stomp.connect()
    stomp.subscribe('/queue/test1', ack='client')
    while True:
        message = stomp.get(block=True)
        print(type(message), message.body)
        stomp.ack(message)
    connection.unsubscribe({'destination': '/queue/test1'})
    time.sleep(1)
    connection.disconnect()
Esempio n. 6
0
def run_stomp():
    #initialize

    #~ Does connection and loops the stomp connection
    stomp = Client(host=stomphost, port=int(stompport))
    try:
        stomp.connect(username=stompusername,
                      password=stomppw,
                      clientid=stompclientid)
    except Exception, e:
        print str(e)
        sys.exit("Cannot connect to STOMP Server")
Esempio n. 7
0
    def __init__(self, host, port, channel, nconcepts, k=2):
        QThread.__init__(self)
        self.stomp = Client(host, port)
        self.channel = channel

        self.array = np.zeros((nconcepts, k))
        self.k = k
        self.nconcepts = nconcepts
        self.labels = RecyclingSet(nconcepts)
        self.labels.listen_for_drops(self.on_drop)

        self.exiting = False
Esempio n. 8
0
def simple_receive():
    stomp = Client('192.168.1.166', 61613)
    stomp.connect()
    stomp.subscribe("/queue/hello", ack="client")

    while True:
        message = stomp.get()
        print message.body
        stomp.ack(message)

    stomp.unsubscribe("/queue/hello")
    stomp.disconnect()
Esempio n. 9
0
 def __init__(self, host=None, port=None, topic=None, username=None,
              password=None, continuous=False):
     try:
         self.topic = topic
         self.username = username
         self.password = password
         self.host = host
         self.port = port
         self.stomp = Client(host=self.host, port=self.port)
         self.stomp.connect(username=self.username, password=self.password)
     except Exception, e:
         raise Exception('Cannot connect to message broker (%s@%s:%d): %s.'\
                            % (username, host, port, e))
Esempio n. 10
0
    def __init__(self, scot_uri, scot_database='scot3'):
        """Create an instance of the JSONupdate class

        arguments:
            stomp_uri: the base uri to the scot stomp server.
            stomp_port: the port used for communicating with the scot stomp
                server.  Defaults to 61613
            scot_database: the scot database to write new alert data to.
                Defaults to scot_v3

        """
        self._scot_uri = scot_uri
        self._stomp_uri = stomp_uri
        self._stomp_port = stomp_port
        self._db = database.Database(database=scot_database,
                                     collection='alerts')

        self._stomp_client = Client(host=self._stomp_uri, port=self._stomp_port)
        self._stomp_client.connect()
        self._stomp_client.subscribe('/topic/CHAT.DEMO',
                                     conf={'message':'chat', 'type':'listen'})
Esempio n. 11
0
def simple():
    # 通过simple方式连接JMS服务器
    # 指定hostname和port(tips:ActiveMQ支持多种协议连接stomp协议的默认端口为61613,这里不要写为61616)
    stomp = Client('192.168.1.166', 61613)
    #stomp = Client()#如果是ActiveMQ和ActiveMQ客户端(本程序)在同一台机器可使用默认值:hostname="localhost",port=61613

    # 连接服务器
    stomp.connect()
    # 发送消息到指定的queue
    stomp.put("The quick brown fox...", destination="/queue/hello")
    # 从指定的queue订阅消息。ack参数指定为"client",不然可能出现一个问题(具体忘了,以后补充),ack默认值为"auto"
    stomp.subscribe("/queue/hello", ack="client")
    # 等待接收ActiveMQ推送的消息
    message = stomp.get()
    # 打印消息的主体
    print message.body
    message.body
    'quick brown fox...'
    stomp.ack(message)
    # 退订
    stomp.unsubscribe("/queue/hello")
    # 关闭连接
    stomp.disconnect()
Esempio n. 12
0
#!/usr/bin/python

from stompy.simple import Client
import json

Dict_Message = dict()
Dict_Message["Test1"] = "CONDOR"

stomp = Client("localhost", 61613)
stomp.connect("producer", "pass")
stomp.put(json.dumps(Dict_Message),
          destination="/queue/test",
          conf={'Test': 'Test123'})
stomp.disconnect()

stomp = Client("localhost", 61613)
stomp.connect("consumer", "pass")
stomp.subscribe("/queue/test", conf={'selector': "Test = 'Test123'"})
#stomp.subscribe("/queue/test")
message = stomp.get()

print message.headers
New_Dict = json.loads(message.body)
print New_Dict
stomp.ack(message)
stomp.unsubscribe("/queue/test")
stomp.disconnect()
Esempio n. 13
0
ami_host = config.get('AMI', 'host')
ami_username = config.get('AMI', 'username')
ami_password = config.get('AMI', 'password')

print 'AMI host:', ami_host
print 'AMI username:'******'AMI password:'******'=' * 80

sql_dsn = config.get('SQL', 'dsn')

print 'SQL:', sql_dsn
print '=' * 80

stomp = Client(stomp_host)
stomp.connect(stomp_username, stomp_password)

stomp.agent_channel = 'jms.queue.msg.'

connection = connectionForURI(sql_dsn)
sqlhub.processConnection = connection

manager = asterisk.manager.Manager()

#try:
#try:
manager.connect(ami_host)
manager.login(ami_username, ami_password)
manager.destination = stomp
Esempio n. 14
0
# simulate fermentation readings

from stompy.simple import Client
from datetime import datetime
import random
from array import array
import time
import json

# open the JMS Client using STOMP protocol
stomp = Client(host='54.201.254.241', port=61613)
stomp.connect()

N = 50  # number of readings to take an average of
readings = array('f')  # the array of readings

total = 0  # the sum of N readings

target = 20  # set the target temp

# initialise the temp readings and calculate the average
for i in range(N):
    temp = random.uniform(target - 5, target + 5)  # get random temp value
    readings.append(temp)  # add temp to the array (this grows the array)
    total += temp  # add temp to the total

average = total / N  # calculate the average temp

# define min and max values and set to average
min = average
max = average
Esempio n. 15
0
        "cacti_filename": '/var/lib/cacti/rra/localhost_freq_9.rrd',
        "cgi_filename": '/home/karl/public_html/rrd/tinytemp1.rrd'
    }
}

from stompy.simple import Client
import jsonpickle
import rrdtool

import logging
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s %(levelname)s %(name)s - %(message)s",
                    filename="/var/log/karlnet_rrd.log")
log = logging.getLogger("main")

stomp = Client(host='egri')


def runMain():
    clientid = "karlnet_rrd@%s/%d" % (socket.gethostname(), os.getpid())
    stomp.connect(clientid=clientid)
    stomp.subscribe("/topic/karlnet.>")

    while True:
        message = stomp.get()
        kp = jsonpickle.decode(message.body)
        log.info("updating RRD for: %s", kp)

        if (config.get(kp.node, None)):  # slightly funky safe check
            args = "N:%f:%d" % (kp.sensors[0].value, kp.sensors[1].value)
            rrdtool.update(config[kp.node]["cacti_filename"], '--template',
Esempio n. 16
0
 def setup(self):
     super(WhenUsingSimpleClient, self).setup()
     self.client = Client()
Esempio n. 17
0
from channel.channel_message import ChannelMessage as ChannelMessage

#import fcntl
#lockfile = os.path.normpath('/var/lock/' + os.path.basename(__file__) + '.lock')
#exclusive_lock = open(lockfile, 'w')
#try:
#    fcntl.lockf(exclusive_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
#except IOError:
#    print "Another instance is already running, quitting."
#    time.sleep(1)
#    sys.exit(-1)

config = ConfigParser.ConfigParser()
config.read('/opt/ucall/etc/config.ini')

stomp = Client(config.get('STOMP', 'host'))
stomp.connect(config.get('STOMP', 'username'), config.get('STOMP', 'password'))

#sys.stdout = open("/var/log/requests/connector2.log","a")
#sys.stderr = open("/var/log/requests/connector-err2.log","a")


class AsteriskEvent(SQLObject):
    added = DateTimeCol(default=sqlbuilder.func.NOW())
    event = StringCol()
    uniqueid = StringCol(default=None)
    raw = StringCol(default=None)


connection = connectionForURI(config.get('SQL', 'dsn'))
sqlhub.processConnection = connection
Esempio n. 18
0
#!/usr/bin/python
import sys
import syck as yaml
import time
from hashlib import sha1
from M2Crypto.RSA import load_pub_key, load_key
from stompy.simple import Client

# Change these.
PREFIX = 'mcollective'
CERTNAME = 'certificate-name'
s = Client('stomp.server')
s.connect('stompusername','stomppassword')
rr = load_key('path-to-unencrypted-private-key.pem')

target = '/topic/%s.discovery.command' % PREFIX
target_reply = '/topic/%s.discovery.reply' % PREFIX
s.subscribe(target_reply)
rid = sha1(str(time.time())).hexdigest()

# Put together message.
r = {}
r[':msgtime'] = int(time.time())
r[':filter'] = {
    'identity': [],
    'fact': [],
    'agent': [],
    'cf_class': [],
}
r[":requestid"] = rid
r[":callerid"] = 'cert=%s' % CERTNAME