diff --git a/cmd/help.go b/cmd/help.go deleted file mode 100644 index 69940fa..0000000 --- a/cmd/help.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright The Microcks Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package cmd - -import "fmt" - -type helpCommand struct { -} - -// NewHelpCommand build a new HelpCommand implementation -func NewHelpCommand() Command { - return new(helpCommand) -} - -// Execute implementation on helpCommand structure -func (c *helpCommand) Execute() { - fmt.Println("") - fmt.Println("microcks-cli is a CLI for interacting with Microcks server APIs.") - fmt.Println("It allows to launch tests or import API artifacts with minimal dependencies") - fmt.Println("") - fmt.Println("") - fmt.Println("Usage:") - fmt.Println(" microcks-cli [command]") - fmt.Println("") - fmt.Println("Available Commands:") - fmt.Println(" version check this CLI version") - fmt.Println(" help display this help message") - fmt.Println(" test launch new test on Microcks server") - fmt.Println(" import import API artifacts on Microcks server") - fmt.Println("") - fmt.Println("Use: microcks-cli test \\") - fmt.Println(" --microcksURL=<> --waitFor=5sec \\") - fmt.Println(" --keycloakClientId=<> --keycloakClientSecret=<>") - fmt.Println("") - fmt.Println("Args: ") - fmt.Println(" Exemple: 'Beer Catalog API:0.9'") - fmt.Println(" URL where is deployed implementation to test") - fmt.Println(" Test strategy (one of: HTTP, SOAP, SOAP_UI, POSTMAN, OPEN_API_SCHEMA, ASYNC_API_SCHEMA, GRPC_PROTOBUF, GRAPHQL_SCHEMA)") - fmt.Println("") - fmt.Println("Flags: ") - fmt.Println(" --microcksURL Microcks API endpoint") - fmt.Println(" --waitFor Time to wait for test to finish (int + one of: milli, sec, min)") - fmt.Println(" --keycloakClientId Keycloak Realm Service Account ClientId") - fmt.Println(" --keycloakClientSecret Keycloak Realm Service Account ClientSecret") - fmt.Println("") - fmt.Println("") - fmt.Println("Use: microcks-cli import \\") - fmt.Println(" --microcksURL=<> \\") - fmt.Println(" --keycloakClientId=<> --keycloakClientSecret=<>") - fmt.Println("") - fmt.Println("Args: ") - fmt.Println(" Exemple: 'specs/my-openapi.yaml:true,specs/my-postmancollection.json:false'") - fmt.Println("") - fmt.Println("Flags: ") - fmt.Println(" --microcksURL Microcks API endpoint") - fmt.Println(" --keycloakClientId Keycloak Realm Service Account ClientId") - fmt.Println(" --keycloakClientSecret Keycloak Realm Service Account ClientSecret") - fmt.Println("") -} diff --git a/cmd/import.go b/cmd/import.go deleted file mode 100644 index 9d6041c..0000000 --- a/cmd/import.go +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright The Microcks Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package cmd - -import ( - "flag" - "fmt" - "os" - "strconv" - "strings" - - "github.com/microcks/microcks-cli/pkg/config" - "github.com/microcks/microcks-cli/pkg/connectors" -) - -type importComamnd struct { -} - -// NewImportCommand build a new ImportCommand implementation -func NewImportCommand() Command { - return new(importComamnd) -} - -// Execute implementation of importComamnd structure -func (c *importComamnd) Execute() { - - // Parse subcommand args first. - if len(os.Args) < 2 { - fmt.Println("import command require args") - os.Exit(1) - } - - specificationFiles := os.Args[2] - - // Then parse flags. - importCmd := flag.NewFlagSet("import", flag.ExitOnError) - - var microcksURL string - var keycloakURL string - var keycloakClientID string - var keycloakClientSecret string - var insecureTLS bool - var caCertPaths string - var verbose bool - - importCmd.StringVar(µcksURL, "microcksURL", "", "Microcks API URL") - importCmd.StringVar(&keycloakClientID, "keycloakClientId", "", "Keycloak Realm Service Account ClientId") - importCmd.StringVar(&keycloakClientSecret, "keycloakClientSecret", "", "Keycloak Realm Service Account ClientSecret") - importCmd.BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection") - importCmd.StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs") - importCmd.BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges") - importCmd.Parse(os.Args[3:]) - - // Validate presence and values of flags. - if len(microcksURL) == 0 { - fmt.Println("--microcksURL flag is mandatory. Check Usage.") - os.Exit(1) - } - if len(keycloakClientID) == 0 { - fmt.Println("--keycloakClientId flag is mandatory. Check Usage.") - os.Exit(1) - } - if len(keycloakClientSecret) == 0 { - fmt.Println("--keycloakClientSecret flag is mandatory. Check Usage.") - os.Exit(1) - } - - // Collect optional HTTPS transport flags. - if insecureTLS { - config.InsecureTLS = true - } - if len(caCertPaths) > 0 { - config.CaCertPaths = caCertPaths - } - if verbose { - config.Verbose = true - } - - // Now we seems to be good ... - // First - retrieve the Keycloak URL from Microcks configuration. - mc := connectors.NewMicrocksClient(microcksURL) - keycloakURL, err := mc.GetKeycloakURL() - if err != nil { - fmt.Printf("Got error when invoking Microcks client retrieving config: %s", err) - os.Exit(1) - } - - var oauthToken string = "unauthentifed-token" - if keycloakURL != "null" { - // If Keycloak is enabled, retrieve an OAuth token using Keycloak Client. - kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret) - - oauthToken, err = kc.ConnectAndGetToken() - if err != nil { - fmt.Printf("Got error when invoking Keycloack client: %s", err) - os.Exit(1) - } - } - - // Then - for each specificationFile, upload the artifact on Microcks Server. - mc.SetOAuthToken(oauthToken) - - sepSpecificationFiles := strings.Split(specificationFiles, ",") - for _, f := range sepSpecificationFiles { - mainArtifact := true - - // Check if mainArtifact flag is provided. - if strings.Contains(f, ":") { - pathAndMainArtifact := strings.Split(f, ":") - f = pathAndMainArtifact[0] - mainArtifact, err = strconv.ParseBool(pathAndMainArtifact[1]) - if err != nil { - fmt.Printf("Cannot parse '%s' as Bool, default to true\n", pathAndMainArtifact[1]) - } - } - - // Try uploading this artifact. - msg, err := mc.UploadArtifact(f, mainArtifact) - if err != nil { - fmt.Printf("Got error when invoking Microcks client importing Artifact: %s", err) - os.Exit(1) - } - fmt.Printf("Microcks has discovered '%s'\n", msg) - } -} diff --git a/version/version.go b/cmd/microcks/internal/version/version.go similarity index 100% rename from version/version.go rename to cmd/microcks/internal/version/version.go diff --git a/cmd/cmd.go b/cmd/microcks/main.go similarity index 78% rename from cmd/cmd.go rename to cmd/microcks/main.go index 6929af1..e6045a1 100644 --- a/cmd/cmd.go +++ b/cmd/microcks/main.go @@ -13,9 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cmd +package main -// Command define single method interface -type Command interface { - Execute() -} +import ( + "os" + + "github.com/microcks/microcks-cli/cmd/microcks/root" +) + +func main() { + err := root.RootCmd().Execute() + if err != nil { + os.Exit(1) + } +} \ No newline at end of file diff --git a/cmd/version.go b/cmd/microcks/root/cmd.go similarity index 62% rename from cmd/version.go rename to cmd/microcks/root/cmd.go index 3a98514..7f0eb7f 100644 --- a/cmd/version.go +++ b/cmd/microcks/root/cmd.go @@ -13,23 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package cmd +package root -import ( - "fmt" +import "github.com/spf13/cobra" - "github.com/microcks/microcks-cli/version" -) -type versionCommand struct { -} +func RootCmd() *cobra.Command { + root := &cobra.Command{ + Use: "microcks", + Short: "Microcks CLI", + Long: `Microcks CLI is a command line interface for Microcks.`, + Example: ` + # Start the Microcks CLI + microcks`, + } -// NewVersionCommand build a new VersionCommand implementation -func NewVersionCommand() Command { - return new(versionCommand) -} + root.AddCommand( + importCmd, + testCmd, + ) + -// Execute implementation on versionCommand structure -func (c *versionCommand) Execute() { - fmt.Println(version.Version) -} + return root + +} \ No newline at end of file diff --git a/cmd/microcks/root/import.go b/cmd/microcks/root/import.go new file mode 100644 index 0000000..d124f8e --- /dev/null +++ b/cmd/microcks/root/import.go @@ -0,0 +1,99 @@ +/* + * Copyright The Microcks Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package root + +import ( + "fmt" + "os" + "strconv" + "strings" + + "github.com/microcks/microcks-cli/pkg/connectors" + "github.com/spf13/cobra" +) + +var ( + microcksURL string + keycloakClientID string + keycloakClientSecret string + insecureTLS bool + caCertPaths string + verbose bool +) + +// importCmd represents the import command +var importCmd = &cobra.Command{ + Use: "import ", + Short: "Import API specifications into Microcks", + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + importArtifacts(args[0]) + }, +} + +func init() { + + importCmd.Flags().StringVar(µcksURL, "microcksURL", "", "Microcks API URL (required)") + importCmd.Flags().StringVar(&keycloakClientID, "keycloakClientId", "", "Keycloak Realm Service Account ClientId (required)") + importCmd.Flags().StringVar(&keycloakClientSecret, "keycloakClientSecret", "", "Keycloak Realm Service Account ClientSecret (required)") + importCmd.Flags().BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection") + importCmd.Flags().StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs") + importCmd.Flags().BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges") + + importCmd.MarkFlagRequired("microcksURL") + importCmd.MarkFlagRequired("keycloakClientId") + importCmd.MarkFlagRequired("keycloakClientSecret") +} + +func importArtifacts(specificationFiles string) { + mc := connectors.NewMicrocksClient(microcksURL) + keycloakURL, err := mc.GetKeycloakURL() + if err != nil { + fmt.Printf("Error retrieving Microcks config: %s\n", err) + os.Exit(1) + } + + var oauthToken = "unauthenticated-token" + if keycloakURL != "null" { + kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret) + oauthToken, err = kc.ConnectAndGetToken() + if err != nil { + fmt.Printf("Error connecting to Keycloak: %s\n", err) + os.Exit(1) + } + } + + mc.SetOAuthToken(oauthToken) + sepSpecificationFiles := strings.Split(specificationFiles, ",") + for _, f := range sepSpecificationFiles { + mainArtifact := true + if strings.Contains(f, ":") { + parts := strings.Split(f, ":") + f = parts[0] + mainArtifact, err = strconv.ParseBool(parts[1]) + if err != nil { + fmt.Printf("Invalid boolean value '%s', defaulting to true\n", parts[1]) + } + } + + msg, err := mc.UploadArtifact(f, mainArtifact) + if err != nil { + fmt.Printf("Error importing artifact: %s\n", err) + os.Exit(1) + } + fmt.Printf("Microcks discovered: '%s'\n", msg) + } +} diff --git a/cmd/microcks/root/test.go b/cmd/microcks/root/test.go new file mode 100644 index 0000000..4575f68 --- /dev/null +++ b/cmd/microcks/root/test.go @@ -0,0 +1,164 @@ +/* + * Copyright The Microcks Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package root + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/microcks/microcks-cli/pkg/config" + "github.com/microcks/microcks-cli/pkg/connectors" + "github.com/spf13/cobra" +) + +var ( + runnerChoices = map[string]bool{"HTTP": true, "SOAP_HTTP": true, "SOAP_UI": true, "POSTMAN": true, "OPEN_API_SCHEMA": true, "ASYNC_API_SCHEMA": true, "GRPC_PROTOBUF": true, "GRAPHQL_SCHEMA": true} + timeUnitChoices = map[string]bool{"milli": true, "sec": true, "min": true} +) + +var testCmd = &cobra.Command{ + Use: "test ", + Short: "Run tests on Microcks", + Args: cobra.ExactArgs(3), + Run: func(cmd *cobra.Command, args []string) { + serviceRef := args[0] + testEndpoint := args[1] + runnerType := args[2] + + if _, valid := runnerChoices[runnerType]; !valid { + fmt.Println("Invalid runner type. Should be one of:", keys(runnerChoices)) + os.Exit(1) + } + + // Retrieve flag values + microcksURL, _ := cmd.Flags().GetString("microcksURL") + keycloakClientID, _ := cmd.Flags().GetString("keycloakClientId") + keycloakClientSecret, _ := cmd.Flags().GetString("keycloakClientSecret") + waitFor, _ := cmd.Flags().GetString("waitFor") + secretName, _ := cmd.Flags().GetString("secretName") + filteredOperations, _ := cmd.Flags().GetString("filteredOperations") + operationsHeaders, _ := cmd.Flags().GetString("operationsHeaders") + oAuth2Context, _ := cmd.Flags().GetString("oAuth2Context") + insecureTLS, _ := cmd.Flags().GetBool("insecure") + caCertPaths, _ := cmd.Flags().GetString("caCerts") + verbose, _ := cmd.Flags().GetBool("verbose") + + if microcksURL == "" || keycloakClientID == "" || keycloakClientSecret == "" { + fmt.Println("--microcksURL, --keycloakClientId, and --keycloakClientSecret are mandatory flags.") + os.Exit(1) + } + + if insecureTLS { + config.InsecureTLS = true + } + if caCertPaths != "" { + config.CaCertPaths = caCertPaths + } + if verbose { + config.Verbose = true + } + + waitForMilliseconds := parseWaitFor(waitFor) + mc := connectors.NewMicrocksClient(microcksURL) + keycloakURL, err := mc.GetKeycloakURL() + if err != nil { + fmt.Printf("Error retrieving Microcks config: %s", err) + os.Exit(1) + } + + oauthToken := "unauthenticated-token" + if keycloakURL != "null" { + kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret) + oauthToken, err = kc.ConnectAndGetToken() + if err != nil { + fmt.Printf("Error retrieving OAuth token: %s", err) + os.Exit(1) + } + } + + mc.SetOAuthToken(oauthToken) + testResultID, err := mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders, oAuth2Context) + if err != nil { + fmt.Printf("Error creating test: %s", err) + os.Exit(1) + } + + time.Sleep(1 * time.Second) + success := pollTestResult(mc, testResultID, waitForMilliseconds) + + fmt.Printf("Full TestResult details: %s/#/tests/%s\n", strings.Split(microcksURL, "/api")[0], testResultID) + if !success { + os.Exit(1) + } + }, +} + +func init() { + testCmd.Flags().String("microcksURL", "", "Microcks API URL") + testCmd.Flags().String("keycloakClientId", "", "Keycloak Client ID") + testCmd.Flags().String("keycloakClientSecret", "", "Keycloak Client Secret") + testCmd.Flags().String("waitFor", "5sec", "Time to wait for test to finish") + testCmd.Flags().String("secretName", "", "Secret for connecting test endpoint") + testCmd.Flags().String("filteredOperations", "", "List of operations for test") + testCmd.Flags().String("operationsHeaders", "", "Override operations headers as JSON") + testCmd.Flags().String("oAuth2Context", "", "OAuth2 client context JSON") + testCmd.Flags().Bool("insecure", false, "Accept insecure HTTPS connections") + testCmd.Flags().String("caCerts", "", "Comma-separated CRT file paths") + testCmd.Flags().Bool("verbose", false, "Enable verbose mode") +} + +func parseWaitFor(waitFor string) int64 { + if strings.HasSuffix(waitFor, "milli") { + ms, _ := strconv.ParseInt(waitFor[:len(waitFor)-5], 10, 64) + return ms + } else if strings.HasSuffix(waitFor, "sec") { + sec, _ := strconv.ParseInt(waitFor[:len(waitFor)-3], 10, 64) + return sec * 1000 + } else if strings.HasSuffix(waitFor, "min") { + min, _ := strconv.ParseInt(waitFor[:len(waitFor)-3], 10, 64) + return min * 60 * 1000 + } + return 5000 +} + +func pollTestResult(mc connectors.MicrocksClient, testResultID string, waitTime int64) bool { + now := time.Now().UnixMilli() + future := now + waitTime + 10000 + for time.Now().UnixMilli() < future { + summary, err := mc.GetTestResult(testResultID) + if err != nil { + fmt.Printf("Error checking test result: %s", err) + os.Exit(1) + } + if !summary.InProgress { + return summary.Success + } + fmt.Println("Waiting 2 seconds before checking again...") + time.Sleep(2 * time.Second) + } + return false +} + +func keys(m map[string]bool) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/cmd/microcks/root/version.go b/cmd/microcks/root/version.go new file mode 100644 index 0000000..46587dd --- /dev/null +++ b/cmd/microcks/root/version.go @@ -0,0 +1,39 @@ +/* + * Copyright The Microcks Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package root + +import ( + "fmt" + + "github.com/microcks/microcks-cli/cmd/microcks/internal/version" + "github.com/spf13/cobra" +) + + +func versionCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "version", + Short: "Check this CLI version", + Long: `Get the version of the Microcks CLI.`, + Example: ` microcks version`, + RunE: func(cmd *cobra.Command, args []string) error { + fmt.Printf("Microcks CLI version: %s\n", version.Version) + return nil + }, + } + return cmd +} \ No newline at end of file diff --git a/cmd/test.go b/cmd/test.go deleted file mode 100644 index 748c39c..0000000 --- a/cmd/test.go +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright The Microcks Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package cmd - -import ( - "flag" - "fmt" - "os" - "strconv" - "strings" - "time" - - "github.com/microcks/microcks-cli/pkg/config" - "github.com/microcks/microcks-cli/pkg/connectors" -) - -var ( - runnerChoices = map[string]bool{"HTTP": true, "SOAP_HTTP": true, "SOAP_UI": true, "POSTMAN": true, "OPEN_API_SCHEMA": true, "ASYNC_API_SCHEMA": true, "GRPC_PROTOBUF": true, "GRAPHQL_SCHEMA": true} - timeUnitChoices = map[string]bool{"milli": true, "sec": true, "min": true} -) - -type testComamnd struct { -} - -// NewTestCommand build a new TestCommand implementation -func NewTestCommand() Command { - return new(testComamnd) -} - -// Execute implementation of testCommand structure -func (c *testComamnd) Execute() { - - // Parse subcommand args first. - if len(os.Args) < 4 { - fmt.Println("test command require args") - os.Exit(1) - } - - serviceRef := os.Args[2] - testEndpoint := os.Args[3] - runnerType := os.Args[4] - - // Validate presence and values of args. - if &serviceRef == nil || strings.HasPrefix(serviceRef, "-") { - fmt.Println("test command require args") - os.Exit(1) - } - if &testEndpoint == nil || strings.HasPrefix(testEndpoint, "-") { - fmt.Println("test command require args") - os.Exit(1) - } - if &runnerType == nil || strings.HasPrefix(runnerType, "-") { - fmt.Println("test command require args") - os.Exit(1) - } - if _, validChoice := runnerChoices[runnerType]; !validChoice { - fmt.Println(" should be one of: HTTP, SOAP, SOAP_UI, POSTMAN, OPEN_API_SCHEMA, ASYNC_API_SCHEMA, GRPC_PROTOBUF, GRAPHQL_SCHEMA") - os.Exit(1) - } - - // Then parse flags. - testCmd := flag.NewFlagSet("test", flag.ExitOnError) - - var microcksURL string - var keycloakURL string - var keycloakClientID string - var keycloakClientSecret string - var waitFor string - var secretName string - var filteredOperations string - var operationsHeaders string - var oAuth2Context string - var insecureTLS bool - var caCertPaths string - var verbose bool - - testCmd.StringVar(µcksURL, "microcksURL", "", "Microcks API URL") - testCmd.StringVar(&keycloakClientID, "keycloakClientId", "", "Keycloak Realm Service Account ClientId") - testCmd.StringVar(&keycloakClientSecret, "keycloakClientSecret", "", "Keycloak Realm Service Account ClientSecret") - testCmd.StringVar(&waitFor, "waitFor", "5sec", "Time to wait for test to finish") - testCmd.StringVar(&secretName, "secretName", "", "Secret to use for connecting test endpoint") - testCmd.StringVar(&filteredOperations, "filteredOperations", "", "List of operations to launch a test for") - testCmd.StringVar(&operationsHeaders, "operationsHeaders", "", "Override of operations headers as JSON string") - testCmd.StringVar(&oAuth2Context, "oAuth2Context", "", "Spec of an OAuth2 client context as JSON string") - testCmd.BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection") - testCmd.StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs") - testCmd.BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges") - testCmd.Parse(os.Args[5:]) - - // Validate presence and values of flags. - if len(microcksURL) == 0 { - fmt.Println("--microcksURL flag is mandatory. Check Usage.") - os.Exit(1) - } - if len(keycloakClientID) == 0 { - fmt.Println("--keycloakClientId flag is mandatory. Check Usage.") - os.Exit(1) - } - if len(keycloakClientSecret) == 0 { - fmt.Println("--keycloakClientSecret flag is mandatory. Check Usage.") - os.Exit(1) - } - if &waitFor == nil || (!strings.HasSuffix(waitFor, "milli") && !strings.HasSuffix(waitFor, "sec") && !strings.HasSuffix(waitFor, "min")) { - fmt.Println("--waitFor format is wrong. Applying default 5sec") - waitFor = "5sec" - } - - // Collect optional HTTPS transport flags. - if insecureTLS { - config.InsecureTLS = true - } - if len(caCertPaths) > 0 { - config.CaCertPaths = caCertPaths - } - if verbose { - config.Verbose = true - } - - // Compute time to wait in milliseconds. - var waitForMilliseconds int64 = 5000 - if strings.HasSuffix(waitFor, "milli") { - waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-5], 0, 64) - } else if strings.HasSuffix(waitFor, "sec") { - waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64) - waitForMilliseconds = waitForMilliseconds * 1000 - } else if strings.HasSuffix(waitFor, "min") { - waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64) - waitForMilliseconds = waitForMilliseconds * 60 * 1000 - } - - // Now we seems to be good ... - // First - retrieve the Keycloak URL from Microcks configuration. - mc := connectors.NewMicrocksClient(microcksURL) - keycloakURL, err := mc.GetKeycloakURL() - if err != nil { - fmt.Printf("Got error when invoking Microcks client retrieving config: %s", err) - os.Exit(1) - } - - var oauthToken string = "unauthentifed-token" - if keycloakURL != "null" { - // If Keycloak is enabled, retrieve an OAuth token using Keycloak Client. - kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret) - - oauthToken, err = kc.ConnectAndGetToken() - if err != nil { - fmt.Printf("Got error when invoking Keycloack client: %s", err) - os.Exit(1) - } - //fmt.Printf("Retrieve OAuthToken: %s", oauthToken) - } - - // Then - launch the test on Microcks Server. - mc.SetOAuthToken(oauthToken) - - var testResultID string - testResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders, oAuth2Context) - if err != nil { - fmt.Printf("Got error when invoking Microcks client creating Test: %s", err) - os.Exit(1) - } - //fmt.Printf("Retrieve TestResult ID: %s", testResultID) - - // Finally - wait before checking and loop for some time - time.Sleep(1 * time.Second) - - // Add 10.000ms to wait time as it's now representing the server timeout. - now := nowInMilliseconds() - future := now + waitForMilliseconds + 10000 - - var success = false - for nowInMilliseconds() < future { - testResultSummary, err := mc.GetTestResult(testResultID) - if err != nil { - fmt.Printf("Got error when invoking Microcks client check TestResult: %s", err) - os.Exit(1) - } - success = testResultSummary.Success - inProgress := testResultSummary.InProgress - fmt.Printf("MicrocksClient got status for test \"%s\" - success: %s, inProgress: %s \n", testResultID, fmt.Sprint(success), fmt.Sprint(inProgress)) - - if !inProgress { - break - } - - fmt.Println("MicrocksTester waiting for 2 seconds before checking again or exiting.") - time.Sleep(2 * time.Second) - } - - fmt.Printf("Full TestResult details are available here: %s/#/tests/%s \n", strings.Split(microcksURL, "/api")[0], testResultID) - - if !success { - os.Exit(1) - } -} - -func nowInMilliseconds() int64 { - return time.Now().UnixNano() / int64(time.Millisecond) -} diff --git a/go.mod b/go.mod index ab91059..00bdff8 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,11 @@ module github.com/microcks/microcks-cli -go 1.21.3 +go 1.22.5 + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/spf13/cobra v1.8.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect +) diff --git a/go.sum b/go.sum index e69de29..c486643 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,20 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go deleted file mode 100644 index 92427da..0000000 --- a/main.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "os" - - "github.com/microcks/microcks-cli/cmd" -) - -func main() { - var c cmd.Command - - if len(os.Args) == 1 { - cmd.NewHelpCommand().Execute() - os.Exit(1) - } - - switch os.Args[1] { - case "version": - c = cmd.NewVersionCommand() - case "help": - c = cmd.NewHelpCommand() - case "test": - c = cmd.NewTestCommand() - case "import": - c = cmd.NewImportCommand() - default: - cmd.NewHelpCommand().Execute() - os.Exit(1) - } - - c.Execute() - return -}