How to use service_names method in localstack

Best Python code snippet using localstack_python

dockercompose.py

Source:dockercompose.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2'''3Module to import docker-compose via saltstack4.. versionadded:: 2016.3.05:maintainer: Jean Praloran <jeanpralo@gmail.com>6:maturity: new7:depends: docker-compose>=1.58:platform: all9Introduction10------------11This module allows one to deal with docker-compose file in a directory.12This is a first version only, the following commands are missing at the moment13but will be built later on if the community is interested in this module:14- run15- logs16- port17- scale18Installation Prerequisites19--------------------------20This execution module requires at least version 1.4.0 of both docker-compose_ and21Docker_. docker-compose can easily be installed using :py:func:`pip.install22<salt.modules.pip.install>`:23.. code-block:: bash24 salt myminion pip.install docker-compose>=1.5.025.. _docker-compose: https://pypi.python.org/pypi/docker-compose26.. _Docker: https://www.docker.com/27How to use this module?28-----------------------29In order to use the module if you have no docker-compose file on the server you30can issue the command create, it takes two arguments the path where the31docker-compose.yml will be stored and the content of this latter:32.. code-block:: bash33 # salt-call -l debug dockercompose.create /tmp/toto '34 database:35 image: mongo:3.036 command: mongod --smallfiles --quiet --logpath=/dev/null37 '38Then you can execute a list of method defined at the bottom with at least one39argument (the path where the docker-compose.yml will be read) and an optional40python list which corresponds to the services names:41.. code-block:: bash42 # salt-call -l debug dockercompose.up /tmp/toto43 # salt-call -l debug dockercompose.restart /tmp/toto '[database]'44 # salt-call -l debug dockercompose.stop /tmp/toto45 # salt-call -l debug dockercompose.rm /tmp/toto46Docker-compose method supported47-------------------------------48- up49- restart50- stop51- start52- pause53- unpause54- kill55- rm56- ps57- pull58- build59Functions60---------61- docker-compose.yml management62 - :py:func:`dockercompose.create <salt.modules.dockercompose.create>`63 - :py:func:`dockercompose.get <salt.modules.dockercompose.get>`64- Manage containers65 - :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`66 - :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`67 - :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`68 - :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`69 - :py:func:`dockercompose.start <salt.modules.dockercompose.start>`70 - :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`71 - :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`72 - :py:func:`dockercompose.up <salt.modules.dockercompose.up>`73- Manage containers image:74 - :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`75 - :py:func:`dockercompose.build <salt.modules.dockercompose.build>`76- Gather information about containers:77 - :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`78Detailed Function Documentation79-------------------------------80'''81from __future__ import absolute_import82import inspect83import logging84import os85import re86import salt.utils87from operator import attrgetter88try:89 import compose90 from compose.cli.command import get_project91 from compose.service import ConvergenceStrategy92 HAS_DOCKERCOMPOSE = True93except ImportError:94 HAS_DOCKERCOMPOSE = False95try:96 from compose.project import OneOffFilter97 USE_FILTERCLASS = True98except ImportError:99 USE_FILTERCLASS = False100MIN_DOCKERCOMPOSE = (1, 5, 0)101MAX_DOCKERCOMPOSE = (1, 9, 0)102VERSION_RE = r'([\d.]+)'103log = logging.getLogger(__name__)104debug = False105__virtualname__ = 'dockercompose'106dc_filename = 'docker-compose.yml'107def __virtual__():108 if HAS_DOCKERCOMPOSE:109 match = re.match(VERSION_RE, str(compose.__version__))110 if match:111 version = tuple([int(x) for x in match.group(1).split('.')])112 if version >= MIN_DOCKERCOMPOSE and version <= MAX_DOCKERCOMPOSE:113 return __virtualname__114 return (False, 'The dockercompose execution module not loaded: '115 'compose python library not available.')116def __standardize_result(status, message, data=None, debug_msg=None):117 '''118 Standardizes all responses119 :param status:120 :param message:121 :param data:122 :param debug_msg:123 :return:124 '''125 result = {126 'status': status,127 'message': message128 }129 if data is not None:130 result['return'] = data131 if debug_msg is not None and debug:132 result['debug'] = debug_msg133 return result134def __read_docker_compose(path):135 '''136 Read the docker-compose.yml file if it exists in the directory137 :param path:138 :return:139 '''140 if os.path.isfile(os.path.join(path, dc_filename)) is False:141 return __standardize_result(False,142 'Path does not exist or docker-compose.yml is not present',143 None, None)144 f = salt.utils.fopen(os.path.join(path, dc_filename), 'r')145 result = {'docker-compose.yml': ''}146 if f:147 for line in f:148 result['docker-compose.yml'] += line149 f.close()150 else:151 return __standardize_result(False, 'Could not read docker-compose.yml file.',152 None, None)153 return __standardize_result(True, 'Reading content of docker-compose.yml file',154 result, None)155def __write_docker_compose(path, docker_compose):156 '''157 Write docker-compose to a temp directory158 in order to use it with docker-compose ( config check )159 :param path:160 docker_compose161 contains the docker-compose file162 :return:163 '''164 if os.path.isdir(path) is False:165 os.mkdir(path)166 f = salt.utils.fopen(os.path.join(path, dc_filename), 'w')167 if f:168 f.write(docker_compose)169 f.close()170 else:171 return __standardize_result(False,172 'Could not write docker-compose file in {0}'.format(path),173 None, None)174 project = __load_project(path)175 if isinstance(project, dict):176 os.remove(os.path.join(path, dc_filename))177 return project178 return path179def __load_project(path):180 '''181 Load a docker-compose project from path182 :param path:183 :return:184 '''185 try:186 project = get_project(path)187 except Exception as inst:188 return __handle_except(inst)189 return project190def __handle_except(inst):191 '''192 Handle exception and return a standard result193 :param inst:194 :return:195 '''196 return __standardize_result(False,197 'Docker-compose command {0} failed'.198 format(inspect.stack()[1][3]),199 '{0}'.format(inst), None)200def _get_convergence_plans(project, service_names):201 '''202 Get action executed for each container203 :param project:204 :param service_names:205 :return:206 '''207 ret = {}208 plans = project._get_convergence_plans(project.get_services(service_names),209 ConvergenceStrategy.changed)210 for cont in plans:211 (action, container) = plans[cont]212 if action == 'create':213 ret[cont] = 'Creating container'214 elif action == 'recreate':215 ret[cont] = 'Re-creating container'216 elif action == 'start':217 ret[cont] = 'Starting container'218 elif action == 'noop':219 ret[cont] = 'Container is up to date'220 return ret221def get(path):222 '''223 Get the content of the docker-compose file into a directory224 path225 Path where the docker-compose file is stored on the server226 CLI Example:227 .. code-block:: bash228 salt myminion dockercompose.get /path/where/docker-compose/stored229 '''230 salt_result = __read_docker_compose(path)231 if not salt_result['status']:232 return salt_result233 project = __load_project(path)234 if isinstance(project, dict):235 salt_result['return']['valid'] = False236 else:237 salt_result['return']['valid'] = True238 return salt_result239def create(path, docker_compose):240 '''241 Create and validate a docker-compose file into a directory242 path243 Path where the docker-compose file will be stored on the server244 docker_compose245 docker_compose file246 CLI Example:247 .. code-block:: bash248 salt myminion dockercompose.create /path/where/docker-compose/stored content249 '''250 if docker_compose:251 ret = __write_docker_compose(path, docker_compose)252 if isinstance(ret, dict):253 return ret254 else:255 return __standardize_result(False,256 'Creating a docker-compose project failed, you must send a valid docker-compose file',257 None, None)258 return __standardize_result(True, 'Successfully created the docker-compose file', {'compose.base_dir': path}, None)259def pull(path, service_names=None):260 '''261 Pull image for containers in the docker-compose file, service_names is a262 python list, if omitted pull all images263 path264 Path where the docker-compose file is stored on the server265 service_names266 If specified will pull only the image for the specified services267 CLI Example:268 .. code-block:: bash269 salt myminion dockercompose.pull /path/where/docker-compose/stored270 salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'271 '''272 project = __load_project(path)273 if isinstance(project, dict):274 return project275 else:276 try:277 project.pull(service_names)278 except Exception as inst:279 return __handle_except(inst)280 return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',281 None, None)282def build(path, service_names=None):283 '''284 Build image for containers in the docker-compose file, service_names is a285 python list, if omitted build images for all containers. Please note286 that at the moment the module does not allow you to upload your Dockerfile,287 nor any other file you could need with your docker-compose.yml, you will288 have to make sure the files you need are actually in the directory specified289 in the `build` keyword290 path291 Path where the docker-compose file is stored on the server292 service_names293 If specified will pull only the image for the specified services294 CLI Example:295 .. code-block:: bash296 salt myminion dockercompose.build /path/where/docker-compose/stored297 salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'298 '''299 project = __load_project(path)300 if isinstance(project, dict):301 return project302 else:303 try:304 project.build(service_names)305 except Exception as inst:306 return __handle_except(inst)307 return __standardize_result(True, 'Building containers images via docker-compose succeeded',308 None, None)309def restart(path, service_names=None):310 '''311 Restart container(s) in the docker-compose file, service_names is a python312 list, if omitted restart all containers313 path314 Path where the docker-compose file is stored on the server315 service_names316 If specified will restart only the specified services317 CLI Example:318 .. code-block:: bash319 salt myminion dockercompose.restart /path/where/docker-compose/stored320 salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'321 '''322 project = __load_project(path)323 debug_ret = {}324 result = {}325 if isinstance(project, dict):326 return project327 else:328 try:329 project.restart(service_names)330 if debug:331 for container in project.containers():332 if service_names is None or container.get('Name')[1:] in service_names:333 container.inspect_if_not_inspected()334 debug_ret[container.get('Name')] = container.inspect()335 result[container.get('Name')] = 'restarted'336 except Exception as inst:337 return __handle_except(inst)338 return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)339def stop(path, service_names=None):340 '''341 Stop running containers in the docker-compose file, service_names is a python342 list, if omitted stop all containers343 path344 Path where the docker-compose file is stored on the server345 service_names346 If specified will stop only the specified services347 CLI Example:348 .. code-block:: bash349 salt myminion dockercompose.stop /path/where/docker-compose/stored350 salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'351 '''352 project = __load_project(path)353 debug_ret = {}354 result = {}355 if isinstance(project, dict):356 return project357 else:358 try:359 project.stop(service_names)360 if debug:361 for container in project.containers(stopped=True):362 if service_names is None or container.get('Name')[1:] in service_names:363 container.inspect_if_not_inspected()364 debug_ret[container.get('Name')] = container.inspect()365 result[container.get('Name')] = 'stopped'366 except Exception as inst:367 return __handle_except(inst)368 return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)369def pause(path, service_names=None):370 '''371 Pause running containers in the docker-compose file, service_names is a python372 list, if omitted pause all containers373 path374 Path where the docker-compose file is stored on the server375 service_names376 If specified will pause only the specified services377 CLI Example:378 .. code-block:: bash379 salt myminion dockercompose.pause /path/where/docker-compose/stored380 salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'381 '''382 project = __load_project(path)383 debug_ret = {}384 result = {}385 if isinstance(project, dict):386 return project387 else:388 try:389 project.pause(service_names)390 if debug:391 for container in project.containers():392 if service_names is None or container.get('Name')[1:] in service_names:393 container.inspect_if_not_inspected()394 debug_ret[container.get('Name')] = container.inspect()395 result[container.get('Name')] = 'paused'396 except Exception as inst:397 return __handle_except(inst)398 return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)399def unpause(path, service_names=None):400 '''401 Un-Pause containers in the docker-compose file, service_names is a python402 list, if omitted unpause all containers403 path404 Path where the docker-compose file is stored on the server405 service_names406 If specified will un-pause only the specified services407 CLI Example:408 .. code-block:: bash409 salt myminion dockercompose.pause /path/where/docker-compose/stored410 salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'411 '''412 project = __load_project(path)413 debug_ret = {}414 result = {}415 if isinstance(project, dict):416 return project417 else:418 try:419 project.unpause(service_names)420 if debug:421 for container in project.containers():422 if service_names is None or container.get('Name')[1:] in service_names:423 container.inspect_if_not_inspected()424 debug_ret[container.get('Name')] = container.inspect()425 result[container.get('Name')] = 'unpaused'426 except Exception as inst:427 return __handle_except(inst)428 return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)429def start(path, service_names=None):430 '''431 Start containers in the docker-compose file, service_names is a python432 list, if omitted start all containers433 path434 Path where the docker-compose file is stored on the server435 service_names436 If specified will start only the specified services437 CLI Example:438 .. code-block:: bash439 salt myminion dockercompose.start /path/where/docker-compose/stored440 salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'441 '''442 project = __load_project(path)443 debug_ret = {}444 result = {}445 if isinstance(project, dict):446 return project447 else:448 try:449 project.start(service_names)450 if debug:451 for container in project.containers():452 if service_names is None or container.get('Name')[1:] in service_names:453 container.inspect_if_not_inspected()454 debug_ret[container.get('Name')] = container.inspect()455 result[container.get('Name')] = 'started'456 except Exception as inst:457 return __handle_except(inst)458 return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)459def kill(path, service_names=None):460 '''461 Kill containers in the docker-compose file, service_names is a python462 list, if omitted kill all containers463 path464 Path where the docker-compose file is stored on the server465 service_names466 If specified will kill only the specified services467 CLI Example:468 .. code-block:: bash469 salt myminion dockercompose.kill /path/where/docker-compose/stored470 salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'471 '''472 project = __load_project(path)473 debug_ret = {}474 result = {}475 if isinstance(project, dict):476 return project477 else:478 try:479 project.kill(service_names)480 if debug:481 for container in project.containers(stopped=True):482 if service_names is None or container.get('Name')[1:] in service_names:483 container.inspect_if_not_inspected()484 debug_ret[container.get('Name')] = container.inspect()485 result[container.get('Name')] = 'killed'486 except Exception as inst:487 return __handle_except(inst)488 return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)489def rm(path, service_names=None):490 '''491 Remove stopped containers in the docker-compose file, service_names is a python492 list, if omitted remove all stopped containers493 path494 Path where the docker-compose file is stored on the server495 service_names496 If specified will remove only the specified stopped services497 CLI Example:498 .. code-block:: bash499 salt myminion dockercompose.rm /path/where/docker-compose/stored500 salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'501 '''502 project = __load_project(path)503 if isinstance(project, dict):504 return project505 else:506 try:507 project.remove_stopped(service_names)508 except Exception as inst:509 return __handle_except(inst)510 return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)511def ps(path):512 '''513 List all running containers and report some information about them514 path515 Path where the docker-compose file is stored on the server516 CLI Example:517 .. code-block:: bash518 salt myminion dockercompose.ps /path/where/docker-compose/stored519 '''520 project = __load_project(path)521 result = {}522 if isinstance(project, dict):523 return project524 else:525 if USE_FILTERCLASS:526 containers = sorted(527 project.containers(None, stopped=True) +528 project.containers(None, OneOffFilter.only),529 key=attrgetter('name'))530 else:531 containers = sorted(532 project.containers(None, stopped=True) +533 project.containers(None, one_off=True),534 key=attrgetter('name'))535 for container in containers:536 command = container.human_readable_command537 if len(command) > 30:538 command = '{0} ...'.format(command[:26])539 result[container.name] = {540 'id': container.id,541 'name': container.name,542 'command': command,543 'state': container.human_readable_state,544 'ports': container.human_readable_ports,545 }546 return __standardize_result(True, 'Listing docker-compose containers', result, None)547def up(path, service_names=None):548 '''549 Create and start containers defined in the the docker-compose.yml file550 located in path, service_names is a python list, if omitted create and551 start all containers552 path553 Path where the docker-compose file is stored on the server554 service_names555 If specified will create and start only the specified services556 CLI Example:557 .. code-block:: bash558 salt myminion dockercompose.up /path/where/docker-compose/stored559 salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'560 '''561 debug_ret = {}562 project = __load_project(path)563 if isinstance(project, dict):564 return project565 else:566 try:567 result = _get_convergence_plans(project, service_names)568 ret = project.up(service_names)569 if debug:570 for container in ret:571 if service_names is None or container.get('Name')[1:] in service_names:572 container.inspect_if_not_inspected()573 debug_ret[container.get('Name')] = container.inspect()574 except Exception as inst:575 return __handle_except(inst)...

Full Screen

Full Screen

runners.py

Source:runners.py Github

copy

Full Screen

...25 self.service_map = {}26 self.config = config27 self.container_cls = get_container_cls(config)28 @property29 def service_names(self):30 return self.service_map.keys()31 @property32 def containers(self):33 return self.service_map.values()34 def add_service(self, cls):35 """ Add a service class to the runner.36 There can only be one service class for a given service name.37 Service classes must be registered before calling start()38 将服务类添加到runner。39 给定服务名称只能有一个服务类。40 必须在调用start()方法之前注册服务类41 """42 service_name = get_service_name(cls)43 container = self.container_cls(cls, self.config)...

Full Screen

Full Screen

services.py

Source:services.py Github

copy

Full Screen

1#2# License: BSD3# https://raw.github.com/robotics-in-concert/rocon_tools/license/LICENSE4#5##############################################################################6# Description7##############################################################################8"""9.. module:: services10 :platform: Unix11 :synopsis: Useful methods relating to ros services.12This module contains anything relating to introspection or manipulation13of ros services.14----15"""16##############################################################################17# Imports18##############################################################################19import rosgraph20import rospy21import socket22import time23from rosservice import ROSServiceIOException, get_service_headers24# Local imports25from .exceptions import NotFoundException26##############################################################################27# Find topics/services28##############################################################################29def service_is_available(service_name):30 '''31 Check whether the specific service is validated or not 32 as retrieving from master state.33 34 :param: str service_name service name checking validtation35 :returns: result of service's validation36 :rtype: bool37 '''38 master = rosgraph.Master(rospy.get_name())39 _, _, services = master.getSystemState()40 is_available = False41 for srv_name, unused_node_name in services:42 if service_name == srv_name:43 is_available = True44 break45 return is_available46def find_service(service_type, timeout=rospy.rostime.Duration(5.0), unique=False):47 '''48 Do a lookup to find services of the type49 specified. This will raise exceptions if it times out or returns50 multiple values. It can apply the additional logic of whether this should51 return a single unique result, or a list. Under the hood this calls out to the ros master for a list52 of registered services and it parses that to determine the result. If nothing53 is found, it loops around internally on a 10Hz loop until the result is54 found or the specified timeout is reached.55 Usage:56 .. code-block:: python57 from rocon_python_comms import find_service58 try:59 service_name = rocon_python_comms.find_service('rocon_interaction_msgs/SetInteractions',60 timeout=rospy.rostime.Duration(15.0),61 unique=True)62 except rocon_python_comms.NotFoundException as e:63 rospy.logwarn("failed to find the set_interactions service.")64 :param str service_type: service type specification, e.g. concert_msgs/GetInteractions65 :param rospy.Duration timeout: raise an exception if nothing is found before this timeout occurs.66 :param bool unique: flag to select the lookup behaviour (single/multiple results)67 :returns: the fully resolved name of the service (unique) or list of names (non-unique)68 :rtype: str69 :raises: :exc:`.NotFoundException`70 '''71 # we could use rosservice_find here, but that throws exceptions and aborts if it comes72 # across any rosservice on the system which is no longer valid. To be robust against this73 # I've just pulled the internals of rosservice_find (ugh its fugly) and replicated it here74 # with the only difference in that I continue over that exception.75 unique_service_name = None76 service_names = []77 timeout_time = time.time() + timeout.to_sec()78 master = rosgraph.Master(rospy.get_name())79 while not rospy.is_shutdown() and time.time() < timeout_time and not service_names:80 services_information = []81 try:82 _, _, services = master.getSystemState()83 for service_name, unused_node_name in services:84 service_uri = master.lookupService(service_name)85 services_information.append((service_name, service_uri))86 except (rosgraph.masterapi.Error, rosgraph.masterapi.Failure, socket.error) as e:87 raise NotFoundException("unable to communicate with the master [%s]" % str(e))88 for (service_name, service_uri) in services_information:89 try:90 next_service_type = get_service_headers(service_name, service_uri).get('type', None)91 except ROSServiceIOException: # should also catch socket.error?92 # ignore this - it is usually a sign of a bad service that could be thrown93 # up by somebody else and not what we're trying to find. If we can skip past it94 # here we can be robust to other people's problems.95 continue96 if next_service_type == service_type:97 service_names.append(service_name)98 if unique:99 if len(service_names) > 1:100 raise NotFoundException("multiple services found %s." % service_names)101 elif len(service_names) == 1:102 unique_service_name = service_names[0]103 if not service_names:104 rospy.rostime.wallsleep(0.1)105 if not service_names:106 raise NotFoundException("timed out")...

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 localstack 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