Updates and new features on the Go Wrapper

This commit is contained in:
FlUxIuS 2024-06-28 11:14:25 +02:00
parent 0ac78aa05e
commit a1db2387d3
No known key found for this signature in database
GPG Key ID: E8B96449EE4FA72F
3 changed files with 227 additions and 76 deletions

View File

@ -82,7 +82,9 @@ var lastCmd = &cobra.Command{
Short: "last container run", Short: "last container run",
Long: `Display the latest container that was run`, Long: `Display the latest container that was run`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
rfdock.DockerLast(FilterLast) labelKey := "org.container.project"
labelValue := "rfswift"
rfdock.DockerLast(FilterLast, labelKey, labelValue)
}, },
} }
@ -175,6 +177,27 @@ var winusbdetachCmd = &cobra.Command{
}, },
} }
var ImagesCmd = &cobra.Command{
Use: "images",
Short: "show rfswift images",
Long: `Display images build for RF Swift`,
Run: func(cmd *cobra.Command, args []string) {
labelKey := "org.container.project"
labelValue := "rfswift"
images_list, err := rfdock.ListImages(labelKey, labelValue)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
for _, image := range images_list {
fmt.Println("ID:", image.ID)
fmt.Println("RepoTags:", image.RepoTags)
fmt.Println("Labels:", image.Labels)
fmt.Println()
}
},
}
func init() { func init() {
rootCmd.AddCommand(runCmd) rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(lastCmd) rootCmd.AddCommand(lastCmd)
@ -184,6 +207,7 @@ func init() {
rootCmd.AddCommand(renameCmd) rootCmd.AddCommand(renameCmd)
rootCmd.AddCommand(installCmd) rootCmd.AddCommand(installCmd)
rootCmd.AddCommand(removeCmd) rootCmd.AddCommand(removeCmd)
rootCmd.AddCommand(ImagesCmd)
// Adding special commands for Windows // Adding special commands for Windows
os := runtime.GOOS os := runtime.GOOS
@ -202,7 +226,7 @@ func init() {
pullCmd.Flags().StringVarP(&ImageRef, "image", "i", "", "image reference") pullCmd.Flags().StringVarP(&ImageRef, "image", "i", "", "image reference")
pullCmd.Flags().StringVarP(&ImageTag, "tag", "t", "", "rename to target tag") pullCmd.Flags().StringVarP(&ImageTag, "tag", "t", "", "rename to target tag")
pullCmd.MarkFlagRequired("image") pullCmd.MarkFlagRequired("image")
pullCmd.MarkFlagRequired("tag") //pullCmd.MarkFlagRequired("tag")
renameCmd.Flags().StringVarP(&ImageRef, "image", "i", "", "image reference") renameCmd.Flags().StringVarP(&ImageRef, "image", "i", "", "image reference")
renameCmd.Flags().StringVarP(&ImageTag, "tag", "t", "", "rename to target tag") renameCmd.Flags().StringVarP(&ImageTag, "tag", "t", "", "rename to target tag")
commitCmd.Flags().StringVarP(&ContID, "container", "c", "", "container to run") commitCmd.Flags().StringVarP(&ContID, "container", "c", "", "container to run")
@ -210,15 +234,15 @@ func init() {
commitCmd.MarkFlagRequired("container") commitCmd.MarkFlagRequired("container")
commitCmd.MarkFlagRequired("image") commitCmd.MarkFlagRequired("image")
execCmd.Flags().StringVarP(&ContID, "container", "c", "", "container to run") execCmd.Flags().StringVarP(&ContID, "container", "c", "", "container to run")
execCmd.Flags().StringVarP(&ExecCmd, "command", "e", "", "command to exec (required!)") execCmd.Flags().StringVarP(&ExecCmd, "command", "e", "/bin/bash", "command to exec (by default: /bin/bash)")
execCmd.Flags().StringVarP(&SInstall, "install", "i", "", "install from function script (e.g: 'sdrpp_soft_install')") execCmd.Flags().StringVarP(&SInstall, "install", "i", "", "install from function script (e.g: 'sdrpp_soft_install')")
execCmd.MarkFlagRequired("command") //execCmd.MarkFlagRequired("command")
runCmd.Flags().StringVarP(&ExtraHost, "extrahosts", "x", "", "set extra hosts (default: 'pluto.local:192.168.1.2', and separate them with commas)") runCmd.Flags().StringVarP(&ExtraHost, "extrahosts", "x", "", "set extra hosts (default: 'pluto.local:192.168.1.2', and separate them with commas)")
runCmd.Flags().StringVarP(&XDisplay, "display", "d", "", "set X Display (by default: 'DISPLAY=:0', and separate them with commas)") runCmd.Flags().StringVarP(&XDisplay, "display", "d", "", "set X Display (by default: 'DISPLAY=:0', and separate them with commas)")
runCmd.Flags().StringVarP(&ExecCmd, "command", "e", "", "command to exec (by default: '/bin/bash')") runCmd.Flags().StringVarP(&ExecCmd, "command", "e", "", "command to exec (by default: '/bin/bash')")
runCmd.Flags().StringVarP(&ExtraBind, "bind", "b", "", "extra bindings (separate them with commas)") runCmd.Flags().StringVarP(&ExtraBind, "bind", "b", "", "extra bindings (separate them with commas)")
runCmd.Flags().StringVarP(&DImage, "image", "i", "", "image (default: 'myrfswift:latest')") runCmd.Flags().StringVarP(&DImage, "image", "i", "", "image (default: 'myrfswift:latest')")
runCmd.Flags().StringVarP(&PulseServer, "pulseserver", "p", "tcp:localhost:34567", "PULSE SERVER TCP address (by default: tcp:localhost:34567)") runCmd.Flags().StringVarP(&PulseServer, "pulseserver", "p", "tcp:127.0.0.1:34567", "PULSE SERVER TCP address (by default: tcp:127.0.0.1:34567)")
lastCmd.Flags().StringVarP(&FilterLast, "filter", "f", "", "filter by image name") lastCmd.Flags().StringVarP(&FilterLast, "filter", "f", "", "filter by image name")
} }

View File

@ -9,6 +9,7 @@ import (
"io" "io"
"os" "os"
"strings" "strings"
"encoding/json"
"context" "context"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
@ -18,6 +19,9 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/stdcopy"
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/moby/term"
"github.com/docker/docker/api/types/filters"
) )
var inout chan []byte var inout chan []byte
@ -53,61 +57,78 @@ var dockerObj = DockerInst{net: "host",
pulse_server: "tcp:localhost:34567", pulse_server: "tcp:localhost:34567",
shell: "/bin/bash"} // Instance with default values shell: "/bin/bash"} // Instance with default values
func DockerLast(ifilter string) { func DockerLast(ifilter string, labelKey string, labelValue string) {
/* Lists 10 last Docker containers /* Lists 10 last Docker containers
in(1): string optional filter for image name in(1): string optional filter for image name
*/ */
ctx := context.Background() ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer cli.Close() defer cli.Close()
containers, err := cli.ContainerList(ctx, container.ListOptions{Latest: true, All: true, Limit: 10}) // Create filters
if err != nil { containerFilters := filters.NewArgs()
panic(err) if ifilter != "" {
} containerFilters.Add("ancestor", ifilter)
}
for _, container := range containers { containerFilters.Add("label", fmt.Sprintf("%s=%s", labelKey, labelValue)) // filter by label
if ifilter != "" {
if container.Image == ifilter { // List containers with the specified filter
fmt.Println("[", container.Created, "][", container.Image, "] Container: ", container.ID, ", Command: ", container.Command) containers, err := cli.ContainerList(ctx, container.ListOptions{
} All: true,
} else { Limit: 10,
fmt.Println("[", container.Created, "][", container.Image, "] Container: ", container.ID, ", Command: ", container.Command) Filters: containerFilters,
} })
} if err != nil {
panic(err)
}
for _, container := range containers {
fmt.Println("[", container.Created, "][", container.Image, "] Container: ", container.ID, ", Command: ", container.Command)
}
} }
func latestDockerID() string { func latestDockerID(labelKey string, labelValue string) string {
/* Get latest Docker container ID by image name /* Get latest Docker container ID by image label
out: string container ID in(1): string label key
*/ in(2): string label value
ctx := context.Background() out: string container ID
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) */
if err != nil { ctx := context.Background()
panic(err) cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
} if err != nil {
defer cli.Close() panic(err)
}
defer cli.Close()
containers, err := cli.ContainerList(ctx, container.ListOptions{All: true}) // Filter containers by the specified image label
if err != nil { containerFilters := filters.NewArgs()
panic(err) containerFilters.Add("label", fmt.Sprintf("%s=%s", labelKey, labelValue))
}
var latestContainer types.Container containers, err := cli.ContainerList(ctx, container.ListOptions{
for _, container := range containers { All: true,
if latestContainer.ID == "" || container.Created > latestContainer.Created { Filters: containerFilters,
latestContainer = container })
} if err != nil {
} panic(err)
}
if latestContainer.ID == "" { var latestContainer types.Container
fmt.Println("No container found with the specified image name.") for _, container := range containers {
} if latestContainer.ID == "" || container.Created > latestContainer.Created {
latestContainer = container
}
}
return latestContainer.ID if latestContainer.ID == "" {
fmt.Println("No container found with the specified image label.")
return ""
}
return latestContainer.ID
} }
func DockerExec(contid string, WorkingDir string) { func DockerExec(contid string, WorkingDir string) {
@ -123,7 +144,9 @@ func DockerExec(contid string, WorkingDir string) {
defer cli.Close() defer cli.Close()
if contid == "" { if contid == "" {
contid = latestDockerID() labelKey := "org.container.project" // TODO: maybe to move in global
labelValue := "rfswift" // TODO: maybe to move in global
contid = latestDockerID(labelKey, labelValue)
} }
if err := cli.ContainerStart(ctx, contid, container.StartOptions{}); err != nil { if err := cli.ContainerStart(ctx, contid, container.StartOptions{}); err != nil {
@ -345,35 +368,50 @@ func DockerCommit(contid string) {
} }
func DockerPull(imageref string, imagetag string) { func DockerPull(imageref string, imagetag string) {
/* Pulls an image from a registry /* Pulls an image from a registry
in(1): string Image reference in(1): string Image reference
in(2): string Image tag target in(2): string Image tag target
*/ */
if imagetag == "" { // if tag is empty, keep same tag if imagetag == "" { // if tag is empty, keep same tag
imagetag = imageref imagetag = imageref
} }
ctx := context.Background() ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer cli.Close() defer cli.Close()
out, err := cli.ImagePull(ctx, imageref, image.PullOptions{}) out, err := cli.ImagePull(ctx, imageref, image.PullOptions{})
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer out.Close()
defer out.Close() fd, isTerminal := term.GetFdInfo(os.Stdout)
jsonDecoder := json.NewDecoder(out)
io.Copy(os.Stdout, out) for {
var msg jsonmessage.JSONMessage
if err := jsonDecoder.Decode(&msg); err == io.EOF {
break
} else if err != nil {
panic(err)
}
err = cli.ImageTag(ctx, imageref, imagetag) if isTerminal {
if err != nil { _ = jsonmessage.DisplayJSONMessagesStream(out, os.Stdout, fd, isTerminal, nil)
panic(err) } else {
} fmt.Println(msg)
}
}
err = cli.ImageTag(ctx, imageref, imagetag)
if err != nil {
panic(err)
}
} }
func DockerRename(imageref string, imagetag string) { func DockerRename(imageref string, imagetag string) {
@ -413,3 +451,60 @@ func DockerRemove(contid string) {
fmt.Println("[+] Container removed!") fmt.Println("[+] Container removed!")
} }
} }
func ListImages(labelKey string, labelValue string) ([]image.Summary, error) {
/* List RF Swift Images
in(1): string labelKey
in(2): string labelValue
out: Tuple ImageSummary, error
*/
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, err
}
defer cli.Close()
// Filter images by the specified image label
imagesFilters := filters.NewArgs()
imagesFilters.Add("label", fmt.Sprintf("%s=%s", labelKey, labelValue))
images, err := cli.ImageList(ctx, image.ListOptions{
All: true,
Filters: imagesFilters,
})
if err != nil {
return nil, err
}
// Only display images with RepoTags
var filteredImages []image.Summary
for _, image := range images {
if len(image.RepoTags) > 0 {
filteredImages = append(filteredImages, image)
}
}
return filteredImages, nil
}
func DeleteImage(imageIDOrTag string) error {
/* Delete an image
in(1): string image ID or tag
out: error
*/
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
defer cli.Close()
_, err = cli.ImageRemove(ctx, imageIDOrTag, types.ImageRemoveOptions{Force: true, PruneChildren: true})
if err != nil {
return err
}
fmt.Printf("Successfully deleted image: %s\n", imageIDOrTag)
return nil
}

View File

@ -0,0 +1,32 @@
#!/bin/bash
function yatebts_blade2_soft_install() { # TODO: make few tests with new Nuand libs, if unstable: fetch 3a411c87c2416dc68030d5823d73ebf3f797a145
goodecho "[+] Feching YateBTS from Nuand"
[ -d /root/thirdparty ] || mkdir /root/thirdparty
cd /root/thirdparty
installfromnet "wget https://nuand.com/downloads/yate-rc-3.tar.gz"
goodecho "[+] Installing Yate"
cd yate
./autogen.sh
./configure --prefix=/usr/local
make -j$(nproc)
make install
ldconfig
cd ..
goodecho "[+] Installing YateBTS"
cd yatebts
./autogen.sh
./configure --prefix=/usr/local
make -j$(nproc)
make install
ldconfig
goodecho "[+] Creating some confs"
touch /usr/local/etc/yate/snmp_data.conf /usr/local/etc/yate/tmsidata.conf
# chown root:yate /usr/local/etc/yate/*.conf # TODO: next when dropping root privs
chmod g+w /usr/local/etc/yate/*.conf
colorecho "[+] Now it's time for you to configure ;)"
}
### TODO: more More!