client.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Copyright 2015 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Client library to programmatically access cAdvisor API.
  15. package v2
  16. import (
  17. "bytes"
  18. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "path"
  24. "strconv"
  25. "strings"
  26. v1 "github.com/google/cadvisor/info/v1"
  27. "github.com/google/cadvisor/info/v2"
  28. )
  29. // Client represents the base URL for a cAdvisor client.
  30. type Client struct {
  31. baseUrl string
  32. }
  33. // NewClient returns a new client with the specified base URL.
  34. func NewClient(url string) (*Client, error) {
  35. if !strings.HasSuffix(url, "/") {
  36. url += "/"
  37. }
  38. return &Client{
  39. baseUrl: fmt.Sprintf("%sapi/v2.1/", url),
  40. }, nil
  41. }
  42. // MachineInfo returns the JSON machine information for this client.
  43. // A non-nil error result indicates a problem with obtaining
  44. // the JSON machine information data.
  45. func (self *Client) MachineInfo() (minfo *v1.MachineInfo, err error) {
  46. u := self.machineInfoUrl()
  47. ret := new(v1.MachineInfo)
  48. if err = self.httpGetJsonData(ret, nil, u, "machine info"); err != nil {
  49. return
  50. }
  51. minfo = ret
  52. return
  53. }
  54. // MachineStats returns the JSON machine statistics for this client.
  55. // A non-nil error result indicates a problem with obtaining
  56. // the JSON machine information data.
  57. func (self *Client) MachineStats() ([]v2.MachineStats, error) {
  58. var ret []v2.MachineStats
  59. u := self.machineStatsUrl()
  60. err := self.httpGetJsonData(&ret, nil, u, "machine stats")
  61. return ret, err
  62. }
  63. // VersionInfo returns the version info for cAdvisor.
  64. func (self *Client) VersionInfo() (version string, err error) {
  65. u := self.versionInfoUrl()
  66. version, err = self.httpGetString(u, "version info")
  67. return
  68. }
  69. // Attributes returns hardware and software attributes of the machine.
  70. func (self *Client) Attributes() (attr *v2.Attributes, err error) {
  71. u := self.attributesUrl()
  72. ret := new(v2.Attributes)
  73. if err = self.httpGetJsonData(ret, nil, u, "attributes"); err != nil {
  74. return
  75. }
  76. attr = ret
  77. return
  78. }
  79. // Stats returns stats for the requested container.
  80. func (self *Client) Stats(name string, request *v2.RequestOptions) (map[string]v2.ContainerInfo, error) {
  81. u := self.statsUrl(name)
  82. ret := make(map[string]v2.ContainerInfo)
  83. data := url.Values{
  84. "type": []string{request.IdType},
  85. "count": []string{strconv.Itoa(request.Count)},
  86. "recursive": []string{strconv.FormatBool(request.Recursive)},
  87. }
  88. u = fmt.Sprintf("%s?%s", u, data.Encode())
  89. if err := self.httpGetJsonData(&ret, nil, u, "stats"); err != nil {
  90. return nil, err
  91. }
  92. return ret, nil
  93. }
  94. func (self *Client) machineInfoUrl() string {
  95. return self.baseUrl + path.Join("machine")
  96. }
  97. func (self *Client) machineStatsUrl() string {
  98. return self.baseUrl + path.Join("machinestats")
  99. }
  100. func (self *Client) versionInfoUrl() string {
  101. return self.baseUrl + path.Join("version")
  102. }
  103. func (self *Client) attributesUrl() string {
  104. return self.baseUrl + path.Join("attributes")
  105. }
  106. func (self *Client) statsUrl(name string) string {
  107. return self.baseUrl + path.Join("stats", name)
  108. }
  109. func (self *Client) httpGetResponse(postData interface{}, urlPath, infoName string) ([]byte, error) {
  110. var resp *http.Response
  111. var err error
  112. if postData != nil {
  113. data, marshalErr := json.Marshal(postData)
  114. if marshalErr != nil {
  115. return nil, fmt.Errorf("unable to marshal data: %v", marshalErr)
  116. }
  117. resp, err = http.Post(urlPath, "application/json", bytes.NewBuffer(data))
  118. } else {
  119. resp, err = http.Get(urlPath)
  120. }
  121. if err != nil {
  122. return nil, fmt.Errorf("unable to post %q to %q: %v", infoName, urlPath, err)
  123. }
  124. if resp == nil {
  125. return nil, fmt.Errorf("received empty response for %q from %q", infoName, urlPath)
  126. }
  127. defer resp.Body.Close()
  128. body, err := ioutil.ReadAll(resp.Body)
  129. if err != nil {
  130. err = fmt.Errorf("unable to read all %q from %q: %v", infoName, urlPath, err)
  131. return nil, err
  132. }
  133. if resp.StatusCode != 200 {
  134. return nil, fmt.Errorf("request %q failed with error: %q", urlPath, strings.TrimSpace(string(body)))
  135. }
  136. return body, nil
  137. }
  138. func (self *Client) httpGetString(url, infoName string) (string, error) {
  139. body, err := self.httpGetResponse(nil, url, infoName)
  140. if err != nil {
  141. return "", err
  142. }
  143. return string(body), nil
  144. }
  145. func (self *Client) httpGetJsonData(data, postData interface{}, url, infoName string) error {
  146. body, err := self.httpGetResponse(postData, url, infoName)
  147. if err != nil {
  148. return err
  149. }
  150. if err = json.Unmarshal(body, data); err != nil {
  151. err = fmt.Errorf("unable to unmarshal %q (Body: %q) from %q with error: %v", infoName, string(body), url, err)
  152. return err
  153. }
  154. return nil
  155. }