Connect establishes a connection to coderd.
()
| 217 | |
| 218 | // Connect establishes a connection to coderd. |
| 219 | func (p *Server) connect() { |
| 220 | defer p.opts.Logger.Debug(p.closeContext, "connect loop exited") |
| 221 | defer p.wg.Done() |
| 222 | logConnect := p.opts.Logger.Debug |
| 223 | if p.externalProvisioner { |
| 224 | logConnect = p.opts.Logger.Info |
| 225 | } |
| 226 | // An exponential back-off occurs when the connection is failing to dial. |
| 227 | // This is to prevent server spam in case of a coderd outage. |
| 228 | connectLoop: |
| 229 | for retrier := retry.New(50*time.Millisecond, 10*time.Second); retrier.Wait(p.closeContext); { |
| 230 | // It's possible for the provisioner daemon to be shut down |
| 231 | // before the wait is complete! |
| 232 | if p.isClosed() { |
| 233 | return |
| 234 | } |
| 235 | p.opts.Logger.Debug(p.closeContext, "dialing coderd") |
| 236 | client, err := p.clientDialer(p.closeContext) |
| 237 | if err != nil { |
| 238 | if errors.Is(err, context.Canceled) { |
| 239 | return |
| 240 | } |
| 241 | var sdkErr *codersdk.Error |
| 242 | // If something is wrong with our auth, stop trying to connect. |
| 243 | if errors.As(err, &sdkErr) && sdkErr.StatusCode() == http.StatusForbidden { |
| 244 | p.opts.Logger.Error(p.closeContext, "not authorized to dial coderd", slog.Error(err)) |
| 245 | return |
| 246 | } |
| 247 | if p.isClosed() { |
| 248 | return |
| 249 | } |
| 250 | p.opts.Logger.Warn(p.closeContext, "coderd client failed to dial", slog.Error(err)) |
| 251 | continue |
| 252 | } |
| 253 | // This log is useful to verify that an external provisioner daemon is |
| 254 | // successfully connecting to coderd. It doesn't add much value if the |
| 255 | // daemon is built-in, so we only log it on the info level if p.externalProvisioner |
| 256 | // is true. This log message is mentioned in the docs: |
| 257 | // https://github.com/coder/coder/blob/5bd86cb1c06561d1d3e90ce689da220467e525c0/docs/admin/provisioners.md#L346 |
| 258 | logConnect(p.closeContext, "successfully connected to coderd") |
| 259 | retrier.Reset() |
| 260 | p.initConnectionOnce.Do(func() { |
| 261 | close(p.initConnectionCh) |
| 262 | }) |
| 263 | |
| 264 | // serve the client until we are closed or it disconnects |
| 265 | for { |
| 266 | select { |
| 267 | case <-p.closeContext.Done(): |
| 268 | client.DRPCConn().Close() |
| 269 | return |
| 270 | case <-client.DRPCConn().Closed(): |
| 271 | logConnect(p.closeContext, "connection to coderd closed") |
| 272 | continue connectLoop |
| 273 | case p.clientCh <- client: |
| 274 | continue |
| 275 | } |
| 276 | } |