<commit_before>#include "rubymotion.h"
#include "motion-game.h"

/// @class Director < Object
/// Director is a shared object that takes care of the scene graph.

VALUE rb_cDirector = Qnil;
static VALUE mc_director_instance = Qnil;
static std::vector<VALUE> director_using_scene(3);

/// @group Constructors

/// @method .shared
/// @return [Director] the shared Director instance.

static VALUE
director_instance(VALUE rcv, SEL sel)
{
    if (mc_director_instance == Qnil) {
	VALUE obj = rb_cocos2d_object_new(cocos2d::Director::getInstance(), rb_cDirector);
	mc_director_instance = rb_retain(obj);
    }
    return mc_director_instance;
}

#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV
static VALUE
director_view_set(VALUE rcv, SEL sel, VALUE obj)
{
    cocos2d::GLView *glview =
	cocos2d::GLViewImpl::createWithEAGLView((void *)obj);
    DIRECTOR(rcv)->setOpenGLView(glview);
    return obj;
}

static VALUE
director_view_get(VALUE rcv, SEL sel)
{
    return (VALUE)DIRECTOR(rcv)->getOpenGLView()->getEAGLView();
}
#endif

/// @group Managing Scenes

/// @method #run(scene)
/// Runs the given scene object.
/// @param scene [Scene] the scene to run.
/// @return [Director] the receiver.

static VALUE
director_run(VALUE rcv, SEL sel, VALUE obj)
{
    director_using_scene[0] = rb_retain(obj);
    DIRECTOR(rcv)->runWithScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #replace(scene)
/// Replaces the current scene with a new one. The running scene will be
/// terminated.
/// @param scene [Scene] the scene to replace the current one with.
/// @return [Director] the receiver.

static VALUE
director_replace(VALUE rcv, SEL sel, VALUE obj)
{
    rb_release(director_using_scene[0]);
    director_using_scene[0] = rb_retain(obj);
    DIRECTOR(rcv)->replaceScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #push(scene)
/// Suspends the execution of the running scene, and starts running the given
/// scene instead.
/// @param scene [Scene] the new scene to run.
/// @return [Director] the receiver.

static VALUE
director_push(VALUE rcv, SEL sel, VALUE obj)
{
    director_using_scene.push_back(rb_retain(obj));
    DIRECTOR(rcv)->pushScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #pop
/// Pops the running scene from the stack, and starts running the previous
/// scene. If there are no more scenes to run, the execution will be stopped.
/// @return [Director] the receiver.

static VALUE
director_pop(VALUE rcv, SEL sel)
{
    VALUE last_scene = director_using_scene.back();
    director_using_scene.pop_back();
    rb_release(last_scene);
    DIRECTOR(rcv)->popScene();
    return rcv;
}

/// @method #end
/// Ends the execution of the running scene.
/// @return [Director] the receiver.

static VALUE
director_end(VALUE rcv, SEL sel)
{
    for (auto iter = director_using_scene.begin();
	 iter != director_using_scene.end(); ++iter) {
	if (*iter != 0) {
	    rb_release(*iter);
	    *iter = 0;
	}
    }
    DIRECTOR(rcv)->end();
    return rcv;
}

/// @method #pause
/// Pauses the execution of the running scene.
/// @return [Director] the receiver.

static VALUE
director_pause(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->pause();
    return rcv;
}

/// @method #resume
/// Resumes the execution of the current paused scene.
/// @return [Director] the receiver.

static VALUE
director_resume(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->resume();
    return rcv;
}

/// @method #start_animation
/// The main loop is triggered again.
/// @return [Director] the receiver.

static VALUE
director_start_animation(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->startAnimation();
    return rcv;
}

/// @method #stop_animation
/// Stops the animation.
/// @return [Director] the receiver.

static VALUE
director_stop_animation(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->stopAnimation();
    return rcv;
}

/// @group Properties

/// @property-readonly #origin
/// @return [Point] the visible origin of the director view in points.

static VALUE
director_origin(VALUE rcv, SEL sel)
{
    return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin());
}

/// @property-readonly #size
/// @return [Size] the visible size of the director view in points.

static VALUE
director_size(VALUE rcv, SEL sel)
{
    return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize());
}

/// @property #show_stats?
/// Controls whether the FPS (frame-per-second) statistic label is displayed
/// in the bottom-left corner of the director view. By default it is hidden.
/// @return [Boolean] whether the FPS label is displayed.

static VALUE
director_show_stats_set(VALUE rcv, SEL sel, VALUE val)
{
    DIRECTOR(rcv)->setDisplayStats(RTEST(val));
    return val;
}

static VALUE
director_show_stats(VALUE rcv, SEL sel)
{
    return DIRECTOR(rcv)->isDisplayStats() ? Qtrue : Qfalse;
}

extern "C"
void
Init_Director(void)
{
    rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject);

    rb_define_singleton_method(rb_cDirector, "shared", director_instance, 0);
    rb_define_method(rb_cDirector, "run", director_run, 1);
    rb_define_method(rb_cDirector, "replace", director_replace, 1);
    rb_define_method(rb_cDirector, "push", director_push, 1);
    rb_define_method(rb_cDirector, "pop", director_pop, 0);
    rb_define_method(rb_cDirector, "end", director_end, 0);
    rb_define_method(rb_cDirector, "pause", director_pause, 0);
    rb_define_method(rb_cDirector, "resume", director_resume, 0);
    rb_define_method(rb_cDirector, "start_animation", director_start_animation, 0);
    rb_define_method(rb_cDirector, "stop_animation", director_stop_animation, 0);
    rb_define_method(rb_cDirector, "origin", director_origin, 0);
    rb_define_method(rb_cDirector, "size", director_size, 0);
    rb_define_method(rb_cDirector, "show_stats=", director_show_stats_set, 1);
    rb_define_method(rb_cDirector, "show_stats?", director_show_stats, 0);

    // Internal.
#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV
    rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1);
    rb_define_method(rb_cDirector, "_get_glview", director_view_get, 0);
#endif
}
<commit_msg>add missing documents<commit_after>#include "rubymotion.h"
#include "motion-game.h"

/// @class Director < Object
/// Director is a shared object that takes care of the scene graph.

VALUE rb_cDirector = Qnil;
static VALUE mc_director_instance = Qnil;
static std::vector<VALUE> director_using_scene(3);

/// @group Constructors

/// @method .shared
/// @return [Director] the shared Director instance.

static VALUE
director_instance(VALUE rcv, SEL sel)
{
    if (mc_director_instance == Qnil) {
	VALUE obj = rb_cocos2d_object_new(cocos2d::Director::getInstance(), rb_cDirector);
	mc_director_instance = rb_retain(obj);
    }
    return mc_director_instance;
}

#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV
static VALUE
director_view_set(VALUE rcv, SEL sel, VALUE obj)
{
    cocos2d::GLView *glview =
	cocos2d::GLViewImpl::createWithEAGLView((void *)obj);
    DIRECTOR(rcv)->setOpenGLView(glview);
    return obj;
}

static VALUE
director_view_get(VALUE rcv, SEL sel)
{
    return (VALUE)DIRECTOR(rcv)->getOpenGLView()->getEAGLView();
}
#endif

/// @group Managing Scenes

/// @method #run(scene)
/// Runs the given scene object.
/// @param scene [Scene] the scene to run.
/// @return [Director] the receiver.

static VALUE
director_run(VALUE rcv, SEL sel, VALUE obj)
{
    director_using_scene[0] = rb_retain(obj);
    DIRECTOR(rcv)->runWithScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #replace(scene)
/// Replaces the current scene with a new one. The running scene will be
/// terminated.
/// @param scene [Scene] the scene to replace the current one with.
/// @return [Director] the receiver.

static VALUE
director_replace(VALUE rcv, SEL sel, VALUE obj)
{
    rb_release(director_using_scene[0]);
    director_using_scene[0] = rb_retain(obj);
    DIRECTOR(rcv)->replaceScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #push(scene)
/// Suspends the execution of the running scene, and starts running the given
/// scene instead.
/// @param scene [Scene] the new scene to run.
/// @return [Director] the receiver.

static VALUE
director_push(VALUE rcv, SEL sel, VALUE obj)
{
    director_using_scene.push_back(rb_retain(obj));
    DIRECTOR(rcv)->pushScene(rb_any_to_scene(obj));
    return rcv;
}

/// @method #pop
/// Pops the running scene from the stack, and starts running the previous
/// scene. If there are no more scenes to run, the execution will be stopped.
/// @return [Director] the receiver.

static VALUE
director_pop(VALUE rcv, SEL sel)
{
    VALUE last_scene = director_using_scene.back();
    director_using_scene.pop_back();
    rb_release(last_scene);
    DIRECTOR(rcv)->popScene();
    return rcv;
}

/// @method #end
/// Ends the execution of the running scene.
/// @return [Director] the receiver.

static VALUE
director_end(VALUE rcv, SEL sel)
{
    for (auto iter = director_using_scene.begin();
	 iter != director_using_scene.end(); ++iter) {
	if (*iter != 0) {
	    rb_release(*iter);
	    *iter = 0;
	}
    }
    DIRECTOR(rcv)->end();
    return rcv;
}

/// @method #pause
/// Pauses the execution of the running scene.
/// @return [Director] the receiver.

static VALUE
director_pause(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->pause();
    return rcv;
}

/// @method #resume
/// Resumes the execution of the current paused scene.
/// @return [Director] the receiver.

static VALUE
director_resume(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->resume();
    return rcv;
}

/// @method #start_animation
/// The main loop is triggered again.
/// @return [Director] the receiver.

static VALUE
director_start_animation(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->startAnimation();
    return rcv;
}

/// @method #stop_animation
/// Stops the animation.
/// @return [Director] the receiver.

static VALUE
director_stop_animation(VALUE rcv, SEL sel)
{
    DIRECTOR(rcv)->stopAnimation();
    return rcv;
}

/// @group Properties

/// @property-readonly #origin
/// @return [Point] the visible origin of the director view in points.

static VALUE
director_origin(VALUE rcv, SEL sel)
{
    return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin());
}

/// @property-readonly #size
/// @return [Size] the visible size of the director view in points.

static VALUE
director_size(VALUE rcv, SEL sel)
{
    return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize());
}

/// @method #show_stats=(value)
/// @param value [Boolean] true if display the FPS label.
/// Controls whether the FPS (frame-per-second) statistic label is displayed
/// in the bottom-left corner of the director view. By default it is hidden.

static VALUE
director_show_stats_set(VALUE rcv, SEL sel, VALUE val)
{
    DIRECTOR(rcv)->setDisplayStats(RTEST(val));
    return val;
}

/// @property-readonly #show_stats?
/// Controls whether the FPS (frame-per-second) statistic label is displayed
/// in the bottom-left corner of the director view. By default it is hidden.
/// @return [Boolean] whether the FPS label is displayed.

static VALUE
director_show_stats(VALUE rcv, SEL sel)
{
    return DIRECTOR(rcv)->isDisplayStats() ? Qtrue : Qfalse;
}

extern "C"
void
Init_Director(void)
{
    rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject);

    rb_define_singleton_method(rb_cDirector, "shared", director_instance, 0);
    rb_define_method(rb_cDirector, "run", director_run, 1);
    rb_define_method(rb_cDirector, "replace", director_replace, 1);
    rb_define_method(rb_cDirector, "push", director_push, 1);
    rb_define_method(rb_cDirector, "pop", director_pop, 0);
    rb_define_method(rb_cDirector, "end", director_end, 0);
    rb_define_method(rb_cDirector, "pause", director_pause, 0);
    rb_define_method(rb_cDirector, "resume", director_resume, 0);
    rb_define_method(rb_cDirector, "start_animation", director_start_animation, 0);
    rb_define_method(rb_cDirector, "stop_animation", director_stop_animation, 0);
    rb_define_method(rb_cDirector, "origin", director_origin, 0);
    rb_define_method(rb_cDirector, "size", director_size, 0);
    rb_define_method(rb_cDirector, "show_stats=", director_show_stats_set, 1);
    rb_define_method(rb_cDirector, "show_stats?", director_show_stats, 0);

    // Internal.
#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV
    rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1);
    rb_define_method(rb_cDirector, "_get_glview", director_view_get, 0);
#endif
}
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <boost/test/unit_test.hpp>
#include <armnn/ArmNN.hpp>
#include <Graph.hpp>
#include <SubgraphView.hpp>
#include <SubgraphViewSelector.hpp>
#include <backendsCommon/OptimizationViews.hpp>
#include <Network.hpp>

#include "CommonTestUtils.hpp"

using namespace armnn;

BOOST_AUTO_TEST_SUITE(OptimizationViewsTestSuite)

BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCount)
{
    OptimizationViews view;
    // Construct a graph with 3 layers
    Graph& baseGraph = view.GetGraph();

    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input");

    Convolution2dDescriptor convDescriptor;
    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);
    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1");
    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2");
    Layer* const substitutableCompiledLayer =
            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output");

    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));
    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));
    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));

    // Subgraph for a failed layer
    SubgraphViewSelector::SubgraphViewPtr failedSubgraph =
        CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                               CreateOutputsFrom({convLayer1}),
                               {convLayer1});
    // Subgraph for an untouched layer
    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer2});
    // Subgraph for a substitutable layer
    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutableCompiledLayer});
    // Create a Graph containing a layer to substitute in
    Graph substitutableGraph;
    Layer* const substitutionpreCompiledLayer =
            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    // Subgraph for a substitution layer
    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),
                                   CreateOutputsFrom({substitutionpreCompiledLayer}),
                                   {substitutionpreCompiledLayer});

    // Sub in the graph
    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);

    view.AddFailedSubgraph(SubgraphView(*failedSubgraph));
    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));

    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutionpreCompiledLayer});
    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});

    // Construct original subgraph to compare against
    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
            CreateOutputsFrom({convLayer2}),
            {convLayer1, convLayer2, substitutionpreCompiledLayer});

    BOOST_CHECK(view.Validate(*originalSubgraph));
}

BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCountFailValidate)
{
    OptimizationViews view;
    // Construct a graph with 3 layers
    Graph& baseGraph = view.GetGraph();

    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input");

    Convolution2dDescriptor convDescriptor;
    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);
    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1");
    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2");
    Layer* const substitutableCompiledLayer =
            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output");

    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));
    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));
    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));

    // Subgraph for an untouched layer
    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer2});
    // Subgraph for a substitutable layer
    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutableCompiledLayer});
    // Create a Graph containing a layer to substitute in
    Graph substitutableGraph;
    Layer* const substitutionpreCompiledLayer =
            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    // Subgraph for a substitution layer
    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),
                                   CreateOutputsFrom({substitutionpreCompiledLayer}),
                                   {substitutionpreCompiledLayer});

    // Sub in the graph
    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);

    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));

    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutionpreCompiledLayer});
    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});

    // Construct original subgraph to compare against
    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer1, convLayer2, substitutionpreCompiledLayer});

    // Validate should fail as convLayer1 is not counted
    BOOST_CHECK(!view.Validate(*originalSubgraph));
}

BOOST_AUTO_TEST_SUITE_END()<commit_msg>IVGCVSW-3033 Unit test using a MockBackend to validate Optimizer<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <boost/test/unit_test.hpp>
#include <armnn/ArmNN.hpp>
#include <Graph.hpp>
#include <SubgraphView.hpp>
#include <SubgraphViewSelector.hpp>
#include <backendsCommon/OptimizationViews.hpp>
#include <Network.hpp>

#include "CommonTestUtils.hpp"
#include "MockBackend.hpp"

using namespace armnn;

void CheckLayers(Graph& graph)
{
    unsigned int m_inputLayerCount = 0, m_outputLayerCount = 0, m_addLayerCount = 0;
    for(auto layer : graph)
    {
        switch(layer->GetType())
        {
            case LayerType::Input:
                ++m_inputLayerCount;
                if (layer->GetGuid() == 0)
                {
                    BOOST_TEST(layer->GetName() == "inLayer0");
                }
                else if (layer->GetGuid() == 1)
                {
                    BOOST_TEST(layer->GetName() == "inLayer1");
                }
                break;
            // The Addition layer should become a PreCompiled Layer after Optimisation
            case LayerType::PreCompiled:
                ++m_addLayerCount;
                BOOST_TEST(layer->GetName() == "pre-compiled");
                break;
            case LayerType::Output:
                ++m_outputLayerCount;
                BOOST_TEST(layer->GetName() == "outLayer");
                break;
            default:
                //Fail for anything else
                BOOST_TEST(false);
        }
    }
    BOOST_TEST(m_inputLayerCount == 2);
    BOOST_TEST(m_outputLayerCount == 1);
    BOOST_TEST(m_addLayerCount == 1);
}

BOOST_AUTO_TEST_SUITE(OptimizationViewsTestSuite)

BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCount)
{
    OptimizationViews view;
    // Construct a graph with 3 layers
    Graph& baseGraph = view.GetGraph();

    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input");

    Convolution2dDescriptor convDescriptor;
    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);
    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1");
    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2");
    Layer* const substitutableCompiledLayer =
            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output");

    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));
    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));
    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));

    // Subgraph for a failed layer
    SubgraphViewSelector::SubgraphViewPtr failedSubgraph =
        CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                               CreateOutputsFrom({convLayer1}),
                               {convLayer1});
    // Subgraph for an untouched layer
    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer2});
    // Subgraph for a substitutable layer
    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutableCompiledLayer});
    // Create a Graph containing a layer to substitute in
    Graph substitutableGraph;
    Layer* const substitutionpreCompiledLayer =
            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    // Subgraph for a substitution layer
    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),
                                   CreateOutputsFrom({substitutionpreCompiledLayer}),
                                   {substitutionpreCompiledLayer});

    // Sub in the graph
    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);

    view.AddFailedSubgraph(SubgraphView(*failedSubgraph));
    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));

    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutionpreCompiledLayer});
    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});

    // Construct original subgraph to compare against
    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
            CreateOutputsFrom({convLayer2}),
            {convLayer1, convLayer2, substitutionpreCompiledLayer});

    BOOST_CHECK(view.Validate(*originalSubgraph));
}

BOOST_AUTO_TEST_CASE(OptimizedViewsSubgraphLayerCountFailValidate)
{
    OptimizationViews view;
    // Construct a graph with 3 layers
    Graph& baseGraph = view.GetGraph();

    Layer* const inputLayer = baseGraph.AddLayer<InputLayer>(0, "input");

    Convolution2dDescriptor convDescriptor;
    PreCompiledDescriptor substitutionLayerDescriptor(1, 1);
    Layer* const convLayer1 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv1");
    Layer* const convLayer2 = baseGraph.AddLayer<Convolution2dLayer>(convDescriptor, "conv2");
    Layer* const substitutableCompiledLayer =
            baseGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    Layer* const outputLayer = baseGraph.AddLayer<OutputLayer>(0, "output");

    inputLayer->GetOutputSlot(0).Connect(convLayer1->GetInputSlot(0));
    convLayer1->GetOutputSlot(0).Connect(convLayer2->GetInputSlot(0));
    convLayer2->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0));

    // Subgraph for an untouched layer
    SubgraphViewSelector::SubgraphViewPtr untouchedSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer2}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer2});
    // Subgraph for a substitutable layer
    SubgraphViewSelector::SubgraphViewPtr substitutableSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutableCompiledLayer});
    // Create a Graph containing a layer to substitute in
    Graph substitutableGraph;
    Layer* const substitutionpreCompiledLayer =
            substitutableGraph.AddLayer<PreCompiledLayer>(substitutionLayerDescriptor, "pre-compiled");

    // Subgraph for a substitution layer
    SubgraphViewSelector::SubgraphViewPtr substitutionSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({substitutionpreCompiledLayer}),
                                   CreateOutputsFrom({substitutionpreCompiledLayer}),
                                   {substitutionpreCompiledLayer});

    // Sub in the graph
    baseGraph.SubstituteSubgraph(*substitutableSubgraph, *substitutionSubgraph);

    view.AddUntouchedSubgraph(SubgraphView(*untouchedSubgraph));

    SubgraphViewSelector::SubgraphViewPtr baseSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {substitutionpreCompiledLayer});
    view.AddSubstitution({*baseSubgraph, *substitutionSubgraph});

    // Construct original subgraph to compare against
    SubgraphViewSelector::SubgraphViewPtr originalSubgraph =
            CreateSubgraphViewFrom(CreateInputsFrom({convLayer1}),
                                   CreateOutputsFrom({convLayer2}),
                                   {convLayer1, convLayer2, substitutionpreCompiledLayer});

    // Validate should fail as convLayer1 is not counted
    BOOST_CHECK(!view.Validate(*originalSubgraph));
}

BOOST_AUTO_TEST_CASE(OptimizeViewsValidateDeviceMockBackend)
{
    // build up the structure of the network
    armnn::INetworkPtr net(armnn::INetwork::Create());

    armnn::IConnectableLayer* input = net->AddInputLayer(0, "inLayer0");
    armnn::IConnectableLayer* input1 = net->AddInputLayer(1, "inLayer1");

    armnn::IConnectableLayer* addition = net->AddAdditionLayer("addLayer");

    armnn::IConnectableLayer* output = net->AddOutputLayer(0, "outLayer");

    input->GetOutputSlot(0).Connect(addition->GetInputSlot(0));
    input1->GetOutputSlot(0).Connect(addition->GetInputSlot(1));
    addition->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    input->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));
    input1->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));
    addition->GetOutputSlot(0).SetTensorInfo(armnn::TensorInfo({ 1, 1, 4, 4 }, armnn::DataType::Float32));

    armnn::IRuntime::CreationOptions options;
    armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options));

    std::vector<armnn::BackendId> backends = { MockBackend().GetIdStatic() };
    armnn::IOptimizedNetworkPtr optNet = armnn::Optimize(*net, backends, runtime->GetDeviceSpec());
    BOOST_CHECK(optNet);

    // Check the optimised graph
    OptimizedNetwork* optNetObjPtr = boost::polymorphic_downcast<OptimizedNetwork*>(optNet.get());
    CheckLayers(optNetObjPtr->GetGraph());
}

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <bitset>
#include <sstream>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"
#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"

using namespace std;

// Global variables for client
static bool connectedToBinder = false;
static int clientBinderSocket = -1;
static int serverBinderSocket = -1;

// Global variables for server
static map<procedure_signature, skeleton, ps_compare> procSkeleDict;
static string serverIdentifier;
static unsigned int port = 0;
static int welcomeSocket = 0;
static bool onSwitch = true;

void mapPrint(){
  cout << "procSkeleDict size: "<<procSkeleDict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin();
   it != procSkeleDict.end(); ++it){

    cout << it->first.name << ", ";
  }

  cout << endl;
}

void printArgTypes(int * argTypes){
  cout << " Printing argTypes: " ;

  unsigned num = countNumOfArgTypes(argTypes);

  for(int i = 0; i < num; i++){
    cout << argTypes[i] << ", ";
  }
  cout << endl;
}

void printArgs(int * argTypes, void  ** args){
  cout << "Printing args: " ;

  // Parses the argument from the buffer
  unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1;

  cout<<"Number of args: " << numOfArgs << endl;

  for (unsigned int i = 0; i < numOfArgs; i++) {
    int argType = argTypes[i];
    int argTypeInformation =
      (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT;
    int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK;
    argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength;
    void *arg = args[i];

    switch (argTypeInformation) {
      case ARG_CHAR: {
        cout << "Printing ARG_CHAR: " << endl;
        char *argCharArray = (char *) arg;
        cout << argCharArray << endl;
        break;
      }

      case ARG_SHORT: {
        cout << "Printing ARG_SHORT: " << endl;
        short *argShortArray = (short *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argShortArray[i] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_INT: {
        cout << "Printing ARG_INT: " << endl;
        int *argIntArray = (int *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argIntArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_LONG: {
        cout << "Printing ARG_LONG: " << endl;
        long *argLongArray = (long *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argLongArray[j] << ",";
        }
        cout << endl;
        break;
      }

      case ARG_DOUBLE: {
        cout << "Printing ARG_DOUBLE: " << endl;
        double *argDoubleArray = (double *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argDoubleArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_FLOAT: {
        cout << "Printing ARG_FLOAT: " << endl;
        float *argFloatArray = (float *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argFloatArray[j] << ", ";
        }
        cout << endl;
        break;
      }
    }
  }
  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	/*
   * Creates a connection socket to be used for accepting connections
	 * from clients
   */
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);

  cout << "This servers welcomeSocket is: " << welcomeSocket << endl;

	// Opens a connection to the binderz
	serverBinderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(serverBinderSocket, binderAddress, binderPort);
  connectedToBinder = true;

  cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl;

  return 0;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Running rpcCall..." << endl;

	string serverAddress;
	unsigned int serverPort = 0;
	int status;

	if(!connectedToBinder){
    cout << "Connecting to binder..." << endl;
		clientBinderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(clientBinderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
    cout << "Connected to binder..." << endl;
	}
	//do something with returnVal

  LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes);
  Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << "LOC REQUEST message sent..." << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){

    Segment *parsedSegment = 0;
    int tempStatus = 0;
    tempStatus = Segment::receive(clientBinderSocket, parsedSegment);

    Message *messageFromBinder = parsedSegment->getMessage();
		switch (parsedSegment->getType()) {
			case MSG_TYPE_LOC_SUCCESS: {
				cout << "LOC SUCCESS message received..." << endl;
        LocSuccessMessage *lsm =
				  dynamic_cast<LocSuccessMessage *>(messageFromBinder);
				serverAddress = lsm->getServerIdentifier();
				serverPort = lsm->getPort();
				cout << "serverAddress: " << serverAddress << endl;
        cout << "serverPort: " << serverPort << endl;
        break;
			}

			case MSG_TYPE_LOC_FAILURE: {
        cout << "LOC FAILURE message received..." << endl;
				return -1;
				break;
			}
		}
	}

  cout << "Connecting to server..." << endl;
  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);

  cout << "status1: " << status1 << endl;
  cout << "Server Socket: " << serverSocket << endl;
  cout << "Server Address: " << serverAddress << endl;
  cout << "Server Port: " << serverPort << endl;
  cout << "Connected to server..." << endl;

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status2 =  exeReqSeg.send(serverSocket);

  cout << "Status of exeRegMsg send: " << status2 << endl;

  int returnVal = 0;

  Segment * parsedSegmentEsm = 0;
  int status3 = 0;
  status3 = Segment::receive(serverSocket, parsedSegmentEsm);
  cout << "Flag 1" << endl;

  //instead we have

  cout << "Flag 2" << endl;

  switch (parsedSegmentEsm->getType()) {
    case MSG_TYPE_EXECUTE_SUCCESS: {
      cout << "EXECUTE SUCCESS message received..." << endl;

      Message * msg = parsedSegmentEsm->getMessage();
      ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg);

      // TODO FIX: name = esm->getName();
      //argTypes = esm->getArgTypes();
      void** newArgs = esm->getArgs();
      unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1;

      for (unsigned int i = 0; i < numOfArgs; i++) {
        args[i] = newArgs[i];
      }

      break;
    }

    case MSG_TYPE_EXECUTE_FAILURE: {
      cout << "EXECUTE FAILURE message received..." << endl;

      Message * cast = parsedSegmentEsm->getMessage();
      ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
      returnVal = efm->getReasonCode();
      break;
    }
  }

  close(serverSocket);
  return returnVal;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){
  cout << "Running rpcRegister..." << endl;
  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);

  /*
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;
  */

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(serverBinderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(serverBinderSocket);

  cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl;
  //cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(serverBinderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      //struct procedure_signature k(string(name), argTypes);
      struct procedure_signature k = procedure_signature(string(name), argTypes);

      procSkeleDict[k] = f;

      cout << "k: " << k.name << ", "<< f << endl;

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

// See interface (header file).
int rpcExecute(){
  cout << "Running rpcExecute..." << endl;
  fd_set allSockets;
  fd_set readSockets;

  /*
   * Clears all entries from the all sockets set and the read
   * sockets set
   */
  FD_ZERO(&allSockets);
  FD_ZERO(&readSockets);

  /*
   * Adds the welcome socket to the all sockets set and sets
   * it as the maximum socket so far
   */
  FD_SET(serverBinderSocket, &allSockets);
  FD_SET(welcomeSocket, &allSockets);
  int maxSocket = welcomeSocket;

  while (onSwitch) {
    readSockets = allSockets;

    // Checks if some of the sockets are ready to be read from
    int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
    if (result < 0) {
      continue;
    }

    for (int i = 0; i <= maxSocket; i++) {
      if (!FD_ISSET(i, &readSockets)) {
        continue;
      }

      if (i == welcomeSocket) {

        /*
         * Creates the connection socket when a connection is made
         * to the welcome socket
         */
        int connectionSocket = acceptConnection(i);
        if (connectionSocket < 0) {
          continue;
        }

        // Adds the connection socket to the all sockets set
        FD_SET(connectionSocket, &allSockets);

        /*
         * Sets the connection socket as the maximum socket so far
         * if necessary
         */
        if (connectionSocket > maxSocket) {
          maxSocket = connectionSocket;
        }

      } else {

        /*
         * Creates a segment to receive data from the client/binder and
         * reads into it from the connection socket
         */
        Segment *segment = 0;
        result = 0;
        result = Segment::receive(i, segment);
        if (result < 0) {
          /*
           * Closes the connection socket and removes it from the
           * all sockets set
           */
          cout << "Bad result, I'm closing, i is: "<< i << endl;
          destroySocket(i);
          FD_CLR(i, &allSockets);
          continue;
        }

        switch (segment->getType()) {
          case MSG_TYPE_EXECUTE_REQUEST: {
            Message * cast = segment->getMessage();
            ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast);

            procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes());

            cout << "erm->getName(): " << erm->getName() << endl;
            printArgTypes(erm->getArgTypes());
            printArgs(erm->getArgTypes(), erm->getArgs());

            skeleton skel = procSkeleDict[*ps];

            if(skel == 0){
              cout << "Skel is null" << endl;
            }

            int result = skel(erm->getArgTypes(), erm->getArgs());

            cout << "Result: " << result << endl;
            printArgs(erm->getArgTypes(), erm->getArgs());

            if(result == 0 ){
              ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs());
              Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
              int tstatus = exeSuccessSeg.send(i);
              cout << "ExecuteSuccessMessage status: " << tstatus << endl;

            }else{
              ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result);
              Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
              int tstatus = exeFailSeg.send(i);
            }

            break;
          }

          case MSG_TYPE_TERMINATE: {
            cout << "Got to terminate" << endl;
            if (i != serverBinderSocket) {
               return ERROR_CODE_TERMINATE;
            }
            onSwitch = false;
            break;
          }
        }

      }
    }
  }

  // Destroys the welcome socket
  cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl;
  destroySocket(welcomeSocket);

  return SUCCESS_CODE;
}

int rpcCacheCall() {
  cout << "Running rpcCacheCall..." << endl;
	return SUCCESS_CODE;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;

  // Sends a terminate message to the binder
  TerminateMessage messageToBinder = TerminateMessage();
  Segment segmentToBinder =
    Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << segmentToBinder.getType() << endl;

  cout << "clientBinderSocket: " << clientBinderSocket << endl;
  // Closes the connection to the binder
  destroySocket(clientBinderSocket);

	return SUCCESS_CODE;
}
<commit_msg>changes<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <bitset>
#include <sstream>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"
#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_functions.h"

using namespace std;

// Global variables for client
static bool connectedToBinder = false;
static int clientBinderSocket = -1;
static int serverBinderSocket = -1;

// Global variables for server
static map<procedure_signature, skeleton, ps_compare> procSkeleDict;
static string serverIdentifier;
static unsigned int port = 0;
static int welcomeSocket = 0;
static bool onSwitch = true;

void mapPrint(){
  cout << "procSkeleDict size: "<<procSkeleDict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = procSkeleDict.begin();
   it != procSkeleDict.end(); ++it){

    cout << it->first.name << ", ";
  }

  cout << endl;
}

void printArgTypes(int * argTypes){
  cout << " Printing argTypes: " ;

  unsigned num = countNumOfArgTypes(argTypes);

  for(int i = 0; i < num; i++){
    cout << argTypes[i] << ", ";
  }
  cout << endl;
}

void printArgs(int * argTypes, void  ** args){
  cout << "Printing args: " ;

  // Parses the argument from the buffer
  unsigned numOfArgs = countNumOfArgTypes(argTypes) - 1;

  cout<<"Number of args: " << numOfArgs << endl;

  for (unsigned int i = 0; i < numOfArgs; i++) {
    int argType = argTypes[i];
    int argTypeInformation =
      (argType & ARG_TYPE_INFORMATION_MASK) >> ARG_TYPE_INFORMATION_SHIFT_AMOUNT;
    int argTypeArrayLength = argType & ARG_TYPE_ARRAY_LENGTH_MASK;
    argTypeArrayLength = (argTypeArrayLength == 0) ? 1: argTypeArrayLength;
    void *arg = args[i];

    switch (argTypeInformation) {
      case ARG_CHAR: {
        cout << "Printing ARG_CHAR: " << endl;
        char *argCharArray = (char *) arg;
        cout << argCharArray << endl;
        break;
      }

      case ARG_SHORT: {
        cout << "Printing ARG_SHORT: " << endl;
        short *argShortArray = (short *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argShortArray[i] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_INT: {
        cout << "Printing ARG_INT: " << endl;
        int *argIntArray = (int *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argIntArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_LONG: {
        cout << "Printing ARG_LONG: " << endl;
        long *argLongArray = (long *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argLongArray[j] << ",";
        }
        cout << endl;
        break;
      }

      case ARG_DOUBLE: {
        cout << "Printing ARG_DOUBLE: " << endl;
        double *argDoubleArray = (double *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argDoubleArray[j] << ", ";
        }
        cout << endl;
        break;
      }

      case ARG_FLOAT: {
        cout << "Printing ARG_FLOAT: " << endl;
        float *argFloatArray = (float *) arg;
        for (int j = 0; j < argTypeArrayLength; j++) {
          cout << argFloatArray[j] << ", ";
        }
        cout << endl;
        break;
      }
    }
  }
  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	/*
   * Creates a connection socket to be used for accepting connections
	 * from clients
   */
  cout << "B4 welcomeSocket is: " << welcomeSocket << endl;
  cout << "B4 serverBinderSocket is: " << serverBinderSocket << endl;

	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);

  cout << "This servers welcomeSocket is: " << welcomeSocket << endl;

	// Opens a connection to the binderz
	serverBinderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(serverBinderSocket, binderAddress, binderPort);
  connectedToBinder = true;

  cout << "This servers serverBinderSocket is: " << serverBinderSocket << endl;

  return 0;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Running rpcCall..." << endl;

	string serverAddress;
	unsigned int serverPort = 0;
	int status;

	if(!connectedToBinder){
    cout << "Connecting to binder..." << endl;
		clientBinderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(clientBinderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
    cout << "Connected to binder..." << endl;
	}
	//do something with returnVal

  LocRequestMessage messageToBinder = LocRequestMessage(string(name), argTypes);
  Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_LOC_REQUEST, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << "LOC REQUEST message sent..." << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){

    Segment *parsedSegment = 0;
    int tempStatus = 0;
    tempStatus = Segment::receive(clientBinderSocket, parsedSegment);

    Message *messageFromBinder = parsedSegment->getMessage();
		switch (parsedSegment->getType()) {
			case MSG_TYPE_LOC_SUCCESS: {
				cout << "LOC SUCCESS message received..." << endl;
        LocSuccessMessage *lsm =
				  dynamic_cast<LocSuccessMessage *>(messageFromBinder);
				serverAddress = lsm->getServerIdentifier();
				serverPort = lsm->getPort();
				cout << "serverAddress: " << serverAddress << endl;
        cout << "serverPort: " << serverPort << endl;
        break;
			}

			case MSG_TYPE_LOC_FAILURE: {
        cout << "LOC FAILURE message received..." << endl;
				return -1;
				break;
			}
		}
	}

  cout << "Connecting to server..." << endl;
  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);

  cout << "status1: " << status1 << endl;
  cout << "Server Socket: " << serverSocket << endl;
  cout << "Server Address: " << serverAddress << endl;
  cout << "Server Port: " << serverPort << endl;
  cout << "Connected to server..." << endl;

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status2 =  exeReqSeg.send(serverSocket);

  cout << "Status of exeRegMsg send: " << status2 << endl;

  int returnVal = 0;

  Segment * parsedSegmentEsm = 0;
  int status3 = 0;
  status3 = Segment::receive(serverSocket, parsedSegmentEsm);
  cout << "Flag 1" << endl;

  //instead we have

  cout << "Flag 2" << endl;

  switch (parsedSegmentEsm->getType()) {
    case MSG_TYPE_EXECUTE_SUCCESS: {
      cout << "EXECUTE SUCCESS message received..." << endl;

      Message * msg = parsedSegmentEsm->getMessage();
      ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(msg);

      // TODO FIX: name = esm->getName();
      //argTypes = esm->getArgTypes();
      void** newArgs = esm->getArgs();
      unsigned numOfArgs = countNumOfArgTypes(esm->getArgTypes()) - 1;

      for (unsigned int i = 0; i < numOfArgs; i++) {
        args[i] = newArgs[i];
      }

      break;
    }

    case MSG_TYPE_EXECUTE_FAILURE: {
      cout << "EXECUTE FAILURE message received..." << endl;

      Message * cast = parsedSegmentEsm->getMessage();
      ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
      returnVal = efm->getReasonCode();
      break;
    }
  }

  close(serverSocket);
  return returnVal;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){
  cout << "Running rpcRegister..." << endl;
  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);

  /*
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;
  */

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(serverBinderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(serverBinderSocket);

  cout << "When we register we use this serverBinderSocket: " << serverBinderSocket << endl;
  //cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(serverBinderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      //struct procedure_signature k(string(name), argTypes);
      struct procedure_signature k = procedure_signature(string(name), argTypes);

      procSkeleDict[k] = f;

      cout << "k: " << k.name << ", "<< f << endl;

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

// See interface (header file).
int rpcExecute(){
  cout << "Running rpcExecute..." << endl;
  fd_set allSockets;
  fd_set readSockets;

  /*
   * Clears all entries from the all sockets set and the read
   * sockets set
   */
  FD_ZERO(&allSockets);
  FD_ZERO(&readSockets);

  /*
   * Adds the welcome socket to the all sockets set and sets
   * it as the maximum socket so far
   */
  FD_SET(serverBinderSocket, &allSockets);
  FD_SET(welcomeSocket, &allSockets);
  int maxSocket = welcomeSocket;

  while (onSwitch) {
    readSockets = allSockets;

    // Checks if some of the sockets are ready to be read from
    int result = select(maxSocket + 1, &readSockets, 0, 0, 0);
    if (result < 0) {
      continue;
    }

    for (int i = 0; i <= maxSocket; i++) {
      if (!FD_ISSET(i, &readSockets)) {
        continue;
      }

      if (i == welcomeSocket) {

        /*
         * Creates the connection socket when a connection is made
         * to the welcome socket
         */
        int connectionSocket = acceptConnection(i);
        if (connectionSocket < 0) {
          continue;
        }

        // Adds the connection socket to the all sockets set
        FD_SET(connectionSocket, &allSockets);

        /*
         * Sets the connection socket as the maximum socket so far
         * if necessary
         */
        if (connectionSocket > maxSocket) {
          maxSocket = connectionSocket;
        }

      } else {

        /*
         * Creates a segment to receive data from the client/binder and
         * reads into it from the connection socket
         */
        Segment *segment = 0;
        result = 0;
        result = Segment::receive(i, segment);
        if (result < 0) {
          /*
           * Closes the connection socket and removes it from the
           * all sockets set
           */
          cout << "Bad result, I'm closing, i is: "<< i << endl;
          destroySocket(i);
          FD_CLR(i, &allSockets);
          continue;
        }

        switch (segment->getType()) {
          case MSG_TYPE_EXECUTE_REQUEST: {
            Message * cast = segment->getMessage();
            ExecuteRequestMessage * erm = dynamic_cast<ExecuteRequestMessage*>(cast);

            procedure_signature * ps = new procedure_signature(erm->getName(), erm->getArgTypes());

            cout << "erm->getName(): " << erm->getName() << endl;
            printArgTypes(erm->getArgTypes());
            printArgs(erm->getArgTypes(), erm->getArgs());

            skeleton skel = procSkeleDict[*ps];

            if(skel == 0){
              cout << "Skel is null" << endl;
            }

            int result = skel(erm->getArgTypes(), erm->getArgs());

            cout << "Result: " << result << endl;
            printArgs(erm->getArgTypes(), erm->getArgs());

            if(result == 0 ){
              ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(erm->getName(), erm->getArgTypes(), erm->getArgs());
              Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
              int tstatus = exeSuccessSeg.send(i);
              cout << "ExecuteSuccessMessage status: " << tstatus << endl;

            }else{
              ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(result);
              Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
              int tstatus = exeFailSeg.send(i);
            }

            break;
          }

          case MSG_TYPE_TERMINATE: {
            cout << "Got to terminate" << endl;
            if (i != serverBinderSocket) {
               return ERROR_CODE_TERMINATE;
            }
            onSwitch = false;
            break;
          }
        }

      }
    }
  }

  // Destroys the welcome socket
  cout << "We are destorying the welcomeSocket: " << welcomeSocket << endl;
  destroySocket(welcomeSocket);

  return SUCCESS_CODE;
}

int rpcCacheCall() {
  cout << "Running rpcCacheCall..." << endl;
	return SUCCESS_CODE;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;

  // Sends a terminate message to the binder
  TerminateMessage messageToBinder = TerminateMessage();
  Segment segmentToBinder =
    Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
  int binder_status = segmentToBinder.send(clientBinderSocket);
  cout << segmentToBinder.getType() << endl;

  cout << "clientBinderSocket: " << clientBinderSocket << endl;
  // Closes the connection to the binder
  destroySocket(clientBinderSocket);

	return SUCCESS_CODE;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <netdb.h>
#include <cstdlib>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"

#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

// Global variables for client
bool connectedToBinder = false;
int binderSocket = 0;

// Global variables for server
struct addrinfo* servinfo;
static map<procedure_signature, skeleton, ps_compare> proc_skele_dict;
string serverIdentifier;
unsigned int port = 0;
int welcomeSocket = 0;

void mapPrint(){
  cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin();
   it != proc_skele_dict.end(); ++it){

    cout << it->first.name << endl;
  }

  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	// Creates a connection socket to be used for accepting connections
	// from clients
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);
	cout << "SERVER IDENTIFIER: " << serverIdentifier << endl;
	cout << "PORT: " << port << endl;

	// Opens a connection to the binder
	binderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(binderSocket, binderAddress, binderPort);
  connectedToBinder = true;
  cout << "binderSocket: " << binderSocket << endl;

  return 0;
}

int sendExecute(int sock, string name, int* argTypes, void**args){

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status =  exeReqSeg.send(sock);

  int returnVal;

	string retName;
	int* retArgTypes;
	void** retArgs;

  if(status == 0){
    Segment * segment = 0;
    status = Segment::receive(sock, segment);

    if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
	 		ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(retName == name){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

    }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
  		Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
    	returnVal = efm->getReasonCode();
    }

  }else{ //Something bad happened
  	returnVal = 99;
  }

  return returnVal;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Flag0" << endl;

	string serverAddress;
	unsigned int serverPort;
	int status;

	if(!connectedToBinder){
		binderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(binderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
	}
	//do something with returnVal

  cout << "Flag1" << endl;

  LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes);
  Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg);
  int binder_status = locReqSeg.send(binderSocket);
  cout << "Flag1.5" << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){
	  cout << "Flag2" << endl;
    Segment * parsedSegment = 0;
    cout << "Flag2.1" << endl;
    int tempStatus = 0;
    cout << "Flag2.2" << endl;
    tempStatus = Segment::receive(binderSocket, parsedSegment);
    cout << "Flag2.5" << endl;

		if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST'
  		cout << "Got success" << endl;
      Message * cast = parsedSegment->getMessage();
  		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);
	  	serverAddress = lcm->getServerIdentifier();
	  	serverPort = lcm->getPort();
	  }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) {
			//something bad happens
	  	return 1;
	  }
	}

  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);
	status1 = sendExecute(serverSocket, string(name), argTypes, args);

	return status1;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){

  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(binderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(binderSocket);
  cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(binderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);

      proc_skele_dict[k] = f;

      //cout << "k: " << k.name << endl;
      mapPrint();

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

int rpcExecute(void){
	cout << "Running rpcExecute..." << endl;
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
				int connectionSocket = acceptConnection(welcomeSocket);
        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[*ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs());
                Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
                status = exeSuccessSeg.send(tempConnection);

              }else{
                ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode);
                Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
                status = exeFailSeg.send(tempConnection);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
  return 0;
}

int rpcCacheCall() {
	return 0;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;
	TerminateMessage messageToBinder = TerminateMessage();
	Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
	segmentToBinder.send(binderSocket);
	return 0;
}
<commit_msg>changes<commit_after>#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <netdb.h>
#include <cstdlib>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"

#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

// Global variables for client
bool connectedToBinder = false;
int binderSocket = 0;

// Global variables for server
struct addrinfo* servinfo;
static map<procedure_signature, skeleton, ps_compare> proc_skele_dict;
string serverIdentifier;
unsigned int port = 0;
int welcomeSocket = 0;

void mapPrint(){
  cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin();
   it != proc_skele_dict.end(); ++it){

    cout << it->first.name << endl;
  }

  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	// Creates a connection socket to be used for accepting connections
	// from clients
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);
	cout << "SERVER IDENTIFIER: " << serverIdentifier << endl;
	cout << "PORT: " << port << endl;

	// Opens a connection to the binder
	binderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(binderSocket, binderAddress, binderPort);
  connectedToBinder = true;
  cout << "binderSocket: " << binderSocket << endl;

  return 0;
}

int sendExecute(int sock, string name, int* argTypes, void**args){

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status =  exeReqSeg.send(sock);

  int returnVal;

	string retName;
	int* retArgTypes;
	void** retArgs;

  if(status == 0){
    Segment * segment = 0;
    status = Segment::receive(sock, segment);

    if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
	 		ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(retName == name){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

    }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
  		Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
    	returnVal = efm->getReasonCode();
    }

  }else{ //Something bad happened
  	returnVal = 99;
  }

  return returnVal;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Flag0" << endl;

	string serverAddress;
	unsigned int serverPort;
	int status;

	if(!connectedToBinder){
    cout << "Does it run" << endl;
		binderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(binderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
	}
	//do something with returnVal

  cout << "binderSocket: " <<binderSocket << endl;

  cout << "Flag1" << endl;

  LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes);
  Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg);
  int binder_status = locReqSeg.send(binderSocket);
  cout << "Flag1.5" << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){
	  cout << "Flag2" << endl;
    Segment * parsedSegment = 0;
    cout << "Flag2.1" << endl;
    int tempStatus = 0;
    cout << "Flag2.2" << endl;
    tempStatus = Segment::receive(binderSocket, parsedSegment);
    cout << "Flag2.5" << endl;

		if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST'
  		cout << "Got success" << endl;
      Message * cast = parsedSegment->getMessage();
  		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);
	  	serverAddress = lcm->getServerIdentifier();
	  	serverPort = lcm->getPort();
	  }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) {
			//something bad happens
	  	return 1;
	  }
	}

  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);
	status1 = sendExecute(serverSocket, string(name), argTypes, args);

	return status1;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){

  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(binderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(binderSocket);
  cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(binderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);

      proc_skele_dict[k] = f;

      //cout << "k: " << k.name << endl;
      mapPrint();

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

int rpcExecute(void){
	cout << "Running rpcExecute..." << endl;
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
				int connectionSocket = acceptConnection(welcomeSocket);
        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[*ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs());
                Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
                status = exeSuccessSeg.send(tempConnection);

              }else{
                ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode);
                Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
                status = exeFailSeg.send(tempConnection);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
  return 0;
}

int rpcCacheCall() {
	return 0;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;
	TerminateMessage messageToBinder = TerminateMessage();
	Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
	segmentToBinder.send(binderSocket);
	return 0;
}
<|endoftext|>


<commit_before>#include "server_functions.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>

#include <netdb.h>
#include <stdlib.h>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"

#include "rpc.h"
#include "constants.h"
#include "helper_function.h"
#include "message_types.h"
#include "message_results.h"

using namespace std;

bool connectedToBinder = false;
int binder_sock;

int connectedToBinder(){

	if(connectedToBinder){
		return 0;
	}

	char * binderAddressString = getenv ("BINDER_ADDRESS");
    char * binderPortString = getenv("BINDER_PORT");

  	if(binderAddressString == NULL){
        return 1;
    }

    if(binderPortString == NULL){
        return 2;
    }

    binder_sock = create_connection(binderAddressString, binderPortString);

    if (binder_sock < 0) {
        return 3;
    }else{
    	connectedToBinder = true;
    }

}

int sendExecute(int sock, char* name, int* argTypes, void**args){

    ExecuteRequestMessage execute_request = new ExecuteRequestMessage(name, argTypes, args);
    int status = execute_request->send(sock);
    int returnVal;

	char* retName;
	int* retArgTypes;
	void** retArgs

    if(status == 0){
		Segment * segment = 0;
        status = Segment::receive(sock, segment);

        if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
			ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(strcmp(retName, name)){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

        }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
			Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
        	returnVal = efm->getReasonCode();
        }

    }else{ //Something bad happened
    	returnVal = 99;
    }

    return returnVal
}

int rpcCall(char * name, int * argTypes, void ** args) {

	int returnVal;
	char *serverAddress;
	char *serverPort;
	int server_socket

	if(!connectedToBinder){
		returnVal = connectedToBinder();
	}
	//do something with returnVal

	LocRequestMessage loc_request = new LocRequestMessage(name, argTypes);
  	int binder_status = loc_request->send(binder_sock);
  	//maybe error check with binder_status

	/**Server stuff **/
	if(status == 0){
		Segment * segment = 0;
        status = Segment::receive(sock, segment);

		if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST'
    		Message * cast = segment->getMessage();
    		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);

		  	serverAddress = lcm->getServerIdentifier();
		  	serverPort = lcm->getPort();

	  	}else if(segment->getType() == MSG_TYPE_LOC_FAILURE){
			//something bad happens
	  		return 1;
	  	}
	}

    int server_sock = create_connection(serverAddress, serverPort);
	int server_status = sendExecute(server_sock, name, argTypes, args);

	return server_status;
}

static map<procedure_signature, skeleton> proc_skele_dict;
string serverIdentifier;
unsigned int port;
//int binder_sock; //only one binder socket variable
int sock;

	//TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

struct thread_data {
  int sock;
  vector<string> *buf;
};

void connect_to_binder() {
  char *serverAddress = getenv("BINDER_ADDRESS");
  char *port = getenv("BINDER_PORT");
  binder_sock = createConnection(serverAddress, port);
  return binder_sock;
}

int rpcRegister(char * name, int *argTypes, skeleton f){

  int binder_sock = connect_to_binder();
  int retStatus;

  RegisterRequestMessage request_message = new RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  int status = success_message->send(binder_sock);

  if(status == 0){
    //Success
    Segment * segment = 0;
    status = Segment::receive(binder_sock, segment);

    if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){
      Message * cast = segment->getMessage();
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);
      proc_skele_dict[k] = f;

    }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status > 0){
    //Warning
    return -99;
  }else if( status < 0){
    //Error
    return 99;
  }

}

int rpcExecute(void){
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;
  struct sockaddr_storage their_addr;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(sock, &readfds);

    n = sock;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(sock, &readfds)) {
        socklen_t addr_size = sizeof their_addr;
        int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size);

        if (new_sock < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          close(new_sock);
          continue;
        }

        myConnections.push_back(new_sock);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(sock, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage execute_success = new ExecuteSuccessMessage(name, eqm->getArgTypes(), eqm->getArgs());
                int status = execute_success->send(sock);
              }else{
                ExecuteFailureMessage execute_failure = new ExecuteFailureMessage(reasoncode);
                int status = execute_failure->send(sock);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(sock);
              return errorMsg;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
}

int rpcInit(void){
  int status;
  struct addrinfo hints;
  struct addrinfo* servinfo;
  struct addrinfo* p;

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  status = getaddrinfo(NULL, "0", &hints, &servinfo);

  if (status != 0) {
    fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
    return 0;
  }

  p = servinfo;
  sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

  status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen);
  status = listen(sock, 5);

  char hostname[256];
  gethostname(hostname, 256);

  struct sockaddr_in sin;
  socklen_t len = sizeof(sin);

  getsockname(sock, (struct sockaddr *)&sin, &len);

  stringstream ss;
  ss << ntohs(sin.sin_port);
  string ps = ss.str();

  serverIdentifier = hostname;
  port =  ntohs(sin.sin_port);

}<commit_msg>changes<commit_after>#include "server_functions.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>

#include <netdb.h>
#include <stdlib.h>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"

#include "rpc.h"
#include "constants.h"
#include "helper_function.h"
#include "message_types.h"
#include "message_results.h"

using namespace std;

bool connectedToBinder = false;
int binder_sock;

int connectToBinder(){

	if(connectedToBinder){
		return 0;
	}

	char * binderAddressString = getenv ("BINDER_ADDRESS");
    char * binderPortString = getenv("BINDER_PORT");

  	if(binderAddressString == NULL){
        return 1;
    }

    if(binderPortString == NULL){
        return 2;
    }

    binder_sock = createConnection(binderAddressString, binderPortString);

    if (binder_sock < 0) {
        return 3;
    }else{
    	connectedToBinder = true;
    }

}

int sendExecute(int sock, char* name, int* argTypes, void**args){

    ExecuteRequestMessage execute_request = new ExecuteRequestMessage(name, argTypes, args);
    int status = execute_request->send(sock);
    int returnVal;

	char* retName;
	int* retArgTypes;
	void** retArgs;

    if(status == 0){
		Segment * segment = 0;
        status = Segment::receive(sock, segment);

        if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
			ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(strcmp(retName, name)){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

        }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
			Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
        	returnVal = efm->getReasonCode();
        }

    }else{ //Something bad happened
    	returnVal = 99;
    }

    return returnVal
}

int rpcCall(char * name, int * argTypes, void ** args) {

	int returnVal;
	char *serverAddress;
	char *serverPort;
	int server_socket

	if(!connectedToBinder){
		returnVal = connectToBinder();
	}
	//do something with returnVal

	LocRequestMessage loc_request = new LocRequestMessage(name, argTypes);
  	int binder_status = loc_request->send(binder_sock);
  	//maybe error check with binder_status

	/**Server stuff **/
	if(status == 0){
		Segment * segment = 0;
        status = Segment::receive(sock, segment);

		if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST'
    		Message * cast = segment->getMessage();
    		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);

		  	serverAddress = lcm->getServerIdentifier();
		  	serverPort = lcm->getPort();

	  	}else if(segment->getType() == MSG_TYPE_LOC_FAILURE){
			//something bad happens
	  		return 1;
	  	}
	}

    int server_sock = createConnection(serverAddress, serverPort);
	int server_status = sendExecute(server_sock, name, argTypes, args);

	return server_status;
}

static map<procedure_signature, skeleton> proc_skele_dict;
string serverIdentifier;
unsigned int port;
//int binder_sock; //only one binder socket variable
int sock;

	//TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

struct thread_data {
  int sock;
  vector<string> *buf;
};

void connect_to_binder() {
  char *serverAddress = getenv("BINDER_ADDRESS");
  char *port = getenv("BINDER_PORT");
  binder_sock = createConnection(serverAddress, port);
  return binder_sock;
}

int rpcRegister(char * name, int *argTypes, skeleton f){

  int binder_sock = connect_to_binder();
  int retStatus;

  RegisterRequestMessage request_message = new RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  int status = success_message->send(binder_sock);

  if(status == 0){
    //Success
    Segment * segment = 0;
    status = Segment::receive(binder_sock, segment);

    if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){
      Message * cast = segment->getMessage();
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);
      proc_skele_dict[k] = f;

    }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status > 0){
    //Warning
    return -99;
  }else if( status < 0){
    //Error
    return 99;
  }

}

int rpcExecute(void){
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;
  struct sockaddr_storage their_addr;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(sock, &readfds);

    n = sock;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(sock, &readfds)) {
        socklen_t addr_size = sizeof their_addr;
        int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size);

        if (new_sock < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          close(new_sock);
          continue;
        }

        myConnections.push_back(new_sock);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(sock, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage execute_success = new ExecuteSuccessMessage(name, eqm->getArgTypes(), eqm->getArgs());
                int status = execute_success->send(sock);
              }else{
                ExecuteFailureMessage execute_failure = new ExecuteFailureMessage(reasoncode);
                int status = execute_failure->send(sock);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(sock);
              return errorMsg;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
}

int rpcInit(void){
  int status;
  struct addrinfo hints;
  struct addrinfo* servinfo;
  struct addrinfo* p;

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  status = getaddrinfo(NULL, "0", &hints, &servinfo);

  if (status != 0) {
    fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
    return 0;
  }

  p = servinfo;
  sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

  status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen);
  status = listen(sock, 5);

  char hostname[256];
  gethostname(hostname, 256);

  struct sockaddr_in sin;
  socklen_t len = sizeof(sin);

  getsockname(sock, (struct sockaddr *)&sin, &len);

  stringstream ss;
  ss << ntohs(sin.sin_port);
  string ps = ss.str();

  serverIdentifier = hostname;
  port =  ntohs(sin.sin_port);

}<|endoftext|>


<commit_before>#include "esmtools.hpp"

//----------------------------------------------------------
EsmTools::EsmTools(const std::string &path)
{
    esm.readFile(path);
}

//----------------------------------------------------------
std::string EsmTools::dumpFile()
{
    std::string dump;
    if(esm.getStatus() == true)
    {
        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)
        {
            size_t cur_pos = 16;
            size_t cur_size = 0;
            std::string cur_id;
            std::string cur_text;
            std::string rec;

            esm.setRecordTo(i);
            rec = esm.getRecordContent();
            dump += esm.getRecordId() + "\r\n";
            while(cur_pos != rec.size())
            {
                cur_id = rec.substr(cur_pos, 4);
                cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4));
                cur_text = rec.substr(cur_pos + 8, cur_size);
                cur_text = tools.replaceNonReadableCharsWithDot(cur_text);
                dump += "    " + cur_id + " " + std::to_string(cur_size) + " " + cur_text + "\r\n";
                cur_pos += 8 + cur_size;
            }
        }
    }
    return dump;
}

//----------------------------------------------------------
std::string EsmTools::makeScriptList()
{
    std::string scripts;
    if(esm.getStatus() == true)
    {
        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)
        {
            esm.setRecordTo(i);
            if(esm.getRecordId() == "SCPT")
            {
                esm.setUniqueTo("SCHD");
                scripts += esm.getUniqueText() + "\r\n";
                scripts += "---\r\n";
                esm.setFirstFriendlyTo("SCTX");
                scripts += esm.getFriendlyText() + "\r\n";
                scripts += "---\r\n";
                esm.setFirstFriendlyTo("SCDT", false);
                scripts += tools.replaceNonReadableCharsWithDot(esm.getFriendlyText()) + "\r\n";
                scripts += "---\r\n";
            }
        }
    }
    return scripts;
}
<commit_msg>add banm script list creator<commit_after>#include "esmtools.hpp"

//----------------------------------------------------------
EsmTools::EsmTools(const std::string &path)
{
    esm.readFile(path);
}

//----------------------------------------------------------
std::string EsmTools::dumpFile()
{
    std::string dump;
    if(esm.getStatus() == true)
    {
        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)
        {
            size_t cur_pos = 16;
            size_t cur_size = 0;
            std::string cur_id;
            std::string cur_text;
            std::string rec;

            esm.setRecordTo(i);
            rec = esm.getRecordContent();
            dump += esm.getRecordId() + "\r\n";
            while(cur_pos != rec.size())
            {
                cur_id = rec.substr(cur_pos, 4);
                cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4));
                cur_text = rec.substr(cur_pos + 8, cur_size);
                cur_text = tools.replaceNonReadableCharsWithDot(cur_text);
                dump += "    " + cur_id + " " + std::to_string(cur_size) + " " + cur_text + "\r\n";
                cur_pos += 8 + cur_size;
            }
        }
    }
    return dump;
}

//----------------------------------------------------------
std::string EsmTools::makeScriptList()
{
    std::string scripts;
    if(esm.getStatus() == true)
    {
        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)
        {
            esm.setRecordTo(i);
            if(esm.getRecordId() == "INFO")
            {
                esm.setUniqueTo("INAM");
                scripts += esm.getUniqueText() + "\r\n";
                scripts += "---\r\n";
                esm.setFirstFriendlyTo("BNAM");
                scripts += esm.getFriendlyText() + "\r\n";
                scripts += "---\r\n";
            }
            if(esm.getRecordId() == "SCPT")
            {
                esm.setUniqueTo("SCHD");
                scripts += esm.getUniqueText() + "\r\n";
                scripts += "---\r\n";
                esm.setFirstFriendlyTo("SCTX");
                scripts += esm.getFriendlyText() + "\r\n";
                scripts += "---\r\n";
                esm.setFirstFriendlyTo("SCDT", false);
                scripts += tools.replaceNonReadableCharsWithDot(esm.getFriendlyText()) + "\r\n";
                scripts += "---\r\n";
            }
        }
    }
    return scripts;
}
<|endoftext|>