2024-01-27 11:20:40 +01:00
|
|
|
package pods
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
2024-01-28 15:31:58 +01:00
|
|
|
"time"
|
2024-01-27 11:20:40 +01:00
|
|
|
|
|
|
|
"github.com/containers/podman/v4/pkg/bindings"
|
|
|
|
"github.com/containers/podman/v4/pkg/bindings/containers"
|
|
|
|
"github.com/containers/podman/v4/pkg/bindings/images"
|
2024-01-28 15:31:58 +01:00
|
|
|
"github.com/containers/podman/v4/pkg/domain/entities"
|
|
|
|
"github.com/spf13/viper"
|
2024-01-27 11:20:40 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var Socket context.Context
|
|
|
|
|
|
|
|
func socketConnection() context.Context {
|
|
|
|
uri := "unix:///run/podman/podman.sock"
|
|
|
|
conn, err := bindings.NewConnection(context.Background(), uri)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
return conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestPodman() {
|
|
|
|
_ = socketConnection()
|
|
|
|
}
|
|
|
|
|
|
|
|
func ConnectSocket() {
|
|
|
|
Socket = socketConnection()
|
|
|
|
}
|
|
|
|
|
2024-01-29 16:45:51 +01:00
|
|
|
func PullImage() error {
|
2024-01-28 15:31:58 +01:00
|
|
|
log.Println("Downloading Container image ", viper.GetString("image"))
|
|
|
|
image := viper.GetString("image")
|
2024-01-27 11:20:40 +01:00
|
|
|
conn := Socket
|
|
|
|
_, err := images.Pull(conn, image, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
2024-01-29 16:45:51 +01:00
|
|
|
return err
|
2024-01-27 11:20:40 +01:00
|
|
|
}
|
2024-01-29 16:45:51 +01:00
|
|
|
return nil
|
2024-01-27 11:20:40 +01:00
|
|
|
}
|
|
|
|
|
2024-01-28 15:31:58 +01:00
|
|
|
// Cleanup deletes Containers older than the specified maximum Age (Equal to session cookie maximum age)
|
2024-01-29 16:45:51 +01:00
|
|
|
func Cleanup() error {
|
2024-01-28 15:31:58 +01:00
|
|
|
log.Println("Starting cleanup function")
|
|
|
|
containerList := containerList()
|
|
|
|
|
2024-01-27 11:20:40 +01:00
|
|
|
for _, container := range containerList {
|
2024-01-28 15:31:58 +01:00
|
|
|
now := time.Now()
|
|
|
|
maxAge := time.Second * time.Duration(viper.GetInt("maxAge"))
|
|
|
|
containerAge := now.Sub(container.Created)
|
|
|
|
if containerAge > maxAge {
|
|
|
|
|
|
|
|
err := containers.Kill(Socket, container.ID, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
2024-01-29 16:45:51 +01:00
|
|
|
return err
|
2024-01-28 15:31:58 +01:00
|
|
|
}
|
|
|
|
_, err = containers.Remove(Socket, container.ID, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
2024-01-29 16:45:51 +01:00
|
|
|
return err
|
2024-01-28 15:31:58 +01:00
|
|
|
}
|
2024-01-27 11:20:40 +01:00
|
|
|
}
|
|
|
|
}
|
2024-01-29 16:45:51 +01:00
|
|
|
return nil
|
2024-01-28 15:31:58 +01:00
|
|
|
}
|
2024-01-27 11:20:40 +01:00
|
|
|
|
2024-01-28 15:31:58 +01:00
|
|
|
func containerList() []entities.ListContainer {
|
|
|
|
containerList, err := containers.List(Socket, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Could not get Containers", err)
|
|
|
|
}
|
|
|
|
return containerList
|
2024-01-27 11:20:40 +01:00
|
|
|
}
|