Adding new restart mechanism

This commit is contained in:
Thomas Quandalle
2022-06-20 23:16:56 +02:00
parent 7c9ac68c33
commit 98e0c1dc54
16 changed files with 296 additions and 180 deletions
+17 -7
View File
@@ -1,10 +1,16 @@
{
"type": "template",
"key": "",
"key": "0x123-a-test-agent",
"name": "camera",
"mqtturi": "tcp://mqtt.kerberos.io",
"mqtt_username": "yourusername",
"mqtt_password": "yourpassword",
"timezone": "Europe/Brussels",
"stunuri": "stun:turn.kerberos.io:8443",
"turnuri": "turn:turn.kerberos.io:8443",
"turn_username": "username1",
"turn_password": "password1",
"heartbeaturi": "https://api.cloud.kerberos.io/devices/heartbeat",
"capture": {
"id": "ipcamera",
"ipcamera": {
@@ -22,7 +28,12 @@
"continuous": "false",
"postrecording": 10,
"prerecording": 5,
"maxlengthrecording": 10
"maxlengthrecording":60,
"forwardwebrtc": "",
"transcodingwebrtc": "false",
"transcodingresolution": 25,
"fragmented": "false",
"fragmentedduration": 1
},
"timetable": [
{
@@ -79,11 +90,10 @@
},
"cloud": "kstorage",
"kstorage": {
"uri": "",
"cloud_key": "",
"access_key": "",
"secret_access_key": "",
"uri": "https://staging.api.vault.kerberos.live",
"access_key": "ABCDEFGHI!@#$%12345",
"secret_access_key": "JKLMNOPQRSTUVWXYZ!@#$%67890",
"provider": "",
"directory": ""
"directory": "youruser"
}
}
+12 -13
View File
@@ -5,25 +5,21 @@ import (
"os"
"github.com/kerberos-io/agent/machinery/src/components"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"github.com/kerberos-io/agent/machinery/src/routers"
)
var log = components.Logging{
Logger: "logrus",
Level: "warning",
}
func main() {
const VERSION = "3.0"
action := os.Args[1]
log.Init()
log.Log.Init()
switch action {
case "version":
log.Info("You are currrently running Kerberos Agent " + VERSION)
log.Log.Info("You are currrently running Kerberos Agent " + VERSION)
case "pending-upload":
name := os.Args[2]
@@ -41,21 +37,24 @@ func main() {
// Read the config on start, and pass it to the other
// function and features. Please note that this might be changed
// when saving or updating the configuration through the REST api or MQTT handler.
var config models.Config
var customConfig models.Config
var globalConfig models.Config
var configuration models.Configuration
configuration.Name = name
configuration.Port = port
// Open this configuration either from Kerberos Agent or Kerberos Factory.
components.OpenConfig(name, log, &config, &customConfig, &globalConfig)
components.OpenConfig(&configuration)
// Bootstrapping the agent
components.Bootstrap(&config, log)
communication := models.Communication{
HandleBootstrap: make(chan string, 1),
}
go components.Bootstrap(&configuration, &communication)
// Start a MQTT listener.
routers.StartMqttListener(name)
// Start the REST API.
routers.StartWebserver(name, port, &config, &customConfig, &globalConfig)
routers.StartWebserver(&configuration, &communication)
}
default:
fmt.Println("Sorry I don't understand :(")
+10 -9
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/kerberos-io/agent/machinery/src/database"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"gopkg.in/mgo.v2/bson"
)
@@ -61,7 +62,7 @@ func ReadUserConfig() (userConfig models.User) {
return
}
func OpenConfig(name string, log Logging, config *models.Config, customConfig *models.Config, globalConfig *models.Config) {
func OpenConfig(configuration *models.Configuration) {
// We are checking which deployment this is running, so we can load
// into the configuration as expected.
@@ -75,17 +76,17 @@ func OpenConfig(name string, log Logging, config *models.Config, customConfig *m
for {
jsonFile, err := os.Open("./data/config/config.json")
if err != nil {
log.Error("Config file is not found " + "./data/config/config.json" + ", trying again in 5s.")
log.Log.Error("Config file is not found " + "./data/config/config.json" + ", trying again in 5s.")
time.Sleep(5 * time.Second)
} else {
log.Info("Successfully Opened config.json from " + name)
log.Log.Info("Successfully Opened config.json from " + configuration.Name)
byteValue, _ := ioutil.ReadAll(jsonFile)
err = json.Unmarshal(byteValue, config)
err = json.Unmarshal(byteValue, &configuration.Config)
jsonFile.Close()
if err != nil {
fmt.Println("JSON file not valid: " + err.Error())
} else {
err = json.Unmarshal(byteValue, customConfig)
err = json.Unmarshal(byteValue, &configuration.CustomConfig)
if err != nil {
fmt.Println("JSON file not valid: " + err.Error())
} else {
@@ -110,24 +111,24 @@ func OpenConfig(name string, log Logging, config *models.Config, customConfig *m
collection.Find(bson.M{
"type": "global",
}).One(&globalConfig)
}).One(&configuration.GlobalConfig)
collection.Find(bson.M{
"type": "config",
"name": os.Getenv("DEPLOYMENT_NAME"),
}).One(&customConfig)
}).One(&configuration.CustomConfig)
// We will merge both configs in a single config file.
// Read again from database but this store overwrite the same object.
collection.Find(bson.M{
"type": "global",
}).One(&config)
}).One(&configuration.Config)
collection.Find(bson.M{
"type": "config",
"name": os.Getenv("DEPLOYMENT_NAME"),
}).One(&config)
}).One(&configuration.Config)
}
return
+38 -33
View File
@@ -5,9 +5,10 @@ import (
"runtime"
"runtime/debug"
"strconv"
"sync/atomic"
"sync"
"time"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"github.com/kerberos-io/joy4/av/pubsub"
"github.com/kerberos-io/joy4/format/mp4"
@@ -42,7 +43,9 @@ func GetVideoDecoder(streams []av.CodecData) *ffmpeg.VideoDecoder {
return dec
}
func HandleStream(log Logging, queue *pubsub.Queue, stopHandleStream <-chan int64, packetsRead *atomic.Value, infile av.DemuxCloser) {
func HandleStream(infile av.DemuxCloser, queue *pubsub.Queue, communication *models.Communication, wg *sync.WaitGroup) {
log.Log.Debug("HandleStream: started")
var err error
loop:
for {
@@ -50,15 +53,15 @@ loop:
// This will check if we need to stop the thread,
// because of a reconfiguration.
select {
case <-stopHandleStream:
case <-communication.HandleStream:
break loop
default:
}
var pkt av.Packet
if pkt, err = infile.ReadPacket(); err != nil { // sometimes this throws an end of file..
log.Info(strconv.Itoa(len(pkt.Data)))
log.Error(err.Error())
log.Log.Info(strconv.Itoa(len(pkt.Data)))
log.Log.Error(err.Error())
if err.Error() == "EOF" {
time.Sleep(30 * time.Second)
}
@@ -72,7 +75,7 @@ loop:
// This will check if we need to stop the thread,
// because of a reconfiguration.
select {
case <-stopHandleStream:
case <-communication.HandleStream:
break loop
default:
}
@@ -91,9 +94,9 @@ loop:
// Increment packets, so we know the device
// is not blocking.
r := packetsRead.Load().(int64)
log.Info("HandleStream: packet size " + strconv.Itoa(len(pkt.Data)))
packetsRead.Store((r + 1) % 1000)
r := communication.PackageCounter.Load().(int64)
log.Log.Info("HandleStream: packet size " + strconv.Itoa(len(pkt.Data)))
communication.PackageCounter.Store((r + 1) % 1000)
/*select {
case packetsRealtime <- pkt:
@@ -106,10 +109,12 @@ loop:
}
}
}
wg.Done()
log.Log.Debug("HandleStream: finished")
}
func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan int64, devicename string, config *models.Config, streams []av.CodecData) {
log.Info("Start recording routine")
func RecordStream(recordingCursor *pubsub.QueueCursor, motion chan int64, devicename string, config *models.Config, streams []av.CodecData) {
log.Log.Debug("RecordStream: started")
recordingPeriod := config.Capture.PostRecording // number of seconds to record.
maxRecordingPeriod := config.Capture.MaxLengthRecording // maximum number of seconds to record.
@@ -123,7 +128,7 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
if config.Capture.Continuous == "true" {
// Do not do anything!
log.Info("Start continuous recording ")
log.Log.Info("Start continuous recording ")
loc, _ := time.LoadLocation(config.Timezone)
now = time.Now().Unix()
@@ -155,15 +160,15 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
// This will write the trailer a well.
if err := myMuxer.WriteTrailer(); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
log.Info("Recording finished: file save: " + name)
log.Log.Info("Recording finished: file save: " + name)
file.Close()
// Check if need to convert to fragmented using bento
if config.Capture.Fragmented == "true" && config.Capture.FragmentedDuration > 0 {
CreateFragmentedMP4(log, fullName, config.Capture.FragmentedDuration)
CreateFragmentedMP4(fullName, config.Capture.FragmentedDuration)
}
// Create a symbol link.
@@ -199,7 +204,7 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
(currentTimeInSeconds >= start2 && currentTimeInSeconds <= end2) {
} else {
log.Debug("Disabled: no continuous recording at this moment. Not within specified time interval.")
log.Log.Debug("Disabled: no continuous recording at this moment. Not within specified time interval.")
time.Sleep(5 * time.Second)
continue
}
@@ -223,35 +228,35 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
fullName = "./data/recordings/" + name
// Running...
log.Info("Recording started")
log.Log.Info("Recording started")
file, err = os.Create(fullName)
if err == nil {
myMuxer = mp4.NewMuxer(file)
}
log.Info("Recording starting: composing recording")
log.Info("Recording starting: write header")
log.Log.Info("Recording starting: composing recording")
log.Log.Info("Recording starting: write header")
// Creating the file, might block sometimes.
if err := myMuxer.WriteHeader(streams); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
if err := myMuxer.WritePacket(pkt); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
} else if start {
if err := myMuxer.WritePacket(pkt); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
}
}
} else {
log.Info("Start motion based recording ")
log.Log.Info("Start motion based recording ")
var myMuxer *mp4.Muxer
var file *os.File
@@ -277,7 +282,7 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
fullName := "./data/recordings/" + name
// Running...
log.Info("Recording started")
log.Log.Info("Recording started")
file, err = os.Create(fullName)
if err == nil {
myMuxer = mp4.NewMuxer(file)
@@ -285,11 +290,11 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
start := false
log.Info("Recording starting: composing recording")
log.Info("Recording starting: write header")
log.Log.Info("Recording starting: composing recording")
log.Log.Info("Recording starting: write header")
// Creating the file, might block sometimes.
if err := myMuxer.WriteHeader(streams); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
// Get as much packets we need.
@@ -306,26 +311,26 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
select {
case <-motion:
timestamp = now
log.Info("Recording expanding: motion detected while recording. Expanding recording.")
log.Log.Info("Recording expanding: motion detected while recording. Expanding recording.")
default:
}
if timestamp+recordingPeriod-now <= 0 || now-startRecording >= maxRecordingPeriod {
break
}
if pkt.IsKeyFrame {
log.Info("Recording writing: write frames")
log.Log.Info("Recording writing: write frames")
start = true
}
if start {
if err := myMuxer.WritePacket(pkt); err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
}
}
}
// This will write the trailer as well.
myMuxer.WriteTrailer()
log.Info("Recording finished: file save: " + name)
log.Log.Info("Recording finished: file save: " + name)
file.Close()
myMuxer = nil
runtime.GC()
@@ -333,7 +338,7 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
// Check if need to convert to fragmented using bento
if config.Capture.Fragmented == "true" && config.Capture.FragmentedDuration > 0 {
CreateFragmentedMP4(log, fullName, config.Capture.FragmentedDuration)
CreateFragmentedMP4(fullName, config.Capture.FragmentedDuration)
}
// Create a symbol linc.
@@ -342,5 +347,5 @@ func RecordStream(log Logging, recordingCursor *pubsub.QueueCursor, motion chan
}
}
log.Info("Stopped recording")
log.Log.Debug("RecordStream: finished")
}
+18 -11
View File
@@ -1,6 +1,7 @@
package components
import (
"fmt"
"image"
"io/ioutil"
"os"
@@ -11,10 +12,10 @@ import (
"sync"
"time"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"github.com/kerberos-io/joy4/av/pubsub"
mqtt "github.com/eclipse/paho.mqtt.golang"
geo "github.com/kellydunn/golang-geo"
"github.com/kerberos-io/joy4/av"
"github.com/kerberos-io/joy4/cgo/ffmpeg"
@@ -94,15 +95,17 @@ func ToRGB8(img image.YCbCr) (gocv.Mat, error) {
return gocv.NewMatFromBytes(y, x, gocv.MatTypeCV8UC3, bytes)
}
func ProcessMotion(log Logging, motionCursor *pubsub.QueueCursor, config *models.Config, name string, mqc mqtt.Client, motion chan<- int64, decoder *ffmpeg.VideoDecoder, decoderMutex *sync.Mutex) {
func ProcessMotion(motionCursor *pubsub.QueueCursor, configuration *models.Configuration, communication *models.Communication, decoder *ffmpeg.VideoDecoder, decoderMutex *sync.Mutex, wg *sync.WaitGroup) {
log.Log.Debug("ProcessMotion: started")
config := configuration.Config
if config.Capture.Continuous == "true" {
log.Info("Disabled Detecting motion...")
log.Log.Info("Disabled Detecting motion...")
} else {
log.Info("Start Detecting motion...")
log.Log.Info("Start Detecting motion...")
key := ""
if config.Cloud == "s3" && config.S3.Publickey != "" {
@@ -223,14 +226,15 @@ func ProcessMotion(log Logging, motionCursor *pubsub.QueueCursor, config *models
} else {
detectMotion = false
log.Debug("Disabled: not within time interval.")
log.Log.Debug("Disabled: not within time interval.")
}
}
if detectMotion && FindMotion(matArray, coordinatesToCheck, log) {
if detectMotion && FindMotion(matArray, coordinatesToCheck) {
// TODO create object for motion
mqc.Publish("kerberos/"+key+"/device/"+config.Key+"/motion", 2, false, "motion")
motion <- time.Now().Unix()
//mqc.Publish("kerberos/"+key+"/device/"+config.Key+"/motion", 2, false, "motion")
fmt.Println(key)
communication.HandleMotion <- strconv.FormatInt(time.Now().Unix(), 10)
}
}
@@ -247,11 +251,14 @@ func ProcessMotion(log Logging, motionCursor *pubsub.QueueCursor, config *models
}
runtime.GC()
debug.FreeOSMemory()
log.Info("Stopped motion")
log.Log.Info("Stopped motion")
}
wg.Done()
log.Log.Debug("ProcessMotion: finished")
}
func FindMotion(matArray [3]*gocv.Mat, coordinatesToCheck [][]int, log Logging) bool {
func FindMotion(matArray [3]*gocv.Mat, coordinatesToCheck [][]int) bool {
h1 := gocv.NewMat()
gocv.AbsDiff(*matArray[2], *matArray[0], &h1)
@@ -284,7 +291,7 @@ func FindMotion(matArray [3]*gocv.Mat, coordinatesToCheck [][]int, log Logging)
eroded.Close()
log.Info("Number of changes detected:" + strconv.Itoa(changes))
log.Log.Info("Number of changes detected:" + strconv.Itoa(changes))
if changes > 75 {
return true
+98 -48
View File
@@ -1,80 +1,130 @@
package components
import (
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"github.com/kerberos-io/joy4/av/pubsub"
"github.com/kerberos-io/joy4/cgo/ffmpeg"
)
func Bootstrap(config *models.Config, log Logging) {
log.Info("Start bootstrapping Agent")
func Bootstrap(configuration *models.Configuration, communication *models.Communication) {
log.Log.Debug("Bootstrap: started")
var packetsRead atomic.Value
packetsRead.Store(int64(0))
// Initiate the packet counter, this is being used to detect
// if a camera is going blocky, or got disconnected.
var packageCounter atomic.Value
packageCounter.Store(int64(0))
communication.PackageCounter = &packageCounter
log.Info("Creating livestream and webrtc channel")
livestreamChan := make(chan int64, 1)
webrtcKeepAlive := make(chan string)
webrtcPeers := make(chan string)
webrtcChan := make(chan models.SDPPayload, 1)
onvifActions := make(chan models.OnvifAction, 1)
// Before starting the agent, we have a control goroutine, that might
// do several checks to see if the agent is still operational.
go ControlAgent(communication)
log.Info("Starting configuration MQTT")
mqc := ConfigureMQTT(log, config, livestreamChan, webrtcChan, webrtcKeepAlive, webrtcPeers, onvifActions)
// Ring buffer of 250 images. 25FPS = 10sec. or if set to 0, use 1 by default.
preRecording := config.Capture.PreRecording * 25
if preRecording < 3 {
preRecording = 3
// Run the agent and fire up all the other
// goroutines which do image capture, motion detection, onvif, etc.
for {
go RunAgent(configuration, communication)
message := <-communication.HandleBootstrap
if message == "restart" {
StopAgent(configuration, communication)
} else {
StopAgent(configuration, communication)
break
}
// Depending on the message, you might do other funky shizzle..
// else if message == "stop" {
// StopAgent(configuration, communication)
// break
//}
}
log.Log.Debug("Bootstrap: finished")
}
// A channel to trigger the motion
motion := make(chan int64, 1)
func RunAgent(configuration *models.Configuration, communication *models.Communication) {
log.Log.Debug("RunAgent: started")
// A channel to stop the streaming loop
stopHandleStream := make(chan int64, 1)
config := configuration.Config
communication.HandleStream = make(chan string, 1)
communication.HandleMotion = make(chan string, 1)
// A channel to stop the uploading loop
//stopUpload := make(chan int64, 1)
// A channel to stop the sendalive loop
//stopSendAlive := make(chan int64, 1)
// open RTSP
log.Info("Opening RTSP stream")
// Establishing the camera connection
log.Log.Info("RunAgent: opening RTSP stream")
rtspUrl := config.Capture.IPCamera.RTSP
infile, streams, err := OpenRTSP(rtspUrl)
var decoder *ffmpeg.VideoDecoder
//var decoder *ffmpeg.VideoDecoder
var queue *pubsub.Queue
if err == nil {
var decoderMutex sync.Mutex
decoder = GetVideoDecoder(streams)
wg := sync.WaitGroup{}
var queue *pubsub.Queue
queue = pubsub.NewQueue()
queue.SetMaxGopCount(5) // GOP time frame is set to 5.
queue.WriteHeader(streams)
recordingCursor := queue.Oldest()
//livestreamCursor := queue.Oldest()
motionCursor := queue.Oldest()
//webrtcCursor := queue.Oldest()
name := config.Name
go RecordStream(log, recordingCursor, motion, name, config, streams)
go ProcessMotion(log, motionCursor, config, name, mqc, motion, decoder, &decoderMutex)
go HandleStream(log, queue, stopHandleStream, &packetsRead, infile)
//go cloud.StartUpload(log, config, name, stopUpload)
//go cloud.SendStillAlive(config, stopSendAlive)
//go cloud.SendLiveStream(config, livestreamCursor, mqc, decoder, &decoderMutex, log, livestreamChan)
//go cloud.SendWebRTCStream(config, webrtcCursor, mqc, streams, log, webrtcChan, webrtcKeepAlive, webrtcPeers, decoder, &decoderMutex)
//go onvif.HandleActions(log, config, onvifActions)
// Start handling the stream
wg.Add(1)
go HandleStream(infile, queue, communication, &wg)
// Start processing of motion
wg.Add(1)
motionCursor := queue.Oldest()
var decoderMutex sync.Mutex
decoder := GetVideoDecoder(streams)
go ProcessMotion(motionCursor, configuration, communication, decoder, &decoderMutex, &wg)
wg.Wait()
} else {
log.Error("Something went wrong while opening RTSP: " + err.Error())
log.Log.Error("Something went wrong while opening RTSP: " + err.Error())
}
// Here we are cleaning up everything!
infile.Close()
queue.Close()
log.Log.Debug("RunAgent: finished")
}
func StopAgent(configuration *models.Configuration, communication *models.Communication) {
log.Log.Debug("StopAgent: started")
communication.HandleStream <- "stop"
communication.HandleMotion <- "stop"
log.Log.Debug("StopAgent: finished")
}
func ControlAgent(communication *models.Communication) {
log.Log.Debug("ControlAgent: started")
packageCounter := communication.PackageCounter
go func() {
// A channel to check the camera activity
var previousPacket int64 = 0
var occurence = 0
for {
packetsR := packageCounter.Load().(int64)
if packetsR == previousPacket {
occurence = occurence + 1
} else {
occurence = 0
}
log.Log.Info("Number of packets read " + strconv.FormatInt(packetsR, 10))
// After 15 seconds without activity this is thrown..
if occurence == 3 {
log.Log.Info("Main: Restarting machinery.")
communication.HandleBootstrap <- "restart"
time.Sleep(2 * time.Second)
occurence = 0
}
previousPacket = packageCounter.Load().(int64)
time.Sleep(5 * time.Second)
}
}()
log.Log.Debug("ControlAgent: finished")
}
+15 -15
View File
@@ -8,6 +8,7 @@ import (
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
)
@@ -15,8 +16,7 @@ var (
CandidateArrays map[string](chan string)
)
func ConfigureMQTT(log Logging,
config *models.Config,
func ConfigureMQTT(config *models.Config,
livestreamChan chan int64,
webrtcChan chan models.SDPPayload,
webrtcKeepAlive chan string,
@@ -31,8 +31,8 @@ func ConfigureMQTT(log Logging,
if mqtt_username != "" || mqtt_password != "" {
opts.SetUsername(mqtt_username)
opts.SetPassword(mqtt_password)
log.Info("MQTT: set username " + mqtt_username)
log.Info("MQTT: set password " + mqtt_password)
log.Log.Info("MQTT: set username " + mqtt_username)
log.Log.Info("MQTT: set password " + mqtt_password)
}
opts.SetCleanSession(true)
@@ -62,29 +62,29 @@ func ConfigureMQTT(log Logging,
randomKerberosHubKey = config.Key
}
opts.SetClientID(randomKerberosHubKey)
log.Info("MQTT: set ClientID " + randomKerberosHubKey)
log.Log.Info("MQTT: set ClientID " + randomKerberosHubKey)
rand.Seed(time.Now().UnixNano())
CandidateArrays = make(map[string](chan string))
opts.OnConnect = func(c mqtt.Client) {
// Create a subscription for the MQTT livestream.
log.Info("MQTT " + randomKerberosHubKey + ": connected to " + mqttURL)
log.Log.Info("MQTT " + randomKerberosHubKey + ": connected to " + mqttURL)
topicRequest := "kerberos/" + key + "/device/" + config.Key + "/request-live"
log.Info("MQTT: sending logs to " + topicRequest)
log.Log.Info("MQTT: sending logs to " + topicRequest)
c.Subscribe(topicRequest, 0, func(c mqtt.Client, msg mqtt.Message) {
select {
case livestreamChan <- time.Now().Unix():
default:
}
log.Info("Livestream " + randomKerberosHubKey + ": received request to livestream.")
log.Log.Info("Livestream " + randomKerberosHubKey + ": received request to livestream.")
msg.Ack()
})
// Create a subscription for the WEBRTC livestream.
topicRequestWebRtc := config.Key + "/register"
c.Subscribe(topicRequestWebRtc, 0, func(c mqtt.Client, msg mqtt.Message) {
log.Info("Webrtc " + randomKerberosHubKey + ": received request to setup webrtc.")
log.Log.Info("Webrtc " + randomKerberosHubKey + ": received request to setup webrtc.")
var sdp models.SDPPayload
json.Unmarshal(msg.Payload(), &sdp)
select {
@@ -98,14 +98,14 @@ func ConfigureMQTT(log Logging,
c.Subscribe(topicKeepAlive, 0, func(c mqtt.Client, msg mqtt.Message) {
alive := string(msg.Payload())
webrtcKeepAlive <- alive
log.Info("WEBRTC (Forward): Received keepalive: " + alive)
log.Log.Info("WEBRTC (Forward): Received keepalive: " + alive)
})
topicPeers := fmt.Sprintf("kerberos/webrtc/peers/%s", config.Key)
c.Subscribe(topicPeers, 0, func(c mqtt.Client, msg mqtt.Message) {
peerCount := string(msg.Payload())
webrtcPeers <- peerCount
log.Info("WEBRTC (Forward): Number of peers listening: " + peerCount)
log.Log.Info("WEBRTC (Forward): Number of peers listening: " + peerCount)
})
//candidates := make(chan string)
@@ -121,7 +121,7 @@ func ConfigureMQTT(log Logging,
CandidateArrays[key] = val
channel = val
}
log.Info("WEBRTC (Remote): " + string(msg.Payload()))
log.Log.Info("WEBRTC (Remote): " + string(msg.Payload()))
channel <- string(msg.Payload())
}
})
@@ -132,20 +132,20 @@ func ConfigureMQTT(log Logging,
var onvifAction models.OnvifAction
json.Unmarshal(msg.Payload(), &onvifAction)
onvifActions <- onvifAction
log.Info("Onvif (action): Received an action - " + onvifAction.Action)
log.Log.Info("Onvif (action): Received an action - " + onvifAction.Action)
})
}
}
mqc := mqtt.NewClient(opts)
if token := mqc.Connect(); token.WaitTimeout(5 * time.Second) {
if token.Error() != nil {
log.Error("MQTT: unable to establish mqtt broker connection, error was: " + token.Error().Error())
log.Log.Error("MQTT: unable to establish mqtt broker connection, error was: " + token.Error().Error())
}
}
return mqc
}
func DisconnectMQTT(log Logging, config models.Config, mqc mqtt.Client) {
func DisconnectMQTT(config models.Config, mqc mqtt.Client) {
//topicRequest := "kerberos/" + config.S3.Publickey + "/device/" + config.Key + "/request-live"
//mqc.Unsubscribe(topicRequest)
mqc.Disconnect(1000)
+7 -6
View File
@@ -4,21 +4,22 @@ import (
"time"
"github.com/cedricve/go-onvif"
"github.com/kerberos-io/agent/machinery/src/log"
)
func Discover(log Logging, timeout time.Duration) {
log.Info("Discovering devices")
log.Info("Waiting for " + (timeout * time.Second).String())
func Discover(timeout time.Duration) {
log.Log.Info("Discovering devices")
log.Log.Info("Waiting for " + (timeout * time.Second).String())
devices, err := onvif.StartDiscovery(timeout * time.Second)
if err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
} else {
for _, device := range devices {
hostname, _ := device.GetHostname()
log.Info(hostname.Name)
log.Log.Info(hostname.Name)
}
if len(devices) == 0 {
log.Info("No devices descovered\n")
log.Log.Info("No devices descovered\n")
}
}
}
+8 -6
View File
@@ -8,6 +8,8 @@ import (
"os"
"os/exec"
"strconv"
"github.com/kerberos-io/agent/machinery/src/log"
)
const letterBytes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
@@ -20,10 +22,10 @@ func CountDigits(i int64) (count int) {
return count
}
func ReadDirectory(log Logging, directory string) ([]os.FileInfo, error) {
func ReadDirectory(directory string) ([]os.FileInfo, error) {
ff, err := ioutil.ReadDir(directory)
if err != nil {
log.Error(err.Error())
log.Log.Error(err.Error())
return []os.FileInfo{}, nil
}
return ff, err
@@ -37,21 +39,21 @@ func RandStringBytesRmndr(n int) string {
return string(b)
}
func CreateFragmentedMP4(log Logging, fullName string, fragmentedDuration int64) {
func CreateFragmentedMP4(fullName string, fragmentedDuration int64) {
path, _ := os.Getwd()
duration := fragmentedDuration * 1000
cmd := exec.Command("mp4fragment", "--fragment-duration", strconv.FormatInt(duration, 10), fullName, fullName+"f.mp4")
cmd.Dir = path
log.Info(cmd.String())
log.Log.Info(cmd.String())
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
log.Error(fmt.Sprint(err) + ": " + stderr.String())
log.Log.Error(fmt.Sprint(err) + ": " + stderr.String())
} else {
log.Info("Created Fragmented: " + out.String())
log.Log.Info("Created Fragmented: " + out.String())
}
// We will swap the files.
+21 -21
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"runtime"
"runtime/debug"
"strconv"
@@ -13,6 +12,7 @@ import (
"sync/atomic"
"time"
"github.com/kerberos-io/agent/machinery/src/log"
"github.com/kerberos-io/agent/machinery/src/models"
"github.com/kerberos-io/joy4/av/pubsub"
@@ -72,7 +72,7 @@ func CreateWebRTC(name string, stunServers []string, turnServers []string, turnS
func (w WebRTC) DecodeSessionDescription(data string) ([]byte, error) {
sd, err := base64.StdEncoding.DecodeString(data)
if err != nil {
log.Println("DecodeString error", err)
log.Log.Error("DecodeString error: " + err.Error())
return []byte{}, err
}
return sd, nil
@@ -86,7 +86,7 @@ func (w WebRTC) CreateOffer(sd []byte) pionWebRTC.SessionDescription {
return offer
}
func InitializeWebRTCConnection(track *pionWebRTC.TrackLocalStaticSample, config models.Config, m models.SDPPayload, c mqtt.Client, log Logging, candidates chan string) {
func InitializeWebRTCConnection(track *pionWebRTC.TrackLocalStaticSample, config models.Config, m models.SDPPayload, c mqtt.Client, candidates chan string) {
name := config.Key
stunServers := []string{config.STUNURI}
@@ -152,13 +152,13 @@ func InitializeWebRTCConnection(track *pionWebRTC.TrackLocalStaticSample, config
atomic.AddInt64(&peerConnectionCount, 1)
} else if connectionState == pionWebRTC.ICEConnectionStateChecking {
for candidate := range candidates {
log.Info("WEBRTC (Remote): received candidate.")
log.Log.Info("WEBRTC (Remote): received candidate.")
if candidateErr := peerConnection.AddICECandidate(pionWebRTC.ICECandidateInit{Candidate: string(candidate)}); candidateErr != nil {
}
}
}
log.Info("WEBRTC: connection state changed to: " + connectionState.String())
log.Info("WEBRTC: Number of peers connected (" + strconv.FormatInt(peerConnectionCount, 10) + ")")
log.Log.Info("WEBRTC: connection state changed to: " + connectionState.String())
log.Log.Info("WEBRTC: Number of peers connected (" + strconv.FormatInt(peerConnectionCount, 10) + ")")
})
offer := w.CreateOffer(sd)
@@ -189,13 +189,13 @@ func InitializeWebRTCConnection(track *pionWebRTC.TrackLocalStaticSample, config
defer candidatesMux.Unlock()
topic := fmt.Sprintf("%s/%s/candidate/edge", name, m.Cuuid)
log.Info("WEBRTC (LOCAL): Send candidate to " + topic)
log.Log.Info("WEBRTC (LOCAL): Send candidate to " + topic)
candiInit := candidate.ToJSON()
sdpmid := "0"
candiInit.SDPMid = &sdpmid
candi, err := json.Marshal(candiInit)
if err == nil {
log.Info("WEBRTC (LOCAL):" + string(candi))
log.Log.Info("WEBRTC (LOCAL):" + string(candi))
token := c.Publish(topic, 2, false, candi)
token.Wait()
}
@@ -205,7 +205,7 @@ func InitializeWebRTCConnection(track *pionWebRTC.TrackLocalStaticSample, config
if err == nil {
topic := fmt.Sprintf("%s/%s/answer", name, m.Cuuid)
log.Info("WEBRTC (LOCAL): Send SDP answer to " + topic)
log.Log.Info("WEBRTC (LOCAL): Send SDP answer to " + topic)
c.Publish(topic, 2, false, []byte(base64.StdEncoding.EncodeToString([]byte(answer.SDP))))
}
}
@@ -216,7 +216,7 @@ func NewVideoTrack() *pionWebRTC.TrackLocalStaticSample {
return outboundVideoTrack
}
func WriteToTrack(key string, keepalive chan string, peers chan string, forwardWebRTC string, transcodingWebRTC string, transcodingResolution int64, log Logging, track *pionWebRTC.TrackLocalStaticSample, livestreamCursor *pubsub.QueueCursor, packets chan av.Packet, codecs []av.CodecData, mqc mqtt.Client, decoder *ffmpeg.VideoDecoder, decoderMutex *sync.Mutex) {
func WriteToTrack(key string, keepalive chan string, peers chan string, forwardWebRTC string, transcodingWebRTC string, transcodingResolution int64, track *pionWebRTC.TrackLocalStaticSample, livestreamCursor *pubsub.QueueCursor, packets chan av.Packet, codecs []av.CodecData, mqc mqtt.Client, decoder *ffmpeg.VideoDecoder, decoderMutex *sync.Mutex) {
// Make peerconnection map
peerConnections = make(map[string]*pionWebRTC.PeerConnection)
@@ -225,10 +225,10 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
// Later when we read a packet we need to figure out which track to send it to.
videoIdx := -1
audioIdx := -1
log.Info("WEBRTC: listing codecs.")
log.Log.Info("WEBRTC: listing codecs.")
for i, codec := range codecs {
log.Info("WEBRTC: codec - " + codec.Type().String() + " found.")
log.Info(codec.Type().String())
log.Log.Info("WEBRTC: codec - " + codec.Type().String() + " found.")
log.Log.Info(codec.Type().String())
if codec.Type().String() == "H264" && videoIdx < 0 {
videoIdx = i
} else if codec.Type().String() == "PCM_MULAW" && audioIdx < 0 {
@@ -237,18 +237,18 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
}
if videoIdx == -1 {
log.Error("WEBRTC: no video codec found.")
log.Log.Error("WEBRTC: no video codec found.")
} else {
annexbNALUStartCode := func() []byte { return []byte{0x00, 0x00, 0x00, 0x01} }
if transcodingWebRTC == "true" {
if videoIdx > -1 {
log.Info("WEBRTC: successfully using a transcoder.")
log.Log.Info("WEBRTC: successfully using a transcoder.")
} else {
//trans = nil
}
} else {
log.Info("WEBRTC: not using a transcoder.")
log.Log.Info("WEBRTC: not using a transcoder.")
//trans = nil
}
@@ -344,10 +344,10 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
pkt.Data = append(annexbNALUStartCode(), pkt.Data...)
pkt.Data = append(codecData.(h264parser.CodecData).SPS(), pkt.Data...)
pkt.Data = append(annexbNALUStartCode(), pkt.Data...)
log.Info("WEBRTC: Sending keyframe")
log.Log.Info("WEBRTC: Sending keyframe")
if forwardWebRTC == "true" {
log.Info("WEBRTC: Sending keep a live to remote broker.")
log.Log.Info("WEBRTC: Sending keep a live to remote broker.")
topic := fmt.Sprintf("kerberos/webrtc/keepalive/%s", key)
mqc.Publish(topic, 2, false, "1")
}
@@ -363,7 +363,7 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
topic := fmt.Sprintf("kerberos/webrtc/packets/%s", key)
mqc.Publish(topic, 0, false, samplePacket)
} else {
log.Info("WEBRTC: Error marshalling frame, " + err.Error())
log.Log.Info("WEBRTC: Error marshalling frame, " + err.Error())
}
} else {
if err := track.WriteSample(sample); err != nil && err != io.ErrClosedPipe {
@@ -372,7 +372,7 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
}
}
case audioIdx:
log.Info("WEBRTC: not writing audio for the moment.")
log.Log.Info("WEBRTC: not writing audio for the moment.")
}
}
}
@@ -384,5 +384,5 @@ func WriteToTrack(key string, keepalive chan string, peers chan string, forwardW
close(peers)
close(keepalive)
peerConnectionCount = 0
log.Info("WEBRTC: stop writing to track.")
log.Log.Info("WEBRTC: stop writing to track.")
}
@@ -1,4 +1,4 @@
package components
package log
import (
"os"
@@ -8,6 +8,12 @@ import (
"gopkg.in/natefinch/lumberjack.v2"
)
// The logging library being used everywhere.
var Log = Logging{
Logger: "logrus",
Level: "debug",
}
// -----------------
// This a gologging
// -> github.com/op/go-logging
@@ -47,7 +53,7 @@ func ConfigureLogrus() {
logrus.SetOutput(os.Stdout)
// Only log the warning severity or above.
logrus.SetLevel(logrus.InfoLevel)
logrus.SetLevel(logrus.DebugLevel)
}
func NewLogger(logger string, level string) *Logging {
+12
View File
@@ -0,0 +1,12 @@
package models
import "sync/atomic"
// The communication struct that is managing
// all the communication between the different goroutines.
type Communication struct {
PackageCounter *atomic.Value
HandleBootstrap chan string
HandleStream chan string
HandleMotion chan string
}
+9
View File
@@ -1,5 +1,14 @@
package models
// A struct which contains the global, local and merged config.
type Configuration struct {
Name string
Port string
Config Config
CustomConfig Config
GlobalConfig Config
}
//Config is the highlevel struct which contains all the configuration of
//your Kerberos Open Source instance.
type Config struct {
+18 -4
View File
@@ -7,7 +7,7 @@ import (
"github.com/kerberos-io/agent/machinery/src/models"
)
func AddRoutes(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware, config *models.Config, customConfig *models.Config, globalConfig *models.Config) *gin.RouterGroup {
func AddRoutes(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware, configuration *models.Configuration, communication *models.Communication) *gin.RouterGroup {
api := r.Group("/api")
{
api.POST("/login", authMiddleware.LoginHandler)
@@ -16,13 +16,27 @@ func AddRoutes(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware, config *mode
api.GET("/config", func(c *gin.Context) {
c.JSON(200, gin.H{
"config": config,
"custom": customConfig,
"global": globalConfig,
"config": configuration.Config,
"custom": configuration.CustomConfig,
"global": configuration.GlobalConfig,
"snapshot": components.GetSnapshot(),
})
})
api.GET("/restart", func(c *gin.Context) {
communication.HandleBootstrap <- "restart"
c.JSON(200, gin.H{
"restarted": true,
})
})
api.GET("/stop", func(c *gin.Context) {
communication.HandleBootstrap <- "stop"
c.JSON(200, gin.H{
"stopped": true,
})
})
api.Use(authMiddleware.MiddlewareFunc())
{
// Secured endpoints..
+3 -3
View File
@@ -33,7 +33,7 @@ import (
// @in header
// @name Authorization
func StartServer(name string, port string, config *models.Config, customConfig *models.Config, globalConfig *models.Config) {
func StartServer(configuration *models.Configuration, communication *models.Communication) {
// Initialize REST API
r := gin.Default()
@@ -55,7 +55,7 @@ func StartServer(name string, port string, config *models.Config, customConfig *
}
// Add all routes
AddRoutes(r, authMiddleware, config, customConfig, globalConfig)
AddRoutes(r, authMiddleware, configuration, communication)
// Add static routes to UI
r.Use(static.Serve("/", static.LocalFile("./www", true)))
@@ -65,7 +65,7 @@ func StartServer(name string, port string, config *models.Config, customConfig *
r.Use(static.Serve("/login", static.LocalFile("./www", true)))
// Run the api on port
err = r.Run(":" + port)
err = r.Run(":" + configuration.Port)
if err != nil {
log.Fatal(err)
}
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"github.com/kerberos-io/agent/machinery/src/routers/mqtt"
)
func StartWebserver(name string, port string, config *models.Config, customConfig *models.Config, globalConfig *models.Config) {
http.StartServer(name, port, config, customConfig, globalConfig)
func StartWebserver(configuration *models.Configuration, communication *models.Communication) {
http.StartServer(configuration, communication)
}
func StartMqttListener(name string) {