### Install spinner with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Install the spinner package using the go get command. ```bash go get github.com/briandowns/spinner ``` -------------------------------- ### Installation: go get github.com/mattn/go-isatty Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/mattn/go-isatty/README.md Command to install the go-isatty package using go get. ```shell $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Install go-colorable with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install tablewriter with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Install the tablewriter package using the go get command. ```bash go get github.com/olekukonko/tablewriter ``` -------------------------------- ### Install color package with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/fatih/color/README.md Install the color package using the standard Go module command. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install uniseg with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Install the uniseg package using the standard Go module command. ```bash go get github.com/rivo/uniseg ``` -------------------------------- ### Install flock package Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/gofrs/flock/README.md Use the go get command to install the flock package. ```bash go get -u github.com/gofrs/flock ``` -------------------------------- ### Start cmk and configure a server profile Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Getting-Started Start cmk, create a new server profile named 'mycloud', set the API URL and credentials, and run 'sync' to discover the available APIs. The output shows the default profile 'localcloud' and the loaded profile details. ```text $ cmk Apache CloudStack 🐡 CloudMonkey 6.3.0 Report issues: https://github.com/apache/cloudstack-cloudmonkey/issues (localcloud) 🐱 > set profile mycloud Loaded server profile: mycloud Url: http://localhost:8080/client/api Username: admin Domain: / API Key: Discovered 697 APIs (mycloud) 🐱 > set url http://myprovider.cloud/client/api (mycloud) 🐱 > set username myusername (mycloud) 🐱 > set password mypassword (mycloud) 🐱 > sync Discovered 697 APIs ``` -------------------------------- ### Install INI package with go get Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/gopkg.in/ini.v1/README.md Install the INI package using the go get command. Add the -u flag to update the package in the future. ```sh $ go get gopkg.in/ini.v1 ``` -------------------------------- ### Implement file locking with TryLock Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/gofrs/flock/README.md Example showing how to initialize a file lock and use TryLock to attempt to acquire the lock without blocking. ```go import "github.com/gofrs/flock" fileLock := flock.New("/var/lock/go-lock.lock") locked, err := fileLock.TryLock() if err != nil { // handle locking error } if locked { // do work fileLock.Unlock() } ``` -------------------------------- ### Output of basic table example Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Output of the basic example. Shows the default bordered table with centered text and right-aligned numbers. ```text +------+-----------------------+--------+ | NAME | SIGN | RATING | +------+-----------------------+--------+ | A | The Good | 500 | | B | The Very very Bad Man | 288 | | C | The Ugly | 120 | | D | The Gopher | 800 | +------+-----------------------+--------+ ``` -------------------------------- ### General help command and output Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Getting-Started Shows the output of the 'help' command in CloudMonkey, which displays usage, allowed flags, and default commands. Also shows examples of using '-h' to get help for a specific command. ```text > help usage: cmk [flags] [commands|apis] [-h] CloudMonkey (cmk) 🐡 is a command line interface for Apache CloudStack. Allowed flags: -h Show this help message or API doc when specified after an API -v Print version -o API response output format: json, text, table, column, csv -p Server profile -d Enable debug mode -c Different config file path -u CloudStack's API endpoint URL -s CloudStack user's secret Key -k CloudStack user's API Key Default commands: exit Exits help Help set Configures options for cmk sync Discovers and updates APIs version Version info > list users -h > help listUsers ``` -------------------------------- ### Output of custom separator example Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Output of the custom separator example. Shows the table with custom separators and row lines. ```text *------------*-----------*---------* β•ͺ FIRST NAME β•ͺ LAST NAME β•ͺ SSN β•ͺ *------------*-----------*---------* β•ͺ John β•ͺ Barry β•ͺ 123456 β•ͺ *------------*-----------*---------* β•ͺ Kathy β•ͺ Smith β•ͺ 687987 β•ͺ *------------*-----------*---------* β•ͺ Bob β•ͺ McCornick β•ͺ 3979870 β•ͺ *------------*-----------*---------* ``` -------------------------------- ### Basic readline usage in Go Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/ergochat/readline/README.md Shows how to create a readline instance with a prompt, read lines in a loop, handle errors (io.EOF, readline.ErrInterrupt), and write output. The example sets log output to rl.Stderr() to redraw the prompt correctly after log output. ```go package main import ( "fmt" "log" "github.com/ergochat/readline" ) func main() { // see readline.NewFromConfig for advanced options: rl, err := readline.New("> ") if err != nil { log.Fatal(err) } defer rl.Close() log.SetOutput(rl.Stderr()) // redraw the prompt correctly after log output for { line, err := rl.ReadLine() // `err` is either nil, io.EOF, readline.ErrInterrupt, or an unexpected // condition in stdin: if err != nil { return } // `line` is returned without the terminating \n or CRLF: fmt.Fprintf(rl, "you wrote: %s\n", line) } } ``` -------------------------------- ### Output of borderless table example Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Output of the borderless table example. Shows the footer row and the separator lines. ```text DATE | DESCRIPTION | CV2 | AMOUNT -----------+--------------------------+-------+---------- 1/1/2014 | Domain name | 2233 | $10.98 1/1/2014 | January Hosting | 2233 | $54.95 1/4/2014 | February Hosting | 2233 | $51.00 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 -----------+--------------------------+-------+---------- TOTAL | $146 93 --------+---------- ``` -------------------------------- ### Install cmk on Linux and macOS Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Getting-Started Download the cmk binary and place it in a directory on $PATH such as /usr/local/bin. The commands use sudo to write to that directory and make the binary executable. ```bash sudo wget -O /usr/local/bin/cmk sudo chmod +x /usr/local/bin/cmk ``` -------------------------------- ### Word segmentation with FirstWordInString Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Demonstrates the FirstWordInString function for segmenting a string into words. The example prints each word, punctuation, and space as separate segments. ```go str := "Hello, world!" state := -1 var c string for len(str) > 0 { c, str, state = uniseg.FirstWordInString(str, state) fmt.Printf("(%s)\n", c) } // (Hello) // (,) // ( ) // (world) // (!) ``` -------------------------------- ### Output of CSV table example Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Output of the CSV example. Shows the table with left-aligned columns. ```text +----------+--------------+------+-----+---------+----------------+ | FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA | +----------+--------------+------+-----+---------+----------------+ | user_id | smallint(5) | NO | PRI | NULL | auto_increment | | username | varchar(10) | NO | | NULL | | | password | varchar(100) | NO | | NULL | | +----------+--------------+------+-----+---------+----------------+ ``` -------------------------------- ### Advanced example: grapheme clusters and line breaks with StepString Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Shows how to use StepString to break a string into grapheme clusters and evaluate line break opportunities. The example prints the string with '|' for possible breaks and 'β€–' for mandatory breaks. ```go str := "First line.\nSecond line." state := -1 var ( c string boundaries int ) for len(str) > 0 { c, str, boundaries, state = uniseg.StepString(str, state) fmt.Print(c) if boundaries&uniseg.MaskLine == uniseg.LineCanBreak { fmt.Print("|") } else if boundaries&uniseg.MaskLine == uniseg.LineMustBreak { fmt.Print("β€–") } } // First |line. // β€–Second |line.β€– ``` -------------------------------- ### Example 5 - Markdown Format Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Demonstrates creating a table with custom borders and center separator using tablewriter. ```APIDOC ## tablewriter.NewWriter ### Description Creates a new table writer that writes to the provided output (e.g., os.Stdout). ### Method NewWriter ### Parameters - **output** (io.Writer) - Required - The destination where the table will be rendered. ### Returns - **table** (*tablewriter.Table) - The table writer instance. ## table.SetHeader ### Description Sets the header row for the table. ### Method SetHeader ### Parameters - **keys** ([]string) - Required - The column headers. ## table.SetBorders ### Description Sets the border configuration for the table. ### Method SetBorders ### Parameters - **border** (tablewriter.Border) - Required - Border settings with fields Left, Top, Right, Bottom (booleans). ## table.SetCenterSeparator ### Description Sets the separator character used for the center lines of the table. ### Method SetCenterSeparator ### Parameters - **sep** (string) - Required - The separator character (e.g., "|"). ## table.AppendBulk ### Description Appends multiple rows of data to the table at once. ### Method AppendBulk ### Parameters - **data** ([][]string) - Required - The rows to append. ## table.Render ### Description Renders the table to the output writer. ### Method Render ### Parameters None. ### Example ```go data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) table.SetCenterSeparator("|") table.AppendBulk(data) // Add Bulk Data table.Render() ``` ``` -------------------------------- ### Set output to JSON and list users with filter Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows setting the output format to JSON and using the filter argument to limit response keys. The example lists users with account=admin and filters to specific fields, displaying the JSON response. ```bash (mycloud) 🐱 > set output json (mycloud) 🐱 > list users account=admin filter= account, accountid, accounttype, apikey, created, domain, domainid, email, firstname, id, iscallerchilddomain, isdefault, lastname, roleid, rolename, roletype, secretkey, state, timezone, username, usersource, (mycloud) 🐱 > list users account=admin filter=account,id,domain,username, { "count": 1, "user": [ { "account": "admin", "domain": "ROOT", "id": "7966afa9-3cd4-11e9-bf33-f4d1082409e6", "username": "admin" } ] } ``` -------------------------------- ### Direct API execution in CloudMonkey shell Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Demonstrates calling CloudStack APIs directly from the CloudMonkey shell or command-line. Examples include listing users and uploading a volume with required parameters. ```bash > listUsers > uploadVolume url=xxx format=yyy name=zzz zoneid=aaa ``` -------------------------------- ### Basic spinner usage in Go Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Creates a spinner with character set 9 and a 100ms delay, starts it, sleeps for 4 seconds to simulate work, then stops it. ```Go package main import ( "github.com/briandowns/spinner" "time" ) func main() { s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) // Build our new spinner s.Start() // Start the spinner time.Sleep(4 * time.Second) // Run for some time to simulate work s.Stop() } ``` -------------------------------- ### Character set examples (indices 0-10) Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Examples of character sets available for spinner animations, indexed from 0 to 10. Each set is a string of characters used as animation frames. ```text β†β†–β†‘β†—β†’β†˜β†“β†™ ``` ```text β–β–ƒβ–„β–…β–†β–‡β–ˆβ–‡β–†β–…β–„β–ƒβ– ``` ```text β––β–˜β–β–— ``` ```text β”€β”˜β”΄β””β”œβ”Œβ”¬β” ``` ```text β—’β—£β—€β—₯ ``` ```text β—°β—³β—²β—± ``` ```text β—΄β—·β—Άβ—΅ ``` ```text ◐◓◑◒ ``` ```text .oO@* ``` ```text |/-\ ``` ```text β—‘β—‘βŠ™βŠ™β— β—  ``` -------------------------------- ### Example 6 - Identical cells merging Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Demonstrates merging identical cells in a table using SetAutoMergeCells and adding a footer. ```APIDOC ## tablewriter.NewWriter ### Description Creates a new table writer that writes to the provided output (e.g., os.Stdout). ### Method NewWriter ### Parameters - **output** (io.Writer) - Required - The destination where the table will be rendered. ### Returns - **table** (*tablewriter.Table) - The table writer instance. ## table.SetHeader ### Description Sets the header row for the table. ### Method SetHeader ### Parameters - **keys** ([]string) - Required - The column headers. ## table.SetFooter ### Description Sets the footer row for the table. ### Method SetFooter ### Parameters - **keys** ([]string) - Required - The footer cells. ## table.SetAutoMergeCells ### Description Enables automatic merging of identical cells in consecutive rows. ### Method SetAutoMergeCells ### Parameters - **merge** (bool) - Required - Set to true to enable merging. ## table.SetRowLine ### Description Enables or disables the line between rows. ### Method SetRowLine ### Parameters - **line** (bool) - Required - Set to true to show row lines. ## table.AppendBulk ### Description Appends multiple rows of data to the table at once. ### Method AppendBulk ### Parameters - **data** ([][]string) - Required - The rows to append. ## table.Render ### Description Renders the table to the output writer. ### Method Render ### Parameters None. ### Example ```go data := [][]string{ []string{"1/1/2014", "Domain name", "1234", "$10.98"}, []string{"1/1/2014", "January Hosting", "2345", "$54.95"}, []string{"1/4/2014", "February Hosting", "3456", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) table.SetAutoMergeCells(true) table.SetRowLine(true) table.AppendBulk(data) table.Render() ``` ``` -------------------------------- ### Usage example: Check if stdout is a terminal Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/mattn/go-isatty/README.md Shows how to use isatty.IsTerminal and isatty.IsCygwinTerminal to check if os.Stdout is a terminal, printing different messages accordingly. ```go package main import ( "fmt" "github.com/mattn/go-isatty" "os" ) func main() { if isatty.IsTerminal(os.Stdout.Fd()) { fmt.Println("Is Terminal") } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { fmt.Println("Is Cygwin/MSYS2 Terminal") } else { fmt.Println("Is Not Terminal") } } ``` -------------------------------- ### Example 7 - Identical cells merging (specify the column index to merge) Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Demonstrates merging identical cells only in specified columns using SetAutoMergeCellsByColumnIndex. ```APIDOC ## tablewriter.NewWriter ### Description Creates a new table writer that writes to the provided output (e.g., os.Stdout). ### Method NewWriter ### Parameters - **output** (io.Writer) - Required - The destination where the table will be rendered. ### Returns - **table** (*tablewriter.Table) - The table writer instance. ## table.SetHeader ### Description Sets the header row for the table. ### Method SetHeader ### Parameters - **keys** ([]string) - Required - The column headers. ## table.SetFooter ### Description Sets the footer row for the table. ### Method SetFooter ### Parameters - **keys** ([]string) - Required - The footer cells. ## table.SetAutoMergeCellsByColumnIndex ### Description Enables merging of identical cells only in the specified column indices. ### Method SetAutoMergeCellsByColumnIndex ### Parameters - **columns** ([]int) - Required - The column indices (0-based) where merging should be applied. ## table.SetRowLine ### Description Enables or disables the line between rows. ### Method SetRowLine ### Parameters - **line** (bool) - Required - Set to true to show row lines. ## table.AppendBulk ### Description Appends multiple rows of data to the table at once. ### Method AppendBulk ### Parameters - **data** ([][]string) - Required - The rows to append. ## table.Render ### Description Renders the table to the output writer. ### Method Render ### Parameters None. ### Example ```go data := [][]string{ []string{"1/1/2014", "Domain name", "1234", "$10.98"}, []string{"1/1/2014", "January Hosting", "1234", "$10.98"}, []string{"1/4/2014", "February Hosting", "3456", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) table.SetAutoMergeCellsByColumnIndex([]int{2, 3}) table.SetRowLine(true) table.AppendBulk(data) table.Render() ``` ``` -------------------------------- ### Use StepString for fast grapheme cluster iteration Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Demonstrates the StepString function, which is faster than the Graphemes class but requires manual state handling. The example iterates over a string and prints the runes of each grapheme cluster. ```go str := "πŸ‡©πŸ‡ͺπŸ³οΈβ€πŸŒˆ" state := -1 var c string for len(str) > 0 { c, str, _, state = uniseg.StepString(str, state) fmt.Printf("%x ", []rune(c)) } // [1f1e9 1f1ea] [1f3f3 fe0f 200d 1f308] ``` -------------------------------- ### Upload file with getUploadParamsForVolume and filepath Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Use the `filepath` parameter with the `get uploadparamsforvolume` command to upload a file directly. The command returns upload parameters and then performs the upload, showing per-file progress and a success message. ```text (localcloud) 🐱 > get uploadparamsforvolume format=qcow2 hypervisor=kvm name=systemvm-image-upload zoneid=e58d87c5-bc92-47f3-9395-ce3f1a0dd415 filepath=/root/systemvmtemplate-4.20.2-x86_64-kvm.qcow2 { "getuploadparams": { "expires": "2025-08-15T08:39:19.045Z", "id": "1254350d-639d-4778-9b11-6a123db7c2dd", "metadata": "i1wBGothRVWB4h/MAjWZ50AeASpRM9uazN8taEsWnm8wFV4egq/TkELz0bQOZ8PZ0EhnIgBsIcboMxpp/3ECVFd4Sw/JDM9TAIm3ERDfhcdkq6BfZiFx6b5ZMq50xOQXwI1Z4/ljRGhPc2/EkRPjC10ZrZkeHANa0U7hSfpSw2gKFk0mdopLhJWCA06XSHE9gWsCG4VNpJbe8HV6y/knnxXkkYdBsRXZPOTgqn2E/MncRIHny/kGoDDkz+OlR0NP7l/9L9tufpXb+TfQq6W52JAZW7zMABCmYaMqCTrMSzlloeZNiKe1FAhBRHpOLVfrSBOFhnt9sASLZXnq1vU6OtOmyaBdul1pobsYLwXFwXYXktvocgACq6atuqcyK4KRljsXRwPUS9qhYjmNH0pa/zMUG/ctTa0eecGlzqHIYVXgDEmaxb8DJeFvA4wST5hceZkcG3E6J+P82diLzyc0Jk1Xy2TgQuH05gygAeCxLKgcHFTOUGEhGJylIMigftxlN0rRjKAWo4kFYeGTEsG8Ux+VLddaP/H3JbiKdRkuRM7vUNkZz96SBMuSFGHMUy4=", "postURL": "https://10-0-55-22.sbcloud.uk/upload/1254350d-639d-4778-9b11-6a123db7c2dd", "signature": "oKST8NtYinWur9XvZF1rhjL6mK0=" } } Uploading files for getUploadParamsForVolume : [/root/systemvmtemplate-4.20.2-x86_64-kvm.qcow2] [1/1] systemvmtemplate-4.20.2-x86_64-kvm.qcow2 [========================] βœ… All files uploaded successfully. ``` -------------------------------- ### Generate a sequence of numbers Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Creates a spinner with a sequence of numbers as its character set. The example generates a 25-digit string of numbers and uses it as the spinner's character set. ```Go setOfDigits := spinner.GenerateNumberSequence(25) // Generate a 25 digit string of numbers s := spinner.New(setOfDigits, 100*time.Millisecond) ``` -------------------------------- ### Pipe CloudMonkey output to external tools Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows how to pipe CloudMonkey output to terminal tools like jq, grep, and wc for text processing. The examples include using jq to extract user IDs, grep to filter account lists, and wc to count users. ```bash $ cmk list users | jq -r '.user[].id' $ cmk ... > list accounts listall=true | grep 'id' > list users | wc -l ``` -------------------------------- ### Get spinner status Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Checks whether the spinner is currently active. The example prints the result of the Active() method. ```Go fmt.Println(s.Active()) ``` -------------------------------- ### Show make targets with make help Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/README.md Lists available Makefile targets for building, testing, debugging, and linting CloudMonkey. Requires Go 1.11 or later and a unix-like environment. ```bash $ make help all Build program binary test-bench Run benchmarks test-short Run only short tests test-verbose Run tests in verbose mode with coverage reporting test-race Run tests with race detector check tests Run tests test-xml Run tests with xUnit output test-coverage Run coverage tests debug Runs a debuggable binary using dlv lint Run golint fmt Run gofmt on all source files ``` -------------------------------- ### Plug into existing code Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/fatih/color/README.md Use color.Set and color.Unset to globally change the color of existing output. Remember to unset after use, or use defer. ```go // Use handy standard colors color.Set(color.FgYellow) fmt.Println("Existing text will now be in yellow") fmt.Printf("This one %s\n", "too") color.Unset() // Don't forget to unset // You can mix up parameters color.Set(color.FgMagenta, color.Bold) defer color.Unset() // Use it in your function fmt.Println("All text will now be bold magenta.") ``` -------------------------------- ### Create network offering with array/map syntax Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Use arg0.key=value syntax for APIs that accept arrays or maps, as shown for serviceproviderlist. ```bash > create networkoffering supportedservices=Dhcp,Dns serviceproviderlist[0].service=Dhcp serviceproviderlist[0].provider=VirtualRouter serviceproviderlist[1].service=Dns serviceproviderlist[1].provider=VirtualRouter ``` -------------------------------- ### Use your own output (io.Writer) Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/fatih/color/README.md Use Fprintln and Fprint to write colored output to a custom io.Writer instead of standard output. ```go // Use your own io.Writer output color.New(color.FgBlue).Fprintln(myWriter, "blue color!") blue := color.New(color.FgBlue) blue.Fprint(writer, "This will print text in blue.") ``` -------------------------------- ### Build and run manually with make all and ./bin/cmk Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/README.md Builds the binary with make all and then runs the resulting ./bin/cmk executable manually. ```bash $ make all $ ./bin/cmk ``` -------------------------------- ### Basic table with header and rows Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Basic usage: create a table writer, set the header, append rows, and render to stdout. The output is a bordered table with centered text and right-aligned numbers. ```go data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() // Send output ``` -------------------------------- ### Disable color globally with flag Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/fatih/color/README.md Disable color output programmatically by setting color.NoColor to true, for example when a -no-color flag is provided. ```go var flagNoColor = flag.Bool("no-color", false, "Disable color output") if *flagNoColor { color.NoColor = true // disables colorized output } ``` -------------------------------- ### Build and run with make run Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/README.md Builds and runs CloudMonkey using the Makefile. ```bash $ make run ``` -------------------------------- ### Assembly file entry points for system call dispatch Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/golang.org/x/sys/unix/README.md The hand-written assembly file asm_${GOOS}_${GOARCH}.s implements three entry points for system call dispatch. The first two are standard and differ in the number of arguments; the third is for low-level use by the ForkExec wrapper and does not call into the scheduler. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Set final output message Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Sets a final message to be displayed when the spinner stops. The example shows a multi-line final message and the resulting output. ```Go s := spinner.New(spinner.CharSets[9], 100*time.Millisecond) s.FinalMSG = "Complete!\nNew line!\nAnother one!\n" s.Start() time.Sleep(4 * time.Second) s.Stop() ``` ```sh Complete! New line! Another one! ``` -------------------------------- ### Set NoWhiteSpace and TablePadding options Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md Configures a table with no borders, no separators, and tab padding using SetNoWhiteSpace and SetTablePadding. The output shows the table without borders and with tab-separated columns. ```go data := [][]string{ {"node1.example.com", "Ready", "compute", "1.11"}, {"node2.example.com", "Ready", "compute", "1.11"}, {"node3.example.com", "Ready", "compute", "1.11"}, {"node4.example.com", "NotReady", "compute", "1.11"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Status", "Role", "Version"}) table.SetAutoWrapText(false) table.SetAutoFormatHeaders(true) table.SetHeaderAlignment(ALIGN_LEFT) table.SetAlignment(ALIGN_LEFT) table.SetCenterSeparator("") table.SetColumnSeparator("") table.SetRowSeparator("") table.SetHeaderLine(false) table.SetBorder(false) table.SetTablePadding("\t") // pad with tabs table.SetNoWhiteSpace(true) table.AppendBulk(data) // Add Bulk Data table.Render() ``` ```text NAME STATUS ROLE VERSION node1.example.com Ready compute 1.11 node2.example.com Ready compute 1.11 node3.example.com Ready compute 1.11 node4.example.com NotReady compute 1.11 ``` -------------------------------- ### Deploy basic zone with cmk CLI Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage A bash script that automates the deployment of a basic zone using the cmk command-line tool. It sets environment variables for network and storage parameters, then runs a sequence of cmk commands to create and configure the zone, physical network, network service providers, network, pod, VLAN IP ranges, cluster, hosts, and secondary storage. The script prints progress messages and ends with enabling the zone. ```bash #!/bin/bash cli=cmk dns_ext=8.8.8.8 dns_int=10.147.28.6 gw=10.147.28.1 nmask=255.255.255.0 hpvr=XenServer pod_start=10.147.28.225 pod_end=10.147.28.234 vlan_start=10.147.28.235 vlan_end=10.147.28.254 #Put space separated host ips in following host_ips=10.147.28.60 host_user=root host_passwd=password sec_storage=nfs://10.147.28.7/export/home/rohit/secondary prm_storage=nfs://10.147.28.7/export/home/rohit/primary zone_id=`$cli create zone dns1=$dns_ext internaldns1=$dns_int name=MyZone networktype=Basic | grep ^id\ = | awk '{print $3}'` echo "Created zone" $zone_id phy_id=`$cli create physicalnetwork name=phy-network zoneid=$zone_id | grep ^id\ = | awk '{print $3}'` echo "Created physical network" $phy_id $cli add traffictype traffictype=Guest physicalnetworkid=$phy_id echo "Added guest traffic" $cli add traffictype traffictype=Management physicalnetworkid=$phy_id echo "Added mgmt traffic" $cli update physicalnetwork state=Enabled id=$phy_id echo "Enabled physicalnetwork" nsp_id=`$cli list networkserviceproviders name=VirtualRouter physicalnetworkid=$phy_id | grep ^id\ = | awk '{print $3}'` vre_id=`$cli list virtualrouterelements nspid=$nsp_id | grep ^id\ = | awk '{print $3}'` $cli api configureVirtualRouterElement enabled=true id=$vre_id $cli update networkserviceprovider state=Enabled id=$nsp_id echo "Enabled virtual router element and network service provider" nsp_sg_id=`$cli list networkserviceproviders name=SecurityGroupProvider physicalnetworkid=$phy_id | grep ^id\ = | awk '{print $3}'` $cli update networkserviceprovider state=Enabled id=$nsp_sg_id echo "Enabled security group provider" netoff_id=`$cli list networkofferings name=DefaultSharedNetworkOfferingWithSGService | grep ^id\ = | awk '{print $3}'` net_id=`$cli create network zoneid=$zone_id name=guestNetworkForBasicZone displaytext=guestNetworkForBasicZone networkofferingid=$netoff_id | grep ^id\ = | awk '{print $3}'` echo "Created network $net_id for zone" $zone_id pod_id=`$cli create pod name=MyPod zoneid=$zone_id gateway=$gw netmask=$nmask startip=$pod_start endip=$pod_end | grep ^id\ = | awk '{print $3}'` echo "Created pod" $cli create vlaniprange podid=$pod_id networkid=$net_id gateway=$gw netmask=$nmask startip=$vlan_start endip=$vlan_end forvirtualnetwork=false echo "Created IP ranges for instances" cluster_id=`$cli add cluster zoneid=$zone_id hypervisor=$hpvr clustertype=CloudManaged podid=$pod_id clustername=MyCluster | grep ^id\ = | awk '{print $3}'` echo "Created cluster" $cluster_id #Put loop here if more than one for host_ip in $host_ips; do $cli add host zoneid=$zone_id podid=$pod_id clusterid=$cluster_id hypervisor=$hpvr username=$host_user password=$host_passwd url=http://$host_ip; echo "Added host" $host_ip; done; #$cli create storagepool zoneid=$zone_id podid=$pod_id clusterid=$cluster_id name=MyNFSPrimary url=$prm_storage #echo "Added primary storage" $cli add secondarystorage zoneid=$zone_id url=$sec_storage echo "Added secondary storage" $cli update zone allocationstate=Enabled id=$zone_id echo "Basic zone deloyment completed!" ``` -------------------------------- ### Reverse a string while preserving grapheme clusters with ReverseString Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Reverses a string while keeping grapheme clusters intact, so that emoji sequences are not broken. The example reverses the German flag and rainbow flag emoji sequence. ```go fmt.Println(uniseg.ReverseString("πŸ‡©πŸ‡ͺπŸ³οΈβ€πŸŒˆ")) // πŸ³οΈβ€πŸŒˆπŸ‡©πŸ‡ͺ ``` -------------------------------- ### Set output to table and list users with filter Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows setting the output format to table and listing users with a filter, displaying the response in a table format. ```bash (mycloud) 🐱 > set output table (mycloud) 🐱 > list users account=admin filter=account,id,domain,username user: count = 1 +---------+--------+--------------------------------------+----------+ | ACCOUNT | DOMAIN | ID | USERNAME | +---------+--------+--------------------------------------+----------+ | admin | ROOT | 7966afa9-3cd4-11e9-bf33-f4d1082409e6 | admin | +---------+--------+--------------------------------------+----------+ ``` -------------------------------- ### Help output for listUsers API Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Getting-Started Shows the help output for the 'listUsers' API command, listing all available parameters, their types, and descriptions. ```text > list users -h listUsers: Lists user accounts API Params Type Description ========== ==== =========== account string list resources by account. Must be used w ith the domainId parameter. accounttype long List users by account type. Valid types i nclude admin, domain-admin, read-only-ad min, or user. domainid uuid list only resources belonging to the doma in specified id uuid List user by ID. isrecursive boolean defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves. keyword string List by keyword listall boolean If set to false, list only resources belo nging to the command's caller; if set to true - list resources that the caller i s authorized to see. Default value is fa lse page integer pagesize integer state string List users by state of the user account. username string List user by the username ``` -------------------------------- ### Count grapheme clusters with GraphemeClusterCount Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Counts the number of grapheme clusters in a string, which is useful for determining the number of user-perceived characters. The example shows that the flag emoji and rainbow flag emoji each count as one cluster. ```go n := uniseg.GraphemeClusterCount("πŸ‡©πŸ‡ͺπŸ³οΈβ€πŸŒˆ") fmt.Println(n) // 2 ``` -------------------------------- ### Create a table with colored headers, columns, and footer using tablewriter Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/olekukonko/tablewriter/README.md This Go snippet creates a table with a header, footer, and border disabled, and applies colors to the header, columns, and footer using tablewriter.Colors. It uses SetHeaderColor, SetColumnColor, and SetFooterColor to define color schemes. The table data is appended in bulk and rendered to stdout. ```go data := [][]string{ []string{"1/1/2014", "Domain name", "2233", "$10.98"}, []string{"1/1/2014", "January Hosting", "2233", "$54.95"}, []string{"1/4/2014", "February Hosting", "2233", "$51.00"}, []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Date", "Description", "CV2", "Amount"}) table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer table.SetBorder(false) // Set Border to false table.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgGreenColor}, tablewriter.Colors{tablewriter.FgHiRedColor, tablewriter.Bold, tablewriter.BgBlackColor}, tablewriter.Colors{tablewriter.BgRedColor, tablewriter.FgWhiteColor}, tablewriter.Colors{tablewriter.BgCyanColor, tablewriter.FgWhiteColor}) table.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor}, tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor}, tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor}, tablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor}) table.SetFooterColor(tablewriter.Colors{}, tablewriter.Colors{}, tablewriter.Colors{tablewriter.Bold}, tablewriter.Colors{tablewriter.FgHiRedColor}) table.AppendBulk(data) table.Render() ``` -------------------------------- ### Set writer to stderr and use with shell redirection Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/briandowns/spinner/README.md Configures the spinner to write to stderr, allowing output to be redirected or piped. The example shows a shell command that encrypts data and redirects output to a file, with the spinner progress on stderr. ```Go s := spinner.New(spinner.CharSets[11], 100*time.Millisecond, spinner.WithWriter(os.Stderr)) s.Suffix = " Encrypting data..." s.Start() // Encrypt the data into ciphertext fmt.Println(os.Stdout, ciphertext) ``` ```sh > myprog encrypt "Secret text" > encrypted.txt β£― Encrypting data... ``` ```sh > cat encrypted.txt 1243hjkbas23i9ah27sj39jghv237n2oa93hg83 ``` -------------------------------- ### Iterate over grapheme clusters with Graphemes class Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Uses the Graphemes class to iterate over grapheme clusters in a string. The example prints the runes of each cluster, showing that the thumbs-up emoji with skin tone is one cluster and the exclamation mark is another. ```go gr := uniseg.NewGraphemes("πŸ‘πŸΌ!") for gr.Next() { fmt.Printf("%x ", gr.Runes()) } // [1f44d 1f3fc] [21] ``` -------------------------------- ### Set output to text and list users with filter Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows setting the output format to text and listing users with a filter, displaying the response in a text format. ```bash (mycloud) 🐱 > set output text (mycloud) 🐱 > list users account=admin filter=account,id,domain,username count = 1 user: account = admin id = 7966afa9-3cd4-11e9-bf33-f4d1082409e6 domain = ROOT username = admin ``` -------------------------------- ### Default cmk config file (~/.cmk/config) Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows the default configuration file created on first run, including core settings and the [localcloud] server profile. Use this as a reference for the default values that can be overridden with the set command. ```ini prompt = 🐱 asyncblock = true timeout = 1800 output = json verifycert = true profile = localcloud [localcloud] url = http://localhost:8080/client/api username = admin password = password domain = / apikey = secretkey = ``` -------------------------------- ### Set output to column and list users with filter Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Shows setting the output format to column and listing users with a filter, displaying the response in a column format. ```bash (mycloud) 🐱 > set output column (mycloud) 🐱 > list users account=admin filter=account,id,domain,username ACCOUNT DOMAIN ID USERNAME admin ROOT 7966afa9-3cd4-11e9-bf33-f4d1082409e6 admin ``` -------------------------------- ### Calculate monospace string width with StringWidth Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/vendor/github.com/rivo/uniseg/README.md Calculates the display width of a string in monospace fonts, accounting for wide characters. The example shows that the flag emoji and rainbow flag emoji each take 2 cells, plus the exclamation mark takes 1, totaling 5. ```go width := uniseg.StringWidth("πŸ‡©πŸ‡ͺπŸ³οΈβ€πŸŒˆ!") fmt.Println(width) // 5 ``` -------------------------------- ### Build for all platforms with make dist Source: https://github.com/apache/cloudstack-cloudmonkey/blob/main/README.md Builds CloudMonkey for all distros and platforms. ```bash $ make dist ``` -------------------------------- ### Upload custom certificate with file content syntax Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Pass file content to an API request using the @/path/to/file syntax. ```bash > upload customcertificate certificate=@/tmp/c.crt privatekey=@/tmp/c.key domainsuffix=some.domain.com ``` -------------------------------- ### Create project with quoted arguments Source: https://github.com/apache/cloudstack-cloudmonkey/wiki/Usage Wrap values containing spaces in double quotes when passing arguments to an API command. ```bash > create project name="my unique name" displaytext="my lengthy description" ```