Skip to content

Commit 8e60e21

Browse files
committed
removed the kubectl dependency completely from applyYaml func and reverted the local setup changes
Signed-off-by: deep-poharkar <[email protected]>
1 parent 066895b commit 8e60e21

File tree

2 files changed

+92
-69
lines changed

2 files changed

+92
-69
lines changed

pkg/apis/upgrade.go

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
package apis
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/json"
67
"errors"
8+
"fmt"
79
"io/ioutil"
810
"net/http"
9-
"os"
1011

1112
"github.com/litmuschaos/litmusctl/pkg/k8s"
1213
"github.com/litmuschaos/litmusctl/pkg/types"
1314
"github.com/litmuschaos/litmusctl/pkg/utils"
15+
"github.com/mitchellh/go-homedir"
16+
"github.com/spf13/cobra"
1417
)
1518

1619
type manifestData struct {
@@ -46,7 +49,7 @@ func UpgradeInfra(c context.Context, cred types.Credentials, projectID string, i
4649

4750
// Query to fetch Infra details from server
4851
query := `{"query":"query {\n getInfraDetails(infraID : \"` + infraID + `\", \n projectID : \"` + projectID + `\"){\n infraNamespace infraID \n}}"}`
49-
resp, err := SendRequest(SendRequestParams{Endpoint: "http://localhost:8080/query", Token: cred.Token}, []byte(query), string(types.Post))
52+
resp, err := SendRequest(SendRequestParams{Endpoint: cred.Endpoint + utils.GQLAPIPath, Token: cred.Token}, []byte(query), string(types.Post))
5053
if err != nil {
5154
return "", err
5255
}
@@ -62,6 +65,7 @@ func UpgradeInfra(c context.Context, cred types.Credentials, projectID string, i
6265
if resp.StatusCode == http.StatusOK {
6366
err = json.Unmarshal(bodyBytes, &infra)
6467
if err != nil {
68+
fmt.Println("Error in unmarshalling infra")
6569
return "", err
6670
}
6771
if len(infra.Errors) > 0 {
@@ -73,8 +77,9 @@ func UpgradeInfra(c context.Context, cred types.Credentials, projectID string, i
7377

7478
// Query to fetch upgraded manifest from the server
7579
query = `{"query":"query {\n getInfraManifest(projectID : \"` + projectID + `\",\n infraID : \"` + infra.Data.GetInfraDetails.InfraID + `\", \n upgrade: true)}"}`
76-
resp, err = SendRequest(SendRequestParams{Endpoint: "http://localhost:8080/query", Token: cred.Token}, []byte(query), string(types.Post))
80+
resp, err = SendRequest(SendRequestParams{Endpoint: cred.Endpoint + utils.GQLAPIPath, Token: cred.Token}, []byte(query), string(types.Post))
7781
if err != nil {
82+
7883
return "", err
7984
}
8085

@@ -90,69 +95,55 @@ func UpgradeInfra(c context.Context, cred types.Credentials, projectID string, i
9095
var manifest manifestData
9196
err = json.Unmarshal(bodyBytes, &manifest)
9297
if err != nil {
98+
fmt.Println("Error in unmarshalling manifest")
9399
return "", err
94100
}
95101

96102
if len(manifest.Errors) > 0 {
97103
return "", errors.New(manifest.Errors[0].Message)
98104
}
99105

100-
// To write the manifest data into a temporary file
101-
err = ioutil.WriteFile("chaos-infra-manifest.yaml", []byte(manifest.Data.GetManifest), 0644)
106+
// Fetching subscriber-config from the subscriber
107+
configData, err := k8s.GetConfigMap(c, "subscriber-config", *infra.Data.GetInfraDetails.InfraNamespace)
102108
if err != nil {
103109
return "", err
104110
}
111+
var configMapString string
112+
113+
metadata := new(bytes.Buffer)
114+
fmt.Fprintf(metadata, "\n%s: %s\n%s: %s\n%s: \n %s: %s\n %s: %s\n%s:\n", "apiVersion", "v1",
115+
"kind", "ConfigMap", "metadata", "name", "subscriber-config", "namespace", *infra.Data.GetInfraDetails.InfraNamespace, "data")
116+
117+
for k, v := range configData {
118+
b := new(bytes.Buffer)
119+
if k == "COMPONENTS" {
120+
fmt.Fprintf(b, " %s: |\n %s", k, v)
121+
} else if k == "START_TIME" || k == "IS_INFRA_CONFIRMED" {
122+
fmt.Fprintf(b, " %s: \"%s\"\n", k, v)
123+
} else {
124+
fmt.Fprintf(b, " %s: %s\n", k, v)
125+
}
126+
configMapString = configMapString + b.String()
105127

106-
// Fetching subscriber-config from the subscriber
107-
// configData, err := k8s.GetConfigMap(c, "subscriber-config", *infra.Data.GetInfraDetails.InfraNamespace)
108-
// if err != nil {
109-
// return "", err
110-
// }
111-
// var configMapString string
112-
113-
// metadata := new(bytes.Buffer)
114-
// fmt.Fprintf(metadata, "\n%s: %s\n%s: %s\n%s: \n %s: %s\n %s: %s\n%s:\n", "apiVersion", "v1",
115-
// "kind", "ConfigMap", "metadata", "name", "subscriber-config", "namespace", *infra.Data.GetInfraDetails.InfraNamespace, "data")
116-
117-
// for k, v := range configData {
118-
// b := new(bytes.Buffer)
119-
// if k == "COMPONENTS" {
120-
// fmt.Fprintf(b, " %s: |\n %s", k, v)
121-
// } else if k == "START_TIME" || k == "IS_INFRA_CONFIRMED" {
122-
// fmt.Fprintf(b, " %s: \"%s\"\n", k, v)
123-
// } else {
124-
// fmt.Fprintf(b, " %s: %s\n", k, v)
125-
// }
126-
// configMapString = configMapString + b.String()
127-
128-
// }
129-
130-
yamlOutput, err := k8s.ApplyYaml(k8s.ApplyYamlParams{
131-
Token: cred.Token,
132-
Endpoint: cred.Endpoint,
133-
YamlPath: "chaos-infra-manifest.yaml",
134-
}, kubeconfig, true)
128+
}
129+
130+
yamlOutput, err := k8s.UpgradeInfra([]byte(manifest.Data.GetManifest), kubeconfig)
135131

136132
if err != nil {
137133
return "", err
138134
}
139135
utils.White.Print("\n", yamlOutput)
140136

141-
err = os.Remove("chaos-infra-manifest.yaml")
137+
// Creating a backup for current subscriber-config in the SUBSCRIBER
138+
home, err := homedir.Dir()
139+
cobra.CheckErr(err)
140+
141+
configMapString = metadata.String() + configMapString
142+
err = ioutil.WriteFile(home+"/backupSubscriberConfig.yaml", []byte(configMapString), 0644)
142143
if err != nil {
143-
return "Error removing Chaos Infrastructure manifest: ", err
144+
return "Error creating backup for subscriber config: ", err
144145
}
145146

146-
// Creating a backup for current subscriber-config in the SUBSCRIBER
147-
// home, err := homedir.Dir()
148-
// cobra.CheckErr(err)
149-
150-
// configMapString = metadata.String() + configMapString
151-
// err = ioutil.WriteFile(home+"/backupSubscriberConfig.yaml", []byte(configMapString), 0644)
152-
// if err != nil {
153-
// return "Error creating backup for subscriber config: ", err
154-
// }
155-
156147
utils.White_B.Print("\n ** A backup of subscriber-config configmap has been saved in your system's home directory as backupSubscriberConfig.yaml **\n")
157148

158149
return "Manifest applied successfully", nil

pkg/k8s/operations.go

Lines changed: 55 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"log"
2626
"net/http"
2727
"os"
28+
"os/exec"
2829
"path/filepath"
2930

3031
"k8s.io/client-go/discovery/cached/memory"
@@ -291,12 +292,61 @@ type ApplyYamlParams struct {
291292
}
292293

293294
func ApplyYaml(params ApplyYamlParams, kubeconfig string, isLocal bool) (output string, err error) {
294-
_, kubeClient, dynamicClient, err := getClientAndConfig(kubeconfig)
295+
path := params.YamlPath
296+
if !isLocal {
297+
path = fmt.Sprintf("%s%s/%s.yaml", params.Endpoint, params.YamlPath, params.Token)
298+
req, err := http.NewRequest("GET", path, nil)
299+
if err != nil {
300+
return "", err
301+
}
302+
resp, err := http.DefaultClient.Do(req)
303+
if err != nil {
304+
return "", err
305+
}
306+
defer resp.Body.Close()
307+
resp_body, err := ioutil.ReadAll(resp.Body)
308+
if err != nil {
309+
return "", err
310+
}
311+
err = ioutil.WriteFile("chaos-infra-manifest.yaml", resp_body, 0644)
312+
if err != nil {
313+
return "", err
314+
}
315+
path = "chaos-infra-manifest.yaml"
316+
}
317+
318+
args := []string{"kubectl", "apply", "-f", path}
319+
if kubeconfig != "" {
320+
args = append(args, []string{"--kubeconfig", kubeconfig}...)
321+
} else {
322+
args = []string{"kubectl", "apply", "-f", path}
323+
}
324+
325+
cmd := exec.Command(args[0], args[1:]...)
326+
var stdout, stderr bytes.Buffer
327+
cmd.Stdout = &stdout
328+
cmd.Stderr = &stderr
329+
err = cmd.Run()
330+
outStr, errStr := stdout.String(), stderr.String()
331+
332+
// err, can have exit status 1
295333
if err != nil {
334+
// if we get standard error then, return the same
335+
if errStr != "" {
336+
return "", fmt.Errorf(errStr)
337+
}
338+
339+
// if not standard error found, return error
296340
return "", err
297341
}
298342

299-
manifest, err := getManifest(isLocal, params, kubeClient)
343+
// If no error found, return standard output
344+
return outStr, nil
345+
}
346+
347+
func UpgradeInfra(manifest []byte, kubeconfig string) (string, error) {
348+
349+
_, kubeClient, dynamicClient, err := getClientAndConfig(kubeconfig)
300350
if err != nil {
301351
return "", err
302352
}
@@ -314,6 +364,7 @@ func ApplyYaml(params ApplyYamlParams, kubeconfig string, isLocal bool) (output
314364
logrus.Println("🚀 Successfully Upgraded Chaos Infra")
315365

316366
return "Success", nil
367+
317368
}
318369

319370
func getClientAndConfig(kubeconfig string) (*rest.Config, *kubernetes.Clientset, dynamic.Interface, error) {
@@ -358,29 +409,9 @@ func getClientAndConfig(kubeconfig string) (*rest.Config, *kubernetes.Clientset,
358409
return config, kubeClient, dynamicClient, nil
359410
}
360411

361-
func getManifest(isLocal bool, params ApplyYamlParams, kubeClient *kubernetes.Clientset) ([]byte, error) {
362-
if isLocal {
363-
home := homedir.HomeDir()
364-
chaosInfraManifest := filepath.Join(home, "chaos-infra-manifest.yaml")
365-
return ioutil.ReadFile(chaosInfraManifest)
366-
}
367-
368-
path := fmt.Sprintf("%s%s/%s.yaml", params.Endpoint, params.YamlPath, params.Token)
369-
req, err := http.NewRequest("GET", path, nil)
370-
if err != nil {
371-
return nil, fmt.Errorf("error in creating new request: %w", err)
372-
}
373-
resp, err := http.DefaultClient.Do(req)
374-
if err != nil {
375-
return nil, fmt.Errorf("error in fetching chaos infra manifest: %w", err)
376-
}
377-
defer resp.Body.Close()
378-
379-
return ioutil.ReadAll(resp.Body)
380-
}
381-
382412
func decodeManifest(manifest []byte) ([]*unstructured.Unstructured, error) {
383413
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(manifest), len(manifest))
414+
// fmt.Println(string(manifest))
384415

385416
// Split the resource file into separate YAML documents.
386417
resources := []*unstructured.Unstructured{}
@@ -392,6 +423,7 @@ func decodeManifest(manifest []byte) ([]*unstructured.Unstructured, error) {
392423
}
393424
return nil, fmt.Errorf("error in decoding resource: %w", err)
394425
}
426+
fmt.Println("resource", resourcestr)
395427
resources = append(resources, resourcestr)
396428
}
397429

0 commit comments

Comments
 (0)