Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-cli/cmd/ports-await.go
2498 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"fmt"
9
"os"
10
"regexp"
11
"strconv"
12
"time"
13
14
"github.com/gitpod-io/gitpod/gitpod-cli/pkg/utils"
15
"github.com/spf13/cobra"
16
"golang.org/x/xerrors"
17
)
18
19
const (
20
fnNetTCP = "/proc/net/tcp"
21
fnNetTCP6 = "/proc/net/tcp6"
22
)
23
24
var awaitPortCmd = &cobra.Command{
25
Use: "await <port>",
26
Short: "Waits for a process to listen on a port",
27
Args: cobra.ExactArgs(1),
28
RunE: func(cmd *cobra.Command, args []string) error {
29
port, err := strconv.ParseUint(args[0], 10, 16)
30
if err != nil {
31
return GpError{Err: xerrors.Errorf("port cannot be parsed as int: %w", err), OutCome: utils.Outcome_UserErr, ErrorCode: utils.UserErrorCode_InvalidArguments}
32
}
33
34
// Expected format: local port (in hex), remote address (irrelevant here), connection state ("0A" is "TCP_LISTEN")
35
pattern, err := regexp.Compile(fmt.Sprintf(":[0]*%X \\w+:\\w+ 0A ", port))
36
if err != nil {
37
return GpError{Err: xerrors.Errorf("cannot compile regexp pattern"), OutCome: utils.Outcome_UserErr, ErrorCode: utils.UserErrorCode_InvalidArguments}
38
}
39
40
var protos []string
41
for _, path := range []string{fnNetTCP, fnNetTCP6} {
42
if _, err := os.Stat(path); err == nil {
43
protos = append(protos, path)
44
}
45
}
46
47
fmt.Printf("Awaiting port %d... ", port)
48
t := time.NewTicker(time.Second * 2)
49
for cmd.Context().Err() == nil {
50
for _, proto := range protos {
51
tcp, err := os.ReadFile(proto)
52
if err != nil {
53
return xerrors.Errorf("cannot read %v: %w", proto, err)
54
}
55
56
if pattern.MatchString(string(tcp)) {
57
fmt.Println("ok")
58
return nil
59
}
60
}
61
select {
62
case <-cmd.Context().Done():
63
return nil
64
case <-t.C:
65
}
66
}
67
return nil
68
},
69
}
70
71
var awaitPortCmdAlias = &cobra.Command{
72
Hidden: true,
73
Deprecated: "please use `ports await` instead.",
74
Use: "await-port <port>",
75
Short: awaitPortCmd.Short,
76
Long: awaitPortCmd.Long,
77
Args: awaitPortCmd.Args,
78
RunE: awaitPortCmd.RunE,
79
}
80
81
func init() {
82
portsCmd.AddCommand(awaitPortCmd)
83
84
rootCmd.AddCommand(awaitPortCmdAlias)
85
}
86
87