github.com/vmware/go-vcloud-director/v2@v2.24.0/samples/openapi/main.go (about)

     1  /*
     2   * Copyright 2020 VMware, Inc.  All rights reserved.  Licensed under the Apache v2 License.
     3   */
     4  package main
     5  
     6  import (
     7  	"encoding/json"
     8  	"flag"
     9  	"fmt"
    10  	"net/url"
    11  	"os"
    12  	"strings"
    13  	"time"
    14  
    15  	"github.com/vmware/go-vcloud-director/v2/govcd"
    16  	"github.com/vmware/go-vcloud-director/v2/types/v56"
    17  )
    18  
    19  var (
    20  	username    string
    21  	password    string
    22  	org         string
    23  	apiEndpoint string
    24  	mode        string
    25  )
    26  
    27  func init() {
    28  	flag.StringVar(&username, "username", "", "Username")
    29  	flag.StringVar(&password, "password", "", "Password")
    30  	flag.StringVar(&org, "org", "System", "Org name. Default is 'System'")
    31  	flag.StringVar(&apiEndpoint, "endpoint", "", "API endpoint (e.g. 'https://hostname/api')")
    32  	flag.StringVar(&mode, "mode", "", "OpenAPI query mode: 1 - RAW json, 2 - inline type")
    33  }
    34  
    35  // Usage:
    36  // # go build -o openapi
    37  // # ./openapi --username my_user --password my_secret_password --org my-org --endpoint
    38  // https://192.168.1.160/api  --mode 1
    39  func main() {
    40  	flag.Parse()
    41  
    42  	if username == "" || password == "" || org == "" || apiEndpoint == "" || mode == "" {
    43  		fmt.Printf("'username', 'password', 'org', 'endpoint' and 'mode' must be specified\n")
    44  		os.Exit(1)
    45  	}
    46  
    47  	vcdURL, err := url.Parse(apiEndpoint)
    48  	if err != nil {
    49  		fmt.Printf("Error parsing supplied endpoint %s: %s", apiEndpoint, err)
    50  		os.Exit(2)
    51  	}
    52  
    53  	vcdCli := govcd.NewVCDClient(*vcdURL, true)
    54  	err = vcdCli.Authenticate(username, password, org)
    55  	if err != nil {
    56  
    57  		fmt.Println(err)
    58  		os.Exit(3)
    59  	}
    60  
    61  	switch mode {
    62  	case "1":
    63  		openAPIGetRawJsonAuditTrail(vcdCli)
    64  	case "2":
    65  		openAPIGetStructAuditTrail(vcdCli)
    66  	}
    67  
    68  }
    69  
    70  // openAPIGetRawJsonAuditTrail is an example function how to use low level function to interact
    71  // with OpenAPI in VCD. This examples dumps to screen valid JSON which can then be processed using
    72  // other tools (for example 'jq' in shell)
    73  // It also uses FIQL query filter to retrieve auditTrail items only for the last 12 hours
    74  func openAPIGetRawJsonAuditTrail(vcdClient *govcd.VCDClient) {
    75  	urlRef, err := vcdClient.Client.OpenApiBuildEndpoint("1.0.0/auditTrail")
    76  	if err != nil {
    77  		panic(err)
    78  	}
    79  
    80  	queryParams := url.Values{}
    81  	filterTime := time.Now().Add(-12 * time.Hour).Format(types.FiqlQueryTimestampFormat)
    82  	queryParams.Add("filter", "timestamp=gt="+filterTime)
    83  
    84  	allResponses := []json.RawMessage{{}}
    85  	err = vcdClient.Client.OpenApiGetAllItems("35.0", urlRef, queryParams, &allResponses, nil)
    86  	if err != nil {
    87  		panic(err)
    88  	}
    89  
    90  	// Wrap slice of response objects into JSON list so that it is correct JSON
    91  	responseStrings := jsonRawMessagesToStrings(allResponses)
    92  	allStringResponses := `[` + strings.Join(responseStrings, ",") + `]`
    93  	fmt.Println(allStringResponses)
    94  }
    95  
    96  // openAPIGetStructAuditTrail is an example function how to use low level function to interact with
    97  // OpenAPI in VCD and marshal responses into custom defined struct with tags.
    98  // It also uses FIQL query filter to retrieve auditTrail items only for the last 12 hours
    99  func openAPIGetStructAuditTrail(vcdClient *govcd.VCDClient) {
   100  	urlRef, err := vcdClient.Client.OpenApiBuildEndpoint("1.0.0/auditTrail")
   101  	if err != nil {
   102  		panic(err)
   103  	}
   104  
   105  	// Inline type
   106  	type AudiTrail struct {
   107  		EventID      string `json:"eventId"`
   108  		Description  string `json:"description"`
   109  		OperatingOrg struct {
   110  			Name string `json:"name"`
   111  			ID   string `json:"id"`
   112  		} `json:"operatingOrg"`
   113  		User struct {
   114  			Name string `json:"name"`
   115  			ID   string `json:"id"`
   116  		} `json:"user"`
   117  		EventEntity struct {
   118  			Name string `json:"name"`
   119  			ID   string `json:"id"`
   120  		} `json:"eventEntity"`
   121  		TaskID               interface{} `json:"taskId"`
   122  		TaskCellID           string      `json:"taskCellId"`
   123  		CellID               string      `json:"cellId"`
   124  		EventType            string      `json:"eventType"`
   125  		ServiceNamespace     string      `json:"serviceNamespace"`
   126  		EventStatus          string      `json:"eventStatus"`
   127  		Timestamp            string      `json:"timestamp"`
   128  		External             bool        `json:"external"`
   129  		AdditionalProperties struct {
   130  			UserRoles                         string `json:"user.roles"`
   131  			UserSessionID                     string `json:"user.session.id"`
   132  			CurrentContextUserProxyAddress    string `json:"currentContext.user.proxyAddress"`
   133  			CurrentContextUserClientIPAddress string `json:"currentContext.user.clientIpAddress"`
   134  		} `json:"additionalProperties"`
   135  	}
   136  
   137  	response := []*AudiTrail{{}}
   138  
   139  	queryParams := url.Values{}
   140  	filterTime := time.Now().Add(-12 * time.Hour).Format(types.FiqlQueryTimestampFormat)
   141  	queryParams.Add("filter", "timestamp=gt="+filterTime)
   142  
   143  	err = vcdClient.Client.OpenApiGetAllItems("35.0", urlRef, queryParams, &response, nil)
   144  	if err != nil {
   145  		panic(err)
   146  	}
   147  
   148  	fmt.Printf("Got %d results\n", len(response))
   149  
   150  	for _, value := range response {
   151  		fmt.Printf("%s - %s, -%s\n", value.Timestamp, value.User.Name, value.EventType)
   152  	}
   153  }
   154  
   155  // jsonRawMessagesToStrings converts []*json.RawMessage to []string
   156  func jsonRawMessagesToStrings(messages []json.RawMessage) []string {
   157  	resultString := make([]string, len(messages))
   158  	for index, message := range messages {
   159  		resultString[index] = string(message)
   160  	}
   161  	return resultString
   162  }