github.com/google/cadvisor@v0.49.1/client/v2/client.go (about)

     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  
    15  // Client library to programmatically access cAdvisor API.
    16  package v2
    17  
    18  import (
    19  	"bytes"
    20  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  	"net/http"
    24  	"net/url"
    25  	"path"
    26  	"strconv"
    27  	"strings"
    28  
    29  	v1 "github.com/google/cadvisor/info/v1"
    30  	v2 "github.com/google/cadvisor/info/v2"
    31  )
    32  
    33  // Client represents the base URL for a cAdvisor client.
    34  type Client struct {
    35  	baseURL string
    36  }
    37  
    38  // NewClient returns a new client with the specified base URL.
    39  func NewClient(url string) (*Client, error) {
    40  	if !strings.HasSuffix(url, "/") {
    41  		url += "/"
    42  	}
    43  
    44  	return &Client{
    45  		baseURL: fmt.Sprintf("%sapi/v2.1/", url),
    46  	}, nil
    47  }
    48  
    49  // MachineInfo returns the JSON machine information for this client.
    50  // A non-nil error result indicates a problem with obtaining
    51  // the JSON machine information data.
    52  func (c *Client) MachineInfo() (minfo *v1.MachineInfo, err error) {
    53  	u := c.machineInfoURL()
    54  	ret := new(v1.MachineInfo)
    55  	if err = c.httpGetJSONData(ret, nil, u, "machine info"); err != nil {
    56  		return
    57  	}
    58  	minfo = ret
    59  	return
    60  }
    61  
    62  // MachineStats returns the JSON machine statistics for this client.
    63  // A non-nil error result indicates a problem with obtaining
    64  // the JSON machine information data.
    65  func (c *Client) MachineStats() ([]v2.MachineStats, error) {
    66  	var ret []v2.MachineStats
    67  	u := c.machineStatsURL()
    68  	err := c.httpGetJSONData(&ret, nil, u, "machine stats")
    69  	return ret, err
    70  }
    71  
    72  // VersionInfo returns the version info for cAdvisor.
    73  func (c *Client) VersionInfo() (version string, err error) {
    74  	u := c.versionInfoURL()
    75  	version, err = c.httpGetString(u, "version info")
    76  	return
    77  }
    78  
    79  // Attributes returns hardware and software attributes of the machine.
    80  func (c *Client) Attributes() (attr *v2.Attributes, err error) {
    81  	u := c.attributesURL()
    82  	ret := new(v2.Attributes)
    83  	if err = c.httpGetJSONData(ret, nil, u, "attributes"); err != nil {
    84  		return
    85  	}
    86  	attr = ret
    87  	return
    88  }
    89  
    90  // Stats returns stats for the requested container.
    91  func (c *Client) Stats(name string, request *v2.RequestOptions) (map[string]v2.ContainerInfo, error) {
    92  	u := c.statsURL(name)
    93  	ret := make(map[string]v2.ContainerInfo)
    94  	data := url.Values{
    95  		"type":      []string{request.IdType},
    96  		"count":     []string{strconv.Itoa(request.Count)},
    97  		"recursive": []string{strconv.FormatBool(request.Recursive)},
    98  	}
    99  	if request.MaxAge != nil {
   100  		data.Set("max_age", request.MaxAge.String())
   101  	}
   102  
   103  	u = fmt.Sprintf("%s?%s", u, data.Encode())
   104  	if err := c.httpGetJSONData(&ret, nil, u, "stats"); err != nil {
   105  		return nil, err
   106  	}
   107  	return ret, nil
   108  }
   109  
   110  func (c *Client) machineInfoURL() string {
   111  	return c.baseURL + path.Join("machine")
   112  }
   113  
   114  func (c *Client) machineStatsURL() string {
   115  	return c.baseURL + path.Join("machinestats")
   116  }
   117  
   118  func (c *Client) versionInfoURL() string {
   119  	return c.baseURL + path.Join("version")
   120  }
   121  
   122  func (c *Client) attributesURL() string {
   123  	return c.baseURL + path.Join("attributes")
   124  }
   125  
   126  func (c *Client) statsURL(name string) string {
   127  	return c.baseURL + path.Join("stats", name)
   128  }
   129  
   130  func (c *Client) httpGetResponse(postData interface{}, urlPath, infoName string) ([]byte, error) {
   131  	var resp *http.Response
   132  	var err error
   133  
   134  	if postData != nil {
   135  		data, marshalErr := json.Marshal(postData)
   136  		if marshalErr != nil {
   137  			return nil, fmt.Errorf("unable to marshal data: %v", marshalErr)
   138  		}
   139  		resp, err = http.Post(urlPath, "application/json", bytes.NewBuffer(data))
   140  	} else {
   141  		resp, err = http.Get(urlPath)
   142  	}
   143  	if err != nil {
   144  		return nil, fmt.Errorf("unable to post %q to %q: %v", infoName, urlPath, err)
   145  	}
   146  	if resp == nil {
   147  		return nil, fmt.Errorf("received empty response for %q from %q", infoName, urlPath)
   148  	}
   149  	defer resp.Body.Close()
   150  	body, err := io.ReadAll(resp.Body)
   151  	if err != nil {
   152  		err = fmt.Errorf("unable to read all %q from %q: %v", infoName, urlPath, err)
   153  		return nil, err
   154  	}
   155  	if resp.StatusCode != 200 {
   156  		return nil, fmt.Errorf("request %q failed with error: %q", urlPath, strings.TrimSpace(string(body)))
   157  	}
   158  	return body, nil
   159  }
   160  
   161  func (c *Client) httpGetString(url, infoName string) (string, error) {
   162  	body, err := c.httpGetResponse(nil, url, infoName)
   163  	if err != nil {
   164  		return "", err
   165  	}
   166  	return string(body), nil
   167  }
   168  
   169  func (c *Client) httpGetJSONData(data, postData interface{}, url, infoName string) error {
   170  	body, err := c.httpGetResponse(postData, url, infoName)
   171  	if err != nil {
   172  		return err
   173  	}
   174  	if err = json.Unmarshal(body, data); err != nil {
   175  		err = fmt.Errorf("unable to unmarshal %q (Body: %q) from %q with error: %v", infoName, string(body), url, err)
   176  		return err
   177  	}
   178  	return nil
   179  }