element_type
stringclasses
4 values
project_name
stringclasses
1 value
uuid
stringlengths
36
36
name
stringlengths
0
346
imports
stringlengths
0
2.67k
structs
stringclasses
761 values
interfaces
stringclasses
22 values
file_location
stringclasses
545 values
code
stringlengths
26
8.07M
global_vars
stringclasses
7 values
package
stringclasses
124 values
tags
stringclasses
1 value
function
openshift/openshift-tests-private
f1ebfcd3-a377-41e8-9111-1de7a416957f
GetSelinux
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetSelinux() string { return rf.statData["selinux"] }
mco
function
openshift/openshift-tests-private
3068d5bf-d483-4ce0-8a68-83f51e2a9016
GetName
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetName() string { return rf.statData["name"] }
mco
function
openshift/openshift-tests-private
f2de9cd0-875f-4453-9f4a-87dd7b867bf1
GetKind
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetKind() string { return rf.statData["kind"] }
mco
function
openshift/openshift-tests-private
60ab9f0c-784d-4252-bd37-2d20c959e18c
GetNpermissions
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetNpermissions() string { return rf.statData["octalperm"] }
mco
function
openshift/openshift-tests-private
bcb8237c-df07-459f-af49-49071deb1d23
GetOctalPermissions
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetOctalPermissions() string { return rf.statData["octalperm"] }
mco
function
openshift/openshift-tests-private
baf289b0-baff-4515-a308-e81262807e2d
GetUIDNumber
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetUIDNumber() string { return rf.statData["uidnumber"] }
mco
function
openshift/openshift-tests-private
91f76f9a-0106-4b19-87cb-fd1a1b603020
GetSymLink
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetSymLink() string { return rf.statData["symlink"] }
mco
function
openshift/openshift-tests-private
5535a6a2-0a19-4e59-bd07-1504157e1a8e
GetSize
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetSize() string { return rf.statData["size"] }
mco
function
openshift/openshift-tests-private
60c49223-fc5e-4c66-b031-0f752de13017
GetRWXPermissions
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetRWXPermissions() string { return rf.statData["rwxperm"] }
mco
function
openshift/openshift-tests-private
11d58375-7e97-4a8a-b9c9-c4f1e76ba4ab
GetGIDNumber
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetGIDNumber() string { return rf.statData["gidnumber"] }
mco
function
openshift/openshift-tests-private
b47973e9-ad32-4565-80e8-1a793f37a339
GetLinks
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) GetLinks() string { return rf.statData["links"] }
mco
function
openshift/openshift-tests-private
cf9a703d-00fe-4aec-864d-a60d8585adb9
IsDirectory
['"strings"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf *RemoteFile) IsDirectory() bool { return rf.GetRWXPermissions()[0] == 'd' && strings.Contains(rf.GetKind(), "directory") }
mco
function
openshift/openshift-tests-private
9f3ea5c0-b778-4cd6-8d72-f15601e1097a
GetTextContentAsList
['"strings"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) GetTextContentAsList() []string { return strings.Split(rf.GetTextContent(), "\n") }
mco
function
openshift/openshift-tests-private
ce0611c9-1ac5-43db-8ce9-03905fae1eb4
GetFilteredTextContent
['"regexp"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) GetFilteredTextContent(regex string) ([]string, error) { content := rf.GetTextContentAsList() filteredContent := []string{} for _, line := range content { match, err := regexp.MatchString(regex, line) if err != nil { logger.Errorf("Error filtering content lines. Error: %s", err) return nil, err } if match { filteredContent = append(filteredContent, line) } } return filteredContent, nil }
mco
function
openshift/openshift-tests-private
0ac058cd-8d21-4e46-a8a0-d66760f986f2
GetFullPath
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) GetFullPath() string { return rf.fullPath }
mco
function
openshift/openshift-tests-private
444b8a5c-0ef3-44c1-b12c-564bb68d7657
ExistsSafe
['"strings"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) ExistsSafe() (bool, error) { output, err := rf.node.DebugNodeWithChroot("stat", rf.fullPath) logger.Infof("\n%s", output) if strings.Contains(output, "No such file or directory") { return false, nil } if err == nil { return true, nil } return false, err }
mco
function
openshift/openshift-tests-private
cd9c6757-26aa-446e-8287-1dfa7495f36f
Exists
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) Exists() bool { exists, err := rf.ExistsSafe() return exists && (err == nil) }
mco
function
openshift/openshift-tests-private
e0afcca4-c63b-45e5-b781-44d1538720c4
Rm
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) Rm(args ...string) error { logger.Infof("Removing file %s from node %s", rf.fullPath, rf.node.GetName()) cmd := []string{"rm"} if len(args) > 0 { cmd = append(cmd, args...) } cmd = append(cmd, rf.fullPath) output, err := rf.node.DebugNodeWithChroot(cmd...) logger.Infof(output) return err }
mco
function
openshift/openshift-tests-private
c241517c-3924-4e54-9eec-5f4a913a7fbe
Create
['"fmt"', '"os"', '"path/filepath"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) Create(content []byte, perm os.FileMode) error { tmpFile := filepath.Join(e2e.TestContext.OutputDir, fmt.Sprintf("fetch-%s", exutil.GetRandomString())) if err := os.WriteFile(tmpFile, content, perm); err != nil { logger.Errorf("Could not read the content from tmp file %s. Error: %s", tmpFile, err) return err } if err := rf.node.CopyFromLocal(tmpFile, rf.fullPath); err != nil { logger.Errorf("Could not copy the file %s from local to path %s in node %s. Error: %s", tmpFile, rf.fullPath, rf.node.GetName(), err) return err } // Actually, the "oc adm copy-to-node" file will ignore the file permissions. Hence, we need to manually set the required permissions if err := rf.PushNewPermissions(fmt.Sprintf("%#o", perm)); err != nil { logger.Infof("Could not set the right permissions in remote file %s in node %s. Error: %s", rf.fullPath, rf.node.GetName(), err) } return nil }
mco
function
openshift/openshift-tests-private
7e3ce223-d8aa-4d52-ae6a-b96f1df9b2df
PrintDebugInfo
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) PrintDebugInfo() error { logger.Infof("Remote file %s in node %s", rf.fullPath, rf.node.GetName()) stdout, _, err := rf.node.DebugNodeWithChrootStd("stat", statFormat, rf.fullPath) if err != nil { return err } logger.Infof("Stat: \n%s", stdout) stdout, _, err = rf.node.DebugNodeWithChrootStd("cat", rf.fullPath) if err != nil { return err } logger.Infof("Content: \n%s", stdout) return nil }
mco
function
openshift/openshift-tests-private
9775858a-47b8-44d8-9889-d92a55993ca3
Read
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) Read() (RemoteFile, error) { return rf, rf.Fetch() }
mco
function
openshift/openshift-tests-private
7a888248-0637-4075-a349-ac396f76ecad
String
['"fmt"']
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) String() string { return fmt.Sprintf("file %s in node %s", rf.fullPath, rf.node.GetName()) }
mco
function
openshift/openshift-tests-private
37ef326e-8a9b-41a9-aed7-945a8ab3be91
HasInfo
['RemoteFile']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile.go
func (rf RemoteFile) HasInfo() bool { return len(rf.statData) > 0 }
mco
file
openshift/openshift-tests-private
c1d74766-503d-4668-b20b-cad65fe265b0
remotefile_gomegamatchers
import ( "fmt" "reflect" o "github.com/onsi/gomega" gomegamatchers "github.com/onsi/gomega/matchers" "github.com/onsi/gomega/types" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" )
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
package mco import ( "fmt" "reflect" o "github.com/onsi/gomega" gomegamatchers "github.com/onsi/gomega/matchers" "github.com/onsi/gomega/types" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" ) // struct implementing gomega matcher interface for RemoteFile struct type remoteFileMethodMatcher struct { method string methodDescMsg string retValue interface{} expected interface{} expectedMatcher types.GomegaMatcher } // Match checks it the condition matches the given json path. The json information matched is always treated as a string. func (matcher *remoteFileMethodMatcher) Match(actual interface{}) (success bool, err error) { // Check that the checked value is a string remoteFilePtr, ok := actual.(*RemoteFile) if !ok { remoteFileObj, ok := actual.(RemoteFile) if !ok { return false, fmt.Errorf(`Wrong type. Matcher expects a type "RemoteFile" or "*RemoteFile"`) } remoteFilePtr = &remoteFileObj } // If the info was not already gathered, we gather it if !remoteFilePtr.HasInfo() { err = remoteFilePtr.Fetch() logger.Infof("Gathering info for %s", remoteFilePtr) if err != nil { return false, err } } // Get a reflect.Value representing the instance value := reflect.ValueOf(remoteFilePtr) // Get a reflect.Method representing the desired method method := value.MethodByName(matcher.method) if !method.IsValid() { msg := fmt.Sprintf("RemoteFile gomega matcher. ERROR! NOT VALID METHOD: [%s]", matcher.method) logger.Errorf(msg) return false, o.StopTrying(msg) } // Call the method on the instance retValues := method.Call(nil) // We call the method without parameters numRetValues := len(retValues) if numRetValues == 0 { msg := fmt.Sprintf("RemoteFile gomega matcher. ERROR! METHOD DOES NOT RETURN ANY VALUE: [%s]", matcher.method) logger.Errorf(msg) return false, o.StopTrying(msg) } if numRetValues != 1 { logger.Warnf("The method %s is returning %d values. The matcher is ignoring all return values but the first one", matcher.method, numRetValues) } matcher.retValue = method.Call(nil)[0].Interface() // We call the method without parameters // Guess if we provided a value or another matcher in order to check the condition var isMatcher bool matcher.expectedMatcher, isMatcher = matcher.expected.(types.GomegaMatcher) if !isMatcher { matcher.expectedMatcher = &gomegamatchers.EqualMatcher{Expected: matcher.expected} } return matcher.expectedMatcher.Match(matcher.retValue) } // FailureMessage returns the message when testing `Should` case and `Match` returned false func (matcher *remoteFileMethodMatcher) FailureMessage(actual interface{}) (message string) { // The type was already validated in Match, we can safely ignore the error remoteFile, ok := actual.(RemoteFile) if !ok { remoteFilePtr, _ := actual.(*RemoteFile) remoteFile = *remoteFilePtr } methodDesc := matcher.method if matcher.methodDescMsg != "" { methodDesc = matcher.methodDescMsg } message = fmt.Sprintf("%s\n. File %s in node %s. The matcher was not satisfied by %s.", matcher.expectedMatcher.FailureMessage(matcher.retValue), remoteFile.GetFullPath(), remoteFile.node.GetName(), methodDesc) return message } // FailureMessage returns the message when testing `ShouldNot` case and `Match` returned true func (matcher *remoteFileMethodMatcher) NegatedFailureMessage(actual interface{}) (message string) { // The type was already validated in Match, we can safely ignore the error remoteFile, ok := actual.(RemoteFile) if !ok { remoteFilePtr, _ := actual.(*RemoteFile) remoteFile = *remoteFilePtr } methodDesc := matcher.method if matcher.methodDescMsg != "" { methodDesc = matcher.methodDescMsg } message = fmt.Sprintf("%s\n. File %s in node %s. The matcher was satisfied by %s, but it should NOT be satisfied", matcher.expectedMatcher.NegatedFailureMessage(matcher.retValue), remoteFile.GetFullPath(), remoteFile.node.GetName(), methodDesc) return message } // HaveContent returns the gomega matcher to check a RemoteFile's content func HaveContent(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetTextContent", methodDescMsg: "the file content"} } // HaveOctalPermissions returns the gomega matcher to check a RemoteFile's permissions. Permissions should be provided as a string representing octal permissions, like '"0644"') func HaveOctalPermissions(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetOctalPermissions", methodDescMsg: "the file permissions"} } // HaveOwner returns the gomega matcher to check a RemoteFile's owner. func HaveOwner(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetUIDName", methodDescMsg: "the file owner"} } // HaveOwnerID returns the gomega matcher to check a RemoteFile's owner ID. The expected owner's id shoul be a string representing the owner's id, like '"0"' (for root) func HaveOwnerID(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetUIDNumber", methodDescMsg: "the file owner"} } // HaveGroup returns the gomega matcher to check a RemoteFile's group. func HaveGroup(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetGIDName", methodDescMsg: "the file group"} } // HaveGroupID returns the gomega matcher to check a RemoteFile's group ID. The expected group's id shoul be a string representing the groups's id, like '"0"' (for root) func HaveGroupID(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetGIDNumber", methodDescMsg: "the file group"} }
package mco
function
openshift/openshift-tests-private
5a4168d0-8730-4695-acc8-573744bd60c5
Match
['"fmt"', '"reflect"', 'o "github.com/onsi/gomega"', '"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func (matcher *remoteFileMethodMatcher) Match(actual interface{}) (success bool, err error) { // Check that the checked value is a string remoteFilePtr, ok := actual.(*RemoteFile) if !ok { remoteFileObj, ok := actual.(RemoteFile) if !ok { return false, fmt.Errorf(`Wrong type. Matcher expects a type "RemoteFile" or "*RemoteFile"`) } remoteFilePtr = &remoteFileObj } // If the info was not already gathered, we gather it if !remoteFilePtr.HasInfo() { err = remoteFilePtr.Fetch() logger.Infof("Gathering info for %s", remoteFilePtr) if err != nil { return false, err } } // Get a reflect.Value representing the instance value := reflect.ValueOf(remoteFilePtr) // Get a reflect.Method representing the desired method method := value.MethodByName(matcher.method) if !method.IsValid() { msg := fmt.Sprintf("RemoteFile gomega matcher. ERROR! NOT VALID METHOD: [%s]", matcher.method) logger.Errorf(msg) return false, o.StopTrying(msg) } // Call the method on the instance retValues := method.Call(nil) // We call the method without parameters numRetValues := len(retValues) if numRetValues == 0 { msg := fmt.Sprintf("RemoteFile gomega matcher. ERROR! METHOD DOES NOT RETURN ANY VALUE: [%s]", matcher.method) logger.Errorf(msg) return false, o.StopTrying(msg) } if numRetValues != 1 { logger.Warnf("The method %s is returning %d values. The matcher is ignoring all return values but the first one", matcher.method, numRetValues) } matcher.retValue = method.Call(nil)[0].Interface() // We call the method without parameters // Guess if we provided a value or another matcher in order to check the condition var isMatcher bool matcher.expectedMatcher, isMatcher = matcher.expected.(types.GomegaMatcher) if !isMatcher { matcher.expectedMatcher = &gomegamatchers.EqualMatcher{Expected: matcher.expected} } return matcher.expectedMatcher.Match(matcher.retValue) }
mco
function
openshift/openshift-tests-private
dd7ca2d6-1a5f-4363-967f-9bc70156bce2
FailureMessage
['"fmt"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func (matcher *remoteFileMethodMatcher) FailureMessage(actual interface{}) (message string) { // The type was already validated in Match, we can safely ignore the error remoteFile, ok := actual.(RemoteFile) if !ok { remoteFilePtr, _ := actual.(*RemoteFile) remoteFile = *remoteFilePtr } methodDesc := matcher.method if matcher.methodDescMsg != "" { methodDesc = matcher.methodDescMsg } message = fmt.Sprintf("%s\n. File %s in node %s. The matcher was not satisfied by %s.", matcher.expectedMatcher.FailureMessage(matcher.retValue), remoteFile.GetFullPath(), remoteFile.node.GetName(), methodDesc) return message }
mco
function
openshift/openshift-tests-private
4344d825-26fb-4a3a-a7bf-8134ef4414b0
NegatedFailureMessage
['"fmt"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func (matcher *remoteFileMethodMatcher) NegatedFailureMessage(actual interface{}) (message string) { // The type was already validated in Match, we can safely ignore the error remoteFile, ok := actual.(RemoteFile) if !ok { remoteFilePtr, _ := actual.(*RemoteFile) remoteFile = *remoteFilePtr } methodDesc := matcher.method if matcher.methodDescMsg != "" { methodDesc = matcher.methodDescMsg } message = fmt.Sprintf("%s\n. File %s in node %s. The matcher was satisfied by %s, but it should NOT be satisfied", matcher.expectedMatcher.NegatedFailureMessage(matcher.retValue), remoteFile.GetFullPath(), remoteFile.node.GetName(), methodDesc) return message }
mco
function
openshift/openshift-tests-private
df8abf8e-2c21-4dd4-89e7-dad304b8ac6d
HaveContent
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveContent(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetTextContent", methodDescMsg: "the file content"} }
mco
function
openshift/openshift-tests-private
f3d13293-39ea-4df1-a0b0-4b0ff3313a1c
HaveOctalPermissions
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveOctalPermissions(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetOctalPermissions", methodDescMsg: "the file permissions"} }
mco
function
openshift/openshift-tests-private
d1cccf16-215a-48c4-a390-3cc787828a1f
HaveOwner
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveOwner(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetUIDName", methodDescMsg: "the file owner"} }
mco
function
openshift/openshift-tests-private
4739e3ae-35a3-4d90-bf4f-3242876fbe64
HaveOwnerID
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveOwnerID(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetUIDNumber", methodDescMsg: "the file owner"} }
mco
function
openshift/openshift-tests-private
dd309330-0ce9-4a1a-aca9-a4444760ddec
HaveGroup
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveGroup(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetGIDName", methodDescMsg: "the file group"} }
mco
function
openshift/openshift-tests-private
1f61de97-a924-44b5-bb0c-ec26e4bd88d2
HaveGroupID
['"github.com/onsi/gomega/types"']
['remoteFileMethodMatcher']
github.com/openshift/openshift-tests-private/test/extended/mco/remotefile_gomegamatchers.go
func HaveGroupID(expected interface{}) types.GomegaMatcher { return &remoteFileMethodMatcher{expected: expected, method: "GetGIDNumber", methodDescMsg: "the file group"} }
mco
file
openshift/openshift-tests-private
74c51e74-ca59-4339-a24c-6442f1e5f17e
skopeo_client
import ( "bytes" "fmt" "io" "os" "os/exec" "strings" container "github.com/openshift/openshift-tests-private/test/extended/util/container" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" )
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
package mco import ( "bytes" "fmt" "io" "os" "os/exec" "strings" container "github.com/openshift/openshift-tests-private/test/extended/util/container" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" ) // SkopeoCLI provides function to run the docker command type SkopeoCLI struct { execPath string ExecCommandPath string globalArgs []string commandArgs []string finalArgs []string verbose bool stdin *bytes.Buffer stdout io.Writer stderr io.Writer showInfo bool UnsetProxy bool env []string authFile string } // NewSkopeoCLI initialize the docker cli framework func NewSkopeoCLI() *SkopeoCLI { newclient := &SkopeoCLI{} newclient.execPath = "skopeo" newclient.showInfo = true newclient.UnsetProxy = false return newclient } // Run executes given skopeo command func (c *SkopeoCLI) Run(commands ...string) *SkopeoCLI { in, out, errout := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{} skopeo := &SkopeoCLI{ execPath: c.execPath, ExecCommandPath: c.ExecCommandPath, UnsetProxy: c.UnsetProxy, showInfo: c.showInfo, env: c.env, } skopeo.globalArgs = commands if c.authFile != "" { skopeo.globalArgs = append(skopeo.globalArgs, "--authfile", c.authFile) } skopeo.stdin, skopeo.stdout, skopeo.stderr = in, out, errout return skopeo.setOutput(c.stdout) } // Output executes the command and returns stdout combined into one string func (c *SkopeoCLI) Output() (string, error) { if c.verbose { logger.Infof("DEBUG: skopeo %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Env = os.Environ() if c.UnsetProxy { var envCmd []string for _, envIndex := range cmd.Env { if !(strings.Contains(strings.ToUpper(envIndex), "HTTP_PROXY") || strings.Contains(strings.ToUpper(envIndex), "HTTPS_PROXY") || strings.Contains(strings.ToUpper(envIndex), "NO_PROXY")) { envCmd = append(envCmd, envIndex) } } cmd.Env = envCmd } if c.env != nil { cmd.Env = append(cmd.Env, c.env...) } if c.ExecCommandPath != "" { logger.Infof("set exec command path is %s\n", c.ExecCommandPath) cmd.Dir = c.ExecCommandPath } cmd.Stdin = c.stdin if c.showInfo { logger.Infof("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) } out, err := cmd.Output() trimmed := strings.TrimSpace(string(out)) switch e := err.(type) { case nil: c.stdout = bytes.NewBuffer(out) return trimmed, nil case *exec.ExitError: c.stdout = bytes.NewBuffer(out) c.stderr = bytes.NewBuffer(e.Stderr) logger.Errorf("Error running %v:\nSTDOUT:%s\nSTDERR:%s", cmd, trimmed, string(e.Stderr)) return trimmed, &container.ExitError{ExitError: e, Cmd: c.execPath + " " + strings.Join(c.finalArgs, " "), StdErr: trimmed} default: container.FatalErr(fmt.Errorf("unable to execute %q: %v", c.execPath, err)) return "", nil } } func (c *SkopeoCLI) printCmd() string { return strings.Join(c.finalArgs, " ") } // Args sets the additional arguments for the skopeo CLI command func (c *SkopeoCLI) Args(args ...string) *SkopeoCLI { c.commandArgs = args c.finalArgs = c.globalArgs c.finalArgs = append(c.finalArgs, c.commandArgs...) return c } // setOutput allows to override the default command output func (c *SkopeoCLI) setOutput(out io.Writer) *SkopeoCLI { c.stdout = out return c } // SetAuthFile sets a file to be used to authorize skopeo. If an authFile is set, all commands will be executed with '--authfile authFile' parameters func (c *SkopeoCLI) SetAuthFile(authFile string) *SkopeoCLI { c.authFile = authFile return c }
package mco
function
openshift/openshift-tests-private
f26a05a5-a4f4-4ddd-99c0-9834d7eae1c9
NewSkopeoCLI
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func NewSkopeoCLI() *SkopeoCLI { newclient := &SkopeoCLI{} newclient.execPath = "skopeo" newclient.showInfo = true newclient.UnsetProxy = false return newclient }
mco
function
openshift/openshift-tests-private
66eec73f-44c4-45f1-b0fd-ca4af9995530
Run
['"bytes"']
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) Run(commands ...string) *SkopeoCLI { in, out, errout := &bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{} skopeo := &SkopeoCLI{ execPath: c.execPath, ExecCommandPath: c.ExecCommandPath, UnsetProxy: c.UnsetProxy, showInfo: c.showInfo, env: c.env, } skopeo.globalArgs = commands if c.authFile != "" { skopeo.globalArgs = append(skopeo.globalArgs, "--authfile", c.authFile) } skopeo.stdin, skopeo.stdout, skopeo.stderr = in, out, errout return skopeo.setOutput(c.stdout) }
mco
function
openshift/openshift-tests-private
0a79424a-cd6b-4893-b006-8e83ce6574e5
Output
['"bytes"', '"fmt"', '"os"', '"os/exec"', '"strings"', 'container "github.com/openshift/openshift-tests-private/test/extended/util/container"']
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) Output() (string, error) { if c.verbose { logger.Infof("DEBUG: skopeo %s\n", c.printCmd()) } cmd := exec.Command(c.execPath, c.finalArgs...) cmd.Env = os.Environ() if c.UnsetProxy { var envCmd []string for _, envIndex := range cmd.Env { if !(strings.Contains(strings.ToUpper(envIndex), "HTTP_PROXY") || strings.Contains(strings.ToUpper(envIndex), "HTTPS_PROXY") || strings.Contains(strings.ToUpper(envIndex), "NO_PROXY")) { envCmd = append(envCmd, envIndex) } } cmd.Env = envCmd } if c.env != nil { cmd.Env = append(cmd.Env, c.env...) } if c.ExecCommandPath != "" { logger.Infof("set exec command path is %s\n", c.ExecCommandPath) cmd.Dir = c.ExecCommandPath } cmd.Stdin = c.stdin if c.showInfo { logger.Infof("Running '%s %s'", c.execPath, strings.Join(c.finalArgs, " ")) } out, err := cmd.Output() trimmed := strings.TrimSpace(string(out)) switch e := err.(type) { case nil: c.stdout = bytes.NewBuffer(out) return trimmed, nil case *exec.ExitError: c.stdout = bytes.NewBuffer(out) c.stderr = bytes.NewBuffer(e.Stderr) logger.Errorf("Error running %v:\nSTDOUT:%s\nSTDERR:%s", cmd, trimmed, string(e.Stderr)) return trimmed, &container.ExitError{ExitError: e, Cmd: c.execPath + " " + strings.Join(c.finalArgs, " "), StdErr: trimmed} default: container.FatalErr(fmt.Errorf("unable to execute %q: %v", c.execPath, err)) return "", nil } }
mco
function
openshift/openshift-tests-private
9786815b-eaa3-4bde-873e-e871a08baa6a
printCmd
['"strings"']
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) printCmd() string { return strings.Join(c.finalArgs, " ") }
mco
function
openshift/openshift-tests-private
6af83235-7a44-4f81-a758-ac2d60a2114c
Args
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) Args(args ...string) *SkopeoCLI { c.commandArgs = args c.finalArgs = c.globalArgs c.finalArgs = append(c.finalArgs, c.commandArgs...) return c }
mco
function
openshift/openshift-tests-private
f40bae12-c6af-43c1-9b2f-ca20ac06ccb2
setOutput
['"io"']
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) setOutput(out io.Writer) *SkopeoCLI { c.stdout = out return c }
mco
function
openshift/openshift-tests-private
d6326c56-c8f1-4e90-a281-ee27fbadc8b4
SetAuthFile
['SkopeoCLI']
github.com/openshift/openshift-tests-private/test/extended/mco/skopeo_client.go
func (c *SkopeoCLI) SetAuthFile(authFile string) *SkopeoCLI { c.authFile = authFile return c }
mco
file
openshift/openshift-tests-private
e6ea5d9e-1720-443c-ac93-6e31403f6df2
testcontext
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
package mco // SharedContext is designed to store test context info as k,v pairs // it can be used to share context values thru all test funcs // test struct can be inherited from this, it can store all kinds of data, primitive or struct // you can get the str,int,bool values. i.e. they're frequently used data types. // note: this impl is not thread safe, dont' use it for concurrent scenario. type SharedContext struct { ctx map[string]interface{} } // NewSharedContext constructor func NewSharedContext() *SharedContext { return &SharedContext{ ctx: make(map[string]interface{}), } } // Put store k,v data in map func (sc *SharedContext) Put(k string, v interface{}) { sc.ctx[k] = v } // Get get object by key, it will return original data func (sc *SharedContext) Get(k string) interface{} { return sc.ctx[k] } // StrValue get value by key and convert it to string // if data type assertion failed, return empty string func (sc *SharedContext) StrValue(k string) string { if v, ok := sc.Get(k).(string); ok { return v } return "" } // IntValue get value by key and convert it to integer // if data type assertion failed, return zero func (sc *SharedContext) IntValue(k string) int { if v, ok := sc.Get(k).(int); ok { return v } return 0 } // BoolValue get value by key and conver it to boolean // if data type assertion failed, return false func (sc *SharedContext) BoolValue(k string) bool { if v, ok := sc.Get(k).(bool); ok { return v } return false }
package mco
function
openshift/openshift-tests-private
47f7a97f-e1a8-4ac2-b1ac-d7579dffbc62
NewSharedContext
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func NewSharedContext() *SharedContext { return &SharedContext{ ctx: make(map[string]interface{}), } }
mco
function
openshift/openshift-tests-private
c09518f9-9e50-4b8e-b45c-c32ec42c8eed
Put
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func (sc *SharedContext) Put(k string, v interface{}) { sc.ctx[k] = v }
mco
function
openshift/openshift-tests-private
bb140d43-0c83-4b20-9158-c6f9308e9fb6
Get
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func (sc *SharedContext) Get(k string) interface{} { return sc.ctx[k] }
mco
function
openshift/openshift-tests-private
7cf9c0ea-97b1-4d78-abe3-8aceaeef44c5
StrValue
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func (sc *SharedContext) StrValue(k string) string { if v, ok := sc.Get(k).(string); ok { return v } return "" }
mco
function
openshift/openshift-tests-private
99a6ee11-8451-4039-ad85-3770cbff4b33
IntValue
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func (sc *SharedContext) IntValue(k string) int { if v, ok := sc.Get(k).(int); ok { return v } return 0 }
mco
function
openshift/openshift-tests-private
24e41778-afb8-4bee-8a04-418abd5bf7a9
BoolValue
['SharedContext']
github.com/openshift/openshift-tests-private/test/extended/mco/testcontext.go
func (sc *SharedContext) BoolValue(k string) bool { if v, ok := sc.Get(k).(bool); ok { return v } return false }
mco
file
openshift/openshift-tests-private
fdb1e9f6-b661-423e-96c6-295b61caeb0b
types
github.com/openshift/openshift-tests-private/test/extended/mco/types.go
package mco // Ignition 2.2.0 // ign22FileUser describes the user that will own a given file type ign22FileUser struct { Name string `json:"name,omitempty"` ID *int `json:"id,omitempty"` } // ign22FileGroup describes the group that will own a given file type ign22FileGroup struct { Name string `json:"name,omitempty"` ID *int `json:"id,omitempty"` } // ign22Contents describes the "contents" field in an ignition 2.2.0 File configuration type ign22Contents struct { Compression string `json:"compression,omitempty"` Source string `json:"source,omitempty"` } // ign22File describes the configuration of a File in ignition 2.2.0 type ign22File struct { Path string `json:"path,omitempty"` Contents ign22Contents `json:"contents,omitempty"` Mode *int `json:"mode,omitempty"` User *ign22FileUser `json:"user,omitempty"` Group *ign22FileGroup `json:"group,omitempty"` Filesystem string `json:"filesystem,omitempty"` } // Ignition 3.2.0. // ign32Contents describes the "contents" field in an ignition 3.2.0 File configuration type ign32Contents struct { Compression string `json:"compression,omitempty"` Source string `json:"source,omitempty"` } // ign32FileUser describes the user that will own a given file type ign32FileUser struct { Name string `json:"name,omitempty"` ID *int `json:"id,omitempty"` } // ign32FileGroup describes the group that will own a given file type ign32FileGroup struct { Name string `json:"name,omitempty"` ID *int `json:"id,omitempty"` } // ign32File describes the configuration of a File in ignition 3.0.0, 3.1.0, 3.2.0, 3.3.0 and 3.4.0 type ign32File struct { Path string `json:"path,omitempty"` Contents ign32Contents `json:"contents,omitempty"` Mode *int `json:"mode,omitempty"` User *ign32FileUser `json:"user,omitempty"` Group *ign32FileGroup `json:"group,omitempty"` } // ign32PaswdUser describes the passwd data regarding a given user type ign32PaswdUser struct { Name string `json:"name,omitempty"` SSHAuthorizedKeys []string `json:"sshAuthorizedKeys,omitempty"` PasswordHash string `json:"passwordHash,omitempty"` }
package mco
file
openshift/openshift-tests-private
0c947cad-cfee-4a34-8631-91b8eb9122bb
versions
import ( "strconv" "strings" e2e "k8s.io/kubernetes/test/e2e/framework" )
github.com/openshift/openshift-tests-private/test/extended/mco/versions.go
package mco import ( "strconv" "strings" e2e "k8s.io/kubernetes/test/e2e/framework" ) var operators = map[string][]int{ "<": {1}, ">": {-1}, "=": {0}, "==": {0}, "<=": {0, 1}, "=<": {0, 1}, ">=": {0, -1}, "=>": {0, -1}, } func validateOperator(operator string) { keys := make([]string, 0, len(operators)) for k := range operators { keys = append(keys, k) if operator == k { return } } e2e.Failf("Operator %s not permitted. Permitted operators: %s", operator, keys) } func compareVer(l, r string) (ret int) { ls := strings.Split(l, ".") rs := strings.Split(r, ".") maxlen := len(ls) if len(rs) > len(ls) { maxlen = len(rs) } for i := 0; i < maxlen; i++ { var tmpl, tmpr string if len(ls) > i { tmpl = ls[i] } if len(rs) > i { tmpr = rs[i] } li, _ := strconv.Atoi(tmpl) ri, _ := strconv.Atoi(tmpr) if li > ri { return -1 } else if li < ri { return 1 } } return 0 } // CompareVersions returns the result of comparing 2 versions using the given operator to compare // i.e CompareVersions("3.1", ">", "3.0") return true func CompareVersions(l, operator, r string) bool { validateOperator(operator) expectedResults := operators[operator] result := compareVer(l, r) for _, res := range expectedResults { if result == res { return true } } return false }
package mco
function
openshift/openshift-tests-private
3e01ce98-4ff7-45ca-be4e-5668348a58b1
validateOperator
github.com/openshift/openshift-tests-private/test/extended/mco/versions.go
func validateOperator(operator string) { keys := make([]string, 0, len(operators)) for k := range operators { keys = append(keys, k) if operator == k { return } } e2e.Failf("Operator %s not permitted. Permitted operators: %s", operator, keys) }
{'operators': 'map[string][]int{\n\t"<": {1},\n\t">": {-1},\n\t"=": {0},\n\t"==": {0},\n\t"<=": {0, 1},\n\t"=<": {0, 1},\n\t">=": {0, -1},\n\t"=>": {0, -1},\n}'}
mco
function
openshift/openshift-tests-private
b193a49d-7490-4441-8ba1-14fa235933a4
compareVer
['"strconv"', '"strings"']
github.com/openshift/openshift-tests-private/test/extended/mco/versions.go
func compareVer(l, r string) (ret int) { ls := strings.Split(l, ".") rs := strings.Split(r, ".") maxlen := len(ls) if len(rs) > len(ls) { maxlen = len(rs) } for i := 0; i < maxlen; i++ { var tmpl, tmpr string if len(ls) > i { tmpl = ls[i] } if len(rs) > i { tmpr = rs[i] } li, _ := strconv.Atoi(tmpl) ri, _ := strconv.Atoi(tmpr) if li > ri { return -1 } else if li < ri { return 1 } } return 0 }
mco
function
openshift/openshift-tests-private
a41df20c-0563-4138-bc34-1ee79355b12e
CompareVersions
github.com/openshift/openshift-tests-private/test/extended/mco/versions.go
func CompareVersions(l, operator, r string) bool { validateOperator(operator) expectedResults := operators[operator] result := compareVer(l, r) for _, res := range expectedResults { if result == res { return true } } return false }
mco
file
openshift/openshift-tests-private
7952aa21-7f76-4ea7-8c70-9411a0b2be46
controller
import ( "fmt" "regexp" "strings" "time" o "github.com/onsi/gomega" exutil "github.com/openshift/openshift-tests-private/test/extended/util" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" )
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
package mco import ( "fmt" "regexp" "strings" "time" o "github.com/onsi/gomega" exutil "github.com/openshift/openshift-tests-private/test/extended/util" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" ) // Controller handles the functinalities related to the MCO controller pod type Controller struct { oc *exutil.CLI logsCheckPoint string podName string } // NewController creates a new Controller struct func NewController(oc *exutil.CLI) *Controller { return &Controller{oc: oc, logsCheckPoint: "", podName: ""} } // GetCachedPodName returns the cached value of the MCO controller pod name. If there is no value available it tries to execute a command to get the pod name from the cluster func (mcc *Controller) GetCachedPodName() (string, error) { if mcc.podName == "" { podName, err := mcc.GetPodName() if err != nil { logger.Infof("Error trying to get the machine-config-controller pod name. Error: %s", err) return "", err } mcc.podName = podName } return mcc.podName, nil } // GetPodName executed a command to get the current pod name of the MCO controller pod. Updateds the cached value of the pod name // This function refreshes the pod name cache func (mcc *Controller) GetPodName() (string, error) { podName, err := mcc.oc.WithoutNamespace().Run("get").Args("pod", "-n", MachineConfigNamespace, "-l", ControllerLabel+"="+ControllerLabelValue, "-o", "jsonpath={.items[0].metadata.name}").Output() if err != nil { return "", err } mcc.podName = podName return podName, nil } // IgnoreLogsBeforeNow when it is called all logs generated before calling it will be ignored by "GetLogs" func (mcc *Controller) IgnoreLogsBeforeNow() error { mcc.logsCheckPoint = "" logsUptoNow, err := mcc.GetLogs() if err != nil { return err } mcc.logsCheckPoint = logsUptoNow return nil } // IgnoreLogsBeofreNowOrFail when it is called all logs generated before calling it will be ignored by "GetLogs", if this method fails, the test is failed func (mcc *Controller) IgnoreLogsBeforeNowOrFail() *Controller { err := mcc.IgnoreLogsBeforeNow() o.Expect(err).NotTo(o.HaveOccurred(), "Error trying to ignore old logs in the MachineConfigController pod") return mcc } // StopIgnoringLogs when it is called "IgnoreLogsBeforeNow" effect will not be taken into account anymore, and "GetLogs" will return full logs in MCO controller func (mcc *Controller) StopIgnoringLogs() { mcc.logsCheckPoint = "" } // GetIgnoredLogs returns the logs that will be ignored after calling "IgnoreLogsBeforeNow" func (mcc Controller) GetIgnoredLogs() string { return mcc.logsCheckPoint } // GetLogs returns the MCO controller logs. Logs generated before calling the function "IgnoreLogsBeforeNow" will not be returned // This function can return big log so, please, try not to print the returned value in your tests func (mcc *Controller) GetLogs() (string, error) { var ( podAllLogs = "" err error ) err = Retry(5, 5*time.Second, func() error { podAllLogs, err = mcc.GetRawLogs() if err != nil { mcc.podName = "" } return err }) if err != nil { return "", err } // Remove the logs before the check point return strings.Replace(podAllLogs, mcc.logsCheckPoint, "", 1), nil } // GetRawLogs return the controller pod's logs without removing the ignored logs part func (mcc Controller) GetRawLogs() (string, error) { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return "", err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return "", err } podAllLogs, err := exutil.GetSpecificPodLogs(mcc.oc, MachineConfigNamespace, ControllerContainer, cachedPodName, "") if err != nil { logger.Errorf("Error getting log lines. Error: %s", err) return "", err } return podAllLogs, nil } // HasAcquiredLease returns true if the controller acquired the lease properly func (mcc Controller) HasAcquiredLease() (bool, error) { podAllLogs, err := mcc.GetRawLogs() if err != nil { return false, err } return strings.Contains(podAllLogs, "successfully acquired lease"), nil } // GetLogsAsList returns the MCO controller logs as a list strings. One string per line func (mcc Controller) GetLogsAsList() ([]string, error) { logs, err := mcc.GetLogs() if err != nil { return nil, err } return strings.Split(logs, "\n"), nil } // GetFilteredLogsAsList returns the filtered logs as a lit of strings, one string per line. func (mcc Controller) GetFilteredLogsAsList(regex string) ([]string, error) { logs, err := mcc.GetLogsAsList() if err != nil { return nil, err } filteredLogs := []string{} for _, line := range logs { match, err := regexp.MatchString(regex, line) if err != nil { logger.Errorf("Error filtering log lines. Error: %s", err) return nil, err } if match { filteredLogs = append(filteredLogs, line) } } return filteredLogs, nil } // GetFilteredLogs returns the logs filtered by a regexp applied to every line. If the match is ok the log line is accepted. // This function can return big log so, please, try not to print the returned value in your tests func (mcc Controller) GetFilteredLogs(regex string) (string, error) { logs, err := mcc.GetFilteredLogsAsList(regex) if err != nil { return "", err } return strings.Join(logs, "\n"), nil } // RemovePod removes the controller pod forcing the creation of a new one func (mcc Controller) RemovePod() error { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return err } // remove the cached podname, since it will not be valid anymore mcc.podName = "" return mcc.oc.WithoutNamespace().Run("delete").Args("pod", "-n", MachineConfigNamespace, cachedPodName).Execute() } // GetNode return the node where the machine controller is running func (mcc Controller) GetNode() (*Node, error) { controllerPodName, err := mcc.GetCachedPodName() if err != nil { return nil, err } controllerPod := NewNamespacedResource(mcc.oc, "pod", MachineConfigNamespace, controllerPodName) nodeName, err := controllerPod.Get(`{.spec.nodeName}`) if err != nil { return nil, err } return NewNode(mcc.oc, nodeName), nil } // GetPreviousLogs returns previous logs of mcc pod func (mcc Controller) GetPreviousLogs() (string, error) { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return "", err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return "", err } prevLogs, err := NewNamespacedResource(mcc.oc, "pod", MachineConfigNamespace, cachedPodName).Logs("-p") if err != nil { exitError, ok := err.(*exutil.ExitError) if ok { if strings.Contains(exitError.StdErr, "not found") { logger.Infof("There was no previous pod for %s", cachedPodName) return "", nil } logger.Infof("An execution error happened, but was not expected: %s", exitError.StdErr) } logger.Infof("Unexpected error while getting MCC previous logs: %s", err) return prevLogs, err } return prevLogs, nil }
package mco
function
openshift/openshift-tests-private
4dbde8c7-ebeb-46b2-b3f6-5d10d7d085bf
NewController
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func NewController(oc *exutil.CLI) *Controller { return &Controller{oc: oc, logsCheckPoint: "", podName: ""} }
mco
function
openshift/openshift-tests-private
1de2ee38-4c37-4ae8-92e0-b51403180747
GetCachedPodName
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) GetCachedPodName() (string, error) { if mcc.podName == "" { podName, err := mcc.GetPodName() if err != nil { logger.Infof("Error trying to get the machine-config-controller pod name. Error: %s", err) return "", err } mcc.podName = podName } return mcc.podName, nil }
mco
function
openshift/openshift-tests-private
b19e77b3-37b6-4a1e-8a50-67ca74bf1bbc
GetPodName
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) GetPodName() (string, error) { podName, err := mcc.oc.WithoutNamespace().Run("get").Args("pod", "-n", MachineConfigNamespace, "-l", ControllerLabel+"="+ControllerLabelValue, "-o", "jsonpath={.items[0].metadata.name}").Output() if err != nil { return "", err } mcc.podName = podName return podName, nil }
mco
function
openshift/openshift-tests-private
592aca4b-4a9d-41ba-9d6d-e17c766bb7b4
IgnoreLogsBeforeNow
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) IgnoreLogsBeforeNow() error { mcc.logsCheckPoint = "" logsUptoNow, err := mcc.GetLogs() if err != nil { return err } mcc.logsCheckPoint = logsUptoNow return nil }
mco
function
openshift/openshift-tests-private
973f59f6-9388-4329-8169-7bb95e19ff49
IgnoreLogsBeforeNowOrFail
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) IgnoreLogsBeforeNowOrFail() *Controller { err := mcc.IgnoreLogsBeforeNow() o.Expect(err).NotTo(o.HaveOccurred(), "Error trying to ignore old logs in the MachineConfigController pod") return mcc }
mco
function
openshift/openshift-tests-private
e5f90f1e-ecc6-4ca4-a60a-17042ab2af86
StopIgnoringLogs
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) StopIgnoringLogs() { mcc.logsCheckPoint = "" }
mco
function
openshift/openshift-tests-private
08e56386-8aec-484c-be48-ca551d0d77af
GetIgnoredLogs
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetIgnoredLogs() string { return mcc.logsCheckPoint }
mco
function
openshift/openshift-tests-private
af7884ff-8149-4c40-8af2-b64a9610921f
GetLogs
['"strings"', '"time"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc *Controller) GetLogs() (string, error) { var ( podAllLogs = "" err error ) err = Retry(5, 5*time.Second, func() error { podAllLogs, err = mcc.GetRawLogs() if err != nil { mcc.podName = "" } return err }) if err != nil { return "", err } // Remove the logs before the check point return strings.Replace(podAllLogs, mcc.logsCheckPoint, "", 1), nil }
mco
function
openshift/openshift-tests-private
81896f04-f1f9-40df-bf5f-fa8fea85a9f2
GetRawLogs
['"fmt"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetRawLogs() (string, error) { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return "", err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return "", err } podAllLogs, err := exutil.GetSpecificPodLogs(mcc.oc, MachineConfigNamespace, ControllerContainer, cachedPodName, "") if err != nil { logger.Errorf("Error getting log lines. Error: %s", err) return "", err } return podAllLogs, nil }
mco
function
openshift/openshift-tests-private
11b6db57-dbfa-40ba-8db0-78262b0aa955
HasAcquiredLease
['"strings"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) HasAcquiredLease() (bool, error) { podAllLogs, err := mcc.GetRawLogs() if err != nil { return false, err } return strings.Contains(podAllLogs, "successfully acquired lease"), nil }
mco
function
openshift/openshift-tests-private
a5ade772-04ee-46ce-aeae-75f008c23bc7
GetLogsAsList
['"strings"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetLogsAsList() ([]string, error) { logs, err := mcc.GetLogs() if err != nil { return nil, err } return strings.Split(logs, "\n"), nil }
mco
function
openshift/openshift-tests-private
686d3403-edae-4841-a2d4-d9f1f3fcd034
GetFilteredLogsAsList
['"regexp"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetFilteredLogsAsList(regex string) ([]string, error) { logs, err := mcc.GetLogsAsList() if err != nil { return nil, err } filteredLogs := []string{} for _, line := range logs { match, err := regexp.MatchString(regex, line) if err != nil { logger.Errorf("Error filtering log lines. Error: %s", err) return nil, err } if match { filteredLogs = append(filteredLogs, line) } } return filteredLogs, nil }
mco
function
openshift/openshift-tests-private
ead33ed9-c6a0-4c7a-8f8e-9e23679fcc5f
GetFilteredLogs
['"strings"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetFilteredLogs(regex string) (string, error) { logs, err := mcc.GetFilteredLogsAsList(regex) if err != nil { return "", err } return strings.Join(logs, "\n"), nil }
mco
function
openshift/openshift-tests-private
51c1ac78-1219-4fc7-9c3b-22b64d9f42c9
RemovePod
['"fmt"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) RemovePod() error { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return err } // remove the cached podname, since it will not be valid anymore mcc.podName = "" return mcc.oc.WithoutNamespace().Run("delete").Args("pod", "-n", MachineConfigNamespace, cachedPodName).Execute() }
mco
function
openshift/openshift-tests-private
a42ab867-02c6-4316-b6e4-ca460f5babef
GetNode
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetNode() (*Node, error) { controllerPodName, err := mcc.GetCachedPodName() if err != nil { return nil, err } controllerPod := NewNamespacedResource(mcc.oc, "pod", MachineConfigNamespace, controllerPodName) nodeName, err := controllerPod.Get(`{.spec.nodeName}`) if err != nil { return nil, err } return NewNode(mcc.oc, nodeName), nil }
mco
function
openshift/openshift-tests-private
def3eebf-1241-40c0-90f9-fc25a5bd98b9
GetPreviousLogs
['"fmt"', '"strings"']
['Controller']
github.com/openshift/openshift-tests-private/test/extended/mco/controller.go
func (mcc Controller) GetPreviousLogs() (string, error) { cachedPodName, err := mcc.GetCachedPodName() if err != nil { return "", err } if cachedPodName == "" { err := fmt.Errorf("Cannot get controller pod name. Failed getting MCO controller logs") logger.Errorf("Error getting controller pod name. Error: %s", err) return "", err } prevLogs, err := NewNamespacedResource(mcc.oc, "pod", MachineConfigNamespace, cachedPodName).Logs("-p") if err != nil { exitError, ok := err.(*exutil.ExitError) if ok { if strings.Contains(exitError.StdErr, "not found") { logger.Infof("There was no previous pod for %s", cachedPodName) return "", nil } logger.Infof("An execution error happened, but was not expected: %s", exitError.StdErr) } logger.Infof("Unexpected error while getting MCC previous logs: %s", err) return prevLogs, err } return prevLogs, nil }
mco
test
openshift/openshift-tests-private
5774f659-fd14-4263-8003-3ecb2d18aab7
generic_behaviour_validation
import ( "fmt" "time" o "github.com/onsi/gomega" "github.com/onsi/gomega/types" exutil "github.com/openshift/openshift-tests-private/test/extended/util" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" e2e "k8s.io/kubernetes/test/e2e/framework" )
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
package mco import ( "fmt" "time" o "github.com/onsi/gomega" "github.com/onsi/gomega/types" exutil "github.com/openshift/openshift-tests-private/test/extended/util" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" e2e "k8s.io/kubernetes/test/e2e/framework" ) type Checker interface { Check(checkedNodes ...Node) } type PreRebootMCDLogChecker struct { Matcher types.GomegaMatcher ErrorMsg string Desc string } // CheckLogs nodeLogs param is a map where the key is the name of the node and the value is the pre-reboot MCD logs func (preMCDLogChecker PreRebootMCDLogChecker) CheckLogs(nodeLogs map[string]string, checkedNodes ...Node) { msg := "Checking pre-reboot MCD logs" if preMCDLogChecker.Desc != "" { msg = preMCDLogChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logs, ok := nodeLogs[node.GetName()] o.Expect(ok).To(o.BeTrue(), "Something went wrong. There pre-reboot nodes found for node %s", node.GetName()) o.Expect(logs).Should(preMCDLogChecker.Matcher, preMCDLogChecker.ErrorMsg) } logger.Infof("OK!\n") } type PostRebootMCDLogChecker struct { Matcher types.GomegaMatcher ErrorMsg string Desc string } func (postMCDLogChecker PostRebootMCDLogChecker) Check(checkedNodes ...Node) { msg := "Checking MCD logs after reboot" if postMCDLogChecker.Desc != "" { msg = postMCDLogChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) o.Expect( exutil.GetSpecificPodLogs(node.oc, MachineConfigNamespace, MachineConfigDaemon, node.GetMachineConfigDaemon(), ""), ).Should(postMCDLogChecker.Matcher, postMCDLogChecker.ErrorMsg) } logger.Infof("OK!\n") } type CommandOutputChecker struct { Command []string Matcher types.GomegaMatcher ErrorMsg string Desc string } func (cOutChecker CommandOutputChecker) Check(checkedNodes ...Node) { msg := "Executing verification commands" if cOutChecker.Desc != "" { msg = cOutChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("In node %s. Executing command %s", node.GetName(), cOutChecker.Command) o.Expect( node.DebugNodeWithChroot(cOutChecker.Command...), ).To(cOutChecker.Matcher, "Command %s validation failed in node %s: %s", cOutChecker.Command, node.GetName(), cOutChecker.ErrorMsg) } logger.Infof("OK!\n") } type NodeEventsChecker struct { EventsSequence []string Desc string EventsAreNotTriggered bool } func (ec NodeEventsChecker) Check(nodes ...Node) { if !ec.EventsAreNotTriggered { ec.checkEventsAreTriggeredSequentially(nodes...) } else { ec.checkEventsAreNotTriggered(nodes...) } } func (ec NodeEventsChecker) checkEventsAreTriggeredSequentially(checkedNodes ...Node) { msg := fmt.Sprintf("Checking triggered events: %s", ec.EventsSequence) if ec.Desc != "" { msg = ec.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) o.Expect(node.GetEvents()).To(HaveEventsSequence(ec.EventsSequence...), "The expected events sequence did not happen in node %s. Expected: %s", node.GetName(), ec.EventsSequence) } logger.Infof("OK!\n") } func (ec NodeEventsChecker) checkEventsAreNotTriggered(checkedNodes ...Node) { msg := fmt.Sprintf("Checking that these events were NOT triggered: %s", ec.EventsSequence) if ec.Desc != "" { msg = ec.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) for _, eventReason := range ec.EventsSequence { o.Expect(node.GetEvents()).NotTo(HaveEventsSequence(eventReason), "The event %s should not be triggered in node %s, but it was trggered", node.GetName(), eventReason) } } logger.Infof("OK!\n") } type RemoteFileChecker struct { FileFullPath string Matcher types.GomegaMatcher ErrorMsg string Desc string } func (rfc RemoteFileChecker) Check(checkedNodes ...Node) { msg := fmt.Sprintf("Checking file: %s", rfc.FileFullPath) if rfc.Desc != "" { msg = rfc.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { rf := NewRemoteFile(node, rfc.FileFullPath) logger.Infof("Checking remote file %s", rf) o.Expect(rf).To(rfc.Matcher, "Validation of %s failed: %", rf, rfc.ErrorMsg) } logger.Infof("OK!\n") } type UpdateBehaviourValidator struct { mcp *MachineConfigPool controller *Controller checkedNodes []Node startTime time.Time PreRebootMCDLogsCheckers []PreRebootMCDLogChecker Checkers []Checker SkipRebootNodesValidation bool RebootNodesShouldBeSkipped bool SkipDrainNodesValidation bool DrainNodesShoulBeSkipped bool SkipRestartCrioValidation bool RestartCrioShouldBeSkipped bool SkipReloadCrioValidation bool ShouldReloadCrio bool } func (v *UpdateBehaviourValidator) Initialize(mcp *MachineConfigPool, nodes []Node) { exutil.By("Gathering initial data needed for the verification steps") v.mcp = mcp // If no node is provided we test only the first node to be updated in the pool if len(nodes) == 0 { v.checkedNodes = []Node{v.mcp.GetSortedNodesOrFail()[0]} } else { v.checkedNodes = nodes } logger.Infof("Start capturing events in nodes") for i := range v.checkedNodes { o.Expect(v.checkedNodes[i].IgnoreEventsBeforeNow()).NotTo(o.HaveOccurred(), "Error getting the latest event in node %s", v.checkedNodes[i].GetName()) } logger.Infof("Start recording controller logs") v.controller = NewController(mcp.oc.AsAdmin()) v.controller.IgnoreLogsBeforeNow() logger.Infof("Getting starting date") // TODO: maybe we should not assume that all nodes are synced var dErr error v.startTime, dErr = v.checkedNodes[0].GetDate() o.Expect(dErr).ShouldNot(o.HaveOccurred(), "Error getting date in node %s", v.checkedNodes[0].GetName()) logger.Infof("Node %s current date %s", v.checkedNodes[0], v.startTime) logger.Infof("OK!\n") } func (v *UpdateBehaviourValidator) Validate() { if len(v.PreRebootMCDLogsCheckers) > 0 && v.SkipRebootNodesValidation == false && v.RebootNodesShouldBeSkipped { e2e.Failf("Inconsistent behaviour! Nodes are expected to be rebooted because PreRebootMCDLogsCheckers were added, but at the same time RebootNodesShouldBeSkipped is true") } // Execute the verification of the pre-reboot MCD logs if len(v.PreRebootMCDLogsCheckers) > 0 { v.checkPreRebootMCDLogs() } exutil.By("Wait for configuration to be applied") v.mcp.waitForComplete() logger.Infof("OK!\n") // Execute the verification of the rebooted nodes (all nodes should have the same date, since they are synced) if !v.SkipRebootNodesValidation { v.checkRebootNodes() } // Execute the verification of the drain nodes behaviour if !v.SkipDrainNodesValidation { v.checkDrainNodes() } // Execute the verification of the crio service restart if !v.SkipRestartCrioValidation { v.checkCrioRestart() } // Execute the verification of the crio service reload if !v.SkipReloadCrioValidation { v.checkCrioReload() } // Execute the generic Checks for _, checker := range v.Checkers { checker.Check(v.checkedNodes...) } } // checkCrioReloaded checks if crio was reloaded or not. func (v *UpdateBehaviourValidator) checkCrioReload() { if v.ShouldReloadCrio { exutil.By("Checking that crio service was reloaded") } else { exutil.By("Checking that crio service was NOT reloaded") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the crio service was reloaded") for _, node := range v.checkedNodes { if v.ShouldReloadCrio { o.Expect(node.GetUnitExecReloadStartTime("crio.service")).To(o.BeTemporally(">", v.startTime), "Crio service was NOT reloaded, but it should be") } else { o.Expect(node.GetUnitExecReloadStartTime("crio.service")).To(o.BeTemporally("<", v.startTime), "Crio service was reloaded, but crio reload should have been skipped") } } logger.Infof("OK!\n") } // checkCrioRestart checks if crio was restarted or not. It can be restarted because the "systemctl restart crio" command is executed, or because the node was restarted (hence, restarting crio as well) func (v *UpdateBehaviourValidator) checkCrioRestart() { // Since we can check crio restart with reboot is skipped and when reboot is executed, we don't know actually were to // look for the log message (pre-reboot log or post-reboot log). So we can't check the crio log message if we dont have more information // It is better to actually get the crio.service status and the how much time it has passed since it was restarted if v.RestartCrioShouldBeSkipped { exutil.By("Checking that crio was NOT restarted") } else { exutil.By("Checking that crio was restarted") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the crio service was restarted") for _, node := range v.checkedNodes { if v.RestartCrioShouldBeSkipped { o.Expect(node.GetUnitActiveEnterTime("crio.service")).To(o.BeTemporally("<", v.startTime), "Crio service was restarted, but crio restart should have been skipped") } else { o.Expect(node.GetUnitActiveEnterTime("crio.service")).To(o.BeTemporally(">", v.startTime), "Crio service was NOT restarted, but it should be") } } logger.Infof("OK!\n") } func (v *UpdateBehaviourValidator) checkDrainNodes() { // We could check the "Drain" event in this function, but sometimes the events are not triggered and we don't know why // Until events are not more stable we should not force even validation in ALL our tests, only in those that we want to expose to this instability if v.DrainNodesShoulBeSkipped { exutil.By("Checking that nodes were NOT drained") } else { exutil.By("Checking that nodes were drained") } for _, node := range v.checkedNodes { checkDrainAction(!v.DrainNodesShoulBeSkipped, node, v.controller) } logger.Infof("OK!\n") } func (v *UpdateBehaviourValidator) checkRebootNodes() { // We could check the "Reboot" event in this function, but sometimes the events are not triggered and we don't know why // Until events are not more stable we should not force even validation in ALL our tests, only in those that we want to expose to this instability if v.RebootNodesShouldBeSkipped { exutil.By("Checking that nodes were NOT rebooted") } else { exutil.By("Checking that nodes were rebooted") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the nodes were rebooted") for _, node := range v.checkedNodes { checkRebootAction(!v.RebootNodesShouldBeSkipped, node, v.startTime) } logger.Infof("OK!\n") } func (v *UpdateBehaviourValidator) checkPreRebootMCDLogs() { logger.Infof("Capture pre-reboot MCD logs") preRebootLogs, err := v.mcp.CaptureAllNodeLogsBeforeRestart() o.Expect(err).NotTo(o.HaveOccurred(), "Error capturing get MCD logs before the nodes reboot") logger.Infof("OK!\n") for _, preRebootMCDLogsChecker := range v.PreRebootMCDLogsCheckers { preRebootMCDLogsChecker.CheckLogs(preRebootLogs, v.checkedNodes...) } } // checkDrainAction checks that the drain action in the node is the expected one (drainSkipped) func checkDrainAction(drainSkipped bool, node Node, controller *Controller) { checkDrainActionWithGomega(drainSkipped, node, controller, o.Default) } // checkDrainAction checks that the drain action in the node is the expected one (drainSkipped). It accepts and extra Gomega parameter that allows the function to be used in the Eventually gomega matchers func checkDrainActionWithGomega(drainExecuted bool, node Node, controller *Controller, gm o.Gomega) { var ( execDrainLogMsg = "initiating drain" ) // We use MCD logs to check if drain is skipped, and we use the Controller logs to check if drain is executed if drainExecuted { // When drain is executed reboot is usually executed too (since one of the reasons why MCO executes a drain operation is to be able to execute a safe reboot). // Hence, we cannot look for the "drain" message in the MCD logs because they have been removed in the reboot. // There are two options, we can look for the message in the pre-reboot MCD logs or we can look for them in the MCController pod // We decided to use the controller logs because it is way easier. logger.Infof("Checking that node %s was drained", node.GetName()) gm.Expect( controller.GetLogs(), ).Should(o.ContainSubstring("node "+node.GetName()+": "+execDrainLogMsg), "Error! The node %s was NOT drained, but it should be", node.GetName()) } else { logger.Infof("Checking that node %s was NOT drained", node.GetName()) gm.Expect( controller.GetLogs(), ).ShouldNot(o.ContainSubstring("node "+node.GetName()+": "+execDrainLogMsg), "Error! The node %s was drained, but the drain operation should have been skipped", node.GetName()) } } // checkRebootActionWithGomega checks that the reboot action in the node is the expected one (rebootSkipped) func checkRebootAction(rebootExecuted bool, node Node, startTime time.Time) { checkRebootActionWithGomega(rebootExecuted, node, startTime, o.Default) } // checkRebootActionWithGomega checks that the reboot action in the node is the expected one (rebootSkipped). It accepts and extra Gomega parameter that allows the function to be used in the Eventually gomega matchers func checkRebootActionWithGomega(rebootExecuted bool, node Node, startTime time.Time, gm o.Gomega) { if rebootExecuted { logger.Infof("Checking that node %s was rebooted", node.GetName()) gm.Expect(node.GetUptime()).Should(o.BeTemporally(">", startTime), "The node %s must be rebooted, but it was not. Uptime date happened before the start config time.", node.GetName()) } else { logger.Infof("Checking that node %s was NOT rebooted", node.GetName()) gm.Expect(node.GetUptime()).Should(o.BeTemporally("<", startTime), "The node %s must NOT be rebooted, but it was rebooted. Uptime date happened after the start config time.", node.GetName()) } }
package mco
function
openshift/openshift-tests-private
c9cd9e56-c0fb-421f-9c02-3c6289accb14
CheckLogs
['PreRebootMCDLogChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (preMCDLogChecker PreRebootMCDLogChecker) CheckLogs(nodeLogs map[string]string, checkedNodes ...Node) { msg := "Checking pre-reboot MCD logs" if preMCDLogChecker.Desc != "" { msg = preMCDLogChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logs, ok := nodeLogs[node.GetName()] o.Expect(ok).To(o.BeTrue(), "Something went wrong. There pre-reboot nodes found for node %s", node.GetName()) o.Expect(logs).Should(preMCDLogChecker.Matcher, preMCDLogChecker.ErrorMsg) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
5966d080-9c92-4122-ae73-62e1eaedf3ee
Check
['PostRebootMCDLogChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (postMCDLogChecker PostRebootMCDLogChecker) Check(checkedNodes ...Node) { msg := "Checking MCD logs after reboot" if postMCDLogChecker.Desc != "" { msg = postMCDLogChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) o.Expect( exutil.GetSpecificPodLogs(node.oc, MachineConfigNamespace, MachineConfigDaemon, node.GetMachineConfigDaemon(), ""), ).Should(postMCDLogChecker.Matcher, postMCDLogChecker.ErrorMsg) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
9f3e4744-d484-4322-b05d-055a83b3fc84
Check
['CommandOutputChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (cOutChecker CommandOutputChecker) Check(checkedNodes ...Node) { msg := "Executing verification commands" if cOutChecker.Desc != "" { msg = cOutChecker.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("In node %s. Executing command %s", node.GetName(), cOutChecker.Command) o.Expect( node.DebugNodeWithChroot(cOutChecker.Command...), ).To(cOutChecker.Matcher, "Command %s validation failed in node %s: %s", cOutChecker.Command, node.GetName(), cOutChecker.ErrorMsg) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
43194656-d185-41fb-907e-9c2f03a45185
Check
['NodeEventsChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (ec NodeEventsChecker) Check(nodes ...Node) { if !ec.EventsAreNotTriggered { ec.checkEventsAreTriggeredSequentially(nodes...) } else { ec.checkEventsAreNotTriggered(nodes...) } }
mco
function
openshift/openshift-tests-private
498e1269-e7d0-481d-bf98-92420b453882
checkEventsAreTriggeredSequentially
['"fmt"']
['NodeEventsChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (ec NodeEventsChecker) checkEventsAreTriggeredSequentially(checkedNodes ...Node) { msg := fmt.Sprintf("Checking triggered events: %s", ec.EventsSequence) if ec.Desc != "" { msg = ec.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) o.Expect(node.GetEvents()).To(HaveEventsSequence(ec.EventsSequence...), "The expected events sequence did not happen in node %s. Expected: %s", node.GetName(), ec.EventsSequence) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
46b6d4f9-8afd-4a17-ae81-cf57e9fc56e2
checkEventsAreNotTriggered
['"fmt"']
['NodeEventsChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (ec NodeEventsChecker) checkEventsAreNotTriggered(checkedNodes ...Node) { msg := fmt.Sprintf("Checking that these events were NOT triggered: %s", ec.EventsSequence) if ec.Desc != "" { msg = ec.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { logger.Infof("Checking node %s", node.GetName()) for _, eventReason := range ec.EventsSequence { o.Expect(node.GetEvents()).NotTo(HaveEventsSequence(eventReason), "The event %s should not be triggered in node %s, but it was trggered", node.GetName(), eventReason) } } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
ad525495-3a3c-49ec-a1f0-5f05d180b792
Check
['"fmt"']
['RemoteFileChecker']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (rfc RemoteFileChecker) Check(checkedNodes ...Node) { msg := fmt.Sprintf("Checking file: %s", rfc.FileFullPath) if rfc.Desc != "" { msg = rfc.Desc } exutil.By(msg) o.Expect(checkedNodes).NotTo(o.BeEmpty(), "Refuse to check an empty list of nodes") for _, node := range checkedNodes { rf := NewRemoteFile(node, rfc.FileFullPath) logger.Infof("Checking remote file %s", rf) o.Expect(rf).To(rfc.Matcher, "Validation of %s failed: %", rf, rfc.ErrorMsg) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
3218392b-57fa-4202-8b51-fd1bfd6b770a
Initialize
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) Initialize(mcp *MachineConfigPool, nodes []Node) { exutil.By("Gathering initial data needed for the verification steps") v.mcp = mcp // If no node is provided we test only the first node to be updated in the pool if len(nodes) == 0 { v.checkedNodes = []Node{v.mcp.GetSortedNodesOrFail()[0]} } else { v.checkedNodes = nodes } logger.Infof("Start capturing events in nodes") for i := range v.checkedNodes { o.Expect(v.checkedNodes[i].IgnoreEventsBeforeNow()).NotTo(o.HaveOccurred(), "Error getting the latest event in node %s", v.checkedNodes[i].GetName()) } logger.Infof("Start recording controller logs") v.controller = NewController(mcp.oc.AsAdmin()) v.controller.IgnoreLogsBeforeNow() logger.Infof("Getting starting date") // TODO: maybe we should not assume that all nodes are synced var dErr error v.startTime, dErr = v.checkedNodes[0].GetDate() o.Expect(dErr).ShouldNot(o.HaveOccurred(), "Error getting date in node %s", v.checkedNodes[0].GetName()) logger.Infof("Node %s current date %s", v.checkedNodes[0], v.startTime) logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
41cf80c4-b32a-4c50-866f-643b5ffa1818
Validate
['"time"']
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) Validate() { if len(v.PreRebootMCDLogsCheckers) > 0 && v.SkipRebootNodesValidation == false && v.RebootNodesShouldBeSkipped { e2e.Failf("Inconsistent behaviour! Nodes are expected to be rebooted because PreRebootMCDLogsCheckers were added, but at the same time RebootNodesShouldBeSkipped is true") } // Execute the verification of the pre-reboot MCD logs if len(v.PreRebootMCDLogsCheckers) > 0 { v.checkPreRebootMCDLogs() } exutil.By("Wait for configuration to be applied") v.mcp.waitForComplete() logger.Infof("OK!\n") // Execute the verification of the rebooted nodes (all nodes should have the same date, since they are synced) if !v.SkipRebootNodesValidation { v.checkRebootNodes() } // Execute the verification of the drain nodes behaviour if !v.SkipDrainNodesValidation { v.checkDrainNodes() } // Execute the verification of the crio service restart if !v.SkipRestartCrioValidation { v.checkCrioRestart() } // Execute the verification of the crio service reload if !v.SkipReloadCrioValidation { v.checkCrioReload() } // Execute the generic Checks for _, checker := range v.Checkers { checker.Check(v.checkedNodes...) } }
mco
function
openshift/openshift-tests-private
8626c69d-3bfb-4b60-bad7-31f76f21bee0
checkCrioReload
['"time"']
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) checkCrioReload() { if v.ShouldReloadCrio { exutil.By("Checking that crio service was reloaded") } else { exutil.By("Checking that crio service was NOT reloaded") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the crio service was reloaded") for _, node := range v.checkedNodes { if v.ShouldReloadCrio { o.Expect(node.GetUnitExecReloadStartTime("crio.service")).To(o.BeTemporally(">", v.startTime), "Crio service was NOT reloaded, but it should be") } else { o.Expect(node.GetUnitExecReloadStartTime("crio.service")).To(o.BeTemporally("<", v.startTime), "Crio service was reloaded, but crio reload should have been skipped") } } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
b9405fe6-14ad-4d57-95b9-bb297d843bcb
checkCrioRestart
['"time"']
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) checkCrioRestart() { // Since we can check crio restart with reboot is skipped and when reboot is executed, we don't know actually were to // look for the log message (pre-reboot log or post-reboot log). So we can't check the crio log message if we dont have more information // It is better to actually get the crio.service status and the how much time it has passed since it was restarted if v.RestartCrioShouldBeSkipped { exutil.By("Checking that crio was NOT restarted") } else { exutil.By("Checking that crio was restarted") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the crio service was restarted") for _, node := range v.checkedNodes { if v.RestartCrioShouldBeSkipped { o.Expect(node.GetUnitActiveEnterTime("crio.service")).To(o.BeTemporally("<", v.startTime), "Crio service was restarted, but crio restart should have been skipped") } else { o.Expect(node.GetUnitActiveEnterTime("crio.service")).To(o.BeTemporally(">", v.startTime), "Crio service was NOT restarted, but it should be") } } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
3b89f516-e8a5-4c68-b83e-2475f8e356e1
checkDrainNodes
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) checkDrainNodes() { // We could check the "Drain" event in this function, but sometimes the events are not triggered and we don't know why // Until events are not more stable we should not force even validation in ALL our tests, only in those that we want to expose to this instability if v.DrainNodesShoulBeSkipped { exutil.By("Checking that nodes were NOT drained") } else { exutil.By("Checking that nodes were drained") } for _, node := range v.checkedNodes { checkDrainAction(!v.DrainNodesShoulBeSkipped, node, v.controller) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
ea545c2f-e454-44a6-8742-e523b99cfd70
checkRebootNodes
['"time"']
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) checkRebootNodes() { // We could check the "Reboot" event in this function, but sometimes the events are not triggered and we don't know why // Until events are not more stable we should not force even validation in ALL our tests, only in those that we want to expose to this instability if v.RebootNodesShouldBeSkipped { exutil.By("Checking that nodes were NOT rebooted") } else { exutil.By("Checking that nodes were rebooted") } // If the startTime is empty it means that something went wrong in the automation // If at any moment we decide to allow an empty value here we can transform this assertion into a warning. o.Expect(v.startTime).NotTo(o.Equal(time.Time{}), "The provided comparison time was EMPTY while trying to guess if the nodes were rebooted") for _, node := range v.checkedNodes { checkRebootAction(!v.RebootNodesShouldBeSkipped, node, v.startTime) } logger.Infof("OK!\n") }
mco
function
openshift/openshift-tests-private
fc17f72d-c5a1-494c-997f-5c28dd02c0f5
checkPreRebootMCDLogs
['UpdateBehaviourValidator']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func (v *UpdateBehaviourValidator) checkPreRebootMCDLogs() { logger.Infof("Capture pre-reboot MCD logs") preRebootLogs, err := v.mcp.CaptureAllNodeLogsBeforeRestart() o.Expect(err).NotTo(o.HaveOccurred(), "Error capturing get MCD logs before the nodes reboot") logger.Infof("OK!\n") for _, preRebootMCDLogsChecker := range v.PreRebootMCDLogsCheckers { preRebootMCDLogsChecker.CheckLogs(preRebootLogs, v.checkedNodes...) } }
mco
function
openshift/openshift-tests-private
3e07aa20-6576-4029-874b-014ea3532799
checkDrainAction
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func checkDrainAction(drainSkipped bool, node Node, controller *Controller) { checkDrainActionWithGomega(drainSkipped, node, controller, o.Default) }
mco
function
openshift/openshift-tests-private
7f640f26-ebbb-4e8b-96fe-3849268fe5bc
checkDrainActionWithGomega
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func checkDrainActionWithGomega(drainExecuted bool, node Node, controller *Controller, gm o.Gomega) { var ( execDrainLogMsg = "initiating drain" ) // We use MCD logs to check if drain is skipped, and we use the Controller logs to check if drain is executed if drainExecuted { // When drain is executed reboot is usually executed too (since one of the reasons why MCO executes a drain operation is to be able to execute a safe reboot). // Hence, we cannot look for the "drain" message in the MCD logs because they have been removed in the reboot. // There are two options, we can look for the message in the pre-reboot MCD logs or we can look for them in the MCController pod // We decided to use the controller logs because it is way easier. logger.Infof("Checking that node %s was drained", node.GetName()) gm.Expect( controller.GetLogs(), ).Should(o.ContainSubstring("node "+node.GetName()+": "+execDrainLogMsg), "Error! The node %s was NOT drained, but it should be", node.GetName()) } else { logger.Infof("Checking that node %s was NOT drained", node.GetName()) gm.Expect( controller.GetLogs(), ).ShouldNot(o.ContainSubstring("node "+node.GetName()+": "+execDrainLogMsg), "Error! The node %s was drained, but the drain operation should have been skipped", node.GetName()) } }
mco
function
openshift/openshift-tests-private
a40e8bb5-bb55-4cc3-a3b5-1a463e57c129
checkRebootAction
['"time"']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func checkRebootAction(rebootExecuted bool, node Node, startTime time.Time) { checkRebootActionWithGomega(rebootExecuted, node, startTime, o.Default) }
mco
function
openshift/openshift-tests-private
a65da50d-924a-4cf1-940f-7dd11302a8a4
checkRebootActionWithGomega
['"time"']
github.com/openshift/openshift-tests-private/test/extended/mco/generic_behaviour_validation.go
func checkRebootActionWithGomega(rebootExecuted bool, node Node, startTime time.Time, gm o.Gomega) { if rebootExecuted { logger.Infof("Checking that node %s was rebooted", node.GetName()) gm.Expect(node.GetUptime()).Should(o.BeTemporally(">", startTime), "The node %s must be rebooted, but it was not. Uptime date happened before the start config time.", node.GetName()) } else { logger.Infof("Checking that node %s was NOT rebooted", node.GetName()) gm.Expect(node.GetUptime()).Should(o.BeTemporally("<", startTime), "The node %s must NOT be rebooted, but it was rebooted. Uptime date happened after the start config time.", node.GetName()) } }
mco
file
openshift/openshift-tests-private
46b5dcce-981d-493b-a97e-b2c498fe7346
machineset
import ( "context" "fmt" "strconv" "strings" "time" o "github.com/onsi/gomega" exutil "github.com/openshift/openshift-tests-private/test/extended/util" "github.com/openshift/openshift-tests-private/test/extended/util/architecture" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "k8s.io/apimachinery/pkg/util/wait" e2e "k8s.io/kubernetes/test/e2e/framework" )
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
package mco import ( "context" "fmt" "strconv" "strings" "time" o "github.com/onsi/gomega" exutil "github.com/openshift/openshift-tests-private/test/extended/util" "github.com/openshift/openshift-tests-private/test/extended/util/architecture" logger "github.com/openshift/openshift-tests-private/test/extended/util/logext" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "k8s.io/apimachinery/pkg/util/wait" e2e "k8s.io/kubernetes/test/e2e/framework" ) const ( // MachineAPINamespace is the namespace where openshift machinesets are created MachineAPINamespace = "openshift-machine-api" ) // MachineSet struct to handle MachineSet resources type MachineSet struct { Resource } // MachineSetList struct to handle lists of MachineSet resources type MachineSetList struct { ResourceList } // NewMachineSet constructs a new MachineSet struct func NewMachineSet(oc *exutil.CLI, namespace, name string) *MachineSet { return &MachineSet{*NewNamespacedResource(oc, MachineSetFullName, namespace, name)} } // NewMachineSetList constructs a new MachineSetListist struct to handle all existing MachineSets func NewMachineSetList(oc *exutil.CLI, namespace string) *MachineSetList { return &MachineSetList{*NewNamespacedResourceList(oc, MachineSetFullName, namespace)} } // String implements the Stringer interface func (ms MachineSet) String() string { return ms.GetName() } // ScaleTo scales the MachineSet to the exact given value func (ms MachineSet) ScaleTo(scale int) error { return ms.Patch("merge", fmt.Sprintf(`{"spec": {"replicas": %d}}`, scale)) } // GetReplicaOfSpec return replica number of spec func (ms MachineSet) GetReplicaOfSpec() string { return ms.GetOrFail(`{.spec.replicas}`) } // AddToScale scales the MachineSet adding the given value (positive or negative). func (ms MachineSet) AddToScale(delta int) error { currentReplicas, err := strconv.Atoi(ms.GetOrFail(`{.spec.replicas}`)) if err != nil { return err } return ms.ScaleTo(currentReplicas + delta) } // GetIsReady returns true the MachineSet instances are ready func (ms MachineSet) GetIsReady() bool { configuredReplicasString, err := ms.Get(`{.spec.replicas}`) if err != nil { logger.Infof("Cannot get configured replicas. Err: %s", err) return false } configuredReplicas, err := strconv.Atoi(configuredReplicasString) if err != nil { logger.Infof("Could not parse configured replicas. Error: %s", err) return false } statusString, err := ms.Get(`{.status}`) if err != nil { logger.Infof("Cannot get status. Err: %s", err) return false } status := JSON(statusString) logger.Infof("status %s", status) replicasData, err := status.GetSafe("replicas") if err != nil { logger.Infof("Cannot get the replicas in the status. Err: %s", err) return false } readyReplicasData, err := status.GetSafe("readyReplicas") if err != nil { logger.Infof("Cannot get the readyReplicas in the status. Err: %s", err) return false } if !replicasData.Exists() { logger.Infof("Replicasdata does not exist") return false } replicas := replicasData.ToInt() if replicas == 0 { if replicas == configuredReplicas { // We cant check the ready status when there is 0 replica configured. // So if status.replicas == spec.replicas == 0 then we consider that it is ok logger.Infof("Zero replicas") return true } logger.Infof("Zero replicas. Status not updated already.") return false } if !readyReplicasData.Exists() { logger.Infof("ReadyReplicasdata does not exist") return false } readyReplicas := readyReplicasData.ToInt() logger.Infof("Replicas %d, readyReplicas %d", replicas, readyReplicas) replicasAreReady := replicas == readyReplicas replicasAreConfigured := replicas == configuredReplicas return replicasAreReady && replicasAreConfigured } // GetMachines returns a slice with the machines created for this MachineSet func (ms MachineSet) GetMachines() ([]Machine, error) { ml := NewMachineList(ms.oc, ms.GetNamespace()) ml.ByLabel("machine.openshift.io/cluster-api-machineset=" + ms.GetName()) ml.SortByTimestamp() return ml.GetAll() } // GetMachinesOrFail get machines from machineset or fail the test if any error occurred func (ms MachineSet) GetMachinesOrFail() []Machine { ml, err := ms.GetMachines() o.Expect(err).NotTo(o.HaveOccurred(), "Get machines of machineset %s failed", ms.GetName()) return ml } // GetMachinesByPhase get machine by phase e.g. Running, Provisioning, Provisioned, Deleting etc. func (ms MachineSet) GetMachinesByPhase(phase string) ([]Machine, error) { // add poller to check machine phase periodically. machines := []Machine{} pollerr := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, 20*time.Second, true, func(_ context.Context) (bool, error) { ml, err := ms.GetMachines() if err != nil { return false, err } for _, m := range ml { if m.GetPhase() == phase { machines = append(machines, m) } } return len(machines) > 0, nil }) return machines, pollerr } // GetMachinesByPhaseOrFail call GetMachineByPhase or fail the test if any error occurred func (ms MachineSet) GetMachinesByPhaseOrFail(phase string) []Machine { ml, err := ms.GetMachinesByPhase(phase) o.Expect(err).NotTo(o.HaveOccurred(), "Get machine by phase %s failed", phase) o.Expect(ml).ShouldNot(o.BeEmpty(), "No machine found by phase %s in machineset %s", phase, ms.GetName()) return ml } // GetNodes returns a slice with all nodes that have been created for this MachineSet func (ms MachineSet) GetNodes() ([]*Node, error) { machines, mErr := ms.GetMachines() if mErr != nil { return nil, mErr } nodes := []*Node{} for _, m := range machines { n, nErr := m.GetNode() if nErr != nil { return nil, nErr } nodes = append(nodes, n) } return nodes, nil } // GetNodesOrFail returns a slice with all nodes that have been created for this MachineSet and fails the test if any error happens func (ms MachineSet) GetNodesOrFail() []*Node { nodes, err := ms.GetNodes() o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred(), "Error getting the nodes that belong to %s", ms) return nodes } // WaitUntilReady waits until the MachineSet reports a Ready status func (ms MachineSet) WaitUntilReady(duration string) error { pDuration, err := time.ParseDuration(duration) if err != nil { logger.Errorf("Error parsing duration %s. Errot: %s", duration, err) return err } immediate := false pollerr := wait.PollUntilContextTimeout(context.TODO(), 20*time.Second, pDuration, immediate, func(_ context.Context) (bool, error) { return ms.GetIsReady(), nil }) return pollerr } // Duplicate creates a new MachineSet by ducplicating the MachineSet information but using a new name, the new duplicated Machineset has 0 replicas // If you need to further modify the new machineset, patch it, and scale it up // For example, to duplicate a machineset and use a new secret in the duplicated machineset: // newMs := ms.Duplicate("newname") // err = newMs.Patch("json", `[{ "op": "replace", "path": "/spec/template/spec/providerSpec/value/userDataSecret/name", "value": "newSecretName" }]`) // newMs.ScaleTo(1) func (ms MachineSet) Duplicate(newName string) (*MachineSet, error) { res, err := CloneResource(&ms, newName, ms.GetNamespace(), // Extra modifications to // 1. Create the resource with 0 replicas // 2. modify the selector matchLabels // 3. modify the selector template metadata labels func(resString string) (string, error) { newResString, err := sjson.Set(resString, "spec.replicas", 0) if err != nil { return "", err } newResString, err = sjson.Set(newResString, `spec.selector.matchLabels.machine\.openshift\.io/cluster-api-machineset`, newName) if err != nil { return "", err } newResString, err = sjson.Set(newResString, `spec.template.metadata.labels.machine\.openshift\.io/cluster-api-machineset`, newName) if err != nil { return "", err } return newResString, nil }, ) if err != nil { return nil, err } logger.Infof("A new machineset %s has been created by cloning %s", res.GetName(), ms.GetName()) return NewMachineSet(ms.oc, res.GetNamespace(), res.GetName()), nil } // SetCoreOsBootImage sets the value of the configured coreos boot image func (ms MachineSet) SetCoreOsBootImage(coreosBootImage string) error { // the coreOs boot image is stored differently in the machineset spec depending on the platform // currently we only support testing the coresOs boot image in GCP platform. patchCoreOsBootImagePath := GetCoreOSBootImagePath(exutil.CheckPlatform(ms.oc)) return ms.Patch("json", fmt.Sprintf(`[{"op": "add", "path": "%s", "value": "%s"}]`, patchCoreOsBootImagePath, coreosBootImage)) } // GetArchitecture returns the architecture configured for this Machineset func (ms MachineSet) GetArchitecture() (*architecture.Architecture, error) { labeledArch, err := ms.Get(`{.metadata.annotations.capacity\.cluster-autoscaler\.kubernetes\.io/labels}`) if err != nil { return nil, err } expectedFormat := "kubernetes.io/arch=" if !strings.Contains(labeledArch, "kubernetes.io/arch=") { return nil, fmt.Errorf("The annotated architecture is not in the expected format. Annotation: %s. Expected format: %s${ARCH}", labeledArch, expectedFormat) } return PtrTo(architecture.FromString(strings.Split(labeledArch, "kubernetes.io/arch=")[1])), nil } func (ms MachineSet) GetArchitectureOrFail() *architecture.Architecture { arch, err := ms.GetArchitecture() o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred(), "Error getting the annotated architecture in %s", ms) return arch } func (ms MachineSet) SetArchitecture(arch string) error { return ms.Patch("json", fmt.Sprintf(`[{"op": "add", "path": "/metadata/annotations/capacity.cluster-autoscaler.kubernetes.io~1labels", "value": "kubernetes.io/arch=%s"}]`, arch)) } // GetUserDataSecret returns the secret used for user-data func (ms MachineSet) GetUserDataSecret() (string, error) { return ms.Get(`{.spec.template.spec.providerSpec.value.userDataSecret.name}`) } // GetCoreOsBootImage returns the configured coreOsBootImage in this machineset func (ms MachineSet) GetCoreOsBootImage() (string, error) { // the coreOs boot image is stored differently in the machineset spec depending on the platform // currently we only support testing the coresOs boot image in GCP platform. coreOsBootImagePath := "" switch p := exutil.CheckPlatform(ms.oc); p { case "aws": coreOsBootImagePath = `{.spec.template.spec.providerSpec.value.ami.id}` case "gcp": coreOsBootImagePath = `{.spec.template.spec.providerSpec.value.disks[0].image}` default: e2e.Failf("Machineset.GetCoreOsBootImage method is only supported for GCP and AWS infrastructure") } return ms.Get(coreOsBootImagePath) } // GetCoreOsBootImage returns the configured coreOsBootImage in this machineset and fails the test case if any error happened func (ms MachineSet) GetCoreOsBootImageOrFail() string { img, err := ms.GetCoreOsBootImage() o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred(), "Error getting the coreos boot image value in %s", ms) return img } // GetAll returns a []MachineSet list with all existing machinesets func (msl *MachineSetList) GetAll() ([]MachineSet, error) { allMSResources, err := msl.ResourceList.GetAll() if err != nil { return nil, err } allMS := make([]MachineSet, 0, len(allMSResources)) for _, msRes := range allMSResources { allMS = append(allMS, *NewMachineSet(msl.oc, msRes.GetNamespace(), msRes.GetName())) } return allMS, nil } // GetAllOrFail returns a []Machineset list with all existing machinesets and fail the test if it is not possible func (msl *MachineSetList) GetAllOrFail() []MachineSet { allMs, err := msl.GetAll() o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred(), "Error getting the list of existing MachineSets") return allMs } // duplicateMachinesetSecret duplicates a userData secret and prepares the new duplicated secret to use the given ignition version func duplicateMachinesetSecret(oc *exutil.CLI, secretName, newName, newIgnitionVersion string) (*Secret, error) { var ( currentSecret = NewSecret(oc, MachineAPINamespace, secretName) err error ) userData, udErr := currentSecret.GetDataValue("userData") if udErr != nil { logger.Errorf("Error getting userData info from secret %s -n %s.\n%s", secretName, MachineAPINamespace, udErr) return nil, udErr } disableTemplating, dtErr := currentSecret.GetDataValue("disableTemplating") if dtErr != nil { logger.Errorf("Error getting disableTemplating info from secret %s -n %s.\n%s", secretName, MachineAPINamespace, dtErr) return nil, dtErr } currentIgnitionVersionResult := gjson.Get(userData, "ignition.version") if !currentIgnitionVersionResult.Exists() || currentIgnitionVersionResult.String() == "" { logger.Debugf("Could not get ignition version from ignition userData: %s", userData) return nil, fmt.Errorf("Could not get ignition version from ignition userData. Enable debug GINKGO_TEST_ENABLE_DEBUG_LOG to get more info") } currentIgnitionVersion := currentIgnitionVersionResult.String() if CompareVersions(currentIgnitionVersion, "==", newIgnitionVersion) { logger.Infof("Current ignition version %s is the same as the new ignition version %s. No need to manipulate the userData info", currentIgnitionVersion, newIgnitionVersion) } else { if CompareVersions(newIgnitionVersion, "<", "3.0.0") { logger.Infof("New ignition version is %s, we need to adapt the userData ignition config to 2.0 config", newIgnitionVersion) logger.Infof("Replace the 'merge' action with the 'append' action") merge := gjson.Get(userData, "ignition.config.merge") if !merge.Exists() { logger.Debugf("Could not find the 'merge' information in the userData ignition config: %s", userData) return nil, fmt.Errorf("Could not find the 'merge' information in the userData ignition config. Enable debug GINKGO_TEST_ENABLE_DEBUG_LOG to get more info") } userData, err = sjson.SetRaw(userData, "ignition.config.append", merge.String()) if err != nil { return nil, err } userData, err = sjson.Delete(userData, "ignition.config.merge") if err != nil { return nil, err } } logger.Infof("Replace ignition version '%s' with version '%s'", currentIgnitionVersion, newIgnitionVersion) userData, err = sjson.Set(userData, "ignition.version", newIgnitionVersion) if err != nil { return nil, err } } logger.Debugf("New userData info:\n%s", userData) _, err = oc.AsAdmin().WithoutNamespace().Run("create").Args("secret", "generic", newName, "-n", MachineAPINamespace, "--from-literal", fmt.Sprintf("userData=%s", userData), "--from-literal", fmt.Sprintf("disableTemplating=%s", disableTemplating)).Output() return NewSecret(oc.AsAdmin(), MachineAPINamespace, newName), err } // getUserDataIgnitionVersionFromOCPVersion returns that right ignition version for a given base image version func getUserDataIgnitionVersionFromOCPVersion(baseImageVersion string) string { /* UserData ignition version is defined in https://github.com/openshift/installer/blob/release-4.16/pkg/asset/ignition/machine/node.go#L52 4.16: 3.2.0 4.15: 3.2.0 4.14: 3.2.0 4.13: 3.2.0 // change to rhel9 4.12: 3.2.0 4.11: 3.2.0 // support for arm64 added 4.10: 3.1.0 4.9: 3.1.0 4.8: 3.1.0 4.7: 3.1.0 4.6: 3.1.0 4.5: 2.2.0 4.4: 2.2.0 4.3: 2.2.0 // support for fips 4.2: 2.2.0 4.1: 2.2.0 */ if CompareVersions(baseImageVersion, "<", "4.6") { return "2.2.0" } if CompareVersions(baseImageVersion, "<", "4.10") { return "3.1.0" } return "3.2.0" } func GetCoreOSBootImagePath(platform string) string { patchCoreOsBootImagePath := "" switch platform { case AWSPlatform: patchCoreOsBootImagePath = "/spec/template/spec/providerSpec/value/ami/id" case GCPPlatform: patchCoreOsBootImagePath = "/spec/template/spec/providerSpec/value/disks/0/image" case VspherePlatform: patchCoreOsBootImagePath = "/spec/template/spec/providerSpec/value/template" default: e2e.Failf("Machineset.GetCoreOsBootImage method is only supported for GCP and AWS platforms") } return patchCoreOsBootImagePath } func GetArchitectureFromMachineset(ms *MachineSet, platform string) (architecture.Architecture, error) { logger.Infof("Getting architecture for machineset %s", ms.GetName()) arch, err := ms.GetArchitecture() if err == nil { return *arch, nil } // In vsphere the machinesets are not annotated, so wee need to get the architecture from the Nodes if they exist if platform != VspherePlatform { return architecture.UNKNOWN, err } logger.Infof("In vsphere we need to get the architecture from the existing nodes created by the machineset %s", ms.GetName()) nodes, err := ms.GetNodes() if err != nil { return architecture.UNKNOWN, err } if len(nodes) == 0 { return architecture.UNKNOWN, fmt.Errorf("Machineset %s has no replicas, so we cannot get the architecture from any existing node", ms.GetName()) } narch, err := nodes[0].GetArchitecture() if err != nil { return architecture.UNKNOWN, err } return narch, nil }
package mco
function
openshift/openshift-tests-private
94638282-9de6-4783-ae28-e1558dfd36cb
NewMachineSet
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func NewMachineSet(oc *exutil.CLI, namespace, name string) *MachineSet { return &MachineSet{*NewNamespacedResource(oc, MachineSetFullName, namespace, name)} }
mco
function
openshift/openshift-tests-private
2fac4bad-e36f-4695-88e5-a470fb7369a6
NewMachineSetList
['MachineSetList']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func NewMachineSetList(oc *exutil.CLI, namespace string) *MachineSetList { return &MachineSetList{*NewNamespacedResourceList(oc, MachineSetFullName, namespace)} }
mco
function
openshift/openshift-tests-private
c419771c-bb6a-4881-921f-ba089be18555
String
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) String() string { return ms.GetName() }
mco
function
openshift/openshift-tests-private
aa0b7fba-1b52-4385-9a37-112484388234
ScaleTo
['"fmt"']
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) ScaleTo(scale int) error { return ms.Patch("merge", fmt.Sprintf(`{"spec": {"replicas": %d}}`, scale)) }
mco
function
openshift/openshift-tests-private
5fbf1535-7b8f-4490-afcf-e0fd90cf2d85
GetReplicaOfSpec
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) GetReplicaOfSpec() string { return ms.GetOrFail(`{.spec.replicas}`) }
mco
function
openshift/openshift-tests-private
c484e30f-a5c4-42ab-975c-869c97fefe84
AddToScale
['"strconv"']
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) AddToScale(delta int) error { currentReplicas, err := strconv.Atoi(ms.GetOrFail(`{.spec.replicas}`)) if err != nil { return err } return ms.ScaleTo(currentReplicas + delta) }
mco
function
openshift/openshift-tests-private
7db7cb35-b946-4730-96ca-a922e3e298d8
GetIsReady
['"strconv"']
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) GetIsReady() bool { configuredReplicasString, err := ms.Get(`{.spec.replicas}`) if err != nil { logger.Infof("Cannot get configured replicas. Err: %s", err) return false } configuredReplicas, err := strconv.Atoi(configuredReplicasString) if err != nil { logger.Infof("Could not parse configured replicas. Error: %s", err) return false } statusString, err := ms.Get(`{.status}`) if err != nil { logger.Infof("Cannot get status. Err: %s", err) return false } status := JSON(statusString) logger.Infof("status %s", status) replicasData, err := status.GetSafe("replicas") if err != nil { logger.Infof("Cannot get the replicas in the status. Err: %s", err) return false } readyReplicasData, err := status.GetSafe("readyReplicas") if err != nil { logger.Infof("Cannot get the readyReplicas in the status. Err: %s", err) return false } if !replicasData.Exists() { logger.Infof("Replicasdata does not exist") return false } replicas := replicasData.ToInt() if replicas == 0 { if replicas == configuredReplicas { // We cant check the ready status when there is 0 replica configured. // So if status.replicas == spec.replicas == 0 then we consider that it is ok logger.Infof("Zero replicas") return true } logger.Infof("Zero replicas. Status not updated already.") return false } if !readyReplicasData.Exists() { logger.Infof("ReadyReplicasdata does not exist") return false } readyReplicas := readyReplicasData.ToInt() logger.Infof("Replicas %d, readyReplicas %d", replicas, readyReplicas) replicasAreReady := replicas == readyReplicas replicasAreConfigured := replicas == configuredReplicas return replicasAreReady && replicasAreConfigured }
mco
function
openshift/openshift-tests-private
898e0174-eb92-46ee-b30c-b1014914c22d
GetMachines
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) GetMachines() ([]Machine, error) { ml := NewMachineList(ms.oc, ms.GetNamespace()) ml.ByLabel("machine.openshift.io/cluster-api-machineset=" + ms.GetName()) ml.SortByTimestamp() return ml.GetAll() }
mco
function
openshift/openshift-tests-private
efd5ecf4-ff65-4caf-978b-bafa7ffa8f43
GetMachinesOrFail
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) GetMachinesOrFail() []Machine { ml, err := ms.GetMachines() o.Expect(err).NotTo(o.HaveOccurred(), "Get machines of machineset %s failed", ms.GetName()) return ml }
mco
function
openshift/openshift-tests-private
6ac03fbd-9512-4260-aa86-ce26cbb55587
GetMachinesByPhase
['"context"', '"time"', '"k8s.io/apimachinery/pkg/util/wait"']
['MachineSet']
github.com/openshift/openshift-tests-private/test/extended/mco/machineset.go
func (ms MachineSet) GetMachinesByPhase(phase string) ([]Machine, error) { // add poller to check machine phase periodically. machines := []Machine{} pollerr := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, 20*time.Second, true, func(_ context.Context) (bool, error) { ml, err := ms.GetMachines() if err != nil { return false, err } for _, m := range ml { if m.GetPhase() == phase { machines = append(machines, m) } } return len(machines) > 0, nil }) return machines, pollerr }
mco