Example #1
0
    def test_multiple_servers_calls(self):

        # start server A
        server_a = callme.Server(server_id='server_a')
        server_a.register_function(lambda: 'a', 'f')
        p_a = self._run_server_thread(server_a)

        # start server B
        server_b = callme.Server(server_id='server_b')
        server_b.register_function(lambda: 'b', 'f')
        p_b = self._run_server_thread(server_b)

        try:
            proxy = callme.Proxy(server_id='server_a')

            result = proxy.f()
            self.assertEqual(result, 'a')

            result = proxy.use_server('server_b').f()
            self.assertEqual(result, 'b')
        finally:
            server_a.stop()
            server_b.stop()
        p_a.join()
        p_b.join()
Example #2
0
    def test_method_single_call(self):
        server = callme.Server(server_id='fooserver')
        server.register_function(lambda a, b: a + b, 'madd')
        p = self._run_server_thread(server)

        try:
            result = callme.Proxy(server_id='fooserver').madd(1, 1)
            self.assertEqual(result, 2)
        finally:
            server.stop()
        p.join()
Example #3
0
    def test_remote_exception_call(self):
        server = callme.Server(server_id='fooserver')
        server.register_function(lambda a, b: a + b, 'madd')
        p = self._run_server_thread(server)

        try:
            proxy = callme.Proxy(server_id='fooserver')

            self.assertRaises(TypeError, proxy.madd)
        finally:
            server.stop()
        p.join()
Example #4
0
def iMain():
    import callme
    from PikaArguments import oParseOptions

    sUsage = __doc__.strip()
    oArgParser = oParseOptions(sUsage)
    oArgParser.add_argument('lArgs',
                            action="store",
                            nargs="*",
                            help="the message to send (required)")
    oOptions = oArgParser.parse_args()
    lArgs = oOptions.lArgs

    assert lArgs, "Need the command to send on the commandline"
    sCmd = lArgs[0]

    o = None
    iMax = 20
    i = 0
    try:
        sId1 = 'Mt4Server'
        proxy1 = callme.Proxy(server_id=sId1, timeout=20)
        #                 amqp_host='localhost',
        #                 amqp_user='******',
        #                 amqp_password='******',
        #                 amqp_vhost='/',
        #                 amqp_port=5672,
        while i < iMax:
            i += 1
            if oOptions.iDebugLevel >= 4:
                print "DEBUG: RPC %d for: %s" % (
                    i,
                    sCmd,
                )
            try:
                # sRetval = proxy1.sPySafeEval('str(' +sCmd +')')
                sRetval = proxy1.eMq4PushQueue(sCmd)
                print "INFO: " + str(sRetval)
                break
            except callme.exceptions.RpcTimeout:
                continue
    except KeyboardInterrupt:
        pass
    except Exception as e:
        print "ERROR: " + str(e)
        raise
    finally:
        # time.sleep(1.0)
        pass
def create_reservation():
    if request.method == 'POST':
        data = request.get_json()
        reservation_json = {
            'email': '*****@*****.**',
            'date': data['date'],
            'time': data['time'],
            'guests': 3,
            'restaurant_id': data['restaurantId']
        }
        proxy = callme.Proxy(
            server_id='reservation_service',
            amqp_host='localhost',
        )
        created, id = proxy.use_server(
            'reservation_service').create_reservation(reservation_json)
        return f'Reservation ID: {id}'
    return 'Make a reservation'
Example #6
0
    def test_method_multiple_calls(self):
        server = callme.Server(server_id='fooserver')
        server.register_function(lambda a, b: a + b, 'madd')
        p = self._run_server_thread(server)

        try:
            proxy = callme.Proxy(server_id='fooserver')

            result = proxy.use_server(timeout=3).madd(1, 2)
            self.assertEqual(result, 3)

            result = proxy.use_server(timeout=2).madd(2, 2)
            self.assertEqual(result, 4)

            result = proxy.use_server(timeout=1).madd(2, 3)
            self.assertEqual(result, 5)
        finally:
            server.stop()
        p.join()
Example #7
0
#
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
#
#     * Neither the name of callme nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import callme
import logging
logging.basicConfig(level=logging.INFO)


if __name__ == "__main__":
    proxy = callme.Proxy(server_id='fooserver')
    print(proxy.add(1, 1))
Example #8
0
 def threaded_call(i, results):
     proxy = callme.Proxy(server_id='fooserver')
     results.append((i, proxy.madd(i)))
Example #9
0
    def post(self, request):
        if request.is_ajax():
            source = request.POST['source']
            # Handle Empty Source Case
            source_empty_check(source)
            print source
            lang = request.POST['lang']
            # Handle Invalid Language Case
            lang_valid_check(lang)

            proxy = callme.Proxy(server_id='fooserver2',
                                 amqp_host='localhost',
                                 timeout=3600)

            resp = proxy.enveloppe_extract(source)

            model = Algorithm

            run_rank = model.objects.filter(
                score__lte=int(resp['score'])).order_by('rank')
            if len(run_rank) > 0:
                rankobj = run_rank.last()
                rank = rankobj.rank + 1

            else:
                rank = 1

            run_rank_low = model.objects.filter(score__gt=int(resp['score']))
            if len(run_rank_low) > 0:
                for i in run_rank_low:
                    i.rank += 1
                    i.save()

            else:
                pass

            b = Algorithm(username=request.user.username,
                          user=request.user,
                          rank=rank,
                          score=resp['score'],
                          time=resp['duration'],
                          source_code=source,
                          cpu=18)
            b.save()
            job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(
                request.user.username, resp['score'], rank)

            resp = model.objects.all().order_by('rank')
            values = resp.values('id')

            for ind, item in enumerate(values):
                if (item['id']) == b.id:
                    paging = divmod(ind, 5)[0]

            feed = Feed(user=request.user,
                        post=job_post,
                        job_link='/leaderboard?q=foo&flop=flip&page=' +
                        str(paging + 1))
            feed.save()

            #request.user.profile.notify_job_done(b)

            like = Activity(activity_type=Activity.RUN_PROCESSED,
                            feed=feed.pk,
                            user=request.user)
            like.save()

            user = request.user
            user.profile.notify_liked_bis(feed)

            print 'Notified'
            return HttpResponse(render(request, 'hackIDE/index.html'))

        else:
            print('error')
            return HttpResponseForbidden()
Example #10
0
    def test_timeout_call(self):
        callme.Server(server_id='fooserver')
        proxy = callme.Proxy(server_id='fooserver', timeout=1)

        self.assertRaises(exc.RpcTimeout, proxy.madd, 1, 2)
Example #11
0
 def threaded_call(i, results):
     results.append((i, callme.Proxy(server_id='fooserver').madd(i)))
Example #12
0
import flask
# import google_auth

app = flask.Flask(__name__)
CREDENTIALS_FILENAME = 'app_credentials.txt'
f = open(CREDENTIALS_FILENAME)
GOOGLE_CLIENT_ID = f.readline().strip()
GOOGLE_CLIENT_SECRET = f.readline().strip()
app.secret_key = GOOGLE_CLIENT_SECRET
CORS(app)

# app.register_blueprint(google_auth.app)
RPC_ADDRESS = '172.18.0.1'
RPC_ADDRESS = 'localhost'

notification_service = callme.Proxy(server_id='notification_service',
                                    amqp_host=RPC_ADDRESS)
reservation_service = callme.Proxy(server_id='reservation_service',
                                   amqp_host=RPC_ADDRESS)
search_service = callme.Proxy(server_id='search_service',
                              amqp_host=RPC_ADDRESS)
restaurant_service = callme.Proxy(server_id='restaurant_service',
                                  amqp_host=RPC_ADDRESS)

user_info = {'email': '*****@*****.**'}


def create_restaurant(data):
    return restaurant_service.use_server(
        'restaurant_service').create_restaurant(data)

    def execute_upload(self,request):
                import uuid
                form = self.form_class(request.POST, request.FILES)

                if  form.is_valid():
                    #resp = self.handle_uploaded_file(request.FILES['file'])
                    with open('uploaded_custom.py', 'wb+') as destination:
                        for chunk in request.FILES['file'].chunks():
                            destination.write(chunk)
                        destination.close()

                    proxy = callme.Proxy(server_id='fooserver2',amqp_host='amqp://*****:*****@37.187.117.106/echopen1', timeout=3600)
               
                    resp = proxy.denoise(open('uploaded_custom.py', 'rb').read())

                    self.uuid_index  = str(uuid.uuid4())

                    model = Algorithm

                    run_rank = model.objects.filter(rating__gt=int(resp['score'])).order_by('ranking')
                    if len(run_rank) > 0:
                        rankobj = run_rank.last()
                        rank = rankobj.ranking + 1

                    else:
                        rank = 1
                     
                    run_rank_low = model.objects.filter(rating__lte=int(resp['score']))
                    if len(run_rank_low) > 0 :
                        for i in run_rank_low:
                            i.ranking += 1
                            i.save()

                    else:
                        pass
                    
                                  
                    b = Algorithm(run_id= self.uuid_index, name=request.user.username, user=request.user, ranking = rank, rating=resp['score'], button = button_type, time= resp['duration'], source_code=source, cpu=18)
                    b.save()
                    job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(request.user.username,resp['score'], rank)
                    
                    resp = model.objects.all().order_by('ranking')
                    values = resp.values('run_id')
                    
                    for ind, item  in enumerate(values) :
                        if (item['run_id']) == self.uuid_index :
                            paging =  divmod(ind, 5)[0]

                    feed = Feed(user=request.user, post=job_post, job_link='/leaderboard?q=foo&flop=flip&page='+str(paging+1))
                    feed.save()


                    #request.user.profile.notify_job_done(b)      
                    

                    like = Activity(activity_type=Activity.RUN_PROCESSED, feed=feed.pk, user=request.user)
                    like.save()

                    user = request.user
                    user.profile.notify_liked_bis(feed)
                    

                    return paging
import callme
import datetime

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# channel.exchange_declare(exchange='new_reservation', exchange_type='fanout')

restaurant_json = {
    'method': 'create',
    'name': 'restaurant123',
    'address': 'restaurant street 123'
}
reservation_json = {
    'email': '*****@*****.**',
    'date': datetime.date.today(),
    'time': 'dinner'
}
# channel.basic_publish(exchange='restaurants', routing_key='', body=str(restaurant_json))

# RPC test
proxy = callme.Proxy(
    server_id='reservation_service',
    amqp_host='localhost',
)
created, id = proxy.use_server('reservation_service').create_reservation(
    reservation_json)
print(created)
print(id)

# print("[x] new reservation")
# connection.close()
Example #15
0
import callme

proxy = callme.Proxy(
    server_id='fooserver',
    amqp_host='localhost',
)
print(proxy.use_server('fooserver').add(1, 2))
Example #16
0
    def post(self, request):
        if request.is_ajax():
            source = request.POST['source']
            # Handle Empty Source Case
            source_empty_check(source)
            print source
            lang = request.POST['lang']
            # Handle Invalid Language Case
            lang_valid_check(lang)
            proxy = callme.Proxy(
                server_id='fooserver',
                amqp_host='salamander.rmq.cloudamqp.com',
                amqp_vhost='spwlpmyp',
                amqp_user='******',
                amqp_password='******')

            resp = proxy.enveloppe_extract(source)

            model = Algorithm
            #source = source    + '\n' + resp['error_msg']
            run_rank = model.objects.filter(
                score__lte=int(resp['score'])).order_by('rank')
            if len(run_rank) > 0:
                rankobj = run_rank.last()
                rank = rankobj.rank + 1

            else:
                rank = 1

            run_rank_low = model.objects.filter(score__gt=int(resp['score']))
            if len(run_rank_low) > 0:
                for i in run_rank_low:
                    i.rank += 1
                    i.save()

            else:
                pass

            b = Algorithm(username=request.user.username,
                          user=request.user,
                          rank=rank,
                          score=resp['score'],
                          time=resp['duration'],
                          source_code=source,
                          cpu=18)
            b.save()
            job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(
                request.user.username, resp['score'], rank)
            cop_resp = resp
            resp = model.objects.all().order_by('rank')
            values = resp.values('id')

            for ind, item in enumerate(values):
                if (item['id']) == b.id:
                    paging = divmod(ind, 5)[0]

            print(cop_resp)
            if cop_resp['error_msg'] == 'None':
                r = {'compile_status': 'OK', 'run_status_status': 'OK'}
            else:
                r = {
                    'compile_status': 'OK',
                    'run_status_status': 'ERROR',
                    'run_status_error': cop_resp['error_msg']
                }

            feed = Feed(user=request.user,
                        post=job_post,
                        job_link='/leaderboard?q=foo&flop=flip&page=' +
                        str(paging + 1))
            feed.save()
            like = Activity(activity_type=Activity.RUN_PROCESSED,
                            feed=feed.pk,
                            user=request.user)
            like.save()

            user = request.user
            user.profile.notify_liked_bis(feed)

            import json
            #r['compile_status'] = 'OK'
            #r['run_status']['status'] = 'AC'
            #r['run_status']['time_used'] = '12'
            #r['run_status']['memory_used'] = '12'
            #r['run_status']['output_html'] = "dededed"
            #r['run_status']['stderr'] =  "toto"

            #r   = json.dumps(r)
            #return HttpResponse(r, content_type="application/json")
            return JsonResponse(r, safe=False)
            #return HttpResponse(render(request, 'hackIDE/index.html'))

        else:
            print('error')
            return HttpResponseForbidden()
Example #17
0
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import logging

import callme


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    proxy = callme.Proxy(server_id='fooserver', timeout=5)

    # call add function
    a = 3
    b = 2
    result = proxy.add(a, b)
    logging.info("add(%d, %d) = %d" % (a, b, result))

    # call fib function
    n = 35
    result = proxy.fib(n)
    logging.info("fib(%d) = %d" % (n, result))
#     login_user,
#     logout_user,
# )
import flask

app = flask.Flask(__name__)
# CREDENTIALS_FILENAME = 'app_credentials.txt'
# f = open(CREDENTIALS_FILENAME)
# GOOGLE_CLIENT_ID = f.readline().strip()
# GOOGLE_CLIENT_SECRET = f.readline().strip()
# app.secret_key = GOOGLE_CLIENT_SECRET
CORS(app)

RABBITMQ_URL = '172.18.0.1'

reservation_service = callme.Proxy(server_id='reservation_service',
                                   amqp_host=RABBITMQ_URL)
restaurant_service = callme.Proxy(server_id='restaurant_service',
                                  amqp_host=RABBITMQ_URL)

table_owners = {
    'restaurants': (restaurant_service, 'restaurant_service'),
    'tables': (restaurant_service, "restaurant_service"),
    'reservations': (reservation_service, 'reservation_service')
}


def serialize_dict(dict):
    """
    Changes date to string.
    :param dict:
    :return: