@@ -24,6 +24,7 @@ import (
2424 "io"
2525 "net/http"
2626 "os"
27+ "strings"
2728 "time"
2829
2930 "github.com/docker/compose-cli/api/compose"
@@ -73,7 +74,7 @@ func NewKubeClient(config genericclioptions.RESTClientGetter) (*KubeClient, erro
7374 }, nil
7475}
7576
76- // GetContainers get containers for a given compose project
77+ // GetPod retrieves a service pod
7778func (kc KubeClient ) GetPod (ctx context.Context , projectName , serviceName string ) (* corev1.Pod , error ) {
7879 pods , err := kc .client .CoreV1 ().Pods (kc .namespace ).List (ctx , metav1.ListOptions {
7980 LabelSelector : fmt .Sprintf ("%s=%s" , compose .ProjectTag , projectName ),
@@ -160,9 +161,39 @@ func (kc KubeClient) GetContainers(ctx context.Context, projectName string, all
160161 if err != nil {
161162 return nil , err
162163 }
164+ services := map [string ][]compose.PortPublisher {}
163165 result := []compose.ContainerSummary {}
164166 for _ , pod := range pods .Items {
165- result = append (result , podToContainerSummary (pod ))
167+ summary := podToContainerSummary (pod )
168+ serviceName := pod .GetObjectMeta ().GetLabels ()[compose .ServiceTag ]
169+ ports , ok := services [serviceName ]
170+ if ! ok {
171+ s , err := kc .client .CoreV1 ().Services (kc .namespace ).Get (ctx , serviceName , metav1.GetOptions {})
172+ if err != nil {
173+ if ! strings .Contains (err .Error (), "not found" ) {
174+ return nil , err
175+ }
176+ result = append (result , summary )
177+ continue
178+ }
179+ ports = []compose.PortPublisher {}
180+ if s != nil {
181+ if s .Spec .Type == corev1 .ServiceTypeLoadBalancer {
182+ if len (s .Status .LoadBalancer .Ingress ) > 0 {
183+ port := compose.PortPublisher {URL : s .Status .LoadBalancer .Ingress [0 ].IP }
184+ if len (s .Spec .Ports ) > 0 {
185+ port .URL = fmt .Sprintf ("%s:%d" , port .URL , s .Spec .Ports [0 ].Port )
186+ port .TargetPort = s .Spec .Ports [0 ].TargetPort .IntValue ()
187+ port .Protocol = string (s .Spec .Ports [0 ].Protocol )
188+ }
189+ ports = append (ports , port )
190+ }
191+ }
192+ }
193+ services [serviceName ] = ports
194+ }
195+ summary .Publishers = ports
196+ result = append (result , summary )
166197 }
167198
168199 return result , nil
@@ -253,8 +284,8 @@ func (kc KubeClient) MapPortsToLocalhost(ctx context.Context, opts PortMappingOp
253284
254285 eg , ctx := errgroup .WithContext (ctx )
255286 for serviceName , servicePorts := range opts .Services {
256- serviceName = serviceName
257- servicePorts = servicePorts
287+ serviceName : = serviceName
288+ servicePorts : = servicePorts
258289 pod , err := kc .GetPod (ctx , opts .ProjectName , serviceName )
259290 if err != nil {
260291 return err
0 commit comments