// 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. // To build this app, run the following command: // CGO_ENABLED=0 GOARCH=amd64 go build -a -installsuffix cgo -o bin/change_dc change_dc.go package findha import ( "context" "crypto/tls" "encoding/json" "fmt" "log" "net/http" "os" "strconv" "strings" "time" "github.com/jedib0t/go-pretty/v6/table" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.rackspace.com/DCM/gomigrate/core" "github.rackspace.com/DCM/gomigrate/shared" "github.rackspace.com/DCM/tools" "github.rackspace.com/gorax/clients/mongodbAPI" "github.rackspace.com/gorax/gokeys" ) type ( // haPairResp type will be the raw response value returned from the // FindHAPairs function. haPairResp struct { Version string Device int HADevice string Platform string } // foDevice type is a representation of // a response from the getFailoverDevice call foDevice struct { Data struct { ThisDevice int `json:"this_device"` FailoverDevice int `json:"failover_device"` EvaluationData string `json:"evaluation_data"` FailoverEnabled bool `json:"failover_enabled"` IsActive bool `json:"is_active"` Version struct { F5Ver string `json:"version,omitempty"` ADXVer string `json:"system_version,omitempty"` ASAVer struct { ID string `json:"version,omitempty"` } `json:"software_version,omitempty"` } `json:"version"` Message string `json:"message"` } `json:"data"` Error string `json:"error"` } ) var argsMoveGroups *[]string // Plugin function will return a argparse.Command type back to the parent parser // nolint:typecheck func Plugin(p *core.Parser) core.Plugin { // Create a argument for the find NetDevices HA configuration cmd := p.NewCommand("find_ha", "Returns a list of NetDevices with their HA configuration") argsMoveGroups = shared.ArgMoveGroups(cmd) return core.Plugin{CMD: cmd, Func: pluginFunc} } // pluginFunc function will prompt for a list of move-groups, then query the migration database // for a listing of network devices to run the failover_device call on. // It should then determine which devices in-fact have an HA configuration and return the // HA status func pluginFunc(cfg gokeys.Settings) { // Pull a core token from the users gokeys keychain coreKey, err := cfg.Core(false) if err != nil { log.Fatalf("gokeys.Core:%s", err) } // Make our empty response value haOrder := make([]haPairResp, 0) adxOrder := make([]haPairResp, 0) moveGroupList := *argsMoveGroups if len(moveGroupList) == 0 { log.Fatalf("no move-groups found in %v", moveGroupList) } // Determine the mongo collection we should be querying based on the move-group // name. collection := shared.GetCollection(moveGroupList[0]) if collection == "" { log.Fatalf("unable to parse collection name from %s", moveGroupList[0]) } logrus.Infof("Gathering device list for %s in %s", strings.Join(moveGroupList, ","), collection) // Pull a list of network devices ONLY for us to run through the failover_device call. deviceList, err := getDeviceList(moveGroupList, coreKey.Password, collection) if err != nil { logrus.Fatalf("unable to get device list for %v", moveGroupList) } logrus.Infof("Getting HA Mate info on %d network devices", len(deviceList)) // Range through the device list response and create a listing of devices that currently have // and HA configuration and the current status. for id, value := range deviceList { data, err := getFailoverDevice(id, coreKey.Password) if err != nil { logrus.Error(err) continue } // If failover is enabled and it is the active unit, append to the list // We do this so that there is not duplicate line entries in the list. if data.Data.FailoverEnabled && data.Data.IsActive { haOrder = append(haOrder, haPairResp{ Device: id, HADevice: strconv.Itoa(data.Data.FailoverDevice), Version: getVersion(data), Platform: value.Device.Type, }) } } printHAOrder(haOrder) for _, d := range haOrder { if strings.Contains(strings.ToLower(d.Version), "asr125") { adxOrder = append(adxOrder, d) } } printADXOrder(adxOrder) } // printHAOrder func will take a structured type of response data and render a table // output to stdout. func printHAOrder(data []haPairResp) { t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"First Run", "Second Run", "Platform", "Version"}) for _, d := range data { t.AppendRow(table.Row{d.Device, d.HADevice, d.Platform, d.Version}) } t.SortBy([]table.SortBy{{Name: "First Run", Mode: table.Asc}}) t.SetStyle(table.StyleDefault) t.Render() } // printADXOrder func will take a structured type of response data and render a table // output to stdout. func printADXOrder(data []haPairResp) { t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Pull 1st", "Pull 2nd", "Platform", "Version"}) for _, d := range data { t.AppendRow(table.Row{d.HADevice, d.Device, d.Platform, d.Version}) } t.SortBy([]table.SortBy{{Name: "Pull 1st", Mode: table.Asc}}) t.SetStyle(table.StyleDefault) t.Render() } // getFailoverDevice function will take a device and reach out to the NSI service that determines // the correct failover device by logging into the device and looking for certain criteria. func getFailoverDevice(deviceID int, token string) (foDevice, error) { var headers = map[string]string{ "Accept": "application/json", "Connection": "close", "authtoken": token, } fullURL := fmt.Sprintf("https://ord-service.nsi.rackspace.com/%d/failover_device", deviceID) 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 { return foDevice{}, fmt.Errorf("getFailoverDevice:NewRequest:%d:%s", deviceID, err) } for key, value := range headers { req.Header.Set(key, value) } // For control over HTTP client headers, // redirect policy, and other settings, // create a Client // A Client is an HTTP client client := &http.Client{ Transport: &http.Transport{ // nolint:gosec TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } // Send the request via a client // Do sends an HTTP request and // returns an HTTP response res, err := client.Do(req) if res != nil { defer func() { if defErr := res.Body.Close(); defErr != nil { err = errors.Wrap(defErr, "defer error") } }() } if err != nil { return foDevice{}, fmt.Errorf("getFailoverDevice:Do:%d:%s", deviceID, err) } // Fill the record with the data from the JSON var data foDevice // Use json.Decode for reading streams of JSON data if err := json.NewDecoder(res.Body).Decode(&data); err != nil { return foDevice{}, fmt.Errorf("getFailoverDevice:Decode:%d:%s", deviceID, err) } if data.Error != "" { return data, fmt.Errorf("conn_err:%d:%s", deviceID, data.Error) } return data, nil } // getVersion function will evaluate the failover device response to determine the // correct version location based on the platform. func getVersion(r foDevice) string { // Return ADX Version Information if r.Data.Version.ADXVer != "" { return r.Data.Version.ADXVer } // Return ASA Version Information if r.Data.Version.ASAVer.ID != "" { return r.Data.Version.ASAVer.ID } // Return F5 Version Information if r.Data.Version.F5Ver != "" { return r.Data.Version.F5Ver } return "" } // getDeviceList will call out to Mongo to pull a list of devices within a move-group // and filter out just network devices that are targeted in shutdown. func getDeviceList(moveGroups []string, token, collection string) (map[int]tools.Device, error) { // Make an empty response var var deviceList = make(map[int]tools.Device) // Create a new Mongo Client c := mongodbAPI.New(mongodbAPI.WithToken(token), "migration", false) // Initiate the call out to the migration/Find resource byt, err := c.Find( &mongodbAPI.FindQuery{ Query: map[string]interface{}{ "move_group": map[string]interface{}{ "$in": moveGroups, }, "deleted": map[string]bool{ "$ne": true, }, }, Projection: []string{ "move_group", "device.make_model", "device.container_component_configuration_type_name", "account.name", "account.number", }, }, collection) if err != nil { return deviceList, fmt.Errorf("getDeviceList:mongodbAPI.Find:%s", err) } // Decode the json response back var payload struct { Result []tools.Device `json:"result"` } jd := json.NewDecoder(strings.NewReader(string(byt))) if err = jd.Decode(&payload); err != nil { return deviceList, err } // Range through the response and only append network devices that // can be ran through shutdown onto the response values. for _, d := range payload.Result { if strings.Contains(strings.ToLower(d.Device.MakeModel), "cisco asa") { deviceList[d.ID] = d } if strings.Contains(strings.ToLower(d.Device.MakeModel), "load-balancer") { deviceList[d.ID] = d } } return deviceList, nil }