package goctk import ( "encoding/json" "errors" "fmt" "net/http" "strconv" ) var ( accountQueryList = map[string]interface{}{ "account": "number", "status": "status.name", } ) type ( Account struct { Number string `json:"number"` Name string `json:"name"` Status string `json:"status.name"` LeadTech string `json:"primary_lead_tech.name"` PrimaryContact string `json:"primary_contact.name"` AccountManager string `json:"account_exec.name"` TeamName string `json:"support_team.name"` NetSecTeam string `json:"netsec_team.name"` IsInternal bool `json:"is_internal"` IsUS bool `json:"is_us"` IsUK bool `json:"is_uk"` CMRR float64 `json:"latest_cmrr"` } AccountSFISearch struct { Number string `json:"core_account_number"` Name string `json:"namex"` Status string `json:"statusx"` Team string `json:"support_team"` } ComputerByAccount struct { Class string `json:"class"` LoadArg int `json:"load_arg"` Count int `json:"count"` Limit int `json:"limit"` Offset int `json:"offset"` Result []ComputerByAct `json:"result"` } ComputerByAct struct { Computers ComputerByActAttrib `json:"computers"` Name string `json:"name"` } ComputerByActAttrib struct { Attribute string `json:"attribute"` SubAttribute []ComputerByActSub `json:"subattributes"` } ComputerByActSub struct { Number int `json:"number"` Name string `json:"name"` Status string `json:"status.name"` PlatformModel string `json:"platform_model"` DataCenter string `json:"datacenter.name"` } Query struct { Class string `json:"class"` LoadArg map[string]interface{} `json:"load_arg"` Attributes map[string]interface{} `json:"attributes,omitempty"` SubAttributes map[string]interface{} `json:"subattributes,omitempty"` } AccountQueryLight struct { Account string `json:"account"` Status string `json:"status"` } AccountQueryLightResponse struct { Result []*AccountQueryLight `json:"result"` } AccountNetsecTeam struct { CoreClass `json:"netsec_team"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` TeamLead Contact `json:"team_leader,omitempty"` } // AccountTicketResp type represents the data returned from CTK containing details // about a newly created ticket AccountTicketResp struct { Number string `json:"number"` Account string `json:"account.number"` Status string `json:"status"` Severity int `json:"severity"` } // AttributeResponse defines a response to a direct query of an attribute AttributeResponse struct { Methods string `json:"methods"` Description string `json:"description"` Values string `json:"values"` ID int `json:"id"` ClassType string `json:"class_type"` ClassName string `json:"class_name"` Attributes string `json:"attributes"` Name string `json:"name"` } ) // AccountsBySupportTeam takes a team number and returns a slice of account numbers assigned to it func (c *Client) AccountsBySupportTeam(team int) ([]int, error) { var alist []int var offset int limit := 250 con := true // Loop until the result count is smaller than the limit (250) for con == true { query := fmt.Sprintf("[{\"class\": \"Account.Account\",\"load_arg\": {\"class\": \"Account.AccountWhere\",\"values\": [[ \"support_team\", \"=\", %d]],\"limit\": %d,\"offset\": %d},\"attributes\": [\"number\"]}]", team, limit, offset) qbyte := []byte(query) response, err := c.Query(qbyte) if err != nil { return alist, err } var res []struct { Count int `json:"count"` Result []struct { Number string `json:"number"` } `json:"result"` Offset int `json:"offset"` } json.Unmarshal(response, &res) for i := 0; i < len(res[0].Result); i++ { n, err := strconv.Atoi(res[0].Result[i].Number) if err != nil { return alist, err } alist = append(alist, n) } // If we got less records than our limit, end the run if res[0].Count < limit { con = false } // If we got the same amount of records as our limit, increment the offset by the size of the limit if res[0].Count == limit { offset += res[0].Count } } return alist, nil } func (c *Client) AccountSegment(account interface{}) (string, error) { // Process if we have an int or string var act string switch account := account.(type) { default: return "", errors.New("Invalid type for account variable") case int: act = strconv.Itoa(account) case string: act = account } url := fmt.Sprintf("https://ws.core.rackspace.com/ctkapi/attribute/Account.Account/%s/segment", act) client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { return "", err } req.Header.Set(c.Type, c.Token) res, err := client.Do(req) if err != nil { return "", err } if res.StatusCode != 200 { return "", errors.New(res.Status) } response := new(AttributeResponse) d := json.NewDecoder(res.Body) if err := d.Decode(response); err != nil { return "", err } return response.Description, nil } // AccountDetails method will return specific information about an account from CTK. func (c *Client) AccountDetails(account int) (Account, error) { var ( actErr = "ERROR: goctk.AccountDetails#%s" acctDetails = Account{} q = struct { Class string `json:"class"` LoadArg int `json:"load_arg"` Attributes []string `json:"attributes"` }{ "Account.Account", account, []string{ "name", "status.name", "is_internal", "is_us", "is_uk", "support_team.name", "netsec_team.name", "account_exec.name", "primary_contact.name", "primary_lead_tech.name", "number", "latest_cmrr", }, } ) query, err := json.Marshal(q) if err != nil { return acctDetails, err } response, err := c.Query(query) if err != nil { return acctDetails, err } var res coreResponse json.Unmarshal(response, &res) if len(res) != 1 { return acctDetails, fmt.Errorf(actErr, "response length incorrect") } if len(res[0].Result) != 1 { return acctDetails, fmt.Errorf(actErr, "respons.Result length incorrect") } json.Unmarshal(res[0].Result[0], &acctDetails) return acctDetails, nil } // AccountSearch method will return a list of account name matches from CTK func (c *Client) AccountSearch(accountPart string) (as []AccountSFISearch, err error) { if len(accountPart) < 3 { err = fmt.Errorf("search %s is not at least 3 characters in lenght", accountPart) return } var ( actErr = "ERROR: goctk.AccountSearch#%s" q = struct { Class string `json:"class"` LoadArg map[string]interface{} `json:"load_arg"` Attributes []string `json:"attributes"` }{ "SFI.Account", map[string]interface{}{ "class": "SFI.AccountWhere", "values": []interface{}{ []string{"name", "like", "%" + accountPart + "%"}, []string{"status", "=", "Active"}, }, }, []string{ "core_account_number", "namex", "statusx", "support_team", }, } ) query, err := json.Marshal(q) if err != nil { return } response, err := c.Query(query) if err != nil { return } var res coreResponse if err = json.Unmarshal(response, &res); err != nil { return } if len(res) != 1 { err = fmt.Errorf(actErr, "response length incorrect") return } for _, rawMsg := range res[0].Result { var data AccountSFISearch if err = json.Unmarshal(rawMsg, &data); err != nil { return } as = append(as, data) } return } func (c *Client) ComputersByAccount(account int) (*ComputerByAccount, error) { type ctk struct { Class string `json:"class"` LoadArg int `json:"load_arg"` Attributes []interface{} `json:"attributes"` } type Attribute struct { Attribute string `json:"attribute"` SubAttributes []string `json:"subattributes"` } js, err := json.Marshal(&ctk{ Class: "Account.Account", LoadArg: account, Attributes: []interface{}{ "name", Attribute{ Attribute: "computers", SubAttributes: []string{"name", "status.name", "number", "platform_model", "datacenter.name"}, }, }, }) if err != nil { return nil, err } res, err := c.Query(js) if err != nil { return nil, err } var t ComputerByAccount if err = json.Unmarshal(res, &[]interface{}{&t}); err != nil { return nil, err } return &t, nil } func (c *Client) AccountListInfo(accounts []int) (*AccountQueryLightResponse, error) { loadArg := map[string]interface{}{"values": []interface{}{ "number", "in", accounts}, "class": "Account.AccountWhere", } js, err := json.Marshal(&Query{ Class: "Account.Account", LoadArg: loadArg, Attributes: accountQueryList, }) if err != nil { return nil, err } res, err := c.Query(js) if err != nil { return nil, err } aq := new(AccountQueryLightResponse) if err := json.Unmarshal(res, &[]interface{}{aq}); err != nil { return nil, err } return aq, nil } func (aq *AccountQueryLightResponse) AccountList() (al []string) { for _, a := range aq.Result { al = append(al, a.Account) } return } // RackConnectCfg type represents the json data back from the rack_connect_configs attribute // in core. type RackConnectCfg struct { ConfigurationId string `json:"ConfigurationId"` ConfigurationName string `json:"ConfigurationName"` Region string `json:"Region"` RackConnectVersion int `json:"RackConnectVersion"` HybridControlDeepLink string `json:"HybridControlDeepLink"` CoreAccountNumber int `json:"CoreAccountNumber"` CloudAccounts []struct { CloudAccountId string `json:"CloudAccountId"` CloudDDIAccount int `json:"CloudDDIAccount"` Username string `json:"Username"` } `json:"CloudAccounts"` } // RackConnectConfigs method is used to gather associated RackConnect cloud accounts and // RC configurations for a given Core Account. func (c *Client) RackConnectConfigs(account int) (rcCfg []RackConnectCfg, err error) { rspCfg := struct { Cfg string `json:"rack_connect_configs"` }{} q := struct { Class string `json:"class"` LoadArg int `json:"load_arg"` Attributes []string `json:"attributes"` }{ "Account.Account", account, []string{"number", "rack_connect_configs"}, } query, err := json.Marshal(q) if err != nil { return } response, err := c.Query(query) if err != nil { return } var res coreResponse json.Unmarshal(response, &res) if len(res) != 1 { err = errors.New("inaccurate number of accounts returned") return } if len(res[0].Result) != 1 { err = errors.New("inaccurate number of account results returned") return } // Unmarshal the result into the response for RC. The parent coreResponse brings the // Result in as a RawMessage, so we have to unmarshal it here. if err = json.Unmarshal(res[0].Result[0], &rspCfg); err != nil { return } // For some reason, the rack_connect_configs element brings back a json payload // that has been escaped into a single string. We need format it back into // json to unmarshal into a struct. byt := []byte(rspCfg.Cfg) // Now finally back into the RC cfg struct if err = json.Unmarshal(byt, &rcCfg); err != nil { return } return rcCfg, nil } // AccountTicket type represents the data required to create a ticket using // the AccountAddTicket method type AccountTicket struct { Queue int Account int Devices []int Subcategory int Source int Severity int Subject string Body string IsPrivate bool } // AccountAddTicket method takes a client receiver and will generate a new ticket in CORE using // CTK API func (c *Client) AccountAddTicket(req AccountTicket) (AccountTicketResp, error) { var ( t = ctkMethod{ Class: "Account.Account", Method: "addTicket", LoadArg: req.Account, Args: []interface{}{ req.Queue, // Ticket.Queue.Queue func() int { if req.Subcategory != 0 { return req.Subcategory } return 29261 }(), // Set subcategory to 'Mass Update' func() int { if req.Source != 0 { return req.Source } return 6 }(), // Set source to Mass Tickets func() int { if req.Severity != 0 { return req.Severity } return 1 }(), // Set severity to Standard req.Subject, // Subject String req.Body, // Text String req.Devices, // devices []int req.IsPrivate, // is_private_message bool }, KeywordArgs: map[string]string{}, ResultMap: map[string]string{ "status": "status.name", "account": "account.number", "number": "number", "severity": "severity.id", }, } ticket = AccountTicketResp{} ) js, err := json.Marshal(t) if err != nil { return ticket, err } res, err := c.Query(js) if err != nil { return ticket, err } var r ctkMethodResp if err := json.Unmarshal(res, &r); err != nil { return ticket, err } if len(r) != 1 { return ticket, fmt.Errorf("response length incorrect: %v", r) } if len(r[0].Result) == 0 { return ticket, fmt.Errorf("respons.Result length incorrect: %v", r[0].Result) } err = json.Unmarshal(r[0].Result, &ticket) return ticket, err }