DatastoreService class used by sensors. This class is meant to be used in context of long running processes (e.g. sensors) and it uses "create_token" method to generate a new auth token. A new token is also automatically generated once the old one expires. Note: This class does nee
| 322 | |
| 323 | |
| 324 | class SensorDatastoreService(BaseDatastoreService): |
| 325 | """ |
| 326 | DatastoreService class used by sensors. This class is meant to be used in context of long |
| 327 | running processes (e.g. sensors) and it uses "create_token" method to generate a new auth |
| 328 | token. A new token is also automatically generated once the old one expires. |
| 329 | |
| 330 | Note: This class does need database access (create_token method - to be able to create a new |
| 331 | token). |
| 332 | """ |
| 333 | |
| 334 | def __init__(self, logger, pack_name, class_name, api_username): |
| 335 | super(SensorDatastoreService, self).__init__( |
| 336 | logger=logger, pack_name=pack_name, class_name=class_name |
| 337 | ) |
| 338 | self._api_username = api_username |
| 339 | self._token_expire = get_datetime_utc_now() |
| 340 | |
| 341 | def get_api_client(self): |
| 342 | """ |
| 343 | Retrieve API client instance. |
| 344 | """ |
| 345 | token_expire = self._token_expire <= get_datetime_utc_now() |
| 346 | |
| 347 | if not self._client or token_expire: |
| 348 | # Note: Late import to avoid high import cost (time wise) |
| 349 | from st2common.services.access import create_token |
| 350 | |
| 351 | self._logger.debug("Creating new Client object.") |
| 352 | |
| 353 | ttl = cfg.CONF.auth.service_token_ttl |
| 354 | api_url = get_full_public_api_url() |
| 355 | |
| 356 | temporary_token = create_token( |
| 357 | username=self._api_username, ttl=ttl, service=True |
| 358 | ) |
| 359 | self._client = Client(api_url=api_url, token=temporary_token.token) |
| 360 | self._token_expire = get_datetime_utc_now() + timedelta(seconds=ttl) |
| 361 | |
| 362 | return self._client |
no outgoing calls