<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/fsouza/go-dockerclient"
	"github.com/gin-gonic/gin"
)

//APIBASE The base of the API that this agent provides
const APIBASE = "/api/1"

//Containers representing information about the running containers
type Containers struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Command string `json:"command"`
	Port    string `json:"port"`
}

//Post represents a post to the server
type Post struct {
	AgentID             string       `json:"agentid"`
	ExpiredAfterSeconds int          `json:"expireAfterSeconds"`
	Containers          []Containers `json:"containers"`
}

var (
	serverURL          string
	agentID            string
	refreshRate        int
	expireAfterSeconds int
	port               string
)

func init() {
	flag.StringVar(&serverURL, "server", "http://localhost:8989", "The server uri where dockmaster is located.")
	flag.StringVar(&agentID, "agent", "localhost", "The name of an Agent. Example: TestQA1.")
	flag.IntVar(&refreshRate, "refresh", 60, "The rate at which this agent should check for changes in seconds.")
	flag.IntVar(&expireAfterSeconds, "expireAfterSeconds", 60, "The rate at which data sent by this agent should expire in seconds.")
	flag.StringVar(&port, "port", "9999", "The port number on which this agent is running on.")

	flag.Parse()
	go startDiscovering()
}

func main() {
	router := gin.Default()
	v1 := router.Group(APIBASE)
	{
		v1.POST("/stop", stopContainer)
		v1.POST("/stopAll", stopAllContainers)
		v1.GET("/inspect/:id", inspectContainer)
	}
	router.Run(":" + port)
}

func stopContainer(c *gin.Context) {
	var container struct {
		ID string `json:"id"`
	}

	//reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
	endpoint := "unix:///var/run/docker.sock"
	client, _ := docker.NewClient(endpoint)
	runningContainers, err := client.ListContainers(docker.ListContainersOptions{All: false})

	for _, v := range runningContainers {
		if v.ID == container.ID {
			err = client.StopContainer(v.ID, 1)
			if err != nil {
				e := ErrorResponse{}
				e.ErrorMessage = "error stopping containers:" + err.Error()
				c.JSON(http.StatusInternalServerError, e)
				return
			}
			m := Message{}
			m.Message = "continer stopped successfully"
			c.JSON(http.StatusOK, m)
		}
	}

	e := ErrorResponse{}
	e.ErrorMessage = "container could not be found!"
	c.JSON(http.StatusNotFound, e)
}

func stopAllContainers(c *gin.Context) {

	var stopErrors [][]string
	for i := range stopErrors {
		stopErrors[i] = make([]string, 0)
	}
	//reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
	endpoint := "unix:///var/run/docker.sock"
	client, _ := docker.NewClient(endpoint)
	runningContainers, err := client.ListContainers(docker.ListContainersOptions{All: false})

	if err != nil {
		e := ErrorResponse{}
		e.ErrorMessage = "error getting all containers:" + err.Error()
		c.JSON(http.StatusInternalServerError, e)
		return
	}

	for _, v := range runningContainers {
		err := client.StopContainer(v.ID, 1)
		if err != nil {
			stopErrors = append(stopErrors, v.Names)
		}
	}

	if len(stopErrors) != 0 {
		var errCon string
		for _, v := range stopErrors {
			errCon += "[" + strings.Join(v, "|") + "]"
		}
		e := ErrorResponse{}
		e.ErrorMessage = "error stopping containers:" + errCon
		c.JSON(http.StatusInternalServerError, e)
		return
	}

	m := Message{}
	m.Message = "all containers successfully stopped"
	c.JSON(http.StatusOK, m)
}

func inspectContainer(c *gin.Context) {
	// cID := c.Param("id")
	// endpoint := "unix:///var/run/docker.sock"
	// client, _ := docker.NewClient(endpoint)<commit_msg>Added return status for inspect.<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/fsouza/go-dockerclient"
	"github.com/gin-gonic/gin"
)

//APIBASE The base of the API that this agent provides
const APIBASE = "/api/1"

//Containers representing information about the running containers
type Containers struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Command string `json:"command"`
	Port    string `json:"port"`
}

//Post represents a post to the server
type Post struct {
	AgentID             string       `json:"agentid"`
	ExpiredAfterSeconds int          `json:"expireAfterSeconds"`
	Containers          []Containers `json:"containers"`
}

var (
	serverURL          string
	agentID            string
	refreshRate        int
	expireAfterSeconds int
	port               string
)

func init() {
	flag.StringVar(&serverURL, "server", "http://localhost:8989", "The server uri where dockmaster is located.")
	flag.StringVar(&agentID, "agent", "localhost", "The name of an Agent. Example: TestQA1.")
	flag.IntVar(&refreshRate, "refresh", 60, "The rate at which this agent should check for changes in seconds.")
	flag.IntVar(&expireAfterSeconds, "expireAfterSeconds", 60, "The rate at which data sent by this agent should expire in seconds.")
	flag.StringVar(&port, "port", "9999", "The port number on which this agent is running on.")

	flag.Parse()
	go startDiscovering()
}

func main() {
	router := gin.Default()
	v1 := router.Group(APIBASE)
	{
		v1.POST("/stop", stopContainer)
		v1.POST("/stopAll", stopAllContainers)
		v1.GET("/inspect/:id", inspectContainer)
	}
	router.Run(":" + port)
}

func stopContainer(c *gin.Context) {
	var container struct {
		ID string `json:"id"`
	}

	//reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
	endpoint := "unix:///var/run/docker.sock"
	client, _ := docker.NewClient(endpoint)
	runningContainers, err := client.ListContainers(docker.ListContainersOptions{All: false})

	for _, v := range runningContainers {
		if v.ID == container.ID {
			err = client.StopContainer(v.ID, 1)
			if err != nil {
				e := ErrorResponse{}
				e.ErrorMessage = "error stopping containers:" + err.Error()
				c.JSON(http.StatusInternalServerError, e)
				return
			}
			m := Message{}
			m.Message = "continer stopped successfully"
			c.JSON(http.StatusOK, m)
		}
	}

	e := ErrorResponse{}
	e.ErrorMessage = "container could not be found!"
	c.JSON(http.StatusNotFound, e)
}

func stopAllContainers(c *gin.Context) {

	var stopErrors [][]string
	for i := range stopErrors {
		stopErrors[i] = make([]string, 0)
	}
	//reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
	endpoint := "unix:///var/run/docker.sock"
	client, _ := docker.NewClient(endpoint)
	runningContainers, err := client.ListContainers(docker.ListContainersOptions{All: false})

	if err != nil {
		e := ErrorResponse{}
		e.ErrorMessage = "error getting all containers:" + err.Error()
		c.JSON(http.StatusInternalServerError, e)
		return
	}

	for _, v := range runningContainers {
		err := client.StopContainer(v.ID, 1)
		if err != nil {
			stopErrors = append(stopErrors, v.Names)
		}
	}

	if len(stopErrors) != 0 {
		var errCon string
		for _, v := range stopErrors {
			errCon += "[" + strings.Join(v, "|") + "]"
		}
		e := ErrorResponse{}
		e.ErrorMessage = "error stopping containers:" + errCon
		c.JSON(http.StatusInternalServerError, e)
		return
	}

	m := Message{}
	m.Message = "all containers successfully stopped"
	c.JSON(http.StatusOK, m)
}

func inspectContainer(c *gin.Context) {
	// cID := c.Param("id")
	// endpoint := "unix:///var/run/docker.sock"
	// client, _ := docker.NewClient(endpoint)
	c.JSON(http.StatusNotImplemented, nil)
{'fraction_non_alphanumeric': 0.14647887323943662, 'fraction_numerical': 0.005902079141515761, 'mean_word_length': 3.782552918537524, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '566462', 'n_tokens_mistral': 2616, 'n_tokens_neox': 2452, 'n_words': 623}