Documentation ¶
Overview ¶
http_client.go
The `http_client` package provides a configurable HTTP client tailored for interacting with specific APIs.
It supports different authentication methods, including "bearer" and "oauth". The client is designed with a focus on concurrency management, structured error handling, and flexible configuration options. The package offers a default timeout, custom backoff strategies, dynamic rate limiting, and detailed logging capabilities. The main `Client` structure encapsulates all necessary components, like the baseURL, authentication details, and an embedded standard HTTP client.
http_client_auth_token_management.go
http_client_bearer_token_auth.go
The http_client_auth package focuses on authentication mechanisms for an HTTP client.
It provides structures and methods for handling both basic and bearer token based authentication
http_client_oauth.go
The http_client_auth package focuses on authentication mechanisms for an HTTP client.
It provides structures and methods for handling OAuth-based authentication
http_concurrency_management.go Package http_client provides utilities to manage HTTP client interactions, including concurrency control. The Concurrency Manager ensures no more than a certain number of concurrent requests (e.g., 5 for Jamf Pro) are sent at the same time. This is managed using a semaphore
http_error_handling.go This package provides utility functions and structures for handling and categorizing HTTP error responses.
http_helpers.go
http_logging.go
http_methods.go
http_request.go
jamfpro_api_handler.go
------------------------------Summary----------------------------------------
This is a api handler module for the http_client to accommodate specifics of jamf's api(s). It handles the encoding (marshalling) and decoding (unmarshalling) of data. It also sets the correct content headers for the various http methods.
This module integrates with the http_client logger for wrapped error handling for human readable return codes. It also supports the http_clients debugMode for verbose logging.
The logic of this module is defined as follows: Classic API:
For requests (GET, POST, PUT, DELETE): - Encoding (Marshalling): Use XML format. For responses (GET, POST, PUT): - Decoding (Unmarshalling): Use XML format. For responses (DELETE): - Handle response codes as response body lacks anything useful. Headers - Set content header as application/xml
JamfPro API:
For requests (GET, POST, PUT, DELETE): - Encoding (Marshalling): Use JSON format. For responses (GET, POST, PUT): - Decoding (Unmarshalling): Use JSON format. For responses (DELETE): - Handle response codes as response body lacks anything useful. Headers - Set content header as application/json
sdk_version.go
Index ¶
- Constants
- func CheckDeprecationHeader(resp *http.Response, logger Logger)
- func EnsureHTTPScheme(url string) string
- func GetUserAgent() string
- func Min(a, b int) int
- func ParseISO8601Date(dateStr string) (time.Time, error)
- type APIError
- type APIHandler
- type BearerTokenAuthCredentials
- type ClassicApiHandler
- func (h *ClassicApiHandler) GetContentType(method string) string
- func (h *ClassicApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
- func (h *ClassicApiHandler) SetDebugMode(debug bool)
- func (h *ClassicApiHandler) SetLogger(logger Logger)
- func (h *ClassicApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
- type Client
- func (c *Client) AdjustConcurrencyBasedOnMetrics()
- func (c *Client) AverageAcquisitionTime() time.Duration
- func (c *Client) ConstructAPIAuthEndpoint(endpointPath string) string
- func (c *Client) ConstructAPIResourceEndpoint(endpointPath string) string
- func (c *Client) Delete(endpoint string, out interface{}) (*http.Response, error)
- func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) EvaluateMetricsAndAdjustConcurrency()
- func (c *Client) Get(endpoint string, out interface{}) (*http.Response, error)
- func (c *Client) GetBearerAuthCredentials() BearerTokenAuthCredentials
- func (c *Client) GetOAuthCredentials() OAuthCredentials
- func (c *Client) GetPerformanceMetrics() *ClientPerformanceMetrics
- func (c *Client) HistoricalAverageAcquisitionTime() time.Duration
- func (c *Client) InvalidateOAuthToken() error
- func (c *Client) ObtainOAuthToken(credentials OAuthCredentials) error
- func (c *Client) ObtainToken() error
- func (c *Client) Patch(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) Post(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) Put(endpoint string, body, out interface{}) (*http.Response, error)
- func (c *Client) RefreshOAuthToken() error
- func (c *Client) RefreshToken() error
- func (c *Client) SetAuthenticationCredentials(creds map[string]string)
- func (c *Client) SetBearerTokenAuthCredentials(credentials BearerTokenAuthCredentials)
- func (c *Client) SetOAuthCredentials(credentials OAuthCredentials)
- func (c *Client) StartConcurrencyAdjustment()
- func (c *Client) StartMetricEvaluation()
- func (c *Client) ValidAuthTokenCheck() (bool, error)
- type ClientAuthConfig
- type ClientOption
- type ClientPerformanceMetrics
- type ConcurrencyManager
- func (c *ConcurrencyManager) Acquire(ctx context.Context) (uuid.UUID, error)
- func (c *ConcurrencyManager) AdjustConcurrencyLimit(newLimit int)
- func (c *ConcurrencyManager) AverageAcquisitionTime() time.Duration
- func (c *ConcurrencyManager) HistoricalAverageAcquisitionTime() time.Duration
- func (c *ConcurrencyManager) Release(requestID uuid.UUID)
- type Config
- type JamfProApiHandler
- func (h *JamfProApiHandler) GetContentType(method string) string
- func (h *JamfProApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
- func (h *JamfProApiHandler) SetDebugMode(debug bool)
- func (h *JamfProApiHandler) SetLogger(logger Logger)
- func (h *JamfProApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
- type Logger
- type OAuthCredentials
- type OAuthResponse
- type StructuredError
- type TokenResponse
- type UnknownApiHandler
- func (h *UnknownApiHandler) GetContentType(method string) string
- func (h *UnknownApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
- func (h *UnknownApiHandler) SetDebugMode(debug bool)
- func (h *UnknownApiHandler) SetLogger(logger Logger)
- func (h *UnknownApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
Constants ¶
const ( MaxConcurrency = 10 // Maximum allowed concurrent requests MinConcurrency = 1 // Minimum allowed concurrent requests EvaluationInterval = 1 * time.Minute // Time interval for evaluating metrics and adjusting concurrency )
const ( BaseDomain = ".jamfcloud.com" // BaseDomain represents the base domain for the jamf instance. OAuthTokenEndpoint = "/api/oauth/token" // OAuthTokenEndpoint: The endpoint to obtain an OAuth token. BearerTokenEndpoint = "/api/v1/auth/token" // BearerTokenEndpoint: The endpoint to obtain a bearer token. TokenRefreshEndpoint = "/api/v1/auth/keep-alive" // TokenRefreshEndpoint: The endpoint to refresh an existing token. TokenInvalidateEndpoint = "/api/v1/auth/invalidate-token" // TokenInvalidateEndpoint: The endpoint to invalidate an active token. )
Endpoint constants represent the URL suffixes used for Jamf API token interactions.
const ( SDKVersion = "10.50.0" UserAgentBase = "go-jamfpro-api-sdk" )
const DefaultTimeout = 10 * time.Second
Variables ¶
This section is empty.
Functions ¶
func CheckDeprecationHeader ¶
CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
func EnsureHTTPScheme ¶
EnsureHTTPScheme prefixes a URL with "http://" it defaults to "https://" doesn't already have an "https://".
func GetUserAgent ¶
func GetUserAgent() string
Types ¶
type APIHandler ¶
type APIHandler interface { MarshalRequest(body interface{}, method string) ([]byte, error) UnmarshalResponse(resp *http.Response, out interface{}) error GetContentType(method string) string SetLogger(logger Logger) SetDebugMode(debug bool) }
APIHandler is an interface for encoding, decoding, and determining content types for different API implementations. It encapsulates behavior for encoding and decoding requests and responses.
func GetAPIHandler ¶
func GetAPIHandler(endpoint string, debugMode bool) APIHandler
GetAPIHandler determines the appropriate APIHandler based on the endpoint. It identifies the type of API (Classic, JamfPro, or Unknown) and returns the corresponding handler.
type BearerTokenAuthCredentials ¶
BearerTokenAuthCredentials represents the username and password for basic authentication.
type ClassicApiHandler ¶
type ClassicApiHandler struct {
// contains filtered or unexported fields
}
ClassicApiHandler handles the specifics of the Classic API.
func (*ClassicApiHandler) GetContentType ¶
func (h *ClassicApiHandler) GetContentType(method string) string
GetContentType for ClassicApiHandler always returns XML as the content type.
func (*ClassicApiHandler) MarshalRequest ¶
func (h *ClassicApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
MarshalRequest encodes the request body in XML format for the Classic API.
func (*ClassicApiHandler) SetDebugMode ¶
func (h *ClassicApiHandler) SetDebugMode(debug bool)
func (*ClassicApiHandler) SetLogger ¶
func (h *ClassicApiHandler) SetLogger(logger Logger)
SetLogger assigns a logger instance to the ClassicApiHandler.
func (*ClassicApiHandler) UnmarshalResponse ¶
func (h *ClassicApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
UnmarshalResponse decodes the response body from XML format for the Classic API.
type Client ¶
type Client struct { InstanceName string Token string OAuthCredentials OAuthCredentials // ClientID / Client Secret BearerTokenAuthCredentials BearerTokenAuthCredentials // Username and Password for Basic Authentication Expiry time.Time ConcurrencyMgr *ConcurrencyManager PerfMetrics ClientPerformanceMetrics // contains filtered or unexported fields }
Client represents an HTTP client to interact with a specific API.
func NewClient ¶
func NewClient(instanceName string, config Config, logger Logger, options ...ClientOption) (*Client, error)
NewClient initializes a new http client instance with the given baseURL, logger, concurrency manager and client configuration
If TokenLifespan and BufferPeriod aren't set in the config, they default to 30 minutes and 5 minutes, respectively. If TotalRetryDuration isn't set in the config, it defaults to 1 minute. If no logger is provided, a default logger will be used. Any additional options provided will be applied to the client during initialization. Detect authentication method based on supplied credential type
func (*Client) AdjustConcurrencyBasedOnMetrics ¶ added in v0.0.28
func (c *Client) AdjustConcurrencyBasedOnMetrics()
AdjustConcurrencyBasedOnMetrics evaluates the current metrics and adjusts the concurrency limit if required. It checks metrics like average token acquisition time and decides on a new concurrency limit. The method ensures that the new limit respects the minimum and maximum allowed concurrency bounds.
func (*Client) AverageAcquisitionTime ¶ added in v0.0.28
Returns the average Acquisition Time to get a token from the semaphore
func (*Client) ConstructAPIAuthEndpoint ¶ added in v0.0.29
ConstructAPIAuthEndpoint returns the full URL for a Jamf API auth endpoint path.
func (*Client) ConstructAPIResourceEndpoint ¶ added in v0.0.29
ConstructAPIResourceEndpoint returns the full URL for a Jamf API resource endpoint path.
func (*Client) Delete ¶
Delete sends a DELETE request to the specified endpoint and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) EvaluateMetricsAndAdjustConcurrency ¶ added in v0.0.28
func (c *Client) EvaluateMetricsAndAdjustConcurrency()
EvaluateMetricsAndAdjustConcurrency evaluates the performance metrics and makes necessary adjustments to the concurrency limit. The method assesses the average response time and adjusts the concurrency based on how it compares to the historical average acquisition time. If the average response time has significantly increased compared to the historical average, the concurrency limit is decreased, and vice versa. The method ensures that the concurrency limit remains within the bounds defined by the system's best practices.
func (*Client) Get ¶
Get sends a GET request to the specified endpoint and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) GetBearerAuthCredentials ¶ added in v0.0.22
func (c *Client) GetBearerAuthCredentials() BearerTokenAuthCredentials
GetBearerAuthCredentials retrieves the current bearer auth credentials (Username and Password) set for the client instance. Used for test cases.
func (*Client) GetOAuthCredentials ¶ added in v0.0.22
func (c *Client) GetOAuthCredentials() OAuthCredentials
GetOAuthCredentials retrieves the current OAuth credentials (Client ID and Client Secret) set for the client instance. Used for test cases.
func (*Client) GetPerformanceMetrics ¶ added in v0.0.35
func (c *Client) GetPerformanceMetrics() *ClientPerformanceMetrics
Returns performance metrics from the http client
func (*Client) HistoricalAverageAcquisitionTime ¶ added in v0.0.28
func (*Client) InvalidateOAuthToken ¶
InvalidateOAuthToken invalidates the current OAuth access token. After invalidation, the token cannot be used for further API requests.
func (*Client) ObtainOAuthToken ¶
func (c *Client) ObtainOAuthToken(credentials OAuthCredentials) error
ObtainOAuthToken fetches an OAuth access token using the provided OAuthCredentials (Client ID and Client Secret). It updates the client's Token and Expiry fields with the obtained values.
func (*Client) ObtainToken ¶
ObtainToken fetches and sets an authentication token using the stored basic authentication credentials.
func (*Client) Patch ¶
Patch sends a PATCH request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) Post ¶
Post sends a POST request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) Put ¶
Put sends a PUT request to the specified endpoint with the provided body and unmarshals the response into 'out'. The caller is responsible for closing the response body.
func (*Client) RefreshOAuthToken ¶
RefreshOAuthToken refreshes the current OAuth token.
func (*Client) RefreshToken ¶
RefreshToken refreshes the current authentication token.
func (*Client) SetAuthenticationCredentials ¶ added in v0.0.19
SetAuthenticationCredentials interprets and sets the credentials for the Client.
func (*Client) SetBearerTokenAuthCredentials ¶
func (c *Client) SetBearerTokenAuthCredentials(credentials BearerTokenAuthCredentials)
SetBearerTokenAuthCredentials sets the BearerTokenAuthCredentials (Username and Password) for the client instance. These credentials are used for obtaining and refreshing bearer tokens for authentication.
func (*Client) SetOAuthCredentials ¶
func (c *Client) SetOAuthCredentials(credentials OAuthCredentials)
SetOAuthCredentials sets the OAuth credentials (Client ID and Client Secret) for the client instance. These credentials are used for obtaining and refreshing OAuth tokens for authentication.
func (*Client) StartConcurrencyAdjustment ¶ added in v0.0.28
func (c *Client) StartConcurrencyAdjustment()
StartConcurrencyAdjustment launches a periodic checker that evaluates current metrics and adjusts concurrency limits if needed. It uses a ticker to periodically trigger the adjustment logic.
func (*Client) StartMetricEvaluation ¶ added in v0.0.28
func (c *Client) StartMetricEvaluation()
StartMetricEvaluation continuously monitors the client's interactions with the API and adjusts the concurrency limits dynamically. The function evaluates metrics at regular intervals to detect burst activity patterns. If a burst activity is detected (e.g., many requests in a short period), the evaluation interval is reduced for more frequent checks. Otherwise, it reverts to a default interval for regular checks. After each evaluation, the function calls EvaluateMetricsAndAdjustConcurrency to potentially adjust the concurrency based on observed metrics.
The evaluation process works as follows: 1. Sleep for the defined evaluation interval. 2. Check if there's a burst in activity using the isBurstActivity method. 3. If a burst is detected, the evaluation interval is shortened to more frequently monitor and adjust the concurrency. 4. If no burst is detected, it maintains the default evaluation interval. 5. It then evaluates the metrics and adjusts the concurrency accordingly.
func (*Client) ValidAuthTokenCheck ¶
ValidAuthTokenCheck checks if the current token is valid and not close to expiry. If the token is invalid, it tries to refresh it. It returns a boolean indicating the validity of the token and an error if there's a failure.
type ClientAuthConfig ¶
type ClientAuthConfig struct { InstanceName string `json:"instanceName,omitempty"` Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` ClientID string `json:"clientID,omitempty"` ClientSecret string `json:"clientSecret,omitempty"` }
ClientAuthConfig represents the structure to read authentication details from a JSON configuration file.
func LoadClientAuthConfig ¶
func LoadClientAuthConfig(filename string) (*ClientAuthConfig, error)
LoadClientAuthConfig reads a JSON configuration file and decodes it into a ClientAuthConfig struct. It is used to retrieve authentication details like BaseURL, Username, and Password for the client.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption defines a function type for modifying client properties during initialization.
type ClientPerformanceMetrics ¶ added in v0.0.28
type ClientPerformanceMetrics struct { TotalRequests int64 TotalRetries int64 TotalRateLimitErrors int64 TotalResponseTime time.Duration TokenWaitTime time.Duration // contains filtered or unexported fields }
ClientPerformanceMetrics captures various metrics related to the client's interactions with the API, providing insights into its performance and behavior.
type ConcurrencyManager ¶
type ConcurrencyManager struct { AcquisitionTimes []time.Duration // contains filtered or unexported fields }
ConcurrencyManager controls the number of concurrent HTTP requests.
func NewConcurrencyManager ¶
func NewConcurrencyManager(limit int, logger Logger, debugMode bool) *ConcurrencyManager
NewConcurrencyManager initializes a new ConcurrencyManager with the given concurrency limit, logger, and debug mode. The ConcurrencyManager ensures no more than a certain number of concurrent requests are made. It uses a semaphore to control concurrency.
func (*ConcurrencyManager) Acquire ¶
Acquire attempts to get a token to allow an HTTP request to proceed. It blocks until a token is available or the context expires. Returns a unique request ID upon successful acquisition.
func (*ConcurrencyManager) AdjustConcurrencyLimit ¶ added in v0.0.28
func (c *ConcurrencyManager) AdjustConcurrencyLimit(newLimit int)
AdjustConcurrencyLimit dynamically modifies the maximum concurrency limit based on the newLimit provided. This function helps in adjusting the concurrency limit in real-time based on observed system performance and other metrics. It transfers the tokens from the old semaphore to the new one, ensuring that there's no loss of tokens during the transition.
func (*ConcurrencyManager) AverageAcquisitionTime ¶ added in v0.0.28
func (c *ConcurrencyManager) AverageAcquisitionTime() time.Duration
AverageAcquisitionTime computes the average time taken to acquire a token from the semaphore. It helps in understanding the contention for tokens and can be used to adjust concurrency limits.
func (*ConcurrencyManager) HistoricalAverageAcquisitionTime ¶ added in v0.0.28
func (c *ConcurrencyManager) HistoricalAverageAcquisitionTime() time.Duration
HistoricalAverageAcquisitionTime computes the average time taken to acquire a token from the semaphore over a historical period (e.g., the last 5 minutes). It helps in understanding the historical contention for tokens and can be used to adjust concurrency limits.
func (*ConcurrencyManager) Release ¶
func (c *ConcurrencyManager) Release(requestID uuid.UUID)
Release returns a token back to the pool, allowing other requests to proceed. It uses the provided requestID for logging and debugging purposes.
type Config ¶
type Config struct { DebugMode bool MaxRetryAttempts int CustomBackoff func(attempt int) time.Duration EnableDynamicRateLimiting bool Logger Logger MaxConcurrentRequests int TokenLifespan time.Duration TokenRefreshBufferPeriod time.Duration TotalRetryDuration time.Duration }
Config holds configuration options for the HTTP Client.
type JamfProApiHandler ¶
type JamfProApiHandler struct {
// contains filtered or unexported fields
}
JamfProApiHandler handles the specifics of the JamfPro API.
func (*JamfProApiHandler) GetContentType ¶
func (h *JamfProApiHandler) GetContentType(method string) string
GetContentType for JamfProApiHandler always returns JSON as the content type.
func (*JamfProApiHandler) MarshalRequest ¶
func (h *JamfProApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
MarshalRequest encodes the request body in JSON format for the JamfPro API.
func (*JamfProApiHandler) SetDebugMode ¶
func (h *JamfProApiHandler) SetDebugMode(debug bool)
func (*JamfProApiHandler) SetLogger ¶
func (h *JamfProApiHandler) SetLogger(logger Logger)
SetLogger assigns a logger instance to the JamfProApiHandler.
func (*JamfProApiHandler) UnmarshalResponse ¶
func (h *JamfProApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
UnmarshalResponse decodes the response body from JSON format for the JamfPro API.
type Logger ¶
type Logger interface { Trace(msg string, keysAndValues ...interface{}) // For very detailed logs Debug(msg string, keysAndValues ...interface{}) // For development and troubleshooting Info(msg string, keysAndValues ...interface{}) // Informational messages Warn(msg string, keysAndValues ...interface{}) // For potentially problematic situations Error(msg string, keysAndValues ...interface{}) // For errors that might still allow the app to continue running Fatal(msg string, keysAndValues ...interface{}) // For errors that might prevent the app from continuing }
Logger is an interface for logging within the SDK.
func NewDefaultLogger ¶
func NewDefaultLogger() Logger
NewDefaultLogger returns a new instance of the default logger.
type OAuthCredentials ¶
OAuthCredentials contains the client ID and client secret required for OAuth authentication.
type OAuthResponse ¶
type OAuthResponse struct { AccessToken string `json:"access_token"` ExpiresIn int64 `json:"expires_in"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token,omitempty"` Error string `json:"error,omitempty"` }
OAuthResponse represents the response structure when obtaining an OAuth access token.
type StructuredError ¶
type StructuredError struct { Error struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"` }
StructuredError represents a structured error response from the API.
type TokenResponse ¶
TokenResponse represents the structure of a token response from the API.
type UnknownApiHandler ¶
type UnknownApiHandler struct {
// contains filtered or unexported fields
}
UnknownApiHandler provides default behavior for unrecognized API types.
func (*UnknownApiHandler) GetContentType ¶
func (h *UnknownApiHandler) GetContentType(method string) string
func (*UnknownApiHandler) MarshalRequest ¶
func (h *UnknownApiHandler) MarshalRequest(body interface{}, method string) ([]byte, error)
MarshalRequest returns an error since the API type is unsupported.
func (*UnknownApiHandler) SetDebugMode ¶
func (h *UnknownApiHandler) SetDebugMode(debug bool)
func (*UnknownApiHandler) SetLogger ¶
func (h *UnknownApiHandler) SetLogger(logger Logger)
SetLogger assigns a logger instance to the UnknownApiHandler.
func (*UnknownApiHandler) UnmarshalResponse ¶
func (h *UnknownApiHandler) UnmarshalResponse(resp *http.Response, out interface{}) error
UnmarshalResponse returns an error since the API type is unsupported.