Example #1
0
        public void ConnectServer()
        {
            try
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = Ice.Util.createProperties();

                string strConfigFile = GetProcessPath() + @"\..\Config\IceClientConfig.txt";
                try
                {
                    initData.properties.load(strConfigFile);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                communicator = Ice.Util.initialize(initData);
                string sProxy = strProxyKey + ".Proxy";
                string strProxy = initData.properties.getProperty(sProxy);
                m_objectPrx = communicator.stringToProxy(strProxy);

                GetProxy();

            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public Coordinator(string[] args)
        {
            _app = (App)System.Windows.Application.Current;
            ObjectDataProvider odp = (ObjectDataProvider)_app.Resources["UserList"];
            _users = (UserList)odp.Data;
            odp = (ObjectDataProvider)_app.Resources["ChatModel"];
            _model = (ChatModel)odp.Data;
            _args = args;

            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = Ice.Util.createProperties(ref _args);
            initData.dispatcher = delegate(System.Action action, Ice.Connection connection)
                {
                    if(_exit) // The GUI is being destroyed, don't use the GUI thread any more
                    {
                        action();
                    }
                    else
                    {
                        System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
                    }
                };

            if(initData.properties.getProperty("Ice.Default.Router").Length == 0)
            {
                initData.properties.setProperty("IceSSL.UsePlatformCAs", "1");
                initData.properties.setProperty("IceSSL.CheckCertName", "1");
                initData.properties.setProperty("Ice.Default.Router",
                                                "Glacier2/router:wss -p 443 -h zeroc.com -r /demo-proxy/chat/glacier2");
            }

            _factory = new Glacier2.SessionFactoryHelper(initData, this);
        }
Example #3
0
 /// <summary>
 /// Creates a SessionFactory object.
 /// </summary>
 /// <param name="callback">The callback object for notifications.</param>
 public SessionFactoryHelper(SessionCallback callback)
 {
     _callback = callback;
     _initData = new Ice.InitializationData();
     _initData.properties = Ice.Util.createProperties();
     setDefaultProperties();
 }
Example #4
0
 /// <summary>
 /// Creates a SessionFactory object.
 /// </summary>
 /// <param name="properties">The properties to use when creating the communicator.</param>
 /// <param name="callback">The callback object for notifications.</param>
 public SessionFactoryHelper(Ice.Properties properties, SessionCallback callback)
 {
     _callback = callback;
     _initData = new Ice.InitializationData();
     _initData.properties = properties;
     setDefaultProperties();
 }
Example #5
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = Ice.Util.createProperties();
                initData.properties.setProperty("Callback.Server.Endpoints", "tcp -h 0.0.0.0 -p " + txtPort.Text);
                _communicator = Ice.Util.initialize(initData);

                Ice.ObjectAdapter adapter = _communicator.createObjectAdapter("Callback.Server");
                _sender = new CallbackSenderI(_communicator);
                adapter.add(_sender, _communicator.stringToIdentity("sender"));
                adapter.activate();

                _thread = new Thread(new ThreadStart(_sender.Run));
                _thread.Start();
                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
            catch(Exception ex)
            {
                lblStatus.Text = "Start Failed: " + Environment.NewLine + ex.ToString();
            }
            lblStatus.Text = "Server started ok";
        }
Example #6
0
 public static int Main(string[] args)
 {
     Ice.InitializationData initData = new Ice.InitializationData();
     initData.properties = Ice.Util.createProperties();
     initData.properties.setProperty("Ice.Admin.DelayCreation", "1");
     App server = new App();
     return server.main(args, initData);
 }
Example #7
0
 /// <summary>
 /// Creates a SessionFactory object.
 /// </summary>
 /// <param name="initData">The initialization data to use when creating the communicator.</param>
 /// <param name="callback">The callback object for notifications.</param>
 public SessionFactoryHelper(Ice.InitializationData initData, SessionCallback callback)
 {
     _callback = callback;
     _initData = initData;
     if(_initData.properties == null)
     {
     _initData.properties = Ice.Util.createProperties();
     }
     setDefaultProperties();
 }
Example #8
0
 SessionFactoryHelper(Ice.Properties properties, SessionCallback callback)
 {
     if(properties == null)
     {
         throw new Ice.InitializationException(
                                     "Attempt to create a SessionFactoryHelper with a null Properties argument");
     }
     _callback = callback;
     _initData = new Ice.InitializationData();
     _initData.properties = properties;
     setDefaultProperties();
 }
Example #9
0
 public MainModel()
 {
     try {
         string[] commandLineArgs = Environment.GetCommandLineArgs();
         var properties = Ice.Util.createProperties(ref commandLineArgs);
         properties.setProperty("Ice.Default.EncodingVersion", "1.0");
         var initializationData = new Ice.InitializationData();
         initializationData.properties = properties;
         IceCommunicator = Ice.Util.initialize(initializationData);
     } catch (Ice.Exception e) {
         MessageBox.Show(e.ToString(), "Error initializing ICE", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     RefreshTimer.Interval = new TimeSpan(0, 0, 5);
     RefreshTimer.Tick += OnRefreshTimerTick;
     RefreshTimer.Start();
 }
        public ChatWindow()
        {
            Ice.InitializationData initData = new Ice.InitializationData();

            initData.properties = Ice.Util.createProperties();
            initData.properties.load("config.client");

            // Dispatch servant calls and AMI callbacks with this windows Dispatcher.
            initData.dispatcher = (System.Action action, Ice.Connection connection) =>
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
            };

            _factory = new SessionFactoryHelper(initData, this);
            InitializeComponent();
            Util.locateOnScreen(this);
        }
Example #11
0
 public MainForm()
 {
     InitializeComponent();
     try
     {
         Ice.InitializationData initData = new Ice.InitializationData();
         initData.properties = Ice.Util.createProperties();
         initData.dispatcher = (Ice.VoidAction action, Ice.Connection connection) =>
         {
             this.BeginInvoke(action);
         };
         _communicator = Ice.Util.initialize(initData);
     }
     catch(Ice.LocalException ex)
     {
         lblStatus.Text = "Exception: " + ex.ice_name();
     }
 }
Example #12
0
 private void Window_Loaded(object sender, EventArgs e)
 {
     try
     {
         Ice.InitializationData initData = new Ice.InitializationData();
         initData.properties = Ice.Util.createProperties();
         initData.properties.load("config.client");
         initData.dispatcher = delegate(System.Action action, Ice.Connection connection)
         {
             Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
         };
         _communicator = Ice.Util.initialize(initData);
     }
     catch(Ice.LocalException ex)
     {
         handleException(ex);
     }
 }
Example #13
0
        public MainPage(string defaultHost)
        {
            InitializeComponent();
            Mode.Items.Add(TWOWAY);
            Mode.Items.Add(TWOWAY_SECURE);
            Mode.Items.Add(ONEWAY);
            Mode.Items.Add(ONEWAY_BATCH);
            Mode.Items.Add(ONEWAY_SECURE);
            Mode.Items.Add(ONEWAY_SECURE_BATCH);
            Mode.Items.Add(DATAGRAM);
            Mode.Items.Add(DATAGRAM_BATCH);
            Mode.SelectedIndex         = 0;
            Hostname.Text              = defaultHost;
            Hostname.TextChanged      += Hostname_TextChanged;
            Mode.SelectedIndexChanged += Mode_SelectedIndexChanged;
            Timeout.ValueChanged      += Timeout_ValueChanged;

            Hello.Clicked    += Hello_Clicked;
            Shutdown.Clicked += Shutdown_Clicked;
            Flush.Clicked    += Flush_Clicked;

            IceSSL.Util.registerIceSSL(true);
            var initData = new Ice.InitializationData();

            initData.properties = Ice.Util.createProperties();
            initData.properties.setProperty("Ice.InitPlugins", "0");
            initData.dispatcher = (Action action, Ice.Connection connection) =>
            {
                Device.BeginInvokeOnMainThread(action);
            };
            _communicator = Ice.Util.initialize(initData);

            var plugin = (IceSSL.Plugin)_communicator.getPluginManager().getPlugin("IceSSL");

            plugin.setCertificates(loadCertificate("client.p12", "password"));
            plugin.setCACertificates(loadCertificate("cacert.der"));
            _communicator.getPluginManager().initializePlugins();
        }
        private void goBtn_Click(object sender, RoutedEventArgs e)
        {
            if (communicator_ == null)
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = Ice.Util.createProperties();
                initData.dispatcher = delegate(System.Action action, Ice.Connection connection)
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
                };
                communicator_ = Ice.Util.initialize(initData);
            }
            if (bitmapProvider_ == null)
            {
                string        connection = "IceStreamer:tcp -h " + tbIpAddress.Text + " -p 10000 -z";
                Ice.ObjectPrx prx        = communicator_.stringToProxy(connection);
                prx             = prx.ice_timeout(1000);
                bitmapProvider_ = Streamer.BitmapProviderPrxHelper.uncheckedCast(prx);
            }

            timer.Interval = new TimeSpan(1000);                  // Timer will tick event/second
            timer.Start();                                        // Start the timer
        }
Example #15
0
        public void ConnectServer()
        {
            try
            {
                //Disconnect();
                //communicator = Ice.Util.initialize();
                //remote =
                //   LogPrxHelper.checkedCast(communicator.stringToProxy("ICLog:tcp -p 15356"));

                //Init();
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = Ice.Util.createProperties();
                initData.properties.setProperty("ICLog.Proxy", "ICLog:tcp -p 15366");

                string strConfigFile = GetProcessPath() + @"\..\Config\IceClientConfig.txt";
                try
                {
                    initData.properties.load(strConfigFile);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                communicator = Ice.Util.initialize(initData);
                string strProxy = initData.properties.getProperty("ICLog.Proxy");
                remote =
                    LogPrxHelper.uncheckedCast(communicator.stringToProxy(strProxy));
                remote.ice_timeout(1000);
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                Console.WriteLine(ex.Message);
            }
        }
Example #16
0
        public void ConnectServer()
        {
            try
            {
                //Disconnect();
                //communicator = Ice.Util.initialize();
                //remote =
                 //   LogPrxHelper.checkedCast(communicator.stringToProxy("ICLog:tcp -p 15356"));

                //Init();
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = Ice.Util.createProperties();
                initData.properties.setProperty("ICLog.Proxy", "ICLog:tcp -p 15366");

                string strConfigFile = GetProcessPath() + @"\..\Config\IceClientConfig.txt";
                try
                {
                    initData.properties.load(strConfigFile);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                communicator = Ice.Util.initialize(initData);
                string strProxy = initData.properties.getProperty("ICLog.Proxy");
                remote =
                    LogPrxHelper.uncheckedCast(communicator.stringToProxy(strProxy));
                remote.ice_timeout(1000);
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                Console.WriteLine(ex.Message);
            }
        }
Example #17
0
 public Ice.Communicator initialize(Ice.Properties properties)
 {
     Ice.InitializationData initData = new Ice.InitializationData();
     initData.properties = properties;
     return(initialize(initData));
 }
Example #18
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing communicator operations... ");
                output.Flush();
                {
                    //
                    // Test: Exercise addAdminFacet, findAdminFacet, removeAdminFacet with a typical configuration.
                    //
                    Ice.InitializationData init = new Ice.InitializationData();
                    init.properties = Ice.Util.createProperties();
                    init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    init.properties.setProperty("Ice.Admin.InstanceName", "Test");
                    Ice.Communicator com = Ice.Util.initialize(init);
                    testFacets(com, true);
                    com.destroy();
                }
                {
                    //
                    // Test: Verify that the operations work correctly in the presence of facet filters.
                    //
                    Ice.InitializationData init = new Ice.InitializationData();
                    init.properties = Ice.Util.createProperties();
                    init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    init.properties.setProperty("Ice.Admin.InstanceName", "Test");
                    init.properties.setProperty("Ice.Admin.Facets", "Properties");
                    Ice.Communicator com = Ice.Util.initialize(init);
                    testFacets(com, false);
                    com.destroy();
                }
                {
                    //
                    // Test: Verify that the operations work correctly with the Admin object disabled.
                    //
                    Ice.Communicator com = Ice.Util.initialize();
                    testFacets(com, false);
                    com.destroy();
                }
                {
                    //
                    // Test: Verify that the operations work correctly with Ice.Admin.Enabled=1
                    //
                    Ice.InitializationData init = new Ice.InitializationData();
                    init.properties = Ice.Util.createProperties();
                    init.properties.setProperty("Ice.Admin.Enabled", "1");
                    Ice.Communicator com = Ice.Util.initialize(init);
                    test(com.getAdmin() == null);
                    Ice.Identity id = Ice.Util.stringToIdentity("test-admin");
                    try
                    {
                        com.createAdmin(null, id);
                        test(false);
                    }
                    catch (Ice.InitializationException)
                    {
                    }

                    Ice.ObjectAdapter adapter = com.createObjectAdapter("");
                    test(com.createAdmin(adapter, id) != null);
                    test(com.getAdmin() != null);

                    testFacets(com, true);
                    com.destroy();
                }
                {
                    //
                    // Test: Verify that the operations work correctly when creation of the Admin object is delayed.
                    //
                    Ice.InitializationData init = new Ice.InitializationData();
                    init.properties = Ice.Util.createProperties();
                    init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    init.properties.setProperty("Ice.Admin.InstanceName", "Test");
                    init.properties.setProperty("Ice.Admin.DelayCreation", "1");
                    Ice.Communicator com = Ice.Util.initialize(init);
                    testFacets(com, true);
                    com.getAdmin();
                    testFacets(com, true);
                    com.destroy();
                }
                output.WriteLine("ok");

                string @ref = "factory:" + helper.getTestEndpoint(0) + " -t 10000";

                Test.RemoteCommunicatorFactoryPrx factory =
                    Test.RemoteCommunicatorFactoryPrxHelper.uncheckedCast(communicator.stringToProxy(@ref));

                output.Write("testing process facet... ");
                output.Flush();
                {
                    //
                    // Test: Verify that Process::shutdown() operation shuts down the communicator.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    var            com  = factory.createCommunicator(props);
                    Ice.ObjectPrx  obj  = com.getAdmin();
                    Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
                    proc.shutdown();
                    com.waitForShutdown();
                    com.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing properties facet... ");
                output.Flush();
                {
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Prop1", "1");
                    props.Add("Prop2", "2");
                    props.Add("Prop3", "3");
                    var                    com = factory.createCommunicator(props);
                    Ice.ObjectPrx          obj = com.getAdmin();
                    Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");

                    //
                    // Test: PropertiesAdmin::getProperty()
                    //
                    test(pa.getProperty("Prop2").Equals("2"));
                    test(pa.getProperty("Bogus").Equals(""));

                    //
                    // Test: PropertiesAdmin::getProperties()
                    //
                    Dictionary <string, string> pd = pa.getPropertiesForPrefix("");
                    test(pd.Count == 5);
                    test(pd["Ice.Admin.Endpoints"].Equals("tcp -h 127.0.0.1"));
                    test(pd["Ice.Admin.InstanceName"].Equals("Test"));
                    test(pd["Prop1"].Equals("1"));
                    test(pd["Prop2"].Equals("2"));
                    test(pd["Prop3"].Equals("3"));

                    Dictionary <string, string> changes;

                    //
                    // Test: PropertiesAdmin::setProperties()
                    //
                    Dictionary <string, string> setProps = new Dictionary <string, string>();
                    setProps.Add("Prop1", "10"); // Changed
                    setProps.Add("Prop2", "20"); // Changed
                    setProps.Add("Prop3", "");   // Removed
                    setProps.Add("Prop4", "4");  // Added
                    setProps.Add("Prop5", "5");  // Added
                    pa.setProperties(setProps);
                    test(pa.getProperty("Prop1").Equals("10"));
                    test(pa.getProperty("Prop2").Equals("20"));
                    test(pa.getProperty("Prop3").Equals(""));
                    test(pa.getProperty("Prop4").Equals("4"));
                    test(pa.getProperty("Prop5").Equals("5"));
                    changes = com.getChanges();
                    test(changes.Count == 5);
                    test(changes["Prop1"].Equals("10"));
                    test(changes["Prop2"].Equals("20"));
                    test(changes["Prop3"].Equals(""));
                    test(changes["Prop4"].Equals("4"));
                    test(changes["Prop5"].Equals("5"));
                    pa.setProperties(setProps);
                    changes = com.getChanges();
                    test(changes.Count == 0);

                    com.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing logger facet... ");
                output.Flush();
                {
                    Dictionary <String, String> props = new Dictionary <String, String>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("NullLogger", "1");
                    var com = factory.createCommunicator(props);

                    com.trace("testCat", "trace");
                    com.warning("warning");
                    com.error("error");
                    com.print("print");

                    Ice.ObjectPrx      obj    = com.getAdmin();
                    Ice.LoggerAdminPrx logger = Ice.LoggerAdminPrxHelper.checkedCast(obj, "Logger");
                    test(logger != null);

                    string prefix = null;

                    //
                    // Get all
                    //
                    Ice.LogMessage[] logMessages = logger.getLog(null, null, -1, out prefix);

                    test(logMessages.Length == 4);
                    test(prefix.Equals("NullLogger"));
                    test(logMessages[0].traceCategory.Equals("testCat") && logMessages[0].message.Equals("trace"));
                    test(logMessages[1].message.Equals("warning"));
                    test(logMessages[2].message.Equals("error"));
                    test(logMessages[3].message.Equals("print"));

                    //
                    // Get only errors and warnings
                    //
                    com.error("error2");
                    com.print("print2");
                    com.trace("testCat", "trace2");
                    com.warning("warning2");

                    Ice.LogMessageType[] messageTypes =
                    {
                        Ice.LogMessageType.ErrorMessage,
                        Ice.LogMessageType.WarningMessage
                    };

                    logMessages = logger.getLog(messageTypes, null, -1, out prefix);

                    test(logMessages.Length == 4);
                    test(prefix.Equals("NullLogger"));

                    foreach (var msg in logMessages)
                    {
                        test(msg.type == Ice.LogMessageType.ErrorMessage ||
                             msg.type == Ice.LogMessageType.WarningMessage);
                    }

                    //
                    // Get only errors and traces with Cat = "testCat"
                    //
                    com.trace("testCat2", "A");
                    com.trace("testCat", "trace3");
                    com.trace("testCat2", "B");

                    messageTypes = new Ice.LogMessageType[] {
                        Ice.LogMessageType.ErrorMessage,
                        Ice.LogMessageType.TraceMessage
                    };
                    string[] categories = { "testCat" };
                    logMessages = logger.getLog(messageTypes, categories, -1, out prefix);
                    test(logMessages.Length == 5);
                    test(prefix.Equals("NullLogger"));

                    foreach (var msg in logMessages)
                    {
                        test(msg.type == Ice.LogMessageType.ErrorMessage ||
                             (msg.type == Ice.LogMessageType.TraceMessage && msg.traceCategory.Equals("testCat")));
                    }

                    //
                    // Same, but limited to last 2 messages(trace3 + error3)
                    //
                    com.error("error3");

                    logMessages = logger.getLog(messageTypes, categories, 2, out prefix);
                    test(logMessages.Length == 2);
                    test(prefix.Equals("NullLogger"));

                    test(logMessages[0].message.Equals("trace3"));
                    test(logMessages[1].message.Equals("error3"));

                    //
                    // Now, test RemoteLogger
                    //
                    Ice.ObjectAdapter adapter =
                        communicator.createObjectAdapterWithEndpoints("RemoteLoggerAdapter", "tcp -h localhost");

                    RemoteLoggerI remoteLogger = new RemoteLoggerI();

                    Ice.RemoteLoggerPrx myProxy =
                        Ice.RemoteLoggerPrxHelper.uncheckedCast(adapter.addWithUUID(remoteLogger));

                    adapter.activate();

                    //
                    // No filtering
                    //
                    logMessages = logger.getLog(null, null, -1, out prefix);

                    logger.attachRemoteLogger(myProxy, null, null, -1);
                    remoteLogger.wait(1);

                    foreach (var m in logMessages)
                    {
                        remoteLogger.checkNextInit(prefix, m.type, m.message, m.traceCategory);
                    }

                    com.trace("testCat", "rtrace");
                    com.warning("rwarning");
                    com.error("rerror");
                    com.print("rprint");

                    remoteLogger.wait(4);

                    remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace", "testCat");
                    remoteLogger.checkNextLog(Ice.LogMessageType.WarningMessage, "rwarning", "");
                    remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror", "");
                    remoteLogger.checkNextLog(Ice.LogMessageType.PrintMessage, "rprint", "");

                    test(logger.detachRemoteLogger(myProxy));
                    test(!logger.detachRemoteLogger(myProxy));

                    //
                    // Use Error + Trace with "traceCat" filter with 4 limit
                    //
                    logMessages = logger.getLog(messageTypes, categories, 4, out prefix);
                    test(logMessages.Length == 4);

                    logger.attachRemoteLogger(myProxy, messageTypes, categories, 4);
                    remoteLogger.wait(1);

                    foreach (var m in logMessages)
                    {
                        remoteLogger.checkNextInit(prefix, m.type, m.message, m.traceCategory);
                    }

                    com.warning("rwarning2");
                    com.trace("testCat", "rtrace2");
                    com.warning("rwarning3");
                    com.error("rerror2");
                    com.print("rprint2");

                    remoteLogger.wait(2);

                    remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace2", "testCat");
                    remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror2", "");

                    //
                    // Attempt reconnection with slightly different proxy
                    //
                    try
                    {
                        logger.attachRemoteLogger(Ice.RemoteLoggerPrxHelper.uncheckedCast(myProxy.ice_oneway()),
                                                  messageTypes, categories, 4);
                        test(false);
                    }
                    catch (Ice.RemoteLoggerAlreadyAttachedException)
                    {
                        // expected
                    }

                    com.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing custom facet... ");
                output.Flush();
                {
                    //
                    // Test: Verify that the custom facet is present.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    var           com = factory.createCommunicator(props);
                    Ice.ObjectPrx obj = com.getAdmin();
                    var           tf  = Test.TestFacetPrxHelper.checkedCast(obj, "TestFacet");
                    tf.op();
                    com.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing facet filtering... ");
                output.Flush();
                {
                    //
                    // Test: Set Ice.Admin.Facets to expose only the Properties facet,
                    // meaning no other facet is available.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Ice.Admin.Facets", "Properties");
                    var            com  = factory.createCommunicator(props);
                    Ice.ObjectPrx  obj  = com.getAdmin();
                    Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
                    test(proc == null);
                    var tf = Test.TestFacetPrxHelper.checkedCast(obj, "TestFacet");
                    test(tf == null);
                    com.destroy();
                }
                {
                    //
                    // Test: Set Ice.Admin.Facets to expose only the Process facet,
                    // meaning no other facet is available.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Ice.Admin.Facets", "Process");
                    var                    com = factory.createCommunicator(props);
                    Ice.ObjectPrx          obj = com.getAdmin();
                    Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
                    test(pa == null);
                    var tf = Test.TestFacetPrxHelper.checkedCast(obj, "TestFacet");
                    test(tf == null);
                    com.destroy();
                }
                {
                    //
                    // Test: Set Ice.Admin.Facets to expose only the TestFacet facet,
                    // meaning no other facet is available.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Ice.Admin.Facets", "TestFacet");
                    var                    com = factory.createCommunicator(props);
                    Ice.ObjectPrx          obj = com.getAdmin();
                    Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
                    test(pa == null);
                    Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
                    test(proc == null);
                    com.destroy();
                }
                {
                    //
                    // Test: Set Ice.Admin.Facets to expose two facets. Use whitespace to separate the
                    // facet names.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Ice.Admin.Facets", "Properties TestFacet");
                    var                    com = factory.createCommunicator(props);
                    Ice.ObjectPrx          obj = com.getAdmin();
                    Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
                    test(pa.getProperty("Ice.Admin.InstanceName").Equals("Test"));
                    var tf = Test.TestFacetPrxHelper.checkedCast(obj, "TestFacet");
                    tf.op();
                    Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
                    test(proc == null);
                    com.destroy();
                }
                {
                    //
                    // Test: Set Ice.Admin.Facets to expose two facets. Use a comma to separate the
                    // facet names.
                    //
                    Dictionary <string, string> props = new Dictionary <string, string>();
                    props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
                    props.Add("Ice.Admin.InstanceName", "Test");
                    props.Add("Ice.Admin.Facets", "TestFacet, Process");
                    var                    com = factory.createCommunicator(props);
                    Ice.ObjectPrx          obj = com.getAdmin();
                    Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
                    test(pa == null);
                    var tf = Test.TestFacetPrxHelper.checkedCast(obj, "TestFacet");
                    tf.op();
                    Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
                    proc.shutdown();
                    com.waitForShutdown();
                    com.destroy();
                }
                output.WriteLine("ok");

                factory.shutdown();
            }
Example #19
0
        private TraceLevels _traceLevels; // Immutable, not reset by destroy().

        #endregion Fields

        #region Constructors

        //
        // Only for use by Ice.CommunicatorI
        //
        public Instance(Ice.Communicator communicator, Ice.InitializationData initData)
        {
            _state = StateActive;
            _initData = initData;

            try
            {
                if(_initData.properties == null)
                {
                    _initData.properties = Ice.Util.createProperties();
                }

                lock(_staticLock)
                {
                    if(!_oneOffDone)
                    {
                        string stdOut = _initData.properties.getProperty("Ice.StdOut");
                        string stdErr = _initData.properties.getProperty("Ice.StdErr");

                        System.IO.StreamWriter outStream = null;

                        if(stdOut.Length > 0)
                        {
                            try
                            {
                                outStream = System.IO.File.AppendText(stdOut);
                            }
                            catch(System.IO.IOException ex)
                            {
                                Ice.FileException fe = new Ice.FileException(ex);
                                fe.path = stdOut;
                                throw fe;
                            }
                            outStream.AutoFlush = true;
                            System.Console.Out.Close();
                            System.Console.SetOut(outStream);
                        }
                        if(stdErr.Length > 0)
                        {
                            if(stdErr.Equals(stdOut))
                            {
                                System.Console.SetError(outStream);
                            }
                            else
                            {
                                System.IO.StreamWriter errStream = null;
                                try
                                {
                                    errStream = System.IO.File.AppendText(stdErr);
                                }
                                catch(System.IO.IOException ex)
                                {
                                    Ice.FileException fe = new Ice.FileException(ex);
                                    fe.path = stdErr;
                                    throw fe;
                                }
                                errStream.AutoFlush = true;
                                System.Console.Error.Close();
                                System.Console.SetError(errStream);
                            }
                        }

                        _oneOffDone = true;
                    }
                }

                if(_initData.logger == null)
                {
                    string logfile = _initData.properties.getProperty("Ice.LogFile");
                    if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0)
                    {
                        if(logfile.Length != 0)
                        {
                            throw new Ice.InitializationException("Ice.LogFile and Ice.UseSyslog cannot both be set.");
                        }
                        _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"),
                            _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER"));
                    }
                    else if(logfile.Length != 0 || Ice.Util.getProcessLogger() is Ice.LoggerI)
                    {
                        //
                        // Ice.ConsoleListener is enabled by default unless Ice.LogFile is set.
                        //
                        bool console =
                            _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener",
                                                                             logfile.Length == 0 ? 1 : 0) > 0;
                        _initData.logger =
                            new Ice.TraceLoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile, console);
                    }
                    else
                    {
                        _initData.logger = Ice.Util.getProcessLogger();
                    }
                }

                _traceLevels = new TraceLevels(_initData.properties);

                _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties);

            #if COMPACT
                _factoryAssemblies = _initData.properties.getPropertyAsList("Ice.FactoryAssemblies");
            #endif

                {
                    const int defaultMessageSizeMax = 1024;
                    int num =
                        _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax);
                    if(num < 1)
                    {
                        _messageSizeMax = defaultMessageSizeMax * 1024; // Ignore non-sensical values.
                    }
                    else if(num > 0x7fffffff / 1024)
                    {
                        _messageSizeMax = 0x7fffffff;
                    }
                    else
                    {
                        _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes
                    }
                }

                //
                // Client ACM enabled by default. Server ACM disabled by default.
                //
                _clientACM = _initData.properties.getPropertyAsIntWithDefault("Ice.ACM.Client", 60);
                _serverACM = _initData.properties.getPropertyAsInt("Ice.ACM.Server");

                _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext"));
                _routerManager = new RouterManager();

                _locatorManager = new LocatorManager(_initData.properties);

                _referenceFactory = new ReferenceFactory(this, communicator);

                _proxyFactory = new ProxyFactory(this);

                bool ipv4 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
                bool ipv6 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv6", 0) > 0;
                if(!ipv4 && !ipv6)
                {
                    throw new Ice.InitializationException("Both IPV4 and IPv6 support cannot be disabled.");
                }
                else if(ipv4 && ipv6)
                {
                    _protocolSupport = Network.EnableBoth;
                }
                else if(ipv4)
                {
                    _protocolSupport = Network.EnableIPv4;
                }
                else
                {
                    _protocolSupport = Network.EnableIPv6;
                }
                _endpointFactoryManager = new EndpointFactoryManager(this);
                EndpointFactory tcpEndpointFactory = new TcpEndpointFactory(this);
                _endpointFactoryManager.add(tcpEndpointFactory);
                EndpointFactory udpEndpointFactory = new UdpEndpointFactory(this);
                _endpointFactoryManager.add(udpEndpointFactory);

                _pluginManager = new Ice.PluginManagerI(communicator);

                _outgoingConnectionFactory = new OutgoingConnectionFactory(this);

                _servantFactoryManager = new ObjectFactoryManager();

                _objectAdapterFactory = new ObjectAdapterFactory(this, communicator);

                _retryQueue = new RetryQueue(this);

                string[] facetFilter = _initData.properties.getPropertyAsList("Ice.Admin.Facets");
                if(facetFilter.Length > 0)
                {
                    foreach(string s in facetFilter)
                    {
                        _adminFacetFilter.Add(s);
                    }
                }
                _adminFacets.Add("Properties", new PropertiesAdminI(_initData.properties));
                _adminFacets.Add("Process", new ProcessI(communicator));
            }
            catch(Ice.LocalException)
            {
                destroy();
                throw;
            }
        }
Example #20
0
            public static void allTestsWithController(global::Test.TestHelper helper, Test.ControllerPrx controller)
            {
                var    communicator = helper.communicator();
                string sref         = "timeout:" + helper.getTestEndpoint(0);
                var    timeout      = TimeoutPrx.Parse(sref, communicator);
                var    output       = helper.getWriter();

                output.Write("testing connect timeout... ");
                output.Flush();
                {
                    //
                    // Expect ConnectTimeoutException.
                    //
                    var to = timeout.Clone(connectionTimeout: 100);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                {
                    //
                    // Expect success.
                    //
                    var to = timeout.Clone(connectionTimeout: -1);
                    controller.holdAdapter(100);
                    try
                    {
                        to.op();
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                        test(false);
                    }
                }
                output.WriteLine("ok");

                // The sequence needs to be large enough to fill the write/recv buffers
                byte[] seq = new byte[2000000];

                output.Write("testing connection timeout... ");
                output.Flush();
                {
                    //
                    // Expect TimeoutException.
                    //
                    var to = timeout.Clone(connectionTimeout: 250);
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                {
                    //
                    // Expect success.
                    //
                    var to = timeout.Clone(connectionTimeout: 2000);
                    controller.holdAdapter(100);
                    try
                    {
                        to.sendData(new byte[1000000]);
                    }
                    catch (TimeoutException)
                    {
                        test(false);
                    }
                }
                output.WriteLine("ok");

                output.Write("testing invocation timeout... ");
                output.Flush();
                {
                    var connection = timeout.GetConnection();
                    var to         = timeout.Clone(invocationTimeout: 100);
                    test(connection == to.GetConnection());
                    try
                    {
                        to.sleep(1000);
                        test(false);
                    }
                    catch (InvocationTimeoutException)
                    {
                    }
                    timeout.IcePing();
                    to = timeout.Clone(invocationTimeout: 1000);
                    test(connection == to.GetConnection());
                    try
                    {
                        to.sleep(100);
                    }
                    catch (InvocationTimeoutException)
                    {
                        test(false);
                    }
                    test(connection == to.GetConnection());
                }
                {
                    //
                    // Expect InvocationTimeoutException.
                    //
                    var to = timeout.Clone(invocationTimeout: 100);
                    try
                    {
                        to.sleepAsync(1000).Wait();
                    }
                    catch (System.AggregateException ex) when(ex.InnerException is InvocationTimeoutException)
                    {
                    }
                    timeout.IcePing();
                }
                {
                    //
                    // Expect success.
                    //
                    var to = timeout.Clone(invocationTimeout: 1000);
                    to.sleepAsync(100).Wait();
                }
                {
                    //
                    // Backward compatible connection timeouts
                    //
                    var to  = timeout.Clone(invocationTimeout: -2, connectionTimeout: 250);
                    var con = connect(to);
                    try
                    {
                        to.sleep(750);
                        test(false);
                    }
                    catch (TimeoutException)
                    {
                        try
                        {
                            con.getInfo();
                            test(false);
                        }
                        catch (TimeoutException)
                        {
                            // Connection got closed as well.
                        }
                    }
                    timeout.IcePing();

                    try
                    {
                        con = connect(to);
                        to.sleepAsync(750).Wait();
                        test(false);
                    }
                    catch (System.AggregateException ex) when(ex.InnerException is TimeoutException)
                    {
                        try
                        {
                            con.getInfo();
                            test(false);
                        }
                        catch (TimeoutException)
                        {
                            // Connection got closed as well.
                        }
                    }
                    timeout.IcePing();
                }
                output.WriteLine("ok");

                output.Write("testing close timeout... ");
                output.Flush();
                {
                    var to         = timeout.Clone(connectionTimeout: 250);
                    var connection = connect(to);
                    controller.holdAdapter(-1);
                    connection.close(Ice.ConnectionClose.GracefullyWithWait);
                    try
                    {
                        connection.getInfo(); // getInfo() doesn't throw in the closing state.
                    }
                    catch (LocalException)
                    {
                        test(false);
                    }

                    while (true)
                    {
                        try
                        {
                            connection.getInfo();
                            Thread.Sleep(10);
                        }
                        catch (ConnectionManuallyClosedException ex)
                        {
                            // Expected.
                            test(ex.graceful);
                            break;
                        }
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                output.WriteLine("ok");

                output.Write("testing timeout overrides... ");
                output.Flush();
                {
                    //
                    // Test Ice.Override.Timeout. This property overrides all
                    // endpoint timeouts.
                    //
                    var initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().Clone();
                    initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
                    initData.properties.setProperty("Ice.Override.Timeout", "100");
                    var comm = helper.initialize(initData);
                    var to   = TimeoutPrx.Parse(sref, comm);
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Calling ice_timeout() should have no effect.
                    //
                    to = to.Clone(connectionTimeout: 1000);
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                    comm.destroy();
                }
                {
                    //
                    // Test Ice.Override.ConnectTimeout.
                    //
                    var initData = new InitializationData();
                    initData.properties = communicator.getProperties().Clone();
                    initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
                    var comm = helper.initialize(initData);
                    controller.holdAdapter(-1);
                    var to = TimeoutPrx.Parse(sref, comm);
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Calling ice_timeout() should have no effect on the connect timeout.
                    //
                    controller.holdAdapter(-1);
                    to = to.Clone(connectionTimeout: 1000);
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Verify that timeout set via ice_timeout() is still used for requests.
                    //
                    to = to.Clone(connectionTimeout: 250);
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                    comm.destroy();
                }
                {
                    //
                    // Test Ice.Override.CloseTimeout.
                    //
                    var initData = new InitializationData();
                    initData.properties = communicator.getProperties().Clone();
                    initData.properties.setProperty("Ice.Override.CloseTimeout", "100");
                    var comm = helper.initialize(initData);
                    IObjectPrx.Parse(sref, comm).GetConnection();
                    controller.holdAdapter(-1);
                    long begin = System.DateTime.Now.Ticks;
                    comm.destroy();
                    test(((long)new System.TimeSpan(System.DateTime.Now.Ticks - begin).TotalMilliseconds - begin) < 1000);
                    controller.resumeAdapter();
                }
                output.WriteLine("ok");

                output.Write("testing invocation timeouts with collocated calls... ");
                output.Flush();
                {
                    communicator.getProperties().setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                    var adapter = communicator.createObjectAdapter("TimeoutCollocated");
                    adapter.Activate();

                    var proxy = adapter.Add(new TimeoutI()).Clone(invocationTimeout: 100);
                    try
                    {
                        proxy.sleep(500);
                        test(false);
                    }
                    catch (InvocationTimeoutException)
                    {
                    }

                    try
                    {
                        proxy.sleepAsync(500).Wait();
                        test(false);
                    }
                    catch (System.AggregateException ex) when(ex.InnerException is InvocationTimeoutException)
                    {
                    }

                    try
                    {
                        proxy.Clone(invocationTimeout: -2).IcePing();
                        proxy.Clone(invocationTimeout: -2).IcePingAsync().Wait();
                    }
                    catch (System.Exception)
                    {
                        test(false);
                    }

                    adapter.Destroy();
                }
                output.WriteLine("ok");

                controller.shutdown();
            }
Example #21
0
        private void startService(string service, string entryPoint, string[] args)
        {
            _m.Lock();
            try
            {
            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;

            //
            // Retrieve the assembly name and the type.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1)
            {
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   System.Char.IsLetter(entryPoint[0]) &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format: " + entryPoint;
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            try
            {
                //
                // First try to load the assemby using Assembly.Load which will succeed
                // if full name is configured or partial name has been qualified in config.
                // If that fails, try Assembly.LoadFrom() which will succeed if a file name
                // is configured or partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            string className = entryPoint.Substring(sepPos + 1);
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            try
            {
                //
                // If the service class provides a constructor that accepts an Ice.Communicator argument,
                // use that in preference to the default constructor.
                //
                Type[] parameterTypes = new Type[1];
                parameterTypes[0] = typeof(Ice.Communicator);
                System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                if(ci != null)
                {
                    try
                    {
                        Object[] parameters = new Object[1];
                        parameters[0] = _communicator;
                        info.service = (Service)ci.Invoke(parameters);
                    }
                    catch(System.MethodAccessException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                        throw e;
                    }
                }
                else
                {
                    //
                    // Fall back to the default constructor.
                    //
                    try
                    {
                        info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                        if(info.service == null)
                        {
                            FailureException e = new FailureException();
                            e.reason = err + "no default constructor for '" + className + "'";
                            throw e;
                        }
                    }
                    catch(System.UnauthorizedAccessException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "unauthorized access to default service constructor for " + className;
                        throw e;
                    }
                }
            }
            catch(FailureException)
            {
                throw;
            }
            catch(System.InvalidCastException ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "service does not implement IceBox.Service";
                throw e;
            }
            catch(System.Reflection.TargetInvocationException ex)
            {
                if(ex.InnerException is IceBox.FailureException)
                {
                    throw ex.InnerException;
                }
                else
                {
                    FailureException e = new FailureException(ex.InnerException);
                    e.reason = "ServiceManager: exception in service constructor for " + className;
                    throw e;
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "exception in service constructor " + className;
                throw e;
            }

            //
            // Invoke Service::start().
            //
            try
            {
                //
                // If IceBox.UseSharedCommunicator.<name> is defined, create a
                // communicator for the service. The communicator inherits
                // from the shared communicator properties. If it's not
                // defined, add the service properties to the shared
                // commnunicator property set.
                //
                Ice.Communicator communicator;
                if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
                {
                    Debug.Assert(_sharedCommunicator != null);
                    communicator = _sharedCommunicator;
                }
                else
                {
                    //
                    // Create the service properties. We use the communicator properties as the default
                    // properties if IceBox.InheritProperties is set.
                    //
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties(service);
                    if(info.args.Length > 0)
                    {
                        //
                        // Create the service properties with the given service arguments. This should
                        // read the service config file if it's specified with --Ice.Config.
                        //
                        initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                        //
                        // Next, parse the service "<service>.*" command line options (the Ice command
                        // line options were parsed by the createProperties above)
                        //
                        info.args = initData.properties.parseCommandLineOptions(service, info.args);
                    }

                    //
                    // Clone the logger to assign a new prefix.
                    //
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));

                    //
                    // Remaining command line options are passed to the communicator. This is
                    // necessary for Ice plug-in properties (e.g.: IceSSL).
                    //
                    info.communicator = Ice.Util.initialize(ref info.args, initData);
                    communicator = info.communicator;
                }

                try
                {
                    info.service.start(service, communicator, info.args);
                    info.status = ServiceStatus.Started;
                }
                catch(System.Exception)
                {
                    if(info.communicator != null)
                    {
                        try
                        {
                            info.communicator.shutdown();
                            info.communicator.waitForShutdown();
                        }
                        catch(Ice.CommunicatorDestroyedException)
                        {
                            //
                            // Ignore, the service might have already destroyed
                            // the communicator for its own reasons.
                            //
                        }
                        catch(System.Exception e)
                        {
                            _logger.warning("ServiceManager: exception while shutting down communicator for service "
                                            + service + "\n" + e.ToString());
                        }

                        try
                        {
                            info.communicator.destroy();
                        }
                        catch(System.Exception e)
                        {
                            _logger.warning("ServiceManager: exception while destroying communicator for service "
                                            + service + "\n" + e.ToString());
                        }
                    }
                    throw;
                }

                _services.Add(info);
            }
            catch(FailureException)
            {
                throw;
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = "ServiceManager: exception while starting service " + service;
                throw e;
            }
            }
            finally
            {
            _m.Unlock();
            }
        }
Example #22
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                string           @ref         = "communicator:" + helper.getTestEndpoint(0);

                Test.RemoteCommunicatorPrx com = Test.RemoteCommunicatorPrxHelper.uncheckedCast(communicator.stringToProxy(@ref));

                var rand   = new Random(unchecked ((int)DateTime.Now.Ticks));
                var output = helper.getWriter();

                output.Write("testing binding with single endpoint... ");
                output.Flush();
                {
                    Test.RemoteObjectAdapterPrx adapter = com.createObjectAdapter("Adapter", "default");

                    var test1 = adapter.getTestIntf();
                    var test2 = adapter.getTestIntf();
                    test(test1.ice_getConnection() == test2.ice_getConnection());

                    test1.ice_ping();
                    test2.ice_ping();

                    com.deactivateObjectAdapter(adapter);

                    var test3 = Test.TestIntfPrxHelper.uncheckedCast(test1);
                    test(test3.ice_getConnection() == test1.ice_getConnection());
                    test(test3.ice_getConnection() == test2.ice_getConnection());

                    try
                    {
                        test3.ice_ping();
                        test(false);
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                    }
                }
                output.WriteLine("ok");

                output.Write("testing binding with multiple endpoints... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter11", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter12", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter13", "default"));

                    //
                    // Ensure that when a connection is opened it's reused for new
                    // proxies and that all endpoints are eventually tried.
                    //
                    List <string> names = new List <string>();
                    names.Add("Adapter11");
                    names.Add("Adapter12");
                    names.Add("Adapter13");
                    while (names.Count > 0)
                    {
                        var adpts = new List <Test.RemoteObjectAdapterPrx>(adapters);

                        var test1 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test2 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test3 = createTestIntfPrx(adpts);
                        test1.ice_ping();
                        test(test1.ice_getConnection() == test2.ice_getConnection());
                        test(test2.ice_getConnection() == test3.ice_getConnection());

                        names.Remove(test1.getAdapterName());
                        test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    //
                    // Ensure that the proxy correctly caches the connection(we
                    // always send the request over the same connection.)
                    //
                    {
                        foreach (var adpt in adapters)
                        {
                            adpt.getTestIntf().ice_ping();
                        }

                        var    t      = createTestIntfPrx(adapters);
                        string name   = t.getAdapterName();
                        int    nRetry = 10;
                        int    i;
                        for (i = 0; i < nRetry && t.getAdapterName().Equals(name); i++)
                        {
                            ;
                        }
                        test(i == nRetry);

                        foreach (var adpt in adapters)
                        {
                            adpt.getTestIntf().ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                        }
                    }

                    //
                    // Deactivate an adapter and ensure that we can still
                    // establish the connection to the remaining adapters.
                    //
                    com.deactivateObjectAdapter((Test.RemoteObjectAdapterPrx)adapters[0]);
                    names.Add("Adapter12");
                    names.Add("Adapter13");
                    while (names.Count > 0)
                    {
                        var adpts = new List <Test.RemoteObjectAdapterPrx>(adapters);

                        var test1 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test2 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test3 = createTestIntfPrx(adpts);

                        test(test1.ice_getConnection() == test2.ice_getConnection());
                        test(test2.ice_getConnection() == test3.ice_getConnection());

                        names.Remove(test1.getAdapterName());
                        test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    //
                    // Deactivate an adapter and ensure that we can still
                    // establish the connection to the remaining adapter.
                    //
                    com.deactivateObjectAdapter((Test.RemoteObjectAdapterPrx)adapters[2]);
                    var obj = createTestIntfPrx(adapters);
                    test(obj.getAdapterName().Equals("Adapter12"));

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing binding with multiple random endpoints... ");
                output.Flush();
                {
                    var adapters = new Test.RemoteObjectAdapterPrx[5];
                    adapters[0] = com.createObjectAdapter("AdapterRandom11", "default");
                    adapters[1] = com.createObjectAdapter("AdapterRandom12", "default");
                    adapters[2] = com.createObjectAdapter("AdapterRandom13", "default");
                    adapters[3] = com.createObjectAdapter("AdapterRandom14", "default");
                    adapters[4] = com.createObjectAdapter("AdapterRandom15", "default");

                    int count        = 20;
                    int adapterCount = adapters.Length;
                    while (--count > 0)
                    {
                        Test.TestIntfPrx[] proxies;
                        if (count == 1)
                        {
                            com.deactivateObjectAdapter(adapters[4]);
                            --adapterCount;
                        }
                        proxies = new Test.TestIntfPrx[10];

                        int i;
                        for (i = 0; i < proxies.Length; ++i)
                        {
                            var adpts = new Test.RemoteObjectAdapterPrx[rand.Next(adapters.Length)];
                            if (adpts.Length == 0)
                            {
                                adpts = new Test.RemoteObjectAdapterPrx[1];
                            }
                            for (int j = 0; j < adpts.Length; ++j)
                            {
                                adpts[j] = adapters[rand.Next(adapters.Length)];
                            }
                            proxies[i] = createTestIntfPrx(new List <Test.RemoteObjectAdapterPrx>(adpts));
                        }

                        for (i = 0; i < proxies.Length; i++)
                        {
                            proxies[i].begin_getAdapterName();
                        }
                        for (i = 0; i < proxies.Length; i++)
                        {
                            try
                            {
                                proxies[i].ice_ping();
                            }
                            catch (Ice.LocalException)
                            {
                            }
                        }

                        List <Ice.Connection> connections = new List <Ice.Connection>();
                        for (i = 0; i < proxies.Length; i++)
                        {
                            if (proxies[i].ice_getCachedConnection() != null)
                            {
                                if (!connections.Contains(proxies[i].ice_getCachedConnection()))
                                {
                                    connections.Add(proxies[i].ice_getCachedConnection());
                                }
                            }
                        }
                        test(connections.Count <= adapterCount);

                        foreach (var a in adapters)
                        {
                            try
                            {
                                a.getTestIntf().ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                            }
                            catch (Ice.LocalException)
                            {
                                // Expected if adapter is down.
                            }
                        }
                    }
                }
                output.WriteLine("ok");

                output.Write("testing binding with multiple endpoints and AMI... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("AdapterAMI11", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI12", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI13", "default"));

                    //
                    // Ensure that when a connection is opened it's reused for new
                    // proxies and that all endpoints are eventually tried.
                    //
                    List <string> names = new List <string>();
                    names.Add("AdapterAMI11");
                    names.Add("AdapterAMI12");
                    names.Add("AdapterAMI13");
                    while (names.Count > 0)
                    {
                        var adpts = new List <Test.RemoteObjectAdapterPrx>(adapters);

                        var test1 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test2 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test3 = createTestIntfPrx(adpts);
                        test1.ice_ping();
                        test(test1.ice_getConnection() == test2.ice_getConnection());
                        test(test2.ice_getConnection() == test3.ice_getConnection());

                        names.Remove(getAdapterNameWithAMI(test1));
                        test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    //
                    // Ensure that the proxy correctly caches the connection(we
                    // always send the request over the same connection.)
                    //
                    {
                        foreach (var adpt in adapters)
                        {
                            adpt.getTestIntf().ice_ping();
                        }

                        var    t      = createTestIntfPrx(adapters);
                        string name   = getAdapterNameWithAMI(t);
                        int    nRetry = 10;
                        int    i;
                        for (i = 0; i < nRetry && getAdapterNameWithAMI(t).Equals(name); i++)
                        {
                            ;
                        }
                        test(i == nRetry);

                        foreach (var adpt in adapters)
                        {
                            adpt.getTestIntf().ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                        }
                    }

                    //
                    // Deactivate an adapter and ensure that we can still
                    // establish the connection to the remaining adapters.
                    //
                    com.deactivateObjectAdapter(adapters[0]);
                    names.Add("AdapterAMI12");
                    names.Add("AdapterAMI13");
                    while (names.Count > 0)
                    {
                        var adpts = new List <Test.RemoteObjectAdapterPrx>(adapters);

                        var test1 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test2 = createTestIntfPrx(adpts);
                        shuffle(ref adpts);
                        var test3 = createTestIntfPrx(adpts);

                        test(test1.ice_getConnection() == test2.ice_getConnection());
                        test(test2.ice_getConnection() == test3.ice_getConnection());

                        names.Remove(getAdapterNameWithAMI(test1));
                        test1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    //
                    // Deactivate an adapter and ensure that we can still
                    // establish the connection to the remaining adapter.
                    //
                    com.deactivateObjectAdapter(adapters[2]);
                    var obj = createTestIntfPrx(adapters);
                    test(getAdapterNameWithAMI(obj).Equals("AdapterAMI12"));

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing random endpoint selection... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter21", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter22", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter23", "default"));

                    var obj = createTestIntfPrx(adapters);
                    test(obj.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random);

                    var names = new List <string>();
                    names.Add("Adapter21");
                    names.Add("Adapter22");
                    names.Add("Adapter23");
                    while (names.Count > 0)
                    {
                        names.Remove(obj.getAdapterName());
                        obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_endpointSelection(Ice.EndpointSelectionType.Random));
                    test(obj.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random);

                    names.Add("Adapter21");
                    names.Add("Adapter22");
                    names.Add("Adapter23");
                    while (names.Count > 0)
                    {
                        names.Remove(obj.getAdapterName());
                        obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    }

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing ordered endpoint selection... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter31", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter32", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter33", "default"));

                    var obj = createTestIntfPrx(adapters);
                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_endpointSelection(Ice.EndpointSelectionType.Ordered));
                    test(obj.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered);
                    int nRetry = 3;
                    int i;

                    //
                    // Ensure that endpoints are tried in order by deactiving the adapters
                    // one after the other.
                    //
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter31"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[0]);
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter32"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[1]);
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter33"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[2]);

                    try
                    {
                        obj.getAdapterName();
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                    }

                    Ice.Endpoint[] endpoints = obj.ice_getEndpoints();

                    adapters.Clear();

                    //
                    // Now, re-activate the adapters with the same endpoints in the opposite
                    // order.
                    //
                    adapters.Add(com.createObjectAdapter("Adapter36", endpoints[2].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter36"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    adapters.Add(com.createObjectAdapter("Adapter35", endpoints[1].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter35"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    adapters.Add(com.createObjectAdapter("Adapter34", endpoints[0].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter34"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing per request binding with single endpoint... ");
                output.Flush();
                {
                    var adapter = com.createObjectAdapter("Adapter41", "default");

                    var test1 = Test.TestIntfPrxHelper.uncheckedCast(adapter.getTestIntf().ice_connectionCached(false));
                    var test2 = Test.TestIntfPrxHelper.uncheckedCast(adapter.getTestIntf().ice_connectionCached(false));
                    test(!test1.ice_isConnectionCached());
                    test(!test2.ice_isConnectionCached());
                    test(test1.ice_getConnection() != null && test2.ice_getConnection() != null);
                    test(test1.ice_getConnection() == test2.ice_getConnection());

                    test1.ice_ping();

                    com.deactivateObjectAdapter(adapter);

                    var test3 = Test.TestIntfPrxHelper.uncheckedCast(test1);
                    try
                    {
                        test(test3.ice_getConnection() == test1.ice_getConnection());
                        test(false);
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                    }
                }
                output.WriteLine("ok");

                output.Write("testing per request binding with multiple endpoints... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter51", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter52", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter53", "default"));

                    var obj = Test.TestIntfPrxHelper.uncheckedCast(createTestIntfPrx(adapters).ice_connectionCached(false));
                    test(!obj.ice_isConnectionCached());

                    List <string> names = new List <string>();
                    names.Add("Adapter51");
                    names.Add("Adapter52");
                    names.Add("Adapter53");
                    while (names.Count > 0)
                    {
                        names.Remove(obj.getAdapterName());
                    }

                    com.deactivateObjectAdapter(adapters[0]);

                    names.Add("Adapter52");
                    names.Add("Adapter53");
                    while (names.Count > 0)
                    {
                        names.Remove(obj.getAdapterName());
                    }

                    com.deactivateObjectAdapter(adapters[2]);

                    test(obj.getAdapterName().Equals("Adapter52"));

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing per request binding with multiple endpoints and AMI... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("AdapterAMI51", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI52", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI53", "default"));

                    var obj = Test.TestIntfPrxHelper.uncheckedCast(createTestIntfPrx(adapters).ice_connectionCached(false));
                    test(!obj.ice_isConnectionCached());

                    var names = new List <string>();
                    names.Add("AdapterAMI51");
                    names.Add("AdapterAMI52");
                    names.Add("AdapterAMI53");
                    while (names.Count > 0)
                    {
                        names.Remove(getAdapterNameWithAMI(obj));
                    }

                    com.deactivateObjectAdapter(adapters[0]);

                    names.Add("AdapterAMI52");
                    names.Add("AdapterAMI53");
                    while (names.Count > 0)
                    {
                        names.Remove(getAdapterNameWithAMI(obj));
                    }

                    com.deactivateObjectAdapter(adapters[2]);

                    test(getAdapterNameWithAMI(obj).Equals("AdapterAMI52"));

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing per request binding and ordered endpoint selection... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter61", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter62", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter63", "default"));

                    var obj = createTestIntfPrx(adapters);
                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_endpointSelection(Ice.EndpointSelectionType.Ordered));
                    test(obj.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered);
                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_connectionCached(false));
                    test(!obj.ice_isConnectionCached());
                    int nRetry = 3;
                    int i;

                    //
                    // Ensure that endpoints are tried in order by deactiving the adapters
                    // one after the other.
                    //
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter61"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[0]);
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter62"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[1]);
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter63"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[2]);

                    try
                    {
                        obj.getAdapterName();
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                    }

                    Ice.Endpoint[] endpoints = obj.ice_getEndpoints();

                    adapters.Clear();

                    //
                    // Now, re-activate the adapters with the same endpoints in the opposite
                    // order.
                    //
                    adapters.Add(com.createObjectAdapter("Adapter66", endpoints[2].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter66"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    adapters.Add(com.createObjectAdapter("Adapter65", endpoints[1].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter65"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    adapters.Add(com.createObjectAdapter("Adapter64", endpoints[0].ToString()));
                    for (i = 0; i < nRetry && obj.getAdapterName().Equals("Adapter64"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing per request binding and ordered endpoint selection and AMI... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("AdapterAMI61", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI62", "default"));
                    adapters.Add(com.createObjectAdapter("AdapterAMI63", "default"));

                    var obj = createTestIntfPrx(adapters);
                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_endpointSelection(Ice.EndpointSelectionType.Ordered));
                    test(obj.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered);
                    obj = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_connectionCached(false));
                    test(!obj.ice_isConnectionCached());
                    int nRetry = 3;
                    int i;

                    //
                    // Ensure that endpoints are tried in order by deactiving the adapters
                    // one after the other.
                    //
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI61"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[0]);
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI62"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[1]);
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI63"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    com.deactivateObjectAdapter(adapters[2]);

                    try
                    {
                        obj.getAdapterName();
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                    }

                    Ice.Endpoint[] endpoints = obj.ice_getEndpoints();

                    adapters.Clear();

                    //
                    // Now, re-activate the adapters with the same endpoints in the opposite
                    // order.
                    //
                    adapters.Add(com.createObjectAdapter("AdapterAMI66", endpoints[2].ToString()));
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI66"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    adapters.Add(com.createObjectAdapter("AdapterAMI65", endpoints[1].ToString()));
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI65"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);
                    adapters.Add(com.createObjectAdapter("AdapterAMI64", endpoints[0].ToString()));
                    for (i = 0; i < nRetry && getAdapterNameWithAMI(obj).Equals("AdapterAMI64"); i++)
                    {
                        ;
                    }
                    test(i == nRetry);

                    deactivate(com, adapters);
                }
                output.WriteLine("ok");

                output.Write("testing endpoint mode filtering... ");
                output.Flush();
                {
                    var adapters = new List <Test.RemoteObjectAdapterPrx>();
                    adapters.Add(com.createObjectAdapter("Adapter71", "default"));
                    adapters.Add(com.createObjectAdapter("Adapter72", "udp"));

                    var obj = createTestIntfPrx(adapters);
                    test(obj.getAdapterName().Equals("Adapter71"));

                    var testUDP = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_datagram());
                    test(obj.ice_getConnection() != testUDP.ice_getConnection());
                    try
                    {
                        testUDP.getAdapterName();
                    }
                    catch (Ice.TwowayOnlyException)
                    {
                    }
                }
                output.WriteLine("ok");
                if (communicator.getProperties().getProperty("Ice.Plugin.IceSSL").Length > 0)
                {
                    output.Write("testing unsecure vs. secure endpoints... ");
                    output.Flush();
                    {
                        var adapters = new List <Test.RemoteObjectAdapterPrx>();
                        adapters.Add(com.createObjectAdapter("Adapter81", "ssl"));
                        adapters.Add(com.createObjectAdapter("Adapter82", "tcp"));

                        var obj = createTestIntfPrx(adapters);
                        int i;
                        for (i = 0; i < 5; i++)
                        {
                            test(obj.getAdapterName().Equals("Adapter82"));
                            obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                        }

                        var testSecure = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_secure(true));
                        test(testSecure.ice_isSecure());
                        testSecure = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_secure(false));
                        test(!testSecure.ice_isSecure());
                        testSecure = Test.TestIntfPrxHelper.uncheckedCast(obj.ice_secure(true));
                        test(testSecure.ice_isSecure());
                        test(obj.ice_getConnection() != testSecure.ice_getConnection());

                        com.deactivateObjectAdapter(adapters[1]);

                        for (i = 0; i < 5; i++)
                        {
                            test(obj.getAdapterName().Equals("Adapter81"));
                            obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                        }

                        com.createObjectAdapter("Adapter83", (obj.ice_getEndpoints()[1]).ToString()); // Reactive tcp OA.

                        for (i = 0; i < 5; i++)
                        {
                            test(obj.getAdapterName().Equals("Adapter83"));
                            obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                        }

                        com.deactivateObjectAdapter(adapters[0]);
                        try
                        {
                            testSecure.ice_ping();
                            test(false);
                        }
                        catch (Ice.ConnectFailedException)
                        {
                        }
                        catch (Ice.ConnectTimeoutException)
                        {
                        }

                        deactivate(com, adapters);
                    }
                    output.WriteLine("ok");
                }

                {
                    output.Write("testing ipv4 & ipv6 connections... ");
                    output.Flush();

                    Ice.Properties ipv4 = Ice.Util.createProperties();
                    ipv4.setProperty("Ice.IPv4", "1");
                    ipv4.setProperty("Ice.IPv6", "0");
                    ipv4.setProperty("Adapter.Endpoints", "tcp -h localhost");

                    Ice.Properties ipv6 = Ice.Util.createProperties();
                    ipv6.setProperty("Ice.IPv4", "0");
                    ipv6.setProperty("Ice.IPv6", "1");
                    ipv6.setProperty("Adapter.Endpoints", "tcp -h localhost");

                    Ice.Properties bothPreferIPv4 = Ice.Util.createProperties();
                    bothPreferIPv4.setProperty("Ice.IPv4", "1");
                    bothPreferIPv4.setProperty("Ice.IPv6", "1");
                    bothPreferIPv4.setProperty("Ice.PreferIPv6Address", "0");
                    bothPreferIPv4.setProperty("Adapter.Endpoints", "tcp -h localhost");

                    Ice.Properties bothPreferIPv6 = Ice.Util.createProperties();
                    bothPreferIPv6.setProperty("Ice.IPv4", "1");
                    bothPreferIPv6.setProperty("Ice.IPv6", "1");
                    bothPreferIPv6.setProperty("Ice.PreferIPv6Address", "1");
                    bothPreferIPv6.setProperty("Adapter.Endpoints", "tcp -h localhost");

                    List <Ice.Properties> clientProps = new List <Ice.Properties>();
                    clientProps.Add(ipv4);
                    clientProps.Add(ipv6);
                    clientProps.Add(bothPreferIPv4);
                    clientProps.Add(bothPreferIPv6);

                    string endpoint = "tcp -p " + helper.getTestPort(2).ToString();

                    Ice.Properties anyipv4 = ipv4.ice_clone_();
                    anyipv4.setProperty("Adapter.Endpoints", endpoint);
                    anyipv4.setProperty("Adapter.PublishedEndpoints", endpoint + " -h 127.0.0.1");

                    Ice.Properties anyipv6 = ipv6.ice_clone_();
                    anyipv6.setProperty("Adapter.Endpoints", endpoint);
                    anyipv6.setProperty("Adapter.PublishedEndpoints", endpoint + " -h \".1\"");

                    Ice.Properties anyboth = Ice.Util.createProperties();
                    anyboth.setProperty("Ice.IPv4", "1");
                    anyboth.setProperty("Ice.IPv6", "1");
                    anyboth.setProperty("Adapter.Endpoints", endpoint);
                    anyboth.setProperty("Adapter.PublishedEndpoints", endpoint + " -h \"::1\":" + endpoint + " -h 127.0.0.1");

                    Ice.Properties localipv4 = ipv4.ice_clone_();
                    localipv4.setProperty("Adapter.Endpoints", "tcp -h 127.0.0.1");

                    Ice.Properties localipv6 = ipv6.ice_clone_();
                    localipv6.setProperty("Adapter.Endpoints", "tcp -h \"::1\"");

                    List <Ice.Properties> serverProps = new List <Ice.Properties>(clientProps);
                    serverProps.Add(anyipv4);
                    serverProps.Add(anyipv6);
                    serverProps.Add(anyboth);
                    serverProps.Add(localipv4);
                    serverProps.Add(localipv6);

                    bool ipv6NotSupported = false;
                    foreach (Ice.Properties p in serverProps)
                    {
                        Ice.InitializationData serverInitData = new Ice.InitializationData();
                        serverInitData.properties = p;
                        Ice.Communicator  serverCommunicator = Ice.Util.initialize(serverInitData);
                        Ice.ObjectAdapter oa;
                        try
                        {
                            oa = serverCommunicator.createObjectAdapter("Adapter");
                            oa.activate();
                        }
                        catch (Ice.DNSException)
                        {
                            serverCommunicator.destroy();
                            continue; // IP version not supported.
                        }
                        catch (Ice.SocketException)
                        {
                            if (p == ipv6)
                            {
                                ipv6NotSupported = true;
                            }
                            serverCommunicator.destroy();
                            continue; // IP version not supported.
                        }

                        Ice.ObjectPrx prx = oa.createProxy(Ice.Util.stringToIdentity("dummy"));
                        try
                        {
                            prx.ice_collocationOptimized(false).ice_ping();
                        }
                        catch (Ice.LocalException)
                        {
                            serverCommunicator.destroy();
                            continue; // IP version not supported.
                        }

                        string strPrx = prx.ToString();
                        foreach (Ice.Properties q in clientProps)
                        {
                            Ice.InitializationData clientInitData = new Ice.InitializationData();
                            clientInitData.properties = q;
                            Ice.Communicator clientCommunicator = Ice.Util.initialize(clientInitData);
                            prx = clientCommunicator.stringToProxy(strPrx);
                            try
                            {
                                prx.ice_ping();
                                test(false);
                            }
                            catch (Ice.ObjectNotExistException)
                            {
                                // Expected, no object registered.
                            }
                            catch (Ice.DNSException)
                            {
                                // Expected if no IPv4 or IPv6 address is
                                // associated to localhost or if trying to connect
                                // to an any endpoint with the wrong IP version,
                                // e.g.: resolving an IPv4 address when only IPv6
                                // is enabled fails with a DNS exception.
                            }
                            catch (Ice.SocketException)
                            {
                                test((p == ipv4 && q == ipv6) || (p == ipv6 && q == ipv4) ||
                                     (p == bothPreferIPv4 && q == ipv6) || (p == bothPreferIPv6 && q == ipv4) ||
                                     (p == bothPreferIPv6 && q == ipv6 && ipv6NotSupported) ||
                                     (p == anyipv4 && q == ipv6) || (p == anyipv6 && q == ipv4) ||
                                     (p == localipv4 && q == ipv6) || (p == localipv6 && q == ipv4) ||
                                     (p == ipv6 && q == bothPreferIPv4) || (p == ipv6 && q == bothPreferIPv6) ||
                                     (p == bothPreferIPv6 && q == ipv6));
                            }
                            clientCommunicator.destroy();
                        }
                        serverCommunicator.destroy();
                    }

                    output.WriteLine("ok");
                }
                com.shutdown();
            }
Example #23
0
 /// <summary>
 /// Creates a SessionFactory object.
 /// </summary>
 /// <param name="initData">The initialization data to use when creating the communicator.</param>
 /// <param name="callback">The callback object for notifications.</param>
 public SessionFactoryHelper(Ice.InitializationData initData, SessionCallback callback)
 {
     _callback = callback;
     _initData = initData;
     setDefaultProperties();
 }
Example #24
0
            public override void startServer(Ice.Current current)
            {
                foreach (Ice.Communicator c in _communicators)
                {
                    c.waitForShutdown();
                    c.destroy();
                }
                _communicators.Clear();

                //
                // Simulate a server: create a new communicator and object
                // adapter. The object adapter is started on a system allocated
                // port. The configuration used here contains the Ice.Locator
                // configuration variable. The new object adapter will register
                // its endpoints with the locator and create references containing
                // the adapter id instead of the endpoints.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = _helper.communicator().getProperties().ice_clone_();
                initData.properties.setProperty("TestAdapter.AdapterId", "TestAdapter");
                initData.properties.setProperty("TestAdapter.ReplicaGroupId", "ReplicatedAdapter");
                initData.properties.setProperty("TestAdapter2.AdapterId", "TestAdapter2");

                Ice.Communicator serverCommunicator = _helper.initialize(initData);
                _communicators.Add(serverCommunicator);

                //
                // Use fixed port to ensure that OA re-activation doesn't re-use previous port from
                // another OA(e.g.: TestAdapter2 is re-activated using port of TestAdapter).
                //
                int nRetry = 10;

                while (--nRetry > 0)
                {
                    Ice.ObjectAdapter adapter  = null;
                    Ice.ObjectAdapter adapter2 = null;
                    try
                    {
                        serverCommunicator.getProperties().setProperty("TestAdapter.Endpoints",
                                                                       _helper.getTestEndpoint(_nextPort++));
                        serverCommunicator.getProperties().setProperty("TestAdapter2.Endpoints",
                                                                       _helper.getTestEndpoint(_nextPort++));

                        adapter  = serverCommunicator.createObjectAdapter("TestAdapter");
                        adapter2 = serverCommunicator.createObjectAdapter("TestAdapter2");

                        Ice.ObjectPrx locator = serverCommunicator.stringToProxy("locator:" + _helper.getTestEndpoint(0));
                        adapter.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator));
                        adapter2.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator));

                        Ice.Object @object = new TestI(adapter, adapter2, _registry);
                        _registry.addObject(adapter.add(@object, Ice.Util.stringToIdentity("test")));
                        _registry.addObject(adapter.add(@object, Ice.Util.stringToIdentity("test2")));
                        adapter.add(@object, Ice.Util.stringToIdentity("test3"));

                        adapter.activate();
                        adapter2.activate();
                        break;
                    }
                    catch (Ice.SocketException ex)
                    {
                        if (nRetry == 0)
                        {
                            throw ex;
                        }

                        // Retry, if OA creation fails with EADDRINUSE(this can occur when running with JS web
                        // browser clients if the driver uses ports in the same range as this test, ICE-8148)
                        if (adapter != null)
                        {
                            adapter.destroy();
                        }
                        if (adapter2 != null)
                        {
                            adapter2.destroy();
                        }
                    }
                }
            }
Example #25
0
        public int runmain(string[] args, Ice.InitializationData initializationData)
        {
            _testName = AppDomain.CurrentDomain.FriendlyName;

            if (_communicator != null)
            {
                Console.Out.WriteLine(_testName + ": only one instance of the Application class can be used");
                return(1);
            }

            //
            // We parse the properties here to extract Ice.ProgramName.
            //
            if (initializationData == null)
            {
                initializationData = getInitData(ref args);
            }

            Ice.InitializationData initData;
            if (initializationData != null)
            {
                initData = (Ice.InitializationData)initializationData.Clone();
            }
            else
            {
                initData = new Ice.InitializationData();
            }
            initData.properties = Ice.Util.createProperties(ref args, initData.properties);

            //
            // If the process logger is the default logger, we replace it with a
            // a logger that uses the program name as the prefix.
            //
            if (Ice.Util.getProcessLogger() is Ice.LoggerI)
            {
                Ice.Util.setProcessLogger(new Ice.ConsoleLoggerI(initData.properties.getProperty("Ice.ProgramName")));
            }

            int status = 0;

            try
            {
                _communicator = Ice.Util.initialize(ref args, initData);
                status        = run(args);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(_testName + ": " + ex);
                status = 1;
            }

            if (_communicator != null)
            {
                try
                {
                    _communicator.destroy();
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(_testName + ": " + ex);
                    status = 1;
                }
                _communicator = null;
            }
            return(status);
        }
Example #26
0
        public static int Main(string[] args)
        {
            int           status = 0;
            List <string> argSeq = new List <string>();
            const string  prefix = "IceBox.Service.";

            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = Ice.Util.createProperties();
            initData.properties.setProperty("Ice.Admin.DelayCreation", "1");

            try
            {
                using (var communicator = Ice.Util.initialize(ref args, initData))
                {
                    Console.CancelKeyPress += (sender, eventArgs) =>
                    {
                        eventArgs.Cancel = true;
                        communicator.shutdown();
                    };

                    Ice.Properties properties            = communicator.getProperties();
                    Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);

                    foreach (string arg in argSeq)
                    {
                        bool valid = false;
                        foreach (KeyValuePair <string, string> pair in services)
                        {
                            string name = pair.Key.Substring(prefix.Length);
                            if (arg.StartsWith("--" + name, StringComparison.CurrentCulture))
                            {
                                valid = true;
                                break;
                            }
                        }
                        if (!valid)
                        {
                            if (arg.Equals("-h") || arg.Equals("--help"))
                            {
                                usage();
                                status = 1;
                                break;
                            }
                            else if (arg.Equals("-v") || arg.Equals("--version"))
                            {
                                Console.Out.WriteLine(Ice.Util.stringVersion());
                                status = 1;
                                break;
                            }
                            else
                            {
                                Console.Error.WriteLine("IceBox.Server: unknown option `" + arg + "'");
                                usage();
                                status = 1;
                                break;
                            }
                        }
                    }

                    ServiceManagerI serviceManagerImpl = new ServiceManagerI(communicator, argSeq.ToArray());
                    status = serviceManagerImpl.run();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                status = 1;
            }

            return(status);
        }
Example #27
0
        private void startService(string service, string entryPoint, string[] args)
        {
            _m.Lock();
            try
            {
                //
                // Extract the assembly name and the class name.
                //
                string err    = "ServiceManager: unable to load service '" + entryPoint + "': ";
                int    sepPos = entryPoint.IndexOf(':');
                if (sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)
                {
                    const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    if (entryPoint.Length > 3 &&
                        sepPos == 1 &&
                        driveLetters.IndexOf(entryPoint[0]) != -1 &&
                        (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                    {
                        sepPos = entryPoint.IndexOf(':', 3);
                    }
                }
                if (sepPos == -1)
                {
                    FailureException e = new FailureException();
                    e.reason = err + "invalid entry point format";
                    throw e;
                }

                System.Reflection.Assembly serviceAssembly = null;
                string assemblyName = entryPoint.Substring(0, sepPos);
                string className    = entryPoint.Substring(sepPos + 1);

                try
                {
                    //
                    // First try to load the assembly using Assembly.Load, which will succeed
                    // if a fully-qualified name is provided or if a partial name has been qualified
                    // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                    // if a file name is configured or a partial name is configured and DEVPATH is used.
                    //
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                    }
                    catch (System.IO.IOException ex)
                    {
                        try
                        {
                            serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                        }
                        catch (System.IO.IOException)
                        {
                            throw ex;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "unable to load assembly: " + assemblyName;
                    throw e;
                }

                //
                // Instantiate the class.
                //
                System.Type c = null;
                try
                {
                    c = serviceAssembly.GetType(className, true);
                }
                catch (System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "GetType failed for '" + className + "'";
                    throw e;
                }

                ServiceInfo info = new ServiceInfo();
                info.name   = service;
                info.status = ServiceStatus.Stopped;
                info.args   = args;

                //
                // If IceBox.UseSharedCommunicator.<name> is defined, create a
                // communicator for the service. The communicator inherits
                // from the shared communicator properties. If it's not
                // defined, add the service properties to the shared
                // commnunicator property set.
                //
                Ice.Communicator          communicator;
                IceInternal.MetricsAdminI metricsAdmin = null;
                if (_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
                {
                    Debug.Assert(_sharedCommunicator != null);
                    communicator = _sharedCommunicator;
                    if (communicator.getObserver() is IceInternal.CommunicatorObserverI)
                    {
                        IceInternal.CommunicatorObserverI o = (IceInternal.CommunicatorObserverI)communicator.getObserver();
                        metricsAdmin = o.getMetricsAdmin();
                    }
                }
                else
                {
                    //
                    // Create the service properties. We use the communicator properties as the default
                    // properties if IceBox.InheritProperties is set.
                    //
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties(service);
                    if (info.args.Length > 0)
                    {
                        //
                        // Create the service properties with the given service arguments. This should
                        // read the service config file if it's specified with --Ice.Config.
                        //
                        initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                        //
                        // Next, parse the service "<service>.*" command line options (the Ice command
                        // line options were parsed by the createProperties above)
                        //
                        info.args = initData.properties.parseCommandLineOptions(service, info.args);
                    }

                    //
                    // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                    // don't set any logger.
                    //
                    if (initData.properties.getProperty("Ice.LogFile").Length == 0 &&
                        (initData.properties.getPropertyAsInt("Ice.UseSyslog") == 0 ||
                         IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows))
                    {
                        initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                    }

                    //
                    // If Ice metrics are enabled on the IceBox communicator, we also enable them on
                    // the service communicator.
                    //
                    if (_communicator.getObserver() is IceInternal.CommunicatorObserverI)
                    {
                        metricsAdmin      = new IceInternal.MetricsAdminI(initData.properties, initData.logger);
                        initData.observer = new IceInternal.CommunicatorObserverI(metricsAdmin);
                    }

                    //
                    // Remaining command line options are passed to the communicator. This is
                    // necessary for Ice plug-in properties (e.g.: IceSSL).
                    //
                    info.communicator = Ice.Util.initialize(ref info.args, initData);
                    communicator      = info.communicator;

                    //
                    // Ensure the metrics admin plugin uses the same property set as the
                    // communicator. This is necessary to correctly deal with runtime
                    // property updates.
                    //
                    if (metricsAdmin != null)
                    {
                        metricsAdmin.setProperties(communicator.getProperties());
                    }
                }

                try
                {
                    //
                    // Add a PropertiesAdmin facet to the service manager's communicator that provides
                    // access to this service's property set. We do this prior to instantiating the
                    // service so that the service's constructor is able to access the facet (e.g.,
                    // in case it wants to set a callback).
                    //
                    string facetName = "IceBox.Service." + info.name + ".Properties";
                    IceInternal.PropertiesAdminI propAdmin = new IceInternal.PropertiesAdminI(facetName,
                                                                                              communicator.getProperties(),
                                                                                              communicator.getLogger());
                    _communicator.addAdminFacet(propAdmin, facetName);

                    //
                    // If a metrics admin facet is setup for the service, register
                    // it with the IceBox communicator.
                    //
                    if (metricsAdmin != null)
                    {
                        _communicator.addAdminFacet(metricsAdmin, "IceBox.Service." + info.name + ".Metrics");

                        // Ensure the metrics admin facet is notified of property updates.
                        propAdmin.addUpdateCallback(metricsAdmin);
                    }

                    //
                    // Instantiate the service.
                    //
                    try
                    {
                        //
                        // If the service class provides a constructor that accepts an Ice.Communicator argument,
                        // use that in preference to the default constructor.
                        //
                        Type[] parameterTypes = new Type[1];
                        parameterTypes[0] = typeof(Ice.Communicator);
                        System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                        if (ci != null)
                        {
                            try
                            {
                                Object[] parameters = new Object[1];
                                parameters[0] = _communicator;
                                info.service  = (Service)ci.Invoke(parameters);
                            }
                            catch (System.MethodAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                                throw e;
                            }
                        }
                        else
                        {
                            //
                            // Fall back to the default constructor.
                            //
                            try
                            {
                                info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                                if (info.service == null)
                                {
                                    FailureException e = new FailureException();
                                    e.reason = err + "no default constructor for '" + className + "'";
                                    throw e;
                                }
                            }
                            catch (System.UnauthorizedAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unauthorized access to default service constructor for " + className;
                                throw e;
                            }
                        }
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (System.InvalidCastException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "service does not implement IceBox.Service";
                        throw e;
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        if (ex.InnerException is IceBox.FailureException)
                        {
                            throw ex.InnerException;
                        }
                        else
                        {
                            FailureException e = new FailureException(ex.InnerException);
                            e.reason = err + "exception in service constructor for " + className;
                            throw e;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "exception in service constructor " + className;
                        throw e;
                    }


                    try
                    {
                        info.service.start(service, communicator, info.args);
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (System.Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = "exception while starting service " + service;
                        throw e;
                    }

                    info.status = ServiceStatus.Started;
                    _services.Add(info);
                }
                catch (Ice.ObjectAdapterDeactivatedException)
                {
                    //
                    // Can be raised by addAdminFacet if the service manager communicator has been shut down.
                    //
                    if (info.communicator != null)
                    {
                        destroyServiceCommunicator(service, info.communicator);
                    }
                }
                catch (System.Exception ex)
                {
                    try
                    {
                        _communicator.removeAdminFacet("IceBox.Service." + service + ".Properties");
                    }
                    catch (Ice.LocalException)
                    {
                        // Ignored
                    }

                    if (info.communicator != null)
                    {
                        destroyServiceCommunicator(service, info.communicator);
                    }

                    throw ex;
                }
            }
            finally
            {
                _m.Unlock();
            }
        }
Example #28
0
 /// <summary>
 /// Creates a Glacier2 session.
 /// </summary>
 /// <param name="callback">The callback for notifications about session
 /// establishment.</param>
 /// <param name="initData">The Ice.InitializationData for initializing
 /// the communicator.</param>
 public SessionHelper(SessionCallback callback, Ice.InitializationData initData)
 {
     _callback = callback;
     _initData = initData;
 }
Example #29
0
        //
        // Only for use by Ice.CommunicatorI
        //
        public Instance(Ice.Communicator communicator, Ice.InitializationData initData)
        {
            _state    = StateActive;
            _initData = initData;

            try
            {
                if (_initData.properties == null)
                {
                    _initData.properties = Ice.Util.createProperties();
                }
#if !SILVERLIGHT && !UNITY
                lock (_staticLock)
                {
                    if (!_oneOffDone)
                    {
                        string stdOut = _initData.properties.getProperty("Ice.StdOut");
                        string stdErr = _initData.properties.getProperty("Ice.StdErr");

                        System.IO.StreamWriter outStream = null;

                        if (stdOut.Length > 0)
                        {
                            try
                            {
                                outStream = System.IO.File.AppendText(stdOut);
                            }
                            catch (System.IO.IOException ex)
                            {
                                Ice.FileException fe = new Ice.FileException(ex);
                                fe.path = stdOut;
                                throw fe;
                            }
                            outStream.AutoFlush = true;
                            System.Console.Out.Close();
                            System.Console.SetOut(outStream);
                        }
                        if (stdErr.Length > 0)
                        {
                            if (stdErr.Equals(stdOut))
                            {
                                System.Console.SetError(outStream);
                            }
                            else
                            {
                                System.IO.StreamWriter errStream = null;
                                try
                                {
                                    errStream = System.IO.File.AppendText(stdErr);
                                }
                                catch (System.IO.IOException ex)
                                {
                                    Ice.FileException fe = new Ice.FileException(ex);
                                    fe.path = stdErr;
                                    throw fe;
                                }
                                errStream.AutoFlush = true;
                                System.Console.Error.Close();
                                System.Console.SetError(errStream);
                            }
                        }

                        _oneOffDone = true;
                    }
                }
#endif

                if (_initData.logger == null)
                {
#if !SILVERLIGHT && !UNITY
                    string logfile = _initData.properties.getProperty("Ice.LogFile");
                    if (_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0 &&
                        AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows)
                    {
                        if (logfile.Length != 0)
                        {
                            throw new Ice.InitializationException("Ice.LogFile and Ice.UseSyslog cannot both be set.");
                        }
                        _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"),
                                                              _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER"));
                    }
                    else if (logfile.Length != 0)
                    {
                        _initData.logger =
                            new Ice.FileLoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile);
                    }
                    else if (Ice.Util.getProcessLogger() is Ice.LoggerI)
                    {
                        //
                        // Ice.ConsoleListener is enabled by default.
                        //
#  if COMPACT
                        _initData.logger =
                            new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName"));
#  else
                        bool console =
                            _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener", 1) == 1;
                        _initData.logger =
                            new Ice.TraceLoggerI(_initData.properties.getProperty("Ice.ProgramName"), console);
#  endif
                    }
#else
                    if (Ice.Util.getProcessLogger() is Ice.LoggerI)
                    {
                        _initData.logger =
                            new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName"));
                    }
#endif
                    else
                    {
                        _initData.logger = Ice.Util.getProcessLogger();
                    }
                }
Example #30
0
    private void startService(string service, string entryPoint, string[] args)
    {
        _m.Lock();
        try
        {
            //
            // Extract the assembly name and the class name.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)
            {
                const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   driveLetters.IndexOf(entryPoint[0]) != -1 &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format";
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            string className = entryPoint.Substring(sepPos + 1);

            try
            {
                //
                // First try to load the assembly using Assembly.Load, which will succeed
                // if a fully-qualified name is provided or if a partial name has been qualified
                // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                // if a file name is configured or a partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;
            
            //
            // If IceBox.UseSharedCommunicator.<name> is defined, create a
            // communicator for the service. The communicator inherits
            // from the shared communicator properties. If it's not
            // defined, add the service properties to the shared
            // commnunicator property set.
            //
            Ice.Communicator communicator;
            IceInternal.MetricsAdminI metricsAdmin = null;
            if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
            {
                Debug.Assert(_sharedCommunicator != null);
                communicator = _sharedCommunicator;
                if(communicator.getObserver() is IceInternal.CommunicatorObserverI)
                {
                    IceInternal.CommunicatorObserverI o = (IceInternal.CommunicatorObserverI)communicator.getObserver();
                    metricsAdmin = o.getMetricsAdmin();
                }
            }
            else
            {
                //
                // Create the service properties. We use the communicator properties as the default
                // properties if IceBox.InheritProperties is set.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties(service);
                if(info.args.Length > 0)
                {
                    //
                    // Create the service properties with the given service arguments. This should
                    // read the service config file if it's specified with --Ice.Config.
                    //
                    initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                    //
                    // Next, parse the service "<service>.*" command line options (the Ice command
                    // line options were parsed by the createProperties above)
                    //
                    info.args = initData.properties.parseCommandLineOptions(service, info.args);
                }

                //
                // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                // don't set any logger.
                //
                if(initData.properties.getProperty("Ice.LogFile").Length == 0 &&
                   (initData.properties.getPropertyAsInt("Ice.UseSyslog") == 0 ||
                    IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows))
                {
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                }

                //
                // If Ice metrics are enabled on the IceBox communicator, we also enable them on
                // the service communicator.
                // 
                if(_communicator.getObserver() is IceInternal.CommunicatorObserverI)
                {
                    metricsAdmin = new IceInternal.MetricsAdminI(initData.properties, initData.logger);
                    initData.observer = new IceInternal.CommunicatorObserverI(metricsAdmin);
                }

                //
                // Remaining command line options are passed to the communicator. This is
                // necessary for Ice plug-in properties (e.g.: IceSSL).
                //
                info.communicator = Ice.Util.initialize(ref info.args, initData);
                communicator = info.communicator;

                //
                // Ensure the metrics admin plugin uses the same property set as the
                // communicator. This is necessary to correctly deal with runtime 
                // property updates.
                //
                if(metricsAdmin != null)
                {
                    metricsAdmin.setProperties(communicator.getProperties());
                }
            }

            try
            {   
                //
                // Add a PropertiesAdmin facet to the service manager's communicator that provides
                // access to this service's property set. We do this prior to instantiating the
                // service so that the service's constructor is able to access the facet (e.g.,
                // in case it wants to set a callback).
                //
                string facetName = "IceBox.Service." + info.name + ".Properties";
                IceInternal.PropertiesAdminI propAdmin = new IceInternal.PropertiesAdminI(facetName, 
                                                                                          communicator.getProperties(), 
                                                                                          communicator.getLogger());
                _communicator.addAdminFacet(propAdmin, facetName);
                
                //
                // If a metrics admin facet is setup for the service, register
                // it with the IceBox communicator.
                //
                if(metricsAdmin != null)
                {
                    _communicator.addAdminFacet(metricsAdmin, "IceBox.Service." + info.name + ".Metrics");

                    // Ensure the metrics admin facet is notified of property updates.
                    propAdmin.addUpdateCallback(metricsAdmin);
                }

                //
                // Instantiate the service.
                //
                try
                {
                    //
                    // If the service class provides a constructor that accepts an Ice.Communicator argument,
                    // use that in preference to the default constructor.
                    //
                    Type[] parameterTypes = new Type[1];
                    parameterTypes[0] = typeof(Ice.Communicator);
                    System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                    if(ci != null)
                    {
                        try
                        {
                            Object[] parameters = new Object[1];
                            parameters[0] = _communicator;
                            info.service = (Service)ci.Invoke(parameters);
                        }
                        catch(System.MethodAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                            throw e;
                        }
                    }
                    else
                    {
                        //
                        // Fall back to the default constructor.
                        //
                        try
                        {
                            info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                            if(info.service == null)
                            {
                                FailureException e = new FailureException();
                                e.reason = err + "no default constructor for '" + className + "'";
                                throw e;
                            }
                        }
                        catch(System.UnauthorizedAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unauthorized access to default service constructor for " + className;
                            throw e;
                        }
                    }
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.InvalidCastException ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "service does not implement IceBox.Service";
                    throw e;
                }
                catch(System.Reflection.TargetInvocationException ex)
                {
                    if(ex.InnerException is IceBox.FailureException)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        FailureException e = new FailureException(ex.InnerException);
                        e.reason = err + "exception in service constructor for " + className;
                        throw e;
                    }
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "exception in service constructor " + className;
                    throw e;
                }


                try
                {
                    info.service.start(service, communicator, info.args);
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = "exception while starting service " + service;
                    throw e;
                }

                info.status = ServiceStatus.Started;
                _services.Add(info);
            }
            catch(Ice.ObjectAdapterDeactivatedException)
            {
                //
                // Can be raised by addAdminFacet if the service manager communicator has been shut down.
                //
                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }
            }
            catch(System.Exception ex)
            {
                try
                {
                    _communicator.removeAdminFacet("IceBox.Service." + service + ".Properties");
                }
                catch(Ice.LocalException)
                {
                    // Ignored
                }

                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }

                throw ex;
            }

        }
        finally
        {
            _m.Unlock();
        }
    }
Example #31
0
            internal static void batchOneways(global::Test.TestHelper helper, Test.MyClassPrx p)
            {
                byte[] bs1 = new byte[10 * 1024];

                Test.MyClassPrx batch = Test.MyClassPrxHelper.uncheckedCast(p.ice_batchOneway());
                batch.ice_flushBatchRequests(); // Empty flush

                p.opByteSOnewayCallCount();     // Reset the call count

                for (int i = 0; i < 30; ++i)
                {
                    try
                    {
                        batch.opByteSOneway(bs1);
                        test(true);
                    }
                    catch (Ice.MemoryLimitException)
                    {
                        test(false);
                    }
                }

                int count = 0;

                while (count < 27) // 3 * 9 requests auto-flushed.
                {
                    count += p.opByteSOnewayCallCount();
                    System.Threading.Thread.Sleep(10);
                }

                if (batch.ice_getConnection() != null)
                {
                    Test.MyClassPrx batch1 = Test.MyClassPrxHelper.uncheckedCast(p.ice_batchOneway());
                    Test.MyClassPrx batch2 = Test.MyClassPrxHelper.uncheckedCast(p.ice_batchOneway());

                    batch1.ice_ping();
                    batch2.ice_ping();
                    batch1.ice_flushBatchRequests();
                    batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    batch1.ice_ping();
                    batch2.ice_ping();

                    batch1.ice_getConnection();
                    batch2.ice_getConnection();

                    batch1.ice_ping();
                    batch1.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    batch1.ice_ping();
                    batch2.ice_ping();
                }

                Ice.Identity identity = new Ice.Identity();
                identity.name = "invalid";
                Ice.ObjectPrx batch3 = batch.ice_identity(identity);
                batch3.ice_ping();
                batch3.ice_flushBatchRequests();

                // Make sure that a bogus batch request doesn't cause troubles to other ones.
                batch3.ice_ping();
                batch.ice_ping();
                batch.ice_flushBatchRequests();
                batch.ice_ping();

                if (batch.ice_getConnection() != null)
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = p.ice_getCommunicator().getProperties().ice_clone_();
                    BatchRequestInterceptorI interceptor = new BatchRequestInterceptorI();
                    initData.batchRequestInterceptor = interceptor.enqueue;
                    Ice.Communicator ic = helper.initialize(initData);

                    batch = Test.MyClassPrxHelper.uncheckedCast(ic.stringToProxy(p.ToString()).ice_batchOneway());

                    test(interceptor.count() == 0);
                    batch.ice_ping();
                    batch.ice_ping();
                    batch.ice_ping();
                    test(interceptor.count() == 0);

                    interceptor.setEnqueue(true);
                    batch.ice_ping();
                    batch.ice_ping();
                    batch.ice_ping();
                    test(interceptor.count() == 3);

                    batch.ice_flushBatchRequests();
                    batch.ice_ping();
                    test(interceptor.count() == 1);

                    batch.opByteSOneway(bs1);
                    test(interceptor.count() == 2);
                    batch.opByteSOneway(bs1);
                    test(interceptor.count() == 3);

                    batch.opByteSOneway(bs1); // This should trigger the flush
                    batch.ice_ping();
                    test(interceptor.count() == 2);

                    ic.destroy();
                }

                p.ice_ping();

                bool supportsCompress = true;

                try
                {
                    supportsCompress = p.supportsCompress();
                }
                catch (Ice.OperationNotExistException)
                {
                }

                if (supportsCompress && p.ice_getConnection() != null &&
                    p.ice_getCommunicator().getProperties().getProperty("Ice.Override.Compress").Equals(""))
                {
                    Ice.ObjectPrx prx = p.ice_getConnection().createProxy(p.ice_getIdentity()).ice_batchOneway();

                    Test.MyClassPrx batchC1 = Test.MyClassPrxHelper.uncheckedCast(prx.ice_compress(false));
                    Test.MyClassPrx batchC2 = Test.MyClassPrxHelper.uncheckedCast(prx.ice_compress(true));
                    Test.MyClassPrx batchC3 = Test.MyClassPrxHelper.uncheckedCast(prx.ice_identity(identity));

                    batchC1.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.ice_getConnection().flushBatchRequests(Ice.CompressBatch.Yes);

                    batchC2.opByteSOneway(bs1);
                    batchC2.opByteSOneway(bs1);
                    batchC2.opByteSOneway(bs1);
                    batchC1.ice_getConnection().flushBatchRequests(Ice.CompressBatch.No);

                    batchC1.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.ice_getConnection().flushBatchRequests(Ice.CompressBatch.BasedOnProxy);

                    batchC1.opByteSOneway(bs1);
                    batchC2.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.ice_getConnection().flushBatchRequests(Ice.CompressBatch.BasedOnProxy);

                    batchC1.opByteSOneway(bs1);
                    batchC3.opByteSOneway(bs1);
                    batchC1.opByteSOneway(bs1);
                    batchC1.ice_getConnection().flushBatchRequests(Ice.CompressBatch.BasedOnProxy);
                }
            }
Example #32
0
            public static void allTestsWithController(global::Test.TestHelper helper, Test.ControllerPrx controller)
            {
                var    communicator = helper.communicator();
                string sref         = "timeout:" + helper.getTestEndpoint(0);
                var    obj          = communicator.stringToProxy(sref);

                test(obj != null);

                Test.TimeoutPrx timeout = Test.TimeoutPrxHelper.checkedCast(obj);
                test(timeout != null);

                var output = helper.getWriter();

                output.Write("testing connect timeout... ");
                output.Flush();
                {
                    //
                    // Expect ConnectTimeoutException.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(100));
                    controller.holdAdapter(-1);
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                {
                    //
                    // Expect success.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(-1));
                    controller.holdAdapter(100);
                    try
                    {
                        to.op();
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                        test(false);
                    }
                }
                output.WriteLine("ok");

                // The sequence needs to be large enough to fill the write/recv buffers
                byte[] seq = new byte[2000000];

                output.Write("testing connection timeout... ");
                output.Flush();
                {
                    //
                    // Expect TimeoutException.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250));
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                {
                    //
                    // Expect success.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(2000));
                    controller.holdAdapter(100);
                    try
                    {
                        to.sendData(new byte[1000000]);
                    }
                    catch (Ice.TimeoutException)
                    {
                        test(false);
                    }
                }
                output.WriteLine("ok");

                output.Write("testing invocation timeout... ");
                output.Flush();
                {
                    var             connection = obj.ice_getConnection();
                    Test.TimeoutPrx to         = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(100));
                    test(connection == to.ice_getConnection());
                    try
                    {
                        to.sleep(1000);
                        test(false);
                    }
                    catch (Ice.InvocationTimeoutException)
                    {
                    }
                    obj.ice_ping();
                    to = Test.TimeoutPrxHelper.checkedCast(obj.ice_invocationTimeout(1000));
                    test(connection == to.ice_getConnection());
                    try
                    {
                        to.sleep(100);
                    }
                    catch (Ice.InvocationTimeoutException)
                    {
                        test(false);
                    }
                    test(connection == to.ice_getConnection());
                }
                {
                    //
                    // Expect InvocationTimeoutException.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(100));
                    Callback        cb = new Callback();
                    to.begin_sleep(1000).whenCompleted(
                        () =>
                    {
                        test(false);
                    },
                        (Ice.Exception ex) =>
                    {
                        test(ex is Ice.InvocationTimeoutException);
                        cb.called();
                    });
                    cb.check();
                    obj.ice_ping();
                }
                {
                    //
                    // Expect success.
                    //
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(1000));
                    Callback        cb = new Callback();
                    to.begin_sleep(100).whenCompleted(
                        () =>
                    {
                        cb.called();
                    },
                        (Ice.Exception ex) =>
                    {
                        test(false);
                    });
                    cb.check();
                }
                {
                    //
                    // Backward compatible connection timeouts
                    //
                    Test.TimeoutPrx to  = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(-2).ice_timeout(250));
                    var             con = connect(to);
                    try
                    {
                        to.sleep(750);
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        try
                        {
                            con.getInfo();
                            test(false);
                        }
                        catch (Ice.TimeoutException)
                        {
                            // Connection got closed as well.
                        }
                    }
                    obj.ice_ping();

                    try
                    {
                        con = connect(to);
                        to.end_sleep(to.begin_sleep(750));
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        try
                        {
                            con.getInfo();
                            test(false);
                        }
                        catch (Ice.TimeoutException)
                        {
                            // Connection got closed as well.
                        }
                    }
                    obj.ice_ping();
                }
                output.WriteLine("ok");

                output.Write("testing close timeout... ");
                output.Flush();
                {
                    Test.TimeoutPrx to         = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250));
                    var             connection = connect(to);
                    controller.holdAdapter(-1);
                    connection.close(Ice.ConnectionClose.GracefullyWithWait);
                    try
                    {
                        connection.getInfo(); // getInfo() doesn't throw in the closing state.
                    }
                    catch (Ice.LocalException)
                    {
                        test(false);
                    }
                    while (true)
                    {
                        try
                        {
                            connection.getInfo();
                            Thread.Sleep(10);
                        }
                        catch (Ice.ConnectionManuallyClosedException ex)
                        {
                            // Expected.
                            test(ex.graceful);
                            break;
                        }
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                }
                output.WriteLine("ok");

                output.Write("testing timeout overrides... ");
                output.Flush();
                {
                    //
                    // Test Ice.Override.Timeout. This property overrides all
                    // endpoint timeouts.
                    //
                    var initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().ice_clone_();
                    initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
                    initData.properties.setProperty("Ice.Override.Timeout", "100");
                    var             comm = helper.initialize(initData);
                    Test.TimeoutPrx to   = Test.TimeoutPrxHelper.uncheckedCast(comm.stringToProxy(sref));
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Calling ice_timeout() should have no effect.
                    //
                    to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(1000));
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                    comm.destroy();
                }
                {
                    //
                    // Test Ice.Override.ConnectTimeout.
                    //
                    var initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().ice_clone_();
                    initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
                    var comm = helper.initialize(initData);
                    controller.holdAdapter(-1);
                    Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(comm.stringToProxy(sref));
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Calling ice_timeout() should have no effect on the connect timeout.
                    //
                    controller.holdAdapter(-1);
                    to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(1000));
                    try
                    {
                        to.op();
                        test(false);
                    }
                    catch (Ice.ConnectTimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.

                    //
                    // Verify that timeout set via ice_timeout() is still used for requests.
                    //
                    to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(250));
                    connect(to);
                    controller.holdAdapter(-1);
                    try
                    {
                        to.sendData(seq);
                        test(false);
                    }
                    catch (Ice.TimeoutException)
                    {
                        // Expected.
                    }
                    controller.resumeAdapter();
                    timeout.op(); // Ensure adapter is active.
                    comm.destroy();
                }
                {
                    //
                    // Test Ice.Override.CloseTimeout.
                    //
                    var initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().ice_clone_();
                    initData.properties.setProperty("Ice.Override.CloseTimeout", "100");
                    var comm = helper.initialize(initData);
                    comm.stringToProxy(sref).ice_getConnection();
                    controller.holdAdapter(-1);
                    long begin = System.DateTime.Now.Ticks;
                    comm.destroy();
                    test(((long)new System.TimeSpan(System.DateTime.Now.Ticks - begin).TotalMilliseconds - begin) < 1000);
                    controller.resumeAdapter();
                }
                output.WriteLine("ok");

                output.Write("testing invocation timeouts with collocated calls... ");
                output.Flush();
                {
                    communicator.getProperties().setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                    var adapter = communicator.createObjectAdapter("TimeoutCollocated");
                    adapter.activate();

                    Test.TimeoutPrx proxy = Test.TimeoutPrxHelper.uncheckedCast(adapter.addWithUUID(new TimeoutI()));
                    proxy = (Test.TimeoutPrx)proxy.ice_invocationTimeout(100);
                    try
                    {
                        proxy.sleep(500);
                        test(false);
                    }
                    catch (Ice.InvocationTimeoutException)
                    {
                    }

                    try
                    {
                        proxy.end_sleep(proxy.begin_sleep(500));
                        test(false);
                    }
                    catch (Ice.InvocationTimeoutException)
                    {
                    }

                    try
                    {
                        ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-2)).ice_ping();
                        ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-2)).begin_ice_ping().waitForCompleted();
                    }
                    catch (Ice.Exception)
                    {
                        test(false);
                    }

                    Test.TimeoutPrx batchTimeout = (Test.TimeoutPrx)proxy.ice_batchOneway();
                    batchTimeout.ice_ping();
                    batchTimeout.ice_ping();
                    batchTimeout.ice_ping();

                    ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-1)).begin_sleep(500); // Keep the server thread pool busy.
                    try
                    {
                        batchTimeout.end_ice_flushBatchRequests(batchTimeout.begin_ice_flushBatchRequests());
                        test(false);
                    }
                    catch (Ice.InvocationTimeoutException)
                    {
                    }

                    adapter.destroy();
                }
                output.WriteLine("ok");

                controller.shutdown();
            }
Example #33
0
        private TraceLevels _traceLevels; // Immutable, not reset by destroy().

        #endregion Fields

        #region Constructors

        //
        // Only for use by Ice.CommunicatorI
        //
        public Instance(Ice.Communicator communicator, Ice.InitializationData initData)
        {
            _state = StateActive;
            _initData = initData;

            try
            {
                if(_initData.properties == null)
                {
                    _initData.properties = Ice.Util.createProperties();
                }

                lock(_staticLock)
                {
                    if(!_oneOffDone)
                    {
                        string stdOut = _initData.properties.getProperty("Ice.StdOut");
                        string stdErr = _initData.properties.getProperty("Ice.StdErr");

                        System.IO.StreamWriter outStream = null;

                        if(stdOut.Length > 0)
                        {
                            try
                            {
                                outStream = System.IO.File.AppendText(stdOut);
                            }
                            catch(System.IO.IOException ex)
                            {
                                Ice.FileException fe = new Ice.FileException(ex);
                                fe.path = stdOut;
                                throw fe;
                            }
                            outStream.AutoFlush = true;
                            System.Console.Out.Close();
                            System.Console.SetOut(outStream);
                        }
                        if(stdErr.Length > 0)
                        {
                            if(stdErr.Equals(stdOut))
                            {
                                System.Console.SetError(outStream);
                            }
                            else
                            {
                                System.IO.StreamWriter errStream = null;
                                try
                                {
                                    errStream = System.IO.File.AppendText(stdErr);
                                }
                                catch(System.IO.IOException ex)
                                {
                                    Ice.FileException fe = new Ice.FileException(ex);
                                    fe.path = stdErr;
                                    throw fe;
                                }
                                errStream.AutoFlush = true;
                                System.Console.Error.Close();
                                System.Console.SetError(errStream);
                            }
                        }

                        _oneOffDone = true;
                    }
                }

                if(_initData.logger == null)
                {
                    string logfile = _initData.properties.getProperty("Ice.LogFile");
                    if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0 &&
                       AssemblyUtil.platform_ != AssemblyUtil.Platform.Windows)
                    {
                        if(logfile.Length != 0)
                        {
                            throw new Ice.InitializationException("Ice.LogFile and Ice.UseSyslog cannot both be set.");
                        }
                        _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"),
                            _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER"));
                    }
                    else if(logfile.Length != 0)
                    {

                        _initData.logger =
                            new Ice.FileLoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile);
                    }
                    else if(Ice.Util.getProcessLogger() is Ice.LoggerI)
                    {
                        //
                        // Ice.ConsoleListener is enabled by default.
                        //
                        bool console =
                            _initData.properties.getPropertyAsIntWithDefault("Ice.ConsoleListener", 1) > 0;
                        _initData.logger =
                            new Ice.TraceLoggerI(_initData.properties.getProperty("Ice.ProgramName"), console);
                    }

                    if(Ice.Util.getProcessLogger() is Ice.LoggerI)
                    {
                        _initData.logger =
                            new Ice.ConsoleLoggerI(_initData.properties.getProperty("Ice.ProgramName"));
                    }
                    else
                    {
                        _initData.logger = Ice.Util.getProcessLogger();
                    }
                }

                _traceLevels = new TraceLevels(_initData.properties);

                _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties, _initData.logger);

                _clientACM = new ACMConfig(_initData.properties,
                                           _initData.logger,
                                           "Ice.ACM.Client",
                                           new ACMConfig(_initData.properties, _initData.logger, "Ice.ACM",
                                                         new ACMConfig(false)));

                _serverACM = new ACMConfig(_initData.properties,
                                           _initData.logger,
                                           "Ice.ACM.Server",
                                           new ACMConfig(_initData.properties, _initData.logger, "Ice.ACM",
                                                         new ACMConfig(true)));

                {
                    const int defaultMessageSizeMax = 1024;
                    int num =
                        _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax);
                    if(num < 1 || num > 0x7fffffff / 1024)
                    {
                        _messageSizeMax = 0x7fffffff;
                    }
                    else
                    {
                        _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes
                    }
                }

                if(_initData.properties.getProperty("Ice.BatchAutoFlushSize").Length == 0 &&
                   _initData.properties.getProperty("Ice.BatchAutoFlush").Length > 0)
                {
                    if(_initData.properties.getPropertyAsInt("Ice.BatchAutoFlush") > 0)
                    {
                        _batchAutoFlushSize = _messageSizeMax;
                    }
                }
                else
                {
                    int num = _initData.properties.getPropertyAsIntWithDefault("Ice.BatchAutoFlushSize", 1024); // 1MB
                    if(num < 1)
                    {
                        _batchAutoFlushSize = num;
                    }
                    else if(num > 0x7fffffff / 1024)
                    {
                        _batchAutoFlushSize = 0x7fffffff;
                    }
                    else
                    {
                        _batchAutoFlushSize = num * 1024; // Property is in kilobytes, _batchAutoFlushSize in bytes
                    }
                }

                _cacheMessageBuffers = _initData.properties.getPropertyAsIntWithDefault("Ice.CacheMessageBuffers", 2);

                _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext"));
                _routerManager = new RouterManager();

                _locatorManager = new LocatorManager(_initData.properties);

                _referenceFactory = new ReferenceFactory(this, communicator);

                _proxyFactory = new ProxyFactory(this);

                _requestHandlerFactory = new RequestHandlerFactory(this);

                bool isIPv6Supported = Network.isIPv6Supported();
                bool ipv4 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
                bool ipv6 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv6", isIPv6Supported ? 1 : 0) > 0;
                if(!ipv4 && !ipv6)
                {
                    throw new Ice.InitializationException("Both IPV4 and IPv6 support cannot be disabled.");
                }
                else if(ipv4 && ipv6)
                {
                    _protocolSupport = Network.EnableBoth;
                }
                else if(ipv4)
                {
                    _protocolSupport = Network.EnableIPv4;
                }
                else
                {
                    _protocolSupport = Network.EnableIPv6;
                }
                _preferIPv6 = _initData.properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;

                _networkProxy = createNetworkProxy(_initData.properties, _protocolSupport);

                _endpointFactoryManager = new EndpointFactoryManager(this);

                ProtocolInstance tcpInstance = new ProtocolInstance(this, Ice.TCPEndpointType.value, "tcp", false);
                _endpointFactoryManager.add(new TcpEndpointFactory(tcpInstance));

                ProtocolInstance udpInstance = new ProtocolInstance(this, Ice.UDPEndpointType.value, "udp", false);
                _endpointFactoryManager.add(new UdpEndpointFactory(udpInstance));
                _pluginManager = new Ice.PluginManagerI(communicator);

                if(_initData.valueFactoryManager == null)
                {
                    _initData.valueFactoryManager = new ValueFactoryManagerI();
                }

                _outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this);

                _objectAdapterFactory = new ObjectAdapterFactory(this, communicator);

                _retryQueue = new RetryQueue(this);
            }
            catch(Ice.LocalException)
            {
                destroy();
                throw;
            }
        }
Example #34
0
        /// <summary>
        /// 初始化连接
        /// </summary>
        /// <returns></returns>
        public bool Init()
        {
            try
            {
                lock (lockData)
                {
                    Ice.InitializationData intiData = new Ice.InitializationData();

                    Ice.Properties properties = Ice.Util.createProperties();

                    properties.setProperty("Ice.MessageSizeMax", "104857600");

                    intiData.properties = properties;

                    ic = Ice.Util.initialize(intiData);

                    // 连接
                    Ice.ObjectPrx objectPrx = ic.stringToProxy(string.Format("{0}:tcp -h {1} -p {2} -t 5000", NMCommunicationRPCId.value,
                                                                             EEMSConfigHelper.GetValueByCommomConfig("config/CommonConfig/netagent_ip", "127.0.0.1"),
                                                                             EEMSConfigHelper.GetValueByCommomConfig("config/CommonConfig/netagent_port", "40050")));

                    client = NMServerPrxHelper.checkedCast(objectPrx);

                    // 代理
                    Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints(NMCommunicationRPCId.value, string.Format("tcp -h {0} -p {1} -t 5000",
                                                                                                                              EEMSConfigHelper.GetValueByCommomConfig("config/CollectClient/WarnInfoLocalIp", "127.0.0.1"),
                                                                                                                              EEMSConfigHelper.GetValueByCommomConfig("config/CollectClient/WarnInfoClentPort", "42050")));

                    NMClientI clientI = new NMClientI();

                    clientI.ReceiveDataHandler += clientI_ReceiveDataHandler;

                    Ice.Object obj = clientI;

                    adapter.add(obj, ic.stringToIdentity(NMCommunicationRPCId.value));

                    adapter.activate();

                    NMClientPrx call = NMClientPrxHelper.uncheckedCast(adapter.createProxy(ic.stringToIdentity(NMCommunicationRPCId.value)));

                    client.NMRegistClient(clientID, call);

                    IsConnect = true;
                }

                return(true);
            }
            catch (Exception e)
            {
                // 初始化失败
                client = null;
                LogHelper.Instance.WirteErrorMsg(e.Message);
                return(false);
            }
            finally
            {
                if (!isThreadStart)
                {
                    isThreadStart = true;
                    CheckConnectThread();
                }
            }
        }
Example #35
0
        private void startService(string service, string entryPoint, string[] args)
        {
            lock(this)
            {
            //
            // Extract the assembly name and the class name.
            //
            string err = "ServiceManager: unable to load service '" + entryPoint + "': ";
            int sepPos = entryPoint.IndexOf(':');
            if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)
            {
                const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                if(entryPoint.Length > 3 &&
                   sepPos == 1 &&
                   driveLetters.IndexOf(entryPoint[0]) != -1 &&
                   (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                {
                    sepPos = entryPoint.IndexOf(':', 3);
                }
            }
            if(sepPos == -1)
            {
                FailureException e = new FailureException();
                e.reason = err + "invalid entry point format";
                throw e;
            }

            System.Reflection.Assembly serviceAssembly = null;
            string assemblyName = entryPoint.Substring(0, sepPos);
            string className = entryPoint.Substring(sepPos + 1);

            try
            {
                //
                // First try to load the assembly using Assembly.Load, which will succeed
                // if a fully-qualified name is provided or if a partial name has been qualified
                // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                // if a file name is configured or a partial name is configured and DEVPATH is used.
                //
                try
                {
                    serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                }
                catch(System.IO.IOException ex)
                {
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                    }
                    catch(System.IO.IOException)
                    {
                         throw ex;
                    }
                }
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "unable to load assembly: " + assemblyName;
                throw e;
            }

            //
            // Instantiate the class.
            //
            System.Type c = null;
            try
            {
                c = serviceAssembly.GetType(className, true);
            }
            catch(System.Exception ex)
            {
                FailureException e = new FailureException(ex);
                e.reason = err + "GetType failed for '" + className + "'";
                throw e;
            }

            ServiceInfo info = new ServiceInfo();
            info.name = service;
            info.status = ServiceStatus.Stopped;
            info.args = args;

            //
            // If IceBox.UseSharedCommunicator.<name> is defined, create a
            // communicator for the service. The communicator inherits
            // from the shared communicator properties. If it's not
            // defined, add the service properties to the shared
            // commnunicator property set.
            //
            Ice.Communicator communicator;
            if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
            {
                Debug.Assert(_sharedCommunicator != null);
                communicator = _sharedCommunicator;
            }
            else
            {
                //
                // Create the service properties. We use the communicator properties as the default
                // properties if IceBox.InheritProperties is set.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties(service);
                if(info.args.Length > 0)
                {
                    //
                    // Create the service properties with the given service arguments. This should
                    // read the service config file if it's specified with --Ice.Config.
                    //
                    initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                    //
                    // Next, parse the service "<service>.*" command line options (the Ice command
                    // line options were parsed by the createProperties above)
                    //
                    info.args = initData.properties.parseCommandLineOptions(service, info.args);
                }

                //
                // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                // don't set any logger.
                //
                if(initData.properties.getProperty("Ice.LogFile").Length == 0 &&
                   (initData.properties.getPropertyAsInt("Ice.UseSyslog") <= 0 ||
                    IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows))
                {
                    initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                }

                //
                // If Admin is enabled on the IceBox communicator, for each service that does not set
                // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then
                // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>.
                //
                string serviceFacetNamePrefix = "IceBox.Service." + service + ".";
                bool addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix);

                //
                // Remaining command line options are passed to the communicator. This is
                // necessary for Ice plug-in properties (e.g.: IceSSL).
                //
                info.communicator = Ice.Util.initialize(ref info.args, initData);
                communicator = info.communicator;

                if(addFacets)
                {
                    // Add all facets created on the service communicator to the IceBox communicator
                    // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet
                    // which is never added
                    foreach(KeyValuePair<string, Ice.Object> p in communicator.findAllAdminFacets())
                    {
                        if(!p.Key.Equals("Process"))
                        {
                            _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key);
                        }
                    }
                }
            }

            try
            {
                //
                // Instantiate the service.
                //
                try
                {
                    //
                    // If the service class provides a constructor that accepts an Ice.Communicator argument,
                    // use that in preference to the default constructor.
                    //
                    Type[] parameterTypes = new Type[1];
                    parameterTypes[0] = typeof(Ice.Communicator);
                    System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                    if(ci != null)
                    {
                        try
                        {
                            Object[] parameters = new Object[1];
                            parameters[0] = _communicator;
                            info.service = (Service)ci.Invoke(parameters);
                        }
                        catch(System.MethodAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                            throw e;
                        }
                    }
                    else
                    {
                        //
                        // Fall back to the default constructor.
                        //
                        try
                        {
                            info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                            if(info.service == null)
                            {
                                FailureException e = new FailureException();
                                e.reason = err + "no default constructor for '" + className + "'";
                                throw e;
                            }
                        }
                        catch(System.UnauthorizedAccessException ex)
                        {
                            FailureException e = new FailureException(ex);
                            e.reason = err + "unauthorized access to default service constructor for " + className;
                            throw e;
                        }
                    }
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.InvalidCastException ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "service does not implement IceBox.Service";
                    throw e;
                }
                catch(System.Reflection.TargetInvocationException ex)
                {
                    if(ex.InnerException is IceBox.FailureException)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        FailureException e = new FailureException(ex.InnerException);
                        e.reason = err + "exception in service constructor for " + className;
                        throw e;
                    }
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "exception in service constructor " + className;
                    throw e;
                }

                try
                {
                    info.service.start(service, communicator, info.args);
                }
                catch(FailureException)
                {
                    throw;
                }
                catch(System.Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = "exception while starting service " + service;
                    throw e;
                }

                info.status = ServiceStatus.Started;
                _services.Add(info);
            }
            catch(System.Exception)
            {
                if(info.communicator != null)
                {
                    destroyServiceCommunicator(service, info.communicator);
                }

                throw;
            }

            }
        }
Example #36
0
            public static Test.TestIntfPrx allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing stringToProxy... ");
                output.Flush();
                string @ref = "test:" + helper.getTestEndpoint(0);

                Ice.ObjectPrx @base = communicator.stringToProxy(@ref);
                test(@base != null);
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                var obj = Test.TestIntfPrxHelper.checkedCast(@base);

                test(obj != null);
                test(obj.Equals(@base));
                output.WriteLine("ok");

                {
                    output.Write("creating/destroying/recreating object adapter... ");
                    output.Flush();
                    Ice.ObjectAdapter adapter =
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                        test(false);
                    }
                    catch (Ice.AlreadyRegisteredException)
                    {
                    }
                    adapter.destroy();

                    //
                    // Use a different port than the first adapter to avoid an "address already in use" error.
                    //
                    adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    adapter.destroy();
                    output.WriteLine("ok");
                }

                output.Write("creating/activating/deactivating object adapter in one operation... ");
                output.Flush();
                obj.transient();
                obj.end_transient(obj.begin_transient());
                output.WriteLine("ok");

                {
                    output.Write("testing connection closure... ");
                    output.Flush();
                    for (int i = 0; i < 10; ++i)
                    {
                        Ice.InitializationData initData = new Ice.InitializationData();
                        initData.properties = communicator.getProperties().ice_clone_();
                        Ice.Communicator comm = Ice.Util.initialize(initData);
                        comm.stringToProxy("test:" + helper.getTestEndpoint(0)).begin_ice_ping();
                        comm.destroy();
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter published endpoints... ");
                output.Flush();
                {
                    communicator.getProperties().setProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 30000");
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapter("PAdapter");
                    test(adapter.getPublishedEndpoints().Length == 1);
                    Ice.Endpoint endpt = adapter.getPublishedEndpoints()[0];
                    test(endpt.ToString().Equals("tcp -h localhost -p 12345 -t 30000"));
                    Ice.ObjectPrx prx =
                        communicator.stringToProxy("dummy:tcp -h localhost -p 12346 -t 20000:tcp -h localhost -p 12347 -t 10000");
                    adapter.setPublishedEndpoints(prx.ice_getEndpoints());
                    test(adapter.getPublishedEndpoints().Length == 2);
                    Ice.Identity id = new Ice.Identity();
                    id.name = "dummy";
                    test(IceUtilInternal.Arrays.Equals(adapter.createProxy(id).ice_getEndpoints(), prx.ice_getEndpoints()));
                    test(IceUtilInternal.Arrays.Equals(adapter.getPublishedEndpoints(), prx.ice_getEndpoints()));
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].Equals(endpt));
                    communicator.getProperties().setProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 20000");
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 12345 -t 20000"));
                    adapter.destroy();
                    test(adapter.getPublishedEndpoints().Length == 0);
                }
                output.WriteLine("ok");

                if (obj.ice_getConnection() != null)
                {
                    output.Write("testing object adapter with bi-dir connection... ");
                    output.Flush();
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapter("");
                    obj.ice_getConnection().setAdapter(adapter);
                    obj.ice_getConnection().setAdapter(null);
                    adapter.deactivate();
                    try
                    {
                        obj.ice_getConnection().setAdapter(adapter);
                        test(false);
                    }
                    catch (Ice.ObjectAdapterDeactivatedException)
                    {
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter with router... ");
                output.Flush();
                {
                    Ice.Identity routerId = new Ice.Identity();
                    routerId.name = "router";
                    Ice.RouterPrx router =
                        Ice.RouterPrxHelper.uncheckedCast(@base.ice_identity(routerId).ice_connectionId("rc"));
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithRouter("", router);
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23456 -t 30000"));
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23457 -t 30000"));
                    try
                    {
                        adapter.setPublishedEndpoints(router.ice_getEndpoints());
                        test(false);
                    }
                    catch (ArgumentException)
                    {
                        // Expected.
                    }
                    adapter.destroy();

                    try
                    {
                        routerId.name = "test";
                        router        = Ice.RouterPrxHelper.uncheckedCast(@base.ice_identity(routerId));
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (Ice.OperationNotExistException)
                    {
                        // Expected: the "test" object doesn't implement Ice::Router!
                    }

                    try
                    {
                        router = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("test:" +
                                                                                              helper.getTestEndpoint(1)));
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                }
                output.WriteLine("ok");

                output.Write("testing object adapter creation with port in use... ");
                output.Flush();
                {
                    var adapter1 = communicator.createObjectAdapterWithEndpoints("Adpt1", helper.getTestEndpoint(10));
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("Adpt2", helper.getTestEndpoint(10));
                        test(false);
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected can't re-use the same endpoint.
                    }
                    adapter1.destroy();
                }
                output.WriteLine("ok");

                output.Write("deactivating object adapter in the server... ");
                output.Flush();
                obj.deactivate();
                output.WriteLine("ok");

                output.Write("testing whether server is gone... ");
                output.Flush();
                try
                {
                    obj.ice_timeout(100).ice_ping(); // Use timeout to speed up testing on Windows
                    test(false);
                }
                catch (Ice.LocalException)
                {
                    output.WriteLine("ok");
                }

                return(obj);
            }
Example #37
0
    private static Ice.Communicator createSendLogCommunicator(Ice.Communicator communicator, Ice.Logger logger)
    {
        Ice.InitializationData initData = new Ice.InitializationData();
        initData.logger = logger;
        initData.properties = Ice.Util.createProperties();

        Ice.Properties mainProps = communicator.getProperties();

        copyProperties("Ice.Default.Locator", mainProps, initData.properties);
        copyProperties("Ice.Plugin.IceSSL", mainProps, initData.properties);
        copyProperties("IceSSL.", mainProps, initData.properties);

        string[] extraProps = mainProps.getPropertyAsList("Ice.Admin.Logger.Properties");
    
        if(extraProps.Length > 0)
        {
            for(int i = 0; i < extraProps.Length; ++i)
            {
                string p = extraProps[i];
                if(!p.StartsWith("--"))
                {
                    extraProps[i] = "--" + p;
                }
            }
            initData.properties.parseCommandLineOptions("", extraProps);
        }
        return Ice.Util.initialize(initData);
    }
Example #38
0
        public IceManager(string adapterName, string host, int port, bool catchSignals = true)
        {
            IceGridHost = host;
            IceGridPort = port;
            Name        = adapterName;

            logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name);

            _ServantIds = new List <Ice.Identity>(); //keep track of servants for emergency cleanup
            string myIP = findLocalIPAddress();

            logger.Info("My IPAddress is: " + myIP);

            //initialize Ice
            Ice.Properties prop = Ice.Util.createProperties();
            prop.setProperty("hms.AdapterId", adapterName);
            prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP);
            prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost);
            prop.setProperty("Ice.ThreadPool.Server.Size", "5");
            prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000");
            prop.setProperty("Ice.ThreadPool.Client.Size", "5");
            prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000");

            Ice.InitializationData iceidata = new Ice.InitializationData();
            iceidata.properties = prop;
            Communicator        = Ice.Util.initialize(iceidata); // could add sys.argv
            try
            {
                _Adapter = Communicator.createObjectAdapter("hms");
                _Adapter.activate();
            }
            catch (Exception ex)
            {
                logger.Fatal("Network error, check configuration: " + ex.Message);
                logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints"));
                logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator"));
                throw (ex); // we are dead anyway
            }
            //Now are we ready to communicate with others
            //getting usefull proxies

            try
            {
                // proxy to icegrid to register our vc devices
                Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query"));
                if (Query == null)
                {
                    logger.Error("invalid ICeGrid proxy");
                }
                // proxy to icestorm to publish events
                EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager"));
                if (EventMgr == null)
                {
                    logger.Error("invalid IceStorm proxy");
                }
                //these 2 objects are only needed to get the IceGrid admin object in order to register
                _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry"));
                updateIceGridAdmin();
            }
            catch (Ice.NotRegisteredException e)
            {
                logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message);
            }
            catch (Exception e)
            {
                logger.Fatal("IceGrid Server not found!!!!!: " + e.Message);
                throw (e);//without yellow page system, there is no need to start
            }
            if (catchSignals)
            {
                setupSignals();
            }
        }
Example #39
0
        public int run()
        {
            try
            {
                Ice.Properties properties = _communicator.getProperties();

                //
                // Create an object adapter. Services probably should NOT share
                // this object adapter, as the endpoint(s) for this object adapter
                // will most likely need to be firewalled for security reasons.
                //
                Ice.ObjectAdapter adapter = null;
                if (properties.getProperty("IceBox.ServiceManager.Endpoints").Length != 0)
                {
                    adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                    Ice.Identity identity = new Ice.Identity();
                    identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                    identity.name     = "ServiceManager";
                    adapter.add(this, identity);
                }

                //
                // Parse the property set with the prefix "IceBox.Service.". These
                // properties should have the following format:
                //
                // IceBox.Service.Foo=<assembly>:Package.Foo [args]
                //
                // We parse the service properties specified in IceBox.LoadOrder
                // first, then the ones from remaining services.
                //
                string prefix = "IceBox.Service.";
                Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);
                string[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
                List <StartServiceInfo> servicesInfo = new List <StartServiceInfo>();
                for (int i = 0; i < loadOrder.Length; ++i)
                {
                    if (loadOrder[i].Length > 0)
                    {
                        string key   = prefix + loadOrder[i];
                        string value = services[key];
                        if (value == null)
                        {
                            FailureException ex = new FailureException();
                            ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
                            throw ex;
                        }
                        servicesInfo.Add(new StartServiceInfo(loadOrder[i], value, _argv));
                        services.Remove(key);
                    }
                }
                foreach (KeyValuePair <string, string> entry in services)
                {
                    string name  = entry.Key.Substring(prefix.Length);
                    string value = entry.Value;
                    servicesInfo.Add(new StartServiceInfo(name, value, _argv));
                }

                //
                // Check if some services are using the shared communicator in which
                // case we create the shared communicator now with a property set that
                // is the union of all the service properties (from services that use
                // the shared communicator).
                //
                if (properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").Count > 0)
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties("SharedCommunicator");
                    foreach (StartServiceInfo service in servicesInfo)
                    {
                        if (properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                        {
                            continue;
                        }

                        //
                        // Load the service properties using the shared communicator properties as
                        // the default properties.
                        //
                        Ice.Properties svcProperties = Ice.Util.createProperties(ref service.args, initData.properties);

                        //
                        // Remove properties from the shared property set that a service explicitly clears.
                        //
                        Dictionary <string, string> allProps = initData.properties.getPropertiesForPrefix("");
                        foreach (string key in allProps.Keys)
                        {
                            if (svcProperties.getProperty(key).Length == 0)
                            {
                                initData.properties.setProperty(key, "");
                            }
                        }

                        //
                        // Add the service properties to the shared communicator properties.
                        //
                        foreach (KeyValuePair <string, string> entry in svcProperties.getPropertiesForPrefix(""))
                        {
                            initData.properties.setProperty(entry.Key, entry.Value);
                        }

                        //
                        // Parse <service>.* command line options (the Ice command line options
                        // were parsed by the call to createProperties above).
                        //
                        service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                    }

                    string facetNamePrefix = "IceBox.SharedCommunicator.";
                    bool   addFacets       = configureAdmin(initData.properties, facetNamePrefix);

                    _sharedCommunicator = Ice.Util.initialize(initData);

                    if (addFacets)
                    {
                        // Add all facets created on shared communicator to the IceBox communicator
                        // but renamed <prefix>.<facet-name>, except for the Process facet which is
                        // never added.
                        foreach (KeyValuePair <string, Ice.Object> p in _sharedCommunicator.findAllAdminFacets())
                        {
                            if (!p.Key.Equals("Process"))
                            {
                                _communicator.addAdminFacet(p.Value, facetNamePrefix + p.Key);
                            }
                        }
                    }
                }

                foreach (StartServiceInfo s in servicesInfo)
                {
                    startService(s.name, s.entryPoint, s.args);
                }

                //
                // We may want to notify external scripts that the services
                // have started. This is done by defining the property:
                //
                // PrintServicesReady=bundleName
                //
                // Where bundleName is whatever you choose to call this set of
                // services. It will be echoed back as "bundleName ready".
                //
                // This must be done after start() has been invoked on the
                // services.
                //
                string bundleName = properties.getProperty("IceBox.PrintServicesReady");
                if (bundleName.Length > 0)
                {
                    Console.Out.WriteLine(bundleName + " ready");
                }

                //
                // Don't move after the adapter activation. This allows
                // applications to wait for the service manager to be
                // reachable before sending a signal to shutdown the
                //
                //
                Ice.Application.shutdownOnInterrupt();

                //
                // Register "this" as a facet to the Admin object and create Admin object
                //
                try
                {
                    _communicator.addAdminFacet(this, "IceBox.ServiceManager");
                    _communicator.getAdmin();
                }
                catch (Ice.ObjectAdapterDeactivatedException)
                {
                    //
                    // Expected if the communicator has been shutdown.
                    //
                }

                //
                // Start request dispatching after we've started the services.
                //
                if (adapter != null)
                {
                    try
                    {
                        adapter.activate();
                    }
                    catch (Ice.ObjectAdapterDeactivatedException)
                    {
                        //
                        // Expected if the communicator has been shutdown.
                        //
                    }
                }

                _communicator.waitForShutdown();
            }
            catch (FailureException ex)
            {
                _logger.error(ex.ToString());
                return(1);
            }
            catch (Exception ex)
            {
                _logger.error("ServiceManager: caught exception:\n" + ex.ToString());
                return(1);
            }
            finally
            {
                //
                // Invoke stop() on the services.
                //
                stopAll();
            }

            return(0);
        }
Example #40
0
        private void startService(string service, string entryPoint, string[] args)
        {
            lock (this)
            {
                //
                // Extract the assembly name and the class name.
                //
                string err    = "ServiceManager: unable to load service '" + entryPoint + "': ";
                int    sepPos = entryPoint.IndexOf(':');
                if (sepPos != -1)
                {
                    const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    if (entryPoint.Length > 3 &&
                        sepPos == 1 &&
                        driveLetters.IndexOf(entryPoint[0]) != -1 &&
                        (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                    {
                        sepPos = entryPoint.IndexOf(':', 3);
                    }
                }
                if (sepPos == -1)
                {
                    FailureException e = new FailureException();
                    e.reason = err + "invalid entry point format";
                    throw e;
                }

                System.Reflection.Assembly serviceAssembly = null;
                string assemblyName = entryPoint.Substring(0, sepPos);
                string className    = entryPoint.Substring(sepPos + 1);

                try
                {
                    //
                    // First try to load the assembly using Assembly.Load, which will succeed
                    // if a fully-qualified name is provided or if a partial name has been qualified
                    // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                    // if a file name is configured or a partial name is configured and DEVPATH is used.
                    //
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                    }
                    catch (System.IO.IOException ex)
                    {
                        try
                        {
                            serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                        }
                        catch (System.IO.IOException)
                        {
                            throw ex;
                        }
                    }
                }
                catch (Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "unable to load assembly: " + assemblyName;
                    throw e;
                }

                //
                // Instantiate the class.
                //
                Type c = null;
                try
                {
                    c = serviceAssembly.GetType(className, true);
                }
                catch (Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "GetType failed for '" + className + "'";
                    throw e;
                }

                ServiceInfo info = new ServiceInfo();
                info.name   = service;
                info.status = ServiceStatus.Stopped;
                info.args   = args;

                //
                // If IceBox.UseSharedCommunicator.<name> is defined, create a
                // communicator for the service. The communicator inherits
                // from the shared communicator properties. If it's not
                // defined, add the service properties to the shared
                // commnunicator property set.
                //
                Ice.Communicator communicator;
                if (_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
                {
                    Debug.Assert(_sharedCommunicator != null);
                    communicator = _sharedCommunicator;
                }
                else
                {
                    //
                    // Create the service properties. We use the communicator properties as the default
                    // properties if IceBox.InheritProperties is set.
                    //
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties(service);
                    if (info.args.Length > 0)
                    {
                        //
                        // Create the service properties with the given service arguments. This should
                        // read the service config file if it's specified with --Ice.Config.
                        //
                        initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                        //
                        // Next, parse the service "<service>.*" command line options (the Ice command
                        // line options were parsed by the createProperties above)
                        //
                        info.args = initData.properties.parseCommandLineOptions(service, info.args);
                    }

                    //
                    // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                    // don't set any logger.
                    //
                    if (initData.properties.getProperty("Ice.LogFile").Length == 0)
                    {
                        initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                    }

                    //
                    // If Admin is enabled on the IceBox communicator, for each service that does not set
                    // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then
                    // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>.
                    //
                    string serviceFacetNamePrefix = "IceBox.Service." + service + ".";
                    bool   addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix);

                    //
                    // Remaining command line options are passed to the communicator. This is
                    // necessary for Ice plug-in properties (e.g.: IceSSL).
                    //
                    info.communicator = Ice.Util.initialize(ref info.args, initData);
                    communicator      = info.communicator;

                    if (addFacets)
                    {
                        // Add all facets created on the service communicator to the IceBox communicator
                        // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet
                        // which is never added
                        foreach (KeyValuePair <string, Ice.Object> p in communicator.findAllAdminFacets())
                        {
                            if (!p.Key.Equals("Process"))
                            {
                                _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key);
                            }
                        }
                    }
                }

                try
                {
                    //
                    // Instantiate the service.
                    //
                    try
                    {
                        //
                        // If the service class provides a constructor that accepts an Ice.Communicator argument,
                        // use that in preference to the default constructor.
                        //
                        Type[] parameterTypes = new Type[1];
                        parameterTypes[0] = typeof(Ice.Communicator);
                        System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                        if (ci != null)
                        {
                            try
                            {
                                object[] parameters = new object[1];
                                parameters[0] = _communicator;
                                info.service  = (Service)ci.Invoke(parameters);
                            }
                            catch (MethodAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                                throw e;
                            }
                        }
                        else
                        {
                            //
                            // Fall back to the default constructor.
                            //
                            try
                            {
                                info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                                if (info.service == null)
                                {
                                    FailureException e = new FailureException();
                                    e.reason = err + "no default constructor for '" + className + "'";
                                    throw e;
                                }
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unauthorized access to default service constructor for " + className;
                                throw e;
                            }
                        }
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (InvalidCastException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "service does not implement IceBox.Service";
                        throw e;
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        if (ex.InnerException is FailureException)
                        {
                            throw ex.InnerException;
                        }
                        else
                        {
                            FailureException e = new FailureException(ex.InnerException);
                            e.reason = err + "exception in service constructor for " + className;
                            throw e;
                        }
                    }
                    catch (Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "exception in service constructor " + className;
                        throw e;
                    }


                    try
                    {
                        info.service.start(service, communicator, info.args);
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = "exception while starting service " + service;
                        throw e;
                    }

                    info.status = ServiceStatus.Started;
                    _services.Add(info);
                }
                catch (Exception)
                {
                    if (info.communicator != null)
                    {
                        destroyServiceCommunicator(service, info.communicator);
                    }

                    throw;
                }
            }
        }
Example #41
0
        public int run()
        {
            try
            {
            Ice.Properties properties = _communicator.getProperties();

            //
            // Create an object adapter. Services probably should NOT share
            // this object adapter, as the endpoint(s) for this object adapter
            // will most likely need to be firewalled for security reasons.
            //
            Ice.ObjectAdapter adapter = null;
            if(properties.getProperty("IceBox.ServiceManager.Endpoints").Length != 0)
            {
                adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                Ice.Identity identity = new Ice.Identity();
                identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                identity.name = "ServiceManager";
                adapter.add(this, identity);
            }

            //
            // Parse the property set with the prefix "IceBox.Service.". These
            // properties should have the following format:
            //
            // IceBox.Service.Foo=Package.Foo [args]
            //
            // We parse the service properties specified in IceBox.LoadOrder
            // first, then the ones from remaining services.
            //
            string prefix = "IceBox.Service.";
            Dictionary<string, string> services = properties.getPropertiesForPrefix(prefix);
            string[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
            List<StartServiceInfo> servicesInfo = new List<StartServiceInfo>();
            for(int i = 0; i < loadOrder.Length; ++i)
            {
                if(loadOrder[i].Length > 0)
                {
                    string key = prefix + loadOrder[i];
                    string value = services[key];
                    if(value == null)
                    {
                        FailureException ex = new FailureException();
                        ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
                        throw ex;
                    }
                    servicesInfo.Add(new StartServiceInfo(loadOrder[i], value, _argv));
                    services.Remove(key);
                }
            }
            foreach(KeyValuePair<string, string> entry in services)
            {
                string name = entry.Key.Substring(prefix.Length);
                string value = entry.Value;
                servicesInfo.Add(new StartServiceInfo(name, value, _argv));
            }

            //
            // Check if some services are using the shared communicator in which
            // case we create the shared communicator now with a property set which
            // is the union of all the service properties (services which are using
            // the shared communicator).
            //
            if(properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").Count > 0)
            {
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = createServiceProperties("SharedCommunicator");
                foreach(StartServiceInfo service in servicesInfo)
                {
                    if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                    {
                        continue;
                    }

                    //
                    // Load the service properties using the shared communicator properties as
                    // the default properties.
                    //
                    Ice.Properties svcProperties = Ice.Util.createProperties(ref service.args, initData.properties);

                    //
                    // Erase properties from the shared communicator which don't exist in the
                    // service properties (which include the shared communicator properties
                    // overriden by the service properties).
                    //
                    Dictionary<string, string> allProps = initData.properties.getPropertiesForPrefix("");
                    foreach(string key in allProps.Keys)
                    {
                        if(svcProperties.getProperty(key).Length == 0)
                        {
                            initData.properties.setProperty(key, "");
                        }
                    }

                    //
                    // Add the service properties to the shared communicator properties.
                    //
                    foreach(KeyValuePair<string, string> entry in svcProperties.getPropertiesForPrefix(""))
                    {
                        initData.properties.setProperty(entry.Key, entry.Value);
                    }

                    //
                    // Parse <service>.* command line options (the Ice command line options
                    // were parsed by the createProperties above)
                    //
                    service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                }
                _sharedCommunicator = Ice.Util.initialize(initData);
            }

            foreach(StartServiceInfo s in servicesInfo)
            {
                startService(s.name, s.entryPoint, s.args);
            }

            //
            // We may want to notify external scripts that the services
            // have started. This is done by defining the property:
            //
            // PrintServicesReady=bundleName
            //
            // Where bundleName is whatever you choose to call this set of
            // services. It will be echoed back as "bundleName ready".
            //
            // This must be done after start() has been invoked on the
            // services.
            //
            string bundleName = properties.getProperty("IceBox.PrintServicesReady");
            if(bundleName.Length > 0)
            {
                Console.Out.WriteLine(bundleName + " ready");
            }

            //
            // Don't move after the adapter activation. This allows
            // applications to wait for the service manager to be
            // reachable before sending a signal to shutdown the
            //
            //
            Ice.Application.shutdownOnInterrupt();

            //
            // Register "this" as a facet to the Admin object and create Admin object
            //
            try
            {
                _communicator.addAdminFacet(this, "IceBox.ServiceManager");

                //
                // Add a Properties facet for each service
                //
                foreach(ServiceInfo info in _services)
                {
                    Ice.Communicator communicator = info.communicator != null ? info.communicator : _sharedCommunicator;
                    _communicator.addAdminFacet(new PropertiesAdminI(communicator.getProperties()),
                                                "IceBox.Service." + info.name + ".Properties");
                }

                _communicator.getAdmin();
            }
            catch(Ice.ObjectAdapterDeactivatedException)
            {
                //
                // Expected if the communicator has been shutdown.
                //
            }

            //
            // Start request dispatching after we've started the services.
            //
            if(adapter != null)
            {
                try
                {
                    adapter.activate();
                }
                catch(Ice.ObjectAdapterDeactivatedException)
                {
                    //
                    // Expected if the communicator has been shutdown.
                    //
                }
            }

            _communicator.waitForShutdown();
            // XXX:
            //Ice.Application.defaultInterrupt();

            //
            // Invoke stop() on the services.
            //
            stopAll();
            }
            catch(FailureException ex)
            {
            _logger.error(ex.ToString());
            stopAll();
            return 1;
            }
            catch(Exception ex)
            {
            _logger.error("ServiceManager: caught exception:\n" + ex.ToString());
            stopAll();
            return 1;
            }

            return 0;
        }
Example #42
0
 public override bool Initialize()
 {
     Ice.Communicator com = null;
     try
     {
         Ice.Properties prop = Ice.Util.createProperties();
         prop.setProperty("Ice.Default.Locator", "IGServerControllerIceGrid/Locator:default -t 5000 -h " + m_endPoint.Address.ToString() + " -p " + m_endPoint.Port.ToString());
         Ice.InitializationData initData = new Ice.InitializationData();
         initData.properties = prop;
         com = Ice.Util.initialize(initData);
         m_serverControllerClient = IGServerControllerIcePrxHelper.checkedCast(com.stringToProxy("serverController"));
     }
     catch (Ice.Exception)
     {
         IGServerManager.Instance.AppendError(string.Format("couldn't find a `::IGServerController::IGServerControllerIce' object for {0}", m_endPoint.Address.ToString()));
         return false;
     }
     finally
     {
         if (m_serverControllerClient == null)
         {
             IGServerManager.Instance.AppendError(string.Format("An exception was thrown while attempting to connect to: {0}", m_endPoint.Address.ToString()));
         }
     }
     return true;
 }
Example #43
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var manager = Test.ServerManagerPrxHelper.checkedCast(
                    communicator.stringToProxy("ServerManager :" + helper.getTestEndpoint(0)));

                test(manager != null);
                var locator = Test.TestLocatorPrxHelper.uncheckedCast(communicator.getDefaultLocator());

                test(locator != null);
                var registry = Test.TestLocatorRegistryPrxHelper.checkedCast(locator.getRegistry());

                test(registry != null);

                var output = helper.getWriter();

                output.Write("testing stringToProxy... ");
                output.Flush();
                Ice.ObjectPrx @base = communicator.stringToProxy("test @ TestAdapter");
                Ice.ObjectPrx base2 = communicator.stringToProxy("test @ TestAdapter");
                Ice.ObjectPrx base3 = communicator.stringToProxy("test");
                Ice.ObjectPrx base4 = communicator.stringToProxy("ServerManager");
                Ice.ObjectPrx base5 = communicator.stringToProxy("test2");
                Ice.ObjectPrx base6 = communicator.stringToProxy("test @ ReplicatedAdapter");
                output.WriteLine("ok");

                output.Write("testing ice_locator and ice_getLocator... ");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), communicator.getDefaultLocator()) == 0);
                Ice.LocatorPrx anotherLocator =
                    Ice.LocatorPrxHelper.uncheckedCast(communicator.stringToProxy("anotherLocator"));
                @base = @base.ice_locator(anotherLocator);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), anotherLocator) == 0);
                communicator.setDefaultLocator(null);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(@base.ice_getLocator() == null);
                @base = @base.ice_locator(anotherLocator);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), anotherLocator) == 0);
                communicator.setDefaultLocator(locator);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), communicator.getDefaultLocator()) == 0);

                //
                // We also test ice_router/ice_getRouter(perhaps we should add a
                // test/Ice/router test?)
                //
                test(@base.ice_getRouter() == null);
                Ice.RouterPrx anotherRouter =
                    Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("anotherRouter"));
                @base = @base.ice_router(anotherRouter);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getRouter(), anotherRouter) == 0);
                Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("dummyrouter"));
                communicator.setDefaultRouter(router);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getRouter(), communicator.getDefaultRouter()) == 0);
                communicator.setDefaultRouter(null);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(@base.ice_getRouter() == null);
                output.WriteLine("ok");

                output.Write("starting server... ");
                output.Flush();
                manager.startServer();
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                var obj = Test.TestIntfPrxHelper.checkedCast(@base);

                test(obj != null);
                var obj2 = Test.TestIntfPrxHelper.checkedCast(base2);

                test(obj2 != null);
                var obj3 = Test.TestIntfPrxHelper.checkedCast(base3);

                test(obj3 != null);
                var obj4 = Test.ServerManagerPrxHelper.checkedCast(base4);

                test(obj4 != null);
                var obj5 = Test.TestIntfPrxHelper.checkedCast(base5);

                test(obj5 != null);
                var obj6 = Test.TestIntfPrxHelper.checkedCast(base6);

                test(obj6 != null);
                output.WriteLine("ok");

                output.Write("testing id@AdapterId indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing id@ReplicaGroupId indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj6.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing identity indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj5 = Test.TestIntfPrxHelper.checkedCast(base5);
                    obj5.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing proxy with unknown identity... ");
                output.Flush();
                try
                {
                    @base = communicator.stringToProxy("unknown/unknown");
                    @base.ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject.Equals("object"));
                    test(ex.id.Equals("unknown/unknown"));
                }
                output.WriteLine("ok");

                output.Write("testing proxy with unknown adapter... ");
                output.Flush();
                try
                {
                    @base = communicator.stringToProxy("test @ TestAdapterUnknown");
                    @base.ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject.Equals("object adapter"));
                    test(ex.id.Equals("TestAdapterUnknown"));
                }
                output.WriteLine("ok");

                output.Write("testing locator cache timeout... ");
                output.Flush();

                Ice.ObjectPrx basencc = communicator.stringToProxy("test@TestAdapter").ice_connectionCached(false);
                int           count   = locator.getRequestCount();

                basencc.ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                test(++count == locator.getRequestCount());
                basencc.ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                test(++count == locator.getRequestCount());
                basencc.ice_locatorCacheTimeout(2).ice_ping(); // 2s timeout.
                test(count == locator.getRequestCount());
                System.Threading.Thread.Sleep(1300);           // 1300ms
                basencc.ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                test(++count == locator.getRequestCount());

                communicator.stringToProxy("test").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                count += 2;
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_locatorCacheTimeout(2).ice_ping(); // 2s timeout
                test(count == locator.getRequestCount());
                System.Threading.Thread.Sleep(1300);                                      // 1300ms
                communicator.stringToProxy("test").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout
                count += 2;
                test(count == locator.getRequestCount());

                communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(-1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_locatorCacheTimeout(-1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test@TestAdapter").ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_ping();
                test(count == locator.getRequestCount());

                test(communicator.stringToProxy("test").ice_locatorCacheTimeout(99).ice_getLocatorCacheTimeout() == 99);

                output.WriteLine("ok");

                output.Write("testing proxy from server... ");
                output.Flush();
                obj = Test.TestIntfPrxHelper.checkedCast(communicator.stringToProxy("test@TestAdapter"));
                var hello = obj.getHello();

                test(hello.ice_getAdapterId().Equals("TestAdapter"));
                hello.sayHello();
                hello = obj.getReplicatedHello();
                test(hello.ice_getAdapterId().Equals("ReplicatedAdapter"));
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing locator request queuing... ");
                output.Flush();
                hello = (Test.HelloPrx)obj.getReplicatedHello().ice_locatorCacheTimeout(0).ice_connectionCached(false);
                count = locator.getRequestCount();
                hello.ice_ping();
                test(++count == locator.getRequestCount());
                List <Ice.AsyncResult <Test.Callback_Hello_sayHello> > results =
                    new List <Ice.AsyncResult <Test.Callback_Hello_sayHello> >();

                for (int i = 0; i < 1000; i++)
                {
                    Ice.AsyncResult <Test.Callback_Hello_sayHello> result = hello.begin_sayHello().
                                                                            whenCompleted(
                        () =>
                    {
                    },
                        (Ice.Exception ex) =>
                    {
                        test(false);
                    });
                    results.Add(result);
                }
                foreach (Ice.AsyncResult <Test.Callback_Hello_sayHello> result in results)
                {
                    result.waitForCompleted();
                }
                results.Clear();
                test(locator.getRequestCount() > count && locator.getRequestCount() < count + 999);
                if (locator.getRequestCount() > count + 800)
                {
                    output.Write("queuing = " + (locator.getRequestCount() - count));
                }
                count = locator.getRequestCount();
                hello = (Test.HelloPrx)hello.ice_adapterId("unknown");
                for (int i = 0; i < 1000; i++)
                {
                    Ice.AsyncResult <Test.Callback_Hello_sayHello> result = hello.begin_sayHello().
                                                                            whenCompleted(
                        () =>
                    {
                        test(false);
                    },
                        (Ice.Exception ex) =>
                    {
                        test(ex is Ice.NotRegisteredException);
                    });
                    results.Add(result);
                }
                foreach (Ice.AsyncResult <Test.Callback_Hello_sayHello> result in results)
                {
                    result.waitForCompleted();
                }
                results.Clear();
                // XXX:
                // Take into account the retries.
                test(locator.getRequestCount() > count && locator.getRequestCount() < count + 1999);
                if (locator.getRequestCount() > count + 800)
                {
                    output.Write("queuing = " + (locator.getRequestCount() - count));
                }
                output.WriteLine("ok");

                output.Write("testing adapter locator cache... ");
                output.Flush();
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject == "object adapter");
                    test(ex.id.Equals("TestAdapter3"));
                }
                registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    registry.setAdapterDirectProxy("TestAdapter3", communicator.stringToProxy("dummy:tcp"));
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_locatorCacheTimeout(0).ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing well-known object locator cache... ");
                output.Flush();
                registry.addObject(communicator.stringToProxy("test3@TestUnknown"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject == "object adapter");
                    test(ex.id.Equals("TestUnknown"));
                }
                registry.addObject(communicator.stringToProxy("test3@TestAdapter4")); // Update
                registry.setAdapterDirectProxy("TestAdapter4", communicator.stringToProxy("dummy:tcp"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.setAdapterDirectProxy("TestAdapter4", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                registry.setAdapterDirectProxy("TestAdapter4", communicator.stringToProxy("dummy:tcp"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                try
                {
                    communicator.stringToProxy("test@TestAdapter4").ice_locatorCacheTimeout(0).ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test@TestAdapter4").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.addObject(communicator.stringToProxy("test3@TestAdapter"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                registry.addObject(communicator.stringToProxy("test4"));
                try
                {
                    communicator.stringToProxy("test4").ice_ping();
                    test(false);
                }
                catch (Ice.NoEndpointException)
                {
                }
                output.WriteLine("ok");

                output.Write("testing locator cache background updates... ");
                output.Flush();
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().ice_clone_();
                    initData.properties.setProperty("Ice.BackgroundLocatorCacheUpdates", "1");
                    Ice.Communicator ic = helper.initialize(initData);

                    registry.setAdapterDirectProxy("TestAdapter5", locator.findAdapterById("TestAdapter"));
                    registry.addObject(communicator.stringToProxy("test3@TestAdapter"));

                    count = locator.getRequestCount();
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(0).ice_ping();             // No locator cache.
                    count += 3;
                    test(count == locator.getRequestCount());
                    registry.setAdapterDirectProxy("TestAdapter5", null);
                    registry.addObject(communicator.stringToProxy("test3:tcp"));
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(10).ice_ping(); // 10s timeout.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(10).ice_ping();             // 10s timeout.
                    test(count == locator.getRequestCount());
                    System.Threading.Thread.Sleep(1200);

                    // The following request should trigger the background
                    // updates but still use the cached endpoints and
                    // therefore succeed.
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping();             // 1s timeout.

                    try
                    {
                        while (true)
                        {
                            ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected to fail once they endpoints have been updated in the background.
                    }
                    try
                    {
                        while (true)
                        {
                            ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected to fail once they endpoints have been updated in the background.
                    }
                    ic.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing proxy from server after shutdown... ");
                output.Flush();
                hello = obj.getReplicatedHello();
                obj.shutdown();
                manager.startServer();
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing object migration... ");
                output.Flush();
                hello = Test.HelloPrxHelper.checkedCast(communicator.stringToProxy("hello"));
                obj.migrateHello();
                hello.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                hello.sayHello();
                obj.migrateHello();
                hello.sayHello();
                obj.migrateHello();
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing locator encoding resolution... ");
                output.Flush();
                hello = Test.HelloPrxHelper.checkedCast(communicator.stringToProxy("hello"));
                count = locator.getRequestCount();
                communicator.stringToProxy("test@TestAdapter").ice_encodingVersion(Ice.Util.Encoding_1_1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test@TestAdapter10").ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping();
                test(++count == locator.getRequestCount());
                communicator.stringToProxy("test -e 1.0@TestAdapter10-2").ice_ping();
                test(++count == locator.getRequestCount());
                output.WriteLine("ok");

                output.Write("shutdown server... ");
                output.Flush();
                obj.shutdown();
                output.WriteLine("ok");

                output.Write("testing whether server is gone... ");
                output.Flush();
                try
                {
                    obj2.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    obj3.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    obj5.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                output.WriteLine("ok");

                output.Write("testing indirect proxies to collocated objects... ");
                output.Flush();

                //
                // Set up test for calling a collocated object through an
                // indirect, adapterless reference.
                //
                Ice.Properties properties = communicator.getProperties();
                properties.setProperty("Ice.PrintAdapterReady", "0");
                Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("Hello", "tcp -h *");
                adapter.setLocator(locator);

                Ice.Identity id = new Ice.Identity();
                id.name = Guid.NewGuid().ToString();
                registry.addObject(adapter.add(new HelloI(), id));
                adapter.activate();

                var helloPrx = Test.HelloPrxHelper.checkedCast(
                    communicator.stringToProxy("\"" + communicator.identityToString(id) + "\""));

                test(helloPrx.ice_getConnection() == null);

                adapter.deactivate();
                output.WriteLine("ok");

                output.Write("shutdown server manager... ");
                output.Flush();
                manager.shutdown();
                output.WriteLine("ok");
            }
Example #44
0
 public Ice.Communicator initialize(ref string[] args)
 {
     Ice.InitializationData initData = new Ice.InitializationData();
     initData.properties = createTestProperties(ref args);
     return(initialize(initData));
 }
Example #45
0
    doMain(string[] args, Ice.InitializationData initData, out int status)
    {
        //
        // Reset internal state variables from Ice.Application. The
        // remainder are reset at the end of this method.
        //
        iceCallbackInProgress = false;
        iceDestroyed = false;
        iceInterrupted = false;

        bool restart = false;
        status = 0;

        try
        {
            iceCommunicator = Ice.Util.initialize(ref args, initData);

            _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter());
            if(_router == null)
            {
                Ice.Util.getProcessLogger().error(iceAppName + ": no Glacier2 router configured");
                status = 1;
            }
            else
            {
                //
                // The default is to destroy when a signal is received.
                //
                if(iceSignalPolicy == Ice.SignalPolicy.HandleSignals)
                {
                    destroyOnInterrupt();
                }

                //
                // If createSession throws, we're done.
                //
                try
                {
                    _session = createSession();
                    _createdSession = true;
                }
                catch(Ice.LocalException ex)
                {
                    Ice.Util.getProcessLogger().error(ex.ToString());
                    status = 1;
                }

                if(_createdSession)
                {
                    int acmTimeout = 0;
                    try
                    {
                        acmTimeout = _router.getACMTimeout();
                    }
                    catch(Ice.OperationNotExistException)
                    {
                    }
                    if(acmTimeout <= 0)
                    {
                        acmTimeout = (int)_router.getSessionTimeout();
                    }
                    if(acmTimeout > 0)
                    {
                        Ice.Connection connection = _router.ice_getCachedConnection();
                        Debug.Assert(connection != null);
                        connection.setACM((int)acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways);
                        connection.setCloseCallback(_ => sessionDestroyed());
                    }
                    _category = _router.getCategoryForClient();
                    status = runWithSession(args);
                }
            }
        }
        //
        // We want to restart on those exceptions that indicate a
        // break down in communications, but not those exceptions that
        // indicate a programming logic error (i.e., marshal, protocol
        // failure, etc).
        //
        catch(RestartSessionException)
        {
            restart = true;
        }
        catch(Ice.ConnectionRefusedException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
        }
        catch(Ice.ConnectionLostException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
        }
        catch(Ice.UnknownLocalException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
        }
        catch(Ice.RequestFailedException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
        }
        catch(Ice.TimeoutException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
        }
        catch(Ice.LocalException ex)
        {
            Ice.Util.getProcessLogger().error(ex.ToString());
            status = 1;
        }
        catch(System.Exception ex)
        {
            Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
            status = 1;
        }

        //
        // Don't want any new interrupt. And at this point
        // (post-run), it would not make sense to release a held
        // signal to run shutdown or destroy.
        //
        if(iceSignalPolicy == Ice.SignalPolicy.HandleSignals)
        {
            ignoreInterrupt();
        }

        lock(iceMutex)
        {
            while(iceCallbackInProgress)
            {
                System.Threading.Monitor.Wait(iceMutex);
            }

            if(iceDestroyed)
            {
                iceCommunicator = null;
            }
            else
            {
                iceDestroyed = true;
                //
                // And iceCommunicator != null, meaning will be
                // destroyed next, iceDestroyed = true also ensures that
                // any remaining callback won't do anything
                //
            }
        }

        if(_createdSession && _router != null)
        {
            try
            {
                _router.destroySession();
            }
            catch(Ice.ConnectionLostException)
            {
                //
                // Expected if another thread invoked on an object from the session concurrently.
                //
            }
            catch(Glacier2.SessionNotExistException)
            {
                //
                // This can also occur.
                //
            }
            catch(System.Exception ex)
            {
                //
                // Not expected.
                //
                Ice.Util.getProcessLogger().error("unexpected exception when destroying the session:\n" +
                                                  ex.ToString());
            }
            _router = null;
        }

        if(iceCommunicator != null)
        {
            try
            {
                iceCommunicator.destroy();
            }
            catch(Ice.LocalException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                status = 1;
            }
            catch(System.Exception ex)
            {
                Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
                status = 1;
            }
            iceCommunicator = null;
        }

        //
        // Reset internal state. We cannot reset the Application state
        // here, since iceDestroyed must remain true until we re-run
        // this method.
        //
        _adapter = null;
        _router = null;
        _session = null;
        _createdSession = false;
        _category = null;

        return restart;
    }
        public IceManager(string adapterName, string host, int port, bool catchSignals = true)
        {
            IceGridHost = host;
            IceGridPort = port;
            Name = adapterName;

            logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name);

            _ServantIds = new List<Ice.Identity>(); //keep track of servants for emergency cleanup
            string myIP = findLocalIPAddress();
            logger.Info("My IPAddress is: " + myIP);

            //initialize Ice
            Ice.Properties prop = Ice.Util.createProperties();
            prop.setProperty("hms.AdapterId", adapterName);
            prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP);
            prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost);
            prop.setProperty("Ice.ThreadPool.Server.Size", "5");
            prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000");
            prop.setProperty("Ice.ThreadPool.Client.Size", "5");
            prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000");

            Ice.InitializationData iceidata = new Ice.InitializationData();
            iceidata.properties = prop;
            Communicator = Ice.Util.initialize(iceidata); // could add sys.argv
            try
            {
                _Adapter = Communicator.createObjectAdapter("hms");
                _Adapter.activate();
            }
            catch (Exception ex)
            {
                logger.Fatal("Network error, check configuration: " + ex.Message);
                logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints"));
                logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator"));
                throw (ex); // we are dead anyway
            }
            //Now are we ready to communicate with others
            //getting usefull proxies

            try
            {
                // proxy to icegrid to register our vc devices
                Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query"));
                if (Query == null)
                {
                    logger.Error("invalid ICeGrid proxy");
                }
                // proxy to icestorm to publish events
                EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager"));
                if (EventMgr == null)
                {
                    logger.Error("invalid IceStorm proxy");
                }
                //these 2 objects are only needed to get the IceGrid admin object in order to register
                _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry"));
                updateIceGridAdmin();

            }
            catch (Ice.NotRegisteredException e)
            {
                logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message);
            }
            catch (Exception e)
            {
                logger.Fatal("IceGrid Server not found!!!!!: " + e.Message);
                throw (e);//without yellow page system, there is no need to start
            }
            if (catchSignals)
            {
                setupSignals();
            }
        }
Example #47
0
        doMain(string[] args, Ice.InitializationData initData, out int status)
        {
            //
            // Reset internal state variables from Ice.Application. The
            // remainder are reset at the end of this method.
            //
            callbackInProgress__ = false;
            destroyed__          = false;
            interrupted__        = false;

            bool restart = false;

            status = 0;

            SessionPingThread ping       = null;
            Thread            pingThread = null;

            try
            {
                communicator__ = Ice.Util.initialize(ref args, initData);

                _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter());
                if (_router == null)
                {
                    Ice.Util.getProcessLogger().error(appName__ + ": no Glacier2 router configured");
                    status = 1;
                }
                else
                {
                    //
                    // The default is to destroy when a signal is received.
                    //
                    if (signalPolicy__ == Ice.SignalPolicy.HandleSignals)
                    {
                        destroyOnInterrupt();
                    }

                    //
                    // If createSession throws, we're done.
                    //
                    try
                    {
                        _session        = createSession();
                        _createdSession = true;
                    }
                    catch (Ice.LocalException ex)
                    {
                        Ice.Util.getProcessLogger().error(ex.ToString());
                        status = 1;
                    }

                    if (_createdSession)
                    {
                        long timeout = _router.getSessionTimeout();
                        if (timeout > 0)
                        {
                            ping       = new SessionPingThread(this, _router, (timeout * 1000) / 2);
                            pingThread = new Thread(new ThreadStart(ping.run));
                            pingThread.Start();
                        }
                        _category = _router.getCategoryForClient();
                        status    = runWithSession(args);
                    }
                }
            }
            //
            // We want to restart on those exceptions that indicate a
            // break down in communications, but not those exceptions that
            // indicate a programming logic error (i.e., marshal, protocol
            // failure, etc).
            //
            catch (RestartSessionException)
            {
                restart = true;
            }
            catch (Ice.ConnectionRefusedException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                restart = true;
            }
            catch (Ice.ConnectionLostException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                restart = true;
            }
            catch (Ice.UnknownLocalException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                restart = true;
            }
            catch (Ice.RequestFailedException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                restart = true;
            }
            catch (Ice.TimeoutException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                restart = true;
            }
            catch (Ice.LocalException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                status = 1;
            }
            catch (System.Exception ex)
            {
                Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
                status = 1;
            }

            //
            // Don't want any new interrupt. And at this point
            // (post-run), it would not make sense to release a held
            // signal to run shutdown or destroy.
            //
            if (signalPolicy__ == Ice.SignalPolicy.HandleSignals)
            {
                ignoreInterrupt();
            }

            mutex__.Lock();
            try
            {
                while (callbackInProgress__)
                {
                    mutex__.Wait();
                }

                if (destroyed__)
                {
                    communicator__ = null;
                }
                else
                {
                    destroyed__ = true;
                    //
                    // And communicator__ != null, meaning will be
                    // destroyed next, destroyed__ = true also ensures that
                    // any remaining callback won't do anything
                    //
                }
            }
            finally
            {
                mutex__.Unlock();
            }

            if (ping != null)
            {
                ping.done();
                ping = null;
                while (true)
                {
#if COMPACT
                    pingThread.Join();
                    break;
#else
                    try
                    {
                        pingThread.Join();
                        break;
                    }
                    catch (ThreadInterruptedException)
                    {
                    }
#endif
                }
                pingThread = null;
            }

            if (_createdSession && _router != null)
            {
                try
                {
                    _router.destroySession();
                }
                catch (Ice.ConnectionLostException)
                {
                    //
                    // Expected if another thread invoked on an object from the session concurrently.
                    //
                }
                catch (Glacier2.SessionNotExistException)
                {
                    //
                    // This can also occur.
                    //
                }
                catch (System.Exception ex)
                {
                    //
                    // Not expected.
                    //
                    Ice.Util.getProcessLogger().error("unexpected exception when destroying the session:\n" +
                                                      ex.ToString());
                }
                _router = null;
            }

            if (communicator__ != null)
            {
                try
                {
                    communicator__.destroy();
                }
                catch (Ice.LocalException ex)
                {
                    Ice.Util.getProcessLogger().error(ex.ToString());
                    status = 1;
                }
                catch (System.Exception ex)
                {
                    Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
                    status = 1;
                }
                communicator__ = null;
            }

            //
            // Reset internal state. We cannot reset the Application state
            // here, since destroyed__ must remain true until we re-run
            // this method.
            //
            _adapter        = null;
            _router         = null;
            _session        = null;
            _createdSession = false;
            _category       = null;

            return(restart);
        }
Example #48
0
File: TestApp.cs Project: zmyer/ice
 //
 // This runmain() must be called by the global main(). runmain()
 // initializes the Communicator, calls run(), and destroys
 // the Communicator upon return from run(). It thereby handles
 // all exceptions properly, i.e., error messages are printed
 // if exceptions propagate to main(), and the Communicator is
 // always destroyed, regardless of exceptions.
 //
 public int runmain(string[] args)
 {
     Ice.InitializationData initData = getInitData(ref args);
     return(runmain(args, initData));
 }