Содержание
- 1 Worst-case matching
- 2 COLOPHON top
- 3 General usage
- 4 EXAMPLES top
- 5 Creating URLs
- 6 OPTIONS top
- 7 Middleware usage
- 8 Алгоритмы маршрутизации
- 9 First route matching
- 10 Политика маршрутизации RS
- 11 Одноадресные протоколы маршрутизации
- 12 Протоколы многоадресной маршрутизации
- 13 Информация для настройки пиринговых сессий с RS
- 14 Как начать пользоваться RS?
- 15 OUTPUT top
Worst-case matching
This benchmark matches the last route and unknown route. It generates a randomly prefixed and suffixed route in an attempt to thwart any optimization. 1,000 routes each with 9 arguments.
This benchmark consists of 12 tests. Each test is executed 1,000 times, the results pruned, and then averaged. Values that fall outside of 3 standard deviations of the mean are discarded.
Test Name | Results | Time | + Interval | Change |
---|---|---|---|---|
r3 — unknown route (1000 routes) | 987 | 0.0000111161 | +0.0000000000 | baseline |
r3 — last route (1000 routes) | 994 | 0.0000135476 | +0.0000024316 | 22% slower |
FastRoute — unknown route (1000 routes) | 982 | 0.0003966292 | +0.0003855132 | 3468% slower |
FastRoute — last route (1000 routes) | 999 | 0.0004029198 | +0.0003918037 | 3525% slower |
Pux ext — unknown route (1000 routes) | 984 | 0.0008801297 | +0.0008690136 | 7818% slower |
Symfony2 Dumped — unknown route (1000 routes) | 981 | 0.0009883075 | +0.0009771914 | 8791% slower |
Pux ext — last route (1000 routes) | 999 | 0.0009942575 | +0.0009831414 | 8844% slower |
Symfony2 Dumped — last route (1000 routes) | 978 | 0.0010521817 | +0.0010410656 | 9365% slower |
Symfony2 — unknown route (1000 routes) | 989 | 0.0061380323 | +0.0061269163 | 55118% slower |
Symfony2 — last route (1000 routes) | 999 | 0.0061715401 | +0.0061604240 | 55419% slower |
Aura v2 — last route (1000 routes) | 982 | 0.1814854888 | +0.1814743727 | 1632542% slower |
Aura v2 — unknown route (1000 routes) | 977 | 0.1871979547 | +0.1871868386 | 1683932% slower |
COLOPHON top
This page is part of the net-tools (networking utilities) project. Information about the project can be found at ⟨http://net-tools.sourceforge.net/⟩. If you have a bug report for this manual page, see ⟨http://net-tools.sourceforge.net/⟩. This page was obtained from the project's upstream Git repository ⟨git://git.code.sf.net/p/net-tools/code⟩ on 2020-08-13. (At that time, the date of the most recent commit that was found in the repos‐ itory was 2018-11-03.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org net-tools 2014-02-17 ROUTE(8)
Pages that refer to this page: networks(5), proc(5), procfs(5), arp(8), ifconfig(8), netstat(8), rarp(8)
General usage
use Yiisoft\Router\Group; use Yiisoft\Router\Route; use Yiisoft\Router\RouteCollection; use Yiisoft\Router\RouteCollectorInterface; use Yiisoft\Router\Fastroute\UrlMatcher; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; $routes = [ Route::get('/', static function (ServerRequestInterface $request, RequestHandlerInterface $next) use ($responseFactory) { $response = $responseFactory->createResponse(); $response->getBody()->write('You are at homepage.'); return $response; }), Route::get('/test/{id:\w+}', static function (ServerRequestInterface $request, RequestHandlerInterface $next) use ($responseFactory) { $id = $request->getAttribute('id'); $response = $responseFactory->createResponse(); $response->getBody()->write('You are at test with param ' . $id); return $response; }) ]; $collector = $container->get(RouteCollectorInterface::class); $collector->addGroup(Group::create(null, $routes)); $urlMatcher = new UrlMatcher(new RouteCollection($collector)); // $request is PSR-7 ServerRequestInterface $result = $urlMatcher->match($request); if (!$result->isSuccess()) { // 404 } // $result->parameters() contains parameters from the match // run middleware assigned to a route found $response = $result->process($request, $handler);
and are specific to adapter package used. See its readme on how to properly configure it.
In you can either specify PSR middleware class name or a callback.
Note that pattern specified for routes depends on the underlying routing library used.
EXAMPLES top
route add -net 127.0.0.0 netmask 255.0.0.0 metric 1024 dev lo adds the normal loopback entry, using netmask 255.0.0.0 and associated with the "lo" device (assuming this device was previously set up correctly with ifconfig(8)). route add -net 192.56.76.0 netmask 255.255.255.0 metric 1024 dev eth0 adds a route to the local network 192.56.76.x via "eth0". The word "dev" can be omitted here. route del default deletes the current default route, which is labeled "default" or 0.0.0.0 in the destination field of the current routing table. route add default gw mango adds a default route (which will be used if no other route matches). All packets using this route will be gatewayed through the address of a node named "mango". The device which will actually be used for that route depends on how we can reach "mango" - "mango" must be on directly reachable route. route add mango sl0 Adds the route to the host named "mango" via the SLIP interface (assuming that "mango" is the SLIP host). route add -net 192.57.66.0 netmask 255.255.255.0 gw mango This command adds the net "192.57.66.x" to be gatewayed through the former route to the SLIP interface. route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 This is an obscure one documented so people know how to do it. This sets all of the class D (multicast) IP routes to go via "eth0". This is the correct normal configuration line with a multicasting kernel. route add -net 10.0.0.0 netmask 255.0.0.0 metric 1024 reject This installs a rejecting route for the private network "10.x.x.x." route -6 add 2001:0002::/48 metric 1 dev eth0 This adds a IPv6 route with the specified metric to be directly reachable via eth0.
Creating URLs
URLs could be created using . Let’s assume a route is defined like the following:
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Yiisoft\Yii\Web\SapiEmitter; use Yiisoft\Yii\Web\ServerRequestFactory; use Yiisoft\Yii\Web\NotFoundHandler; use Yiisoft\Router\Route; use Yiisoft\Router\RouteCollection; use Yiisoft\Router\RouteCollectorInterface; use Yiisoft\Router\Fastroute\UrlMatcher; $request = $container->get(ServerRequestFactory::class)->createFromGlobals(); $responseFactory = $container->get(ResponseFactoryInterface::class); $notFoundHandler = new NotFoundHandler($responseFactory); $collector = $container->get(RouteCollectorInterface::class); $collector->addRoute(Route::get('/test/{id:\w+}', static function (ServerRequestInterface $request, RequestHandlerInterface $next) use ($responseFactory) { $id = $request->getAttribute('id'); $response = $responseFactory->createResponse(); $response->getBody()->write('You are at test with param ' . $id); return $response; })->name('test')); $router = new UrlMatcher(new RouteCollection($collector)); $route = $router->match($request); $response = $route->process($request, $notFoundHandler); $emitter = new SapiEmitter(); $emitter->emit($response, $request->getMethod() === Method::HEAD);
Then that is how URL could be obtained for it:
use Yiisoft\Router\UrlGeneratorInterface; function getUrl(UrlGeneratorInterface $urlGenerator, $parameters = []) { return $urlGenerator->generate('test', $parameters); }
OPTIONS top
-A family use the specified address family (eg `inet'). Use route --help for a full list. You can use -6 as an alias for --inet6 and -4 as an alias for -A inet -F operate on the kernel's FIB (Forwarding Information Base) routing table. This is the default. -C operate on the kernel's routing cache. -v select verbose operation. -n show numerical addresses instead of trying to determine symbolic host names. This is useful if you are trying to determine why the route to your nameserver has vanished. -e use netstat(8)-format for displaying the routing table. -ee will generate a very long line with all parameters from the routing table. del delete a route. add add a new route. target the destination network or host. You can provide an addresses or symbolic network or host name. Optionally you can use prefixlen notation instead of using the netmask option. -net the target is a network. -host the target is a host. netmask NM when adding a network route, the netmask to be used. gw GW route packets via a gateway. NOTE: The specified gateway must be reachable first. This usually means that you have to set up a static route to the gateway beforehand. If you specify the address of one of your local interfaces, it will be used to decide about the interface to which the packets should be routed to. This is a BSDism compatibility hack. metric M set the metric field in the routing table (used by routing daemons) to M. If this option is not specified the metric for inet6 (IPv6) address family defaults to '1', for inet (IPv4) it defaults to '0'. You should always specify an explicit metric value to not rely on those defaults - they also differ from iproute2. mss M sets MTU (Maximum Transmission Unit) of the route to M bytes. Note that the current implementation of the route command does not allow the option to set the Maximum Segment Size (MSS). window W set the TCP window size for connections over this route to W bytes. This is typically only used on AX.25 networks and with drivers unable to handle back to back frames. irtt I set the initial round trip time (irtt) for TCP connections over this route to I milliseconds (1-12000). This is typically only used on AX.25 networks. If omitted the RFC 1122 default of 300ms is used. reject install a blocking route, which will force a route lookup to fail. This is for example used to mask out networks before using the default route. This is NOT for firewalling. mod, dyn, reinstate install a dynamic or modified route. These flags are for diagnostic purposes, and are generally only set by routing daemons. dev If force the route to be associated with the specified device, as the kernel will otherwise try to determine the device on its own (by checking already existing routes and device specifications, and where the route is added to). In most normal networks you won't need this. If dev If is the last option on the command line, the word dev may be omitted, as it's the default. Otherwise the order of the route modifiers (metric netmask gw dev) doesn't matter.
Middleware usage
In order to simplify usage in PSR-middleware based application, there is a ready to use middleware provided:
$router = $container->get(Yiisoft\Router\UrlMatcherInterface::class); $responseFactory = $container->get(\Psr\Http\Message\ResponseFactoryInterface::class); $routerMiddleware = new Yiisoft\Router\Middleware\Router($router, $responseFactory, $container); // add middleware to your middleware handler of choice
In case of a route match router middleware executes handler middleware attached to the route. If there is no match, next application middleware processes the request.
Алгоритмы маршрутизации
Flooding
Flooding — это самый простой способ пересылки пакетов. Когда пакет принимается, маршрутизаторы отправляют его на все интерфейсы, кроме тех, на которых он был получен. Это создает слишком большую нагрузку на сеть и множество дублирующих пакетов, блуждающих по сети.
Time to Live (TTL) можно использовать, чтобы избежать бесконечного цикла пакетов. Существует еще один подход к наводнению, который называется выборочным наводнением для снижения накладных расходов в сети. В этом методе маршрутизатор не реализуется на всех интерфейсах, а выборочно.
Shortest Path
Решение о маршрутизации в сетях, в основном, берется на основе стоимости между источником и пунктом назначения. Здесь играет важную роль. Самый короткий путь — это метод, который использует различные алгоритмы для определения пути с минимальным количеством прыжков.
Общими алгоритмами кратчайшего пути являются:
- Алгоритм Дейкстры
- Алгоритм Беллмана Форда
- Алгоритм Флойда Варшалла
First route matching
This benchmark tests how quickly each router can match the first route. 1,000 routes each with 9 arguments.
This benchmark consists of 6 tests. Each test is executed 1,000 times, the results pruned, and then averaged. Values that fall outside of 3 standard deviations of the mean are discarded.
Test Name | Results | Time | + Interval | Change |
---|---|---|---|---|
php-r3 — first route | 989 | 0.0000097053 | +0.0000000000 | baseline |
Pux ext — first route | 985 | 0.0000209825 | +0.0000112773 | 116% slower |
FastRoute — first route | 999 | 0.0000382496 | +0.0000285443 | 294% slower |
Symfony2 Dumped — first route | 991 | 0.0000611150 | +0.0000514098 | 530% slower |
Symfony2 — first route | 978 | 0.0002531449 | +0.0002434397 | 2508% slower |
Aura v2 — first route | 985 | 0.0003834265 | +0.0003737212 | 3851% slower |
Политика маршрутизации RS
Обмен роутинговой информацией между RS и каждым участником осуществляется по протоколу BGP4, описанном в RFC4271. Пиры RS получают от RS лучший выбранный маршрут из принятых от всех пиров. При передаче BGP-анонса от RS атрибут Next-Hop содержит IP-адрес того маршрутизатора, от которого данный анонс были получен RS; атрибут AS_PATH передается без изменений. Таким образом, обмен трафиком участников происходит напрямую, минуя RS.
RS обрабатывает BGP-анонсы по следующим принципам:
- Не принимаются анонсы приватных сетей, маршрута по умолчанию (default route), прочих сетей специального назначения (RFC6890).
- Не принимаются анонсы приватных AS и AS специального назначения (RFC5398, RFC6996, RFC7300, RFC7607).
- Не принимаются анонсы сетей, для которых значение origin объекта route/route6 в базе данных IRR не совпадает с номером начальной AS в атрибуте AS_PATH анонса.
- Не принимаются анонсы сетей, для которых номер последней добавленной AS в атрибуте AS_PATH анонса не совпадает с номером AS участника, с которым установлена BGP-сессия.
-
Осуществляется проверка валидности анонсов с точки зрения технологии RPKI (RFC6480), проставляется соответствующее BGP-community по результатам проверки.
- Анонс со статусом RPKI_VALID принимается, если его AS входит в as-set или равна aut-num, которые указаны в export или mp-export политике взаимодействия AS участника с AS роут-сервера.
- Анонсы со статусом RPKI_INVALID не принимаются.
- Анонсы со статусом RPKI_UNKNOWN проверяются по пунктам 6-7.
- Анонс принимается, если для него описан route/route6 объект в IRR DB, входящий в as-set или aut-num, которые указаны в export или mp-export политике взаимодействия AS участника с AS роут-сервера. Размер префикса route/route6 объекта и BGP-анонса должны совпадать, за исключением пункта 7.
- Анонс принимается, если для него не описан route/route6 объект в IRR DB, но при этом описан route/route6 агрегата данного префикса, удовлетворяющий требованиям пункта 6. Анонсы, удовлетворяющие критериям пункта 7, дополнительно маркируются (RSAS:65500).
Одноадресные протоколы маршрутизации
Существует два типа протоколов маршрутизации для маршрутизации одноадресных пакетов:
- Протокол маршрутизации с дистанционным вектором Distance Vector — это простой протокол маршрутизации, который принимает решение о маршрутизации количества переходов между источником и получателем. Лучшим маршрутом считается маршрут с меньшим количеством перелетов. Каждый маршрутизатор рекламирует свои лучшие маршруты для других маршрутизаторов. В конечном счете, все маршрутизаторы создают свою топологию сети на основе рекламы своих одноранговых маршрутизаторов. Например, протокол маршрутизации информации (RIP).
- Протокол маршрутизации состояния канала Протокол состояния канала — это несколько сложный протокол, чем «Вектор расстояния». Он учитывает состояния ссылок всех маршрутизаторов в сети. Этот метод помогает маршрутам строить общий график всей сети. Затем все маршрутизаторы рассчитывают наилучший путь для маршрутизации. Например, Open Shortest Path First (OSPF) и промежуточная система для промежуточной системы (ISIS).
Протоколы многоадресной маршрутизации
Протоколы одноадресной маршрутизации используют графики, в то время как протоколы маршрутизации многоадресной рассылки используют деревья, т.е. Связывают дерево, чтобы избежать циклов. Оптимальное дерево называется кратчайшим связующим деревом.
- DVMRP — Протокол маршрутизации многоадресной передачи расстояния
- MOSPF — Открытый многоадресный маршрут
- CBT — базовое дерево
- PIM — независимая от протокола многоадресная рассылка
Протокол Независимой Многоадресной рассылки (PIM) используется сейчас. Он имеет два вида:
- Режим PIM DenseВ этом режиме используются деревья на основе источника. Он используется в плотной среде, такой как LAN.
- PIM разреженный режимВ этом режиме используются общие деревья. Он используется в редких средах, таких как WAN.
Информация для настройки пиринговых сессий с RS
Город | Route Server AS | Анонсируемый объект | IP-адреса BGP-спикеров* | Расписание реконфигурации**(время местное) |
Москва | AS-MSKROUTESERVER | 195.208.208.100/212001:7F8:20:101::208:100/64 | 15:30-16:30 (время местное)ежедневно понедельник-пятница | |
195.208.215.100/212001:7F8:20:101::215:100/64 | 11:30-12:30 (время местное)ежедневно понедельник-пятница | |||
Санкт-Петербург | AS-SPBROUTESERVER | 194.226.100.100/232001:7f8:20:201::100:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
194.226.102.100/232001:7f8:20:202::102:100/64 | 13:00-14:00 (время местное)ежедневно понедельник-пятница | |||
Ростов-на-Дону | AS-RNDROUTESERVER | 193.232.140.100/242001:7f8:20:501::140:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
Ставрополь | AS-STWROUTESERVER | 194.85.177.100/242001:7f8:20:901::177:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
Самара | AS-SMRROUTESERVER | 193.232.135.100/242001:7f8:20:601::135:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
193.232.135.200/242001:7f8:20:601::135:200/64 | 12:30-13:30 (время местное)ежедневно понедельник-пятница | |||
Казань | AS-KZNROUTESERVER | 194.190.119.100/242001:7f8:20:801::119:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
Екатеринбург | AS-EKTROUTESERVER | 194.85.107.100/242001:7f8:20:301::107:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
194.85.107.200/242001:7f8:20:301::107:200/64 | 12:30-13:30 (время местное)ежедневно понедельник-пятница | |||
Новосибирск | AS-NSKROUTESERVER | 193.232.87.100/242001:7f8:20:401::87:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
193.232.87.200/242001:7f8:20:401::87:200/64 | 12:30-13:30 (время местное)ежедневно понедельник-пятница | |||
Владивосток | AS-VLVROUTESERVER | 193.232.136.100/242001:7f8:20:701::136:100/64 | 17:00-18:00 (время местное)ежедневно понедельник-пятница | |
Рига | n/a |
Как начать пользоваться RS?
Чтобы начать пользоваться RS в городе подключения к MSK-IX, настройте взаимодействие с соответствующей служебной автономной системой Route Server AS (см. ) по протоколу BGP.
Для этого выполните следующие шаги:
- Внесите описание политики взаимодействия вашей сети с Route Server AS в базу данных Internet Routing Registry (IRR), поддерживаемую MSK-IX (RIPE, ARIN, RADB).
- Направьте с любого из авторизованных по договору контактных адресов на адрес noc@ix.ru заявку, содержащую город подключения к MSK-IX, идентификатор организации, номер AS участника и IP-адрес маршрутизатора (IPv4 и/или IPv6).
- Настройте BGP-сессии со своей стороны со всеми BGP-спикерами службы RS в соответствующем городе.
- В конфигурации BGP со своей стороны отключите проверку first-as командой no bgp enforce-first-as.
Информация об использовании RS участниками MSK-IX, доступна в Клиентском кабинете MSK-IX.
Информация о политике маршрутизации Route Server AS содержится в базе RIPE (сайт https://www.ripe.net или утилита whois -h whois.ripe.net as).
Для отладки маршрутизации и контроля BGP-анонсов, принимаемых RS, пользуйтесь службой Looking Glass.
OUTPUT top
The output of the kernel routing table is organized in the following columns Destination The destination network or destination host. Gateway The gateway address or '*' if none set. Genmask The netmask for the destination net; '255.255.255.255' for a host destination and '0.0.0.0' for the default route. Flags Possible flags include U (route is up) H (target is a host) G (use gateway) R (reinstate route for dynamic routing) D (dynamically installed by daemon or redirect) M (modified from routing daemon or redirect) A (installed by addrconf) C (cache entry) ! (reject route) Metric The 'distance' to the target (usually counted in hops). Ref Number of references to this route. (Not used in the Linux kernel.) Use Count of lookups for the route. Depending on the use of -F and -C this will be either route cache misses (-F) or hits (-C). Iface Interface to which packets for this route will be sent. MSS Default maximum segment size for TCP connections over this route. Window Default window size for TCP connections over this route. irtt Initial RTT (Round Trip Time). The kernel uses this to guess about the best TCP protocol parameters without waiting on (possibly slow) answers. HH (cached only) The number of ARP entries and cached routes that refer to the hardware header cache for the cached route. This will be -1 if a hardware address is not needed for the interface of the cached route (e.g. lo). Arp (cached only) Whether or not the hardware address for the cached route is up to date.
С этим читают
- React router v6 preview
- .net framework
- Использование net framework 3.5 и 4.5 в windows 10
- Почему net framework 4 не устанавливается windows 7?
- Полное руководство по yii 2.0
- Laravel framework russian community
- Веб-фреймворки: введение для новичков
- Building a vue spa with laravel
- .net core на linux, devops на коне
- Nuxtjs