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

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

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

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

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

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

#open_timeoutInteger Originally defined in module Attributes

#server_pathString (readonly) Originally defined in module Attributes

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

#timeoutInteger Originally defined in module Attributes

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

Instance Method Details

#base_urlURI::HTTPS Originally defined in module Attributes

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

Delete a resource from the Classic API

Raises:

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

#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

#c_object_list_cacheConcurrent::Map Originally defined in module Cache

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

Create a new Classic API resource via POST

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

Update an existing Classic API resource

#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:

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

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

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

#jamf_buildString Originally defined in module Attributes

#jamf_versionGem::Version Originally defined in module Attributes

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

Delete an existing Jamf Pro API resource

#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.

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

Update an existing Jamf Pro API resource

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

Create a JPAPI resource via POST

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

Replace an existing Jamf Pro API resource

#keep_alive?Boolean Originally defined in module Attributes

#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

#pretty_print_instance_variablesArray

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



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

#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

#ssl_versionString Originally defined in module Attributes

#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



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

#update_refreshed_token(subcnx) ⇒ Object Originally defined in module Connect

always use the current token, which by default will auto-refresh

#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.

#userString Originally defined in module Attributes

#validate_connected(subcnx) ⇒ Object 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