fedilogue/ctl.go
Farhan Khan a122f72af7 Fully migrated to jsonb, adjusted uniquefifo to keep cache fresh
* Added fifo mechanism to actors table
* Increased fifo size to 10
* Still getting some database insert duplicate errors, but only for
  very active instances when they are newly identified
2021-02-02 23:34:43 +00:00

120 lines
2.6 KiB
Go

package main
import (
"encoding/binary"
"encoding/json"
"io"
"net"
)
func startctl() {
logInfo.Print("Starting ctl listener on 127.0.0.1:5555")
l, err := net.Listen("tcp", "127.0.0.1:5555")
if err != nil {
logFatal.Fatal("Unable to start listener:", err)
}
defer l.Close()
commandClient := make(chan net.Conn)
go func(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
logFatal.Fatal("Error on accept", err)
}
commandClient <- c
}
}(l)
for {
c := <-commandClient // New client connection
go handleClient(c)
}
}
func handleClient(commandClient net.Conn) {
defer commandClient.Close()
sizebyte := make([]byte, 4)
var commandmap CommandMap
var responseback ResponseBack
n, err := io.ReadFull(commandClient, sizebyte)
if err != nil {
logFatal.Fatal("Read error: ", err)
return
}
if n != 4 {
logFatal.Fatal("Did not read 4 bytes, failure.")
return
}
jsonsize := int(binary.LittleEndian.Uint32(sizebyte))
jsonbyte := make([]byte, jsonsize)
n, err = io.ReadFull(commandClient, jsonbyte)
if err != nil {
logFatal.Fatal("Unable to unmarshal")
}
if n != jsonsize {
logFatal.Fatal("Failed to read json size of ", n)
}
err = json.Unmarshal(jsonbyte, &commandmap)
if err != nil {
logFatal.Fatal("Unable to unmarshal")
}
switch commandmap.Type {
case "status":
responseback.Message = "Ok"
case "add":
logInfo.Print("Manually added instance: " + commandmap.Endpoint)
ri_mutex.Lock()
_, exists := runninginstances[commandmap.Endpoint]
if exists == true {
logInfo.Println("Already exists: " + commandmap.Endpoint)
responseback.Message = "Exists: " + commandmap.Endpoint
} else {
responseback.Message = "Adding: " + commandmap.Endpoint
o := RunningInstance{}
o.recentactivities = newUniqueFifo(10)
o.recentactors = newUniqueFifo(10)
o.client = BuildClient(commandmap.Endpoint)
runninginstances[commandmap.Endpoint] = o
go StartInstance(commandmap.Endpoint)
}
ri_mutex.Unlock()
case "suspend":
logFatal.Fatal("Suspend")
case "resume":
logFatal.Fatal("Resume")
default:
logFatal.Fatal("Something else")
}
responseback.Type = "status"
responseback.RunningInstances = runninginstances
responsebytes, err := json.Marshal(responseback)
if err != nil {
logErr.Fatal(err)
}
n = len(responsebytes)
binary.LittleEndian.PutUint32(sizebyte, uint32(n))
_, err = commandClient.Write(sizebyte)
if err != nil {
logFatal.Fatal("Error on write:", err)
}
responsebyte, err := json.Marshal(responseback)
if err != nil {
logFatal.Fatal("Error response back: ", err)
}
_, err = commandClient.Write(responsebyte)
if err != nil {
logFatal.Fatal("Error on write:", err)
}
}