1
0
mirror of https://github.com/bingohuang/docker-labs.git synced 2025-10-05 01:43:22 +08:00

Add session persistence and use attach instead of exec

This commit is contained in:
Marcos Lilljedahl
2016-11-13 20:13:39 -03:00
parent dec3861c2c
commit 23bb4eaf69
6 changed files with 101 additions and 54 deletions

View File

@@ -1,8 +1,10 @@
package services
import (
"encoding/gob"
"log"
"math"
"os"
"sync"
"time"
@@ -13,17 +15,25 @@ import (
var wsServer *socketio.Server
type Session struct {
sync.Mutex
rw sync.Mutex
Id string `json:"id"`
Instances map[string]*Instance `json:"instances"`
Clients []*Client `json:"-"`
clients []*Client `json:"-"`
}
func (s *Session) Lock() {
s.rw.Lock()
}
func (s *Session) Unlock() {
s.rw.Unlock()
}
func (s *Session) GetSmallestViewPort() ViewPort {
minRows := s.Clients[0].ViewPort.Rows
minCols := s.Clients[0].ViewPort.Cols
minRows := s.clients[0].ViewPort.Rows
minCols := s.clients[0].ViewPort.Cols
for _, c := range s.Clients {
for _, c := range s.clients {
minRows = uint(math.Min(float64(minRows), float64(c.ViewPort.Rows)))
minCols = uint(math.Min(float64(minCols), float64(c.ViewPort.Cols)))
}
@@ -32,7 +42,7 @@ func (s *Session) GetSmallestViewPort() ViewPort {
}
func (s *Session) AddNewClient(c *Client) {
s.Clients = append(s.Clients, c)
s.clients = append(s.clients, c)
}
var sessions map[string]*Session
@@ -51,12 +61,12 @@ func CreateWSServer() *socketio.Server {
}
func CloseSession(s *Session) error {
s.Lock()
defer s.Unlock()
s.rw.Lock()
defer s.rw.Unlock()
wsServer.BroadcastTo(s.Id, "session end")
log.Printf("Starting clean up of session [%s]\n", s.Id)
for _, i := range s.Instances {
i.Conn.Close()
i.conn.Close()
if err := DeleteContainer(i.Name); err != nil {
log.Println(err)
return err
@@ -88,10 +98,39 @@ func NewSession() (*Session, error) {
log.Println("ERROR NETWORKING")
return nil, err
}
return s, nil
}
func GetSession(sessionId string) *Session {
return sessions[sessionId]
s := sessions[sessionId]
if s != nil {
for _, instance := range s.Instances {
if !instance.IsConnected() {
instance.SetSession(s)
go instance.Attach()
}
}
}
return s
}
func LoadSessionsFromDisk() error {
file, err := os.Open("./sessions.gob")
if err == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(&sessions)
}
file.Close()
return err
}
func saveSessionsToDisk() error {
file, err := os.Create("./sessions.gob")
if err == nil {
encoder := gob.NewEncoder(file)
err = encoder.Encode(&sessions)
}
file.Close()
return err
}