Skip to content

Commit 44d2251

Browse files
committed
all: reallocate server to cmd/occamyd
1 parent 7547ea8 commit 44d2251

20 files changed

+107
-503
lines changed

Makefile

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,19 @@ HOME = changkun.de/x/occamy
1010
IMAGE = occamy
1111

1212
compile:
13-
go build -mod vendor -x -o occamyd
13+
go build -x -o occamyd cmd/occamyd/*
1414
.PHONY: compile
1515

1616
build:
17-
docker build -t $(IMAGE):$(VERSION) -t $(IMAGE):latest -f docker/Dockerfile .
17+
docker build --platform linux/x86_64 -t $(IMAGE):$(VERSION) -t $(IMAGE):latest -f docker/Dockerfile .
1818
.PHONY: occamy
1919

20-
run:
20+
up:
2121
cd docker && docker-compose up -d
2222

23-
stop:
23+
down:
2424
cd docker && docker-compose down
2525

26-
test:
27-
go test -cover -coverprofile=cover.test -v ./...
28-
go tool cover -html=cover.test -o cover.html
29-
3026
clean:
3127
docker images -f "dangling=true" -q | xargs docker rmi -f
3228
docker image prune -f

server/connection.go renamed to cmd/occamyd/connection.go

Lines changed: 3 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
// Use of this source code is governed by a MIT
33
// license that can be found in the LICENSE file.
44

5-
package server
5+
package main
66

77
import (
88
"context"
99
"log"
1010
"net/http"
11-
"net/http/pprof"
1211
"os"
1312
"os/signal"
1413
"sync"
@@ -28,7 +27,7 @@ func init() {
2827
// Run is an export method that serves occamy proxy
2928
func Run() {
3029
proxy := &proxy{
31-
sessions: make(map[string]*Session),
30+
// sessions: make(map[string]*Session),
3231
upgrader: &websocket.Upgrader{
3332
ReadBufferSize: protocol.MaxInstructionLength,
3433
WriteBufferSize: protocol.MaxInstructionLength,
@@ -44,9 +43,7 @@ type proxy struct {
4443
jwtm *jwt.GinJWTMiddleware
4544
upgrader *websocket.Upgrader
4645
engine *gin.Engine
47-
48-
mu sync.Mutex
49-
sessions map[string]*Session
46+
sess sync.Map // map[string]*Session
5047
}
5148

5249
func (p *proxy) serve() {
@@ -90,9 +87,6 @@ func (p *proxy) routers() *gin.Engine {
9087
auth := v1.Group("/connect")
9188
auth.Use(p.jwtm.MiddlewareFunc())
9289
auth.GET("", p.serveWS)
93-
if gin.Mode() == gin.DebugMode {
94-
p.profile()
95-
}
9690
return p.engine
9791
}
9892

@@ -129,42 +123,3 @@ func (p *proxy) initJWT() {
129123
}
130124
p.jwtm = jwtm
131125
}
132-
133-
// profile the standard HandlerFuncs from the net/http/pprof package with
134-
// the provided gin.Engine. prefixOptions is a optional. If not prefixOptions,
135-
// the default path prefix is used, otherwise first prefixOptions will be path prefix.
136-
//
137-
// Basic Usage:
138-
//
139-
// - use the pprof tool to look at the heap profile:
140-
// go tool pprof http://0.0.0.0:5636/debug/pprof/heap
141-
// - look at a 30-second CPU profile:
142-
// go tool pprof http://0.0.0.0:5636/debug/pprof/profile
143-
// - look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate:
144-
// go tool pprof http://0.0.0.0:5636/debug/pprof/block
145-
// - collect a 5-second execution trace:
146-
// wget http://0.0.0.0:5636/debug/pprof/trace?seconds=5
147-
//
148-
func (p *proxy) profile() {
149-
pprofHandler := func(h http.HandlerFunc) gin.HandlerFunc {
150-
handler := http.HandlerFunc(h)
151-
return func(c *gin.Context) {
152-
handler.ServeHTTP(c.Writer, c.Request)
153-
}
154-
}
155-
r := p.engine.Group("/debug/pprof")
156-
{
157-
r.GET("/", pprofHandler(pprof.Index))
158-
r.GET("/cmdline", pprofHandler(pprof.Cmdline))
159-
r.GET("/profile", pprofHandler(pprof.Profile))
160-
r.POST("/symbol", pprofHandler(pprof.Symbol))
161-
r.GET("/symbol", pprofHandler(pprof.Symbol))
162-
r.GET("/trace", pprofHandler(pprof.Trace))
163-
r.GET("/allocs", pprofHandler(pprof.Handler("allocs").ServeHTTP))
164-
r.GET("/block", pprofHandler(pprof.Handler("block").ServeHTTP))
165-
r.GET("/goroutine", pprofHandler(pprof.Handler("goroutine").ServeHTTP))
166-
r.GET("/heap", pprofHandler(pprof.Handler("heap").ServeHTTP))
167-
r.GET("/mutex", pprofHandler(pprof.Handler("mutex").ServeHTTP))
168-
r.GET("/threadcreate", pprofHandler(pprof.Handler("threadcreate").ServeHTTP))
169-
}
170-
}

occamy.go renamed to cmd/occamyd/occamyd.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,4 @@
44

55
package main
66

7-
import "changkun.de/x/occamy/server"
8-
9-
func main() { server.Run() }
7+
func main() { Run() }

server/routers.go renamed to cmd/occamyd/routers.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a MIT
33
// license that can be found in the LICENSE file.
44

5-
package server
5+
package main
66

77
import (
88
"log"
@@ -39,25 +39,25 @@ func (p *proxy) serveWS(c *gin.Context) {
3939
}
4040

4141
func (p *proxy) routeConn(ws *websocket.Conn, jwt *config.JWT) (err error) {
42-
p.mu.Lock()
43-
s, ok := p.sessions[jwt.GenerateID()]
44-
if ok {
45-
err = s.Join(ws, jwt, false, func() { p.mu.Unlock() })
46-
return
47-
}
42+
jwtId := jwt.GenerateID()
4843

49-
s, err = NewSession(jwt.Protocol)
44+
// Creating a new session because there was no session yet.
45+
s, err := NewSession(jwt.Protocol)
5046
if err != nil {
51-
p.mu.Unlock()
5247
return
5348
}
54-
55-
p.sessions[jwt.GenerateID()] = s
5649
log.Printf("new session was created: %s", s.ID)
57-
err = s.Join(ws, jwt, true, func() { p.mu.Unlock() }) // block here
5850

59-
p.mu.Lock()
60-
delete(p.sessions, jwt.GenerateID())
61-
p.mu.Unlock()
51+
// Check if there are already a session. If so, join.
52+
ss, loaded := p.sess.LoadOrStore(jwtId, s)
53+
if loaded {
54+
s.Close()
55+
s = ss.(*Session)
56+
log.Printf("already had old session: %s", s.ID)
57+
}
58+
59+
err = s.Join(ws, jwt, true) // block here
60+
p.sess.Delete(jwtId)
61+
s.Close()
6262
return
6363
}

server/session.go renamed to cmd/occamyd/session.go

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a MIT
33
// license that can be found in the LICENSE file.
44

5-
package server
5+
package main
66

77
import (
88
"fmt"
@@ -13,7 +13,7 @@ import (
1313
"syscall"
1414

1515
"changkun.de/x/occamy/internal/config"
16-
"changkun.de/x/occamy/internal/lib"
16+
"changkun.de/x/occamy/internal/guacd"
1717
"changkun.de/x/occamy/internal/protocol"
1818
"github.com/gorilla/websocket"
1919
)
@@ -24,14 +24,14 @@ type Session struct {
2424
ID string
2525
connectedUsers uint64
2626
once sync.Once
27-
client *lib.Client // shared client in a session
27+
client *guacd.Client // shared client in a session
2828
}
2929

3030
// NewSession creates a new occamy proxy session
3131
func NewSession(proto string) (*Session, error) {
3232
runtime.LockOSThread() // without unlock to exit the Go thread
3333

34-
cli, err := lib.NewClient()
34+
cli, err := guacd.NewClient()
3535
if err != nil {
3636
return nil, fmt.Errorf("occamy-lib: new client error: %w", err)
3737
}
@@ -40,7 +40,7 @@ func NewSession(proto string) (*Session, error) {
4040
s.client.InitLogLevel(config.Runtime.Mode)
4141
err = s.client.LoadProtocolPlugin(proto)
4242
if err != nil {
43-
s.close()
43+
s.Close()
4444
return nil, fmt.Errorf("occamy-lib: load protocol plugin failed: %w", err)
4545
}
4646
s.ID = s.client.ID
@@ -51,26 +51,24 @@ func NewSession(proto string) (*Session, error) {
5151
// reading/writing from the socket via read/write threads. The given socket,
5252
// parser, and any associated resources will be freed unless the user is not
5353
// added successfully.
54-
func (s *Session) Join(ws *websocket.Conn, jwt *config.JWT, owner bool, unlock func()) error {
55-
defer s.close()
56-
lib.ResetErrors()
54+
func (s *Session) Join(ws *websocket.Conn, jwt *config.JWT, owner bool) error {
55+
guacd.ResetErrors()
5756

5857
// 1. prepare socket pair
5958
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
6059
if err != nil {
61-
unlock()
6260
return fmt.Errorf("new socket pair error: %w", err)
6361
}
6462

6563
// 2. create guac socket using fds[0]
66-
sock, err := lib.NewSocket(fds[0])
64+
sock, err := guacd.NewSocket(fds[0])
6765
if err != nil {
6866
return fmt.Errorf("occamy-lib: create guac socket error: %w", err)
6967
}
7068
defer sock.Close()
7169

7270
// 3. create guac user using created guac socket
73-
u, err := lib.NewUser(sock, s.client, owner, jwt)
71+
u, err := guacd.NewUser(sock, s.client, owner, jwt)
7472
if err != nil {
7573
return fmt.Errorf("occamy-lib: create guac user error: %w", err)
7674
}
@@ -83,10 +81,10 @@ func (s *Session) Join(ws *websocket.Conn, jwt *config.JWT, owner bool, unlock f
8381
// 5. preparing connection
8482
err = u.Prepare()
8583
if err != nil {
86-
unlock()
8784
return fmt.Errorf("occamy-lib: handle user connection error: %w", err)
8885
}
89-
unlock()
86+
87+
log.Println("start to handle connections...")
9088

9189
// 6. handle connection
9290
done := make(chan struct{}, 1)
@@ -102,7 +100,7 @@ func (s *Session) Join(ws *websocket.Conn, jwt *config.JWT, owner bool, unlock f
102100
}
103101

104102
// Close closes a session.
105-
func (s *Session) close() {
103+
func (s *Session) Close() {
106104
if atomic.LoadUint64(&s.connectedUsers) > 0 {
107105
return
108106
}

docker/Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ ENV LC_ALL=en_US.UTF-8 \
3131
libtool \
3232
libvncserver-devel \
3333
make" \
34-
GO_VERSION=1.15.7
34+
GO_VERSION=1.17.3
3535
RUN yum -y update && \
3636
yum -y install epel-release $RUNTIME_DEPENDENCIES $BUILD_DEPENDENCIES && \
3737
# see: https://github.com/Zer0CoolX/guacamole-install-rhel/issues/78#issuecomment-534620524
@@ -49,7 +49,7 @@ RUN mkdir /golang && \
4949
tar -xvf go${GO_VERSION}.linux-amd64.tar.gz
5050
ADD . .
5151
RUN ./guacamole/src/build-libguac.sh /occamy/guacamole
52-
RUN /golang/go/bin/go build -mod vendor -x -o occamyd
52+
RUN /golang/go/bin/go build -x -o occamyd cmd/occamyd/*
5353

5454
EXPOSE 5636
5555
CMD ["/occamy/occamyd"]

docker/docker-compose.yaml

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,24 +27,24 @@ services:
2727
networks:
2828
occamy_network:
2929
ipv4_address: 172.16.239.11
30-
rdp:
31-
# user: root, password: Docker
32-
image: umis/xubuntu-office-xrdp-desktop:v1.0
33-
container_name: rdp
34-
environment:
35-
- "USERNAME:root"
36-
- "PASSWORD:Docker"
37-
networks:
38-
occamy_network:
39-
ipv4_address: 172.16.239.12
30+
# rdp:
31+
# # user: root, password: Docker
32+
# image: umis/xubuntu-office-xrdp-desktop:v1.0
33+
# container_name: rdp
34+
# environment:
35+
# - "USERNAME:root"
36+
# - "PASSWORD:Docker"
37+
# networks:
38+
# occamy_network:
39+
# ipv4_address: 172.16.239.12
4040

41-
ssh:
42-
# user: root, password: root
43-
image: rastasheep/ubuntu-sshd:14.04
44-
container_name: ssh
45-
networks:
46-
occamy_network:
47-
ipv4_address: 172.16.239.13
41+
# ssh:
42+
# # user: root, password: root
43+
# image: rastasheep/ubuntu-sshd:14.04
44+
# container_name: ssh
45+
# networks:
46+
# occamy_network:
47+
# ipv4_address: 172.16.239.13
4848

4949
networks:
5050
occamy_network:

0 commit comments

Comments
 (0)