예제 #1
0
    def test_disconnect(self):
        """Test that the disconnect method works correctly."""

        with NetworkOEFNode():
            agent_1 = OEFAgent("disconnect", "127.0.0.1", 3333)
            assert not agent_1._oef_proxy.is_connected()
            agent_1.connect()
            assert agent_1._oef_proxy.is_connected()
            agent_1.disconnect()
            assert not agent_1._oef_proxy.is_connected()
예제 #2
0
class OEFHealthCheck(object):
    """A health check class."""
    def __init__(
        self,
        oef_addr: str,
        oef_port: int,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ):
        """
        Initialize.

        :param oef_addr: IP address of the OEF node.
        :param oef_port: Port of the OEF node.
        """
        self.oef_addr = oef_addr
        self.oef_port = oef_port

        self._result = False
        self._stop = False
        self._core = AsyncioCore()
        self.agent = OEFAgent("check",
                              core=self._core,
                              oef_addr=self.oef_addr,
                              oef_port=self.oef_port)
        self.agent.on_connect_success = self.on_connect_ok
        self.agent.on_connection_terminated = self.on_connect_terminated
        self.agent.on_connect_failed = self.exception_handler

    def exception_handler(self, url=None, ex=None):
        """Handle exception during a connection attempt."""
        print("An error occurred. Exception: {}".format(ex))
        self._stop = True

    def on_connect_ok(self, url=None):
        """Handle a successful connection."""
        print("Connection OK!")
        self._result = True
        self._stop = True

    def on_connect_terminated(self, url=None):
        """Handle a connection failure."""
        print("Connection terminated.")
        self._stop = True

    def run(self) -> bool:
        """
        Run the check, asynchronously.

        :return: True if the check is successful, False otherwise.
        """
        self._result = False
        self._stop = False

        def stop_connection_attempt(self):
            if self.agent.state == "connecting":
                self.agent.state = "failed"

        t = Timer(1.5, stop_connection_attempt, args=(self, ))

        try:
            print("Connecting to {}:{}...".format(self.oef_addr,
                                                  self.oef_port))
            self._core.run_threaded()

            t.start()
            self._result = self.agent.connect()
            self._stop = True

            if self._result:
                print("Connection established. Tearing down connection...")
                self.agent.disconnect()
                t.cancel()
            else:
                print("A problem occurred. Exiting...")
            return self._result

        except Exception as e:
            print(str(e))
            return self._result
        finally:
            t.join(1.0)
            self.agent.stop()
            self.agent.disconnect()
            self._core.stop()
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ------------------------------------------------------------------------------
"""
A short script that show how an agent can register/unregister to the OEF.
"""
from oef.schema import Description

from oef.agents import OEFAgent

if __name__ == '__main__':
    agent = OEFAgent("agent_1", oef_addr="127.0.0.1", oef_port=3333)

    agent.connect()
    print("Agent successfully connected.")

    # specify message id to receive any error messages from the OEF Node.
    # look at the 'onOEFError' agent method.
    message_id = 0
    agent.register_agent(message_id, Description({}))
    print("Agent registered to the OEF Node.")

    agent.unregister_agent(message_id + 1)
    print("Agent {} unregistered".format(agent.public_key))

    agent.disconnect()