Skip to content

Commit

Permalink
add /v2/casaos/health/ports to get ports in use (IceWhaleTech#1023)
Browse files Browse the repository at this point in the history
Signed-off-by: Tiger Wang <tigerwang@outlook.com>
  • Loading branch information
tigerinus authored Apr 24, 2023
1 parent af440ea commit 8e1b9b8
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 20 deletions.
39 changes: 39 additions & 0 deletions api/casaos/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ paths:
$ref: "#/components/responses/GetHealthServicesOK"
"500":
$ref: "#/components/responses/ResponseInternalServerError"

/health/ports:
get:
tags:
- Health methods
summary: Get port in use
operationId: getHealthPorts
responses:
"200":
$ref: "#/components/responses/GetHealthPortsOK"
"500":
$ref: "#/components/responses/ResponseInternalServerError"

/file/test:
get:
tags:
Expand Down Expand Up @@ -93,6 +106,17 @@ components:
data:
$ref: "#/components/schemas/HealthServices"

GetHealthPortsOK:
description: OK
content:
application/json:
schema:
allOf:
- $ref: "#/components/schemas/BaseResponse"
- properties:
data:
$ref: "#/components/schemas/HealthPorts"

schemas:
BaseResponse:
properties:
Expand All @@ -114,3 +138,18 @@ components:
items:
type: string
example: "casaos.service"

HealthPorts:
properties:
tcp:
type: array
items:
type: integer
example: 80
x-go-name: TCP
udp:
type: array
items:
type: integer
example: 53
x-go-name: UDP
63 changes: 47 additions & 16 deletions codegen/casaos_api.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,18 @@ require (
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
github.com/robfig/cron/v3 v3.0.1
github.com/samber/lo v1.38.1
github.com/satori/go.uuid v1.2.0
github.com/shirou/gopsutil/v3 v3.23.2
github.com/sirupsen/logrus v1.9.0
github.com/stretchr/testify v1.8.2
github.com/tidwall/gjson v1.14.4
go.uber.org/goleak v1.2.1
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.7.0
golang.org/x/oauth2 v0.6.0
golang.org/x/sync v0.1.0
golang.org/x/sys v0.6.0
gorm.io/gorm v1.24.6
gotest.tools v2.2.0+incompatible
)
Expand All @@ -53,6 +56,7 @@ require (
github.com/bytedance/sonic v1.8.5 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5 // indirect
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
Expand Down Expand Up @@ -100,6 +104,7 @@ require (
github.com/pelletier/go-toml/v2 v2.0.7 // indirect
github.com/perimeterx/marshmallow v1.1.4 // indirect
github.com/pierrec/lz4/v4 v4.1.17 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/tidwall/match v1.1.1 // indirect
Expand All @@ -116,9 +121,9 @@ require (
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/image v0.6.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.8.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6po
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rwtodd/Go.Sed v0.0.0-20210816025313-55464686f9ef/go.mod h1:8AEUvGVi2uQ5b24BIhcr0GCcpd/RNAFWaN2CJFrWIIQ=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/shirou/gopsutil/v3 v3.23.2 h1:PAWSuiAszn7IhPMBtXsbSCafej7PqUOvY6YywlQUExU=
Expand Down Expand Up @@ -324,6 +326,8 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.6.0 h1:bR8b5okrPI3g/gyZakLZHeWxAR8Dn5CyxXv1hLH5g/4=
golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0=
Expand Down
7 changes: 4 additions & 3 deletions route/v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ func InitV2Router() http.Handler {
e.Use(echo_middleware.JWTWithConfig(echo_middleware.JWTConfig{
Skipper: func(c echo.Context) bool {
return c.RealIP() == "::1" || c.RealIP() == "127.0.0.1"
//return true
// return true
},
ParseTokenFunc: func(token string, c echo.Context) (interface{}, error) {
claims, code := jwt.Validate(token)
claims, code := jwt.Validate(token) // TODO - needs JWT validation
if code != common_err.SUCCESS {
return nil, echo.ErrUnauthorized
}
Expand Down Expand Up @@ -137,6 +137,7 @@ func InitV2DocRouter(docHTML string, docYAML string) http.Handler {
}
})
}

func InitFile() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("path")
Expand Down Expand Up @@ -174,7 +175,7 @@ func InitDir() http.Handler {
// handles only single files not folders and multiple files
// if len(list) == 1 {

//filePath := list[0]
// filePath := list[0]
// info, err := os.Stat(filePath)
// if err != nil {

Expand Down
17 changes: 17 additions & 0 deletions route/v2/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,20 @@ func (s *CasaOS) GetHealthServices(ctx echo.Context) error {
},
})
}

func (s *CasaOS) GetHealthPorts(ctx echo.Context) error {
tcpPorts, udpPorts, err := service.MyService.Health().Ports()
if err != nil {
message := err.Error()
return ctx.JSON(http.StatusInternalServerError, codegen.ResponseInternalServerError{
Message: &message,
})
}

return ctx.JSON(http.StatusOK, codegen.GetHealthPortsOK{
Data: &codegen.HealthPorts{
TCP: &tcpPorts,
UDP: &udpPorts,
},
})
}
56 changes: 56 additions & 0 deletions service/health.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
package service

import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"

"github.com/samber/lo"

"github.com/IceWhaleTech/CasaOS-Common/utils/systemctl"
)

type HealthService interface {
Services() (map[bool]*[]string, error)
Ports() ([]int, []int, error)
}

type service struct{}
Expand Down Expand Up @@ -34,6 +44,52 @@ func (s *service) Services() (map[bool]*[]string, error) {
return result, nil
}

func (s *service) Ports() ([]int, []int, error) {
usedPorts := map[string]map[int]struct{}{
"tcp": {},
"udp": {},
}

for _, protocol := range []string{"tcp", "udp"} {
filename := fmt.Sprintf("/proc/net/%s", protocol)

file, err := os.Open(filename)
if err != nil {
return nil, nil, errors.New("Failed to open " + filename)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}

localAddress := fields[1]
addressParts := strings.Split(localAddress, ":")
if len(addressParts) < 2 {
continue
}

portHex := addressParts[1]
port, err := strconv.ParseInt(portHex, 16, 0)
if err != nil {
continue
}

usedPorts[protocol][int(port)] = struct{}{}
}

if err := scanner.Err(); err != nil {
return nil, nil, errors.New("Error reading from " + filename)
}
}

return lo.Keys(usedPorts["tcp"]), lo.Keys(usedPorts["udp"]), nil
}

func NewHealthService() HealthService {
return &service{}
}
18 changes: 18 additions & 0 deletions service/health_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package service_test

import (
"testing"

"github.com/IceWhaleTech/CasaOS/service"
"github.com/stretchr/testify/assert"
)

func TestPorts(t *testing.T) {
service := service.NewHealthService()

tcpPorts, udpPorts, err := service.Ports()
assert.NoError(t, err)

assert.NotEmpty(t, tcpPorts)
assert.NotEmpty(t, udpPorts)
}

0 comments on commit 8e1b9b8

Please sign in to comment.