Unable to list machinesets on Openshift 4.10 cluster - openshift

I am using the below code snippet to list machinesets but unable to get back any machinesets on the cluster:
cfg, err := config.GetConfig()
if err != nil {
log.Fatal(err)
}
opts := manager.Options{Scheme: scheme.Scheme}
mgr, err := manager.New(cfg, opts)
if err != nil {
klog.Fatal(err)
}
//Get client from manager
r = mgr.GetClient()
msList := &machinev1.MachineSetList{}
r.List(context.TODO(), msList, client.InNamespace(namespace_to_list))
klog.Infof("len, %d", len(msList.Items))
Any help is much appreciated, thanks

Related

AWS SDK How to increase ECS cluster ec2 instance without auto scaling

I'm using Demon service in ECS Cluster. Demon service cannot use auto-scaling.
I want to increase cluster ec2 instance count via aws ecs sdk.
But I can't find the function doing this.
Is there someone who knows this?
I found solution in aws cli sdk. by changing AsgMaxSize
import "github.com/aws/amazon-ecs-cli/ecs-cli/modules/clients/aws/cloudformation"
...
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
Credentials: credentials.NewStaticCredentials("AKID", "Secret", ""),
})
cloudClient := cloudformation.NewCloudformationClient(&config.CommandConfig{
Session:sess,
})
stackName := "EC2ContainerService-name"
params, err := cloudClient.GetStackParameters(stackName)
if err != nil {
log.Println(err)
return nil
}
log.Println(params)
newParams, err := cloudformation.NewCfnStackParamsForUpdate([]string{"AsgMaxSize"}, params)
if err != nil {
return nil
}
newParams.Add("AsgMaxSize", "3")
out, err := cloudClient.UpdateStack(stackName, newParams)
if err != nil {
log.Println(err)
return nil
}

Golang Encode/Decode base64 with json post doesn't work

I build a client and a server in golang both are using this functions to encrypt/decrypt
func encrypt(text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
b := base64.StdEncoding.EncodeToString(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
return ciphertext, nil
}
func decrypt(text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
data, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return nil, err
}
return data, nil
}
so yeah I make a normal post request
url := "https://"+configuration.Server+configuration.Port+"/get"
// TODO maybe bugs rest here
ciphertext, err := encrypt([]byte(*getUrl))
if err != nil {
fmt.Println("Error: " + err.Error())
}
fmt.Println(string(ciphertext))
values := map[string]interface{}{"url": *getUrl, "urlCrypted": ciphertext}
jsonValue, _ := json.Marshal(values)
jsonStr := bytes.NewBuffer(jsonValue)
req, err := http.NewRequest("POST", url, jsonStr)
and the servercode is as following
requestContent := getRequestContentFromRequest(req)
url := requestContent["url"].(string)
undecryptedUrl := requestContent["urlCrypted"].(string)
decryptedurl, err := decrypt([]byte(undecryptedUrl))
if err != nil {
fmt.Println("Error: " + err.Error())
}
fmt.Println(decryptedurl)
where getRequestContentFromRequest is as following
func getRequestContentFromRequest(req *http.Request)
map[string]interface{} {
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
data := buf.Bytes()
var requestContent map[string]interface{}
err := json.Unmarshal(data, &requestContent)
if err != nil {
fmt.Println(err)
}
return requestContent
}
Now to the problem.
If I encrypt my string in the client and decrypt it direct after that everything is fine.
But, when I send the encrypted string to the server and try to decrypt it with literrally the same function as in the client, the decrypt function throws an error.
Error: illegal base64 data at input byte 0
I think the Problem is the unmarshalling of the JSON.
Thanks for help.
P.S.
Repos are
github.com/BelphegorPrime/goSafeClient and github.com/BelphegorPrime/goSafe
UPDATE
Example JSON
{"url":"facebook2.com","urlCrypted":"/}\ufffd\ufffd\ufffdgP\ufffdN뼞\ufffd\u0016\ufffd)\ufffd\ufffd\ufffdy\u001c\u000f\ufffd\ufffd\ufffdep\ufffd\rY\ufffd\ufffd$\ufffd\ufffd"}
UPDATE2
I made a playground here
The problem is that you encode in base64 twice. The first time in the encrypt function and the second time during the JSON marshalling. byte slices are automatically converted into base64 strings by the encoding/json marshaller.
The solution is to decode the base64 string before calling decrypt.
Example on the Go PlayGround
EDIT
Working solution here

Best way to parse problematic JSON files in Golang

I have some valid JSON files and some which are not (without the surrounding brackets)
Currently I have a method for each case: one uses json.Unmarshal for the valid ones and the other uses json.NewDecoder for the bracketless ones.
How can I merge it into one function what can handle both cases?
EDIT:
Here is the code of the two cases:
func getDrivers() []Drivers {
raw, err := ioutil.ReadFile("/home/ubuntu/drivers.json")
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var d []Drivers
json.Unmarshal(raw, &d)
return d
}
func getMetrics() []Metrics {
file, err := os.Open("/home/ubuntu/metrics.json")
if err != nil {
fmt.Println("bad err!")
}
r := bufio.NewReader(file)
dec := json.NewDecoder(r)
// while the array contains values
var metrics []Metrics
for dec.More() {
var m Metrics
err := dec.Decode(&m)
if err != nil {
log.Fatal(err)
}
metrics = append(metrics, m)
}
return metrics
}
Thank you

System cannot find path specified trying to parse template

I'm just getting started learning about html/templates in Go. The error I'm getting is that 'system cannot find file path specified'. and the file path is templates/time.html. the location of time.html (the page I'm trying to render) is
src/templates/time.html
the location of my go main is src/timeserver/timerserver.go
here's the code I used
func TimeServer(w http.ResponseWriter, req *http.Request) {
// if user goes to another website after time/...
if req.URL.Path != "/time/" {
errorHandler(w, req, http.StatusNotFound)
return
}
cookie, _ := req.Cookie("UUID")
//existCheck := false
//temp2 := ""
profile := Profile{"",time.Now().Format("3:04:04 PM")}
if cookie != nil { // if cookie exist set flags
name, check := cookieJar.GetValue(cookie.Value)
profile = Profile{name,time.Now().Format("3:04:04 PM")}
fmt.Println(name)
//existCheck = check
//temp2 = name
fmt.Println(check)
}
fp := path.Join("templates", "time.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, profile); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
Problem was that my path wasn't correct. changed
fp := path.Join("templates", "time.html")
to
fp := path.Join("Home/go/src/templates", "time.html")

smtp won't work in production, Unauthenticated even with credentials

I am having a hell of a time here. My code works on the local instance (OSX) with this config:
mail.host = smtp.gmail.com
mail.port = 25
mail.from = mysite.com
mail.username = email#gmail.com
But says it is unauthenticated in production (Ubuntu 12.0.1):
Here is my code (and you can find all of it at github.com/tanema/revel_mailer). The authentication error is thrown at the c.Mail(username) line.
func (m *Mailer) Send(mail_args map[string]interface{}) error {
m.renderargs = mail_args
pc, _, _, _ := runtime.Caller(1)
names := strings.Split(runtime.FuncForPC(pc).Name(), ".")
m.template = names[len(names)-2] + "/" + names[len(names)-1]
host, host_ok := revel.Config.String("mail.host")
if !host_ok {
revel.ERROR.Println("mail host not set")
}
port, port_ok := revel.Config.Int("mail.port")
if !port_ok {
revel.ERROR.Println("mail port not set")
}
c, err := smtp.Dial(fmt.Sprintf("%s:%d", host, port))
if err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(nil); err != nil {
return err
}
}
from, from_ok := revel.Config.String("mail.from")
if !from_ok {
revel.ERROR.Println("mail.from not set")
}
username, username_ok := revel.Config.String("mail.username")
if !username_ok {
revel.ERROR.Println("mail.username not set")
}
if err = c.Auth(smtp.PlainAuth(from, username, getPassword(), host)); err != nil {
return err
}
if err = c.Mail(username); err != nil {
return err
}
if mail_args["to"] != nil {
m.to = makeSAFI(mail_args["to"]) //makeSAFI == make string array from interface
}
if mail_args["cc"] != nil {
m.cc = makeSAFI(mail_args["cc"])
}
if mail_args["bcc"] != nil {
m.bcc = makeSAFI(mail_args["bcc"])
}
if len(m.to) + len(m.cc) + len(m.bcc) == 0 {
return fmt.Errorf("Cannot send email without recipients")
}
recipients := append(m.to, append(m.cc, m.bcc...)...)
for _, addr := range recipients {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
mail, err := m.renderMail(w)
if err != nil {
return err
}
if revel.RunMode == "dev" {
fmt.Println(string(mail))
}
_, err = w.Write(mail)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}
I cannot figure out what the problem is; please help.
EDIT:
So I bit the bullet and signed up for google apps and set it all up with the domain and email. That lead me to believe that it was actually the MX records that I didnt change. So I tested out sending with my personal email again now that the MX records are set. No Luck. Any idea if I can setup the MX records for a personal gmail email so I dont have to pay for google apps?
I developed a Gmail front-end and encountered a similar problem. Try the following:
Try using ssl://smtp.gmail.com and port 465.
log into your GMail account to see if it says something like 'An unauthorised third-party tried to accesss this account'. If you do, then grant your app permission to log you in.