// 2019 Rackspace, Inc. // // 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 mirrorports import ( "context" "encoding/json" "fmt" "log" "net/http" "net/url" "os" "strconv" "time" "github.com/jokelyo/argparse" "github.com/jedib0t/go-pretty/table" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.rackspace.com/DCM/gomigrate/core" "github.rackspace.com/DCM/gomigrate/shared" "github.rackspace.com/gorax/gokeys" ) type ( mirrorAuditResp struct { Mirror []monitorSessions `json:"monitor_sessions"` Errors []string `json:"errors"` } resp struct { Data mirrorAuditResp `json:"data"` Error string `json:"error"` } monitorSessions struct { Source []device `json:"source"` Destination []device `json:"destination"` } device struct { ID int `json:"device_id"` Platform string `json:"platform"` AccountID int `json:"account_number"` AccountName string `json:"account_name"` SpanID int `json:"span_id"` Port string `json:"port"` MappedPort string `json:"mapped_port"` } ) var ( argMoveGroup *[]string argDevice *[]int argAccount *[]string ) // SubPlugin function will return a argparse.Command type back to the parent parser // nolint:typecheck func SubPlugin(p *argparse.Command) core.Plugin { // Create a command and argument for the mirroports cmd := p.NewCommand("mirror_ports", "Checks for mirror ports") argDevice = shared.ArgDevices(cmd) argMoveGroup = shared.ArgMoveGroups(cmd) argAccount = shared.ArgAccounts(cmd) return core.Plugin{CMD: cmd, Func: pluginFunc} } // pluginFunc function will prompt for a move group, device, or account // and will run the mirror ports API call with that information // It should then determine the current mirror ports and predict mig port config func pluginFunc(cfg gokeys.Settings) { // Pull an identity token from the users gokeys keychain identKey, err := cfg.Identity(false) if err != nil { log.Fatalf("gokeys.Identity:%s", err) } // Pull a core token from the users gokeys keychain coreKey, err := cfg.Core(false) if err != nil { log.Fatalf("gokeys.Core:%s", err) } if len(*argMoveGroup) == 0 && len(*argDevice) == 0 && len(*argAccount) == 0 { fmt.Println("Must specify a move-group, account, or device") } // Select which arg will be passed to the API - move group, device, account resource := "" collection := "" values := make([]string, 0) switch { case len(*argMoveGroup) != 0: mg := *argMoveGroup collection = shared.GetCollection(mg[0]) resource = "move_group" values = *argMoveGroup case len(*argAccount) != 0: account := *argAccount collection = shared.GetAccountCollection(account[0], coreKey.Password) resource = "account" values = *argAccount case len(*argDevice) != 0: devices := *argDevice collection = shared.GetDeviceCollection(devices[0], coreKey.Password) resource = "device" // Converting device numbers to string for API call for _, d := range *argDevice { values = append(values, strconv.Itoa(d)) } } // Allowing for the possibility to pass multiples of any arg, will // loop through and call the API for each for _, val := range values { auditResp, err := getMirrorPortAudit(collection, resource, val, identKey.Password) if err != nil { logrus.Fatal(err) } pPrint(auditResp) } } // getMirrorPortAudit function will take a move group, device, or account // and pass the information to the API for span session information func getMirrorPortAudit(collection, resource, value, token string) (mirrorAuditResp, error) { var ( headers = map[string]string{ "Accept": "application/json", "X-Auth-Token": token, } fullURL = fmt.Sprintf("%s/audit/mirror_port/%s/%s/%s", shared.MigAPI, collection, resource, value) ) ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) defer cancel() // Build the request req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) if err != nil { logrus.Errorf("getMirrorPortAudit:NewRequest:%s", err) return mirrorAuditResp{}, err } par := url.Values{} req.URL.RawQuery = par.Encode() for key, value := range headers { req.Header.Set(key, value) } // Send the request via a client // Do sends an HTTP request and // returns an HTTP response r, err := http.DefaultClient.Do(req) if err != nil { logrus.Errorf("getMirrorPortAudit:Do:%s", err) return mirrorAuditResp{}, err } // closes connection if r != nil { defer func() { if defErr := r.Body.Close(); defErr != nil { err = errors.Wrap(defErr, "defer error") } }() } // checks for http code returned if r.StatusCode > http.StatusNoContent { logrus.Errorf("resp_err:%s:%s", r.Status) return mirrorAuditResp{}, err } // Use json.Decode for reading streams of JSON data var payload resp if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { logrus.Errorf("getMirrorPortAudit:Decode:%s:%s", err) return mirrorAuditResp{}, err } return payload.Data, nil } // pPrint func will take a structured type of response data and render a table // output to stdout. func pPrint(data mirrorAuditResp) { for _, d := range data.Mirror { t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Source/Dest", "ID", "Platform", "Account Number", "Account Name", "Source Port", "Mapped Port", "Span ID"}) for _, source := range d.Source { t.AppendRow(table.Row{"Source", source.ID, source.Platform, source.AccountID, source.AccountName, source.Port, source.MappedPort, source.SpanID}) } for _, dest := range d.Destination { t.AppendRow(table.Row{"Dest", dest.ID, dest.Platform, dest.AccountID, dest.AccountName, dest.Port, dest.MappedPort, dest.SpanID}) } t.Render() } for _, err := range data.Errors { logrus.Error(err) } }