How to use getPortConfig method of service Package

Best Selenoid code snippet using service.getPortConfig

docker.go

Source:docker.go Github

copy

Full Screen

...78 ExposedPorts map[nat.Port]struct{}79}80// StartWithCancel - Starter interface implementation81func (d *Docker) StartWithCancel() (*StartedService, error) {82 portConfig, err := getPortConfig(d.Service, d.Caps, d.Environment)83 if err != nil {84 return nil, fmt.Errorf("configuring ports: %v", err)85 }86 mem, err := getMemory(d.Service, d.Environment)87 if err != nil {88 return nil, fmt.Errorf("invalid memory limit: %v", err)89 }90 cpu, err := getCpu(d.Service, d.Environment)91 if err != nil {92 return nil, fmt.Errorf("invalid CPU limit: %v", err)93 }94 selenium := portConfig.SeleniumPort95 fileserver := portConfig.FileserverPort96 clipboard := portConfig.ClipboardPort97 vnc := portConfig.VNCPort98 devtools := portConfig.DevtoolsPort99 requestId := d.RequestId100 image := d.Service.Image101 ctx := context.Background()102 log.Printf("[%d] [CREATING_CONTAINER] [%s]", requestId, image)103 hostConfig := ctr.HostConfig{104 Binds: d.Service.Volumes,105 AutoRemove: true,106 PortBindings: portConfig.PortBindings,107 LogConfig: getLogConfig(*d.LogConfig, d.Caps),108 NetworkMode: ctr.NetworkMode(d.Network),109 Tmpfs: d.Service.Tmpfs,110 ShmSize: getShmSize(d.Service),111 Privileged: d.Privileged,112 Resources: ctr.Resources{113 Memory: mem,114 NanoCPUs: cpu,115 },116 ExtraHosts: getExtraHosts(d.Service, d.Caps),117 }118 hostConfig.PublishAllPorts = d.Service.PublishAllPorts119 if len(d.Caps.DNSServers) > 0 {120 hostConfig.DNS = d.Caps.DNSServers121 }122 if !d.Privileged {123 hostConfig.CapAdd = strslice.StrSlice{sysAdmin}124 }125 if len(d.ApplicationContainers) > 0 {126 hostConfig.Links = d.ApplicationContainers127 }128 if len(d.Service.Sysctl) > 0 {129 hostConfig.Sysctls = d.Service.Sysctl130 }131 cl := d.Client132 env := getEnv(d.ServiceBase, d.Caps)133 container, err := cl.ContainerCreate(ctx,134 &ctr.Config{135 Hostname: getContainerHostname(d.Caps),136 Image: image.(string),137 Env: env,138 ExposedPorts: portConfig.ExposedPorts,139 Labels: getLabels(d.Service, d.Caps),140 },141 &hostConfig,142 &network.NetworkingConfig{}, "")143 if err != nil {144 return nil, fmt.Errorf("create container: %v", err)145 }146 browserContainerStartTime := time.Now()147 browserContainerId := container.ID148 videoContainerId := ""149 log.Printf("[%d] [STARTING_CONTAINER] [%s] [%s]", requestId, image, browserContainerId)150 err = cl.ContainerStart(ctx, browserContainerId, types.ContainerStartOptions{})151 if err != nil {152 removeContainer(ctx, cl, requestId, browserContainerId)153 return nil, fmt.Errorf("start container: %v", err)154 }155 log.Printf("[%d] [CONTAINER_STARTED] [%s] [%s] [%.2fs]", requestId, image, browserContainerId, util.SecondsSince(browserContainerStartTime))156 if len(d.AdditionalNetworks) > 0 {157 for _, networkName := range d.AdditionalNetworks {158 err = cl.NetworkConnect(ctx, networkName, browserContainerId, nil)159 if err != nil {160 return nil, fmt.Errorf("failed to connect container %s to network %s: %v", browserContainerId, networkName, err)161 }162 }163 }164 stat, err := cl.ContainerInspect(ctx, browserContainerId)165 if err != nil {166 removeContainer(ctx, cl, requestId, browserContainerId)167 return nil, fmt.Errorf("inspect container %s: %s", browserContainerId, err)168 }169 _, ok := stat.NetworkSettings.Ports[selenium]170 if !ok {171 removeContainer(ctx, cl, requestId, browserContainerId)172 return nil, fmt.Errorf("no bindings available for %v", selenium)173 }174 servicePort := d.Service.Port175 pc := map[string]nat.Port{176 servicePort: selenium,177 ports.VNC: vnc,178 ports.Devtools: devtools,179 ports.Fileserver: fileserver,180 ports.Clipboard: clipboard,181 }182 hostPort := getHostPort(d.Environment, servicePort, d.Caps, stat, pc)183 u := &url.URL{Scheme: "http", Host: hostPort.Selenium, Path: d.Service.Path}184 if d.Video {185 videoContainerId, err = startVideoContainer(ctx, cl, requestId, stat, d.Environment, d.ServiceBase, d.Caps)186 if err != nil {187 return nil, fmt.Errorf("start video container: %v", err)188 }189 }190 serviceStartTime := time.Now()191 err = wait(u.String(), d.StartupTimeout)192 if err != nil {193 if videoContainerId != "" {194 stopVideoContainer(ctx, cl, requestId, videoContainerId, d.Environment)195 }196 removeContainer(ctx, cl, requestId, browserContainerId)197 return nil, fmt.Errorf("wait: %v", err)198 }199 log.Printf("[%d] [SERVICE_STARTED] [%s] [%s] [%.2fs]", requestId, image, browserContainerId, util.SecondsSince(serviceStartTime))200 log.Printf("[%d] [PROXY_TO] [%s] [%s]", requestId, browserContainerId, u.String())201 var publishedPortsInfo map[string]string202 if d.Service.PublishAllPorts {203 publishedPortsInfo = getContainerPorts(stat)204 }205 s := StartedService{206 Url: u,207 Container: &session.Container{208 ID: browserContainerId,209 IPAddress: getContainerIP(d.Environment.Network, stat),210 Ports: publishedPortsInfo,211 },212 HostPort: hostPort,213 Cancel: func() {214 if videoContainerId != "" {215 stopVideoContainer(ctx, cl, requestId, videoContainerId, d.Environment)216 }217 defer removeContainer(ctx, cl, requestId, browserContainerId)218 if d.LogOutputDir != "" && (d.SaveAllLogs || d.Log) {219 r, err := d.Client.ContainerLogs(ctx, browserContainerId, types.ContainerLogsOptions{220 Timestamps: true,221 ShowStdout: true,222 ShowStderr: true,223 })224 if err != nil {225 log.Printf("[%d] [FAILED_TO_COPY_LOGS] [%s] [Failed to capture container logs: %v]", requestId, browserContainerId, err)226 return227 }228 defer r.Close()229 filename := filepath.Join(d.LogOutputDir, d.LogName)230 f, err := os.Create(filename)231 if err != nil {232 log.Printf("[%d] [FAILED_TO_COPY_LOGS] [%s] [Failed to create log file %s: %v]", requestId, browserContainerId, filename, err)233 return234 }235 defer f.Close()236 _, err = stdcopy.StdCopy(f, f, r)237 if err != nil {238 log.Printf("[%d] [FAILED_TO_COPY_LOGS] [%s] [Failed to copy data to log file %s: %v]", requestId, browserContainerId, filename, err)239 }240 }241 },242 }243 return &s, nil244}245func getPortConfig(service *config.Browser, caps session.Caps, env Environment) (*portConfig, error) {246 selenium, err := nat.NewPort("tcp", service.Port)247 if err != nil {248 return nil, fmt.Errorf("new selenium port: %v", err)249 }250 fileserver, err := nat.NewPort("tcp", ports.Fileserver)251 if err != nil {252 return nil, fmt.Errorf("new fileserver port: %v", err)253 }254 clipboard, err := nat.NewPort("tcp", ports.Clipboard)255 if err != nil {256 return nil, fmt.Errorf("new clipboard port: %v", err)257 }258 exposedPorts := map[nat.Port]struct{}{selenium: {}, fileserver: {}, clipboard: {}}259 var vnc nat.Port...

Full Screen

Full Screen

docker_deployment.go

Source:docker_deployment.go Github

copy

Full Screen

...112 for _, service := range services {113 serviceID := service.ID114 name := service.Spec.Name115 dockerImage := service.Spec.TaskTemplate.ContainerSpec.Image116 portConfig := getPortConfigForDetails(service.Spec.EndpointSpec.Ports)117 replicas := deployment.Replicas(*service.Spec.Mode.Replicated.Replicas)118 serviceDetails = append(serviceDetails, deployment.Details{119 ID: serviceID,120 Name: name,121 Dockerimage: dockerImage,122 PortConfigs: portConfig,123 Replicas: replicas,124 })125 }126 return serviceDetails, nil127}128//ListByName implementation for deployment.ListByName()129func (dockerDeployment Deployment) ListByName(name string) (deployment.Details, error) {130 return deployment.Details{}, nil131}132//LogsByName implementation for deployment.LogsByName()133func (dockerDeployment Deployment) LogsByName(name string, options quebictypes.FunctionContainerLogOptions) (string, error) {134 ctx, cli, err := dockerDeployment.getContextAndClient()135 if err != nil {136 return "", err137 }138 dockerLogsOptions := types.ContainerLogsOptions{139 Details: options.Details,140 Follow: options.Follow,141 ShowStderr: options.ShowStderr,142 ShowStdout: options.ShowStdout,143 Since: options.Since,144 Tail: options.Tail,145 Timestamps: options.Timestamps,146 Until: options.Until,147 }148 if !options.ShowStdout && !options.ShowStderr {149 options.ShowStdout = true150 }151 reader, err := cli.ServiceLogs(ctx, name, dockerLogsOptions)152 if err != nil {153 return "", err154 }155 buf := new(bytes.Buffer)156 buf.ReadFrom(reader)157 return buf.String(), nil158}159func (dockerDeployment Deployment) getContextAndClient() (context.Context, *client.Client, error) {160 ctx := context.Background()161 cli, err := client.NewEnvClient()162 if err != nil {163 return ctx, cli, fmt.Errorf("%s client-get-failed %v", logPrefix, err)164 }165 return ctx, cli, nil166}167func (dockerDeployment Deployment) networkCreate(networkID string) error {168 if networkID == "" {169 return fmt.Errorf("%s network-id should not be empty", logPrefix)170 }171 ctx, cli, err := dockerDeployment.getContextAndClient()172 if err != nil {173 return err174 }175 options := types.NetworkCreate{176 Driver: "overlay"}177 cli.NetworkCreate(ctx, networkID, options)178 return nil179}180func (dockerDeployment Deployment) serviceCreate(deploySpec deployment.Spec) (string, error) {181 serviceSpec, err := dockerDeployment.getServiceSpec(deploySpec)182 if err != nil {183 return "", err184 }185 ctx, cli, err := dockerDeployment.getContextAndClient()186 if err != nil {187 return "", err188 }189 options := types.ServiceCreateOptions{}190 serviceCreateResponse, err := cli.ServiceCreate(ctx, serviceSpec, options)191 if err != nil {192 return "", fmt.Errorf("%s service-create-failed %v", logPrefix, err)193 }194 if len(serviceCreateResponse.Warnings) != 0 {195 log.Printf("%s service-create-warn %v", logPrefix, serviceCreateResponse.Warnings[0])196 }197 return serviceCreateResponse.ID, nil198}199func (dockerDeployment Deployment) serviceUpdate(deploySpec deployment.Spec) error {200 serviceSpec, err := dockerDeployment.getServiceSpec(deploySpec)201 if err != nil {202 return err203 }204 ctx, cli, err := dockerDeployment.getContextAndClient()205 if err != nil {206 return err207 }208 //delete previous running service209 err = cli.ServiceRemove(ctx, serviceSpec.Name)210 if err != nil {211 return err212 }213 waitForPreviousServiceStop(deploySpec.PortConfigs)214 options := types.ServiceCreateOptions{}215 //create as new service216 serviceUpdateResponse, err := cli.ServiceCreate(ctx, serviceSpec, options)217 if err != nil {218 return fmt.Errorf("%s service-update-failed %v", logPrefix, err)219 }220 if len(serviceUpdateResponse.Warnings) != 0 {221 log.Printf("%s service-update-warn %v", logPrefix, serviceUpdateResponse.Warnings[0])222 }223 return nil224}225//WaitForPreviousServiceStop waitForPreviousServiceStop226func waitForPreviousServiceStop(portConfigs []deployment.PortConfig) error {227 waitForResponse := make(chan bool)228 go func() {229 log.Printf("waiting for previous services stop ...")230 var connectedList []bool231 for {232 for _, portConfig := range portConfigs {233 connectionStr := fmt.Sprintf("%s:%d", common.HostMachineIP, portConfig.Port)234 _, err := net.Dial("tcp", connectionStr)235 //connected236 if err == nil {237 connectedList = append(connectedList, true)238 }239 }240 //check there are no any connected ports241 if len(connectedList) == 0 {242 waitForResponse <- true243 break244 }245 connectedList = nil246 time.Sleep(time.Second * 1)247 }248 }()249 select {250 case <-waitForResponse:251 break252 case <-time.After(waitTimeForPreviousServiceStop):253 return fmt.Errorf("previous service is still running. please try again")254 }255 return nil256}257func (dockerDeployment Deployment) serviceRemove(serviceName string) error {258 ctx, cli, err := dockerDeployment.getContextAndClient()259 if err != nil {260 return err261 }262 return cli.ServiceRemove(ctx, serviceName)263}264func (dockerDeployment Deployment) serviceGetByName(serviceName string) (*swarm.Service, error) {265 ctx, cli, err := dockerDeployment.getContextAndClient()266 if err != nil {267 return nil, err268 }269 options := types.ServiceInspectOptions{}270 service, _, err := cli.ServiceInspectWithRaw(ctx, serviceName, options)271 if err != nil {272 return nil, fmt.Errorf("%s service-inspect-failed %v", logPrefix, err)273 }274 return &service, nil275}276func (dockerDeployment Deployment) serviceList(filters deployment.ListFilters) ([]swarm.Service, error) {277 ctx, cli, err := dockerDeployment.getContextAndClient()278 if err != nil {279 return nil, err280 }281 //TODO filters282 options := types.ServiceListOptions{}283 return cli.ServiceList(ctx, options)284}285func (dockerDeployment Deployment) serviceLogs(286 serviceName string,287 options types.ContainerLogsOptions,288) (io.ReadCloser, error) {289 ctx, cli, err := dockerDeployment.getContextAndClient()290 if err != nil {291 return nil, err292 }293 if !options.ShowStdout && !options.ShowStderr {294 options.ShowStdout = true295 }296 return cli.ServiceLogs(ctx, serviceName, options)297}298func (dockerDeployment Deployment) getServiceSpec(deploySpec deployment.Spec) (swarm.ServiceSpec, error) {299 serviceName := deploySpec.Name300 dockerimage := deploySpec.Dockerimage301 portConfig := deploySpec.PortConfigs302 replicas := deploySpec.Replicas303 envkeys := deploySpec.Envkeys304 //validation305 if serviceName == "" {306 return swarm.ServiceSpec{}, fmt.Errorf("%s service-name should not be empty", logPrefix)307 }308 if dockerimage == "" {309 return swarm.ServiceSpec{}, fmt.Errorf("%s docker-image should not be empty", logPrefix)310 }311 if replicas < 1 {312 return swarm.ServiceSpec{}, fmt.Errorf("%s replicas should not be empty", logPrefix)313 }314 //validation315 networkName := dockerDeployment.Config.NetworkName316 replicasValue := uint64(replicas)317 networkAttachmentConfigs := []swarm.NetworkAttachmentConfig{318 swarm.NetworkAttachmentConfig{Target: networkName},319 }320 containerSpec := &swarm.ContainerSpec{321 Image: dockerimage,322 Hostname: serviceName,323 }324 //env set325 var env []string326 if envkeys != nil {327 for key, value := range envkeys {328 env = append(env, fmt.Sprintf("%s=%s", key, value))329 }330 }331 if env != nil {332 containerSpec.Env = env333 }334 taskSpec := swarm.TaskSpec{335 ContainerSpec: containerSpec,336 Networks: networkAttachmentConfigs,337 }338 return swarm.ServiceSpec{339 Annotations: swarm.Annotations{Name: serviceName},340 Mode: swarm.ServiceMode{341 Replicated: &swarm.ReplicatedService{342 Replicas: &replicasValue,343 },344 },345 TaskTemplate: taskSpec,346 EndpointSpec: &swarm.EndpointSpec{Ports: getPortConfig(portConfig)},347 }, nil348}349func getPortConfig(portConfigs []deployment.PortConfig) []swarm.PortConfig {350 var swarmPortConfigs []swarm.PortConfig351 for _, portConfig := range portConfigs {352 swarmPortConfig := swarm.PortConfig{353 Name: portConfig.Name,354 Protocol: swarm.PortConfigProtocol(portConfig.Protocol),355 PublishedPort: uint32(portConfig.Port),356 TargetPort: uint32(portConfig.TargetPort),357 }358 swarmPortConfigs = append(swarmPortConfigs, swarmPortConfig)359 }360 if swarmPortConfigs == nil {361 swarmPortConfigs = append(swarmPortConfigs, swarm.PortConfig{})362 }363 return swarmPortConfigs364}365func getPortConfigForDetails(portConfigs []swarm.PortConfig) []deployment.PortConfig {366 var deploymentPortConfigs []deployment.PortConfig367 for _, portConfig := range portConfigs {368 deploymentPortConfig := deployment.PortConfig{369 Name: portConfig.Name,370 Protocol: deployment.PortProtocol(portConfig.Protocol),371 Port: deployment.Port(portConfig.PublishedPort),372 TargetPort: deployment.Port(portConfig.TargetPort),373 }374 deploymentPortConfigs = append(deploymentPortConfigs, deploymentPortConfig)375 }376 return deploymentPortConfigs377}...

Full Screen

Full Screen

getPortConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 eg := edgegrid.Init("~/.edgerc", "default")4 c := client.New(eg)5 s := networklist.New(c)6 resp, err := s.GetPortConfig("1234")7 if err != nil {8 fmt.Println(err.Error())9 } else {10 fmt.Println(resp)11 }12}

Full Screen

Full Screen

getPortConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := edgegrid.Init("~/.edgerc", "papi")4 if err != nil {5 fmt.Println("Error: ", err)6 os.Exit(1)7 }8 svc, err := papi.New(config)9 if err != nil {10 fmt.Println("Error: ", err)11 os.Exit(1)12 }13 portConfig, err := svc.GetPortConfig("ctr_1-1B7L7V", "grp_1-1B7L7V", "prd_1-1B7L7V")14 if err != nil {15 fmt.Println("Error: ", err)16 os.Exit(1)17 }18 fmt.Println("Port Config: ", portConfig)19}

Full Screen

Full Screen

getPortConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 sdk, err := fabsdk.New(config.FromFile("/home/ritik/go/src/github.com/hyperledger/fabric-sdk-go/test/integration/fixtures/config/config_test.yaml"))4 if err != nil {5 fmt.Println("Failed to create new SDK: %s", err)6 os.Exit(-1)7 }8 defer sdk.Close()9 flag.StringVar(&portId, "portId", "1", "Port ID")10 flag.Parse()11 clientContext := sdk.ChannelContext("mychannel", fabsdk.WithUser("Admin"))12 client, err := channel.New(clientContext)13 if err != nil {14 fmt.Println("Failed to create new channel client: %s", err)15 os.Exit(-1)16 }17 args = append(args, "getPortConfig")18 args = append(args, portId)19 req := channel.Request{ChaincodeID: "mycc", Fcn: args[0], Args: [][]byte{[]byte(args[1])}}20 response, err := client.Query(req, channel.WithRetry(retry.DefaultChannelOpts))21 if err != nil {22 fmt.Println("Failed to query: %s", err)23 os.Exit(-1)24 }25 fmt.Println(string(response.Payload))26}

Full Screen

Full Screen

getPortConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) < 2 {4 fmt.Println("Usage: ./1.go <service-name> <port>")5 os.Exit(1)6 }7 port, err := strconv.Atoi(os.Args[2])8 if err != nil {9 fmt.Println("Error in parsing port number")10 os.Exit(1)11 }

Full Screen

Full Screen

getPortConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 service := master.NewService()4 portConfig, err := service.GetPortConfig("default", "frontend")5 if err != nil {6 fmt.Println("Error getting port config", err)7 }8 fmt.Println("port config", portConfig)9 portConfig, err = service.GetPortConfig("default", "backend")10 if err != nil {11 fmt.Println("Error getting port config", err)12 }13 fmt.Println("port config", portConfig)14 portConfig, err = service.GetPortConfig("default", "frontend")15 if err != nil {16 fmt.Println("Error getting port config", err)17 }18 fmt.Println("port config", portConfig)19 portConfig, err = service.GetPortConfig("default", "backend")20 if err != nil {21 fmt.Println("Error getting port config", err)22 }23 fmt.Println("port config", portConfig)24 portConfig, err = service.GetPortConfig("default", "frontend")25 if err != nil {26 fmt.Println("Error getting port config", err)27 }28 fmt.Println("port config", portConfig)29 portConfig, err = service.GetPortConfig("default", "backend")30 if err != nil {31 fmt.Println("Error getting port config", err)32 }33 fmt.Println("port config", portConfig)34 portConfig, err = service.GetPortConfig("default", "frontend")35 if err != nil {36 fmt.Println("Error getting port config", err)37 }38 fmt.Println("port config", portConfig)39 portConfig, err = service.GetPortConfig("default", "backend")40 if err != nil {41 fmt.Println("Error getting port config", err)42 }43 fmt.Println("port config", portConfig)44 portConfig, err = service.GetPortConfig("default", "frontend")45 if err != nil {46 fmt.Println("Error getting port config", err)47 }48 fmt.Println("port

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful