diff --git a/lib/utils/kube.go b/lib/utils/kube.go index f75bbae3..986c496f 100644 --- a/lib/utils/kube.go +++ b/lib/utils/kube.go @@ -12,9 +12,11 @@ import ( g "github.com/sdslabs/katana/configs" "github.com/sdslabs/katana/types" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" @@ -47,7 +49,7 @@ func GetKubeClient() (*kubernetes.Clientset, error) { return kubernetes.NewForConfig(config) } -func GetPods(lbls map[string]string, ns ...string) ([]v1.Pod, error) { +func GetPods(lbls map[string]string, ns ...string) ([]corev1.Pod, error) { var namespace string if len(ns) == 0 { namespace = g.KatanaConfig.KubeNameSpace @@ -122,7 +124,7 @@ func CopyIntoPod(podName string, containerName string, pathInPod string, localFi } // Find the container in the pod - var container *v1.Container + var container *corev1.Container for _, c := range pod.Spec.Containers { if c.Name == containerName { container = &c @@ -142,7 +144,7 @@ func CopyIntoPod(podName string, containerName string, pathInPod string, localFi SubResource("exec"). Param("container", containerName) - req.VersionedParams(&v1.PodExecOptions{ + req.VersionedParams(&corev1.PodExecOptions{ Container: containerName, Command: []string{"bash", "-c", "cat > " + pathInPod}, Stdin: true, @@ -241,7 +243,7 @@ func Podexecutor(command []string, kubeClientset *kubernetes.Clientset, kubeConf Name("katana-team-master-pod-0"). Namespace(podNamespace + "-ns"). SubResource("exec") - req.VersionedParams(&v1.PodExecOptions{ + req.VersionedParams(&corev1.PodExecOptions{ Command: command, Stdin: false, Stdout: true, @@ -320,7 +322,7 @@ func DeleteConfigMapAndWait(kubeClientset *kubernetes.Clientset, kubeConfig *res for event := range watcher.ResultChan() { // Check if ConfigMap exists - configMapName := event.Object.(*v1.ConfigMap).Name + configMapName := event.Object.(*corev1.ConfigMap).Name if configMapName == "" { break } @@ -351,7 +353,7 @@ func WaitForLoadBalancerExternalIP(clientset *kubernetes.Clientset, serviceName defer watcher.Stop() for event := range watcher.ResultChan() { - service, ok := event.Object.(*v1.Service) + service, ok := event.Object.(*corev1.Service) if !ok { continue } @@ -395,3 +397,73 @@ func WaitForDeploymentReady(clientset *kubernetes.Clientset, deploymentName stri return nil } + +func CreateService(clientset *kubernetes.Clientset, serviceName string, namespace string, port int32, targetPort int32, selector map[string]string) error { + service := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: serviceName, + }, + Spec: corev1.ServiceSpec{ + Selector: selector, + Ports: []corev1.ServicePort{ + { + Port: port, + TargetPort: intstr.FromInt(int(targetPort)), + }, + }, + }, + } + + _, err := clientset.CoreV1().Services(namespace).Create(context.Background(), service, metav1.CreateOptions{}) + if err != nil { + return err + } + + return nil +} + +func CreateIngress(clientset *kubernetes.Clientset, ingressName string, namespace string, serviceName string, servicePort int32, host string) error { + ingressClassName := "nginx" + + ingress := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: ingressName, + }, + Spec: networkingv1.IngressSpec{ + IngressClassName: &ingressClassName, + Rules: []networkingv1.IngressRule{ + { + Host: host, + IngressRuleValue: networkingv1.IngressRuleValue{ + HTTP: &networkingv1.HTTPIngressRuleValue{ + Paths: []networkingv1.HTTPIngressPath{ + { + Path: "/", + PathType: func() *networkingv1.PathType { + pathType := networkingv1.PathTypePrefix + return &pathType + }(), + Backend: networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: serviceName, + Port: networkingv1.ServiceBackendPort{ + Number: servicePort, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + _, err := clientset.NetworkingV1().Ingresses(namespace).Create(context.Background(), ingress, metav1.CreateOptions{}) + if err != nil { + return err + } + + return nil +} diff --git a/services/challengedeployerservice/controller.go b/services/challengedeployerservice/controller.go new file mode 100644 index 00000000..107095f1 --- /dev/null +++ b/services/challengedeployerservice/controller.go @@ -0,0 +1,183 @@ +package challengedeployerservice + +import ( + "context" + "fmt" + "log" + "os" + "regexp" + "strconv" + + "github.com/gofiber/fiber/v2" + archiver "github.com/mholt/archiver/v3" + g "github.com/sdslabs/katana/configs" + "github.com/sdslabs/katana/lib/utils" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func DeployChallenge(c *fiber.Ctx) error { + + challengeType := "web" + folderName := "" + patch := false + replicas := g.KatanaConfig.TeamDeployment + log.Println("Starting") + if form, err := c.MultipartForm(); err == nil { + + files := form.File["challenge"] + + // Loops through all challenges, if multiple uploaded : + for _, file := range files { + + //creates folders for each challenge + pattern := `([^/]+)\.tar\.gz$` + regex := regexp.MustCompile(pattern) + match := regex.FindStringSubmatch(file.Filename) + folderName = match[1] + + response, challengePath := createFolder(folderName) + if response == 1 { + log.Println("Directory already exists with same name") + return c.SendString("Directory already exists with same name") + } else if response == 2 { + log.Println("Issue with creating chall directory.Check permissions") + return c.SendString("Issue with creating chall directory.Check permissions") + } + + //save to disk in that directory + if err := c.SaveFile(file, fmt.Sprintf("./challenges/%s/%s", folderName, file.Filename)); err != nil { + return err + } + + //Create folder inside the challenge folder + err = os.Mkdir(challengePath+"/"+folderName, 0777) + if err != nil { + log.Println("Error in creating folder inside challenge folder") + return c.SendString("Error in creating folder inside challenge folder") + } + + //extract the tar.gz file + err := archiver.Unarchive("./challenges/"+folderName+"/"+file.Filename, "./challenges/"+folderName) + if err != nil { + log.Println("Error in unarchiving", err) + return c.SendString("Error in unarchiving") + } + + //Update challenge path to get dockerfile + challengePath = challengePath + "/" + folderName + + utils.BuildDockerImage(folderName, challengePath) + + //Get no.of teams and DEPLOY CHALLENGE to each namespace (assuming they exist and /createTeams has been called) + clusterConfig := g.ClusterConfig + numberOfTeams := clusterConfig.TeamCount + res := make([][]string, 0) + for i := 0; i < int(numberOfTeams); i++ { + log.Println("-----------Deploying challenge for team: " + strconv.Itoa(i) + " --------") + teamName := "katana-team-" + strconv.Itoa(i) + utils.DeployChallenge(folderName, teamName, patch, replicas) + url, err := createServiceAndIngressForChallenge(folderName, teamName, 3000) + if err != nil { + res = append(res, []string{teamName, err.Error()}) + } else { + res = append(res, []string{teamName, url}) + } + } + + //Copy challenge in pods and etc. + copyChallengeIntoTsuka(challengePath, folderName, challengeType) + + return c.JSON(res) + } + } + log.Println("Ending") + + return c.SendString("Wrong file") +} + +func DeleteChallenge(c *fiber.Ctx) error { + + challengeName := c.Params("challengeName") + //Delete chall directory also ? + log.Println("Challenge name is : " + challengeName) + + dirPath, _ := os.Getwd() + challengePath := dirPath + "/challenges/" + challengeName + log.Println("Deleting challenge folder :", challengePath) + err := os.RemoveAll(challengePath) + if err != nil { + log.Println("Error in deleting challenge folder") + return err + } + + totalTeams := utils.GetTeamNumber() + + for i := 0; i < totalTeams; i++ { + + teamName := "team-" + strconv.Itoa(i) + + teamNamespace := "katana-" + teamName + "-ns" + kubeclient, err := utils.GetKubeClient() + if err != nil { + return err + } + + log.Println("---------------Deleting challenge for team: ", teamNamespace) + serviceClient := kubeclient.CoreV1().Services(teamNamespace) + deploymentsClient := kubeclient.AppsV1().Deployments(teamNamespace) + + //Get deployment + deps, err := deploymentsClient.Get(context.TODO(), challengeName, metav1.GetOptions{}) + if err != nil { + log.Println(" Error in getting deployments associated with the challenge. ") + continue + //panic(err) + } + + //Delete deployments + if deps.Name != challengeName { + log.Println("Deployment does not exist. Create one using /deploy route.") + return nil + } else { + log.Println("Deleting deployment...") + deletePolicy := metav1.DeletePropagationForeground + err = deploymentsClient.Delete(context.TODO(), challengeName, metav1.DeleteOptions{PropagationPolicy: &deletePolicy}) + if err != nil { + log.Println("Error in deleting deployment.") + continue + } + } + + //Check if service exists + services, err := serviceClient.List(context.TODO(), metav1.ListOptions{}) + if err != nil { + log.Println(" Error in getting services for" + challengeName + "in the namespace " + teamNamespace) + continue + //panic(err) + } + + flag := 0 + for _, service := range services.Items { + if service.Name == challengeName { + flag = 1 + } + } + if flag == 0 { + log.Println("Service does not exist for the " + challengeName + " in namespace " + teamNamespace) + continue + } + + //Delete service + log.Println("Deleting services associated with this challenge...") + err = serviceClient.Delete(context.TODO(), challengeName, metav1.DeleteOptions{}) + if err != nil { + log.Println("Error in deleting service for "+challengeName+" in namespace "+teamNamespace, err) + continue + } + + } + + log.Println("Process completed") + + return c.SendString("Deleted challenge" + challengeName + "in all namespaces.") +} diff --git a/services/challengedeployerservice/copyInPod.go b/services/challengedeployerservice/copyInPod.go deleted file mode 100644 index cca4b459..00000000 --- a/services/challengedeployerservice/copyInPod.go +++ /dev/null @@ -1,65 +0,0 @@ -package challengedeployerservice - -import ( - "fmt" - "log" - "os" - "regexp" - - git "github.com/go-git/go-git/v5" - "github.com/go-git/go-git/v5/config" - g "github.com/sdslabs/katana/configs" - "github.com/sdslabs/katana/lib/utils" - v1 "k8s.io/api/core/v1" -) - -func CopyInPod(localFilePath string, pathInPod string) error { - - //regex to find challenge name since localFilePath[12:22] is hardcoded - regexPattern := `\/([^\/]+)\.tar\.gz$` - regex := regexp.MustCompile(regexPattern) - matches := regex.FindStringSubmatch(localFilePath) - filename := matches[1] - - // Get pods from different namespaces - var pods []v1.Pod - numberOfTeams := utils.GetTeamNumber() - for i := 0; i < numberOfTeams; i++ { - path := "katana-team-" + fmt.Sprint(i) + "/" + filename - err := os.Mkdir("teams/"+path, 0755) - if err != nil { - log.Println(err) - } - git.PlainInit("teams/"+path, false) - repo, err := git.PlainOpen("teams/" + path) - if err != nil { - log.Println(err) - } - remoteConfig := &config.RemoteConfig{ - Name: "origin", - URLs: []string{"http://sdslabs@" + utils.GetGogsIp() + ":18080" + "/" + path}} - _, err = repo.CreateRemote(remoteConfig) - - if err != nil { - log.Println(err) - } - podsInTeam, err := utils.GetPods(map[string]string{ - "app": g.ClusterConfig.TeamLabel, - }, "katana-team-"+fmt.Sprint(i)+"-ns") - if err != nil { - log.Println(err) - return err - } - pods = append(pods, podsInTeam...) - } - // Loop over pods - for _, pod := range pods { - // Copy file into pod - if err := utils.CopyIntoPod(pod.Name, g.TeamVmConfig.ContainerName, pathInPod, localFilePath, pod.Namespace); err != nil { - log.Println(err) - return err - } - } - - return nil -} diff --git a/services/challengedeployerservice/createService.go b/services/challengedeployerservice/createService.go deleted file mode 100644 index ac353741..00000000 --- a/services/challengedeployerservice/createService.go +++ /dev/null @@ -1,96 +0,0 @@ -package challengedeployerservice - -import ( - "context" - "log" - "os/exec" - intstr "k8s.io/apimachinery/pkg/util/intstr" - - "github.com/sdslabs/katana/lib/utils" - v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func CreateService(chall_name, team_name string) (string, error) { - - team_namespace := team_name + "-ns" - kubeclient, err := utils.GetKubeClient() - if err != nil { - return "", err - } - serviceClient := kubeclient.CoreV1().Services(team_namespace) - - service := &v1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: team_namespace, - Name: chall_name, - }, - - Spec: v1.ServiceSpec{ - Type: v1.ServiceTypeLoadBalancer, // Change the service type to LoadBalancer - Selector: map[string]string{ - "app": chall_name, - }, - Ports: []v1.ServicePort{ - { - Name: "http", - Protocol: v1.ProtocolTCP, - Port: 80, - TargetPort: intstr.FromInt(80), - }, - }, - }, - } - - - //Get all services - - //Check if service already exists - services, err := serviceClient.List(context.TODO(), metav1.ListOptions{}) - for _, service := range services.Items { - if service.Name == chall_name { - log.Println("Service already exists for the challenge " + chall_name + " in namespace " + team_namespace) - return "", nil - } - } - - if err != nil { - log.Println(" Error in getting services. ") - //return err - panic(err) - } - - // Create Service - log.Println("Creating service...") - result, err := serviceClient.Create(context.TODO(), service, metav1.CreateOptions{}) - if err != nil { - log.Println("Error creating service.. ") - return "", err - // panic(err) - } - - log.Printf("Created service %q.\n", result.GetObjectMeta().GetName()+" in namespace "+team_namespace) - - // expose service to localhost - // TODO: change implementation when deploying on cluster - url, err := ExposeService(chall_name, team_namespace) - if err != nil { - log.Printf("Error in exposing service %s for namespace %s", chall_name, team_namespace) - log.Println("Error: ", err) - return "", err - } - - log.Printf("Challenge for %s is deployed at %s", team_name, url) - - return url, nil -} - -func ExposeService(service_name, namespace string) (string, error) { - // run command to expose service minikube service -n --url - out := exec.Command("minikube", "service", service_name, "-n", namespace, "--url") - url, err := out.Output() - if err != nil { - return "", err - } - return string(url), nil -} diff --git a/services/challengedeployerservice/deleteChall.go b/services/challengedeployerservice/deleteChall.go deleted file mode 100644 index 547dc845..00000000 --- a/services/challengedeployerservice/deleteChall.go +++ /dev/null @@ -1,94 +0,0 @@ -package challengedeployerservice - -import ( - "context" - "log" - "os" - "strconv" - - "github.com/sdslabs/katana/lib/utils" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func DeleteChallenge(chall_name string) error { - - //Delete Challenge Folder - dirPath, _ := os.Getwd() - challengePath := dirPath + "/challenges/" + chall_name - log.Println("Deleting challenge folder :", challengePath) - err := os.RemoveAll(challengePath) - if err != nil { - log.Println("Error in deleting challenge folder") - return err - } - - totalteams := utils.GetTeamNumber() - - for i := 0; i < totalteams; i++ { - - team_name := "team-" + strconv.Itoa(i) - - team_namespace := "katana-" + team_name + "-ns" - kubeclient, err := utils.GetKubeClient() - if err != nil { - return err - } - - log.Println("---------------Deleting challenge for team: ", team_namespace) - serviceClient := kubeclient.CoreV1().Services(team_namespace) - deploymentsClient := kubeclient.AppsV1().Deployments(team_namespace) - - //Get deployment - deps, err := deploymentsClient.Get(context.TODO(), chall_name, metav1.GetOptions{}) - if err != nil { - log.Println(" Error in getting deployments associated with the challenge. ") - continue - //panic(err) - } - - //Delete deployments - if deps.Name != chall_name { - log.Println("Deployment does not exist. Create one using /deploy route.") - return nil - } else { - log.Println("Deleting deployment...") - deletePolicy := metav1.DeletePropagationForeground - err = deploymentsClient.Delete(context.TODO(), chall_name, metav1.DeleteOptions{PropagationPolicy: &deletePolicy}) - if err != nil { - log.Println("Error in deleting deployment.") - continue - } - } - - //Check if service exists - services, err := serviceClient.List(context.TODO(), metav1.ListOptions{}) - if err != nil { - log.Println(" Error in getting services for" + chall_name + "in the namespace " + team_namespace) - continue - //panic(err) - } - - flag := 0 - for _, service := range services.Items { - if service.Name == chall_name { - flag = 1 - } - } - if flag == 0 { - log.Println("Service does not exist for the " + chall_name + " in namespace " + team_namespace) - continue - } - - //Delete service - log.Println("Deleting services associated with this challenge...") - err = serviceClient.Delete(context.TODO(), chall_name, metav1.DeleteOptions{}) - if err != nil { - log.Println("Error in deleting service for "+chall_name+" in namespace "+team_namespace, err) - continue - } - - } - - log.Println("Process completed") - return nil -} diff --git a/services/challengedeployerservice/helper.go b/services/challengedeployerservice/helper.go new file mode 100644 index 00000000..c5dada0e --- /dev/null +++ b/services/challengedeployerservice/helper.go @@ -0,0 +1,127 @@ +package challengedeployerservice + +import ( + "fmt" + "log" + "os" + "regexp" + + git "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/config" + g "github.com/sdslabs/katana/configs" + "github.com/sdslabs/katana/lib/utils" + v1 "k8s.io/api/core/v1" +) + +func copyChallengeIntoTsuka(dirPath string, challengeName string, challengeType string) error { + localFilePath := dirPath + "/" + challengeName + ".tar.gz" + pathInPod := "/opt/katana/katana_" + challengeType + "_" + challengeName + ".tar.gz" + log.Println("Testing" + localFilePath + "....and..." + pathInPod) + + //regex to find challenge name since localFilePath[12:22] is hardcoded + regexPattern := `\/([^\/]+)\.tar\.gz$` + regex := regexp.MustCompile(regexPattern) + matches := regex.FindStringSubmatch(localFilePath) + filename := matches[1] + + // Get pods from different namespaces + var pods []v1.Pod + numberOfTeams := utils.GetTeamNumber() + for i := 0; i < numberOfTeams; i++ { + path := "katana-team-" + fmt.Sprint(i) + "/" + filename + err := os.Mkdir("teams/"+path, 0755) + if err != nil { + log.Println(err) + } + git.PlainInit("teams/"+path, false) + repo, err := git.PlainOpen("teams/" + path) + if err != nil { + log.Println(err) + } + remoteConfig := &config.RemoteConfig{ + Name: "origin", + URLs: []string{"http://sdslabs@" + utils.GetGogsIp() + ":18080" + "/" + path}} + _, err = repo.CreateRemote(remoteConfig) + + if err != nil { + log.Println(err) + } + podsInTeam, err := utils.GetPods(map[string]string{ + "app": g.ClusterConfig.TeamLabel, + }, "katana-team-"+fmt.Sprint(i)+"-ns") + if err != nil { + log.Println(err) + return err + } + pods = append(pods, podsInTeam...) + } + // Loop over pods + for _, pod := range pods { + // Copy file into pod + if err := utils.CopyIntoPod(pod.Name, g.TeamVmConfig.ContainerName, pathInPod, localFilePath, pod.Namespace); err != nil { + log.Println(err) + return err + } + } + + return nil +} + +func createServiceAndIngressForChallenge(challengeName, teamName string, targetPort int32) (string, error) { + + kubeclient, _ := utils.GetKubeClient() + serviceName := challengeName + "-svc" + teamNamespace := teamName + "-ns" + port := int32(80) + selector := map[string]string{ + "app": challengeName, + } + + utils.CreateService(kubeclient, serviceName, teamNamespace, port, targetPort, selector) + + log.Printf("Created service %s for challenge %s in namespace %s", serviceName, challengeName, teamNamespace) + + // Create ingress + ingressName := challengeName + "-ingress" + ingressHost := fmt.Sprintf("%s.%s.%s", challengeName, teamName, "katana.local") + utils.CreateIngress(kubeclient, ingressName, teamNamespace, serviceName, port, ingressHost) + + log.Printf("Created ingress %s for challenge %s in namespace %s", ingressName, challengeName, teamNamespace) + + return ingressHost, nil +} + +func createFolder(challengeName string) (message int, challengePath string) { + + basePath, _ := os.Getwd() + dirPath := basePath + "/challenges" //basepath is .../katana + + // Open the challenges directory to check if it exists , create if not + dir, err := os.Open(dirPath) + if err != nil { + if os.IsNotExist(err) { + log.Println("Challenges directory does not exist ,creating directory") + os.Mkdir(dirPath, 0777) + } else if os.IsPermission(err) { + log.Println("Error opening challenge directory. Permission Issue", err) + //Permission issue + return 2, challengePath + } else { + log.Println("Error opening challenge directory:", err) + //Some other error + return 2, challengePath + } + } + defer dir.Close() + + // Create a new challenge directory to keep challenge + challengePath = dirPath + "/" + challengeName + log.Println("Creating directory :", challengeName) + err = os.Mkdir(challengePath, 0777) + if err != nil { + //Directory already exists with same name + return 1, challengePath + } + //Successfully created directory + return 0, challengePath +} diff --git a/services/master/controllers/deploy.go b/services/master/controllers/deploy.go deleted file mode 100644 index e6f10acc..00000000 --- a/services/master/controllers/deploy.go +++ /dev/null @@ -1,150 +0,0 @@ -package controllers - -import ( - "fmt" - "log" - "os" - "regexp" - "strconv" - - "github.com/gofiber/fiber/v2" - archiver "github.com/mholt/archiver/v3" - g "github.com/sdslabs/katana/configs" - "github.com/sdslabs/katana/lib/utils" - - deployer "github.com/sdslabs/katana/services/challengedeployerservice" -) - -func challcopy(dirPath, challengename, challengetype string) { - - localFilePath := dirPath + "/" + challengename + ".tar.gz" - pathInPod := "/opt/katana/katana_" + challengetype + "_" + challengename + ".tar.gz" - log.Println("Testing" + localFilePath + "....and..." + pathInPod) - deployer.CopyInPod(localFilePath, pathInPod) - -} - -func createfolder(challengename string) (message int, challengePath string) { - - basePath, _ := os.Getwd() - dirPath := basePath + "/challenges" //basepath is .../katana - - // Open the challenges directory to check if it exists , create if not - dir, err := os.Open(dirPath) - if err != nil { - if os.IsNotExist(err) { - log.Println("Challenges directory does not exist ,creating directory") - os.Mkdir(dirPath, 0777) - } else if os.IsPermission(err) { - log.Println("Error opening challenge directory. Permission Issue", err) - //Permission issue - return 2, challengePath - } else { - log.Println("Error opening challenge directory:", err) - //Some other error - return 2, challengePath - } - } - defer dir.Close() - - // Create a new challenge directory to keep challenge - challengePath = dirPath + "/" + challengename - log.Println("Creating directory :", challengename) - err = os.Mkdir(challengePath, 0777) - if err != nil { - //Directory already exists with same name - return 1, challengePath - } - //Successfully created directory - return 0, challengePath -} - -func Deploy(c *fiber.Ctx) error { - - challengetype := "web" - folderName := "" - patch := false - replicas := g.KatanaConfig.TeamDeployment - log.Println("Starting") - if form, err := c.MultipartForm(); err == nil { - - files := form.File["challenge"] - - // Loops through all challenges, if multiple uploaded : - for _, file := range files { - - //creates folders for each challenge - pattern := `([^/]+)\.tar\.gz$` - regex := regexp.MustCompile(pattern) - match := regex.FindStringSubmatch(file.Filename) - folderName = match[1] - - response, challengePath := createfolder(folderName) - if response == 1 { - log.Println("Directory already exists with same name") - return c.SendString("Directory already exists with same name") - } else if response == 2 { - log.Println("Issue with creating chall directory.Check permissions") - return c.SendString("Issue with creating chall directory.Check permissions") - } - - //save to disk in that directory - if err := c.SaveFile(file, fmt.Sprintf("./challenges/%s/%s", folderName, file.Filename)); err != nil { - return err - } - - //Create folder inside the challenge folder - err = os.Mkdir(challengePath+"/"+folderName, 0777) - if err != nil { - log.Println("Error in creating folder inside challenge folder") - return c.SendString("Error in creating folder inside challenge folder") - } - - //extract the tar.gz file - err := archiver.Unarchive("./challenges/"+folderName+"/"+file.Filename, "./challenges/"+folderName) - if err != nil { - log.Println("Error in unarchiving", err) - return c.SendString("Error in unarchiving") - } - - //Update challenge path to get dockerfile - challengePath = challengePath + "/" + folderName - - utils.BuildDockerImage(folderName, challengePath) - - //Get no.of teams and DEPLOY CHALLENGE to each namespace (assuming they exist and /createTeams has been called) - clusterConfig := g.ClusterConfig - numberOfTeams := clusterConfig.TeamCount - res := make([][]string, 0) - for i := 0; i < int(numberOfTeams); i++ { - log.Println("-----------Deploying challenge for team: " + strconv.Itoa(i) + " --------") - teamName := "katana-team-" + strconv.Itoa(i) - utils.DeployChallenge(folderName, teamName, patch, replicas) - url, err := deployer.CreateService(folderName, teamName) - if err != nil { - res = append(res, []string{teamName, err.Error()}) - } else { - res = append(res, []string{teamName, url}) - } - } - - //Copy challenge in pods and etc. - challcopy(challengePath, folderName, challengetype) - - return c.JSON(res) - } - } - log.Println("Ending") - - return c.SendString("Wrong file") -} - -func DeleteChallenge(c *fiber.Ctx) error { - - chall_name := c.Params("chall_name") - //Delete chall directory also ? - log.Println("Challenge name is : " + chall_name) - - deployer.DeleteChallenge(chall_name) - return c.SendString("Deleted challenge" + chall_name + "in all namespaces.") -} diff --git a/services/master/server.go b/services/master/server.go index dd399dc6..6e74b9d8 100644 --- a/services/master/server.go +++ b/services/master/server.go @@ -8,6 +8,7 @@ import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" cfg "github.com/sdslabs/katana/configs" + challengeDeployerService "github.com/sdslabs/katana/services/challengedeployerservice" c "github.com/sdslabs/katana/services/master/controllers" ) @@ -45,9 +46,9 @@ func Server() error { admin.Get("/createTeams/:number", c.CreateTeams) admin.Post("/challengeUpdate", c.ChallengeUpdate) admin.Post("/logs", c.Logs) - admin.Post("/deploy", c.Deploy) + admin.Post("/deployChallenge", challengeDeployerService.DeployChallenge) admin.Get("/gitServer", c.GitServer) - admin.Get("/deleteChallenge/:chall_name", c.DeleteChallenge) + admin.Get("/deleteChallenge/:chall_name", challengeDeployerService.DeleteChallenge) admin.Get("/setupIngress", c.SetupIngress) log.Printf("Listening on %s:%d\n", cfg.APIConfig.Host, cfg.APIConfig.Port) return app.Listen(fmt.Sprintf("%s:%d", cfg.APIConfig.Host, cfg.APIConfig.Port))