Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

katana-cli [WIP] #79

Open
wants to merge 50 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
b711559
fadd unc for infra curl
rizul2108 Nov 4, 2023
d1fa863
error msg change
rizul2108 Nov 4, 2023
e61b12d
function move to older file
rizul2108 Nov 7, 2023
b4b700b
add 2 func cli
rizul2108 Nov 8, 2023
2b8e7e0
update cmds for more abstraction
rizul2108 Nov 9, 2023
2dccc09
error handling
rizul2108 Nov 27, 2023
02cc99a
basic structure
rizul2108 Nov 30, 2023
6461b28
minor fixes
rizul2108 Nov 30, 2023
2501fb8
add createTeams func
rizul2108 Dec 1, 2023
a78736b
minor fixes
rizul2108 Dec 1, 2023
f53e00e
changes in createTeams func
rizul2108 Dec 2, 2023
ae6116f
wip changes
rizul2108 Dec 5, 2023
8098282
fixes
rizul2108 Dec 18, 2023
c064cd8
gogsetup error fix
rizul2108 Dec 20, 2023
af72587
Fix setup command and add MongoDB setup
rizul2108 Dec 20, 2023
9083ff3
add GlobalKubeClient and GlobalKubeConfig
rizul2108 Dec 21, 2023
b5490d1
minor fixes
rizul2108 Dec 21, 2023
784ffdb
fixes
rizul2108 Dec 21, 2023
b3cb683
code cleanup
rizul2108 Dec 21, 2023
2378139
Add OpenSSL version check
rizul2108 Dec 21, 2023
fde86f7
minor fixes for chall handling funcs
rizul2108 Dec 22, 2023
4fcc1e0
Add wireguard.yml
Bisht13 Aug 10, 2023
42cdcfb
update submodule ref
P3rcy-8685 Aug 30, 2023
0004d6c
update submodule ref
P3rcy-8685 Aug 30, 2023
4d53a45
update wireguard yml
P3rcy-8685 Aug 30, 2023
edcaf4b
remove cmd for certs and dynamic lb ip for wireguard
ashpect Aug 30, 2023
5891103
Get route for pre-existing challenges
ashpect Aug 31, 2023
c00b07e
[wip] remove cmd for certs
ashpect Sep 1, 2023
11380cb
Write firewall rules in image
ashpect Sep 1, 2023
b405d2b
add sample challenges
ashpect Sep 1, 2023
fee938b
Wireguard finishup
ashpect Sep 1, 2023
9dea00b
update
ashpect Oct 17, 2023
9015f14
fix
ashpect Oct 17, 2023
d7b822a
update crypto.go
ashpect Dec 20, 2023
404cc52
some bug fixes and minor updates
P3rcy-8685 Dec 21, 2023
eefbf23
func add for infra curl
rizul2108 Nov 4, 2023
60eba50
error handling
rizul2108 Nov 27, 2023
ce73eab
minor fixes
rizul2108 Dec 1, 2023
3b896e7
wip changes
rizul2108 Dec 5, 2023
f5c8e25
fixes
rizul2108 Dec 18, 2023
3a02293
add GlobalKubeClient and GlobalKubeConfig
rizul2108 Dec 21, 2023
7971487
code cleanup
rizul2108 Dec 21, 2023
7c05023
Add OpenSSL version check
rizul2108 Dec 21, 2023
35ad757
fixes for rebase
rizul2108 Dec 22, 2023
828f99a
Merge branch 'develop' into katana-cli
rizul2108 Dec 22, 2023
1b66b95
minor fixes
rizul2108 Dec 22, 2023
15bc421
func deployChallenge fixes
rizul2108 Dec 22, 2023
f62d8ea
fixes for deleteChal
rizul2108 Dec 22, 2023
2e1b1cb
minor fixes
rizul2108 Dec 23, 2023
7549335
minor fixes in challHandling funcs
rizul2108 Dec 23, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions cliHelpers/chalDeployerService/deleteChal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package chalDeployerService

import (
"fmt"
"log"

"github.com/spf13/cobra"

g "github.com/sdslabs/katana/configs"
)

// still have to test this [WIP]

var DelChalCmd = &cobra.Command{
Use: "delete-chal",
Short: "Run the Challenge Delete command",
Long: "Deletes the Challenge",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
challengeID := args[0]
g.LoadConfiguration();
g.LoadKubeElements();

if err := DeleteChallenge(challengeID); err != nil {
log.Printf("Error deleting the challenge with ID %s: %v", challengeID, err)
return fmt.Errorf("failed to delete challenge: %v", err)
}

log.Printf("Challenge with ID %s deleted successfully", challengeID)
return nil
},
}
27 changes: 27 additions & 0 deletions cliHelpers/chalDeployerService/deployChal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package chalDeployerService

import (
"log"

"github.com/spf13/cobra"

g "github.com/sdslabs/katana/configs"
)

// still have to test this [WIP]

var DeployChalCmd = &cobra.Command{
Use: "chal-deploy",
Short: "Run the Challenge Deploy command",
Long: "Runs the challenge deploy",
RunE: func(cmd *cobra.Command, args []string) error {
g.LoadConfiguration();
g.LoadKubeElements();
if err := DeployChallenge(); err != nil {
log.Println("Error deploying the challenge:", err)
return err
}
log.Println("Challenge deployed successfully")
return nil
},
}
191 changes: 191 additions & 0 deletions cliHelpers/chalDeployerService/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package chalDeployerService

import (
"context"
"log"
"os"
"strconv"
"strings"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"github.com/sdslabs/katana/configs"
g "github.com/sdslabs/katana/configs"
"github.com/sdslabs/katana/lib/deployment"
"github.com/sdslabs/katana/lib/utils"
"github.com/sdslabs/katana/services/challengedeployerservice"
)

func DeployChallenge() error {
patch := false
replicas := int32(1)
challengeType := "web"
log.Println("Starting")

katanaDir, err := utils.GetKatanaRootPath()
if err != nil {
return err
}
challengesDir:=katanaDir+"/challenges"

//Read folder challenge by os
dir, err := os.Open(challengesDir)

//Loop over all subfolders in the challenge folder
if err != nil {
log.Println("Error in opening challenges folder")
return err
}
defer dir.Close()

//Read all challenges in the folder
fileInfos, err := dir.Readdir(-1)
if err != nil {
log.Println("Error in reading challenges folder")
return err
}

res := make([][]string, 0)

//Loop over all folders
for _, fileInfo := range fileInfos {
//Check if it is a directory
if fileInfo.IsDir() {
//Get the challenger name
folderName := fileInfo.Name()
log.Println("Folder name is : " + folderName)
//Update challenge path to be absolute path
challengePath, _ := os.Getwd()
challengePath = challengePath + "/challenges/" + folderName
log.Println("Challenge path is : " + challengePath)
log.Println(challengePath + "/" + folderName + "/" + folderName)

//Check if the folder has a Dockerfile
if _, err := os.Stat(challengePath + "/" + folderName + "/" + folderName); err != nil {
log.Println("Dockerfile not found in the " + folderName + " challenge folder. Please follow proper format.")
} else {
//Update challenge path to get dockerfile
err := utils.BuildDockerImage(folderName, challengePath+"/"+folderName+"/"+folderName)
if err != nil {
return err
}
clusterConfig := g.ClusterConfig
numberOfTeams := clusterConfig.TeamCount
for i := 0; i < int(numberOfTeams); i++ {
log.Println("-----------Deploying challenge for team: " + strconv.Itoa(i) + " --------")
teamName := "katana-team-" + strconv.Itoa(i)
err = deployment.DeployChallengeToCluster(folderName, teamName, patch, replicas)
if err != nil {
if !(strings.Contains(err.Error(), "already exists")) {
return err
}else{
log.Println("Deployment already existed.")
}
}
url, err := challengedeployerservice.CreateServiceForChallenge(folderName, teamName, 3000, i)
if err != nil {
return err
} else {
res = append(res, []string{teamName, url})
}
}
}
err = challengedeployerservice.CopyChallengeIntoTsuka(challengePath, folderName, challengeType)
if err != nil {
return err
}
err = challengedeployerservice.CopyFlagDataIntoKashira(challengePath, folderName)
if err != nil {
return err
}
err = challengedeployerservice.CopyChallengeCheckerIntoKissaki(challengePath, folderName)
if err != nil {
return err
}
}
}
return nil
}

func DeleteChallenge(challengeName string) error {

//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 := configs.GlobalKubeClient
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
}

//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)
return err
}

flag := 0
for _, service := range services.Items {
if service.Name == challengeName+"-svc-"+strconv.Itoa(i) {
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+"-svc-"+strconv.Itoa(i), metav1.DeleteOptions{})
if err != nil {
log.Println("Error in deleting service for "+challengeName+" in namespace "+teamNamespace, err)
continue
}
}

log.Println("Process completed")

return nil
}
112 changes: 112 additions & 0 deletions cliHelpers/createTeams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package cliHelpers

import (
"bytes"
"context"
"fmt"
"html/template"
"log"
"os"
"path/filepath"
"strconv"

coreV1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"github.com/sdslabs/katana/configs"
"github.com/sdslabs/katana/lib/deployment"
"github.com/sdslabs/katana/lib/mongo"
"github.com/sdslabs/katana/lib/utils"
"github.com/sdslabs/katana/services/infrasetservice"
)

func CreateTeams() error {

// if !utils.VerifyToken(c) {
// return c.SendString("Unauthorized")
// }
config:= configs.GlobalKubeConfig
client:= configs.GlobalKubeClient
noOfTeams := int(configs.ClusterConfig.TeamCount)

if _, err := os.Stat("teams"); os.IsNotExist(err) {
errDir := os.Mkdir("teams", 0755)
if errDir != nil {
log.Fatal(err)
return err
}
}

// Create a directory named teams in the current directory
if _, err := os.Stat("teams"); os.IsNotExist(err) {
errDir := os.Mkdir("teams", 0755)
if errDir != nil {
log.Fatal(err)
}
}

// Create a directory named teams in the current directory
if _, err := os.Stat("teams"); os.IsNotExist(err) {
errDir := os.Mkdir("teams", 0755)
if errDir != nil {
log.Fatal(err)
}
}

var teams []interface{}
credsFile, err := os.Create(configs.SSHProviderConfig.CredsFile)
if err != nil {
log.Fatal(err)
return err
}

for i := 0; i < noOfTeams; i++ {
// Create a directory named katana-team-i in the teams directory
if _, err := os.Stat("teams/katana-team-" + strconv.Itoa(i)); os.IsNotExist(err) {
errDir := os.Mkdir("teams/katana-team-"+strconv.Itoa(i), 0755)
if errDir != nil {
log.Fatal(err)
return err
}
}

log.Println("Creating Team: " + strconv.Itoa(i))
namespace := "katana-team-" + strconv.Itoa(i) + "-ns"
nsName := &coreV1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
_, err = client.CoreV1().Namespaces().Create(context.TODO(), nsName, metav1.CreateOptions{})
if err != nil {
log.Fatal(err)
return err
}

manifest := &bytes.Buffer{}
tmpl, err := template.ParseFiles(filepath.Join(configs.ClusterConfig.TemplatedManifestDir, "runtime", "teams.yml"))
if err != nil {
return err
}

pwd, team, err := infrasetservice.CreateTeamCredentials(i)
if err != nil {
return err
}
deploymentConfig := utils.DeploymentConfig()

deploymentConfig.SSHPassword = pwd

if err = tmpl.Execute(manifest, deploymentConfig); err != nil {
return err
}

if err = deployment.ApplyManifest(config, client, manifest.Bytes(), namespace); err != nil {
return err
}
teams = append(teams, team)
fmt.Fprintf(credsFile, "Team: %d, Username: %s, Password: %s\n", i, team.Name, pwd)
}
mongo.CreateTeams(teams)
return nil
}
Loading
Loading