(ctx context.Context, project *composetypes.Project)
| 249 | } |
| 250 | |
| 251 | func (d *Deployer) ensureNetworks(ctx context.Context, project *composetypes.Project) (map[string]string, error) { |
| 252 | ids := make(map[string]string) |
| 253 | |
| 254 | // Two listings: project-owned (for idempotent reuse) and external references. |
| 255 | // Project filter keeps the response small on hosts with many stacks. |
| 256 | ownedList, err := d.cli.NetworkList(ctx, client.NetworkListOptions{ |
| 257 | Filters: make(client.Filters).Add("label", labelComposeProject+"="+project.Name), |
| 258 | }) |
| 259 | if err != nil { |
| 260 | return nil, fmt.Errorf("listing networks: %w", err) |
| 261 | } |
| 262 | ownedByName := make(map[string]string, len(ownedList.Items)) |
| 263 | for _, n := range ownedList.Items { |
| 264 | ownedByName[n.Name] = n.ID |
| 265 | } |
| 266 | |
| 267 | // External networks are looked up unfiltered, on demand (they are not project-labeled). |
| 268 | var externalByName map[string]string |
| 269 | lookupExternalNet := func() error { |
| 270 | if externalByName != nil { |
| 271 | return nil |
| 272 | } |
| 273 | all, err := d.cli.NetworkList(ctx, client.NetworkListOptions{}) |
| 274 | if err != nil { |
| 275 | return fmt.Errorf("listing external networks: %w", err) |
| 276 | } |
| 277 | externalByName = make(map[string]string, len(all.Items)) |
| 278 | for _, n := range all.Items { |
| 279 | externalByName[n.Name] = n.ID |
| 280 | } |
| 281 | return nil |
| 282 | } |
| 283 | |
| 284 | for name, netCfg := range project.Networks { |
| 285 | if bool(netCfg.External) { |
| 286 | extName := netCfg.Name |
| 287 | if extName == "" { |
| 288 | extName = name |
| 289 | } |
| 290 | if err := lookupExternalNet(); err != nil { |
| 291 | return nil, err |
| 292 | } |
| 293 | id, ok := externalByName[extName] |
| 294 | if !ok { |
| 295 | return nil, fmt.Errorf("external network %q not found", extName) |
| 296 | } |
| 297 | ids[name] = id |
| 298 | continue |
| 299 | } |
| 300 | |
| 301 | fullName := netCfg.Name |
| 302 | if fullName == "" { |
| 303 | fullName = project.Name + "_" + name |
| 304 | } |
| 305 | |
| 306 | if id, ok := ownedByName[fullName]; ok { |
| 307 | ids[name] = id |
| 308 | log.Info().Str("network", fullName).Msg("Network already exists, skipping") |
no test coverage detected