Failed to receive status rpc error code unavailable desc transport is closing

docker service list fails with «rpc error: code = Unavailable desc = transport is closing» #37849 Comments we hava a physical docker swarm with 3 managers, 1 of them updated to 18.06.01-ce (sys2) and the others still in 17.12.0-ce (sys1 and db1) everything works ok, except the docker service list command from the updated […]

Содержание

  1. docker service list fails with «rpc error: code = Unavailable desc = transport is closing» #37849
  2. Comments
  3. GRPC stream fail rpc error: code = Unavailable desc = transport is closing #2443
  4. Comments
  5. What version of gRPC are you using?
  6. What version of Go are you using ( go version )?
  7. What operating system (Linux, Windows, …) and version?
  8. What did you do?
  9. What did you expect to see?
  10. What did you see instead?
  11. FATA[0000] rpc error: code = Unavailable desc = transport is closing with every command #3811
  12. Comments
  13. «Unavailable desc = transport is closing» A #19248
  14. Comments
  15. Error: rpc error: code = Unavailable desc = transport is closing in release v1.2.0 #486
  16. Comments
  17. Provider Version
  18. Terraform Version
  19. Affected Resource(s)
  20. Terraform Configuration Files
  21. Debug Output
  22. Panic Output
  23. Steps to Reproduce
  24. Important Factoids
  25. References

docker service list fails with «rpc error: code = Unavailable desc = transport is closing» #37849

we hava a physical docker swarm with 3 managers, 1 of them updated to 18.06.01-ce (sys2) and the others still in 17.12.0-ce (sys1 and db1)

everything works ok, except the docker service list command from the updated node:

when this happens docker events shows:

also, all connections from sys2 to the cluster (docker service log . ) are interrupted

Steps to reproduce the issue:

  1. update 1 node to 18.06.01
  2. docker service list
  • I’m unable to reproduce the issue on my test lab

Describe the results you received:
Error response from daemon: rpc error: code = Unavailable desc = transport is closing

Describe the results you expected:
the list of services

Output of docker version :

Output of docker info :

The text was updated successfully, but these errors were encountered:

we reduced the number of old tasks (reducing RestartAttempts and task-history-limit) until the response to api/tasks was under 1Mb

Possibly related to #37997 (and #38123, #38103)

os: centos 7
my k8s node get down every time I run a job in a pod.
When I login to the node, I realize that dockerd was terminated(in fact it was killed).

cmd on node to get dockerd log: sudo journalctl -u docker.service
what log I get:
level=error msg=»failed to get event» error=»rpc error: code = Unavailable desc = transport is closing» module=libcontainerd namespace=moby level=warning msg=»grpc: addrConn.createTransport failed to connect to . Err :connection error: desc = »transport: Error while dialing dial unix /run/containerd/containerd.sock: connect: connection refused». Reconnecting. » module=grpc level=error msg=»failed to get event» error=»rpc error: code = Unavailable desc = transport is closing» module=libcontainerd namespace=plugins.moby level=info msg=»Processing signal ‘terminated’» level=warning msg=»grpc: addrConn.createTransport failed to connect to . Err :connection error: desc = »transport: Error while dialing dial unix /run/containerd/containerd.sock: connect: connection refused». Reconnecting. » module=grpc
cmd to get system log: grep «Out of memory» /var/log/messages

and I guess that it is a task that run in the container that casuse the above problem. The app consume much memory and cause OOM. I run the task which is a training task in a container, and it was killed.

solution: optimize the task to consume less mem, or run the task on another node with enough mem.

Same issue with Docker version 20.10.7, build 20.10.7-0ubuntu1

18.04.1. Any clues on this ?

@shivam2202 it’s a different error in your case. Also a «rpc» error, but because docker failed to connect with containerd. ( libcontainerd is the containerd client in the docker daemon). Could be that containerd crashed or something ran out of resources; the error itself is not very informative (just means the gRPC connection with containerd closed), but I’d recommend looking if other log entries around that timeframe give more details that help you find the cause (also be sure to check logs for containerd itself, and system logs)

Источник

GRPC stream fail rpc error: code = Unavailable desc = transport is closing #2443

Please answer these questions before submitting your issue.

What version of gRPC are you using?

What version of Go are you using ( go version )?

go version go1.11

What operating system (Linux, Windows, …) and version?

What did you do?

If possible, provide a recipe for reproducing the error.

I use the grpc client to send the request to the same server at the same time, during which the service is normal, but after the restart, the master reports this error.

If you restart the master server, it works fine.

What did you expect to see?

Will not report this error

What did you see instead?

The text was updated successfully, but these errors were encountered:

Can you turn on logging on both client and server side? i.e. using environment variable GRPC_GO_LOG_VERBOSITY_LEVEL=99 GRPC_GO_LOG_SEVERITY_LEVEL=info .

Also can you provide a code snippet to show your set up? Thanks!

I have solved it because of the problem caused by the null pointer. thank you @lyuxuan.

Could you please elaborate on what you had to do to fix this issue. I’ve got the same rpc error and do not know what causes it.

Thanks for your response!
I’m currently rewriting a client I wrote in Python in Go. When trying to connect to the server without the right credentials with python, it returned the rpc error «origin authentication failed», so I guess I just expected a similar error to be returned with Go and now I am a little puzzled about why the rpc error in Go is the same if the server is down and if the connection failed on handshaking.

without the right credentials

What exactly went wrong in the configuration?

In my mind, this can be one of:

  1. Server expects auth, but client doesn’t do auth (connect using WithInsecure ).
    • The client doesn’t do creds handshake at all. What we see is that the connection is closed, for some unclear reason. It could be authentication or something else.
  2. Client uses the wrong configuration (e.g. wrong certificate).
    • The RPC should fail with an error like rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = «transport: authentication handshake failed: .

Thanks for your response.
The server did expect authentication, but I knowingly tried to connect using WithInsecure() and expected the error to be similar to the one in python where you get a different error, depending on if the server is down or if it expects authentication.
I managed to achieve what I wanted, so thanks again.

Hey, I just wanted to briefly detail how we solved this issue recently, just in case someone else has a similar setup and is facing these ‘intermittent’ connection drops

Our environment (prior to solving the issue):

  • grpc v1.18 (in both client and server)
  • golang v1.10.8 (in both client and server)
  • connection from a k8s cluster in GCP to an instance in AWS. No meshes in between, but there’s a network load balancer routing traffic to our AWS instance. This turned out to be the key part.
  • unary, non-TLS RPCs
  • no keepalive settings configured in neither client nor server
  • server and client verbose logging:

What we were experiencing were random transport is closing errors on the client when making unary RPCs to our server (usually after

5 minutes of inactivity). Most of the time, our server would not even get the request from the client, so we thought some other component in between should be causing the connections to be closed.

After some digging, we eventually found this section in the AWS network load balancer docs:

For each request that a client makes through a Network Load Balancer, the state of that connection is tracked. The connection is terminated by the target. If no data is sent through the connection by either the client or target for longer than the idle timeout, the connection is closed. If a client sends data after the idle timeout period elapses, it receives a TCP RST packet to indicate that the connection is no longer valid.

Elastic Load Balancing sets the idle timeout value to 350 seconds. You cannot modify this value. Your targets can use TCP keepalive packets to reset the idle timeout.

Immediately after seeing this, we decided to start using keepalive pings from the client. You can easily enable this on the client as a dial option ( keepalive.ClientParameters ) and on the server ( grpc.KeepaliveEnforcementPolicy ) as a server option which forces clients to comply with the keepalive policy.

Since we just use unary RPCs, we had to set PermitWithoutStream=true , so that the client sends keepalive pings while not streaming. We also made sure that the enforcement policy has a KeepaliveEnforcementPolicy.MinTime=1 * time.Minute (it has to be lower than the LB’s connection idle timeout of 350s) and the client would submit keepalive pings every 2 minutes ( ClientParameters.Time=2 * time.Minute ). As long as Time > MinTime , we’re good!

We applied the changes to our clients and server (as others have mentioned, the clients must comply with the server policy, otherwise you’ll have more connectivity issues) and the transport is closing issue is now totally gone, as the client will keep the connections alive.

Источник

FATA[0000] rpc error: code = Unavailable desc = transport is closing with every command #3811

If you are trying to resolve an environment-specific issue or have a one-off question about the edge case that does not require a feature then please consider asking a
question in argocd slack channel.

  • [ X ] I’ve searched in the docs and FAQ for my answer: http://bit.ly/argocd-faq.
  • [ X ] I’ve included steps to reproduce the bug.
  • [ X ] I’ve pasted the output of argocd version .

Describe the bug

A clear and concise description of what the bug is.

When i run the command ./argocd —insecure account list or any command like that exeptc: ./argocd —insecure —grpc-web app sync $APP_NAME —force which run perfectly fine I got this error:
FATA[0000] rpc error: code = Unavailable desc = transport is closing which is not very clear to me it miss a lot of information to debug (even when I try to change log-level to debug)
To Reproduce
Run ./argocd —insecure account list

A list of the steps required to reproduce the issue. Best of all, give us the URL to a repository that exhibits this issue.

Expected behavior
I except command run like the documentation says.
I except the list of users.

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Version

Logs

The text was updated successfully, but these errors were encountered:

Источник

«Unavailable desc = transport is closing» A #19248

When I apply JSON template below, I get this:

Some of the details of the template have been obfuscated.
Versions:
Terraform v0.12.0-alpha1

The text was updated successfully, but these errors were encountered:

Hi @dgarstang! Thanks for reporting this.

It looks like the provider process crashed somehow, without producing any panic output. If possible, it’d be helpful to see the full trace log (with the TF_LOG=trace environment variable set) for this operation, which will hopefully include information about what crashed in the provider here.

If you’re able to capture such a log, please share it as a gist because logs are too long to be readable in a GitHub comment.

Unfortunately it looks like the log you shared there is not complete because you answered «Yes» (capital Y) to the confirm prompt which Terraform did not interpret as confirmation and instead exited immediately. Would you mind doing that one more time with the apply steps included, since that’s where the crash seemed to be in your initial report?

Thanks @dgarstang! I found the following panic message in the logs:

This seems to be the same problem as in #19152, which has fortunately since been fixed in master and is included in the subsequent alpha2 builds. Hopefully if you repeat this with the alpha2 builds you’ll see it work.

(Note that since the alpha builds have provider binaries embedded in them it’s important to ensure that the providers from alpha1 are not still in the directory containing the terraform executable. The easiest way to ensure that is to extract alpha2 into a different directory, so that it won’t be able to find the alpha1 provider builds.)

Since I didn’t hear back from you and the stack trace here looks just like the one from #19152, I’m going to close this out now assuming that this one is also fixed, just to keep things updated here. If you find that isn’t true, please let me know!

Источник

Error: rpc error: code = Unavailable desc = transport is closing in release v1.2.0 #486

Provider Version

Terraform Version

Affected Resource(s)

Terraform Configuration Files

Debug Output

Panic Output

Steps to Reproduce

Important Factoids

Running this as a CircleCI job:

References

I notice at hashicorp/terraform-provider-aws#11420 that they determined that they needed to introduce greater defensiveness on the input value, but I don’t know if this is at all related, just a similar error. I’m mid-debugging, so I’ll update if I find out more.

The text was updated successfully, but these errors were encountered:

It turns out this was because we were trying to pass nil values that we failed to use the required function for in our chart templates, and the helm linter was failing there. And these helm lint failures caused the above Go panic downstream.

I am getting the same error when trying to install this chart.

If run a helm pull on this chart and then helm lint passing in the same values that I am providing to the helm_release resource, the lint command works fine.

I think this linting functionality might need a second look or at least better error propagation. I’m going to be pinning back to 1.1.1 for the time being.

OK — I was able to reproduce this. Thanks for opening this issue and investigating @jaredscheib.

This code assumes that the number of items in r.Messages with an Err value that is not nil will be the same length as r.Errors , but this is not the case as there appears to be warnings that will have an Err value but not appear in the r.Errors list.

I’ll have a PR with a fix for this shortly.

Источник

Обновлено 15.02.2022

the rpc server is unavailable

Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов в рунете Pyatilistnik.org. В прошлый раз мы с вами разобрали замечательную утилиту командной строки robocopy, и с ее помощью научились создавать точные копии папок, двигать их в нужное расположение и многое другое. В сегодняшней публикации я покажу вам, как устранять ошибку «Сервер RPC недоступен (The rpc server is unavailable)», покажу примеры, когда ее мониторинг очень важен в работе корпоративных сервисов.

Для чего нужна служба «Удаленный вызов процедур (RPC)»

Удаленный вызов процедур (RPC) — это  протокол,  который одна программа может использовать для запроса услуги у программы, расположенной на другом компьютере в сети, без необходимости разбираться в деталях сети. RPC используется для вызова других процессов на удаленных системах, таких как локальная система. Вызов процедуры также иногда называют вызовом функции или вызовом подпрограммы .

RPC использует модель  клиент-сервер. Запрашивающая программа — это клиент, а программа, предоставляющая услуги, — это сервер. Подобно обычному или локальному вызову процедуры, RPC — это  синхронная операция, требующая приостановки запрашивающей программы до тех пор, пока не будут возвращены результаты удаленной процедуры. Однако использование облегченных процессов или потоков, которые совместно используют одно и то же адресное пространство, позволяет одновременно выполнять несколько RPC.

Язык определения интерфейса (IDL) — язык спецификации, используемый для описания интерфейса прикладного программирования (API) программного компонента — обычно используется в программном обеспечении удаленного вызова процедур. В этом случае IDL обеспечивает мост между машинами на обоих концах связи, которые могут использовать разные операционные системы (ОС) и компьютерные языки.

Процедура сообщения RPC

Когда программные операторы, использующие структуру RPC, компилируются в исполняемую программу, в скомпилированный код включается заглушка, которая выступает в качестве представителя кода удаленной процедуры. Когда программа запускается и выполняется вызов процедуры, заглушка получает запрос и пересылает его клиентской программе и времени выполнения на локальном компьютере. При первом вызове клиентской заглушки она связывается с сервером имен, чтобы определить транспортный адрес, по которому находится сервер.

Программа среды выполнения клиента знает, как обращаться к удаленному компьютеру и серверному приложению, и отправляет сообщение по сети, которое запрашивает удаленную процедуру. Точно так же сервер включает исполняющую программу и заглушку, которая взаимодействует с самой удаленной процедурой. Протоколы ответа-запроса возвращаются таким же образом.

Данная служба есть в любой операционной системе Windows, начиная от Windows 7 и заканчивая Windows 11 и в любой из Windows Server редакции.

Как работает RPC?

Когда вызывается служба RPC (удаленный вызов процедуры), вызывающая среда приостанавливается, параметры процедуры передаются по сети в среду, в которой должна выполняться процедура, а затем процедура выполняется в этой среде. Когда процедура завершается, результаты передаются обратно в вызывающую среду, где выполнение возобновляется, как если бы оно возвращалось из обычного вызова процедуры.

Во время RPC выполняются следующие шаги:

  1. Клиент вызывает клиентскую заглушку. Вызов представляет собой вызов локальной процедуры с параметрами, помещенными в стек обычным способом.
  2. Клиентская заглушка упаковывает параметры процедуры в сообщение и выполняет системный вызов для отправки сообщения. Упаковка параметров процедуры называется маршалингом.
  3. Локальная ОС клиента отправляет сообщение с клиентского компьютера на удаленный сервер.
  4. Серверная ОС передает входящие пакеты на серверную заглушку.
  5. Заглушка сервера распаковывает параметры из сообщения — это называется демаршалингом .
  6. Когда серверная процедура завершается, она возвращается к серверной заглушке, которая маршалирует возвращаемые значения в сообщение. Затем заглушка сервера передает сообщение на транспортный уровень.
  7. Транспортный уровень отправляет полученное сообщение обратно на клиентский транспортный уровень, который возвращает сообщение клиентской заглушке.
  8. Клиентская заглушка не упорядочивает возвращаемые параметры, и выполнение возвращается вызывающей стороне.

Клиент RPC по 135 порту подключается к службе RPC Endpoint Mapper (сопоставления конечных точек), а далее уже запрашивает номер порта, где запущено нужное RPC приложение. Служба сопоставления конечных точек вернет клиенту RPC номер динамического RPC порта (диапазон 1024 – 65535), на котором работает нужная служба. Дальше уже все взаимодействие идет по TCP порту

Если вы видите ошибку «Сервер RPC недоступен” (The RPC server is unavailable)», то у вас точно недоступен порт 135. Это может быть критичным для ряда ситуации. Например вы не сможете сохранить настройки RDS фермы, если у одного из хостов RDSH есть проблемы с RPC, то вы будите видеть ошибку «Could not change the connection state for server», вы не сможете перевести его в режим обслуживания (Drain Mode)

Could not change the connection state for server

Или в приложении Terminal Services Manager будет ошибка при попытке получения данных «Сервер RPC недоступен«.

Сервер RPC недоступен

Так же RPC может быть причиной проблемы в репликации контроллеров домена, где в логах Windows будет фигурировать ошибка ID 1722. Это очень не приятный момент, который может привести к большим проблемам.

Типы RPC

Существует пять типов RPC:

  1. Обычный метод работы, при котором клиент выполняет вызов и не продолжает работу до тех пор, пока сервер не вернет ответ.
  2. Клиент звонит и продолжает свою обработку. Сервер не отвечает.
  3. Средство для отправки нескольких клиентских неблокирующих вызовов в одном пакете.
  4. У клиентов RPC есть средство широковещательной рассылки, т. е. Они могут отправлять сообщения на множество серверов, а затем получать все полученные ответы.
  5. Клиент делает неблокирующий вызов клиент/сервер; сервер сигнализирует о завершении вызова путем вызова процедуры, связанной с клиентом.

Почему может не работать служба RPC

  1. Удаленный компьютер с которым идет взаимодействие выключен
  2. На удаленном сервере не запущена или перестала работать служба RPC
  3. Подключение по RPC происходит не к тому серверу (Может быть проблема с DNS или IP адресом)
  4. Есть блокировки между клиентом и сервером на фаэрволе
  5. Используются некорректные настройки сетевого подключение на клиенте или сервере

Преимущества удаленного вызова процедур

К преимуществам удаленного вызова процедур можно отнести следующее:

  • помогает клиентам общаться с серверами посредством традиционного использования вызовов процедур на языках высокого уровня;
  • может использоваться как в распределенной, так и в локальной среде;
  • поддерживает процессно-ориентированные и поточно-ориентированные модели;
  • скрывает внутренний механизм передачи сообщений от пользователя;
  • требует минимальных усилий для переписывания и повторной разработки кода;
  • обеспечивает абстракцию, т. е. характер передачи сообщений по сети скрыт от пользователя;
  • опускает многие уровни протокола для повышения производительности.

Недостатки RPC

Некоторые из недостатков RPC включают следующее:

  • Клиент и сервер используют разные среды выполнения для своих соответствующих подпрограмм, и использование ресурсов, например файлов, также является более сложным. Следовательно, системы RPC не подходят для передачи больших объемов данных.
  • RPC очень уязвим для сбоев, потому что он включает в себя систему связи, другую машину и другой процесс.
  • Единого стандарта для RPC не существует; это может быть реализовано множеством способов.
  • RPC основан только на взаимодействии и, как таковой, не предлагает гибкости, когда дело касается аппаратной архитектуры.

Проверка доступности службы RPC

  • Как я и писал выше, в первую очередь вы должны убедиться, что удаленный компьютер к которому вы делаете проверку RPC доступен по сети. Для этого элементарно откройте командную строку или оболочку PowerShell и воспользуйтесь командой Ping, NSlookup, Test-NetConnection. Я буду производить проверку службы удаленного вызова в PowerShell. Выполним для начала команду Ping. Мой удаленный сервер называется SVT201S01.root.pyatilistnik.org. Пишем команду:

ping SVT201S01.root.pyatilistnik.org

Если вдруг компьютер не ответил, то это не значит, что он не работает, может работать брандмауэр и просто блокировать ping пакеты.Проверка доступности службы RPC через ping

  • Далее выполните Nslookup, чтобы удостовериться, что нужное вам имя компьютера преобразовывается в нужный IP-адрес. Выполните:

nslookup SVT201S01.root.pyatilistnik.org

Небольшой пример из практики, предположим, что вы мигрировали сервер в другую подсеть, в итоге в DNS должна быть изменена соответствующая запись, но Windows это поймет не сразу, так как у нее есть свой локальный кэш, он живет 15 минут, поэтому если при проверке DNS имени вам выдается не тот IP-адрес, вам необходимо произвести очистку кэша DNS.

Проверка доступности службы RPC через nslookup

  • Далее я вам советую проверить отвечает ли порт. Напоминаю, что служба RPC Endpoint Mapper слушает порт под номером 135. В PowerShell введите команду:

Test-NetConnection svt2019s01.root.pyatilistnik.org -Port 135

Если удаленный RPC порт доступен вы в в строке TcpTestSucceeded будет стоять статус «True».

Проверка доступности службы RPC через Test-NetConnection

Если будет порт закрыт или блокируется, то ошибка «Сервер RPC недоступен (The rpc server is unavailable)» вам обеспечена. Поняв, что порт не отвечает, нужно удостовериться, что трафик от клиента до сервера не блокирует фаервол. По умолчанию в любой версии Windows есть встроенный брандмауэр. На время тестирования и поиска причины, я советую его выключить для всех профилей. Сделаем мы это через командную строку:

Netsh Advfirewall set allprofiles state off

Данная команда выключит брандмауэр на всех трех профилях сетевой карты.

Отключение брандмауэра Windows через командную строку

Далее если порт 135 стал доступен, то можно делать правила на удаленном сервере. Напоминаю, что нужно сделать правило для трех служб:

  1. Remote Procedure Call (RPC) — Удаленный вызов процедур (RPC)
  2. RPC Endpoint Mapper — Сопоставитель конечных точек RPC
  3. COM Server Process Launcher — Модуль запуска процессов DCOM-сервера

Подробнее, о том как сделать правила — https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-firewall/create-inbound-rules-to-support-rpc)

Еще хочу отметить, что если у вас есть сторонние антивирусные решения, например Касперский, то там так же есть встроенный сетевой экран, где так же нужно будет создать необходимые, разрешающие правила, которые корректно будут обрабатывать трафик динамических RPC портов.

Проверка работы служб RPC

Следующим шагом является проверка состояния службы на нужном вам сервере или компьютере. Проверять следует три службы:

  1. Remote Procedure Call (RPC) — Удаленный вызов процедур (RPC)
  2. RPC Endpoint Mapper — Сопоставитель конечных точек RPC
  3. COM Server Process Launcher — Модуль запуска процессов DCOM-сервера

В оболочке PowerShell выполните команду:

Для локального сервера — Get-Service RpcSs,RpcEptMapper,DcomLaunch| Select DisplayName,Status,StartType

Для удаленного выполнения Enter-PSSession svt2019s01 далее Get-Service RpcSs,RpcEptMapper,DcomLaunch| Select DisplayName,Status,StartType

Напоминаю, что в команде svt2019s01, это имя удаленного сервера. Как видно из примера, все службы RPC запущены и имею автоматический тип запуска.

Проверка состояния служб RPC

Если службы не запущены, то откройте оснастку «services.msc’, зайдите в свойства службы и выставите автозапуск и попробуйте запустить вручную.

services.msc

Если по каким, то причинам вы не можете запустить службу из оснастки, то можно это сделать через реестр (Кстати реестр можно править и удаленно). Для этого есть несколько веток, но для начала откройте окно «Выполнить» и введите regedit.

Запуск реестра Windows

  • Модуль запуска процессов DCOM-сервера — HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesDcomLaunch
  • Сопоставитель конечных точек RPC — HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesRpcEptMapper
  • Удаленный вызов процедур (RPC) — ветка реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesRpcSs

В каждом из этих расположений есть ключик «Start«, выставите ему значение «2«, это будет означать автоматический запуск службы.

Управление автозапуском службы через реестр

Дополнительные сетевые проверки

В некоторых случаях причиной ошибок с доступностью RPC выступает сбой на сетевых адаптерах. Помогает сброс сетевых настроек и перезагрузка. В сети с Active Directory, старайтесь, чтобы на всех ваших сетевых адаптерах в свойствах были выставлены обе галки IPV4 и IPV6, особенно это актуально для контроллеров домена, где вы легко можете получать ошибку 1722. Еще может помочь отключение протокола Teredo у IPv6. В командной строке выполните:

netsh interface teredo set state disabled

Для включения обратно введите:

netsh interface teredo set state enabled

Еще на сайте Майкрософт пишут, что необходимо на сервере RPC иметь включенную службу «Удаленный реестр«. На этом у меня все, с вами был Иван Сёмин, автор и создатель IP портала Pyatilistnik.org.

Package grpc implements an RPC system called gRPC.

See grpc.io for more information about gRPC.

  • Constants
  • Variables
  • func Code(err error) codes.Codedeprecated
  • func ErrorDesc(err error) stringdeprecated
  • func Errorf(c codes.Code, format string, a …interface{}) errordeprecated
  • func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, …) error
  • func Method(ctx context.Context) (string, bool)
  • func MethodFromServerStream(stream ServerStream) (string, bool)
  • func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context
  • func SendHeader(ctx context.Context, md metadata.MD) error
  • func SetHeader(ctx context.Context, md metadata.MD) error
  • func SetTrailer(ctx context.Context, md metadata.MD) error
  • type BackoffConfigdeprecated
  • type CallOption
    • func CallContentSubtype(contentSubtype string) CallOption
    • func CallCustomCodec(codec Codec) CallOptiondeprecated
    • func FailFast(failFast bool) CallOptiondeprecated
    • func ForceCodec(codec encoding.Codec) CallOption
    • func Header(md *metadata.MD) CallOption
    • func MaxCallRecvMsgSize(bytes int) CallOption
    • func MaxCallSendMsgSize(bytes int) CallOption
    • func MaxRetryRPCBufferSize(bytes int) CallOption
    • func Peer(p *peer.Peer) CallOption
    • func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption
    • func Trailer(md *metadata.MD) CallOption
    • func UseCompressor(name string) CallOption
    • func WaitForReady(waitForReady bool) CallOption
  • type ClientConn
    • func Dial(target string, opts …DialOption) (*ClientConn, error)
    • func DialContext(ctx context.Context, target string, opts …DialOption) (conn *ClientConn, err error)
    • func (cc *ClientConn) Close() error
    • func (cc *ClientConn) Connect()
    • func (cc *ClientConn) GetMethodConfig(method string) MethodConfig
    • func (cc *ClientConn) GetState() connectivity.State
    • func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, …) error
    • func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts …CallOption) (ClientStream, error)
    • func (cc *ClientConn) ResetConnectBackoff()
    • func (cc *ClientConn) Target() string
    • func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool
  • type ClientConnInterface
  • type ClientStream
    • func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, …) (ClientStream, error)
  • type Codecdeprecated
  • type Compressordeprecated
    • func NewGZIPCompressor() Compressordeprecated
    • func NewGZIPCompressorWithLevel(level int) (Compressor, error)deprecated
  • type CompressorCallOption
  • type ConnectParams
  • type ContentSubtypeCallOption
  • type CustomCodecCallOption
  • type Decompressordeprecated
    • func NewGZIPDecompressor() Decompressordeprecated
  • type DialOption
    • func FailOnNonTempDialError(f bool) DialOption
    • func WithAuthority(a string) DialOption
    • func WithBackoffConfig(b BackoffConfig) DialOptiondeprecated
    • func WithBackoffMaxDelay(md time.Duration) DialOptiondeprecated
    • func WithBlock() DialOption
    • func WithChainStreamInterceptor(interceptors …StreamClientInterceptor) DialOption
    • func WithChainUnaryInterceptor(interceptors …UnaryClientInterceptor) DialOption
    • func WithChannelzParentID(id *channelz.Identifier) DialOption
    • func WithCodec(c Codec) DialOptiondeprecated
    • func WithCompressor(cp Compressor) DialOptiondeprecated
    • func WithConnectParams(p ConnectParams) DialOption
    • func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption
    • func WithCredentialsBundle(b credentials.Bundle) DialOption
    • func WithDecompressor(dc Decompressor) DialOptiondeprecated
    • func WithDefaultCallOptions(cos …CallOption) DialOption
    • func WithDefaultServiceConfig(s string) DialOption
    • func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOptiondeprecated
    • func WithDisableHealthCheck() DialOption
    • func WithDisableRetry() DialOption
    • func WithDisableServiceConfig() DialOption
    • func WithInitialConnWindowSize(s int32) DialOption
    • func WithInitialWindowSize(s int32) DialOption
    • func WithInsecure() DialOptiondeprecated
    • func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption
    • func WithMaxHeaderListSize(s uint32) DialOption
    • func WithMaxMsgSize(s int) DialOptiondeprecated
    • func WithNoProxy() DialOption
    • func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
    • func WithReadBufferSize(s int) DialOption
    • func WithResolvers(rs …resolver.Builder) DialOption
    • func WithReturnConnectionError() DialOption
    • func WithServiceConfig(c <-chan ServiceConfig) DialOptiondeprecated
    • func WithStatsHandler(h stats.Handler) DialOption
    • func WithStreamInterceptor(f StreamClientInterceptor) DialOption
    • func WithTimeout(d time.Duration) DialOptiondeprecated
    • func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
    • func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption
    • func WithUserAgent(s string) DialOption
    • func WithWriteBufferSize(s int) DialOption
  • type EmptyCallOption
  • type EmptyDialOption
  • type EmptyServerOption
  • type FailFastCallOption
  • type ForceCodecCallOption
  • type HeaderCallOption
  • type MaxRecvMsgSizeCallOption
  • type MaxRetryRPCBufferSizeCallOption
  • type MaxSendMsgSizeCallOption
  • type MethodConfigdeprecated
  • type MethodDesc
  • type MethodInfo
  • type PeerCallOption
  • type PerRPCCredsCallOption
  • type PreparedMsg
    • func (p *PreparedMsg) Encode(s Stream, msg interface{}) error
  • type Server
    • func NewServer(opt …ServerOption) *Server
    • func (s *Server) GetServiceInfo() map[string]ServiceInfo
    • func (s *Server) GracefulStop()
    • func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
    • func (s *Server) Serve(lis net.Listener) error
    • func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
    • func (s *Server) Stop()
  • type ServerOption
    • func ChainStreamInterceptor(interceptors …StreamServerInterceptor) ServerOption
    • func ChainUnaryInterceptor(interceptors …UnaryServerInterceptor) ServerOption
    • func ConnectionTimeout(d time.Duration) ServerOption
    • func Creds(c credentials.TransportCredentials) ServerOption
    • func CustomCodec(codec Codec) ServerOptiondeprecated
    • func ForceServerCodec(codec encoding.Codec) ServerOption
    • func HeaderTableSize(s uint32) ServerOption
    • func InTapHandle(h tap.ServerInHandle) ServerOption
    • func InitialConnWindowSize(s int32) ServerOption
    • func InitialWindowSize(s int32) ServerOption
    • func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption
    • func KeepaliveParams(kp keepalive.ServerParameters) ServerOption
    • func MaxConcurrentStreams(n uint32) ServerOption
    • func MaxHeaderListSize(s uint32) ServerOption
    • func MaxMsgSize(m int) ServerOptiondeprecated
    • func MaxRecvMsgSize(m int) ServerOption
    • func MaxSendMsgSize(m int) ServerOption
    • func NumStreamWorkers(numServerWorkers uint32) ServerOption
    • func RPCCompressor(cp Compressor) ServerOptiondeprecated
    • func RPCDecompressor(dc Decompressor) ServerOptiondeprecated
    • func ReadBufferSize(s int) ServerOption
    • func StatsHandler(h stats.Handler) ServerOption
    • func StreamInterceptor(i StreamServerInterceptor) ServerOption
    • func UnaryInterceptor(i UnaryServerInterceptor) ServerOption
    • func UnknownServiceHandler(streamHandler StreamHandler) ServerOption
    • func WriteBufferSize(s int) ServerOption
  • type ServerStream
  • type ServerTransportStream
    • func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream
  • type ServiceConfigdeprecated
  • type ServiceDesc
  • type ServiceInfo
  • type ServiceRegistrar
  • type Streamdeprecated
  • type StreamClientInterceptor
  • type StreamDesc
  • type StreamHandler
  • type StreamServerInfo
  • type StreamServerInterceptor
  • type Streamer
  • type TrailerCallOption
  • type UnaryClientInterceptor
  • type UnaryHandler
  • type UnaryInvoker
  • type UnaryServerInfo
  • type UnaryServerInterceptor

View Source

const (
	SupportPackageIsVersion3 = true
	SupportPackageIsVersion4 = true
	SupportPackageIsVersion5 = true
	SupportPackageIsVersion6 = true
	SupportPackageIsVersion7 = true
)

The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 7.

Older versions are kept for compatibility.

These constants should not be referenced from any other code.

PickFirstBalancerName is the name of the pick_first balancer.

Version is the current grpc version.

DefaultBackoffConfig uses values specified for backoff in
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

Deprecated: use ConnectParams instead. Will be supported throughout 1.x.

EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package.
This should only be set before any RPCs are sent or received by this program.

ErrClientConnTimeout indicates that the ClientConn cannot establish the
underlying connections within the specified timeout.

Deprecated: This error is never returned by grpc and should not be
referenced by users.

ErrServerStopped indicates that the operation is now illegal because of
the server being stopped.

Code returns the error code for err if it was produced by the rpc system.
Otherwise, it returns codes.Unknown.

Deprecated: use status.Code instead.

ErrorDesc returns the error description of err if it was produced by the rpc system.
Otherwise, it returns err.Error() or empty string when err is nil.

Deprecated: use status.Convert and Message method instead.

Errorf returns an error containing an error code and a description;
Errorf returns nil if c is OK.

Deprecated: use status.Errorf instead.

Invoke sends the RPC request on the wire and returns after response is
received. This is typically called by generated code.

DEPRECATED: Use ClientConn.Invoke instead.

Method returns the method string for the server context. The returned
string is in the format of «/service/method».

MethodFromServerStream returns the method string for the input stream.
The returned string is in the format of «/service/method».

NewContextWithServerTransportStream creates a new context from ctx and
attaches stream to it.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

SendHeader sends header metadata. It may be called at most once, and may not
be called after any event that causes headers to be sent (see SetHeader for
a complete list). The provided md and headers set by SetHeader() will be
sent.

The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.

SetHeader sets the header metadata to be sent from the server to the client.
The context provided must be the context passed to the server’s handler.

Streaming RPCs should prefer the SetHeader method of the ServerStream.

When called multiple times, all the provided metadata will be merged. All
the metadata will be sent out when one of the following happens:

  • grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  • The first response message is sent. For unary handlers, this occurs when
    the handler returns; for streaming handlers, this can happen when stream’s
    SendMsg method is called.
  • An RPC status is sent out (error or success). This occurs when the handler
    returns.

SetHeader will fail if called after any of the events above.

The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.

SetTrailer sets the trailer metadata that will be sent when an RPC returns.
When called more than once, all the provided metadata will be merged.

The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.

BackoffConfig defines the parameters for the default gRPC backoff strategy.

Deprecated: use ConnectParams instead. Will be supported throughout 1.x.

type CallOption interface {
	
}

CallOption configures a Call before it starts or extracts information from
a Call after it completes.

func CallContentSubtype ¶

added in
v1.10.0


func CallContentSubtype(contentSubtype string) CallOption

CallContentSubtype returns a CallOption that will set the content-subtype
for a call. For example, if content-subtype is «json», the Content-Type over
the wire will be «application/grpc+json». The content-subtype is converted
to lowercase before being included in Content-Type. See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details.

If ForceCodec is not also used, the content-subtype will be used to look up
the Codec to use in the registry controlled by RegisterCodec. See the
documentation on RegisterCodec for details on registration. The lookup of
content-subtype is case-insensitive. If no such Codec is found, the call
will result in an error with code codes.Internal.

If ForceCodec is also used, that Codec will be used for all request and
response messages, with the content-subtype set to the given contentSubtype
here for requests.

func CallCustomCodec(codec Codec) CallOption

CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
an encoding.Codec.

Deprecated: use ForceCodec instead.

func FailFast(failFast bool) CallOption

FailFast is the opposite of WaitForReady.

Deprecated: use WaitForReady.

ForceCodec returns a CallOption that will set codec to be used for all
request and response messages for a call. The result of calling Name() will
be used as the content-subtype after converting to lowercase, unless
CallContentSubtype is also used.

See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details. Also see the documentation on RegisterCodec and
CallContentSubtype for more details on the interaction between Codec and
content-subtype.

This function is provided for advanced users; prefer to use only
CallContentSubtype to select a registered codec instead.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

Header returns a CallOptions that retrieves the header metadata
for a unary RPC.

func MaxCallRecvMsgSize(bytes int) CallOption

MaxCallRecvMsgSize returns a CallOption which sets the maximum message size
in bytes the client can receive. If this is not set, gRPC uses the default
4MB.

func MaxCallSendMsgSize(bytes int) CallOption

MaxCallSendMsgSize returns a CallOption which sets the maximum message size
in bytes the client can send. If this is not set, gRPC uses the default
`math.MaxInt32`.

func MaxRetryRPCBufferSize(bytes int) CallOption

MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
used for buffering this RPC’s requests for retry purposes.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

Peer returns a CallOption that retrieves peer information for a unary RPC.
The peer field will be populated *after* the RPC completes.

PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
for a call.

Trailer returns a CallOptions that retrieves the trailer metadata
for a unary RPC.

UseCompressor returns a CallOption which sets the compressor used when
sending the request. If WithCompressor is also set, UseCompressor has
higher priority.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WaitForReady(waitForReady bool) CallOption

WaitForReady configures the action to take when an RPC is attempted on broken
connections or unreachable servers. If waitForReady is false and the
connection is in the TRANSIENT_FAILURE state, the RPC will fail
immediately. Otherwise, the RPC client will block the call until a
connection is available (or the call is canceled or times out) and will
retry the call if it fails due to a transient error. gRPC will not retry if
data was written to the wire unless the server indicates it did not process
the data. Please refer to
https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.

By default, RPCs don’t «wait for ready».

type ClientConn struct {
	
}

ClientConn represents a virtual connection to a conceptual endpoint, to
perform RPCs.

A ClientConn is free to have zero or more actual connections to the endpoint
based on configuration, load, etc. It is also free to determine which actual
endpoints to use and may change it every RPC, permitting client-side load
balancing.

A ClientConn encapsulates a range of functionality including name
resolution, TCP connection establishment (with retries and backoff) and TLS
handshakes. It also handles errors on established connections by
re-resolving the name and reconnecting.

Dial creates a client connection to the given target.

DialContext creates a client connection to the given target. By default, it’s
a non-blocking dial (the function won’t wait for connections to be
established, and connecting happens in the background). To make it a blocking
dial, use WithBlock() dial option.

In the non-blocking case, the ctx does not act against the connection. It
only controls the setup steps.

In the blocking case, ctx can be used to cancel or expire the pending
connection. Once this function returns, the cancellation and expiration of
ctx will be noop. Users should call ClientConn.Close to terminate all the
pending operations after this function returns.

The target name syntax is defined in
https://github.com/grpc/grpc/blob/master/doc/naming.md.
e.g. to use dns resolver, a «dns:///» prefix should be applied to the target.

Close tears down the ClientConn and all underlying connections.

func (cc *ClientConn) Connect()

Connect causes all subchannels in the ClientConn to attempt to connect if
the channel is idle. Does not wait for the connection attempts to begin
before returning.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a later
release.

func (cc *ClientConn) GetMethodConfig(method string) MethodConfig

GetMethodConfig gets the method config of the input method.
If there’s an exact match for input method (i.e. /service/method), we return
the corresponding MethodConfig.
If there isn’t an exact match for the input method, we look for the service’s default
config under the service (i.e /service/) and then for the default for all services (empty string).

If there is a default MethodConfig for the service, we return it.
Otherwise, we return an empty MethodConfig.

GetState returns the connectivity.State of ClientConn.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a later
release.

Invoke sends the RPC request on the wire and returns after response is
received. This is typically called by generated code.

All errors returned by Invoke are compatible with the status package.

NewStream creates a new Stream for the client side. This is typically
called by generated code. ctx is used for the lifetime of the stream.

To ensure resources are not leaked due to the stream returned, one of the following
actions must be performed:

  1. Call Close on the ClientConn.
  2. Cancel the context provided.
  3. Call RecvMsg until a non-nil error is returned. A protobuf-generated
    client-streaming RPC, for instance, might use the helper function
    CloseAndRecv (note that CloseSend does not Recv, therefore is not
    guaranteed to release all resources).
  4. Receive a non-nil, non-io.EOF error from Header or SendMsg.

If none of the above happen, a goroutine and a context will be leaked, and grpc
will not call the optionally-configured stats handler with a stats.End message.

func (cc *ClientConn) ResetConnectBackoff()

ResetConnectBackoff wakes up all subchannels in transient failure and causes
them to attempt another connection immediately. It also resets the backoff
times used for subsequent attempts regardless of the current state.

In general, this function should not be used. Typical service or network
outages result in a reasonable client reconnection strategy by default.
However, if a previously unavailable network becomes available, this may be
used to trigger an immediate reconnect.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

Target returns the target string of the ClientConn.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
ctx expires. A true value is returned in former case and false in latter.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

ClientConnInterface defines the functions clients need to perform unary and
streaming RPCs. It is implemented by *ClientConn, and is only intended to
be referenced by generated code.

ClientStream defines the client-side behavior of a streaming RPC.

All errors returned from ClientStream methods are compatible with the
status package.

NewClientStream is a wrapper for ClientConn.NewStream.

type Codec interface {
	
	Marshal(v interface{}) ([]byte, error)
	
	Unmarshal(data []byte, v interface{}) error
	
	
	String() string
}

Codec defines the interface gRPC uses to encode and decode messages.
Note that implementations of this interface must be thread safe;
a Codec’s methods can be called from concurrent goroutines.

Deprecated: use encoding.Codec instead.

Compressor defines the interface gRPC uses to compress a message.

Deprecated: use package encoding.

func NewGZIPCompressor() Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

Deprecated: use package encoding/gzip.

func NewGZIPCompressorWithLevel(level int) (Compressor, error)

NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
of assuming DefaultCompression.

The error returned will be nil if the level is valid.

Deprecated: use package encoding/gzip.

type CompressorCallOption struct {
	CompressorType string
}

CompressorCallOption is a CallOption that indicates the compressor to use.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

ConnectParams defines the parameters for connecting and retrying. Users are
encouraged to use this instead of the BackoffConfig type defined above. See
here for more details:
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type ContentSubtypeCallOption ¶

added in
v1.11.0


type ContentSubtypeCallOption struct {
	ContentSubtype string
}

ContentSubtypeCallOption is a CallOption that indicates the content-subtype
used for marshaling messages.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type CustomCodecCallOption struct {
	Codec Codec
}

CustomCodecCallOption is a CallOption that indicates the codec used for
marshaling messages.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

Decompressor defines the interface gRPC uses to decompress a message.

Deprecated: use package encoding.

func NewGZIPDecompressor() Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

Deprecated: use package encoding/gzip.

type DialOption interface {
	
}

DialOption configures how we set up the connection.

func FailOnNonTempDialError(f bool) DialOption

FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
non-temporary dial errors. If f is true, and dialer returns a non-temporary
error, gRPC will fail the connection to the network address and won’t try to
reconnect. The default value of FailOnNonTempDialError is false.

FailOnNonTempDialError only affects the initial dial, and does not do
anything useful unless you are also using WithBlock().

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

WithAuthority returns a DialOption that specifies the value to be used as the
:authority pseudo-header and as the server name in authentication handshake.

func WithBackoffConfig(b BackoffConfig) DialOption

WithBackoffConfig configures the dialer to use the provided backoff
parameters after connection failures.

Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.

WithBackoffMaxDelay configures the dialer to use the provided maximum delay
when backing off after failed connection attempts.

Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.

func WithBlock() DialOption

WithBlock returns a DialOption which makes callers of Dial block until the
underlying connection is up. Without this, Dial returns immediately and
connecting the server happens in background.

func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption

WithChainStreamInterceptor returns a DialOption that specifies the chained
interceptor for streaming RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All interceptors added by this method will be chained, and the interceptor
defined by WithStreamInterceptor will always be prepended to the chain.

func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption

WithChainUnaryInterceptor returns a DialOption that specifies the chained
interceptor for unary RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All interceptors added by this method will be chained, and the interceptor
defined by WithUnaryInterceptor will always be prepended to the chain.

WithChannelzParentID returns a DialOption that specifies the channelz ID of
current ClientConn’s parent. This function is used in nested channel creation
(e.g. grpclb dial).

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WithCodec(c Codec) DialOption

WithCodec returns a DialOption which sets a codec for message marshaling and
unmarshaling.

Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be
supported throughout 1.x.

func WithCompressor(cp Compressor) DialOption

WithCompressor returns a DialOption which sets a Compressor to use for
message compression. It has lower priority than the compressor set by the
UseCompressor CallOption.

Deprecated: use UseCompressor instead. Will be supported throughout 1.x.

func WithConnectParams(p ConnectParams) DialOption

WithConnectParams configures the ClientConn to use the provided ConnectParams
for creating and maintaining connections to servers.

The backoff configuration specified as part of the ConnectParams overrides
all defaults specified in
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider
using the backoff.DefaultConfig as a base, in cases where you want to
override only a subset of the backoff configuration.

WithContextDialer returns a DialOption that sets a dialer to create
connections. If FailOnNonTempDialError() is set to true, and an error is
returned by f, gRPC checks the error’s Temporary() method to decide if it
should try to reconnect to the network address.

WithCredentialsBundle returns a DialOption to set a credentials bundle for
the ClientConn.WithCreds. This should not be used together with
WithTransportCredentials.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WithDecompressor(dc Decompressor) DialOption

WithDecompressor returns a DialOption which sets a Decompressor to use for
incoming message decompression. If incoming response messages are encoded
using the decompressor’s Type(), it will be used. Otherwise, the message
encoding will be used to look up the compressor registered via
encoding.RegisterCompressor, which will then be used to decompress the
message. If no compressor is registered for the encoding, an Unimplemented
status error will be returned.

Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.

func WithDefaultCallOptions(cos ...CallOption) DialOption

WithDefaultCallOptions returns a DialOption which sets the default
CallOptions for calls over the connection.

func WithDefaultServiceConfig(s string) DialOption

WithDefaultServiceConfig returns a DialOption that configures the default
service config, which will be used in cases where:

1. WithDisableServiceConfig is also used, or

2. The name resolver does not provide a service config or provides an
invalid service config.

The parameter s is the JSON representation of the default service config.
For more information about service configs, see:
https://github.com/grpc/grpc/blob/master/doc/service_config.md
For a simple example of usage, see:
examples/features/load_balancing/client/main.go

WithDialer returns a DialOption that specifies a function to use for dialing
network addresses. If FailOnNonTempDialError() is set to true, and an error
is returned by f, gRPC checks the error’s Temporary() method to decide if it
should try to reconnect to the network address.

Deprecated: use WithContextDialer instead. Will be supported throughout
1.x.

func WithDisableHealthCheck() DialOption

WithDisableHealthCheck disables the LB channel health checking for all
SubConns of this ClientConn.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WithDisableRetry() DialOption

WithDisableRetry returns a DialOption that disables retries, even if the
service config enables them. This does not impact transparent retries, which
will happen automatically if no data is written to the wire or if the RPC is
unprocessed by the remote server.

func WithDisableServiceConfig() DialOption

WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any
service config provided by the resolver and provides a hint to the resolver
to not fetch service configs.

Note that this dial option only disables service config from resolver. If
default service config is provided, gRPC will use the default service config.

func WithInitialConnWindowSize(s int32) DialOption

WithInitialConnWindowSize returns a DialOption which sets the value for
initial window size on a connection. The lower bound for window size is 64K
and any value smaller than that will be ignored.

func WithInitialWindowSize(s int32) DialOption

WithInitialWindowSize returns a DialOption which sets the value for initial
window size on a stream. The lower bound for window size is 64K and any value
smaller than that will be ignored.

func WithInsecure() DialOption

WithInsecure returns a DialOption which disables transport security for this
ClientConn. Under the hood, it uses insecure.NewCredentials().

Note that using this DialOption with per-RPC credentials (through
WithCredentialsBundle or WithPerRPCCredentials) which require transport
security is incompatible and will cause grpc.Dial() to fail.

Deprecated: use WithTransportCredentials and insecure.NewCredentials()
instead. Will be supported throughout 1.x.

WithKeepaliveParams returns a DialOption that specifies keepalive parameters
for the client transport.

func WithMaxHeaderListSize(s uint32) DialOption

WithMaxHeaderListSize returns a DialOption that specifies the maximum
(uncompressed) size of header list that the client is prepared to accept.

func WithMaxMsgSize(s int) DialOption

WithMaxMsgSize returns a DialOption which sets the maximum message size the
client can receive.

Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will
be supported throughout 1.x.

func WithNoProxy() DialOption

WithNoProxy returns a DialOption which disables the use of proxies for this
ClientConn. This is ignored if WithDialer or WithContextDialer are used.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

WithPerRPCCredentials returns a DialOption which sets credentials and places
auth state on each outbound RPC.

func WithReadBufferSize(s int) DialOption

WithReadBufferSize lets you set the size of read buffer, this determines how
much data can be read at most for each read syscall.

The default value for this buffer is 32KB. Zero or negative values will
disable read buffer for a connection so data framer can access the
underlying conn directly.

WithResolvers allows a list of resolver implementations to be registered
locally with the ClientConn without needing to be globally registered via
resolver.Register. They will be matched against the scheme used for the
current Dial only, and will take precedence over the global registry.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WithReturnConnectionError() DialOption

WithReturnConnectionError returns a DialOption which makes the client connection
return a string containing both the last connection error that occurred and
the context.DeadlineExceeded error.
Implies WithBlock()

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func WithServiceConfig(c <-chan ServiceConfig) DialOption

WithServiceConfig returns a DialOption which has a channel to read the
service configuration.

Deprecated: service config should be received through name resolver or via
WithDefaultServiceConfig, as specified at
https://github.com/grpc/grpc/blob/master/doc/service_config.md. Will be
removed in a future 1.x release.

func WithStatsHandler ¶

added in
v1.2.0


WithStatsHandler returns a DialOption that specifies the stats handler for
all the RPCs and underlying network connections in this ClientConn.

func WithStreamInterceptor(f StreamClientInterceptor) DialOption

WithStreamInterceptor returns a DialOption that specifies the interceptor for
streaming RPCs.

WithTimeout returns a DialOption that configures a timeout for dialing a
ClientConn initially. This is valid if and only if WithBlock() is present.

Deprecated: use DialContext instead of Dial and context.WithTimeout
instead. Will be supported throughout 1.x.

WithTransportCredentials returns a DialOption which configures a connection
level security credentials (e.g., TLS/SSL). This should not be used together
with WithCredentialsBundle.

func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption

WithUnaryInterceptor returns a DialOption that specifies the interceptor for
unary RPCs.

WithUserAgent returns a DialOption that specifies a user agent string for all
the RPCs.

func WithWriteBufferSize(s int) DialOption

WithWriteBufferSize determines how much data can be batched before doing a
write on the wire. The corresponding memory allocation for this buffer will
be twice the size to keep syscalls low. The default value for this buffer is
32KB.

Zero or negative values will disable the write buffer such that each write
will be on underlying connection. Note: A Send call may not directly
translate to a write.

type EmptyCallOption struct{}

EmptyCallOption does not alter the Call configuration.
It can be embedded in another structure to carry satellite data for use
by interceptors.

type EmptyDialOption struct{}

EmptyDialOption does not alter the dial configuration. It can be embedded in
another structure to build custom dial options.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type EmptyServerOption struct{}

EmptyServerOption does not alter the server configuration. It can be embedded
in another structure to build custom server options.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type FailFastCallOption struct {
	FailFast bool
}

FailFastCallOption is a CallOption for indicating whether an RPC should fail
fast or not.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

ForceCodecCallOption is a CallOption that indicates the codec used for
marshaling messages.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type HeaderCallOption struct {
}

HeaderCallOption is a CallOption for collecting response header metadata.
The metadata field will be populated *after* the RPC completes.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type MaxRecvMsgSizeCallOption struct {
	MaxRecvMsgSize int
}

MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
size in bytes the client can receive.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type MaxRetryRPCBufferSizeCallOption struct {
	MaxRetryRPCBufferSize int
}

MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
memory to be used for caching this RPC for retry purposes.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type MaxSendMsgSizeCallOption struct {
	MaxSendMsgSize int
}

MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
size in bytes the client can send.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type MethodDesc struct {
	MethodName string
	Handler    methodHandler
}

MethodDesc represents an RPC service’s method specification.

type MethodInfo struct {
	
	Name string
	
	IsClientStream bool
	
	IsServerStream bool
}

MethodInfo contains the information of an RPC including its method name and type.

type PeerCallOption struct {
	PeerAddr *peer.Peer
}

PeerCallOption is a CallOption for collecting the identity of the remote
peer. The peer field will be populated *after* the RPC completes.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

PerRPCCredsCallOption is a CallOption that indicates the per-RPC
credentials to use for the call.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

type PreparedMsg struct {
	
}

PreparedMsg is responsible for creating a Marshalled and Compressed object.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

func (p *PreparedMsg) Encode(s Stream, msg interface{}) error

Encode marshalls and compresses the message using the codec and compressor for the stream.

Server is a gRPC server to serve RPC requests.

func NewServer(opt ...ServerOption) *Server

NewServer creates a gRPC server which has no service registered and has not
started to accept requests yet.

func (s *Server) GetServiceInfo() map[string]ServiceInfo

GetServiceInfo returns a map from service names to ServiceInfo.
Service names include the package names, in the form of <package>.<service>.

func (s *Server) GracefulStop()

GracefulStop stops the gRPC server gracefully. It stops the server from
accepting new connections and RPCs and blocks until all the pending RPCs are
finished.

func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})

RegisterService registers a service and its implementation to the gRPC
server. It is called from the IDL generated code. This must be called before
invoking Serve. If ss is non-nil (for legacy code), its type is checked to
ensure it implements sd.HandlerType.

Serve accepts incoming connections on the listener lis, creating a new
ServerTransport and service goroutine for each. The service goroutines
read gRPC requests and then call the registered handlers to reply to them.
Serve returns when lis.Accept fails with fatal errors. lis will be closed when
this method returns.
Serve will return a non-nil error unless Stop or GracefulStop is called.

ServeHTTP implements the Go standard library’s http.Handler
interface by responding to the gRPC request r, by looking up
the requested gRPC method in the gRPC server s.

The provided HTTP request must have arrived on an HTTP/2
connection. When using the Go standard library’s server,
practically this means that the Request must also have arrived
over TLS.

To share one port (such as 443 for https) between gRPC and an
existing http.Handler, use a root http.Handler such as:

if r.ProtoMajor == 2 && strings.HasPrefix(
	r.Header.Get("Content-Type"), "application/grpc") {
	grpcServer.ServeHTTP(w, r)
} else {
	yourMux.ServeHTTP(w, r)
}

Note that ServeHTTP uses Go’s HTTP/2 server implementation which is totally
separate from grpc-go’s HTTP/2 server. Performance and features may vary
between the two paths. ServeHTTP does not support some gRPC features
available through grpc-go’s HTTP/2 server.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

Stop stops the gRPC server. It immediately closes all open
connections and listeners.
It cancels all active RPCs on the server side and the corresponding
pending RPCs on the client side will get notified by connection
errors.

type ServerOption interface {
	
}

A ServerOption sets options such as credentials, codec and keepalive parameters, etc.

func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption

ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor
for streaming RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All stream interceptors added by this method will be chained.

func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption

ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor
for unary RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All unary interceptors added by this method will be chained.

ConnectionTimeout returns a ServerOption that sets the timeout for
connection establishment (up to and including HTTP/2 handshaking) for all
new connections. If this is not set, the default is 120 seconds. A zero or
negative value will result in an immediate timeout.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

Creds returns a ServerOption that sets credentials for server connections.

func CustomCodec(codec Codec) ServerOption

CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.

This will override any lookups by content-subtype for Codecs registered with RegisterCodec.

Deprecated: register codecs using encoding.RegisterCodec. The server will
automatically use registered codecs based on the incoming requests’ headers.
See also
https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
Will be supported throughout 1.x.

ForceServerCodec returns a ServerOption that sets a codec for message
marshaling and unmarshaling.

This will override any lookups by content-subtype for Codecs registered
with RegisterCodec.

See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details. Also see the documentation on RegisterCodec and
CallContentSubtype for more details on the interaction between encoding.Codec
and content-subtype.

This function is provided for advanced users; prefer to register codecs
using encoding.RegisterCodec.
The server will automatically use registered codecs based on the incoming
requests’ headers. See also
https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
Will be supported throughout 1.x.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

HeaderTableSize returns a ServerOption that sets the size of dynamic
header table for stream.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func InTapHandle ¶

added in
v1.0.5


InTapHandle returns a ServerOption that sets the tap handle for all the server
transport to be created. Only one can be installed.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func InitialConnWindowSize(s int32) ServerOption

InitialConnWindowSize returns a ServerOption that sets window size for a connection.
The lower bound for window size is 64K and any value smaller than that will be ignored.

func InitialWindowSize(s int32) ServerOption

InitialWindowSize returns a ServerOption that sets window size for stream.
The lower bound for window size is 64K and any value smaller than that will be ignored.

KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.

KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.

func MaxConcurrentStreams(n uint32) ServerOption

MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
of concurrent streams to each ServerTransport.

MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size
of header list that the server is prepared to accept.

func MaxMsgSize(m int) ServerOption

MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
If this is not set, gRPC uses the default limit.

Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x.

func MaxRecvMsgSize(m int) ServerOption

MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
If this is not set, gRPC uses the default 4MB.

func MaxSendMsgSize(m int) ServerOption

MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
If this is not set, gRPC uses the default `math.MaxInt32`.

func NumStreamWorkers(numServerWorkers uint32) ServerOption

NumStreamWorkers returns a ServerOption that sets the number of worker
goroutines that should be used to process incoming streams. Setting this to
zero (default) will disable workers and spawn a new goroutine for each
stream.

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

func RPCCompressor(cp Compressor) ServerOption

RPCCompressor returns a ServerOption that sets a compressor for outbound
messages. For backward compatibility, all outbound messages will be sent
using this compressor, regardless of incoming message compression. By
default, server messages will be sent using the same compressor with which
request messages were sent.

Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.

func RPCDecompressor(dc Decompressor) ServerOption

RPCDecompressor returns a ServerOption that sets a decompressor for inbound
messages. It has higher priority than decompressors registered via
encoding.RegisterCompressor.

Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.

func ReadBufferSize(s int) ServerOption

ReadBufferSize lets you set the size of read buffer, this determines how much
data can be read at most for one read syscall. The default value for this
buffer is 32KB. Zero or negative values will disable read buffer for a
connection so data framer can access the underlying conn directly.

func StatsHandler ¶

added in
v1.2.0


StatsHandler returns a ServerOption that sets the stats handler for the server.

func StreamInterceptor(i StreamServerInterceptor) ServerOption

StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
server. Only one stream interceptor can be installed.

func UnaryInterceptor(i UnaryServerInterceptor) ServerOption

UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
server. Only one unary interceptor can be installed. The construction of multiple
interceptors (e.g., chaining) can be implemented at the caller.

func UnknownServiceHandler ¶

added in
v1.2.0


func UnknownServiceHandler(streamHandler StreamHandler) ServerOption

UnknownServiceHandler returns a ServerOption that allows for adding a custom
unknown service handler. The provided method is a bidi-streaming RPC service
handler that will be invoked instead of returning the «unimplemented» gRPC
error whenever a request is received for an unregistered service or method.
The handling function and stream interceptor (if set) have full access to
the ServerStream, including its Context.

func WriteBufferSize(s int) ServerOption

WriteBufferSize determines how much data can be batched before doing a write
on the wire. The corresponding memory allocation for this buffer will be
twice the size to keep syscalls low. The default value for this buffer is
32KB. Zero or negative values will disable the write buffer such that each
write will be on underlying connection.
Note: A Send call may not directly translate to a write.

ServerStream defines the server-side behavior of a streaming RPC.

Errors returned from ServerStream methods are compatible with the status
package. However, the status code will often not match the RPC status as
seen by the client application, and therefore, should not be relied upon for
this purpose.

ServerTransportStream is a minimal interface that a transport stream must
implement. This can be used to mock an actual transport stream for tests of
handler code that use, for example, grpc.SetHeader (which requires some
stream to be in context).

See also NewContextWithServerTransportStream.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

ServerTransportStreamFromContext returns the ServerTransportStream saved in
ctx. Returns nil if the given context has no stream associated with it
(which implies it is not an RPC invocation context).

Experimental ¶

Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.

ServiceConfig is provided by the service provider and contains parameters for how
clients that connect to the service should behave.

Deprecated: Users should not use this struct. Service config should be received
through name resolver, as specified here
https://github.com/grpc/grpc/blob/master/doc/service_config.md

type ServiceDesc struct {
	ServiceName string
	
	
	HandlerType interface{}
	Methods     []MethodDesc
	Streams     []StreamDesc
	Metadata    interface{}
}

ServiceDesc represents an RPC service’s specification.

type ServiceInfo struct {
	Methods []MethodInfo
	
	Metadata interface{}
}

ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.

type ServiceRegistrar interface {
	
	
	
	
	
	RegisterService(desc *ServiceDesc, impl interface{})
}

ServiceRegistrar wraps a single method that supports service registration. It
enables users to pass concrete types other than grpc.Server to the service
registration methods exported by the IDL generated code.

Stream defines the common interface a client or server stream has to satisfy.

Deprecated: See ClientStream and ServerStream documentation instead.

StreamClientInterceptor intercepts the creation of a ClientStream. Stream
interceptors can be specified as a DialOption, using WithStreamInterceptor()
or WithChainStreamInterceptor(), when creating a ClientConn. When a stream
interceptor(s) is set on the ClientConn, gRPC delegates all stream creations
to the interceptor, and it is the responsibility of the interceptor to call
streamer.

desc contains a description of the stream. cc is the ClientConn on which the
RPC was invoked. streamer is the handler to create a ClientStream and it is
the responsibility of the interceptor to call it. opts contain all applicable
call options, including defaults from the ClientConn as well as per-call
options.

StreamClientInterceptor may return a custom ClientStream to intercept all I/O
operations. The returned error must be compatible with the status package.

type StreamDesc struct {
	
	
	StreamName string        
	Handler    StreamHandler 

	
	
	
	ServerStreams bool 
	ClientStreams bool 
}

StreamDesc represents a streaming RPC service’s method specification. Used
on the server when registering services and on the client when initiating
new streams.

type StreamHandler ¶


type StreamHandler func(srv interface{}, stream ServerStream) error

StreamHandler defines the handler called by gRPC server to complete the
execution of a streaming RPC.

If a StreamHandler returns an error, it should either be produced by the
status package, or be one of the context errors. Otherwise, gRPC will use
codes.Unknown as the status code and err.Error() as the status message of the
RPC.

type StreamServerInfo struct {
	
	FullMethod string
	
	IsClientStream bool
	
	IsServerStream bool
}

StreamServerInfo consists of various information about a streaming RPC on
server side. All per-rpc information may be mutated by the interceptor.

type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error

StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.
info contains all the information of this RPC the interceptor can operate on. And handler is the
service method implementation. It is the responsibility of the interceptor to invoke handler to
complete the RPC.

Streamer is called by StreamClientInterceptor to create a ClientStream.

type TrailerCallOption struct {
	TrailerAddr *metadata.MD
}

TrailerCallOption is a CallOption for collecting response trailer metadata.
The metadata field will be populated *after* the RPC completes.

Experimental ¶

Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.

UnaryClientInterceptor intercepts the execution of a unary RPC on the client.
Unary interceptors can be specified as a DialOption, using
WithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating a
ClientConn. When a unary interceptor(s) is set on a ClientConn, gRPC
delegates all unary RPC invocations to the interceptor, and it is the
responsibility of the interceptor to call invoker to complete the processing
of the RPC.

method is the RPC name. req and reply are the corresponding request and
response messages. cc is the ClientConn on which the RPC was invoked. invoker
is the handler to complete the RPC and it is the responsibility of the
interceptor to call it. opts contain all applicable call options, including
defaults from the ClientConn as well as per-call options.

The returned error must be compatible with the status package.

type UnaryHandler ¶


UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal
execution of a unary RPC.

If a UnaryHandler returns an error, it should either be produced by the
status package, or be one of the context errors. Otherwise, gRPC will use
codes.Unknown as the status code and err.Error() as the status message of the
RPC.

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

type UnaryServerInfo struct {
	
	Server interface{}
	
	FullMethod string
}

UnaryServerInfo consists of various information about a unary RPC on
server side. All per-rpc information may be mutated by the interceptor.

type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)

UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info
contains all the information of this RPC the interceptor can operate on. And handler is the wrapper
of the service method implementation. It is the responsibility of the interceptor to invoke handler
to complete the RPC.

I am using Hyperledger Fabric on Windows 10 when I start ./startFabric.sh file then following error is showing

 Error: proposal failed (err: rpc error: code = Unavailable desc = transport is closing)

 hyperledger Fabric v 1.3.0

 docker -v 2.0.0.0

 startFabric.sh file code is below

 #!/bin/bash # # Copyright IBM Corp All Rights Reserved # # SPDX-License-Identifier: Apache-2.0 # # Exit on first error set -e # don’t rewrite paths for Windows Git Bash users export MSYS_NO_PATHCONV=1 starttime=$(date +%s) LANGUAGE=${1:-«golang»} CC_SRC_PATH=github.com/fabcar/go if [ «$LANGUAGE» = «node» -o «$LANGUAGE» = «NODE» ]; then CC_SRC_PATH=/opt/gopath/src/github.com/fabcar/node fi # clean the keystore rm -rf ./hfc-key-store # launch network; create channel and join peer to channel cd ../basic-network ./start.sh # Now launch the CLI container in order to install, instantiate chaincode # and prime the ledger with our 10 cars docker-compose -f ./docker-compose.yml up -d cli docker exec -e «CORE_PEER_LOCALMSPID=Org1MSP» -e «CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp» cli peer chaincode install -n fabcar -v 1.0 -p «$CC_SRC_PATH» -l «$LANGUAGE» docker exec -e «CORE_PEER_LOCALMSPID=Org1MSP» -e «CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp» cli peer chaincode instantiate -o orderer.example.com:7050 -C mychannel -n fabcar -l «$LANGUAGE» -v 1.0 -c ‘{«Args»:[«»]}’ -P «OR (‘Org1MSP.member’,’Org2MSP.member’)» sleep 10 docker exec -e «CORE_PEER_LOCALMSPID=Org1MSP» -e «CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp» cli peer chaincode invoke -o orderer.example.com:7050 -C mychannel -n fabcar -c ‘{«function»:»initLedger»,»Args»:[«»]}’ printf «nTotal setup execution time : $(($(date +%s) — starttime)) secs …nnn» printf «Start by installing required packages run ‘npm install’n» printf «Then run ‘node enrollAdmin.js’, then ‘node registerUser’nn» printf «The ‘node invoke.js’ will fail until it has been updated with valid argumentsn» printf «The ‘node query.js’ may be run at anytime once the user has been registerednn»

Понравилась статья? Поделить с друзьями:
  • Failed to read rom error 0fl01 atiflash
  • Failed to read patcher version information black desert как исправить
  • Failed to read initialization file fortnite как исправить
  • Failed to read from socket error is 10060
  • Failed to read detroit become human error