1# coding: utf-8
2# Copyright (c) 2016, 2021, Oracle and/or its affiliates.  All rights reserved.
3# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
4
5from __future__ import absolute_import
6
7from oci._vendor import requests  # noqa: F401
8from oci._vendor import six
9
10from oci import retry, circuit_breaker  # noqa: F401
11from oci.base_client import BaseClient
12from oci.config import get_config_value_or_default, validate_config
13from oci.signer import Signer
14from oci.util import Sentinel, get_signer_from_authentication_type, AUTHENTICATION_TYPE_FIELD_NAME
15from .models import compute_instance_agent_type_mapping
16missing = Sentinel("Missing")
17
18
19class PluginconfigClient(object):
20    """
21    API for the Oracle Cloud Agent software running on compute instances. Oracle Cloud Agent
22    is a lightweight process that monitors and manages compute instances.
23    """
24
25    def __init__(self, config, **kwargs):
26        """
27        Creates a new service client
28
29        :param dict config:
30            Configuration keys and values as per `SDK and Tool Configuration <https://docs.cloud.oracle.com/Content/API/Concepts/sdkconfig.htm>`__.
31            The :py:meth:`~oci.config.from_file` method can be used to load configuration from a file. Alternatively, a ``dict`` can be passed. You can validate_config
32            the dict using :py:meth:`~oci.config.validate_config`
33
34        :param str service_endpoint: (optional)
35            The endpoint of the service to call using this client. For example ``https://iaas.us-ashburn-1.oraclecloud.com``. If this keyword argument is
36            not provided then it will be derived using the region in the config parameter. You should only provide this keyword argument if you have an explicit
37            need to specify a service endpoint.
38
39        :param timeout: (optional)
40            The connection and read timeouts for the client. The default values are connection timeout 10 seconds and read timeout 60 seconds. This keyword argument can be provided
41            as a single float, in which case the value provided is used for both the read and connection timeouts, or as a tuple of two floats. If
42            a tuple is provided then the first value is used as the connection timeout and the second value as the read timeout.
43        :type timeout: float or tuple(float, float)
44
45        :param signer: (optional)
46            The signer to use when signing requests made by the service client. The default is to use a :py:class:`~oci.signer.Signer` based on the values
47            provided in the config parameter.
48
49            One use case for this parameter is for `Instance Principals authentication <https://docs.cloud.oracle.com/Content/Identity/Tasks/callingservicesfrominstances.htm>`__
50            by passing an instance of :py:class:`~oci.auth.signers.InstancePrincipalsSecurityTokenSigner` as the value for this keyword argument
51        :type signer: :py:class:`~oci.signer.AbstractBaseSigner`
52
53        :param obj retry_strategy: (optional)
54            A retry strategy to apply to all calls made by this service client (i.e. at the client level). There is no retry strategy applied by default.
55            Retry strategies can also be applied at the operation level by passing a ``retry_strategy`` keyword argument as part of calling the operation.
56            Any value provided at the operation level will override whatever is specified at the client level.
57
58            This should be one of the strategies available in the :py:mod:`~oci.retry` module. A convenience :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY`
59            is also available. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
60
61        :param obj circuit_breaker_strategy: (optional)
62            A circuit breaker strategy to apply to all calls made by this service client (i.e. at the client level).
63            This client uses :py:data:`~oci.circuit_breaker.DEFAULT_CIRCUIT_BREAKER_STRATEGY` as default if no circuit breaker strategy is provided.
64            The specifics of circuit breaker strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/circuit_breakers.html>`__.
65
66        :param function circuit_breaker_callback: (optional)
67            Callback function to receive any exceptions triggerred by the circuit breaker.
68        """
69        validate_config(config, signer=kwargs.get('signer'))
70        if 'signer' in kwargs:
71            signer = kwargs['signer']
72
73        elif AUTHENTICATION_TYPE_FIELD_NAME in config:
74            signer = get_signer_from_authentication_type(config)
75
76        else:
77            signer = Signer(
78                tenancy=config["tenancy"],
79                user=config["user"],
80                fingerprint=config["fingerprint"],
81                private_key_file_location=config.get("key_file"),
82                pass_phrase=get_config_value_or_default(config, "pass_phrase"),
83                private_key_content=config.get("key_content")
84            )
85
86        base_client_init_kwargs = {
87            'regional_client': True,
88            'service_endpoint': kwargs.get('service_endpoint'),
89            'base_path': '/20180530',
90            'service_endpoint_template': 'https://iaas.{region}.{secondLevelDomain}',
91            'skip_deserialization': kwargs.get('skip_deserialization', False),
92            'circuit_breaker_strategy': kwargs.get('circuit_breaker_strategy', circuit_breaker.GLOBAL_CIRCUIT_BREAKER_STRATEGY)
93        }
94        if 'timeout' in kwargs:
95            base_client_init_kwargs['timeout'] = kwargs.get('timeout')
96        if base_client_init_kwargs.get('circuit_breaker_strategy') is None:
97            base_client_init_kwargs['circuit_breaker_strategy'] = circuit_breaker.DEFAULT_CIRCUIT_BREAKER_STRATEGY
98        self.base_client = BaseClient("pluginconfig", config, signer, compute_instance_agent_type_mapping, **base_client_init_kwargs)
99        self.retry_strategy = kwargs.get('retry_strategy')
100        self.circuit_breaker_callback = kwargs.get('circuit_breaker_callback')
101
102    def list_instanceagent_available_plugins(self, compartment_id, os_name, os_version, **kwargs):
103        """
104        The API to get the list of plugins that are available.
105
106
107        :param str compartment_id: (required)
108            The `OCID`__ of the compartment.
109
110            __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
111
112        :param str os_name: (required)
113            The OS for which the plugin is supported.
114            Examples of OperatingSystemQueryParam:OperatingSystemVersionQueryParam are as follows:
115            'CentOS' '6.10' , 'CentOS Linux' '7', 'CentOS Linux' '8',
116            'Oracle Linux Server' '6.10', 'Oracle Linux Server' '8.0',
117            'Red Hat Enterprise Linux Server' '7.8',
118            'Windows' '10', 'Windows' '2008ServerR2', 'Windows' '2012ServerR2', 'Windows' '7', 'Windows' '8.1'
119
120        :param str os_version: (required)
121            The OS version for which the plugin is supported.
122
123        :param str opc_request_id: (optional)
124            Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request,
125            please provide the request ID.
126
127        :param str page: (optional)
128            For list pagination. The value of the `opc-next-page` response header from the previous \"List\"
129            call. For important details about how pagination works, see
130            `List Pagination`__.
131
132            __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine
133
134        :param int limit: (optional)
135            For list pagination. The maximum number of results per page, or items to return in a paginated
136            \"List\" call. For important details about how pagination works, see
137            `List Pagination`__.
138
139            __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine
140
141        :param str sort_by: (optional)
142            The field to sort by. You can provide one sort order (`sortOrder`). Default order for
143            `TIMECREATED` is descending.
144
145            **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you
146            optionally filter by availability domain if the scope of the resource type is within a
147            single availability domain. If you call one of these \"List\" operations without specifying
148            an availability domain, the resources are grouped by availability domain, then sorted.
149
150            Allowed values are: "TIMECREATED", "DISPLAYNAME"
151
152        :param str sort_order: (optional)
153            The sort order to use, either ascending (`ASC`) or descending (`DESC`). The `DISPLAYNAME` sort order
154            is case sensitive.
155
156            Allowed values are: "ASC", "DESC"
157
158        :param str name: (optional)
159            The plugin name
160
161        :param obj retry_strategy: (optional)
162            A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
163
164            This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
165            The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
166
167            To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
168
169        :return: A :class:`~oci.response.Response` object with data of type list of :class:`~oci.compute_instance_agent.models.AvailablePluginSummary`
170        :rtype: :class:`~oci.response.Response`
171
172        :example:
173        Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/2.53.1/computeinstanceagent/list_instanceagent_available_plugins.py.html>`__ to see an example of how to use list_instanceagent_available_plugins API.
174        """
175        resource_path = "/instanceagent/availablePlugins"
176        method = "GET"
177
178        # Don't accept unknown kwargs
179        expected_kwargs = [
180            "retry_strategy",
181            "opc_request_id",
182            "page",
183            "limit",
184            "sort_by",
185            "sort_order",
186            "name"
187        ]
188        extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
189        if extra_kwargs:
190            raise ValueError(
191                "list_instanceagent_available_plugins got unknown kwargs: {!r}".format(extra_kwargs))
192
193        if 'sort_by' in kwargs:
194            sort_by_allowed_values = ["TIMECREATED", "DISPLAYNAME"]
195            if kwargs['sort_by'] not in sort_by_allowed_values:
196                raise ValueError(
197                    "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values)
198                )
199
200        if 'sort_order' in kwargs:
201            sort_order_allowed_values = ["ASC", "DESC"]
202            if kwargs['sort_order'] not in sort_order_allowed_values:
203                raise ValueError(
204                    "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values)
205                )
206
207        query_params = {
208            "compartmentId": compartment_id,
209            "page": kwargs.get("page", missing),
210            "limit": kwargs.get("limit", missing),
211            "osName": os_name,
212            "osVersion": os_version,
213            "sortBy": kwargs.get("sort_by", missing),
214            "sortOrder": kwargs.get("sort_order", missing),
215            "name": kwargs.get("name", missing)
216        }
217        query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None}
218
219        header_params = {
220            "accept": "application/json",
221            "content-type": "application/json",
222            "opc-request-id": kwargs.get("opc_request_id", missing)
223        }
224        header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
225
226        retry_strategy = self.base_client.get_preferred_retry_strategy(
227            operation_retry_strategy=kwargs.get('retry_strategy'),
228            client_retry_strategy=self.retry_strategy
229        )
230
231        if retry_strategy:
232            if not isinstance(retry_strategy, retry.NoneRetryStrategy):
233                self.base_client.add_opc_client_retries_header(header_params)
234                retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
235            return retry_strategy.make_retrying_call(
236                self.base_client.call_api,
237                resource_path=resource_path,
238                method=method,
239                query_params=query_params,
240                header_params=header_params,
241                response_type="list[AvailablePluginSummary]")
242        else:
243            return self.base_client.call_api(
244                resource_path=resource_path,
245                method=method,
246                query_params=query_params,
247                header_params=header_params,
248                response_type="list[AvailablePluginSummary]")
249