Class: Jamf::Connection

Inherits:
Object show all
Includes:
Attributes, Cache, ClassicAPI, Connect, Constants, JamfProAPI
Defined in:
lib/jamf/api/connection.rb,
lib/jamf/api/connection/cache.rb,
lib/jamf/api/connection/token.rb,
lib/jamf/api/connection/connect.rb,
lib/jamf/api/connection/constants.rb,
lib/jamf/api/connection/attributes.rb,
lib/jamf/api/connection/classic_api.rb,
lib/jamf/api/connection/jamf_pro_api.rb,
lib/jamf/api/connection/default_connection.rb,
lib/jamf/api/connection/jamf_pro_api_error.rb

Overview

The connection class

Defined Under Namespace

Modules: Attributes, Cache, ClassicAPI, Connect, Constants, DefaultConnection, JamfProAPI Classes: JamfProAPIError, Token

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil, **params) ⇒ Connection

Instantiate a connection object.

If name: is provided it will be stored as the Connection’s name attribute.

if no url is provided and params are empty, or contains only a :name key, then you must call #connect with all the connection parameters before accessing a server.

See Jamf::Connection::Connect#connect for the parameters



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/jamf/api/connection.rb', line 175

def initialize(url = nil, **params)
  @name = params.delete :name
  @connected = false

  # initialize the data caches
  # see cache.rb
  @c_object_list_cache = {}
  @c_ext_attr_definition_cache = {}
  # @jp_singleton_cache = {}
  # @jp_collection_cache = {}
  # @jp_ext_attr_cache = {}

  return if url.nil? && params.empty?

  connect url, **params
end

Instance Attribute Details

#c_cnxFaraday::Connection (readonly) Originally defined in module Attributes

Returns the underlying C-API connection object.

Returns:

  • (Faraday::Connection)

    the underlying C-API connection object

#connect_timeTime (readonly) Also known as: login_time Originally defined in module Attributes

Returns when this connection was connected.

Returns:

  • (Time)

    when this connection was connected

#connectedBoolean (readonly) Also known as: connected? Originally defined in module Attributes

Returns are we connected right now?.

Returns:

  • (Boolean)

    are we connected right now?

#jp_cnxFaraday::Connection (readonly) Originally defined in module Attributes

Returns the underlying JPAPI connection object.

Returns:

  • (Faraday::Connection)

    the underlying JPAPI connection object

#last_http_responseFaraday::Response (readonly) Originally defined in module Attributes

Returns The response from the most recent API call.

Returns:

  • (Faraday::Response)

    The response from the most recent API call

#nameString, Symbol (readonly) Originally defined in module Attributes

Returns an arbitrary name that can be given to this connection during initialization, using the name: parameter. defaults to user@hostname:port.

Returns:

  • (String, Symbol)

    an arbitrary name that can be given to this connection during initialization, using the name: parameter. defaults to user@hostname:port

#open_timeoutInteger Originally defined in module Attributes

Returns Seconds before an http connection open times out.

Returns:

  • (Integer)

    Seconds before an http connection open times out

#server_pathString (readonly) Originally defined in module Attributes

Returns any path in the URL below the hostname. See Connect#connect.

Returns:

#sticky_sessionBoolean Also known as: sticky_session?, sticky? Originally defined in module Attributes

Returns are we using a sticky session?.

Returns:

  • (Boolean)

    are we using a sticky session?

Returns The current sticky_session cookie. nil unless sticky_session is set to true, either as a param to ‘connect’ or via #sticky_session=

When set via .connect, the cookie is gleaned from the token creation reponse. When set via #sticky_session=, a HEAD request is made, and the cookie will be in the response.

Only valid when the connection is to a Jamf Cloud server.

Returns:

  • (String, nil)

    The current sticky_session cookie. nil unless sticky_session is set to true, either as a param to ‘connect’ or via #sticky_session=

    When set via .connect, the cookie is gleaned from the token creation reponse. When set via #sticky_session=, a HEAD request is made, and the cookie will be in the response.

    Only valid when the connection is to a Jamf Cloud server.
    

#timeoutInteger Originally defined in module Attributes

Returns Seconds before an http request times out.

Returns:

  • (Integer)

    Seconds before an http request times out

#tokenJamf::Connection::Token (readonly) Originally defined in module Attributes

Returns the token used for connecting.

Returns:

Instance Method Details

#base_urlURI::HTTPS Originally defined in module Attributes

Returns the base URL to the server.

Returns:

  • (URI::HTTPS)

    the base URL to the server

#c_delete(rsrc) ⇒ String Also known as: delete_rsrc Originally defined in module ClassicAPI

Delete a resource from the Classic API

Parameters:

  • rsrc (String)

    the resource to create, the URL part after ‘JSSResource/’

Returns:

  • (String)

    the xml response from the server.

Raises:

#c_ext_attr_definition_cacheHash{Class: Hash{String => Jamf::ExtensionAttribute}} Originally defined in module Cache

Returns This Hash caches the C-API Extension Attribute definition objects for the three types of ext. attribs: ComputerExtensionAttribute, MobileDeviceExtensionAttribute, and UserExtensionAttribute, whenever they are fetched for parsing or validating extention attribute data.

The top-level keys are the EA classes themselves:

  • ComputerExtensionAttribute

  • MobileDeviceExtensionAttribute

  • UserExtensionAttribute

These each point to a Hash of their instances, keyed by name, e.g.

{
 "A Computer EA" => <Jamf::ComputerExtensionAttribute...>,
 "A different Computer EA" => <Jamf::ComputerExtensionAttribute...>,
 ...
}.

Returns:

  • (Hash{Class: Hash{String => Jamf::ExtensionAttribute}})

    This Hash caches the C-API Extension Attribute definition objects for the three types of ext. attribs: ComputerExtensionAttribute, MobileDeviceExtensionAttribute, and UserExtensionAttribute, whenever they are fetched for parsing or validating extention attribute data.

    The top-level keys are the EA classes themselves:

    • ComputerExtensionAttribute

    • MobileDeviceExtensionAttribute

    • UserExtensionAttribute

    These each point to a Hash of their instances, keyed by name, e.g.

    {
     "A Computer EA" => <Jamf::ComputerExtensionAttribute...>,
     "A different Computer EA" => <Jamf::ComputerExtensionAttribute...>,
     ...
    }
    

#c_get(rsrc, format = :json, raw_json: false) ⇒ Hash, String Also known as: get_rsrc Originally defined in module ClassicAPI

Get a Classic API resource via GET

The first argument is the resource to get (the part of the API url after the ‘JSSResource/’ ) The resource must be properly URL escaped beforehand. Note: URL.encode is deprecated, use CGI.escape

By default we get the data in JSON, and parse it into a ruby Hash with symbolized Hash keys.

If the second parameter is :xml then the XML version is retrieved and returned as a String.

To get the raw JSON string as it comes from the API, pass raw_json: true

Parameters:

  • rsrc (String)

    the resource to get (the part of the API url after the ‘JSSResource/’ )

  • format (Symbol) (defaults to: :json)

    either ;json or :xml If the second argument is :xml, the XML data is returned as a String.

  • raw_json (Boolean) (defaults to: false)

    When GETting JSON, return the raw unparsed string (the XML is always returned as a raw string)

Returns:

Raises:

#c_object_list_cacheConcurrent::Map Originally defined in module Cache

Returns This Hash-like object caches the results of C-API queries for an APIObject subclass’s .all summary list, keyed by the subclass’s RSRC_LIST_KEY. See the APIObject.all class method.

It also caches related data items for speedier processing:

  • The Hashes created by APIObject.map_all_ids_to(other_key), keyed by “#RSRC_LIST_KEYmap#other_key”.to_sym

  • This hash also holds a cache of the rarely-used APIObject.all_objects hash, keyed by “#RSRC_LIST_KEY_objects”.to_sym

When APIObject.all, and related methods are called without an argument, and this hash has a matching value, the value is returned, rather than requerying the API. The first time a class calls .all, or whenever refresh is not false, the API is queried and the value in this hash is updated.

Returns:

  • (Concurrent::Map)

    This Hash-like object caches the results of C-API queries for an APIObject subclass’s .all summary list, keyed by the subclass’s RSRC_LIST_KEY. See the APIObject.all class method.

    It also caches related data items for speedier processing:

    • The Hashes created by APIObject.map_all_ids_to(other_key), keyed by “#RSRC_LIST_KEYmap#other_key”.to_sym

    • This hash also holds a cache of the rarely-used APIObject.all_objects hash, keyed by “#RSRC_LIST_KEY_objects”.to_sym

    When APIObject.all, and related methods are called without an argument, and this hash has a matching value, the value is returned, rather than requerying the API. The first time a class calls .all, or whenever refresh is not false, the API is queried and the value in this hash is updated.

#c_post(rsrc, xml) ⇒ String Also known as: post_rsrc Originally defined in module ClassicAPI

Create a new Classic API resource via POST

Parameters:

  • rsrc (String)

    the API resource being created, the URL part after ‘JSSResource/’

  • xml (String)

    the xml specifying the new object.

Returns:

  • (String)

    the xml response from the server.

#c_put(rsrc, xml) ⇒ String Also known as: put_rsrc Originally defined in module ClassicAPI

Update an existing Classic API resource

Parameters:

  • rsrc (String)

    the API resource being changed, the URL part after ‘JSSResource/’

  • xml (String)

    the xml specifying the changes.

Returns:

  • (String)

    the xml response from the server.

#connect(url = nil, **params) ⇒ String Also known as: login Originally defined in module Connect

Connect to the both the Classic and Jamf Pro APIs

IMPORTANT: http (non-SSL, unencrypted) connections are not allowed.

The first parameter may be a URL (must be https) from which the host & port will be used, and if present, the user and password E.g.

connect 'https://myuser:[email protected]:8443'

which is the same as:

connect host: 'host.domain.edu', port: 8443, user: 'myuser', pw: 'pass'

When using a URL, other parameters below may be specified, however host: and port: parameters will be ignored, since they came from the URL, as will user: and :pw, if they are present in the URL. If the URL doesn’t contain user and pw, they can be provided via the parameters, or left to default values.

### Passwords

The pw: parameter also accepts the symbols :prompt, and :stdin

If :prompt, the user is promted on the commandline to enter the password for the :user.

If :stdin, the password is read from the first line of stdin

If :stdinX, (where X is an integer) the password is read from the Xth line of stdin.see Jamf.stdin

If omitted, and running from an interactive terminal, the user is prompted as with :prompt

### Tokens Instead of a user and password, you may specify a valid ‘token:’, which is either:

A Jamf::Connection::Token object, which can be extracted from an active Jamf::Connection via its #token method

or

A valid token string e.g. “eyJhdXR…6EKoo” from any source can also be used.

When using an existing token or token string, the username used to create the token will be read from the server. However, if you don’t also provide the users password using the pw: parameter, then the pw_fallback option will always be false.

### Default values

Any values available via JSS.config will be used if they are not provided in the parameters. See Jamf::Configuration. If there are no config values then a built-in default is used if available.

### API Clients

As of Jamf Pro 10.49, API connections can be made using “API Clients” which are assigned to various “API Roles”, as well as regular Jamf Pro accounts.

Connections made with API Client credentials are different from regular connections:

- Their expiration period can vary based on the Client definition
- The expirations are usually quite short, less than the default 30 min. session timeout
- They cannot be kept alive, they will become invalid when the expiration time arrives.
- The API endpoints and data exchange used for making API Client connections are
  different from those used by normal connections.

To make a connection using an API Client, pass in the client_id: and client_secret: instead of user: and pw:

Parameters:

  • url (String) (defaults to: nil)

    The URL to use for the connection. Must be ‘https’. The host, port, and (if provided), user and spassword will be extracted. Any of those params explicitly provided will be ignored if present in the url

  • params (Hash)

    the keyed parameters for connection.

Options Hash (**params):

  • :host (String)

    the hostname of the JSS API server, required if not defined in JSS.config

  • :server_path (String)

    If your JSS is not at the root of the server, e.g. if it’s at

    https://myjss.myserver.edu:8443/dev_mgmt/jssweb
    

    rather than

    https://myjss.myserver.edu:8443/
    

    then use this parameter to specify the path below the root e.g:

    server_path: 'dev_mgmt/jssweb'
    
  • :user (String)

    a JSS user who has API privs, required if not defined in Jamf::CONFIG. NOTE: To use an API Client (Jamf pro 10.49 and up), provide client_id: instead of user:

  • :client_id (String)

    The Client ID of an “API Client” available in Jamf Pro 10.49 and up. Use this instead of user:

  • :client_secret (String)

    The Client Secret of an “API Client” available in Jamf Pro 10.49 and up. Use this instead of pw:

  • :pw (String, Symbol)

    The user’s password, :prompt, or :stdin If :prompt, the user is promted on the commandline to enter the password If :stdin#, the password is read from a line of std in represented by the digit at #, so :stdin3 reads the passwd from the third line of standard input. Defaults to line 1, if no digit is supplied. see Jamf.stdin NOTE: To use an API Client (Jamf pro 10.49 and up), provide client_secret: instead of pw:

  • :port (Integer)

    the port number to connect with, defaults to 443 for Jamf Cloud hosts, 8443 for on-prem hosts

  • :ssl_version (String, Symbol)

    The SSL version to use. Default is TLSv1_2

  • :verify_cert (Boolean)

    should SSL certificates be verified. Defaults to true.

  • :open_timeout (Integer)

    the number of seconds to wait for an initial response, defaults to 60

  • :timeout (Integer)

    the number of seconds before an API call times out, defaults to 60

  • :keep_alive (Boolean)

    Should the token for the connection for be automatically refreshed before it expires? Default is true

  • :token_refresh_buffer (Integer)

    If keep_alive, refresh the token this many seconds before it expires. Must be >= Jamf::Connection::Token::MIN_REFRESH_BUFFER, which is the default

  • :pw_fallback (Boolean)

    If keep_alive, should the passwd be cached in memory and used to create a new token, if there are problems with the normal token refresh process?

  • :sticky_session (Boolean)

    Use a ‘sticky session’? Default is false. The hostname of Jamf Cloud urls does not point to a single https server, but any node of a cluster. Those nodes often take time to see changes made in other node. Sometimes, its important to perform a series of API actions to the same node, to avoid sync-timing problems between node. Setting sticky_session to true will cause all communication for this Connection to go through the one specific node it first connected ith. This is only relevant to Jamf Cloud connections, and will raise an exception is used with on-prem Jamf Pro servers. NOTE: It is not always appropriate to use this feature, and inapproriate use may negatively impact server performance. For more info, see developer.jamf.com/developer-guide/docs/sticky-sessions-for-jamf-cloud

Returns:

  • (String)

    connection description, the output of #to_s

Raises:

  • (ArgumentError)

#create_jp_connection(parse_json: true) ⇒ Object Originally defined in module JamfProAPI

create the faraday JPAPI connection object

#disconnectvoid Originally defined in module Connect

This method returns an undefined value.

With a REST connection, there isn’t any real “connection” to disconnect from So to disconnect, we just unset all our credentials.

#enable_sticky_session(headers) ⇒ Object Originally defined in module Connect

If a sticky_session was requested when the connection was made, and we are connected to a jamf cloud server, the token’s http response contains the cookie we need to send with every request to ensure a stickey session.

#flushcache(key_or_klass = nil) ⇒ void Originally defined in module Cache

This method returns an undefined value.

Empty cached lists from this connection then run garbage collection to clear any available memory

See the getters for

  • c_object_list_cache

  • c_ext_attr_definition_cache

NOTE since all ruby variables are references to objects in memory, if you’ve referenced objects in these caches, those objects won’t be removed from memory by garbage collection but all cached data will be recached as needed.

e.g.

my_ref = Jamf::SomeClass.all
# my_ref now points to the same cached hash that Jamf::SomeClass.all does

my_connection.flushcache
# Jamf::SomeClass.all now points to an empty hash in the cache, but the one
# that my_ref points to still exists, full of the original data. Because
# my_ref still points to it, garbage collection doesn't remove it from
# memory

Jamf::SomeClass.all
# Jamf::SomeClass.all re-reads the data from the API and populates the
# Hash in the cache with new data, potentially different from that you're
# still seeing in my_ref

Parameters:

  • key_or_klass (Symbol, Class) (defaults to: nil)

    Flush only the caches for the given RSRC_LIST_KEY. or the EAdef cache for the given extendable class. If nil (the default), flushes all caches

#hostString Also known as: server, hostname Originally defined in module Attributes

Returns the hostname of the Jamf Pro server API connection.

Returns:

  • (String)

    the hostname of the Jamf Pro server API connection

#jamf_buildString Originally defined in module Attributes

Returns the build of the Jamf Pro server.

Returns:

  • (String)

    the build of the Jamf Pro server

#jamf_versionGem::Version Originally defined in module Attributes

Returns the version of the Jamf Pro server.

Returns:

  • (Gem::Version)

    the version of the Jamf Pro server

#jp_delete(rsrc) ⇒ String Also known as: delete Originally defined in module JamfProAPI

Delete an existing Jamf Pro API resource

Parameters:

  • rsrc (String)

    the API resource being deleted, the URL part after ‘api/’

Returns:

  • (String)

    the response from the server.

Raises:

#jp_download(rsrc) ⇒ Object Originally defined in module JamfProAPI

GET a rsrc without doing any JSON parsing, using a temporary Faraday connection object

#jp_get(rsrc) ⇒ Hash Also known as: get Originally defined in module JamfProAPI

Returns the result of the get.

Returns:

  • (Hash)

    the result of the get

Raises:

#jp_patch(rsrc, data) ⇒ String Also known as: patch Originally defined in module JamfProAPI

Update an existing Jamf Pro API resource

Parameters:

  • rsrc (String)

    the API resource being changed, the URL part after ‘api/’

  • data (String)

    the json specifying the changes.

Returns:

  • (String)

    the response from the server.

Raises:

#jp_post(rsrc, data) ⇒ String Also known as: post Originally defined in module JamfProAPI

Create a JPAPI resource via POST

Parameters:

  • rsrc (String)

    the resource to POST (the part of the API url after the ‘/api/’ )

  • data (String)

    the JSON data to POST

Returns:

  • (String)

    the response body

Raises:

#jp_put(rsrc, data) ⇒ String Also known as: put Originally defined in module JamfProAPI

Replace an existing Jamf Pro API resource

Parameters:

  • rsrc (String)

    the API resource being changed, the URL part after ‘api/’

  • data (String)

    the json specifying the changes.

Returns:

  • (String)

    the response from the server.

Raises:

#keep_alive?Boolean Originally defined in module Attributes

Returns Is the connection token being automatically refreshed?.

Returns:

  • (Boolean)

    Is the connection token being automatically refreshed?

#logoutObject Originally defined in module Connect

Same as disconnect, but invalidates the token on the server first

#next_refreshObject

@deprecated, use .token.next_refresh



219
220
221
# File 'lib/jamf/api/connection.rb', line 219

def next_refresh
  @token.next_refresh
end

#portInteger Originally defined in module Attributes

Returns The port of the Jamf Pro server API connection.

Returns:

  • (Integer)

    The port of the Jamf Pro server API connection

#pretty_print_instance_variablesArray

Only selected items are displayed with prettyprint otherwise its too much data in irb.

Returns:

  • (Array)

    the desired instance_variables



214
215
216
# File 'lib/jamf/api/connection.rb', line 214

def pretty_print_instance_variables
  PP_VARS
end

#pw_fallback?Boolean Originally defined in module Attributes

Returns If keep_alive is true, is the password Cached in memory to use if the refresh fails?.

Returns:

  • (Boolean)

    If keep_alive is true, is the password Cached in memory to use if the refresh fails?

#secs_to_refreshObject

@deprecated, use .token.secs_to_refresh



224
225
226
# File 'lib/jamf/api/connection.rb', line 224

def secs_to_refresh
  @token.secs_to_refresh
end

#ssl_optionsHash Originally defined in module Attributes

Returns the ssl version and verify cert, to pass into faraday connections.

Returns:

  • (Hash)

    the ssl version and verify cert, to pass into faraday connections

#ssl_versionString Originally defined in module Attributes

Returns SSL version used for the connection.

Returns:

  • (String)

    SSL version used for the connection

#time_to_refreshObject

@deprecated, use .token.time_to_refresh



229
230
231
# File 'lib/jamf/api/connection.rb', line 229

def time_to_refresh
  @token.time_to_refresh
end

#to_sString

A useful string about this connection

Returns:



199
200
201
202
203
204
205
206
207
# File 'lib/jamf/api/connection.rb', line 199

def to_s
  return 'not connected' unless connected?

  if name.to_s.start_with? "#{user}@"
    name
  else
    "#{user}@#{host}:#{port}, name: #{name}"
  end
end

#upload(rsrc, local_file) ⇒ String Originally defined in module ClassicAPI

Upload a file. This is really only used for the ‘fileuploads’ endpoint of the classic API, as implemented in the Uploadable mixin module, q.v.

Parameters:

  • rsrc (String)

    the API resource being uploadad-to, the URL part after ‘JSSResource/’

  • local_file (String, Pathname)

    the local file to upload

Returns:

  • (String)

    the xml response from the server.

#userString Originally defined in module Attributes

Returns the username who’s connected to the JSS API.

Returns:

  • (String)

    the username who’s connected to the JSS API

#validate_connectedObject Originally defined in module Connect

raise exception if not connected, and make sure we’re using the current token

#validate_tokenvoid Originally defined in module Attributes

This method returns an undefined value.

raise an error if no token yet

#verify_cert?Boolean Also known as: verify_cert Originally defined in module Attributes

Returns Should the SSL certifcate from the server be verified?.

Returns:

  • (Boolean)

    Should the SSL certifcate from the server be verified?