How to use registered_services method in tempest

Best Python code snippet using tempest_python

sensing_service_manager.py

Source:sensing_service_manager.py Github

copy

Full Screen

1import asyncio2from multiprocessing import Pipe3from typing import Dict, List4from .service_delegate import ServiceDelegate5import logging6from ..utils.logging_utils import get_cur_logger_dir7import time8class SensingServiceManager:9 registered_services: Dict[str, ServiceDelegate] = {}10 _logger = None11 def __init__(self, services):12 self._register_services(services)13 def _register_services(self, services):14 """15 Takes list of services and adds them to the list.16 It additionally ensures there is a delegate for each service type.17 """18 self.registered_services = self._ensure_services(services)19 def _ensure_services(self, services):20 """21 Internal Function22 Takes in a list of services then:23 - ensure service is not already registered24 - creates a service delegate for the service25 Returns list as dictionary from {[id]: service_delegate}26 """27 service_dict = {}28 for service in services:29 if service.__id__ in service_dict or self.registered_services.get(service.__id__) is not None:30 raise Exception(31 "Service {} already registered", service.__id__)32 service_dict[service.__id__] = ServiceDelegate(33 service.__id__, service, self.get_logger())34 return service_dict35 def configure_service(self, service_id, config):36 """37 Provide configuration value to services. Should only be done38 before a service is started.39 """40 service_status = self.get_service_status(service_id)41 if service_status.is_running:42 raise Exception(43 "Service {} is already running".format(service_id))44 service_status.config = config45 async def start(self):46 for service_id in self.registered_services.keys():47 await self.start_service(service_id)48 def get_service_status(self, service_id) -> ServiceDelegate:49 if service_id not in self.registered_services:50 raise Exception(51 "Service {} not a registered service".format(service_id))52 return self.registered_services[service_id]53 def get_active_services(self):54 return [service_id for service_id, service_status in self.registered_services.items() if service_status.is_running]55 async def start_service(self, service_id):56 return await self.registered_services[service_id].start(is_manual=True)57 async def get_all_data(self, data_timeout):58 # logger = self.get_logger()59 data_obj = {}60 coros = []61 for service_id in self.get_active_services():62 coros.append(self.registered_services[service_id].get_data(63 data_timeout=data_timeout))64 gathered = await asyncio.gather(*coros)65 for data in gathered:66 if data is not None and isinstance(data, dict):67 data_obj.update(data)68 return data_obj69 def terminate_service(self, service_id):70 logger = self.get_logger()71 service_status = self.get_service_status(service_id)72 if not service_status.is_running:73 logger.info(74 "Tried to terminate service {} but service not started.".format(service_id))75 return False76 service_status.terminate_handle()77 def get_logger(self):78 if self._logger is not None:79 return self._logger80 self._logger = logging.getLogger(type(self).__name__)81 if self._logger.handlers:82 return self._logger83 logfile_dir = get_cur_logger_dir()84 logfile = logfile_dir + "/service_manager.log"85 self._logger.setLevel(logging.DEBUG)86 filehandler = logging.FileHandler(87 logfile88 )89 formatter = logging.Formatter(90 # [Process: %(process)d, %(filename)s:%(funcName)s(%(lineno)d)]91 "[%(asctime)s| %(processName)s> %(levelname)s] %(message)s"92 )93 filehandler.setFormatter(formatter)94 ch = logging.StreamHandler()95 ch.setLevel(logging.INFO)96 ch.setFormatter(formatter)97 self._logger.addHandler(filehandler)98 self._logger.addHandler(ch)99 return self._logger100 async def tlc_services(self):101 """ Provice TLC to services102 This means:103 - Restarting services which refuse to start up to 5 times at exponential backoff104 - Restarting services which are unhealthy (not responding to heartbeat)105 """106 for service_id, service_status in self.registered_services.items():107 if service_status.should_reboot and not service_status.is_healthy and not service_status.is_waiting_to_reboot:108 service_status.stop()109 await service_status.try_reboot()110 def get_healthy_services(self) -> List[ServiceDelegate]:111 services: List[ServiceDelegate] = []112 for service, delegate in self.registered_services.items():113 if self.registered_services[service].is_healthy:114 services.append(delegate)115 return services116 async def monitor_services(self, sample_rate):117 """118 Monitor services, yielding data at the given sample rate.119 Additionally perform tlc on services (including restarting iff sick.)120 """121 sampling_timeout = 1/sample_rate122 last_reading_time = time.time()123 loop = asyncio.get_event_loop()124 while True:125 d = await self.get_all_data(data_timeout=sampling_timeout)126 yield d127 loop.create_task(self.tlc_services())128 # sleep the required time to keep the same sample rate129 loop_time = time.time() - last_reading_time130 await asyncio.sleep(max(sampling_timeout - loop_time, sampling_timeout))131 self.get_logger().debug("Sampling rate: {}".format(132 1/(time.time() - last_reading_time) if time.time() - last_reading_time > 0 else 0))...

Full Screen

Full Screen

service_registry.py

Source:service_registry.py Github

copy

Full Screen

1# Members: Quang Nguyen, Vinh Tran2# CPSC 4493# Project 3: Polyglot Persistence and Service Discovery4import hug5import configparser6import logging.config7import requests8import time9import threading10import concurrent.futures11import os12import socket13lock = threading.Lock()14registered_services = {15 "users": [],16 "posts": [],17 "likes": [],18 "polls": []19}20# Load configuration21#22config = configparser.ConfigParser()23config.read("./etc/service_registry.ini")24logging.config.fileConfig(config["logging"]["config"], disable_existing_loggers=False)25def health_check():26 while 1:27 for i in registered_services:28 for j in registered_services[i]:29 print("[CHECKING]", j)30 try:31 r = requests.get(j + "/health-check/")32 # Scenario #133 # Check one of each service's URLs34 # If it returns a status code other than '200 OK', then remove it35 if r.status_code != 200:36 print(f'[REMOVED] {j}')37 # Using basic synchronization lock to prevent race condition38 with lock:39 registered_services[i].remove(j)40 print(f'[{r.status_code}] {j}\n')41 except requests.ConnectionError:42 # Scenario #243 # If one of each service's instances is down, then remove it44 # Using basic synchronization lock to prevent race condition45 with lock:46 registered_services[i].remove(j)47 print(f'[CONNECTION FAILED] {j}')48 print(f'[REMOVED] {j}\n')49 time.sleep(5)50@hug.startup()51def startup(api=None):52 myThread = threading.Thread(target=health_check, daemon=True)53 myThread.start()54# Arguments to inject into route functions55@hug.directive()56def log(name=__name__, **kwargs):57 return logging.getLogger(name)58@hug.get("/{service}/")59def get_services(service: hug.types.text):60 services = []61 try:62 for i in registered_services[service]:63 services.append(i)64 except Exception as e:65 response.status = hug.falcon.HTTP_40466 return services67######## Register service instance ########68@hug.post("/register-instance/", status=hug.falcon.HTTP_201)69def register_intances(request,response,70 service: hug.types.text,71 URL: hug.types.text):72 try:73 registered_services[service].append(URL)74 except Exception as e:75 response.status = hug.falcon.HTTP_409...

Full Screen

Full Screen

service.py

Source:service.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3narcissist.services.service4---------------------------5Module full of ponies.6"""7from exceptions import KeyError8# registered_services holds the loaded service plugins9registered_services = {}10class Service(object):11 """ Acts as a Factory and as a plugin loader. It's metaclass registers each12 class that inherits it in registered_services """13 @staticmethod14 def load(name, extra_context):15 """ The Factory part """16 try:17 cls = registered_services.get(name)18 return cls(extra_context)19 except KeyError, e:20 return None21 class __metaclass__(type):22 """ PONIES """23 def __init__(cls, name, bases, dict):24 type.__init__(cls, name, bases, dict)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tempest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful