Ejemplo n.º 1
0
    def test_read_invalid_config(self):
        with open(os.path.join(self.basedir, 'tahoe.cfg'), 'w') as f:
            f.write('[invalid section]\n' 'foo = bar\n')
        with self.assertRaises(UnknownConfigError) as ctx:
            read_config(
                self.basedir,
                "client.port",
            )

        self.assertIn(
            "invalid section",
            str(ctx.exception),
        )
Ejemplo n.º 2
0
 def test_tor_i2p_listeners(self):
     n = EmptyNode()
     n.basedir = self.mktemp()
     n.config_fname = os.path.join(n.basedir, "tahoe.cfg")
     os.mkdir(n.basedir)
     os.mkdir(os.path.join(n.basedir, "private"))
     with open(n.config_fname, "w") as f:
         f.write(BASE_CONFIG)
         f.write("tub.port = listen:i2p,listen:tor\n")
         f.write("tub.location = tcp:example.org:1234\n")
     # we're doing a lot of calling-into-setup-methods here, it might be
     # better to just create a real Node instance, I'm not sure.
     n.config = read_config(n.basedir, "client.port")
     n.check_privacy()
     n.services = []
     i2p_ep = object()
     tor_ep = object()
     n._i2p_provider = mock.Mock()
     n._i2p_provider.get_listener = mock.Mock(return_value=i2p_ep)
     n._tor_provider = mock.Mock()
     n._tor_provider.get_listener = mock.Mock(return_value=tor_ep)
     n.init_connections()
     n.set_tub_options()
     t = FakeTub()
     with mock.patch("allmydata.node.Tub", return_value=t):
         n.create_main_tub()
     self.assertEqual(n._i2p_provider.get_listener.mock_calls, [mock.call()])
     self.assertEqual(n._tor_provider.get_listener.mock_calls, [mock.call()])
     self.assertEqual(t.listening_ports, [i2p_ep, tor_ep])
Ejemplo n.º 3
0
 def test_multiple_ports(self):
     n = EmptyNode()
     n.basedir = self.mktemp()
     n.config_fname = os.path.join(n.basedir, "tahoe.cfg")
     os.mkdir(n.basedir)
     os.mkdir(os.path.join(n.basedir, "private"))
     port1 = iputil.allocate_tcp_port()
     port2 = iputil.allocate_tcp_port()
     port = ("tcp:%d:interface=127.0.0.1,tcp:%d:interface=127.0.0.1" %
             (port1, port2))
     location = "tcp:localhost:%d,tcp:localhost:%d" % (port1, port2)
     with open(n.config_fname, "w") as f:
         f.write(BASE_CONFIG)
         f.write("tub.port = %s\n" % port)
         f.write("tub.location = %s\n" % location)
     # we're doing a lot of calling-into-setup-methods here, it might be
     # better to just create a real Node instance, I'm not sure.
     n.config = read_config(n.basedir, "client.port")
     n.check_privacy()
     n.services = []
     n.create_i2p_provider()
     n.create_tor_provider()
     n.init_connections()
     n.set_tub_options()
     t = FakeTub()
     with mock.patch("allmydata.node.Tub", return_value=t):
         n.create_main_tub()
     self.assertEqual(t.listening_ports, [
         "tcp:%d:interface=127.0.0.1" % port1,
         "tcp:%d:interface=127.0.0.1" % port2
     ])
Ejemplo n.º 4
0
    def test_read_invalid_config(self):
        with open(os.path.join(self.basedir, 'tahoe.cfg'), 'w') as f:
            f.write(
                '[invalid section]\n'
                'foo = bar\n'
            )
        with self.assertRaises(UnknownConfigError) as ctx:
            read_config(
                self.basedir,
                "client.port",
            )

        self.assertIn(
            "invalid section",
            str(ctx.exception),
        )
Ejemplo n.º 5
0
 def test_tor_i2p_listeners(self):
     n = EmptyNode()
     n.basedir = self.mktemp()
     n.config_fname = os.path.join(n.basedir, "tahoe.cfg")
     os.mkdir(n.basedir)
     os.mkdir(os.path.join(n.basedir, "private"))
     with open(n.config_fname, "w") as f:
         f.write(BASE_CONFIG)
         f.write("tub.port = listen:i2p,listen:tor\n")
         f.write("tub.location = tcp:example.org:1234\n")
     # we're doing a lot of calling-into-setup-methods here, it might be
     # better to just create a real Node instance, I'm not sure.
     n.config = read_config(n.basedir, "client.port")
     n.check_privacy()
     n.services = []
     i2p_ep = object()
     tor_ep = object()
     n._i2p_provider = mock.Mock()
     n._i2p_provider.get_listener = mock.Mock(return_value=i2p_ep)
     n._tor_provider = mock.Mock()
     n._tor_provider.get_listener = mock.Mock(return_value=tor_ep)
     n.init_connections()
     n.set_tub_options()
     t = FakeTub()
     with mock.patch("allmydata.node.Tub", return_value=t):
         n.create_main_tub()
     self.assertEqual(n._i2p_provider.get_listener.mock_calls,
                      [mock.call()])
     self.assertEqual(n._tor_provider.get_listener.mock_calls,
                      [mock.call()])
     self.assertEqual(t.listening_ports, [i2p_ep, tor_ep])
Ejemplo n.º 6
0
def invite(options):
    if options.parent['node-directory']:
        basedir = argv_to_abspath(options.parent['node-directory'])
    else:
        basedir = get_default_nodedir()
    config = read_config(basedir, u"")
    out = options.stdout
    err = options.stderr

    try:
        introducer_furl = get_introducer_furl(basedir, config)
    except Exception as e:
        print("Can't find introducer FURL for node '{}': {}".format(
            basedir, str(e)),
              file=err)
        raise SystemExit(1)

    nick = options['nick']

    remote_config = {
        "shares-needed":
        options["shares-needed"] or config.get('client', 'shares.needed'),
        "shares-total":
        options["shares-total"] or config.get('client', 'shares.total'),
        "shares-happy":
        options["shares-happy"] or config.get('client', 'shares.happy'),
        "nickname":
        nick,
        "introducer":
        introducer_furl,
    }

    yield _send_config_via_wormhole(options, remote_config)
    print("Completed successfully", file=out)
Ejemplo n.º 7
0
    def test_config_items(self):
        """
        All items in a config section can be retrieved.
        """
        basedir = u"test_node/test_config_items"
        create_node_dir(basedir, "testing")

        with open(os.path.join(basedir, 'tahoe.cfg'), 'wt') as f:
            f.write(
                dedent("""
                [node]
                nickname = foo
                timeout.disconnect = 12
                """))
        config = read_config(basedir, "portnum")
        self.assertEqual(
            config.items("node"),
            [
                ("nickname", "foo"),
                ("timeout.disconnect", "12"),
            ],
        )
        self.assertEqual(
            config.items("node", [("unnecessary", "default")]),
            [
                ("nickname", "foo"),
                ("timeout.disconnect", "12"),
            ],
        )
Ejemplo n.º 8
0
 def test_multiple_ports(self):
     n = EmptyNode()
     n.basedir = self.mktemp()
     n.config_fname = os.path.join(n.basedir, "tahoe.cfg")
     os.mkdir(n.basedir)
     os.mkdir(os.path.join(n.basedir, "private"))
     port1 = iputil.allocate_tcp_port()
     port2 = iputil.allocate_tcp_port()
     port = ("tcp:%d:interface=127.0.0.1,tcp:%d:interface=127.0.0.1" %
             (port1, port2))
     location = "tcp:localhost:%d,tcp:localhost:%d" % (port1, port2)
     with open(n.config_fname, "w") as f:
         f.write(BASE_CONFIG)
         f.write("tub.port = %s\n" % port)
         f.write("tub.location = %s\n" % location)
     # we're doing a lot of calling-into-setup-methods here, it might be
     # better to just create a real Node instance, I'm not sure.
     n.config = read_config(n.basedir, "client.port")
     n.check_privacy()
     n.services = []
     n.create_i2p_provider()
     n.create_tor_provider()
     n.init_connections()
     n.set_tub_options()
     t = FakeTub()
     with mock.patch("allmydata.node.Tub", return_value=t):
         n.create_main_tub()
     self.assertEqual(t.listening_ports,
                      ["tcp:%d:interface=127.0.0.1" % port1,
                       "tcp:%d:interface=127.0.0.1" % port2])
Ejemplo n.º 9
0
def create_client(basedir=u"."):
    from allmydata.node import read_config
    config = read_config(basedir,
                         u"client.port",
                         _valid_config_sections=_valid_config_sections)
    #defer.returnValue(
    return _Client(config, basedir=basedir)
Ejemplo n.º 10
0
def create_introducer(basedir=u"."):
    from allmydata.node import read_config
    config = read_config(basedir,
                         u"client.port",
                         generated_files=["introducer.furl"])
    config.validate(_valid_config_sections())
    #defer.returnValue(
    return _IntroducerNode(config, basedir=basedir)
Ejemplo n.º 11
0
def create_client(basedir=u"."):
    from allmydata.node import read_config
    config = read_config(basedir, u"client.port", _valid_config_sections=_valid_config_sections)
    #defer.returnValue(
    return _Client(
            config,
            basedir=basedir
        )
Ejemplo n.º 12
0
def create_introducer(basedir=u"."):
    from allmydata.node import read_config
    config = read_config(basedir, u"client.port", generated_files=["introducer.furl"])
    config.validate(_valid_config_sections())
    #defer.returnValue(
    return _IntroducerNode(
            config,
            basedir=basedir
        )
Ejemplo n.º 13
0
    def test_config_required(self):
        """
        Asking for missing (but required) configuration is an error
        """
        basedir = u"test_node/test_config_required"
        config = read_config(basedir, "portnum")

        with self.assertRaises(Exception):
            config.get_config_from_file("it_does_not_exist", required=True)
Ejemplo n.º 14
0
    def test_config_required(self):
        """
        Asking for missing (but required) configuration is an error
        """
        basedir = u"test_node/test_config_required"
        config = read_config(basedir, "portnum")

        with self.assertRaises(Exception):
            config.get_config_from_file("it_does_not_exist", required=True)
Ejemplo n.º 15
0
 def test_set_config_write(self):
     """
     ``_Config.set_config`` persists the configuration change so it can be
     re-loaded later.
     """
     # Let our nonsense config through
     valid_config = ValidConfiguration.everything()
     basedir = FilePath(self.mktemp())
     basedir.makedirs()
     cfg = basedir.child(b"tahoe.cfg")
     cfg.setContent(b"")
     new_config = read_config(basedir.path, "", [], valid_config)
     new_config.set_config("foo", "bar", "value1")
     loaded_config = read_config(basedir.path, "", [], valid_config)
     self.assertEqual(
         loaded_config.get_config("foo", "bar"),
         "value1",
     )
Ejemplo n.º 16
0
    def test_private_config_missing(self):
        """
        a missing config with no default is an error
        """
        basedir = u"test_node/test_private_config_missing"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")

        with self.assertRaises(MissingConfigEntry):
            config.get_or_create_private_config("foo")
Ejemplo n.º 17
0
    def test_private_config_missing(self):
        """
        a missing config with no default is an error
        """
        basedir = u"test_node/test_private_config_missing"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")

        with self.assertRaises(MissingConfigEntry):
            config.get_or_create_private_config("foo")
Ejemplo n.º 18
0
    def test_tahoe_cfg_utf8(self):
        basedir = "test_node/test_tahoe_cfg_utf8"
        fileutil.make_dirs(basedir)
        f = open(os.path.join(basedir, 'tahoe.cfg'), 'wb')
        f.write(u"\uFEFF[node]\n".encode('utf-8'))
        f.write(u"nickname = \u2621\n".encode('utf-8'))
        f.close()

        config = read_config(basedir, "")
        self.failUnlessEqual(config.get_config("node", "nickname"), u"\u2621")
Ejemplo n.º 19
0
    def test_tahoe_cfg_utf8(self):
        basedir = "test_node/test_tahoe_cfg_utf8"
        fileutil.make_dirs(basedir)
        f = open(os.path.join(basedir, 'tahoe.cfg'), 'wt')
        f.write(u"\uFEFF[node]\n".encode('utf-8'))
        f.write(u"nickname = \u2621\n".encode('utf-8'))
        f.close()

        config = read_config(basedir, "")
        self.failUnlessEqual(config.get_config("node", "nickname").decode('utf-8'),
                             u"\u2621")
Ejemplo n.º 20
0
    def test_tahoe_cfg_hash_in_name(self):
        basedir = "test_node/test_cfg_hash_in_name"
        nickname = "Hash#Bang!" # a clever nickname containing a hash
        fileutil.make_dirs(basedir)
        f = open(os.path.join(basedir, 'tahoe.cfg'), 'wt')
        f.write("[node]\n")
        f.write("nickname = %s\n" % (nickname,))
        f.close()

        config = read_config(basedir, "")
        self.failUnless(config.nickname == nickname)
Ejemplo n.º 21
0
    def test_tahoe_cfg_hash_in_name(self):
        basedir = "test_node/test_cfg_hash_in_name"
        nickname = "Hash#Bang!" # a clever nickname containing a hash
        fileutil.make_dirs(basedir)
        f = open(os.path.join(basedir, 'tahoe.cfg'), 'wt')
        f.write("[node]\n")
        f.write("nickname = %s\n" % (nickname,))
        f.close()

        config = read_config(basedir, "")
        self.failUnless(config.nickname == nickname)
Ejemplo n.º 22
0
def read_config(basedir, portnumfile, generated_files=[]):
    """
    Read and validate configuration for a client-style Node. See
    :method:`allmydata.node.read_config` for parameter meanings (the
    only difference here is we pass different validation data)

    :returns: :class:`allmydata.node._Config` instance
    """
    return node.read_config(
        basedir, portnumfile,
        generated_files=generated_files,
        _valid_config_sections=_valid_config_sections,
    )
Ejemplo n.º 23
0
def read_config(basedir, portnumfile, generated_files=[]):
    """
    Read and validate configuration for a client-style Node. See
    :method:`allmydata.node.read_config` for parameter meanings (the
    only difference here is we pass different validation data)

    :returns: :class:`allmydata.node._Config` instance
    """
    return node.read_config(
        basedir, portnumfile,
        generated_files=generated_files,
        _valid_config=_valid_config(),
    )
Ejemplo n.º 24
0
    def test_private_config_unreadable(self):
        """
        Asking for inaccessible private config is an error
        """
        basedir = u"test_node/test_private_config_unreadable"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")
        config.get_or_create_private_config("foo", "contents")
        fname = os.path.join(basedir, "private", "foo")
        os.chmod(fname, 0)

        with self.assertRaises(Exception):
            config.get_or_create_private_config("foo")
Ejemplo n.º 25
0
    def test_private_config_unreadable(self):
        """
        Asking for inaccessible private config is an error
        """
        basedir = u"test_node/test_private_config_unreadable"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")
        config.get_or_create_private_config("foo", "contents")
        fname = os.path.join(basedir, "private", "foo")
        os.chmod(fname, 0)

        with self.assertRaises(Exception):
            config.get_or_create_private_config("foo")
Ejemplo n.º 26
0
    def test_hash_in_furl(self):
        """
        Hashes in furl options are not allowed, resulting in exception.
        """
        basedir = self.mktemp()
        fileutil.make_dirs(basedir)
        with open(os.path.join(basedir, 'tahoe.cfg'), 'wt') as f:
            f.write("[node]\n")
            f.write("log_gatherer.furl = lalal#onohash\n")

        config = read_config(basedir, "")
        with self.assertRaises(UnescapedHashError):
            config.get_config("node", "log_gatherer.furl")
Ejemplo n.º 27
0
    def test_private_config_unreadable_preexisting(self):
        """
        error if reading private config data fails
        """
        basedir = u"test_node/test_private_config_unreadable_preexisting"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")
        fname = os.path.join(basedir, "private", "foo")
        with open(fname, "w") as f:
            f.write("stuff")
        os.chmod(fname, 0)

        with self.assertRaises(Exception):
            config.get_private_config("foo")
Ejemplo n.º 28
0
    def test_private_config_unreadable_preexisting(self):
        """
        error if reading private config data fails
        """
        basedir = u"test_node/test_private_config_unreadable_preexisting"
        create_node_dir(basedir, "testing")
        config = read_config(basedir, "portnum")
        fname = os.path.join(basedir, "private", "foo")
        with open(fname, "w") as f:
            f.write("stuff")
        os.chmod(fname, 0)

        with self.assertRaises(Exception):
            config.get_private_config("foo")
Ejemplo n.º 29
0
def create_introducer(basedir=u"."):
    """
    :returns: a Deferred that yields a new _IntroducerNode instance
    """
    try:
        # see https://tahoe-lafs.org/trac/tahoe-lafs/ticket/2946
        from twisted.internet import reactor

        if not os.path.exists(basedir):
            create_node_dir(basedir, INTRODUCER_README)

        config = read_config(
            basedir,
            u"client.port",
            generated_files=["introducer.furl"],
            _valid_config=_valid_config(),
        )

        i2p_provider = create_i2p_provider(reactor, config)
        tor_provider = create_tor_provider(reactor, config)

        default_connection_handlers, foolscap_connection_handlers = create_connection_handlers(
            reactor, config, i2p_provider, tor_provider)
        tub_options = create_tub_options(config)

        # we don't remember these because the Introducer doesn't make
        # outbound connections.
        i2p_provider = None
        tor_provider = None
        main_tub = create_main_tub(
            config,
            tub_options,
            default_connection_handlers,
            foolscap_connection_handlers,
            i2p_provider,
            tor_provider,
        )
        control_tub = create_control_tub()

        node = _IntroducerNode(
            config,
            main_tub,
            control_tub,
            i2p_provider,
            tor_provider,
        )
        return defer.succeed(node)
    except Exception:
        return Failure()
Ejemplo n.º 30
0
    def test_introducer_clients_unloadable(self):
        """
        ``create_introducer_clients`` raises ``EnvironmentError`` if
        ``introducers.yaml`` exists but we can't read it.
        """
        basedir = u"introducer.IntroducerNode.test_introducer_clients_unloadable"
        os.mkdir(basedir)
        os.mkdir(os.path.join(basedir, u"private"))
        yaml_fname = os.path.join(basedir, u"private", u"introducers.yaml")
        with open(yaml_fname, 'w') as f:
            f.write(u'---\n')
        os.chmod(yaml_fname, 0o000)
        self.addCleanup(lambda: os.chmod(yaml_fname, 0o700))

        config = read_config(basedir, "portnum")
        with self.assertRaises(EnvironmentError):
            create_introducer_clients(config, Tub())
Ejemplo n.º 31
0
    def test_config_items_missing_section(self):
        """
        If a default is given for a missing section, the default is used.

        Lacking both default and section, an error is raised.
        """
        basedir = self.mktemp()
        create_node_dir(basedir, "testing")

        with open(os.path.join(basedir, 'tahoe.cfg'), 'wt') as f:
            f.write("")

        config = read_config(basedir, "portnum")
        with self.assertRaises(configparser.NoSectionError):
            config.items("nosuch")
        default = [("hello", "world")]
        self.assertEqual(config.items("nosuch", default), default)
Ejemplo n.º 32
0
    def test_missing_config_item(self):
        """
        If a config item is missing:

        1. Given a default, return default.
        2. Otherwise, raise MissingConfigEntry.
        """
        basedir = self.mktemp()
        fileutil.make_dirs(basedir)
        with open(os.path.join(basedir, 'tahoe.cfg'), 'wt') as f:
            f.write("[node]\n")
        config = read_config(basedir, "")

        self.assertEquals(
            config.get_config("node", "log_gatherer.furl", "def"), "def")
        with self.assertRaises(MissingConfigEntry):
            config.get_config("node", "log_gatherer.furl")
Ejemplo n.º 33
0
def create_introducer(basedir=u"."):
    """
    :returns: a Deferred that yields a new _IntroducerNode instance
    """
    try:
        # see https://tahoe-lafs.org/trac/tahoe-lafs/ticket/2946
        from twisted.internet import reactor

        if not os.path.exists(basedir):
            create_node_dir(basedir, INTRODUCER_README)

        config = read_config(
            basedir, u"client.port",
            generated_files=["introducer.furl"],
            _valid_config_sections=_valid_config_sections,
        )

        i2p_provider = create_i2p_provider(reactor, config)
        tor_provider = create_tor_provider(reactor, config)

        default_connection_handlers, foolscap_connection_handlers = create_connection_handlers(reactor, config, i2p_provider, tor_provider)
        tub_options = create_tub_options(config)

        # we don't remember these because the Introducer doesn't make
        # outbound connections.
        i2p_provider = None
        tor_provider = None
        main_tub = create_main_tub(
            config, tub_options, default_connection_handlers,
            foolscap_connection_handlers, i2p_provider, tor_provider,
        )
        control_tub = create_control_tub()

        node = _IntroducerNode(
            config,
            main_tub,
            control_tub,
            i2p_provider,
            tor_provider,
        )
        return defer.succeed(node)
    except Exception:
        return Failure()
Ejemplo n.º 34
0
        def start():
            node_to_instance = {
                u"client":
                lambda: maybeDeferred(
                    namedAny("allmydata.client.create_client"), self.basedir),
                u"introducer":
                lambda: maybeDeferred(
                    namedAny("allmydata.introducer.server.create_introducer"),
                    self.basedir),
                u"stats-gatherer":
                lambda: maybeDeferred(namedAny(
                    "allmydata.stats.StatsGathererService"),
                                      read_config(self.basedir, None),
                                      self.basedir,
                                      verbose=True),
                u"key-generator":
                key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            def handle_config_error(fail):
                if fail.check(UnknownConfigError):
                    self.stderr.write("\nConfiguration error:\n{}\n\n".format(
                        fail.value))
                else:
                    self.stderr.write("\nUnknown error\n")
                    fail.printTraceback(self.stderr)
                reactor.stop()

            d = service_factory()

            def created(srv):
                srv.setServiceParent(self.parent)

            d.addCallback(created)
            d.addErrback(handle_config_error)
            d.addBoth(self._call_hook, 'running')
            return d
Ejemplo n.º 35
0
    def match(self, other):
        """
        Match a private key which is the same as the private key in the node at
        ``self.basedir``.

        :param other: A signing key (aka "private key") from
            ``allmydata.crypto.ed25519``.  This is the key to check against
            the node's key.

        :return Mismatch: If the keys don't match.
        """
        config = read_config(self.basedir, u"tub.port")
        privkey_bytes = config.get_private_config("node.privkey")
        private_key = ed25519.signing_keypair_from_string(privkey_bytes)[0]
        signature = ed25519.sign_data(private_key, b"")
        other_public_key = ed25519.verifying_key_from_signing_key(other)
        try:
            ed25519.verify_signature(other_public_key, signature, b"")
        except error.BadSignature:
            return Mismatch("The signature did not verify.")
Ejemplo n.º 36
0
        def start():
            node_to_instance = {
                u"client":
                lambda: namedAny("allmydata.client.create_client")
                (self.basedir),
                u"introducer":
                lambda: namedAny(
                    "allmydata.introducer.server.create_introducer")
                (self.basedir),
                u"stats-gatherer":
                lambda: namedAny("allmydata.stats.StatsGathererService")
                (read_config(self.basedir, None), self.basedir, verbose=True),
                u"key-generator":
                key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            srv = service_factory()
            srv.setServiceParent(self.parent)
Ejemplo n.º 37
0
    def test_introducer_clients_unloadable(self):
        """
        Error if introducers.yaml exists but we can't read it
        """
        basedir = u"introducer.IntroducerNode.test_introducer_clients_unloadable"
        os.mkdir(basedir)
        os.mkdir(os.path.join(basedir, u"private"))
        yaml_fname = os.path.join(basedir, u"private", u"introducers.yaml")
        with open(yaml_fname, 'w') as f:
            f.write(u'---\n')
        os.chmod(yaml_fname, 0o000)
        self.addCleanup(lambda: os.chmod(yaml_fname, 0o700))
        # just mocking the yaml failure, as "yamlutil.safe_load" only
        # returns None on some platforms for unreadable files

        with patch("allmydata.client.yamlutil") as p:
            p.safe_load = Mock(return_value=None)

            fake_tub = Mock()
            config = read_config(basedir, "portnum")

            with self.assertRaises(EnvironmentError):
                create_introducer_clients(config, fake_tub)
Ejemplo n.º 38
0
        def start():
            node_to_instance = {
                u"client": lambda: maybeDeferred(namedAny("allmydata.client.create_client"), self.basedir),
                u"introducer": lambda: maybeDeferred(namedAny("allmydata.introducer.server.create_introducer"), self.basedir),
                u"stats-gatherer": lambda: maybeDeferred(namedAny("allmydata.stats.StatsGathererService"), read_config(self.basedir, None), self.basedir, verbose=True),
                u"key-generator": key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            def handle_config_error(fail):
                fail.trap(UnknownConfigError)
                sys.stderr.write("\nConfiguration error:\n{}\n\n".format(fail.value))
                reactor.stop()
                return

            d = service_factory()

            def created(srv):
                srv.setServiceParent(self.parent)
            d.addCallback(created)
            d.addErrback(handle_config_error)
            d.addBoth(self._call_hook, 'running')
            return d
Ejemplo n.º 39
0
        def start():
            node_to_instance = {
                u"client": lambda: namedAny("allmydata.client.create_client")(self.basedir),
                u"introducer": lambda: namedAny("allmydata.introducer.server.create_introducer")(self.basedir),
                u"stats-gatherer": lambda: namedAny("allmydata.stats.StatsGathererService")(read_config(self.basedir, None), self.basedir, verbose=True),
                u"key-generator": key_generator_removed,
            }

            try:
                service_factory = node_to_instance[self.nodetype]
            except KeyError:
                raise ValueError("unknown nodetype %s" % self.nodetype)

            srv = service_factory()
            srv.setServiceParent(self.parent)
Ejemplo n.º 40
0
    def _try(self, tp, tl, exp):
        log.msg("PortLocation._try:", tp, tl, exp)
        cfg_tubport = {"missing": None,
                       "empty": "",
                       "disabled": "disabled",
                       "endpoint": "tcp:777",
                       }[tp]
        cfg_location = {"missing": None,
                        "empty": "",
                        "disabled": "disabled",
                        "hintstring": "tcp:HOST:888,AUTO",
                        }[tl]

        n = EmptyNode()
        basedir = os.path.join("test_node/portlocation/%s/%s" % (tp, tl))
        fileutil.make_dirs(basedir)
        config = n.config = read_config(basedir, "node.port")
        n._reveal_ip = True

        if exp in ("ERR1", "ERR2", "ERR3", "ERR4"):
            e = self.assertRaises(ValueError, n.get_tub_portlocation,
                                  cfg_tubport, cfg_location)
            if exp == "ERR1":
                self.assertEqual("tub.port must not be empty", str(e))
            elif exp == "ERR2":
                self.assertEqual("tub.location must not be empty", str(e))
            elif exp == "ERR3":
                self.assertEqual("tub.port is disabled, but not tub.location",
                                 str(e))
            elif exp == "ERR4":
                self.assertEqual("tub.location is disabled, but not tub.port",
                                 str(e))
            else:
                self.assert_(False)
        elif exp == "no-listen":
            res = n.get_tub_portlocation(cfg_tubport, cfg_location)
            self.assertEqual(res, None)
        elif exp in ("alloc/auto", "alloc/file", "auto", "manual"):
            with mock.patch("allmydata.util.iputil.get_local_addresses_sync",
                            return_value=["LOCAL"]):
                with mock.patch("allmydata.util.iputil.allocate_tcp_port",
                                return_value=999):
                    port, location = n.get_tub_portlocation(cfg_tubport,
                                                            cfg_location)
            try:
                with open(config.portnum_fname, "r") as f:
                    saved_port = f.read().strip()
            except EnvironmentError:
                saved_port = None
            if exp == "alloc/auto":
                self.assertEqual(port, "tcp:999")
                self.assertEqual(location, "tcp:LOCAL:999")
                self.assertEqual(saved_port, "tcp:999")
            elif exp == "alloc/file":
                self.assertEqual(port, "tcp:999")
                self.assertEqual(location, "tcp:HOST:888,tcp:LOCAL:999")
                self.assertEqual(saved_port, "tcp:999")
            elif exp == "auto":
                self.assertEqual(port, "tcp:777")
                self.assertEqual(location, "tcp:LOCAL:777")
                self.assertEqual(saved_port, None)
            elif exp == "manual":
                self.assertEqual(port, "tcp:777")
                self.assertEqual(location, "tcp:HOST:888,tcp:LOCAL:777")
                self.assertEqual(saved_port, None)
            else:
                self.assert_(False)
        else:
            self.assert_(False)
Ejemplo n.º 41
0
 def __init__(self, basedir):
     config = read_config(basedir, 'DEFAULT_PORTNUMFILE_BLANK')
     Node.__init__(self, config, basedir)
Ejemplo n.º 42
0
def NoNetworkClient(basedir):
    # XXX FIXME this is just to avoid massive search-replace for now;
    # should be create_nonetwork_client() or something...
    from allmydata.node import read_config
    config = read_config(basedir, u'client.port')
    return _NoNetworkClient(config, basedir=basedir)
Ejemplo n.º 43
0
def NoNetworkClient(basedir):
    # XXX FIXME this is just to avoid massive search-replace for now;
    # should be create_nonetwork_client() or something...
    from allmydata.node import read_config
    config = read_config(basedir, u'client.port')
    return _NoNetworkClient(config, basedir=basedir)
Ejemplo n.º 44
0
    def _try(self, tp, tl, exp):
        log.msg("PortLocation._try:", tp, tl, exp)
        cfg_tubport = {
            "missing": None,
            "empty": "",
            "disabled": "disabled",
            "endpoint": "tcp:777",
        }[tp]
        cfg_location = {
            "missing": None,
            "empty": "",
            "disabled": "disabled",
            "hintstring": "tcp:HOST:888,AUTO",
        }[tl]

        n = EmptyNode()
        basedir = os.path.join("test_node/portlocation/%s/%s" % (tp, tl))
        fileutil.make_dirs(basedir)
        config = n.config = read_config(basedir, "node.port")
        n._reveal_ip = True

        if exp in ("ERR1", "ERR2", "ERR3", "ERR4"):
            e = self.assertRaises(ValueError, n.get_tub_portlocation,
                                  cfg_tubport, cfg_location)
            if exp == "ERR1":
                self.assertEqual("tub.port must not be empty", str(e))
            elif exp == "ERR2":
                self.assertEqual("tub.location must not be empty", str(e))
            elif exp == "ERR3":
                self.assertEqual("tub.port is disabled, but not tub.location",
                                 str(e))
            elif exp == "ERR4":
                self.assertEqual("tub.location is disabled, but not tub.port",
                                 str(e))
            else:
                self.assert_(False)
        elif exp == "no-listen":
            res = n.get_tub_portlocation(cfg_tubport, cfg_location)
            self.assertEqual(res, None)
        elif exp in ("alloc/auto", "alloc/file", "auto", "manual"):
            with mock.patch("allmydata.util.iputil.get_local_addresses_sync",
                            return_value=["LOCAL"]):
                with mock.patch("allmydata.util.iputil.allocate_tcp_port",
                                return_value=999):
                    port, location = n.get_tub_portlocation(
                        cfg_tubport, cfg_location)
            try:
                with open(config.portnum_fname, "r") as f:
                    saved_port = f.read().strip()
            except EnvironmentError:
                saved_port = None
            if exp == "alloc/auto":
                self.assertEqual(port, "tcp:999")
                self.assertEqual(location, "tcp:LOCAL:999")
                self.assertEqual(saved_port, "tcp:999")
            elif exp == "alloc/file":
                self.assertEqual(port, "tcp:999")
                self.assertEqual(location, "tcp:HOST:888,tcp:LOCAL:999")
                self.assertEqual(saved_port, "tcp:999")
            elif exp == "auto":
                self.assertEqual(port, "tcp:777")
                self.assertEqual(location, "tcp:LOCAL:777")
                self.assertEqual(saved_port, None)
            elif exp == "manual":
                self.assertEqual(port, "tcp:777")
                self.assertEqual(location, "tcp:HOST:888,tcp:LOCAL:777")
                self.assertEqual(saved_port, None)
            else:
                self.assert_(False)
        else:
            self.assert_(False)
Ejemplo n.º 45
0
 def __init__(self, basedir):
     config = read_config(basedir, 'DEFAULT_PORTNUMFILE_BLANK')
     Node.__init__(self, config, basedir)