Skip to content

Commit

Permalink
Feature/save and kill processes (#18)
Browse files Browse the repository at this point in the history
* Save started processes to file and kill them at the next start

* Update threadfin.go
  • Loading branch information
marcelGoerentz committed Aug 19, 2024
1 parent 476c110 commit e066006
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 80 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,4 @@ VOLUME $THREADFIN_TEMP
EXPOSE $THREADFIN_PORT

# Run the Threadfin executable
ENTRYPOINT ${THREADFIN_BIN}/threadfin -port=${THREADFIN_PORT} -config=${THREADFIN_CONF} -debug=${THREADFIN_DEBUG}
ENTRYPOINT ${THREADFIN_BIN}/threadfin -port=${THREADFIN_PORT} -config=${THREADFIN_CONF} -debug=${THREADFIN_DEBUG} -branch=${BRANCH}
80 changes: 61 additions & 19 deletions src/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"io"
"log"
"net/http"
"runtime"

//"net/url"
"os"
Expand Down Expand Up @@ -934,7 +935,7 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum

case "ffmpeg":
path = Settings.FFmpegPath
options = fmt.Sprintf("%s", Settings.FFmpegOptions)
options = Settings.FFmpegOptions

case "vlc":
path = Settings.VLCPath
Expand Down Expand Up @@ -1038,7 +1039,6 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum
}

var cmd = exec.Command(path, args...)
//writePIDtoDisc(string(cmd.Process.Pid))

debug = fmt.Sprintf("%s:%s %s", bufferType, path, args)
showDebug(debug, 1)
Expand Down Expand Up @@ -1067,10 +1067,11 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum

cmd.Start()
defer cmd.Wait()
writePIDtoDisc(fmt.Sprintf("%d", cmd.Process.Pid))

go func() {

// Log Daten vom Prozess im Dubug Mode 1 anzeigen.
// Log Daten vom Prozess im Debug Mode 1 anzeigen.
scanner := bufio.NewScanner(logOut)
scanner.Split(bufio.ScanLines)

Expand Down Expand Up @@ -1126,11 +1127,10 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum
select {
case timeout := <-t:
if timeout >= 20 && tmpSegment == 1 {
cmd.Process.Kill()
err = errors.New("Timout")
terminateProcessGracefully(cmd)
err = errors.New("Timeout")
ShowError(err, 4006)
addErrorToStream(err)
cmd.Wait()
f.Close()
return
}
Expand All @@ -1144,9 +1144,8 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum
}

if !clientConnection(stream) {
cmd.Process.Kill()
terminateProcessGracefully(cmd)
f.Close()
cmd.Wait()
return
}

Expand All @@ -1158,10 +1157,9 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum
fileSize = fileSize + len(buffer[:n])

if _, err := f.Write(buffer[:n]); err != nil {
cmd.Process.Kill()
terminateProcessGracefully(cmd)
ShowError(err, 0)
addErrorToStream(err)
cmd.Wait()
return
}

Expand Down Expand Up @@ -1192,19 +1190,17 @@ func thirdPartyBuffer(streamID int, playlistID string, useBackup bool, backupNum
_, errCreate = bufferVFS.Create(tmpFile)
f, errOpen = bufferVFS.OpenFile(tmpFile, os.O_APPEND|os.O_WRONLY, 0600)
if errCreate != nil || errOpen != nil {
cmd.Process.Kill()
terminateProcessGracefully(cmd)
ShowError(err, 0)
addErrorToStream(err)
cmd.Wait()
return
}

}

}

cmd.Process.Kill()
cmd.Wait()
terminateProcessGracefully(cmd)

err = errors.New(bufferType + " error")

Expand Down Expand Up @@ -1337,15 +1333,21 @@ func debugResponse(resp *http.Response) {

func terminateProcessGracefully(cmd *exec.Cmd) {
if cmd.Process != nil {

// Send a SIGTERM to the process
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
// If an error occurred while trying to send the SIGTERM, you might resort to a SIGKILL.
ShowError(err, 0)
if runtime.GOOS == "windows" {
cmd.Process.Kill()
} else {
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
// If an error occurred while trying to send the SIGTERM, use SIGKILL.
ShowError(err, 0)
cmd.Process.Signal(syscall.SIGKILL)
}
}

// Optionally, you can wait for the process to finish too
cmd.Wait()
deletPIDfromDisc(fmt.Sprintf("%d", cmd.Process.Pid))
}
}

Expand All @@ -1364,6 +1366,46 @@ func writePIDtoDisc(pid string) {
}
}

func deletPIDfromDisc(pid string) {
log.Fatal("Nothing")
func deletPIDfromDisc(delete_pid string) (error){
file, err := os.OpenFile(System.Folder.Temp + "PIDs", os.O_RDWR, 0660)
if err != nil {
return err
}
// Create a scanner
scanner := bufio.NewScanner(file)

// Read line by line
pids := []string{}
for scanner.Scan() {
line := scanner.Text()
pids = append(pids, line)
}

// Rewind the file to the beginning
_, err = file.Seek(0, 0)
if err != nil {
return err
}

updatedPIDs := []string{}
for index, pid := range pids {
if pid != delete_pid {
// Create a new slice by excluding the element at the specified index
_, err = file.WriteString(pid + "\n")
if err != nil {
return err
}
} else {
updatedPIDs = append(pids[:index], pids[:index+1]...)
}
}

// Truncate any remaining content (if the new slice is shorter)
if len(updatedPIDs) < len(pids) {
err = file.Truncate(int64(len(updatedPIDs)))
if err != nil {
return err
}
}
return nil
}
58 changes: 29 additions & 29 deletions src/webUI.go

Large diffs are not rendered by default.

72 changes: 41 additions & 31 deletions threadfin.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ var GitHub = GitHubStruct{Branch: "Main", User: "marcelGoerentz", Repo: "Threadf
const Name = "Threadfin"

// Version : Version, die Build Nummer wird in der main func geparst.
const Version = "1.2.4-beta"
const Version = "1.3.0-beta"

// DBVersion : Datanbank Version
const DBVersion = "0.5.0"

// APIVersion : API Version
const APIVersion = "1.2.4-beta"
const APIVersion = "1.3.0-beta"

var homeDirectory = fmt.Sprintf("%s%s.%s%s", src.GetUserHomeDirectory(), string(os.PathSeparator), strings.ToLower(Name), string(os.PathSeparator))
var samplePath = fmt.Sprintf("%spath%sto%sthreadfin%s", string(os.PathSeparator), string(os.PathSeparator), string(os.PathSeparator), string(os.PathSeparator))
Expand Down Expand Up @@ -153,20 +153,27 @@ func main() {


// Kill all remaining processes and remove PIDs file
pids, err := getPIDsFromFile(*system)
if err != nil {
fmt.Printf("Error scanning file PIDs: %v", err)
} else {
if len(pids) > 0 {
for _, pid := range pids {
err := killProcess(pid)
if err != nil {
fmt.Printf("Error killing process %s: %v", pid, err)
} else {
fmt.Printf("Successfully killed process %s", pid)
tempFolder := os.TempDir() + string(os.PathSeparator) + strings.ToLower(Name) + string(os.PathSeparator)
folders, err := os.ReadDir(tempFolder)
if err == nil {
for _, folder := range folders {
folderName := fmt.Sprintf("%s%s", tempFolder, folder.Name())
pids, err := getPIDsFromFile(folderName)
if err != nil {
fmt.Printf("Error scanning file PIDs: %v", err)
} else {
if len(pids) > 0 {
for _, pid := range pids {
err := killProcess(pid)
if err != nil {
fmt.Printf("Error killing process %s: %v", pid, err)
} else {
fmt.Printf("Successfully killed process %s", pid)
}
}
os.Remove(folderName + string(os.PathSeparator) + "PIDs")
}
}
os.Remove(system.Folder.Temp + "PIDs")
}
}

Expand Down Expand Up @@ -238,28 +245,31 @@ func main() {

}

func getPIDsFromFile(system src.SystemStruct) ([]string, error){
var err error
func getPIDsFromFile(tempFolder string) ([]string, error){
pids := []string{}
// Open the file
pidsFile := system.Folder.Temp + "PIDs"
pidsFile := tempFolder + string(os.PathSeparator) + "PIDs"
_, err_stat := os.Stat(pidsFile)
if os.IsExist(err_stat) {
var file *os.File
file, err = os.Open(pidsFile)
defer file.Close() // Close the file when done

// Create a scanner
scanner := bufio.NewScanner(file)

// Read line by line
for scanner.Scan() {
line := scanner.Text()
pids = append(pids, line)
}
if os.IsNotExist(err_stat) {
return pids, nil // Return early if the file doesn't exist
}
return pids, err

file, err_open := os.Open(pidsFile)
if err_open != nil {
return nil, err_open
}
defer file.Close() // Close the file when done

// Create a scanner
scanner := bufio.NewScanner(file)

// Read line by line
for scanner.Scan() {
line := scanner.Text()
pids = append(pids, line)
}

return pids, nil
}

// killProcess kills a process by its PID
Expand Down

0 comments on commit e066006

Please sign in to comment.