query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| negatives
listlengths 19
20
| metadata
dict |
---|---|---|---|
Describes available AWS services in a prefix list format, which includes the prefix list name and prefix list ID of the service and the IP address range for the service. A prefix list ID is required for creating an outbound security group rule that allows traffic from a VPC to access an AWS service through a VPC endpoint.
|
def describe_prefix_lists(DryRun=None, PrefixListIds=None, Filters=None, MaxResults=None, NextToken=None):
pass
|
[
"def services(self):\n _log.debug('get service list')\n result = self._requestJSON('services', '')\n return self._getKey(result, 'name')",
"def list_services(ctx):\n\n ctx.respond(ctx._(\"I am running: {services}\").format(\n services=\", \".join(ctx.bot.services))\n )",
"def get_ip_prefixes(config, services):\n\n ip_prefixes = set()\n\n for service in services:\n ip_prefixes.add(config[service]['ip_prefix'])\n\n return ip_prefixes",
"def CustomServiceNames(self) -> ServiceNameCollection:",
"def view_prefix_list(username, password, host) -> None:\r\n\r\n # Get prefix-list configuration\r\n prefix_lists = get_prefix_list(username, password, host)\r\n\r\n for prefix_list in prefix_lists[0]:\r\n print(prefix_list.get(\"name\"))\r\n lists = is_instance(prefix_list[\"seq\"])\r\n for sequence in lists:\r\n action = is_permit_or_deny(sequence)\r\n print(sequence.get(\"no\"), action, sequence[action].get(\"ip\"), sequence[action].get(\"ge\", \"\"), sequence[action].get(\"le\", \"\"))\r\n print(\"\\n\")",
"def service_names(self):\n return self.services.keys()",
"async def list_prefix(self, ctx):\n\n _prefix = '\\n'.join(['myst pls ', 'myst '])\n\n if await self.dbp[str(ctx.guild.id)].find().count() <= 0:\n return await ctx.send(f'**My assigned prefixes for your server:**\\n\\n{_prefix}')\n\n prefixes = [x['_id'] async for x in self.dbp[str(ctx.guild.id)].find()]\n\n pages = SimplePaginator(title='Prefixes',\n ctx=ctx, bot=self.bot,\n colour=0x886aff,\n entries=prefixes,\n prepend='**•** - ',\n append='',\n footer='You may also mention me.')\n await pages.embed_creator()",
"def test_prefixes_list(self):\n pass",
"def get_services_to_k8s_namespaces_to_allowlist(\n service_list: List[str], cluster: str, soa_dir: str, kube_client: KubeClient\n) -> Dict[\n str, # service\n Dict[\n str, # namespace\n Optional[Set[str]], # allowlist of secret names, None means allow all.\n ],\n]:\n services_to_k8s_namespaces_to_allowlist: Dict[\n str, Dict[str, Optional[Set[str]]]\n ] = defaultdict(dict)\n\n for service in service_list:\n if service == \"_shared\":\n # _shared is handled specially for each service.\n continue\n\n config_loader = PaastaServiceConfigLoader(service, soa_dir)\n for service_instance_config in config_loader.instance_configs(\n cluster=cluster, instance_type_class=KubernetesDeploymentConfig\n ):\n secrets_used, shared_secrets_used = get_secrets_used_by_instance(\n service_instance_config\n )\n allowlist = services_to_k8s_namespaces_to_allowlist[service].setdefault(\n service_instance_config.get_namespace(),\n set(),\n )\n if allowlist is not None:\n allowlist.update(secrets_used)\n\n if \"_shared\" in service_list:\n shared_allowlist = services_to_k8s_namespaces_to_allowlist[\n \"_shared\"\n ].setdefault(\n service_instance_config.get_namespace(),\n set(),\n )\n if shared_allowlist is not None:\n shared_allowlist.update(shared_secrets_used)\n\n for instance_type in INSTANCE_TYPES:\n if instance_type == \"kubernetes\":\n continue # handled above.\n\n instances = get_service_instance_list(\n service=service,\n instance_type=instance_type,\n cluster=cluster,\n soa_dir=soa_dir,\n )\n if instances:\n # Currently, all instance types besides kubernetes use one big namespace, defined in\n # INSTANCE_TYPE_TO_K8S_NAMESPACE. Sync all shared secrets and all secrets belonging to any service\n # which uses that instance type.\n\n services_to_k8s_namespaces_to_allowlist[service][\n INSTANCE_TYPE_TO_K8S_NAMESPACE[instance_type]\n ] = None\n if \"_shared\" in service_list:\n services_to_k8s_namespaces_to_allowlist[\"_shared\"][\n INSTANCE_TYPE_TO_K8S_NAMESPACE[instance_type]\n ] = None\n\n return dict(services_to_k8s_namespaces_to_allowlist)",
"def services_all(ctx):\n ctx.run(KUBERNETES_GET_SERVICES_ALL_CMD)",
"def list_prefixes(self, bucket_name=None, prefix='', delimiter='', \n page_size=None, max_items=None):\n pass \n # calls self.get_conn().get_paginator",
"def describe_services(\n ecs, cluster: str, services: typing.Set[str]\n) -> typing.List[typing.Dict[str, typing.Any]]:\n result: typing.List[typing.Dict[str, typing.Any]] = []\n services_list = list(services)\n for i in range(0, len(services_list), 10):\n response = ecs.describe_services(\n cluster=cluster, services=services_list[i : i + 10]\n )\n result.extend(response[\"services\"])\n return result",
"def hs_list(args):\n for hs in get_hidden_services():\n print args.fmt.replace(r'\\t', '\\t') % hs",
"def test_services_list(self):\n pass",
"def getServiceNames(self):\n self.send_getServiceNames()\n return self.recv_getServiceNames()",
"def do_service_list(cs, args):\r\n result = cs.services.list(host=args.host, binary=args.binary)\r\n columns = [\"Binary\", \"Host\", \"Zone\", \"Status\", \"State\", \"Updated_at\"]\r\n # NOTE(jay-lau-513): we check if the response has disabled_reason\r\n # so as not to add the column when the extended ext is not enabled.\r\n if result and hasattr(result[0], 'disabled_reason'):\r\n columns.append(\"Disabled Reason\")\r\n if result:\r\n print 'OKKKKKKKKK'\r\n utils.print_list(result, columns)",
"def _get_services_container_names(self):\n services = {}\n sellables = set(os.listdir(Two1Composer.SERVICES_DIR)).intersection(\n set(Two1Composer.GRID_SERVICES))\n for service in sellables:\n services[service] = \"sell_\" + service\n return services",
"def __get_pod_service_list(pod_items):\n out_names = set()\n for pod_item in pod_items:\n if pod_item.spec.service_account:\n out_names.add(pod_item.spec.service_account)\n else:\n out_names.add(pod_item.metadata.name)\n return out_names",
"def parse_services(self):\n #Client\n for item in self.client_config.get(\"services\"):\n service = Service(item[\"name\"],type=item[\"type\"],parameters=item)\n self.client_services_list.append(service) \n\n #Server\n for item in self.server_config.get(\"services\"):\n service = Service(item[\"name\"],type=item[\"type\"],parameters=item)\n self.server_services_list.append(service)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more regions that are currently available to you. For a list of the regions supported by Amazon EC2, see Regions and Endpoints .
|
def describe_regions(DryRun=None, RegionNames=None, Filters=None):
pass
|
[
"def get_us_aws_regions():\n try:\n resp = boto3.client('ec2').describe_regions()\n return [reg['RegionName'] for reg in resp['Regions'] if 'us-' in reg['RegionName']]\n except BaseException as err:\n print_err(err)",
"def regions():\n from boto.directconnect.layer1 import DirectConnectConnection\n return get_regions('directconnect', connection_cls=DirectConnectConnection)",
"def aws_regions():\n regions = boto_queries.describe_regions()\n region_names = []\n for region in regions:\n region_names.append(region[\"RegionName\"])\n return region_names",
"def ex_list_regions(self):\r\n list_regions = []\r\n request = '/regions'\r\n response = self.connection.request(request, method='GET').object\r\n list_regions = [self._to_region(r) for r in response['items']]\r\n return list_regions",
"def ListRegionFunc(self):\n return self.api.addresses.list",
"def get_regions(boto_cfg: Config = None) -> List[str]:\n ec2 = boto3.client('ec2') if boto_cfg == None else boto3.client('ec2', config=boto_cfg)\n try:\n return [r['RegionName'] for r in ec2.describe_regions()['Regions']]\n except ClientError as err:\n logging.debug(err)\n return []",
"def test_vmware_service_resources_regions_get(self):\n pass",
"def allowed_regions(self) -> pulumi.Output[Sequence[str]]:\n return pulumi.get(self, \"allowed_regions\")",
"def test_azure_service_api_regions_get(self):\n pass",
"def test_list_available_regions(self):\n subscription_client = mock.MagicMock()\n subscription_id = \"subscription ID\"\n\n result = self.subscription_service.list_available_regions(subscription_client=subscription_client,\n subscription_id=subscription_id)\n\n self.assertIsInstance(result, list)\n subscription_client.subscriptions.list_locations.assert_called_once_with(subscription_id)",
"def regions(self):\n url = self.base_url + 'nodes?hierarchy=%2A'\n headers = {'Authorization': 'Bearer {}'.format(self.auth())}\n r = requests.get(url, headers=headers)\n df = pd.read_json(r.content, orient='records')\n return pd.Series(df['name'].unique(), name='region')",
"def get_available_regions(service):\n s = boto3.session.Session()\n return s.get_available_regions(service)",
"def describe_availability_zones(region, credential):\n with aws_credential_provider(region, credential):\n client = boto3.client(\"ec2\", region_name=region)\n return client.describe_availability_zones(\n Filters=[\n {\"Name\": \"region-name\", \"Values\": [str(region)]},\n {\"Name\": \"zone-type\", \"Values\": [\"availability-zone\"]},\n ]\n ).get(\"AvailabilityZones\")",
"def allocated_regions(self) -> Sequence[str]:\n return pulumi.get(self, \"allocated_regions\")",
"def allowed_regions(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:\n return pulumi.get(self, \"allowed_regions\")",
"def regions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['WorkerPoolRegionsItem']]]]:\n return pulumi.get(self, \"regions\")",
"def process_regions(region_list): \n\n for region in region_list['Regions']:\n\n spinner.update()\n\n region_name = region['RegionName']\n\n if not args.region_prefixes == None:\n good_region = False\n for region_prefix in args.region_prefixes[0].split(','):\n if region_name.startswith(region_prefix.lower()):\n good_region = True\n break\n if not good_region:\n continue\n\n region_client = boto3.client('ec2', region_name=region_name)\n\n process_zones(region_name, boto3.resource('ec2', region_name=region_name), region_client.describe_availability_zones())",
"def get_region(self):\n try:\n return self.meta_data['placement'][\n 'availability-zone'][:-1].strip()\n except KeyError:\n raise IcsMetaException(\n \"Cannot find the 'region info' in meta-data.\")",
"def get_availability_zones_for(region: str) -> List[str]:\n check_aws_region_for_invalid_characters(region)\n ec2 = boto3.client('ec2', region_name=region)\n try:\n response = ec2.describe_availability_zones(Filters=[{'Name':'region-name', 'Values': [region]}])\n return [r['ZoneName'] for r in response['AvailabilityZones']]\n except ClientError as err:\n logging.debug(err)\n return []"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of the Reserved Instances that you purchased. For more information about Reserved Instances, see Reserved Instances in the Amazon Elastic Compute Cloud User Guide .
|
def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):
pass
|
[
"def getReservedInstances(verbose):\n lres = {}\n jResp = EC2C.describe_reserved_instances()\n for reserved in jResp['ReservedInstances']:\n if reserved['State'] == 'active':\n if verbose:\n lres[reserved['InstanceType']] = str(reserved['Start'])+\";\"+\\\n str(reserved['End'])+\";\"+\\\n str(reserved['InstanceCount'])+\";\"+\\\n reserved['ProductDescription']+\";\"+\\\n str(reserved['UsagePrice'])\n else:\n if re.search(\"win\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"windows\"\n elif re.search(\"red hat\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"redhat\"\n elif re.search(\"suse\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"suse\"\n else:\n os = \"linux\"\n lres[reserved['InstanceType']+\";\"+os] = str(reserved['InstanceCount'])\n return lres",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCount=None, OfferingClass=None):\n pass",
"def purchase_reserved_instances_offering(DryRun=None, ReservedInstancesOfferingId=None, InstanceCount=None, LimitPrice=None):\n pass",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def ex_list_reserved_nodes(self):\r\n params = {'Action': 'DescribeReservedInstances'}\r\n\r\n response = self.connection.request(self.path, params=params).object\r\n\r\n return self._to_reserved_nodes(response, 'reservedInstancesSet/item')",
"def list_instances(ec2):\n\n reservations = ec2.describe_instances(\n Filters=[\n {'Name': 'tag-key', 'Values': ['backup', 'Backup']},\n ]\n )['Reservations']\n\n instances = sum(\n [\n [i for i in r['Instances']]\n for r in reservations\n ], [])\n\n return instances",
"def modify_reserved_instances(ClientToken=None, ReservedInstancesIds=None, TargetConfigurations=None):\n pass",
"def get_listing():\n\n ec2 = boto3.client('ec2')\n listing = []\n\n try:\n full_listing = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ 'running' ]\n }\n ],\n MaxResults=1000)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n for reservation in full_listing['Reservations']:\n for instance in reservation['Instances']:\n listing.append(instance)\n\n return listing",
"def showinstances():\n username, conn = _getbotoconn(auth_user)\n\n print \"all instances running under the %s account\" % username\n\n num_running = 0\n reservations = conn.get_all_instances()\n for reservation in reservations:\n num_running += _print_reservation(reservation)\n\n return num_running",
"def describe_reserved_instances_modifications(ReservedInstancesModificationIds=None, NextToken=None, Filters=None):\n pass",
"def optimizeReservation(verbose,region):\n print(\"WARNING: As it's not possible to get OS through AWS API, All \"\\\n \"Linux are reported as Linux (no RedHat, Suse, etc)\\n\"\\\n \"This issue will be address in a future update\\n\\n\")\n shouldReserved = {}\n dreserved = getReservedInstances(False)\n dinstances = listInstances(False)\n dflavors = getInstanceTypes(region)\n count_by_type_os = countInstanceByTypeByOS(False, dinstances)\n resp = \"\"\n for typos, nb in count_by_type_os.items():\n if typos in dreserved:\n if int(count_by_type_os[typos]) - int(dreserved[typos]) >= 0:\n count_by_type_os[typos] = int(count_by_type_os[typos]) - int(dreserved[typos])\n resp += \"Reservation fully used for \"+typos+\"\\n\"\n else:\n print(\"Reservation not fully used for \"+typos+\": \"+dreserved[typos]+\"reserved but only \"+count_by_type_os[typos]+\" instances\")\n for typos, nb in dreserved.items():\n if typos not in count_by_type_os:\n resp += \"Reservation is not used for \"+typos+\"\\n\"\n #Provide tips for better reservations\n #Begin by removing instances that have reservation\n for instanceId in list(dinstances):\n if dinstances[instanceId]['flavor'] in dreserved:\n if int(dreserved[dinstances[instanceId]['flavor']]) > 0:\n dreserved[dinstances[instanceId]['flavor']] -= 1\n del dinstances[instanceId]\n today = datetime.datetime.now(datetime.timezone.utc)\n months6 = today-datetime.timedelta(days=180)\n for k, v in dinstances.items():\n if v['LaunchTime'] < months6:\n try:\n shouldReserved[v['flavor']+\";\"+v['platform']] += 1\n except:\n shouldReserved[v['flavor']+\";\"+v['platform']] = 1\n resp += \"\\nBased on instances older than 6 months, you should buy following reservations:\\n\"\n saveno, savepa = 0, 0\n for k, v in shouldReserved.items():\n resp += k+\":\"+str(v)+\"\\n\"\n saveno += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1yno'])) * v\n savepa += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1ypa'])) * v\n resp += \"You can save up to \"+str(saveno)+\"$/hour with no upfront reservation\\n\"\n resp += \"You can save up to \"+str(savepa)+\"$/hour with partial upfront reservation\\n\"\n if verbose:\n resp += \"\\nInstances below doesn't have reservation:\\n\"\n for k, v in count_by_type_os.items():\n resp += k+\":\"+str(v)+\"\\n\"\n return saveno, resp",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def _print_reservation(reservation):\n num_running = 0\n for inst in reservation.instances:\n if inst.state != u'running':\n continue\n print \"ID: %s\" % inst.id\n print \"state: %s\" % inst.state\n print \"IP: %s\" % inst.ip_address\n print \"private IP: %s\" % inst.private_ip_address\n print \"DNS: %s\" % inst.public_dns_name\n print \"private DNS: %s\" % inst.private_dns_name\n print \"architecture: %s\" % inst.architecture\n print \"image ID: %s\" % inst.image_id\n print \"class: %s\" % inst.instance_class\n print \"type: %s\" % inst.instance_type\n print \"key_name: %s\" % inst.key_name\n print \"launch time: %s\" % inst.launch_time\n print \"\"\n num_running += 1\n\n return num_running",
"def describe_ec2_instances(ec2, ec2_filter):\r\n tmp_instances = []\r\n instances = []\r\n resp = ec2.describe_instances(Filters=ec2_filter)\r\n for res in resp['Reservations']:\r\n tmp_instances.extend(res['Instances'])\r\n while 'NextToken' in resp:\r\n resp = ec2.describe_instances(Filters=ec2_filter,\r\n NextToken=resp['NextToken'])\r\n for res in resp['Reservations']:\r\n tmp_instances.extend(res['Instances'])\r\n\r\n for inst in tmp_instances:\r\n instances.append({'InstanceId': inst['InstanceId'],\r\n 'State': inst['State'],\r\n 'BlockDeviceMappings': inst['BlockDeviceMappings'],\r\n 'AttemptCount': 0,\r\n 'Tags': inst['Tags']})\r\n return instances",
"def test_list_instances(self):\n # Run test to list available instances\n instances = self.RSD.list_instances()\n\n # Confirm the result matches the internal list\n self.assertEqual(instances, {self.inst1.uuid: self.inst1})",
"def do_printInstances(self,args):\n parser = CommandArgumentParser(\"printInstances\")\n parser.add_argument(dest='filters',nargs='*',default=[\"*\"],help='Filter instances');\n parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');\n parser.add_argument('-t','--tags',action='store_true',dest='tags',help='list all instance tags');\n parser.add_argument('-d','--allDetails',action='store_true',dest='details',help='print all instance details');\n parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');\n parser.add_argument('-z','--zones',dest='availabilityZones',nargs='+',help='Only include specified availability zones');\n args = vars(parser.parse_args(args))\n \n client = AwsConnectionFactory.getEc2Client()\n\n filters = args['filters']\n addresses = args['addresses']\n tags = args['tags']\n details = args['details']\n availabilityZones = args['availabilityZones']\n needDescription = addresses or tags or details\n\n if args['refresh']:\n self.scalingGroupDescription = self.client.describe_auto_scaling_groups(AutoScalingGroupNames=[self.scalingGroup])\n \n # print \"AutoScaling Group:{}\".format(self.scalingGroup)\n print \"=== Instances ===\"\n instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']\n\n instances = filter( lambda x: fnmatches(x['InstanceId'],filters),instances)\n if availabilityZones:\n instances = filter( lambda x: fnmatches(x['AvailabilityZone'],availabilityZones),instances)\n \n index = 0\n for instance in instances:\n instance['index'] = index\n print \"* {0:3d} {1} {2} {3}\".format(index,instance['HealthStatus'],instance['AvailabilityZone'],instance['InstanceId'])\n description = None\n if needDescription:\n description = client.describe_instances(InstanceIds=[instance['InstanceId']])\n if addresses:\n networkInterfaces = description['Reservations'][0]['Instances'][0]['NetworkInterfaces']\n number = 0\n print \" Network Interfaces:\"\n for interface in networkInterfaces:\n print \" * {0:3d} {1}\".format(number, interface['PrivateIpAddress'])\n number +=1\n if tags:\n tags = description['Reservations'][0]['Instances'][0]['Tags']\n print \" Tags:\"\n for tag in tags:\n print \" * {0} {1}\".format(tag['Key'],tag['Value'])\n if details:\n pprint(description)\n \n index += 1",
"def getReservations():\n from commands import getstatusoutput\n cmd = \"scontrol -o show reservation\"\n\n output = filter(None, getstatusoutput(cmd)[1].split(\"\\n\"))\n\n return [Slurm.Reservation(each) for each in output]",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the modifications made to your Reserved Instances. If no parameter is specified, information about all your Reserved Instances modification requests is returned. If a modification ID is specified, only information about the specific modification is returned. For more information, see Modifying Reserved Instances in the Amazon Elastic Compute Cloud User Guide.
|
def describe_reserved_instances_modifications(ReservedInstancesModificationIds=None, NextToken=None, Filters=None):
pass
|
[
"def get_modification(self) -> str:\n return self._root[\"Modification\"]",
"def modification_id(self, modification_id):\n\n self._modification_id = modification_id",
"def modified(object, *descriptions):",
"def changes(self) -> List[str]:\n output: List[str] = []\n if self.status() is self.UNMODIFIED:\n output = [self.formatter % (\" \", self.key, self.old_value)]\n elif self.status() is self.ADDED:\n output.append(self.formatter % (\"+\", self.key, self.new_value))\n elif self.status() is self.REMOVED:\n output.append(self.formatter % (\"-\", self.key, self.old_value))\n elif self.status() is self.MODIFIED:\n output.append(self.formatter % (\"-\", self.key, self.old_value))\n output.append(self.formatter % (\"+\", self.key, self.new_value))\n return output",
"def describe_change_set(self, change_set_name):\n self.logger.debug(\n \"%s - Describing Change Set '%s'\", self.stack.name, change_set_name\n )\n return self.connection_manager.call(\n service=\"cloudformation\",\n command=\"describe_change_set\",\n kwargs={\n \"ChangeSetName\": change_set_name,\n \"StackName\": self.stack.external_name,\n },\n )",
"def _ConvertNicDiskModifications(mods):\n result = []\n\n for (identifier, params) in mods:\n if identifier == constants.DDM_ADD:\n # Add item as last item (legacy interface)\n action = constants.DDM_ADD\n identifier = -1\n elif identifier == constants.DDM_ATTACH:\n # Attach item as last item (legacy interface)\n action = constants.DDM_ATTACH\n identifier = -1\n elif identifier == constants.DDM_REMOVE:\n # Remove last item (legacy interface)\n action = constants.DDM_REMOVE\n identifier = -1\n elif identifier == constants.DDM_DETACH:\n # Detach last item (legacy interface)\n action = constants.DDM_DETACH\n identifier = -1\n else:\n # Modifications and adding/attaching/removing/detaching at arbitrary\n # indices\n add = params.pop(constants.DDM_ADD, _MISSING)\n attach = params.pop(constants.DDM_ATTACH, _MISSING)\n remove = params.pop(constants.DDM_REMOVE, _MISSING)\n detach = params.pop(constants.DDM_DETACH, _MISSING)\n modify = params.pop(constants.DDM_MODIFY, _MISSING)\n\n # Check if the user has requested more than one operation and raise an\n # exception. If no operations have been given, default to modify.\n action = constants.DDM_MODIFY\n ops = {\n constants.DDM_ADD: add,\n constants.DDM_ATTACH: attach,\n constants.DDM_REMOVE: remove,\n constants.DDM_DETACH: detach,\n constants.DDM_MODIFY: modify,\n }\n count = 0\n for op, param in ops.items():\n if param is not _MISSING:\n count += 1\n action = op\n if count > 1:\n raise errors.OpPrereqError(\n \"Cannot do more than one of the following operations at the\"\n \" same time: %s\" % \", \".join(ops.keys()),\n errors.ECODE_INVAL)\n\n assert not (constants.DDMS_VALUES_WITH_MODIFY & set(params.keys()))\n\n if action in (constants.DDM_REMOVE, constants.DDM_DETACH) and params:\n raise errors.OpPrereqError(\"Not accepting parameters on removal/detach\",\n errors.ECODE_INVAL)\n\n result.append((action, identifier, params))\n\n return result",
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def apply_modify(cal: Calendar, modify: dict) -> Calendar:\n\n cal = modify_time(cal, modify)\n cal = modify_text(cal, modify, \"name\")\n cal = modify_text(cal, modify, \"description\")\n cal = modify_text(cal, modify, \"location\")\n return cal",
"def get_modification_count(self):\n ret_val = self._get_modification_count()\n return ret_val",
"def modification_date(self):\n return self._moment.get(\"modificationDate\")",
"def modification_time(self):\n ret = self._get_attr(\"modificationTime\")\n return ret",
"def changes(self, tv_id, start_date=None, end_date=None, page=1):\n params = \"page=%s\" % page\n if start_date:\n params += \"&start_date=%s\" % start_date\n if end_date:\n params += \"&end_date=%s\" % end_date\n return self._request_obj(\n self._urls[\"changes\"] % tv_id,\n params=params,\n key=\"changes\"\n )",
"def modify_parameters(\n self,\n request: gpdb_20160503_models.ModifyParametersRequest,\n ) -> gpdb_20160503_models.ModifyParametersResponse:\n runtime = util_models.RuntimeOptions()\n return self.modify_parameters_with_options(request, runtime)",
"def get_modifitication_date_time(self):\n return self._root[\"ModificationDateTime\"]",
"def modify_volume_snapshot(self, snapshot_id, name=None, description=None,\n expiration_timestamp=None):\n LOG.info(\"Modifying volume snapshot: '%s'\" % snapshot_id)\n payload = self._prepare_create_modify_snapshot_payload(\n name=name, description=description,\n expiration_timestamp=expiration_timestamp\n )\n self.rest_client.request(\n constants.PATCH,\n constants.MODIFY_VOLUME_URL.format(self.server_ip, snapshot_id),\n payload\n )\n return self.get_volume_snapshot_details(snapshot_id)",
"def modificationsIncludingKickstartFile(self, _kickstartFileContent):\n modifications = []\n return modifications",
"def modification_changed(self, state=None, index=None, editor_id=None):\n if editor_id is not None:\n for index, _finfo in enumerate(self.data):\n if id(_finfo.editor) == editor_id:\n break\n # This must be done before refreshing save/save all actions:\n # (otherwise Save/Save all actions will always be enabled)\n self.emit(SIGNAL('opened_files_list_changed()'))\n # --\n if index is None:\n index = self.get_stack_index()\n if index == -1:\n return\n finfo = self.data[index]\n if state is None:\n state = finfo.editor.document().isModified()\n self.set_stack_title(index, state)\n # Toggle save/save all actions state\n self.save_action.setEnabled(state)\n self.emit(SIGNAL('refresh_save_all_action()'))\n # Refreshing eol mode\n eol_chars = finfo.editor.get_line_separator()\n os_name = sourcecode.get_os_name_from_eol_chars(eol_chars)\n self.emit(SIGNAL('refresh_eol_chars(QString)'), os_name)",
"def get_affect_names(self):\n return self.affects.keys()",
"def description(self, description=None, persister=None):\n persister.exec_stmt(Group.UPDATE_GROUP,\n {\"params\":(description, self.__group_id)})\n self.__description = description"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes Reserved Instance offerings that are available for purchase. With Reserved Instances, you purchase the right to launch instances for a period of time. During that time period, you do not receive insufficient capacity errors, and you pay a lower usage rate than the rate charged for OnDemand instances for the actual time used. If you have listed your own Reserved Instances for sale in the Reserved Instance Marketplace, they will be excluded from these results. This is to ensure that you do not purchase your own Reserved Instances. For more information, see Reserved Instance Marketplace in the Amazon Elastic Compute Cloud User Guide .
|
def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCount=None, OfferingClass=None):
pass
|
[
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def getReservedInstances(verbose):\n lres = {}\n jResp = EC2C.describe_reserved_instances()\n for reserved in jResp['ReservedInstances']:\n if reserved['State'] == 'active':\n if verbose:\n lres[reserved['InstanceType']] = str(reserved['Start'])+\";\"+\\\n str(reserved['End'])+\";\"+\\\n str(reserved['InstanceCount'])+\";\"+\\\n reserved['ProductDescription']+\";\"+\\\n str(reserved['UsagePrice'])\n else:\n if re.search(\"win\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"windows\"\n elif re.search(\"red hat\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"redhat\"\n elif re.search(\"suse\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"suse\"\n else:\n os = \"linux\"\n lres[reserved['InstanceType']+\";\"+os] = str(reserved['InstanceCount'])\n return lres",
"def purchase_reserved_instances_offering(DryRun=None, ReservedInstancesOfferingId=None, InstanceCount=None, LimitPrice=None):\n pass",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def optimizeReservation(verbose,region):\n print(\"WARNING: As it's not possible to get OS through AWS API, All \"\\\n \"Linux are reported as Linux (no RedHat, Suse, etc)\\n\"\\\n \"This issue will be address in a future update\\n\\n\")\n shouldReserved = {}\n dreserved = getReservedInstances(False)\n dinstances = listInstances(False)\n dflavors = getInstanceTypes(region)\n count_by_type_os = countInstanceByTypeByOS(False, dinstances)\n resp = \"\"\n for typos, nb in count_by_type_os.items():\n if typos in dreserved:\n if int(count_by_type_os[typos]) - int(dreserved[typos]) >= 0:\n count_by_type_os[typos] = int(count_by_type_os[typos]) - int(dreserved[typos])\n resp += \"Reservation fully used for \"+typos+\"\\n\"\n else:\n print(\"Reservation not fully used for \"+typos+\": \"+dreserved[typos]+\"reserved but only \"+count_by_type_os[typos]+\" instances\")\n for typos, nb in dreserved.items():\n if typos not in count_by_type_os:\n resp += \"Reservation is not used for \"+typos+\"\\n\"\n #Provide tips for better reservations\n #Begin by removing instances that have reservation\n for instanceId in list(dinstances):\n if dinstances[instanceId]['flavor'] in dreserved:\n if int(dreserved[dinstances[instanceId]['flavor']]) > 0:\n dreserved[dinstances[instanceId]['flavor']] -= 1\n del dinstances[instanceId]\n today = datetime.datetime.now(datetime.timezone.utc)\n months6 = today-datetime.timedelta(days=180)\n for k, v in dinstances.items():\n if v['LaunchTime'] < months6:\n try:\n shouldReserved[v['flavor']+\";\"+v['platform']] += 1\n except:\n shouldReserved[v['flavor']+\";\"+v['platform']] = 1\n resp += \"\\nBased on instances older than 6 months, you should buy following reservations:\\n\"\n saveno, savepa = 0, 0\n for k, v in shouldReserved.items():\n resp += k+\":\"+str(v)+\"\\n\"\n saveno += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1yno'])) * v\n savepa += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1ypa'])) * v\n resp += \"You can save up to \"+str(saveno)+\"$/hour with no upfront reservation\\n\"\n resp += \"You can save up to \"+str(savepa)+\"$/hour with partial upfront reservation\\n\"\n if verbose:\n resp += \"\\nInstances below doesn't have reservation:\\n\"\n for k, v in count_by_type_os.items():\n resp += k+\":\"+str(v)+\"\\n\"\n return saveno, resp",
"def get_listing():\n\n ec2 = boto3.client('ec2')\n listing = []\n\n try:\n full_listing = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ 'running' ]\n }\n ],\n MaxResults=1000)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n for reservation in full_listing['Reservations']:\n for instance in reservation['Instances']:\n listing.append(instance)\n\n return listing",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def attemptPurchases(order):\n print(\"\\n\")\n # here we sort out the availability zones\n hasOrdersAssigned = True\n\n for az in order.AvailabilityZones:\n if az.ordered is None:\n az.ordered = 0\n if az.Number is None:\n hasOrdersAssigned = False\n\n if hasOrdersAssigned == False:\n remainder = int(order.Number) % len(order.AvailabilityZones)\n eachOrderGets = int((int(order.Number) - remainder) /\n len(order.AvailabilityZones))\n # here we assign all the orders\n for az in order.AvailabilityZones:\n az.Number = eachOrderGets\n if remainder != 0:\n az.Number += 1\n remainder -= 1\n\n # this client can be used for all the az's\n print(order.Region)\n client = boto3.client('ec2', region_name=order.Region,aws_access_key_id=order.aws_access_key_id,aws_secret_access_key=order.aws_secret_access_key)\n for az in order.AvailabilityZones:\n\n # for each AZ we're buying from\n kwargs = order.getKwargs(az.Name)\n response = client.describe_reserved_instances_offerings(**kwargs)\n ReservedInstancesOfferings = response[\"ReservedInstancesOfferings\"]\n\n # we search for all instance types, not just fixed or hourly, then sort when we recieve results\n # do the sorting of the reserved instances by price, cheapest first\n allOfferings = []\n\n # get all the offerings objects\n for instanceOffering in ReservedInstancesOfferings:\n # isFixed and isHourly completely filter out or in whether or not those instance types get included\n # if both are true, then all types of instances get included regardless of payment type\n\n # for limits, 0 means no limit, everything else abides by the limit\n\n iOffering = getInstanceOffering(instanceOffering)\n fixedPrice = iOffering.FixedPrice\n recurringAmount = iOffering.RecurringAmount\n fixedPriceExists = False\n recurringAmountExists = False\n\n if fixedPrice is not None and fixedPrice != 0:\n fixedPriceExists = True\n if recurringAmount is not None and recurringAmount != 0:\n recurringAmountExists = True\n\n MaxFixedPrice = 0\n if order.MaxFixedPrice is not None:\n MaxFixedPrice = order.MaxFixedPrice\n\n MaxRecurringPrice = 0\n if order.MaxHourlyPrice is not None:\n MaxRecurringPrice = order.MaxHourlyPrice\n\n if order.isFixedPrice == True and order.isHourlyPrice == True:\n # either hourly or fixed or both\n if fixedPriceExists and recurringAmountExists:\n if (MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice) and (MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice):\n allOfferings.append(iOffering)\n elif fixedPriceExists:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n elif recurringAmountExists:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n elif order.isFixedPrice == True:\n # only fixed price servers\n if fixedPriceExists and recurringAmountExists == False:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n\n elif order.isHourlyPrice == True:\n # only hourly servers\n if recurringAmountExists and fixedPriceExists == False:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n # sort into cost effectiveness, and these all have the correct AZ\n allOfferings.sort(key=lambda x: x.EffectiveHourlyRate)\n\n # print(order.Number)\n if order.Number is not None and order.Number > 0:\n if order.ordered is None:\n # brand new order bring it up to speed\n order.ordered = 0\n\n if az.ordered >= az.Number:\n print(\"AZ\", az.Name, \"has already been fulfilled with\",\n az.ordered, \"instances\")\n # buy until finished\n purchasedJustNow = 0\n previouslyPurchased = az.ordered\n for instanceOffering in allOfferings:\n # instanceOffering.print()\n # also we might want to write to the file, like keep it open, and update it for each order bought\n # something might go wrong\n # print(instanceOffering, \"\\n\")\n if order.ordered < order.Number and az.ordered < az.Number:\n # do purchase\n order.ordered += 1\n az.ordered += 1\n purchasedJustNow += 1\n instance = allOfferings.pop(0)\n kwargs = instance.getKwargs(order.DryRun)\n response = None\n try:\n response = client.purchase_reserved_instances_offering(\n **kwargs)\n print(response)\n except:\n pass\n print(\"Just Purchased:\")\n instanceOffering.print()\n order.PurchasedInstances.append(instanceOffering)\n\n if order.ordered >= order.Number or az.ordered >= az.Number:\n break\n\n print(purchasedJustNow,\n \"Reserved Instances were just purchased for:\", az.Name)\n print(previouslyPurchased, \"instances had been purchased previously\")\n if az.ordered >= az.Number:\n print(\"Purchased all\", az.ordered,\n \"Reserved Instances for:\", az.Name, \"\\n\")\n else:\n print(\"Still need\", int(az.Number - az.ordered), \"instances for availability zone:\",\n az.Name, \", will attempt to purchase the rest during the next run\", \"\\n\")\n\n if order.ordered >= order.Number:\n print(\"Purchased all\", order.ordered,\n \"Reserved Instances for this order\\n\\n\")\n else:\n print(\"Could only purchase\", order.ordered,\n \"Reserved Instances for this order, will attempt to purchase the rest at a later date.\\n\\n\")\n return",
"def ex_list_reserved_nodes(self):\r\n params = {'Action': 'DescribeReservedInstances'}\r\n\r\n response = self.connection.request(self.path, params=params).object\r\n\r\n return self._to_reserved_nodes(response, 'reservedInstancesSet/item')",
"def describe_reserved_instances_modifications(ReservedInstancesModificationIds=None, NextToken=None, Filters=None):\n pass",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def list_instances(ec2):\n\n reservations = ec2.describe_instances(\n Filters=[\n {'Name': 'tag-key', 'Values': ['backup', 'Backup']},\n ]\n )['Reservations']\n\n instances = sum(\n [\n [i for i in r['Instances']]\n for r in reservations\n ], [])\n\n return instances",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def _print_reservation(reservation):\n num_running = 0\n for inst in reservation.instances:\n if inst.state != u'running':\n continue\n print \"ID: %s\" % inst.id\n print \"state: %s\" % inst.state\n print \"IP: %s\" % inst.ip_address\n print \"private IP: %s\" % inst.private_ip_address\n print \"DNS: %s\" % inst.public_dns_name\n print \"private DNS: %s\" % inst.private_dns_name\n print \"architecture: %s\" % inst.architecture\n print \"image ID: %s\" % inst.image_id\n print \"class: %s\" % inst.instance_class\n print \"type: %s\" % inst.instance_type\n print \"key_name: %s\" % inst.key_name\n print \"launch time: %s\" % inst.launch_time\n print \"\"\n num_running += 1\n\n return num_running",
"def getReservations():\n from commands import getstatusoutput\n cmd = \"scontrol -o show reservation\"\n\n output = filter(None, getstatusoutput(cmd)[1].split(\"\\n\"))\n\n return [Slurm.Reservation(each) for each in output]",
"def showinstances():\n username, conn = _getbotoconn(auth_user)\n\n print \"all instances running under the %s account\" % username\n\n num_running = 0\n reservations = conn.get_all_instances()\n for reservation in reservations:\n num_running += _print_reservation(reservation)\n\n return num_running",
"def describe_host_reservation_offerings(OfferingId=None, MinDuration=None, MaxDuration=None, Filters=None, MaxResults=None, NextToken=None):\n pass",
"def do_printInstances(self,args):\n parser = CommandArgumentParser(\"printInstances\")\n parser.add_argument(dest='filters',nargs='*',default=[\"*\"],help='Filter instances');\n parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');\n parser.add_argument('-t','--tags',action='store_true',dest='tags',help='list all instance tags');\n parser.add_argument('-d','--allDetails',action='store_true',dest='details',help='print all instance details');\n parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');\n parser.add_argument('-z','--zones',dest='availabilityZones',nargs='+',help='Only include specified availability zones');\n args = vars(parser.parse_args(args))\n \n client = AwsConnectionFactory.getEc2Client()\n\n filters = args['filters']\n addresses = args['addresses']\n tags = args['tags']\n details = args['details']\n availabilityZones = args['availabilityZones']\n needDescription = addresses or tags or details\n\n if args['refresh']:\n self.scalingGroupDescription = self.client.describe_auto_scaling_groups(AutoScalingGroupNames=[self.scalingGroup])\n \n # print \"AutoScaling Group:{}\".format(self.scalingGroup)\n print \"=== Instances ===\"\n instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']\n\n instances = filter( lambda x: fnmatches(x['InstanceId'],filters),instances)\n if availabilityZones:\n instances = filter( lambda x: fnmatches(x['AvailabilityZone'],availabilityZones),instances)\n \n index = 0\n for instance in instances:\n instance['index'] = index\n print \"* {0:3d} {1} {2} {3}\".format(index,instance['HealthStatus'],instance['AvailabilityZone'],instance['InstanceId'])\n description = None\n if needDescription:\n description = client.describe_instances(InstanceIds=[instance['InstanceId']])\n if addresses:\n networkInterfaces = description['Reservations'][0]['Instances'][0]['NetworkInterfaces']\n number = 0\n print \" Network Interfaces:\"\n for interface in networkInterfaces:\n print \" * {0:3d} {1}\".format(number, interface['PrivateIpAddress'])\n number +=1\n if tags:\n tags = description['Reservations'][0]['Instances'][0]['Tags']\n print \" Tags:\"\n for tag in tags:\n print \" * {0} {1}\".format(tag['Key'],tag['Value'])\n if details:\n pprint(description)\n \n index += 1",
"def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your route tables. Each subnet in your VPC must be associated with a route table. If a subnet is not explicitly associated with any route table, it is implicitly associated with the main route table. This command does not return the subnet ID for implicit associations. For more information about route tables, see Route Tables in the Amazon Virtual Private Cloud User Guide .
|
def describe_route_tables(DryRun=None, RouteTableIds=None, Filters=None):
pass
|
[
"def describe_route_tables(\n route_table_id=None,\n route_table_name=None,\n vpc_id=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not any((route_table_id, route_table_name, tags, vpc_id)):\n raise SaltInvocationError(\n \"At least one of the following must be specified: \"\n \"route table id, route table name, vpc_id, or tags.\"\n )\n\n try:\n conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {\"Filters\": []}\n\n if route_table_id:\n filter_parameters[\"RouteTableIds\"] = [route_table_id]\n\n if vpc_id:\n filter_parameters[\"Filters\"].append({\"Name\": \"vpc-id\", \"Values\": [vpc_id]})\n\n if route_table_name:\n filter_parameters[\"Filters\"].append(\n {\"Name\": \"tag:Name\", \"Values\": [route_table_name]}\n )\n\n if tags:\n for tag_name, tag_value in tags.items():\n filter_parameters[\"Filters\"].append(\n {\"Name\": \"tag:{}\".format(tag_name), \"Values\": [tag_value]}\n )\n\n route_tables = conn3.describe_route_tables(**filter_parameters).get(\n \"RouteTables\", []\n )\n\n if not route_tables:\n return []\n\n tables = []\n keys = {\n \"id\": \"RouteTableId\",\n \"vpc_id\": \"VpcId\",\n \"tags\": \"Tags\",\n \"routes\": \"Routes\",\n \"associations\": \"Associations\",\n }\n route_keys = {\n \"destination_cidr_block\": \"DestinationCidrBlock\",\n \"gateway_id\": \"GatewayId\",\n \"instance_id\": \"Instance\",\n \"interface_id\": \"NetworkInterfaceId\",\n \"nat_gateway_id\": \"NatGatewayId\",\n \"vpc_peering_connection_id\": \"VpcPeeringConnectionId\",\n }\n assoc_keys = {\n \"id\": \"RouteTableAssociationId\",\n \"main\": \"Main\",\n \"route_table_id\": \"RouteTableId\",\n \"SubnetId\": \"subnet_id\",\n }\n for item in route_tables:\n route_table = {}\n for outkey, inkey in keys.items():\n if inkey in item:\n if outkey == \"routes\":\n route_table[outkey] = _key_remap(inkey, route_keys, item)\n elif outkey == \"associations\":\n route_table[outkey] = _key_remap(inkey, assoc_keys, item)\n elif outkey == \"tags\":\n route_table[outkey] = {}\n for tagitem in item.get(inkey, []):\n route_table[outkey][tagitem.get(\"Key\")] = tagitem.get(\n \"Value\"\n )\n else:\n route_table[outkey] = item.get(inkey)\n tables.append(route_table)\n return tables\n\n except BotoServerError as e:\n return {\"error\": __utils__[\"boto.get_error\"](e)}",
"def _get_subnet_explicit_route_table(\n subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None\n):\n if not conn:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if conn:\n vpc_route_tables = conn.get_all_route_tables(filters={\"vpc_id\": vpc_id})\n for vpc_route_table in vpc_route_tables:\n for rt_association in vpc_route_table.associations:\n if rt_association.subnet_id == subnet_id and not rt_association.main:\n return rt_association.id\n return None",
"def associate_route_table(\n route_table_id=None,\n subnet_id=None,\n route_table_name=None,\n subnet_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if all((subnet_id, subnet_name)):\n raise SaltInvocationError(\n \"Only one of subnet_name or subnet_id may be provided.\"\n )\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\", subnet_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not subnet_id:\n return {\n \"associated\": False,\n \"error\": {\"message\": \"Subnet {} does not exist.\".format(subnet_name)},\n }\n\n if all((route_table_id, route_table_name)):\n raise SaltInvocationError(\n \"Only one of route_table_name or route_table_id may be provided.\"\n )\n if route_table_name:\n route_table_id = _get_resource_id(\n \"route_table\",\n route_table_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not route_table_id:\n return {\n \"associated\": False,\n \"error\": {\n \"message\": \"Route table {} does not exist.\".format(route_table_name)\n },\n }\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n association_id = conn.associate_route_table(route_table_id, subnet_id)\n log.info(\n \"Route table %s was associated with subnet %s\", route_table_id, subnet_id\n )\n return {\"association_id\": association_id}\n except BotoServerError as e:\n return {\"associated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def _assert_nat_in_subnet_route(ec2_client, subnet_id):\n response = ec2_client.describe_route_tables(Filters=[{\"Name\": \"association.subnet-id\", \"Values\": [subnet_id]}])\n routes = response[\"RouteTables\"][0][\"Routes\"]\n assert_that(next(route for route in routes if route[\"DestinationCidrBlock\"] == \"0.0.0.0/0\")).contains(\n \"NatGatewayId\"\n )",
"def associate_route_table(DryRun=None, SubnetId=None, RouteTableId=None):\n pass",
"def list_tgw_routetable():\n client = boto3.client(\"ec2\")\n tgw_table = list()\n\n try:\n tables = client.describe_transit_gateway_route_tables()\n\n for table in tables[\"TransitGatewayRouteTables\"]:\n #tgw_table_name = (table[\"Tags\"][2].get(\"Value\"))\n tgw_table.append(table[\"TransitGatewayRouteTableId\"])\n\n except botocore.exceptionsClientError as error:\n print(error)\n\n return tgw_table",
"def _assert_internet_gateway_in_subnet_route(ec2_client, subnet_id, expected_internet_gateway_id):\n response = ec2_client.describe_route_tables(Filters=[{\"Name\": \"association.subnet-id\", \"Values\": [subnet_id]}])\n routes = response[\"RouteTables\"][0][\"Routes\"]\n internet_gateway_route = next(route for route in routes if route[\"DestinationCidrBlock\"] == \"0.0.0.0/0\")\n assert_that(internet_gateway_route).contains(\"GatewayId\")\n assert_that(internet_gateway_route[\"GatewayId\"]).is_equal_to(expected_internet_gateway_id)",
"def RoutingTable(self, instance):\n parsedRoutes = []\n instanceName = \"master\"\n if instance : \n instanceName = instance.Name\n # get route table size\n routeTableSize = self.RouteTableSize(instance)\n if routeTableSize > self._maxRouteTableEntries :\n # query only default route \n cmd = \"show route 0.0.0.0 inet.0\"\n if instanceName.lower() != \"master\" : cmd = \"show route 0.0.0.0 table {0}.inet.0\".format(instance.Name)\n else:\n # query inet.0 route table for the requested instance\n cmd = \"show route table inet.0\"\n if instanceName.lower() != \"master\" : cmd = \"show route table {0}.inet.0\".format(instance.Name)\n \n routes = Session.ExecCommand(cmd)\n # define regex expressions for logical text blocks\n networkBlockFilter = re.compile(r\"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\\/\\d{1,2}\")\n protocolBlockFilter = re.compile(r\"[*[](.*?)\\]\")\n # network blocks are the top level blocks of the text output, get the iterator for them\n networkBlockIterator = tuple(networkBlockFilter.finditer(routes))\n networkMatchcount = len(networkBlockIterator)\n networkMatchIndex = 0\n # iterate through the network blocks\n for thisNetworkMatch in networkBlockIterator:\n try:\n # thisNetworkMatch is now a MatchObject\n thisNetwork = thisNetworkMatch.group(0)\n # a route block is the text of routes between the position of this match start and the next match start\n routeBlockStart = thisNetworkMatch.start()\n routeBlockEnd = -1\n if (networkMatchIndex == networkMatchcount - 1):\n routeBlockEnd = len(routes)\n else:\n routeBlockEnd = networkBlockIterator[networkMatchIndex + 1].start()\n \n thisRouteBlock = routes[routeBlockStart : routeBlockEnd] \n # protocol blocks appear inside a network block, get the iterator for them\n protocolBlockIterator = tuple(protocolBlockFilter.finditer(thisRouteBlock))\n # process networks\n protocolMatchcount = len(protocolBlockIterator)\n protocolMatchIndex = 0\n # iterte through the protocol blocks\n for thisProtocolMatch in protocolBlockIterator:\n try:\n # thisProtocolMatch is now a MatchObject\n protocolBlockHeader = thisProtocolMatch.group(0)\n isBestRoute = \"*[\" in protocolBlockHeader\n protocolBlockStart = thisProtocolMatch.start()\n # a protocol block is the text portion in actual routeBlock between the position of this match start and the next match start\n protocolBlockStart = thisProtocolMatch.start()\n protocolBlockEnd = -1\n if (protocolMatchIndex == protocolMatchcount - 1):\n protocolBlockEnd = len(thisRouteBlock)\n else:\n protocolBlockEnd = protocolBlockIterator[protocolMatchIndex + 1].start() \n \n thisProtocolBlock = thisRouteBlock[protocolBlockStart : protocolBlockEnd]\n thisProtocolNames = re.findall(r\"[a-zA-Z,-]+\", protocolBlockHeader)\n nextHopAddresses = re.findall(r\"(?<=to )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n routeTags = re.findall(r\"(?<=tag )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n asPath = re.findall(r\"(?<=AS path:).[^,]*\",thisProtocolBlock, re.IGNORECASE)\n outInterfaces = re.findall(r\"(?<=via ).*\", thisProtocolBlock, re.IGNORECASE)\n leartFrom = re.findall(r\"(?<=from )[\\d\\.]{0,99}\", thisProtocolBlock, re.IGNORECASE)\n routePreference = re.findall(r\"[0-9]+\", protocolBlockHeader)\n \n matchIndex = 0\n for thisOutInterface in outInterfaces:\n rte = L3Discovery.RouteTableEntry()\n # Protocol\n if len(thisProtocolNames) == 1 : rte.Protocol = thisProtocolNames[0]\n else : rte.Protocol = \"UNKNOWN\"\n # RouterID\n rte.RouterID = self._ridCalculator.GetRouterID(rte.Protocol, instance)\n # Prefix and Mask length\n prefixAndMask = thisNetwork.split(\"/\")\n rte.Prefix = prefixAndMask[0]\n rte.MaskLength = int(prefixAndMask[1])\n # OutInterface\n rte.OutInterface = thisOutInterface\n # NextHop address\n if len(nextHopAddresses) > matchIndex : rte.NextHop = nextHopAddresses[matchIndex]\n else : rte.NextHop = \"\"\n # LeartFrom\n if len(leartFrom) == 1 : rte.From = leartFrom[0]\n else : rte.From = \"\"\n # Prefix parameters\n rte.Best = isBestRoute\n if len(routeTags) == 1 : rte.Tag = routeTags[0]\n else : rte.Tag = \"\"\n if len(routePreference) == 1 : rte.AD = routePreference[0]\n else : rte.AD = \"\"\n if len(asPath) == 1 : rte.ASPath = asPath[0]\n else : rte.ASPath = \"\"\n rte.Community = \"\"\n rte.Metric = \"\"\n parsedRoutes.Add(rte)\n matchIndex += 1\n \n protocolMatchIndex += 1\n except Exception as Ex:\n message = \"JunOS Router Module Error : could not parse a route table Protocol block because : \" + str(Ex)\n DebugEx.WriteLine(message) \n \n networkMatchIndex += 1\n except Exception as Ex:\n message = \"JunOS Router Module Error : could not parse a route table Network block because : \" + str(Ex)\n DebugEx.WriteLine(message)\n \n return parsedRoutes",
"def get_route_table(_ctx=ctx):\n return _ctx.node.properties.get('route_table_name') or \\\n get_ancestor_name(\n _ctx.instance, constants.REL_CONTAINED_IN_RT)",
"def create_route_entry(self, route_tables, vpc_id):\n params = {}\n results = []\n changed = False \n vrouter_table_id = None\n\n # Describe Vpc for getting VRouterId \n desc_vpc_param = {}\n self.build_list_params(desc_vpc_param, vpc_id, 'VpcId')\n desc_vpc_response = self.get_status('DescribeVpcs', desc_vpc_param)\n if int(desc_vpc_response[u'TotalCount']) > 0:\n vrouter_id = str(desc_vpc_response[u'Vpcs'][u'Vpc'][0][u'VRouterId']) \n\n # Describe Route Tables for getting RouteTable Id \n desc_route_table_param = {}\n self.build_list_params(desc_route_table_param, vrouter_id, 'VRouterId')\n desc_route_table_response = self.get_status('DescribeRouteTables', desc_route_table_param)\n if int(desc_route_table_response[u'TotalCount']) > 0:\n vrouter_table_id = str(desc_route_table_response[u'RouteTables'][u'RouteTable'][0][u'RouteTableId'])\n\n for vroute in route_tables:\n self.build_list_params(params, vrouter_table_id , 'RouteTableId') \n if \"next_hop_id\" in vroute:\n if (\"dest\" in vroute) or (\"destination_cidrblock\" in vroute):\n fixed_dest_cidr_block = None\n if 'dest' in vroute:\n fixed_dest_cidr_block = vroute[\"dest\"]\n if 'destination_cidrblock' in vroute:\n fixed_dest_cidr_block = vroute[\"destination_cidrblock\"]\n if fixed_dest_cidr_block:\n self.build_list_params(params, fixed_dest_cidr_block, 'DestinationCidrBlock')\n\n if 'next_hop_type' in vroute:\n self.build_list_params(params, vroute[\"next_hop_type\"], 'NextHopType')\n\n if 'next_hop_id' in vroute:\n self.build_list_params(params, vroute[\"next_hop_id\"], 'NextHopId')\n \n try:\n instance_result = self.get_instance_info()\n flag = False\n if instance_result:\n for instances in instance_result[0][u'Instances'][u'Instance']:\n if vroute[\"next_hop_id\"] == instances['InstanceId']:\n flag = True\n break\n if flag: \n response = self.get_status('CreateRouteEntry', params)\n results.append(response)\n changed = True\n time.sleep(10)\n else:\n results.append({\"Error Message\": str(vroute[\"next_hop_id\"])+\" Instance not found\"})\n except Exception as ex:\n error_code = ex.error_code\n error_msg = ex.message\n results.append({\"Error Code\": error_code, \"Error Message\": error_msg})\n else:\n results.append({\"Error Message\": \"destination_cidrblock is required to create custom route entry\"})\n else:\n results.append({\"Error Message\": \"next_hop_id is required to create custom route entry\"})\n else:\n results.append({\"Error Message\": \"vpc_id is not valid\"})\n \n return changed, results",
"def describe_subnet(\n subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None\n):\n try:\n subnet = _get_resource(\n \"subnet\",\n name=subnet_name,\n resource_id=subnet_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as e:\n return {\"error\": __utils__[\"boto.get_error\"](e)}\n\n if not subnet:\n return {\"subnet\": None}\n log.debug(\"Found subnet: %s\", subnet.id)\n\n keys = (\"id\", \"cidr_block\", \"availability_zone\", \"tags\", \"vpc_id\")\n ret = {\"subnet\": {k: getattr(subnet, k) for k in keys}}\n explicit_route_table_assoc = _get_subnet_explicit_route_table(\n ret[\"subnet\"][\"id\"],\n ret[\"subnet\"][\"vpc_id\"],\n conn=None,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if explicit_route_table_assoc:\n ret[\"subnet\"][\n \"explicit_route_table_association_id\"\n ] = explicit_route_table_assoc\n return ret",
"def configure_routing(vpc):\n internet_gateways = list(vpc.internet_gateways.all())\n if len(internet_gateways) == 1:\n internet_gateway = internet_gateways[0]\n elif len(internet_gateways) == 0:\n raise CraftingTableError(\"No internet gateway found\")\n else:\n raise CraftingTableError(f\"Multiple internet gateways found: {id_list(internet_gateways)}\")\n\n route_tables = list(vpc.route_tables.filter(Filters=[{\"Name\": \"association.main\", \"Values\": [\"true\"]}]))\n if len(route_tables) == 1:\n route_table = route_tables[0]\n elif len(route_tables) == 0:\n raise CraftingTableError(\"No route table found\")\n if len(route_tables) != 1:\n raise CraftingTableError(f\"Multiple route tables found: {id_list(route_tables)}\")\n\n for route in route_table.routes:\n if route.gateway_id == internet_gateway.id:\n break\n else:\n route_table.create_route(DestinationCidrBlock=\"0.0.0.0/0\", GatewayId=internet_gateway.id)\n click.echo(f\"Created default route to {internet_gateway.id}\")",
"def get_subnet_routing_table(self,\n id: str,\n **kwargs\n ) -> DetailedResponse:\n\n if id is None:\n raise ValueError('id must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='get_subnet_routing_table')\n headers.update(sdk_headers)\n\n params = {\n 'version': self.version,\n 'generation': self.generation\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n path_param_keys = ['id']\n path_param_values = self.encode_path_vars(id)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/subnets/{id}/routing_table'.format(**path_param_dict)\n request = self.prepare_request(method='GET',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response",
"def delete_route_tables():\n client = boto3.resource('ec2')\n print('Deleting Route Tables')\n for route_table in client.route_tables.all():\n for route in route_table.routes:\n if route.origin == 'CreateRoute':\n print('Deleting Route {} in Route Table {}'.format(route.destination_cidr_block,\n route_table.id))\n route.delete()\n main = False\n for rta in route_table.associations:\n if rta.main:\n main = True\n else:\n print('Deleting Route Table Association {}'.format(rta.id))\n rta.delete()\n if not main:\n print('Deleting Route Table {}'.format(route_table.id))\n route_table.delete()\n print('Route Tables deleted')",
"def add_subnet(tag_name, ip_part, route_table, az, realm):\n template_name = tag_name.title().replace('-', '')\n subnet = ec2.Subnet(\n template_name,\n VpcId=Ref(self.vpc),\n CidrBlock=_(Ref(self.vpc_base_net), \".{}.0/24\".format(ip_part)),\n AvailabilityZone=Select(az, GetAZs()),\n Tags=self.get_tags(tag_name, realm=realm)\n )\n subnet = self.t.add_resource(subnet)\n\n self.t.add_resource(ec2.SubnetRouteTableAssociation(\n \"{}RouteTableAssociation\".format(template_name),\n SubnetId=Ref(subnet),\n RouteTableId=Ref(route_table)\n ))\n\n return subnet",
"def describe_nat_gateways(\n nat_gateway_id=None,\n subnet_id=None,\n subnet_name=None,\n vpc_id=None,\n vpc_name=None,\n states=(\"pending\", \"available\"),\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n return _find_nat_gateways(\n nat_gateway_id=nat_gateway_id,\n subnet_id=subnet_id,\n subnet_name=subnet_name,\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n states=states,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )",
"def routing_table(ip, community, ci):\n ipRouteType = \"1.3.6.1.2.1.4.21.1.8\"\n ret = get_bulk(ip, ipRouteType, community)\n if ret != None:\n for r in ret:\n for name, val in r:\n ip = name.prettyPrint()[len(\"SNMPv2-SMI::mib-2.4.21.1.8.\"):]\n route_type = int(val.prettyPrint())\n\n # indirect(4)\n if route_type == 4:\n discovery_info.add_ip(ip)\n\n new_ci = ConfigurationItem.ConfigurationItem()\n new_ci.add_ipv4_address(ip)\n mac = discovery_info.get_mac_from_ip(ip)\n if mac != None:\n ci.set_mac_address(mac)\n\n rel_type = methods.add_rel_type(\n RelationshipType.RelationshipType(\"route to\"))\n rel_obj_1 = methods.create_relation(ci, new_ci, rel_type)\n rel_obj_1.set_title(str(ci.get_title()) +\n \" route to \" + str(new_ci.get_title()))\n\n rel_obj_2 = methods.create_relation(new_ci, ci, rel_type)\n rel_obj_2.set_title(str(new_ci.get_title()) + \" route to \" +\n str(ci.get_title()))\n\n methods.add_ci(new_ci)\n methods.add_rel(rel_obj_1)\n methods.add_rel(rel_obj_2)\n\n # direct(3)\n elif route_type == 3:\n ci.add_ipv4_address(ip)\n # discovery_info.add_ip(ip)",
"def getAllroutes(asn, add_query_params=''):\n #ipaddress.IPv4Network, ipaddress.IPv6Network\n results = ASNOrigin.lookup(asn, add_query_params=add_query_params)\n return [ipaddress.ip_network(_net['cidr']) for _net in results['nets']]",
"def _assert_nat_in_subnet(ec2_client, subnet_id):\n response = ec2_client.describe_nat_gateways(Filters=[{\"Name\": \"subnet-id\", \"Values\": [subnet_id]}])\n assert_that(len(response[\"NatGateways\"])).is_greater_than(0)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your Scheduled Instances.
|
def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):
pass
|
[
"def describe(self):\n print(Controller().describe_instances())",
"def run_scheduled_instances(DryRun=None, ClientToken=None, InstanceCount=None, ScheduledInstanceId=None, LaunchSpecification=None):\n pass",
"def report_instance_status(DryRun=None, Instances=None, Status=None, StartTime=None, EndTime=None, ReasonCodes=None, Description=None):\n pass",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def do_printInstances(self,args):\n parser = CommandArgumentParser(\"printInstances\")\n parser.add_argument(dest='filters',nargs='*',default=[\"*\"],help='Filter instances');\n parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');\n parser.add_argument('-t','--tags',action='store_true',dest='tags',help='list all instance tags');\n parser.add_argument('-d','--allDetails',action='store_true',dest='details',help='print all instance details');\n parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');\n parser.add_argument('-z','--zones',dest='availabilityZones',nargs='+',help='Only include specified availability zones');\n args = vars(parser.parse_args(args))\n \n client = AwsConnectionFactory.getEc2Client()\n\n filters = args['filters']\n addresses = args['addresses']\n tags = args['tags']\n details = args['details']\n availabilityZones = args['availabilityZones']\n needDescription = addresses or tags or details\n\n if args['refresh']:\n self.scalingGroupDescription = self.client.describe_auto_scaling_groups(AutoScalingGroupNames=[self.scalingGroup])\n \n # print \"AutoScaling Group:{}\".format(self.scalingGroup)\n print \"=== Instances ===\"\n instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']\n\n instances = filter( lambda x: fnmatches(x['InstanceId'],filters),instances)\n if availabilityZones:\n instances = filter( lambda x: fnmatches(x['AvailabilityZone'],availabilityZones),instances)\n \n index = 0\n for instance in instances:\n instance['index'] = index\n print \"* {0:3d} {1} {2} {3}\".format(index,instance['HealthStatus'],instance['AvailabilityZone'],instance['InstanceId'])\n description = None\n if needDescription:\n description = client.describe_instances(InstanceIds=[instance['InstanceId']])\n if addresses:\n networkInterfaces = description['Reservations'][0]['Instances'][0]['NetworkInterfaces']\n number = 0\n print \" Network Interfaces:\"\n for interface in networkInterfaces:\n print \" * {0:3d} {1}\".format(number, interface['PrivateIpAddress'])\n number +=1\n if tags:\n tags = description['Reservations'][0]['Instances'][0]['Tags']\n print \" Tags:\"\n for tag in tags:\n print \" * {0} {1}\".format(tag['Key'],tag['Value'])\n if details:\n pprint(description)\n \n index += 1",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def print_formatted_instances(running_instances) -> None:\n BASIC_FORMAT = \"{:^3} {:^20} {:^20} {:^20}\"\n headers = ['#', 'ID', 'Public IPv4', 'Launch Datetime']\n print(BASIC_FORMAT.format(*headers))\n print(BASIC_FORMAT.format(*[\"-\" * len(i) for i in headers]))\n for i, instance in enumerate(running_instances):\n print(BASIC_FORMAT.format(\n *[i + 1, instance.id, instance.public_ip_address, instance.launch_time.strftime(\"%Y/%m/%d %H:%M:%S\")])\n )",
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def list() -> None:\n config = load_config_file()\n running_instances = get_running_instances(config)\n print_formatted_instances(running_instances)\n logging.info('Done!')",
"def showinstances():\n username, conn = _getbotoconn(auth_user)\n\n print \"all instances running under the %s account\" % username\n\n num_running = 0\n reservations = conn.get_all_instances()\n for reservation in reservations:\n num_running += _print_reservation(reservation)\n\n return num_running",
"def test__AutoModerationEventType__name():\n for instance in AutoModerationEventType.INSTANCES.values():\n vampytest.assert_instance(instance.name, str)",
"def list(ctx):\r\n config = ctx.obj['config']\r\n config.validate()\r\n host = config.get_active_host()\r\n instances = host.get_instances()\r\n logger.info(\"Instances on: %s\", host.name)\r\n outputters.table([x.dump() for x in instances])",
"def name(self) -> str:\n return f\"{self._schedule_name} Schedule\"",
"def scheduling(self) -> Optional[pulumi.Input['InstanceTemplateSchedulingArgs']]:\n return pulumi.get(self, \"scheduling\")",
"def list_schedules(self) -> Iterator[ScheduledGraph]:\n pass",
"def scheduled_tasks():\n\n return render_template('admin/scheduled_tasks.html')",
"def get_instance_names(self):\r\n return [r.name for r in self.get_instances()]",
"def _print_reservation(reservation):\n num_running = 0\n for inst in reservation.instances:\n if inst.state != u'running':\n continue\n print \"ID: %s\" % inst.id\n print \"state: %s\" % inst.state\n print \"IP: %s\" % inst.ip_address\n print \"private IP: %s\" % inst.private_ip_address\n print \"DNS: %s\" % inst.public_dns_name\n print \"private DNS: %s\" % inst.private_dns_name\n print \"architecture: %s\" % inst.architecture\n print \"image ID: %s\" % inst.image_id\n print \"class: %s\" % inst.instance_class\n print \"type: %s\" % inst.instance_type\n print \"key_name: %s\" % inst.key_name\n print \"launch time: %s\" % inst.launch_time\n print \"\"\n num_running += 1\n\n return num_running",
"def test_jenkins_autoscaling_schedules_set(self) -> None:\n self.assertTrue(all([\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-morning',\n recurrence='0 11 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-morning',\n recurrence='0 12 * * *',\n max_size=0,\n min_size=0,\n desired_size=0),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-evening',\n recurrence='0 22 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-evening',\n recurrence='0 23 * * *',\n max_size=0,\n min_size=0,\n desired_size=0\n )\n ]))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your security groups. A security group is for use with instances either in the EC2Classic platform or in a specific VPC. For more information, see Amazon EC2 Security Groups in the Amazon Elastic Compute Cloud User Guide and Security Groups for Your VPC in the Amazon Virtual Private Cloud User Guide .
|
def describe_security_groups(DryRun=None, GroupNames=None, GroupIds=None, Filters=None):
pass
|
[
"def getsecuritygroups(show):\n securitygrouplist=[]\n \n try:\n securitygroups=ec2.describe_security_groups()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting security group data: \\n\\n\\n\")\n print(e)\n for securitygroup in securitygroups['SecurityGroups']:\n name=securitygroup['GroupName']\n \n gid=securitygroup['GroupId']\n description=securitygroup['Description']\n if show:\n print(\"name: \"+name+\" Descripton: \"+ description)\n securitygrouplist.append({ \"name\":gid})\n return securitygrouplist",
"def describe_security_groups(self, xml_bytes):\n root = XML(xml_bytes)\n result = []\n for group_info in root.findall(\"securityGroupInfo/item\"):\n id = group_info.findtext(\"groupId\")\n name = group_info.findtext(\"groupName\")\n description = group_info.findtext(\"groupDescription\")\n owner_id = group_info.findtext(\"ownerId\")\n allowed_groups = []\n allowed_ips = []\n ip_permissions = group_info.find(\"ipPermissions\")\n if ip_permissions is None:\n ip_permissions = ()\n for ip_permission in ip_permissions:\n\n # openstack doesn't handle self authorized groups properly\n # XXX this is an upstream problem and should be addressed there\n # lp bug #829609\n ip_protocol = ip_permission.findtext(\"ipProtocol\")\n from_port = ip_permission.findtext(\"fromPort\")\n to_port = ip_permission.findtext(\"toPort\")\n\n if from_port:\n from_port = int(from_port)\n\n if to_port:\n to_port = int(to_port)\n\n for groups in ip_permission.findall(\"groups/item\") or ():\n user_id = groups.findtext(\"userId\")\n group_name = groups.findtext(\"groupName\")\n if user_id and group_name:\n if (user_id, group_name) not in allowed_groups:\n allowed_groups.append((user_id, group_name))\n for ip_ranges in ip_permission.findall(\"ipRanges/item\") or ():\n cidr_ip = ip_ranges.findtext(\"cidrIp\")\n allowed_ips.append(\n model.IPPermission(\n ip_protocol, from_port, to_port, cidr_ip))\n\n allowed_groups = [model.UserIDGroupPair(user_id, group_name)\n for user_id, group_name in allowed_groups]\n\n security_group = model.SecurityGroup(\n id, name, description, owner_id=owner_id,\n groups=allowed_groups, ips=allowed_ips)\n result.append(security_group)\n return result",
"def validate_security_groups(sg_spec):\n exit_if_none(sg_spec, \"Missing security groups\")\n actual_sgs = {}\n paginator = boto3.client('ec2').get_paginator('describe_security_groups')\n for page in paginator.paginate():\n for sg in page['SecurityGroups']:\n actual_sgs[sg['GroupId']] = sg.get('VpcId') # some people may still have non-VPC groups\n security_groups = []\n vpcs = set()\n for sg_id in sg_spec.split(\",\"):\n vpc_id = actual_sgs.get(sg_id)\n exit_if_none(vpc_id, f\"invalid security group: {sg_id}\")\n security_groups.append(sg_id)\n vpcs.add(vpc_id)\n if (len(vpcs) > 1):\n exit_if_none(None, \"security groups belong to different VPCs\")\n return security_groups",
"def describe_placement_groups(DryRun=None, GroupNames=None, Filters=None):\n pass",
"def get_security_group_details(ec2_client, security_group_id: str) -> dict:\n response = ec2_client\\\n .describe_security_groups(GroupIds=[security_group_id])\n return response['SecurityGroups'][0]",
"def get_ec2_security_groups(self):\n ec2_client = self.session.client('ec2')\n instances = ec2_client.describe_instances()\n reservations = instances['Reservations']\n\n for reservation in reservations:\n for instance in reservation['Instances']:\n self.ec2_instances_count += 1\n for group in instance['SecurityGroups']:\n self.security_groups_in_use.add(group['GroupId'])",
"def security_group(self) -> aws_cdk.aws_ec2.ISecurityGroup:\n return self._values.get('security_group')",
"def create_security_group():\n conn = boto.connect_ec2()\n sec_group = conn.create_security_group(\"shopply\", \"Shopply servers security group\")\n sec_group.authorize('tcp', 80, 80, '0.0.0.0/0')\n sec_group.authorize('tcp', 22, 22, '0.0.0.0/0')\n sec_group.authorize('tcp', 8080, 8080, '0.0.0.0/0')\n sec_group.authorize('tcp', 9001, 9001, '0.0.0.0/0')",
"def ex_list_security_groups(self):\r\n params = {'Action': 'DescribeSecurityGroups'}\r\n response = self.connection.request(self.path, params=params).object\r\n\r\n groups = []\r\n for group in findall(element=response, xpath='securityGroupInfo/item',\r\n namespace=NAMESPACE):\r\n name = findtext(element=group, xpath='groupName',\r\n namespace=NAMESPACE)\r\n groups.append(name)\r\n\r\n return groups",
"def create_security_group(self, context, sg):\n # vnc_openstack does not allow to create default security group\n if sg.get('name') == 'default':\n sg['name'] = 'default-openstack'\n sg['description'] = 'default-openstack security group'\n sec_g = {'security_group': sg}\n try:\n self.drv.create_security_group(context, sec_g)\n except Exception:\n LOG.exception('Failed to create Security Group %s' % sg)",
"def test_vmware_service_resources_security_groups_get(self):\n pass",
"def delete_security_groups():\n print('Deleting Security Groups')\n client = boto3.resource('ec2')\n for security_group in client.security_groups.all():\n print('Deleting Security Group rules for security group {}'.format(security_group.id))\n for perm in security_group.ip_permissions:\n security_group.revoke_ingress(\n IpPermissions=[perm]\n )\n for perm in security_group.ip_permissions_egress:\n security_group.revoke_egress(\n IpPermissions=[perm]\n )\n for security_group in client.security_groups.all():\n if security_group.group_name != 'default':\n print('Deleting Security Group {}'.format(security_group.id))\n security_group.delete()\n print('Security Groups deleted')",
"def create_http_security_group(sg_name, options):\n\n sg_desc = \"Security group to be applied to any spot instance running our schedule jobs\"\n\n client = boto3.client('ec2',\n aws_access_key_id=options['aws_access_key_id'],\n aws_secret_access_key=options['aws_secret_access_key'])\n\n # First verify if such a SG already exists. If so, just return its id\n try:\n response = client.describe_security_groups(GroupNames=[sg_name])\n return response[\"SecurityGroups\"][0][\"GroupId\"]\n\n except botocore.exceptions.NoCredentialsError:\n print \"AWS credentials failed\"\n sys.exit(3)\n\n except botocore.exceptions.ClientError as e: # If there's no sg with such name\n\n # Credentials wrong?\n if e.response['Error']['Code'] == 'AuthFailure':\n print \"AWS credentials failed\"\n sys.exit(3)\n\n # Create a new group and save its id\n response = client.create_security_group(\n GroupName=sg_name, Description=sg_desc)\n sg_id = response[\"GroupId\"]\n\n # Add the rules\n response = client.authorize_security_group_ingress(GroupId=sg_id, IpPermissions=[\n {'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80,\n 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}])\n\n # Return the SG id\n return sg_id",
"def ex_list_security_groups(self):\r\n return self._to_security_groups(\r\n self.connection.request('/os-security-groups').object)",
"def test_create_list_sec_grp_no_rules(self):\n sec_grp_settings = SecurityGroupConfig(\n name=self.sec_grp_name + \"-1\", description='hello group')\n self.security_groups.append(neutron_utils.create_security_group(\n self.neutron, self.keystone, sec_grp_settings))\n\n sec_grp_settings2 = SecurityGroupConfig(\n name=self.sec_grp_name + \"-2\", description='hola group')\n self.security_groups.append(neutron_utils.create_security_group(\n self.neutron, self.keystone, sec_grp_settings2))\n\n returned_sec_groups = neutron_utils.list_security_groups(self.neutron)\n\n self.assertIsNotNone(returned_sec_groups)\n worked = 0\n for sg in returned_sec_groups:\n if sec_grp_settings.name == sg.name:\n worked += 1\n elif sec_grp_settings2.name == sg.name:\n worked += 1\n\n self.assertEqual(worked, 2)",
"def cli(env, group_id, name, description):\n mgr = SoftLayer.NetworkManager(env.client)\n data = {}\n if name:\n data['name'] = name\n if description:\n data['description'] = description\n\n if not mgr.edit_securitygroup(group_id, **data):\n raise exceptions.CLIAbort(\"Failed to edit security group\")",
"def test_list_security_groups(self):\n admin_resource_id = self.secgroup['id']\n with (self.override_role_and_validate_list(\n admin_resource_id=admin_resource_id)) as ctx:\n ctx.resources = self.security_groups_client.list_security_groups(\n id=admin_resource_id)[\"security_groups\"]",
"def _init_security_group(self):\n # Get list of security groups\n # Checks if Key pairs exists, like for key pairs\n # needs case insensitive names check\n ec2_client = self._session.client('ec2')\n with _ExceptionHandler.catch():\n security_groups = ec2_client.describe_security_groups()\n\n name_lower = self._security_group.lower()\n group_exists = False\n security_group_id = ''\n for security_group in security_groups['SecurityGroups']:\n group_name = security_group['GroupName']\n if group_name.lower() == name_lower:\n # Update name\n self._security_group = group_name\n\n # Get group ID\n security_group_id = security_group['GroupId']\n\n # Mark as existing\n group_exists = True\n break\n\n # Try to create security group if not exist\n if not group_exists:\n # Get VPC\n with _ExceptionHandler.catch():\n vpc_id = ec2_client.describe_vpcs().get(\n 'Vpcs', [{}])[0].get('VpcId', '')\n\n with _ExceptionHandler.catch():\n response = ec2_client.create_security_group(\n GroupName=self._security_group,\n Description=_utl.gen_msg('accelize_generated'),\n VpcId=vpc_id)\n\n # Get group ID\n security_group_id = response['GroupId']\n\n _get_logger().info(_utl.gen_msg(\n 'created_named', 'security group', security_group_id))\n\n # Add host IP to security group if not already done\n public_ip = _utl.get_host_public_ip()\n\n ip_permissions = []\n for port in self.ALLOW_PORTS:\n ip_permissions.append({\n 'IpProtocol': 'tcp', 'FromPort': port, 'ToPort': port,\n 'IpRanges': [{'CidrIp': public_ip}]})\n\n with _ExceptionHandler.catch(\n filter_error_codes='InvalidPermission.Duplicate'):\n ec2_client.authorize_security_group_ingress(\n GroupId=security_group_id,\n IpPermissions=ip_permissions)\n\n _get_logger().info(\n _utl.gen_msg('authorized_ip', public_ip, self._security_group))",
"def groups(region):\n return [group.name for group in\n connect_to_region(region).get_all_security_groups()]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. For more information about EBS snapshots, see Amazon EBS Snapshots in the Amazon Elastic Compute Cloud User Guide .
|
def describe_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None):
pass
|
[
"def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):\n pass",
"def setSnapshotAttribute(self, snapshot: 'char const *') -> \"void\":\n return _coin.ScXMLAnchorElt_setSnapshotAttribute(self, snapshot)",
"def describe_volume_attribute(DryRun=None, VolumeId=None, Attribute=None):\n pass",
"def describe_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def tag_snapshot(ec2, snap_id, label):\n\n ec2.create_tags(\n Resources=(snap_id,),\n Tags=[\n {'Key': 'DeleteOn', 'Value': label},\n ])\n print \"Creating tag for snap %s with %s label!\" % ( snap_id, label )",
"def describe_attr_value(attr, die, section_offset):\r\n descr_func = _ATTR_DESCRIPTION_MAP[attr.form]\r\n val_description = descr_func(attr, die, section_offset)\r\n\r\n # For some attributes we can display further information\r\n extra_info_func = _EXTRA_INFO_DESCRIPTION_MAP[attr.name]\r\n extra_info = extra_info_func(attr, die, section_offset)\r\n return str(val_description) + '\\t' + extra_info",
"def getSnapshotAttribute(self) -> \"char const *\":\n return _coin.ScXMLAnchorElt_getSnapshotAttribute(self)",
"def test_edit_volume_snapshot(self, snapshot, volumes_steps_ui):\n new_snapshot_name = snapshot.name + '(updated)'\n with snapshot.put(name=new_snapshot_name):\n volumes_steps_ui.update_snapshot(snapshot.name, new_snapshot_name)",
"def make_snapshot(ec2,vol,retention,description):\n\n snap = ec2.create_snapshot(VolumeId=vol,Description=description)\n return snap",
"def Attributes(self) -> _n_5_t_17:",
"def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):\n pass",
"def modify_volume_snapshot(self, snapshot_id, name=None, description=None,\n expiration_timestamp=None):\n LOG.info(\"Modifying volume snapshot: '%s'\" % snapshot_id)\n payload = self._prepare_create_modify_snapshot_payload(\n name=name, description=description,\n expiration_timestamp=expiration_timestamp\n )\n self.rest_client.request(\n constants.PATCH,\n constants.MODIFY_VOLUME_URL.format(self.server_ip, snapshot_id),\n payload\n )\n return self.get_volume_snapshot_details(snapshot_id)",
"def attr_summary(self):\n\n print(self._attr_repr())",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def showattribute(self, vname=None, device=None):\n if device is None:\n device = sys.stdout\n if vname is None:\n vname = self.default_variable_name\n device.write(\"Attributes of \")\n device.write(vname)\n device.write(\" in file \")\n device.write(self.id)\n device.write(\":\\n\")\n device.write(str(self.listattribute(vname)))\n device.write(\"\\n\")",
"def match_vol_details(self, snapshot):\n vol_name = self.module.params['vol_name']\n vol_id = self.module.params['vol_id']\n\n try:\n if vol_name and vol_name != snapshot['ancestorVolumeName']:\n errormsg = \"Given volume name do not match with the \" \\\n \"corresponding snapshot details.\"\n self.module.fail_json(msg=errormsg)\n\n if vol_id and vol_id != snapshot['ancestorVolumeId']:\n errormsg = \"Given volume ID do not match with the \" \\\n \"corresponding snapshot details.\"\n self.module.fail_json(msg=errormsg)\n except Exception as e:\n errormsg = \"Failed to match volume details with the snapshot \" \\\n \"with error %s\" % str(e)\n LOG.error(errormsg)\n self.module.fail_json(msg=errormsg)",
"def cli(env, identifier, notes):\n\n iscsi_mgr = SoftLayer.ISCSIManager(env.client)\n iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, identifier, 'iSCSI')\n iscsi_mgr.create_snapshot(iscsi_id, notes)",
"def test_attribute_name_map(self):\n converter = mock.MagicMock()\n block = SnapshotBlockConverter(converter, [])\n block.child_type = \"Control\"\n expected_attrs = [\n ('slug', 'Code'),\n ('audit', 'Audit'), # inserted attribute\n ('revision_date', 'Revision Date'), # inserted attribute\n ('title', 'Title'),\n ('description', 'Description'),\n ('notes', 'Notes'),\n ('test_plan', 'Assessment Procedure'),\n ('start_date', 'Effective Date'),\n ('end_date', 'Last Deprecated Date'),\n ('status', 'State'),\n ('os_state', 'Review State'),\n ('assertions', 'Assertions'),\n ('categories', 'Categories'),\n ('fraud_related', 'Fraud Related'),\n ('key_control', 'Significance'),\n ('kind', 'Kind/Nature'),\n ('means', 'Type/Means'),\n ('reference_url', 'Reference URL'),\n ('verify_frequency', 'Frequency'),\n ('recipients', 'Recipients'),\n ('send_by_default', 'Send by default'),\n ('document_evidence', 'Evidence File'),\n ('updated_at', 'Last Updated'),\n ('modified_by', 'Last Updated By'),\n ('created_at', 'Created Date'),\n ]\n ac_roles = db.session.query(all_models.AccessControlRole.name).filter(\n all_models.AccessControlRole.object_type == \"Control\"\n ).all()\n expected_attrs += [\n (\"__acl__:{}\".format(role[0]), role[0]) for role in ac_roles\n ]\n # last_assessment_date and comments should be in the end\n # according to current order\n expected_attrs.append(('comments', 'Comments'))\n expected_attrs.append(('last_assessment_date', 'Last Assessment Date'))\n\n self.assertEqual(\n block._attribute_name_map.items(),\n expected_attrs\n )",
"def add_snapshot(self, *params):\n if not params or len(params)==0:\n raise TypeError(\"add_snapshot takes at lease 1 argument 0 given.\")\n elif params and len(params)>2:\n raise TypeError(\"add_snapshot takes at lease 1 argument %u given.\" %(len(params)))\n destdisk=params[0]\n sourcedisk=params[1]\n properties=destdisk.getProperties()\n properties.setProperty(\"vdisk\", sourcedisk.getAttribute(\"name\"))\n return self._add(\"snapshot\", destdisk.getAttribute(\"name\"), properties)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of the EBS snapshots available to you. Available snapshots include public snapshots available for any AWS account to launch, private snapshots that you own, and private snapshots owned by another AWS account but for which you've been given explicit create volume permissions.
|
def describe_snapshots(DryRun=None, SnapshotIds=None, OwnerIds=None, RestorableByUserIds=None, Filters=None, NextToken=None, MaxResults=None):
pass
|
[
"def list_snapshots(self):\r\n return self._snapshot_manager.list()",
"def snapshots_list(self, stack_name, ext_id):\n \n path=\"/stacks/%s/%s/snapshots\"%(stack_name,ext_id)\n if stack_name is not None and ext_id is not None:\n res = self.client.call(path, 'GET', data='', token=self.manager.identity.token)\n else:\n raise OpenstackError(\"You must specify both stack name and stack UUID\", 404) \n \n self.logger.debug('Openstack heat snapshots list: %s' % \\\n truncate(res))\n return res[0]",
"def ex_list_snapshots(self):\r\n list_snapshots = []\r\n request = '/global/snapshots'\r\n response = self.connection.request(request, method='GET').object\r\n list_snapshots = [self._to_snapshot(s) for s in\r\n response.get('items', [])]\r\n return list_snapshots",
"def vmsnapshotlist(args):\n snapshot = args.snapshot\n name = args.name\n config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace)\n k = config.k\n common.pprint(\"Listing snapshots of %s...\" % name)\n snapshots = k.snapshot(snapshot, name, listing=True)\n if isinstance(snapshots, dict):\n common.pprint(\"Vm %s not found\" % name, color='red')\n return\n else:\n for snapshot in snapshots:\n print(snapshot)\n return",
"def list_snapshots(self):\n return self.machine.cloud.ctl.compute.list_machine_snapshots(\n self.machine)",
"def list_snapshots(connection, volume):\n\n logger.info(\n '+----------------'\n '+----------------------'\n '+---------------------------+')\n logger.info(\n '| {snapshot:<14} '\n '| {snapshot_name:<20.20} '\n '| {created:<25} |'.format(\n snapshot='Snapshot ID',\n snapshot_name='Snapshot name',\n created='Created'))\n logger.info(\n '+----------------'\n '+----------------------'\n '+---------------------------+')\n\n vid = get_volume_id(connection, volume)\n if vid:\n vol = connection.get_all_volumes(volume_ids=[vid])[0]\n for snap in vol.snapshots():\n logger.info(\n '| {snapshot:<14} '\n '| {snapshot_name:<20.20} '\n '| {created:<25} |'.format(\n snapshot=snap.id,\n snapshot_name=snap.tags.get('Name', ''),\n created=snap.start_time))\n\n logger.info(\n '+----------------'\n '+----------------------'\n '+---------------------------+')",
"def list_snapshots(self):\r\n return [snap for snap in self.manager.list_snapshots()\r\n if snap.volume_id == self.id]",
"def make_snapshots(client, tag_key, tag_value):\n tag_filter = {'Name': 'tag:%s' % tag_key, 'Values': [tag_value]}\n try:\n reservations = client.describe_instances(Filters=[tag_filter])['Reservations']\n except BotoCoreError as exc:\n logging.error(\"Failed to get list of instances to back up:\\n%s\", exc)\n instances = list(chain.from_iterable([x['Instances'] for x in reservations]))\n if not instances:\n logging.warning(\"Couldn't find any instances whose volumes need snapshotting. Aborting …\")\n sys.exit(0)\n\n # Create snapshots for all volumes per instance.\n for instance in instances:\n # Get the volumes attached to the instance.\n try:\n volumes_for_instance = client.describe_volumes(Filters=[\n {'Name': 'attachment.instance-id',\n 'Values': [instance['InstanceId']]},\n {'Name': 'status',\n 'Values': ['in-use']}])['Volumes']\n except BotoCoreError as exc:\n logging.error(\"Failed to get the list of volumes attached to instance %s:\\n%s\",\n instance['InstanceId'], exc)\n if not volumes_for_instance:\n logging.warning(\"Found instance %s to backup, but no attached \"\n \"volumes. Something is fishy here. Aborting …\",\n instance['InstanceId'])\n sys.exit(1)\n\n # Get the instance name from the tags if it exists.\n instance_name = None\n for tag in instance['Tags']:\n if tag['Key'] == 'Name':\n instance_name = tag['Value']\n continue\n\n for volume in volumes_for_instance:\n attachments = volume['Attachments']\n volume_attach_devices = ', '.join([att['Device'] for att in attachments])\n volume_attach_instances = ', '.join([att['InstanceId'] for att in attachments])\n\n if instance_name:\n description = ('automated snapshot of volume '\n '%s attached as %s to %s (%s)' %\n (volume['VolumeId'],\n volume_attach_devices,\n instance_name,\n volume_attach_instances))\n else:\n description = ('automated snapshot of volume '\n '%s attached as %s to %s' %\n (volume['VolumeId'],\n volume_attach_devices,\n volume_attach_instances))\n try:\n snapshot = client.create_snapshot(VolumeId=volume['VolumeId'],\n Description=description)\n except BotoCoreError as exc:\n logging.error(\"Creating a snapshot of volume %s failed:\\n%s\",\n volume['VolumeId'],\n exc)\n else:\n logging.info(\"Creating snapshot %s of volume %s\",\n snapshot['SnapshotId'],\n volume['VolumeId'])\n snapshot_date = datetime.now().strftime('%Y-%m-%d %H:%M')\n if instance_name:\n name_tag_value = '%s %s %s' % (instance_name,\n volume_attach_devices,\n snapshot_date)\n else:\n name_tag_value = '%s %s %s' % (volume_attach_instances,\n volume_attach_devices,\n snapshot_date)\n try:\n client.create_tags(Resources=[snapshot['SnapshotId']],\n Tags=[{'Key': 'Name',\n 'Value': name_tag_value},\n {'Key': 'Creator',\n 'Value': 'ebs_snapshot_automation'},\n {'Key': 'Origin-Instance',\n 'Value': instance['InstanceId']},\n {'Key': 'Origin-%s' % tag_key,\n 'Value': tag_value}])\n except BotoCoreError as exc:\n logging.error(\"Tagging the snapshot %s of volume %s failed:\\n%s\",\n snapshot['SnapshotId'],\n volume['VolumeId'],\n exc)",
"def getSnapshots(self):\r\n self.server.logMsg(\"FINDING SNAPSHOTS FOR \" + self.vmName)\r\n self.snapshotList = []\r\n if hasattr(self.vmObject.snapshot, 'rootSnapshotList'):\r\n self.enumerateSnapshotsRecursively(self.vmObject.snapshot.rootSnapshotList, '')\r\n return",
"def create_snapshot(volumes):\n ec2 = boto3.resource(\"ec2\")\n snapshots = []\n for volume in volumes:\n for tag in volume['volume_tags']:\n if tag['Key'] == 'Name':\n volume_name = tag['Value']\n description = \"Snapshot of %s - Created %s\" % ( volume_name, curdate() )\n snapshot = ec2.create_snapshot(VolumeId=volume['VolumeId'], Description=description)\n logging.info(\"%s - Creating Snapshot of %s - SnapshotId: %s\" % (curdate(), snapshot.volume_id, snapshot.id))\n snapshots.append(snapshot)\n tags = snapshot.create_tags(\n Tags=volume['volume_tags']\n )\n logging.info(\"%s Updated Tags on Snapshot: %s\" % (curdate, snapshot.id))\n return snapshots",
"def test_03_list_snapshots(self):\n list_snapshot_response = Snapshot.list(\n self.apiclient,\n ids=[self.snapshot_1.id, self.snapshot_2.id, self.snapshot_3.id],\n listAll=True\n )\n self.assertEqual(\n isinstance(list_snapshot_response, list),\n True,\n \"ListSnapshots response was not a valid list\"\n )\n self.assertEqual(\n len(list_snapshot_response),\n 3,\n \"ListSnapshots response expected 3 Snapshots, received %s\" % len(list_snapshot_response)\n )",
"def __snap_list_cmd(self, region, selector, disp):\n if not selector.has_selection():\n return\n ec2_conn = self.get_ec2_conn(region)\n snapshot_list = ec2_conn.get_all_snapshots(\n snapshot_ids=selector.resource_id_list,\n owner='self',\n filters=selector.get_filter_dict())\n snapshot_list = selector.filter_resources(snapshot_list)\n with CommandOutput(output_path=disp.get_output_file()) as pg:\n if disp.display_count:\n if disp.display_size:\n pg.prt(\"Snapshot stats: count=%d size=%d\",\n len(snapshot_list),\n sum([snap.volume_size for snap in snapshot_list]))\n else:\n pg.prt(\"Snapshot count: %d\", len(snapshot_list))\n else:\n snapshot_list = disp.order_resources(snapshot_list)\n for snapshot in snapshot_list:\n self.__snap_display(snapshot, disp, pg, region)",
"def get_volume_snapshots(self, volume_id):\n LOG.info(\"Getting volume snapshots from vol id: '%s'\" % volume_id)\n filter_by_source = {\n 'protection_data->>source_id': constants.EQUALS + volume_id\n }\n return self.rest_client.request(\n constants.GET,\n constants.GET_VOLUME_LIST_URL.format(self.server_ip),\n querystring=helpers.prepare_querystring(\n constants.SELECT_ID_AND_NAME, filter_by_source,\n type=constants.EQUALS + VOLUME_TYPE.snapshot\n )\n )",
"def list_volume_snapshots(self, volume):\r\n raise NotImplementedError(\r\n 'list_volume_snapshots not implemented for this driver')",
"def create_several_snapshots(request, storage):\n self = request.node.cls\n\n self.snapshot_list = []\n\n for snap in range(self.snap_count):\n\n snapshot_description = getattr(\n self, 'snapshot_description',\n storage_helpers.create_unique_object_name(\n self.__name__, config.OBJECT_TYPE_SNAPSHOT\n ) + '%s' % snap\n )\n testflow.setup(\n \"Creating snapshot %s of VM %s\",\n snapshot_description, self.vm_name\n )\n assert ll_vms.addSnapshot(\n True, self.vm_name, snapshot_description\n ), \"Failed to create snapshot of VM %s\" % self.vm_name\n ll_vms.wait_for_vm_snapshots(\n self.vm_name, [config.SNAPSHOT_OK], snapshot_description\n )\n ll_jobs.wait_for_jobs([config.JOB_CREATE_SNAPSHOT])\n\n self.snapshot_list.append(snapshot_description)",
"def describe_snapshots(self, DirectoryId: str = None, SnapshotIds: List = None, NextToken: str = None, Limit: int = None) -> Dict:\n pass",
"def backup_volume(ec2,instances):\n\n for instance in instances:\n retention = get_retention(instance)\n if not is_master(instance['PrivateIpAddress']):\n #make snapshot only on primary\n continue\n\n for dev in instance['BlockDeviceMappings']:\n if dev.get('Ebs', None) is None:\n # skip non-EBS volumes\n continue\n\n retention = get_retention(instance)\n now = datetime.today()\n delete_date_days = (now + timedelta(days=retention['days'])).strftime('%Y-%m-%d')\n delete_date_weeks = (now + timedelta(weeks=retention['weeks'])).strftime('%Y-%m-%d')\n delete_date_months = (now + relativedelta(months=retention['months'])).strftime('%Y-%m-%d')\n desc_date = now.strftime('%Y-%m-%d.%H:%M:%S')\n\n\n # all mongo disks are sdf\n if dev['DeviceName'] == '/dev/sdf':\n vol_id = dev['Ebs']['VolumeId']\n\n # Make sure that only one snapshot is taken, whether daily, weekly or monthly.\n if now.strftime('%d') == '01':\n print \"Creating snapshot of %s volume that will be retain for %d months\" % (vol_id, retention['months'])\n snap = make_snapshot(ec2,vol_id, retention['months'], \"MongoMonthlyBackupSnapshot-\"+desc_date)\n tag_snapshot(ec2, snap['SnapshotId'], delete_date_months)\n elif now.strftime('%a') == 'Sun':\n print \"Creating snapshot of %s volume that will be retain for %d weeks\" % (vol_id, retention['weeks'])\n snap = make_snapshot(ec2,vol_id, retention['weeks'], \"MongoWeeklyBackupSnapshot-\"+desc_date)\n tag_snapshot(ec2, snap['SnapshotId'], delete_date_weeks)\n else:\n print \"Creating snapshot of %s volume that will be retain for %d days\" % (vol_id, retention['days'])\n snap = make_snapshot(ec2,vol_id, retention['days'], \"MongoDailyBackupSnapshot-\"+desc_date)\n tag_snapshot(ec2, snap['SnapshotId'], delete_date_days)\n\n return True",
"def ListVolumes(self) -> Dict[str, 'ebs.AWSVolume']:\n\n return self.aws_account.ListVolumes(\n filters=[{\n 'Name': 'attachment.instance-id',\n 'Values': [self.instance_id]}])",
"def test_vmware_service_resources_snapshots_get(self):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the data feed for Spot instances. For more information, see Spot Instance Data Feed in the Amazon Elastic Compute Cloud User Guide .
|
def describe_spot_datafeed_subscription(DryRun=None):
pass
|
[
"def describe_spot_fleet_instances(DryRun=None, SpotFleetRequestId=None, NextToken=None, MaxResults=None):\n pass",
"def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):\n pass",
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def info():\n return render_template(\n os.path.join(os.path.dirname(__file__), 'templates/instance_info.html'),\n concurrents=concurrents,\n current_requests=current_requests,\n os=os,\n runtime=os.getenv('GAE_RUNTIME'),\n )",
"def describe_spot_price_history(DryRun=None, StartTime=None, EndTime=None, InstanceTypes=None, ProductDescriptions=None, Filters=None, AvailabilityZone=None, MaxResults=None, NextToken=None):\n pass",
"def describe(self):\n print(Controller().describe_instances())",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def _scrape_metadata(self):\n return",
"def get_listing():\n\n ec2 = boto3.client('ec2')\n listing = []\n\n try:\n full_listing = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ 'running' ]\n }\n ],\n MaxResults=1000)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n for reservation in full_listing['Reservations']:\n for instance in reservation['Instances']:\n listing.append(instance)\n\n return listing",
"def get_instance_metadata(cls, instances, no_dev=False):\n\n instance_data = []\n\n for instance in instances:\n instance_dict = {}\n\n if instance.tags:\n instance_dict['name'] = instance.tags[0]['Value']\n else:\n instance_dict['name'] = ''\n\n instance_dict['type'] = instance.instance_type\n instance_dict['id'] = instance.id\n instance_dict['tags'] = []\n instance_dict['state'] = instance.state['Name']\n instance_dict['launch_time'] = instance.launch_time\n\n if no_dev:\n if instance_dict['name'] != MANTRA_DEVELOPMENT_TAG_NAME:\n instance_data.append(instance_dict)\n else:\n if instance_dict['name'] == MANTRA_DEVELOPMENT_TAG_NAME:\n instance_dict['tags'] += ['development']\n instance_data.append(instance_dict)\n\n return instance_data",
"def spotify(self, app_region, template):\n if app_region.spot is None:\n return\n\n resources = template['Resources']\n parameters = template['Parameters']\n self._add_spot_fleet(app_region, resources, parameters)\n self._clean_up_asg(template)",
"def print_instance_summary(self, instance: EC2Instance):\n print(instance.instance_id)\n self.not_quiet(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n self.verbose_output(f\" AMI: {instance.image_id}\")\n self.not_quiet(f\" Type: {instance.instance_type}\")\n self.verbose_output(f\" Launched: {instance.launch_time}\")\n self.verbose_output(f\" AZ: {instance.availability_zone}\")\n self.verbose_output(f\" Private DNS: {instance.private_dns_name}\")\n self.verbose_output(f\" Public DNS: {instance.public_dns_name}\")\n self.not_quiet(f\" Private IP: {instance.private_ip_address}\")\n self.not_quiet(f\" Public IP: {instance.public_ip_address}\")\n self.verbose_output(f\" Subnet Id: {instance.subnet_id}\")\n self.verbose_output(f\" VPC Id: {instance.vpc_id}\")\n self.not_quiet(f\" State: {instance.state}\")\n self.verbose_output(f\" Tags: {instance.tags}\")\n self.not_quiet(\"\\n\")",
"def get_quick_stats(self):\n print(\"\")\n print(self.cam_name)\n print(\"Status:\\t\\t{}\".format(self.cam_status))\n print(\"Created:\\t{} on {}\".format(self.created_date.split(\"T\")[1].split(\".\")[0],\n self.created_date.split(\"T\")[0]))\n print(\"Started:\\t{} on {}\".format(self.launch_date.split(\"T\")[1].split(\".\")[0],\n self.launch_date.split(\"T\")[0]))\n if self.cam_status == \"Completed\":\n print(\"Completed:\\t{} on {}\".format(self.completed_date.split(\"T\")[1].split(\".\")[0],\n self.completed_date.split(\"T\")[0]))\n print(\"\")\n print(\"Total Targets:\\t{}\".format(self.total_targets))\n print(\"Emails Sent:\\t{}\".format(self.total_sent))\n print(\"IPs Seen:\\t{}\".format(len(self.ip_addresses)))\n print(\"\")\n print(\"Total Opened Events:\\t\\t{}\".format(self.total_opened))\n print(\"Total Click Events:\\t\\t{}\".format(self.total_clicked))\n print(\"Total Submitted Data Events:\\t{}\".format(self.total_submitted))\n print(\"\")\n print(\"Individuals Who Opened:\\t\\t{}\".format(self.total_unique_opened))\n print(\"Individuals Who Clicked:\\t{}\".format(self.total_unique_clicked))\n print(\"Individuals Who Entered data:\\t{}\".format(self.total_unique_submitted))",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def print_new_episodes():\n print(\"\")\n print(\"NEW EPISODES:\")\n print(tab(st.open_nel(),headers=\"keys\", tablefmt=\"psql\"))",
"def do_printInstances(self,args):\n parser = CommandArgumentParser(\"printInstances\")\n parser.add_argument(dest='filters',nargs='*',default=[\"*\"],help='Filter instances');\n parser.add_argument('-a','--addresses',action='store_true',dest='addresses',help='list all ip addresses');\n parser.add_argument('-t','--tags',action='store_true',dest='tags',help='list all instance tags');\n parser.add_argument('-d','--allDetails',action='store_true',dest='details',help='print all instance details');\n parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');\n parser.add_argument('-z','--zones',dest='availabilityZones',nargs='+',help='Only include specified availability zones');\n args = vars(parser.parse_args(args))\n \n client = AwsConnectionFactory.getEc2Client()\n\n filters = args['filters']\n addresses = args['addresses']\n tags = args['tags']\n details = args['details']\n availabilityZones = args['availabilityZones']\n needDescription = addresses or tags or details\n\n if args['refresh']:\n self.scalingGroupDescription = self.client.describe_auto_scaling_groups(AutoScalingGroupNames=[self.scalingGroup])\n \n # print \"AutoScaling Group:{}\".format(self.scalingGroup)\n print \"=== Instances ===\"\n instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']\n\n instances = filter( lambda x: fnmatches(x['InstanceId'],filters),instances)\n if availabilityZones:\n instances = filter( lambda x: fnmatches(x['AvailabilityZone'],availabilityZones),instances)\n \n index = 0\n for instance in instances:\n instance['index'] = index\n print \"* {0:3d} {1} {2} {3}\".format(index,instance['HealthStatus'],instance['AvailabilityZone'],instance['InstanceId'])\n description = None\n if needDescription:\n description = client.describe_instances(InstanceIds=[instance['InstanceId']])\n if addresses:\n networkInterfaces = description['Reservations'][0]['Instances'][0]['NetworkInterfaces']\n number = 0\n print \" Network Interfaces:\"\n for interface in networkInterfaces:\n print \" * {0:3d} {1}\".format(number, interface['PrivateIpAddress'])\n number +=1\n if tags:\n tags = description['Reservations'][0]['Instances'][0]['Tags']\n print \" Tags:\"\n for tag in tags:\n print \" * {0} {1}\".format(tag['Key'],tag['Value'])\n if details:\n pprint(description)\n \n index += 1",
"def dataDescribe(self, data):\n data['Display Time'] = pd.to_datetime(data['Display Time'])\n data['time_gap'] = data['Display Time']- data['Display Time'].shift(1)\n data_description = self.summaryTable(data)\n \n return data_description",
"def printMetadata(self):\n print (\"************COMMONDATA************\")\n print (\"Setname:\", self.setname, \"PROC:\", self.proc)\n print (\"NDAT:\", self.ndata,\"NSYS:\",self.nsys)",
"def list(ctx):\r\n config = ctx.obj['config']\r\n config.validate()\r\n host = config.get_active_host()\r\n instances = host.get_instances()\r\n logger.info(\"Instances on: %s\", host.name)\r\n outputters.table([x.dump() for x in instances])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the running instances for the specified Spot fleet.
|
def describe_spot_fleet_instances(DryRun=None, SpotFleetRequestId=None, NextToken=None, MaxResults=None):
pass
|
[
"def showinstances():\n username, conn = _getbotoconn(auth_user)\n\n print \"all instances running under the %s account\" % username\n\n num_running = 0\n reservations = conn.get_all_instances()\n for reservation in reservations:\n num_running += _print_reservation(reservation)\n\n return num_running",
"def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):\n pass",
"def get_listing():\n\n ec2 = boto3.client('ec2')\n listing = []\n\n try:\n full_listing = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ 'running' ]\n }\n ],\n MaxResults=1000)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n for reservation in full_listing['Reservations']:\n for instance in reservation['Instances']:\n listing.append(instance)\n\n return listing",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def fleet_scheduled(self, fleet, howMany=MAX_RECORD_LENGTH, offset=0):\n data = {\"fleet\": fleet, \"howMany\": howMany, \"offset\": offset}\n return self._request(\"FleetScheduled\", data)",
"def describe(self):\n print(Controller().describe_instances())",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def get_running_instances(config):\n logging.info('Getting running instances...')\n ec2_resource = get_resource(config, 'ec2')\n dock_running_instances = ec2_resource.instances.filter(\n Filters=[\n {'Name': 'instance-state-name', 'Values': ['running']},\n {'Name': 'tag:Purpose', 'Values': ['Dockchain Test']}\n ]\n )\n return dock_running_instances",
"def _print_reservation(reservation):\n num_running = 0\n for inst in reservation.instances:\n if inst.state != u'running':\n continue\n print \"ID: %s\" % inst.id\n print \"state: %s\" % inst.state\n print \"IP: %s\" % inst.ip_address\n print \"private IP: %s\" % inst.private_ip_address\n print \"DNS: %s\" % inst.public_dns_name\n print \"private DNS: %s\" % inst.private_dns_name\n print \"architecture: %s\" % inst.architecture\n print \"image ID: %s\" % inst.image_id\n print \"class: %s\" % inst.instance_class\n print \"type: %s\" % inst.instance_type\n print \"key_name: %s\" % inst.key_name\n print \"launch time: %s\" % inst.launch_time\n print \"\"\n num_running += 1\n\n return num_running",
"def fleet(self) -> Fleet:\n pass",
"def _running_instances(self, service, rev, instance):\n running_instances = set()\n\n active_cutoff = time.time() - SERVICE_EXPIRY\n service_statuses = self._db.get_service_status(service, rev, instance)\n for instance, services_status in service_statuses:\n for status in services_status.values():\n sub_state = status['sub_state']\n active_time = status['active_enter_time']\n if sub_state == 'running' and active_time <= active_cutoff:\n running_instances.add(instance)\n\n return running_instances",
"def list() -> None:\n config = load_config_file()\n running_instances = get_running_instances(config)\n print_formatted_instances(running_instances)\n logging.info('Done!')",
"def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):\n pass",
"def describe_spot_fleet_requests(DryRun=None, SpotFleetRequestIds=None, NextToken=None, MaxResults=None):\n pass",
"def list(ctx):\r\n config = ctx.obj['config']\r\n config.validate()\r\n host = config.get_active_host()\r\n instances = host.get_instances()\r\n logger.info(\"Instances on: %s\", host.name)\r\n outputters.table([x.dump() for x in instances])",
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def report_instance_status(DryRun=None, Instances=None, Status=None, StartTime=None, EndTime=None, ReasonCodes=None, Description=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the events for the specified Spot fleet request during the specified time. Spot fleet events are delayed by up to 30 seconds before they can be described. This ensures that you can query by the last evaluated time and not miss a recorded event.
|
def describe_spot_fleet_request_history(DryRun=None, SpotFleetRequestId=None, EventType=None, StartTime=None, NextToken=None, MaxResults=None):
pass
|
[
"def events_after(self, events, time):\n relevant_logs = [log_time for log_time in events\n if log_time > time]\n return dict((logtime, events[logtime]) for logtime in relevant_logs)",
"def describe_spot_fleet_requests(DryRun=None, SpotFleetRequestIds=None, NextToken=None, MaxResults=None):\n pass",
"def trackTime(self,event):\n self.timings[event] = time.time()",
"def get_event_by_timestamp(self, time: dt):\n # ensure that the given time uses the same timezone as the computer\n now = dt.now()\n time = time.astimezone(now.tzinfo)\n\n events = self.get_events()\n filtered_events = []\n # find the wanted event\n for e in events:\n event_start = next(v for k, v in e[\"start\"].items() if \"date\" in k)\n event_start = dt.fromisoformat(event_start).astimezone(now.tzinfo)\n\n event_end = next(v for k, v in e[\"end\"].items() if \"date\" in k)\n event_end = dt.fromisoformat(event_end).astimezone(now.tzinfo)\n\n # check if the given time is between the start and end of an event\n if time >= event_start and time <= event_end:\n filtered_events.append(e)\n return filtered_events",
"def request_events(self):\n start_time = None\n if self._config.ORG_URL.startswith(\"http://\"):\n url = \"https://{}/api/v1/logs\".format(self._config.ORG_URL.replace(\"https://\", \"\"))\n else:\n url = \"https://{}/api/v1/logs\".format(self._config.ORG_URL)\n headers = {'Authorization': 'SSWS {}'.format(self._config.TOKEN),\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\"}\n params = {\"sortOrder\": \"ASCENDING\"}\n param_sort_only = {\"sortOrder\": \"ASCENDING\"}\n if path.exists(self._config.TIMESTAMP_FILE):\n with open(self._config.TIMESTAMP_FILE) as f:\n start_time = f.read().strip()\n if start_time is not None:\n params[\"after\"] = start_time\n response = requests.get(url, headers=headers, params=params)\n return response, headers",
"def test_list_event_after_with_timestamp(self, screen, query, command, dbsession):\n timestamp = time()\n event = command.send_event('view', screen.id)\n\n with DeleteOnExit(dbsession, event):\n result = query.list_events_after(screen.id, timestamp)\n assert len(result) == 1\n assert result[0].id == event.id",
"def test_fetch_incidents_long_running_events__timeout(self, mocker):\n def mock_enrich_offense_with_events(client, offense, fetch_mode, events_columns, events_limit):\n time.sleep(0.001)\n return offense\n\n QRadar_v2.DEFAULT_EVENTS_TIMEOUT = 0\n offense_with_no_events = RAW_RESPONSES[\"fetch-incidents\"]\n if 'events' in offense_with_no_events:\n del offense_with_no_events['events']\n client = QRadarClient(\"\", {}, {\"identifier\": \"*\", \"password\": \"*\"})\n fetch_mode = FetchMode.all_events\n mocker.patch.object(QRadar_v2, \"get_integration_context\", return_value={})\n mocker.patch.object(QRadar_v2, \"fetch_raw_offenses\", return_value=[offense_with_no_events])\n print_debug_msg_mock = mocker.patch.object(QRadar_v2, \"print_debug_msg\")\n QRadar_v2.enrich_offense_with_events = mock_enrich_offense_with_events\n mocker.patch.object(demisto, \"createIncidents\")\n mocker.patch.object(demisto, \"debug\")\n sic_mock = mocker.patch.object(QRadar_v2, \"set_integration_context\")\n\n fetch_incidents_long_running_events(client, \"\", \"\", False, False, fetch_mode, \"\", \"\")\n\n assert print_debug_msg_mock.call_args_list[0].args[0] == \"Timed out while waiting for events\"\n assert sic_mock.call_args[0][0]['id'] == 450\n assert len(sic_mock.call_args[0][0]['samples']) == 1\n incident_raw_json = json.loads(sic_mock.call_args[0][0]['samples'][0]['rawJSON'])\n assert 'events' not in incident_raw_json\n QRadar_v2.DEFAULT_EVENTS_TIMEOUT = 30",
"def add_event_at(self, time, event):\n if time not in self.events:\n self.events[time] = []\n self.events[time].append(event)\n\n return self",
"def main(timeString = None, location = None):\n credentials = get_credentials()\n if timeString == None:\n return\n \n http = credentials.authorize(httplib2.Http())\n service = discovery.build('calendar', 'v3', http=http)\n\n # generate the 'newEvent'-dictionary\n newEvent = makeEvent(timeString, location)\n newStart = newEvent['start'].get('dateTime', newEvent['start'].get('date'))\n \n # ask Google for events with the first word (.split(' ', 1)[0]) of \n # config.summaryFormat in its summary\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n eventsResult = service.events().list(\n calendarId='primary', \n timeMin=now, \n maxResults=50, \n singleEvents=True,\n orderBy='startTime', \n q=(config.summaryFormat).split(' ', 1)[0]\n ).execute()\n events = eventsResult.get('items', [])\n \n # check if one of these events is already our newEvent\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n if newStart == start and newEvent['summary'] == event['summary']:\n #print(event['summary'] + ' bei ' + start + ' gibts schon. nix zu tun. (0)')\n print(event['summary'] + ' gibts schon. nix zu tun. (0)')\n return\n\n\n if config.testmode:\n print('=== Test ohne Eintrag in Kalender ===\\ndieser Event _würde_ jetzt eingetragen werden:\\n')\n print(newEvent)\n else:\n event = service.events().insert(calendarId='primary', body=newEvent).execute()\n print(newEvent['summary'] + ' am ' + newStart + ', Abholung eingetragen (+)')",
"def filterTiming(events):\n filters = []\n filters.append( KeepEventTypes(['EcatTimeOverrun', 'RealtimeLoopOverrun']) )\n filters.append( IntervalMerge(2.0) )\n return runFilters(filters,events)",
"def fleet_scheduled(self, fleet, howMany=MAX_RECORD_LENGTH, offset=0):\n data = {\"fleet\": fleet, \"howMany\": howMany, \"offset\": offset}\n return self._request(\"FleetScheduled\", data)",
"def events_before(self, events, time):\n relevant_logs = [log_time for log_time in events\n if log_time < time]\n return dict((logtime, events[logtime]) for logtime in relevant_logs)",
"def get_event(self, timeout=None):",
"def makeEvent(timeString, location):\n timeString = timeString.rstrip()\n \n \n # if \"Morgen\" or \"Heute\" is in the timeString, replace it with the format used for other days\n if timeString.startswith('Heute'):\n timeString = timeString.replace('Heute', (datetime.date.today()).strftime('%A, %d. %b'))\n elif timeString.startswith('Morgen'):\n timeString = timeString.replace('Morgen', (datetime.date.today() + datetime.timedelta(1)).strftime('%A, %d. %b'))\n \n # parse a time String like 'Donnerstag, 10. Aug, 16:00 Uhr' and set the year\n time = datetime.datetime.strptime(timeString,'%A, %d. %b, %H:%M Uhr').replace(config.thisYear)\n \n event = {\n 'summary': config.summaryFormat.format(location),\n 'colorId' : config.colorId,\n 'start': {\n 'dateTime': time.isoformat() + '+02:00',\n 'timeZone': 'Europe/Berlin',\n },\n 'end': {\n 'dateTime': (time + datetime.timedelta(0,0,0,0,config.deltaMinutes)).isoformat() + '+02:00',\n 'timeZone': 'Europe/Berlin',\n },\n }\n\n return event",
"def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):\n pass",
"def get_events_per_time():\n clean_expired_sessions()\n\n # reads the session\n session = request.args.get('session', type=str)\n # reads the requested process name\n process = request.args.get('process', default='receipt', type=str)\n\n logging.info(\"get_events_per_time start session=\" + str(session) + \" process=\" + str(process))\n\n dictio = {}\n\n if check_session_validity(session):\n user = get_user_from_session(session)\n if lh.check_user_log_visibility(user, process):\n Commons.semaphore_matplot.acquire()\n try:\n base64, gviz_base64, ret = lh.get_handler_for_process_and_session(process,\n session).get_events_per_time_svg()\n data_x = []\n data_y = []\n for i in range(len(ret)):\n data_x.append(ret[i][0])\n data_y.append(ret[i][1])\n\n dictio = {\"base64\": base64.decode('utf-8'), \"gviz_base64\": gviz_base64.decode('utf-8'), \"points\": ret,\"points_x\":data_x, \"points_y\":data_y}\n except:\n logging.error(traceback.format_exc())\n dictio = {\"base64\": \"\", \"gviz_base64\": \"\", \"points\": [],\"points_x\":[],\"points_y\":[]}\n Commons.semaphore_matplot.release()\n\n logging.info(\n \"get_events_per_time complete session=\" + str(session) + \" process=\" + str(process) + \" user=\" + str(user))\n\n ret = jsonify(dictio)\n\n return ret",
"def get_hide_expired_events():",
"def fleet_arrived(self, fleet, howMany=MAX_RECORD_LENGTH, offset=0):\n\n data = {\"fleet\": fleet, \"howMany\": howMany, \"offset\": offset}\n return self._request(\"FleetArrived\", data)",
"def test_enrich_offense_with_events__all_events(self, mocker):\n client = QRadarClient(\"\", {}, {\"identifier\": \"*\", \"password\": \"*\"})\n offense = RAW_RESPONSES[\"fetch-incidents\"]\n fetch_mode = FetchMode.all_events\n events_cols = \"\"\n events_limit = \"\"\n\n poee_mock = mocker.patch.object(QRadar_v2, \"perform_offense_events_enrichment\", return_value=offense)\n enrich_offense_with_events(client, offense, fetch_mode, events_cols, events_limit)\n assert poee_mock.call_args[0][1] == \"\""
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes your Spot fleet requests. Spot fleet requests are deleted 48 hours after they are canceled and their instances are terminated.
|
def describe_spot_fleet_requests(DryRun=None, SpotFleetRequestIds=None, NextToken=None, MaxResults=None):
pass
|
[
"def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):\n pass",
"def describe_spot_fleet_request_history(DryRun=None, SpotFleetRequestId=None, EventType=None, StartTime=None, NextToken=None, MaxResults=None):\n pass",
"def help_list_requests():\n get_list_ride_requests_parser().print_help()",
"def modify_spot_fleet_request(SpotFleetRequestId=None, TargetCapacity=None, ExcessCapacityTerminationPolicy=None):\n pass",
"def fleet_scheduled(self, fleet, howMany=MAX_RECORD_LENGTH, offset=0):\n data = {\"fleet\": fleet, \"howMany\": howMany, \"offset\": offset}\n return self._request(\"FleetScheduled\", data)",
"def describe_spot_fleet_instances(DryRun=None, SpotFleetRequestId=None, NextToken=None, MaxResults=None):\n pass",
"def help_delete_request():\n get_delete_request_parser().print_help()",
"def delete_request():",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def wait_for_fulfillment(self, timeout=50, request_ids=None):\n logger.debug(\"waiting for requests to be fulfilled\") \n\n if request_ids is None:\n spot_req_ids = self.spot_req_ids\n else:\n spot_req_ids = request_ids\n\n processed_dict=dict()\n for sir_id in spot_req_ids:\n processed_dict[sir_id] = False\n #status_dict[sir_id] = None\n\n ### wait for a disposition for each spot request (basically when sir.state is not open)\n loop_count=0\n while not all( processed_dict.values()) and loop_count <= timeout:\n loop_count+=1\n try:\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n except boto.exception.EC2ResponseError:\n ### need to wait a little time for AWS to register the requests, if this function called\n ### right after create_spot_instances\n time.sleep(3)\n continue\n for sir in spot_reqs:\n if sir.state != 'open':\n processed_dict[sir.id] = True\n\n if not all ( processed_dict.values()):\n time.sleep(15)\n\n\n ### get disposition of each spot instance request\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n instance_ids = list()\n instance_ready = dict()\n for sir in spot_reqs:\n if sir.state == 'open':\n self.request_status_dict[sir.id] = 'timed out'\n else:\n self.request_status_dict[sir.id] = sir.status.code\n\n if sir.status.code == 'fulfilled':\n instance_ids.append(sir.instance_id)\n instance_ready[sir.instance_id] = False\n else:\n self.failed_req_ids.append(sir.id)\n \n ### wait for ready states in the fulfilled instances\n while not all ( instance_ready.values()) and loop_count <= timeout:\n loop_count+=1\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'pending':\n instance_ready[inst.id] = True\n \n if not all (instance_ready.values()):\n time.sleep(15)\n\n ### get final dispositions of instances\n good_instances =0\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'running':\n sir_id = inst.spot_instance_request_id\n self.failed_req_ids.append(sir_id)\n if inst.state == 'pending':\n self.request_status_dict[sir_id] = 'timed out'\n else:\n self.request_status_dict[sir_id] = 'post-fulfillment premature instance termination'\n else:\n if self.use_private_ips:\n ipaddr=inst.private_ip_address\n else:\n ipaddr=inst.ip_address\n self.instance_ids.append(inst.id)\n self.ip_dict[inst.id] = ipaddr\n self.rev_ip_dict[ipaddr] = inst.id\n self.request_status_dict[sir_id] = 'running'\n good_instances+=1\n\n\n ### might have to sleep a little bit after running status toggles before it can accept ssh connections\n # put a 30 second delay in\n time.sleep(30)\n\n return (len (spot_req_ids), good_instances) \n\n ### to retrieve good instances: awsobj.instance_ids[-good_instances:]",
"def logRequest(self,client_name,requests):\n if self.data.has_key(client_name):\n t_el=self.data[client_name]\n else:\n t_el={}\n t_el['Downtime'] = {'status':self.downtime}\n self.data[client_name]=t_el\n\n if t_el.has_key('Requested'):\n el=t_el['Requested']\n else:\n el={}\n t_el['Requested']=el\n\n for reqpair in (('IdleGlideins','Idle'),('MaxRunningGlideins','MaxRun')):\n org,new=reqpair\n if not el.has_key(new):\n el[new]=0\n if requests.has_key(org):\n el[new]+=requests[org]\n\n # Had to get rid of this\n # Does not make sense when one aggregates\n #el['Parameters']=copy.deepcopy(params)\n # Replacing with an empty list\n el['Parameters']={}\n\n self.updated=time.time()",
"def get_aws_req_status(req_id):\n\n client = boto3.client('ec2')\n\n response = client.describe_spot_instance_requests(\n SpotInstanceRequestIds=[req_id]\n )\n\n req_state = response['SpotInstanceRequests'][0]['State']\n req_status_code = response['SpotInstanceRequests'][0]['Status']['Code']\n\n instance_id = response['SpotInstanceRequests'][0].get('InstanceId', None)\n\n return [req_state, req_status_code, instance_id]",
"def PendingSweeps(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def cancel_uber():\n\n request_id = flask.request.form['request_id']\n response = uber_client.cancel_ride(request_id)\n return render_template(\"ride_cancelled.html\")",
"def testF_view_request(self):\n _, _, requestIds = self._inject(15) # creates x docs/requests\n requestView = self._getViewResults(\"request\")\n self.assertEqual(len(requestView), 15)\n for reqView in requestView:\n self.failUnless(reqView[u\"key\"] in requestIds)\n self.failUnless(reqView[u\"value\"][u\"state\"] == u\"NewlyHeld\")",
"def change_requests():\r\n kwargs = {}\r\n kwargs['loggedin'], uname, ugroup = if_logged_in(request)\r\n kwargs['block_add'] = False if ugroup in GROUPS_CAN_ADD_CHANGE_REQUEST else True\r\n kwargs['block_del'] = False if ugroup in GROUPS_CAN_DEL_CHANGE_REQUEST else True\r\n if get_by_name(uname, target='email') in get_test_manager_email(DBSession, 0):\r\n kwargs['block_add'] = False\r\n data_list = get_change_request_info(DBSession)\r\n kwargs['data_list'] = convert_dates_for_table(data_list)\r\n unique_requests = []\r\n for data in get_change_request_info(DBSession):\r\n unique_requests.append(data[0])\r\n kwargs['unique_requests'] = set(unique_requests)\r\n if not kwargs['block_add'] and request.form.get('user_action') == 'new':\r\n return redirect(\"/new_change_request\", 302)\r\n else:\r\n return render_template('change_requests.html', **kwargs)",
"def get(self):\n try:\n right_now = datetime.now() # let's assume datetime is the class\n except AttributeError:\n # App Engine sometimes imports datetime as a module...\n # Has been reported to GOOG: http://code.google.com/p/googleappengine/issues/detail?id=7341\n right_now = datetime.datetime.now()\n\n if self.request.get('early', False):\n right_now = right_now + datetime.timedelta(days=1)\n\n expired_instances = SIBTInstance.all()\\\n .filter('end_datetime <=', right_now)\\\n .filter('is_live =', True)\n\n for instance in expired_instances:\n taskqueue.add(\n url=url('RemoveExpiredSIBTInstance'),\n params={\n 'instance_uuid': instance.uuid\n }\n )\n msg = 'expiring %d instances' % expired_instances.count()\n logging.info(msg)\n self.response.out.write(msg)",
"async def fleet(self, agency : str, number : int):\n\t\tagencyname = 'null '\n\t\tcurator = 'null'\n\n\t\tdata = discord.Embed(title=\"Fleet Information\",description=\"Vehicle not found.\",colour=discord.Colour(value=12786604))\n\n\t\turl = \"http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=ttc\"\n\t\traw = urlopen(url).read() # Get page and read data\n\t\tdecoded = raw.decode(\"utf-8\") # Decode from bytes object\n\t\tparsed = minidom.parseString(decoded) # Parse with minidom to get XML stuffses\n\n\t\tif agency == \"info\":\n\t\t\tdata = discord.Embed(title=\"Sources\",description=\"Most fleet information is from the CPTDB wiki, with data curated by NJC staff.\\nhttps://cptdb.ca/wiki/index.php/Main_Page.\\n\\nNOTE: When a vehicle status is `Inactive`, this means the vehicle is currently not used for revenue service. \",colour=discord.Colour(value=5))\n\t\t\tawait self.bot.say(embed=data)\n\t\t\treturn\n\n\n\t\t# AGENCY NAME\n\t\tif agency == 'go':\n\t\t\tagencyname = \"GO Transit \"\n\t\telif agency =='ttc':\n\t\t\tagencyname = \"TTC \"\n\t\telif agency =='yrt':\n\t\t\tagencyname = \"YRT \"\n\t\telif agency =='miway':\n\t\t\tagencyname = \"MiWay \"\n\t\telif agency =='ddot':\n\t\t\tagencyname = \"DDOT \"\n\t\telse:\n\t\t\tagencyname = \"\"\n\n\t\ttry:\n\t\t\tfleetlist = open(\"cogs/njc/fleets/{}.csv\".format(agency))\n\t\t\treader = csv.reader(fleetlist,delimiter=\"\t\")\n\t\t\tline = []\n\t\texcept Exception as e:\n\t\t\tdata = discord.Embed(title=\"This agency is unsupported or invalid at this time.\",description=\"You can help contribute to the fleet lists. Contact <@300473777047994371>\\n\\nError: `\" + str(e) + \"`\",colour=discord.Colour(value=5))\n\t\t\tawait self.bot.say(embed=data)\n\t\t\treturn\n\n\t\ttry:\n\t\t\tfor row in reader:\n\t\t\t\tif row[0] != \"vehicle\" and int(row[0]) == number:\n\t\t\t\t\tline = row\n\t\t\tfleetlist.close()\n\t\t\tdata = discord.Embed( colour=discord.Colour(value=474494))\n\t\t\tdata.add_field(name=\"Manufacturer\", value=line[2])\n\t\t\tdata.add_field(name=\"Model\", value=line[3])\n\t\t\tdata.add_field(name=\"Division/Category\", value=line[4])\n\t\t\tdata.add_field(name=\"Powertrain/Motor\", value=line[5])\n\t\t\tdata.add_field(name=\"Vehicle Group\", value=line[1])\n\t\t\tdata.add_field(name=\"Status\", value=line[6])\n\t\t\tdata.set_footer(text=\"Last updated \" + line[8])\n\n\n\t\t\tif number < 1000:\n\t\t\t\tif agency == 'ttc':\n\t\t\t\t\tnumber = str('W{}'.format(number))\n\t\t\t\telif agency == 'miway':\n\t\t\t\t\tnumber = str('0{}'.format(number))\n\t\t\tdata.set_author(name=\"Fleet Information for {}\".format(agencyname) + str(number), url=line[7])\n\t\t\tdata.set_thumbnail(url=line[7])\n\n\t\texcept Exception as e:\n\t\t\tdata = discord.Embed(title=\"Vehicle {} was not found \".format(number) + \"for {}\".format(agencyname),description=\"Either you have entered a non-existent vehicle number, or that vehicle has not been added to our database yet! Vehicle groups that have been completely retired are removed from the database!\\n\\nError: `\" + str(e) + \"`\",colour=discord.Colour(value=16467744))\n\n\t\tawait self.bot.say(embed=data)",
"def get_requests_summary(self) -> bool:\n _state_manager = state_manager.get_state_manager()\n instance_id = turbinia_config.INSTANCE_ID\n tasks = _state_manager.get_task_data(instance=instance_id)\n request_ids = set()\n\n for task in tasks:\n request_id = task.get('request_id')\n if not request_id in request_ids:\n request_ids.add(request_id)\n\n for request_id in request_ids:\n filtered_tasks = [\n task for task in tasks if task.get('request_id') == request_id\n ]\n request_status = RequestStatus()\n request_status.get_request_data(request_id, filtered_tasks, summary=True)\n self.requests_status.append(request_status)\n\n return bool(self.requests_status)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the Spot instance requests that belong to your account. Spot instances are instances that Amazon EC2 launches when the bid price that you specify exceeds the current Spot price. Amazon EC2 periodically sets the Spot price based on available Spot instance capacity and current Spot instance requests. For more information, see Spot Instance Requests in the Amazon Elastic Compute Cloud User Guide . You can use DescribeSpotInstanceRequests to find a running Spot instance by examining the response. If the status of the Spot instance is fulfilled , the instance ID appears in the response and contains the identifier of the instance. Alternatively, you can use DescribeInstances with a filter to look for instances where the instance lifecycle is spot . Spot instance requests are deleted 4 hours after they are canceled and their instances are terminated.
|
def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):
pass
|
[
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def describe_spot_fleet_instances(DryRun=None, SpotFleetRequestId=None, NextToken=None, MaxResults=None):\n pass",
"def describe_spot_fleet_requests(DryRun=None, SpotFleetRequestIds=None, NextToken=None, MaxResults=None):\n pass",
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def get_aws_req_status(req_id):\n\n client = boto3.client('ec2')\n\n response = client.describe_spot_instance_requests(\n SpotInstanceRequestIds=[req_id]\n )\n\n req_state = response['SpotInstanceRequests'][0]['State']\n req_status_code = response['SpotInstanceRequests'][0]['Status']['Code']\n\n instance_id = response['SpotInstanceRequests'][0].get('InstanceId', None)\n\n return [req_state, req_status_code, instance_id]",
"def wait_for_fulfillment(self, timeout=50, request_ids=None):\n logger.debug(\"waiting for requests to be fulfilled\") \n\n if request_ids is None:\n spot_req_ids = self.spot_req_ids\n else:\n spot_req_ids = request_ids\n\n processed_dict=dict()\n for sir_id in spot_req_ids:\n processed_dict[sir_id] = False\n #status_dict[sir_id] = None\n\n ### wait for a disposition for each spot request (basically when sir.state is not open)\n loop_count=0\n while not all( processed_dict.values()) and loop_count <= timeout:\n loop_count+=1\n try:\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n except boto.exception.EC2ResponseError:\n ### need to wait a little time for AWS to register the requests, if this function called\n ### right after create_spot_instances\n time.sleep(3)\n continue\n for sir in spot_reqs:\n if sir.state != 'open':\n processed_dict[sir.id] = True\n\n if not all ( processed_dict.values()):\n time.sleep(15)\n\n\n ### get disposition of each spot instance request\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n instance_ids = list()\n instance_ready = dict()\n for sir in spot_reqs:\n if sir.state == 'open':\n self.request_status_dict[sir.id] = 'timed out'\n else:\n self.request_status_dict[sir.id] = sir.status.code\n\n if sir.status.code == 'fulfilled':\n instance_ids.append(sir.instance_id)\n instance_ready[sir.instance_id] = False\n else:\n self.failed_req_ids.append(sir.id)\n \n ### wait for ready states in the fulfilled instances\n while not all ( instance_ready.values()) and loop_count <= timeout:\n loop_count+=1\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'pending':\n instance_ready[inst.id] = True\n \n if not all (instance_ready.values()):\n time.sleep(15)\n\n ### get final dispositions of instances\n good_instances =0\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'running':\n sir_id = inst.spot_instance_request_id\n self.failed_req_ids.append(sir_id)\n if inst.state == 'pending':\n self.request_status_dict[sir_id] = 'timed out'\n else:\n self.request_status_dict[sir_id] = 'post-fulfillment premature instance termination'\n else:\n if self.use_private_ips:\n ipaddr=inst.private_ip_address\n else:\n ipaddr=inst.ip_address\n self.instance_ids.append(inst.id)\n self.ip_dict[inst.id] = ipaddr\n self.rev_ip_dict[ipaddr] = inst.id\n self.request_status_dict[sir_id] = 'running'\n good_instances+=1\n\n\n ### might have to sleep a little bit after running status toggles before it can accept ssh connections\n # put a 30 second delay in\n time.sleep(30)\n\n return (len (spot_req_ids), good_instances) \n\n ### to retrieve good instances: awsobj.instance_ids[-good_instances:]",
"def describe_spot_price_history(DryRun=None, StartTime=None, EndTime=None, InstanceTypes=None, ProductDescriptions=None, Filters=None, AvailabilityZone=None, MaxResults=None, NextToken=None):\n pass",
"def describe_spot_fleet_request_history(DryRun=None, SpotFleetRequestId=None, EventType=None, StartTime=None, NextToken=None, MaxResults=None):\n pass",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def get_listing():\n\n ec2 = boto3.client('ec2')\n listing = []\n\n try:\n full_listing = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ 'running' ]\n }\n ],\n MaxResults=1000)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n for reservation in full_listing['Reservations']:\n for instance in reservation['Instances']:\n listing.append(instance)\n\n return listing",
"def instance_from_response(response: Dict) -> List[EC2Instance]:\n ec2_instances = []\n for reservation in response.get(\"Reservations\"):\n for instance in reservation.get(\"Instances\"):\n if dns := instance.get(\"PublicDnsName\"):\n public_dns_name = dns\n else:\n public_dns_name = \"NONE\"\n if ip := instance.get(\"PublicIpAddress\"):\n public_ip_address = ip\n else:\n public_ip_address = \"NONE\"\n ec2_instance = EC2Instance(\n image_id=instance.get(\"ImageId\"),\n instance_id=instance.get(\"InstanceId\"),\n instance_type=instance.get(\"InstanceType\"),\n launch_time=instance.get(\"LaunchTime\"),\n availability_zone=instance.get(\"Placement\").get(\"AvailabilityZone\"),\n private_dns_name=instance.get(\"PrivateDnsName\"),\n private_ip_address=instance.get(\"PrivateIpAddress\"),\n public_dns_name=public_dns_name,\n public_ip_address=public_ip_address,\n state=instance.get(\"State\").get(\"Name\"),\n subnet_id=instance.get(\"SubnetId\"),\n vpc_id=instance.get(\"VpcId\"),\n tags=instance.get(\"Tags\"),\n )\n ec2_instances.append(ec2_instance)\n\n return ec2_instances",
"def _show_instances(self):\n conn = ec2.connect_to_region(\n self.availability_zone,\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n )\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n print reservation\n for instance in reservation.instances:\n print instance\n print '- AMI ID:', instance.image_id\n print '- Instance Type:', instance.instance_type\n print '- Availability Zone:', instance.placement",
"def start_server():\n log.info(\"Logging into AWS\")\n\n if _server_is_running():\n sys.exit(\"There is already a g2.2xlarge instance running\")\n\n log.info(\"Creating spot instance request for ${}\"\n .format(MAX_DOLLARS_PER_HOUR))\n output = ec2.meta.client.request_spot_instances(\n DryRun=False,\n SpotPrice=MAX_DOLLARS_PER_HOUR,\n InstanceCount=1,\n LaunchSpecification={\n 'ImageId': 'ami-ee897b8e',\n 'InstanceType': 'g2.2xlarge',\n 'KeyName': KEYNAME}\n )\n if output['ResponseMetadata']['HTTPStatusCode'] != 200:\n sys.exit(\"There was an issue with the request.\")\n else:\n log.info(\"Success! Your spot request is pending fufillment.\")\n request_id = output['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n\n _is_spot_fufilled(request_id)\n log.info(\"Server successfully provisioned\")\n\n while not _server_is_running():\n log.info(\"Still waiting for the server to be ready\")\n sleep(10)\n\n self.log(\"sleeping a bit\")\n sleep(60)\n\n log.info(\"Setting up instance\")\n set_up_server()\n ip = _get_ip_address()\n log.info(\"ssh -i {} ec2-user@{}\".format(PATH_TO_PEM, ip))",
"def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCount=None, OfferingClass=None):\n pass",
"def _retrieve_instances_info_from_ec2(self, instance_ids: list):\n complete_instances = []\n partial_instance_ids = []\n\n if instance_ids:\n try:\n ec2_client = boto3.client(\"ec2\", region_name=self._region, config=self._boto3_config)\n paginator = ec2_client.get_paginator(\"describe_instances\")\n response_iterator = paginator.paginate(InstanceIds=instance_ids)\n filtered_iterator = response_iterator.search(\"Reservations[].Instances[]\")\n\n for instance_info in filtered_iterator:\n try:\n # Try to build EC2Instance objects using all the required fields\n EC2Instance.from_describe_instance_data(instance_info)\n complete_instances.append(instance_info)\n except KeyError as e:\n logger.debug(\"Unable to retrieve instance info: %s\", e)\n partial_instance_ids.append(instance_info[\"InstanceId\"])\n except ClientError as e:\n logger.debug(\"Unable to retrieve instance info: %s\", e)\n partial_instance_ids.extend(instance_ids)\n\n return complete_instances, partial_instance_ids",
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):\n pass",
"def getReservedInstances(verbose):\n lres = {}\n jResp = EC2C.describe_reserved_instances()\n for reserved in jResp['ReservedInstances']:\n if reserved['State'] == 'active':\n if verbose:\n lres[reserved['InstanceType']] = str(reserved['Start'])+\";\"+\\\n str(reserved['End'])+\";\"+\\\n str(reserved['InstanceCount'])+\";\"+\\\n reserved['ProductDescription']+\";\"+\\\n str(reserved['UsagePrice'])\n else:\n if re.search(\"win\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"windows\"\n elif re.search(\"red hat\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"redhat\"\n elif re.search(\"suse\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"suse\"\n else:\n os = \"linux\"\n lres[reserved['InstanceType']+\";\"+os] = str(reserved['InstanceCount'])\n return lres",
"def get_spot_price(instance_type, region_name):\n ec2_client = boto3.client('ec2', region_name=region_name)\n response = ec2_client.describe_spot_price_history(\n InstanceTypes=[instance_type],\n ProductDescriptions=['Linux/UNIX'],\n MaxResults=1)\n\n spot_price = response['SpotPriceHistory'][0]['SpotPrice']\n return float(spot_price)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the Spot price history. For more information, see Spot Instance Pricing History in the Amazon Elastic Compute Cloud User Guide . When you specify a start and end time, this operation returns the prices of the instance types within the time range that you specified and the time when the price changed. The price is valid within the time period that you specified; the response merely indicates the last time that the price changed.
|
def describe_spot_price_history(DryRun=None, StartTime=None, EndTime=None, InstanceTypes=None, ProductDescriptions=None, Filters=None, AvailabilityZone=None, MaxResults=None, NextToken=None):
pass
|
[
"def get_spot_price(instance_type, region_name):\n ec2_client = boto3.client('ec2', region_name=region_name)\n response = ec2_client.describe_spot_price_history(\n InstanceTypes=[instance_type],\n ProductDescriptions=['Linux/UNIX'],\n MaxResults=1)\n\n spot_price = response['SpotPriceHistory'][0]['SpotPrice']\n return float(spot_price)",
"def page__pricehistory(app, ctx):\r\n page = Template(ctx)\r\n page.add(H1(\"Price History for %s/%s\" % (ctx.base, ctx.quote)))\r\n\r\n tbl, = page.add(TABLE(THEAD(TR(TH(\"Date\"), TH(\"Rate\"))),\r\n CLASS='price_history'))\r\n\r\n prices = app.ledger.directives['price'].prices\r\n phist = prices[(ctx.base, ctx.quote)]\r\n for date_, rate in phist:\r\n tbl.append( TR(TD(date_.isoformat()), TD(str(rate))) )\r\n\r\n return page.render(app)",
"def price_range(self) -> Optional[pulumi.Input['GoogleCloudRecommendationengineV1beta1ProductCatalogItemPriceRangeArgs']]:\n return pulumi.get(self, \"price_range\")",
"def _read_prices(self, prices):\n data = prices\n list_prices = []\n for k, v in data.get('products').items():\n if v.get('attributes').get('currentGeneration') == 'Yes':\n self.products.append({k: {\"instance_type\": v.get(\"attributes\").\n get(\"instanceType\"), \"storage\": v.get(\"attributes\").get(\n \"storage\")}})\n\n for sku_id, hourly_price in data.get('terms').get(self.AWS_DEFAULT_TERMS).items():\n for hourly_price_id, price_rates in data.get('terms').get(self.AWS_DEFAULT_TERMS).get(\n sku_id).items():\n rates = \"{}.{}.{}\".format(sku_id, self.AWS_HOURLY_TERMS_CODE, self.AWS_RATE_CODE)\n if \"{}.{}\".format(sku_id, self.AWS_HOURLY_TERMS_CODE):\n if sku_id == price_rates.get('sku'):\n if rates in price_rates.get('priceDimensions'):\n list_prices.append({\"sku\": sku_id,\n \"price\": price_rates.get('priceDimensions').get(\n rates).get('pricePerUnit').get('USD')})\n\n return list_prices",
"def get_market_price_history(asset1, asset2, start_ts=None, end_ts=None, as_dict=False):\n now_ts = calendar.timegm(time.gmtime())\n if not end_ts: # default to current datetime\n end_ts = now_ts\n if not start_ts: # default to 180 days before the end date\n start_ts = end_ts - (180 * 24 * 60 * 60)\n base_asset, quote_asset = util.assets_to_asset_pair(asset1, asset2)\n\n # get ticks -- open, high, low, close, volume\n result = config.mongo_db.trades.aggregate([\n {\"$match\": {\n \"base_asset\": base_asset,\n \"quote_asset\": quote_asset,\n \"block_time\": {\n \"$gte\": datetime.datetime.utcfromtimestamp(start_ts)\n } if end_ts == now_ts else {\n \"$gte\": datetime.datetime.utcfromtimestamp(start_ts),\n \"$lte\": datetime.datetime.utcfromtimestamp(end_ts)\n }\n }},\n {\"$project\": {\n \"year\": {\"$year\": \"$block_time\"},\n \"month\": {\"$month\": \"$block_time\"},\n \"day\": {\"$dayOfMonth\": \"$block_time\"},\n \"hour\": {\"$hour\": \"$block_time\"},\n \"block_index\": 1,\n \"unit_price\": 1,\n \"base_quantity_normalized\": 1 # to derive volume\n }},\n {\"$group\": {\n \"_id\": {\"year\": \"$year\", \"month\": \"$month\", \"day\": \"$day\", \"hour\": \"$hour\"},\n \"open\": {\"$first\": \"$unit_price\"},\n \"high\": {\"$max\": \"$unit_price\"},\n \"low\": {\"$min\": \"$unit_price\"},\n \"close\": {\"$last\": \"$unit_price\"},\n \"vol\": {\"$sum\": \"$base_quantity_normalized\"},\n \"count\": {\"$sum\": 1},\n }},\n {\"$sort\": SON([(\"_id.year\", pymongo.ASCENDING), (\"_id.month\", pymongo.ASCENDING), (\"_id.day\", pymongo.ASCENDING), (\"_id.hour\", pymongo.ASCENDING)])},\n ])\n result = list(result)\n if not len(result):\n return False\n\n midline = [((r['high'] + r['low']) / 2.0) for r in result]\n if as_dict:\n for i in range(len(result)):\n result[i]['interval_time'] = int(calendar.timegm(datetime.datetime(\n result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000)\n result[i]['midline'] = midline[i]\n del result[i]['_id']\n return result\n else:\n list_result = []\n for i in range(len(result)):\n list_result.append([\n int(calendar.timegm(datetime.datetime(\n result[i]['_id']['year'], result[i]['_id']['month'], result[i]['_id']['day'], result[i]['_id']['hour']).timetuple()) * 1000),\n result[i]['open'], result[i]['high'], result[i]['low'], result[i]['close'], result[i]['vol'],\n result[i]['count'], midline[i]\n ])\n return list_result",
"def historical_prices(self) -> List[dict]:\n\n return self._historical_prices",
"def get_performance(symbol, start_date=config.start_date, end_date=config.end_date):\n\n if utils.refresh(utils.get_file_path(config.prices_data_path, prices.price_table_filename, symbol=symbol), refresh=False):\n prices.download_data_from_yahoo(symbol, start_date=start_date, end_date=end_date)\n df = pd.read_csv(utils.get_file_path(config.prices_data_path, prices.price_table_filename, symbol=symbol), index_col=\"Date\", parse_dates=[\"Date\"])[start_date:end_date]\n return df[\"Close\"].add(df[\"Dividends\"].cumsum())[-1] / df[\"Close\"][0]",
"def price_on_amazon(self):\n #Getting html page data from amazon url\n res = requests.get(self.url_data[1], headers=self.headers)\n res.raise_for_status()\n soup = BeautifulSoup(res.text, 'lxml')\n #Filtering the data\n price = soup.find(\"span\", {\"id\": \"priceblock_dealprice\"})\n if price == None:\n price = soup.find(\"span\", {\"id\": \"priceblock_ourprice\"})\n if price == None:\n return ['Not Found', 0]\n product_name = soup.find(\"span\", \n {\"id\": \"productTitle\"}).text.replace('\\n', '')\n #Purifying filtered data and converting into desired format\n price = price.text\n price = price.split('.')[0]\n price = price.replace(',', '')\n current_price = ''\n if not price.isnumeric():\n price = price[1:]\n for txt in list(price):\n if txt in [str(i) for i in range(10)]:\n current_price += txt\n \n data = [f\"{product_name[:35]}...\", int(current_price)]\n return data",
"def list_price_range(query_params):\n date_start = query_params.get(\"start_date\").split(\"-\")\n date_end = query_params.get(\"end_date\").split(\"-\")\n stock = int(query_params.get(\"stock\"))\n try:\n s_year = int(date_start[0])\n s_month = int(date_start[1])\n s_day = int(date_start[2])\n e_year = int(date_end[0])\n e_month = int(date_end[1])\n e_day = int(date_end[2])\n s_date = datetime(\n year=s_year, month=s_month, day=s_day, hour=0, minute=0, second=0\n ).replace(tzinfo=pytz.UTC)\n # s_date = datetime(year=2019, month=1, day=22, hour=0, minute=0, second=0)\n e_date = datetime(\n year=e_year,\n month=e_month,\n day=e_day,\n hour=0,\n minute=0,\n second=0,\n tzinfo=pytz.UTC,\n ).replace(tzinfo=pytz.UTC)\n\n except Exception:\n raise APIException(detail=\"Provide proper dates\")\n return PriceList.objects.filter(\n price_date__gte=s_date, price_date__lt=e_date, stock_id=stock\n )",
"def spot_price(self) -> str:\n return pulumi.get(self, \"spot_price\")",
"def _collect_price_time_series(self):\n r = requests.get(self.GRAPH_URL)\n #dictionary of 2 dictionaries, \"daily\" and \"average\"\n response = r.json()\n daily_series = TimeSeries.from_dictionary(response[\"daily\"])\n average_series = TimeSeries.from_dictionary(response[\"average\"])\n return (daily_series, average_series)",
"def get_prices(ticker_list, start, stop, price_types=['Close'], logger=logger):\n\n price_array = []\n num = 1\n total = len(ticker_list)\n for stock in ticker_list:\n logger.info(f'Scraping {stock} - {num} out of {total} tickers')\n try:\n price_array.append(web.DataReader(stock, 'yahoo', start, stop))\n except: # noqa\n price_array.append('NA')\n num += 1\n price_df = dict(zip(ticker_list, price_array))\n dels = []\n for key in price_df.keys():\n if type(price_df[key]) == str:\n dels.append(key)\n for key in dels:\n price_df.pop(key, None)\n price_df = pd.concat(price_df)\n price_df = price_df[['Close']].reset_index()\n price_df.columns = ['ticker', 'date'] + [i.lower() for i in ['Close']]\n return price_df",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def estimates_price(\n self,\n start_latitude: float,\n start_longitude: float,\n end_latitude: float,\n end_longitude: float,\n max_lines: Optional[int] = None) -> List['Product']:\n url = \"\".join([\n self.url_prefix,\n '/estimates/price/',\n str(start_latitude),\n '/',\n str(start_longitude),\n '/',\n str(end_latitude),\n '/',\n str(end_longitude)])\n\n params = {} # type: Dict[str, str]\n\n if max_lines is not None:\n params['max_lines'] = json.dumps(max_lines)\n\n resp = self.session.request(\n method='get',\n url=url,\n params=params,\n )\n\n with contextlib.closing(resp):\n resp.raise_for_status()\n return from_obj(\n obj=resp.json(),\n expected=[list, Product])",
"def get_24h_price_change(symbol=None):\n r = requests.get(CurrencyComConstants.PRICE_CHANGE_24H_ENDPOINT,\n params={'symbol': symbol} if symbol else {})\n return r.json()",
"def get_slice_prices(self, start_date, end_date):\r\n return fill_missing_data_business(self.price, start_date, end_date,'B')\r\n # result = np.nan\r\n # if isinstance(end_date, int):\r\n # inter_dates = [datetime.strftime(item, '%Y-%m-%d') for item in\r\n # pd.date_range(start=start_date, freq='B', periods=end_date)]\r\n # result = pd.DataFrame(self.price.reindex(inter_dates, method='ffill').loc[:].astype(float))\r\n # elif isinstance(end_date, str):\r\n # inter_dates = [datetime.strftime(item, '%Y-%m-%d') for item in\r\n # pd.date_range(start=start_date, freq='B', end=end_date)]\r\n # result = pd.DataFrame(self.price.reindex(inter_dates, method='ffill').loc[:].astype(float))\r\n # else:\r\n # print(\"input end_date as string or window size as int\")\r\n # return\r\n #\r\n # return result\r",
"def tickPrice(self, TickerId, tickType, price, canAutoExecute):\n for security in self.data: \n if security.req_real_time_price_id==TickerId:\n self.data[security].datetime=self.stime\n self.log.debug(__name__ + ', ' + str(TickerId) + \", \" + MSG_TABLE[tickType]\n + \", \" + str(security.symbol) + \", price = \" + str(price))\n if tickType==1: #Bid price\n self.data[security].bid_price = price\n self.update_DataClass(security, 'bid_price_flow', price)\n elif tickType==2: #Ask price\n self.data[security].ask_price = price\n self.update_DataClass(security, 'ask_price_flow', price) \n elif tickType==4: #Last price\n self.data[security].price = price\n self.update_DataClass(security, 'last_price_flow', price) \n elif tickType==6: #High daily price\n self.data[security].daily_high_price=price\n elif tickType==7: #Low daily price\n self.data[security].daily_low_price=price\n elif tickType==9: #last close price\n self.data[security].daily_prev_close_price = price\n elif tickType == IBCpp.TickType.OPEN:\n self.data[security].daily_open_price = price\n\n #if (self.stime_previous is None or self.stime - \n #self.stime_previous > self.barSize):\n # # the begining of the bar\n # self.data[security].open_price=self.data[security].bid_price\n # self.data[security].high=self.data[security].bid_price\n # self.data[security].low=self.data[security].bid_price\n #else:\n # if tickType==4 and price>self.data[security].high: #Bid price\n # self.data[security].high=price\n # if tickType==4 and price<self.data[security].low: #Bid price\n # self.data[security].low=price",
"def lookup_prices(symbol: str,\n period: int = 2,\n period_type: str = \"month\",\n frequency: int = 1,\n frequency_type: str = \"daily\",\n end_date: str = \"\",\n num_entries_to_analyze: int = 40) -> pd.DataFrame:\n\n if end_date == \"\":\n end_date = int(round(time.time() * 1000))\n else:\n end_date = int(\n round(datetime.datetime.strptime(end_date, '%m-%d-%Y').timestamp() * 1000))\n\n endpoint = f\"https://api.tdameritrade.com/v1/marketdata/{symbol}/pricehistory\"\n payload = {\n 'apikey': config.config['AMERITRADE']['API_KEY'],\n 'period': period,\n 'periodType': period_type,\n 'frequency': frequency,\n 'frequencyType': frequency_type,\n 'endDate': end_date,\n 'needExtendedHoursData': 'false',\n }\n\n # TODO: Add more exception handling\n try:\n content = requests.get(url=endpoint, params=payload)\n except requests.exceptions.ProxyError:\n print(\"ProxyError, maybe you need to connect to to your proxy server?\")\n sys.exit()\n\n try:\n data = content.json()\n except json.decoder.JSONDecodeError:\n print(\"Error, API Request Returned: \" + str(content))\n print(\"Endpoint: \" + endpoint)\n print(\"payload:: \" + str(payload))\n return None\n\n candle_data = pd.DataFrame.from_records(data['candles'])\n\n if candle_data.empty:\n return None\n\n candle_data = candle_data[['datetime', 'open', 'high', 'low', 'close', 'volume']]\n candle_data = candle_data[-num_entries_to_analyze:]\n candle_data = pd.DataFrame.reset_index(candle_data, drop=True)\n\n # Convert datetime TODO: Understand the different timestamps used\n candle_data['datetime'] = mdates.epoch2num(candle_data['datetime'] / 1000)\n\n return candle_data",
"def get_the_price(self, t):\r\n try:\r\n return float(self.price.loc[t])\r\n except:\r\n print(\"couldn't find the price at time of \" + self.ticker + \" \" + t)\r\n return"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[EC2VPC only] Describes the stale security group rules for security groups in a specified VPC. Rules are stale when they reference a deleted security group in a peer VPC, or a security group in a peer VPC for which the VPC peering connection has been deleted.
|
def describe_stale_security_groups(DryRun=None, VpcId=None, MaxResults=None, NextToken=None):
pass
|
[
"def vpc_classic_link_security_groups(self) -> Sequence[str]:\n warnings.warn(\"\"\"With the retirement of EC2-Classic the vpc_classic_link_security_groups attribute has been deprecated and will be removed in a future version.\"\"\", DeprecationWarning)\n pulumi.log.warn(\"\"\"vpc_classic_link_security_groups is deprecated: With the retirement of EC2-Classic the vpc_classic_link_security_groups attribute has been deprecated and will be removed in a future version.\"\"\")\n\n return pulumi.get(self, \"vpc_classic_link_security_groups\")",
"def revoke_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def validate_security_groups(sg_spec):\n exit_if_none(sg_spec, \"Missing security groups\")\n actual_sgs = {}\n paginator = boto3.client('ec2').get_paginator('describe_security_groups')\n for page in paginator.paginate():\n for sg in page['SecurityGroups']:\n actual_sgs[sg['GroupId']] = sg.get('VpcId') # some people may still have non-VPC groups\n security_groups = []\n vpcs = set()\n for sg_id in sg_spec.split(\",\"):\n vpc_id = actual_sgs.get(sg_id)\n exit_if_none(vpc_id, f\"invalid security group: {sg_id}\")\n security_groups.append(sg_id)\n vpcs.add(vpc_id)\n if (len(vpcs) > 1):\n exit_if_none(None, \"security groups belong to different VPCs\")\n return security_groups",
"def refresh_security_group_rules(self, *args, **kwargs):\n raise NotImplementedError()",
"def delete_security_groups():\n print('Deleting Security Groups')\n client = boto3.resource('ec2')\n for security_group in client.security_groups.all():\n print('Deleting Security Group rules for security group {}'.format(security_group.id))\n for perm in security_group.ip_permissions:\n security_group.revoke_ingress(\n IpPermissions=[perm]\n )\n for perm in security_group.ip_permissions_egress:\n security_group.revoke_egress(\n IpPermissions=[perm]\n )\n for security_group in client.security_groups.all():\n if security_group.group_name != 'default':\n print('Deleting Security Group {}'.format(security_group.id))\n security_group.delete()\n print('Security Groups deleted')",
"def get_rds_security_groups(self):\n rds_client = self.session.client('rds')\n rdses = rds_client.describe_db_instances()\n for rds in rdses['DBInstances']:\n self.rds_count += 1\n for group in rds['VpcSecurityGroups']:\n self.security_groups_in_use.add(group['VpcSecurityGroupId'])",
"def get_ec2_security_groups(self):\n ec2_client = self.session.client('ec2')\n instances = ec2_client.describe_instances()\n reservations = instances['Reservations']\n\n for reservation in reservations:\n for instance in reservation['Instances']:\n self.ec2_instances_count += 1\n for group in instance['SecurityGroups']:\n self.security_groups_in_use.add(group['GroupId'])",
"def remove_sg_inbound_rule(self):\n try:\n vpc = self.ec2_client.Vpc(id=self.cluster_props['VpcId'])\n sg_list = list(vpc.security_groups.all())\n for sg in sg_list:\n if sg.group_id == self.security_group_id:\n sg.authorize_ingress(\n GroupName=sg.group_name,\n CidrIp='0.0.0.0/0',\n IpProtocol='TCP',\n FromPort=int(self.dwh_port),\n ToPort=int(self.dwh_port))\n continue\n except Exception as e:\n print(e)",
"def AddVpcNetworkGroupFlags(parser, resource_kind='service', is_update=False):\n group = parser.add_argument_group('Direct VPC egress setting flags group.')\n AddVpcNetworkFlags(group, resource_kind)\n AddVpcSubnetFlags(group, resource_kind)\n if not is_update:\n AddVpcNetworkTagsFlags(group, resource_kind)\n return\n tags_group = group.add_mutually_exclusive_group()\n AddVpcNetworkTagsFlags(tags_group, resource_kind)\n AddClearVpcNetworkTagsFlags(tags_group, resource_kind)",
"def get_redshift_security_groups(self):\n redshift_client = self.session.client('redshift')\n redshifts = redshift_client.describe_clusters()\n for cluster in redshifts['Clusters']:\n self.redshift_count += 1\n for group in cluster['VpcSecurityGroups']:\n self.security_groups_in_use.add(group['VpcSecurityGroupId'])",
"def test_050_create_security_groups(self):\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"WebServerSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.web_security_group = sg\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"NATSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.nat_security_group = sg\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"DBServerSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.db_security_group = sg\n\n sg = self.ctx.web_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 1433, 1433,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 3306, 3306,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 22, 22,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=80, to_port=80,\n cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=443, to_port=443,\n cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=22, to_port=22,\n cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=3389,\n to_port=3389, cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n\n sg = self.ctx.nat_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 443, 443, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"udp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=53,\n to_port=53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"udp\", from_port=53,\n to_port=53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=80, to_port=80,\n cidr_ip=str(self.db_subnet))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=443, to_port=443,\n cidr_ip=str(self.db_subnet))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=22, to_port=22,\n cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n\n sg = self.ctx.db_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 443, 443, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"udp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=1433,\n to_port=1433,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=3306,\n to_port=3306,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=22,\n to_port=22,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)",
"def authorize_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def getsecuritygroups(show):\n securitygrouplist=[]\n \n try:\n securitygroups=ec2.describe_security_groups()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting security group data: \\n\\n\\n\")\n print(e)\n for securitygroup in securitygroups['SecurityGroups']:\n name=securitygroup['GroupName']\n \n gid=securitygroup['GroupId']\n description=securitygroup['Description']\n if show:\n print(\"name: \"+name+\" Descripton: \"+ description)\n securitygrouplist.append({ \"name\":gid})\n return securitygrouplist",
"def test_create_list_sec_grp_no_rules(self):\n sec_grp_settings = SecurityGroupConfig(\n name=self.sec_grp_name + \"-1\", description='hello group')\n self.security_groups.append(neutron_utils.create_security_group(\n self.neutron, self.keystone, sec_grp_settings))\n\n sec_grp_settings2 = SecurityGroupConfig(\n name=self.sec_grp_name + \"-2\", description='hola group')\n self.security_groups.append(neutron_utils.create_security_group(\n self.neutron, self.keystone, sec_grp_settings2))\n\n returned_sec_groups = neutron_utils.list_security_groups(self.neutron)\n\n self.assertIsNotNone(returned_sec_groups)\n worked = 0\n for sg in returned_sec_groups:\n if sec_grp_settings.name == sg.name:\n worked += 1\n elif sec_grp_settings2.name == sg.name:\n worked += 1\n\n self.assertEqual(worked, 2)",
"def revoke_security_group_ingress(DryRun=None, GroupName=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def update_all_clusters_in_vpc(self):\n sections = [section for section in self.config_rds.sections()\n if section.split(\"-\")[0] == self.vpc_name]\n logging.debug(\"The following RDS clusters will be updated: %s\", \", \".join(sections))\n for section in sections:\n self.update_cluster(section)",
"def test_list_security_groups(self):\n admin_resource_id = self.secgroup['id']\n with (self.override_role_and_validate_list(\n admin_resource_id=admin_resource_id)) as ctx:\n ctx.resources = self.security_groups_client.list_security_groups(\n id=admin_resource_id)[\"security_groups\"]",
"def enforce_security_groups_rules(self) -> None:\n sagsnl_sg = self.get_security_group(SwiftComponents.SAGSNL + \"SG\")\n rds_sg = self.get_security_group(\"RDSSG\")\n mq_sg = self.get_security_group(\"MQSG\")\n amh_sg = self.get_security_group(SwiftComponents.AMH + \"SG\")\n\n boto = boto3.client(\"ec2\")\n prefix_lists = boto.describe_prefix_lists(\n Filters=[{\"Name\": \"prefix-list-name\", \"Values\": [\"com.amazonaws.*.s3\"]}])\n s3_prefix_list = prefix_lists[\"PrefixLists\"][0][\"PrefixListId\"]\n\n sagsnl_sg.connections.allow_from(other=amh_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"SAGSNL- AMH (48002,48003)\",\n from_port=48002,\n to_port=48003\n ),\n description=\"Incoming connection from AMH\")\n\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._workstation_ip_range,\n from_port=2443, to_port=2443, is_ingress=True,\n description=\"SWP Web GUI Interface Ingress from workstation\"\n )\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.TCP,\n prefix_list=s3_prefix_list,\n from_port=443, to_port=443, is_ingress=False,\n description=\"Egress to S3 VPC Gateway Endpoint\"\n )\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.ALL,\n cidr_range=self._swift_ip_range,\n from_port=0, to_port=65535, is_ingress=False,\n description=\"To SWIFT via VGW and VPN\"\n )\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._hsm_ip,\n from_port=1792, to_port=1792, is_ingress=False,\n description=\"To HSM via VGW\"\n )\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._hsm_ip,\n from_port=22, to_port=22, is_ingress=False,\n description=\"To HSM (SSH) via VGW\"\n )\n self.add_security_group_rule(SwiftComponents.SAGSNL + \"SG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._hsm_ip,\n from_port=48321, to_port=48321, is_ingress=False,\n description=\"TO HSM (Remote PED) via VGW \"\n )\n\n amh_sg.connections.allow_to(other=sagsnl_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"AMH - SAGSNL (48002, 48003)\",\n from_port=48002,\n to_port=48003\n ),\n description=\"AMH to SAGSNL connection\")\n\n amh_sg.connections.allow_to(other=rds_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"RDS (1521)\",\n from_port=1521,\n to_port=1521\n ),\n description=\"AMH - RDS (1521)\")\n amh_sg.connections.allow_to(other=mq_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"MQ (61617)\",\n from_port=61617,\n to_port=61617\n ),\n description=\"AMH - MQ (61617)\")\n self.add_security_group_rule(SwiftComponents.AMH + \"SG\", protocol=_ec2.Protocol.TCP,\n prefix_list=s3_prefix_list,\n from_port=443, to_port=443,\n is_ingress=False,\n description=\"AMH Egress to S3\"\n )\n self.add_security_group_rule(SwiftComponents.AMH + \"SG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._workstation_ip_range,\n from_port=8443, to_port=8443, is_ingress=True\n )\n rds_sg.connections.allow_from(other=amh_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"RDS (1521)\",\n from_port=1521,\n to_port=1521\n ),\n description=\"AMH - RDS (1521)\")\n\n mq_sg.connections.allow_from(other=amh_sg,\n port_range=_ec2.Port(\n protocol=_ec2.Protocol.TCP,\n string_representation=\"MQ (61617)\",\n from_port=61617,\n to_port=61617\n ),\n description=\"AMH - MQ (61617)\")\n self.add_security_group_rule(\"MQSG\", protocol=_ec2.Protocol.TCP,\n cidr_range=self._workstation_ip_range,\n from_port=8162, to_port=8162, is_ingress=True\n )",
"def AddVpcNetworkGroupFlagsForUpdate(parser, resource_kind='service'):\n group = parser.add_mutually_exclusive_group()\n AddVpcNetworkGroupFlags(group, resource_kind, is_update=True)\n AddClearVpcNetworkFlags(group, resource_kind)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the specified attribute of the specified volume. You can specify only one attribute at a time. For more information about EBS volumes, see Amazon EBS Volumes in the Amazon Elastic Compute Cloud User Guide .
|
def describe_volume_attribute(DryRun=None, VolumeId=None, Attribute=None):
pass
|
[
"def showattribute(self, vname=None, device=None):\n if device is None:\n device = sys.stdout\n if vname is None:\n vname = self.default_variable_name\n device.write(\"Attributes of \")\n device.write(vname)\n device.write(\" in file \")\n device.write(self.id)\n device.write(\":\\n\")\n device.write(str(self.listattribute(vname)))\n device.write(\"\\n\")",
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def describe_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):\n pass",
"def describe_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None):\n pass",
"def describe_attr_value(attr, die, section_offset):\r\n descr_func = _ATTR_DESCRIPTION_MAP[attr.form]\r\n val_description = descr_func(attr, die, section_offset)\r\n\r\n # For some attributes we can display further information\r\n extra_info_func = _EXTRA_INFO_DESCRIPTION_MAP[attr.name]\r\n extra_info = extra_info_func(attr, die, section_offset)\r\n return str(val_description) + '\\t' + extra_info",
"def _extract_attributes_from_volume(self):\n vol = nibabel.load(self.nifti_1)\n try:\n (xyz_units, t_units) = vol.get_header().xyzt_units()\n except:\n (xyz_units, t_units) = (None, None)\n if xyz_units == 'mm':\n xyz_units = 'Millimeters'\n elif xyz_units == 'm':\n xyz_units = 'Meters'\n elif xyz_units == 'um':\n xyz_units = 'Micrometers'\n else:\n xyz_units = None\n if t_units == 's':\n t_units = 'Seconds'\n elif t_units == 'ms':\n t_unit = 'Milliseconds'\n elif t_units == 'ms':\n t_unit = 'Microseconds'\n else:\n t_unit = None\n self.image_num_dimensions = len(vol.shape)\n pixdim = vol.get_header()['pixdim']\n for i in xrange(self.image_num_dimensions):\n setattr(self, 'image_extent%d' % (i+1), vol.shape[i])\n setattr(self, 'image_resolution%d' % (i+1), pixdim[i+1])\n if i < 3 and xyz_units:\n setattr(self, 'image_unit%d' % (i+1), xyz_unit)\n if i == 3 and t_units:\n self.image_unit4 = t_unit\n return",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def attributeInfo(multi=bool, inherited=bool, bool=bool, internal=bool, type=\"string\", hidden=bool, enumerated=bool, allAttributes=bool, logicalAnd=bool, writable=bool, userInterface=bool, leaf=bool, short=bool):\n pass",
"def volume(ctx, *args, **kwargs):",
"def volume_options_list_info(self, volume):\n return self.request( \"volume-options-list-info\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n }, {\n 'options': [ VolumeOptionInfo, True ],\n } )",
"def show_volume(svm_name) -> None:\n print()\n print(\"Getting Volume Details\")\n print(\"===================\")\n try:\n for volume in Volume.get_collection(\n **{\"svm.name\": svm_name}, fields=\"uuid\"):\n print(\n \"Volume name:-%s ; Volume uuid:-%s \" %\n (volume.name, volume.uuid))\n except NetAppRestError as error:\n print(\"Error:- \" % error.http_err_response.http_response.text)\n print(\"Exception caught :\" + str(error))",
"def Attributes(self) -> _n_5_t_17:",
"def volume(self):\n return self.intrinsicValue(\"measuredvolume\")",
"def info(self, attribute):\n return self.call('catalog_product_attribute.info', [attribute])",
"def volume(ctx, vol):\n avr = ctx.obj['avr']\n if vol:\n try:\n avr.volume = vol\n click.echo(avr.volume)\n except ReponseException as e:\n if \"Volume\" in str(e):\n msg = \"Volume must be specified in -0.5 increments.\"\n err = click.style(msg, fg='red')\n click.echo(err, err=True)\n else:\n click.echo(avr.volume)",
"def volumeBind(influence=\"string\", name=\"string\"):\n pass",
"def test_volume_info(self):\n pass",
"def recordAttr(delete=bool, attribute=\"string\"):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event.
|
def describe_volume_status(DryRun=None, VolumeIds=None, Filters=None, NextToken=None, MaxResults=None):
pass
|
[
"def volume_status(self, volume):\r\n volume = self._get_volume(volume)\r\n raid = self._get_raid(volume[\"devicefile\"])\r\n if volume is not None and raid is not None:\r\n return raid[\"state\"]",
"def volume_status(mnode, volname):\n return RestClient(mnode).handle_request(\n \"GET\", \"/v1/volumes/%s/status\" % volname,\n httplib.OK, None)",
"def volume_move_status(self, source_volume=None, is_verbose=None):\n return self.request( \"volume-move-status\", {\n 'source_volume': [ source_volume, 'source-volume', [ basestring, 'None' ], False ],\n 'is_verbose': [ is_verbose, 'is-verbose', [ bool, 'None' ], False ],\n }, {\n 'status': [ VolMoveStatusInfo, True ],\n } )",
"def volume_snapshot_statuses(self):\n return self._volume_snapshot_statuses",
"def get_status(self):\n result = None\n try:\n r = requests.get(self.url_status)\n result = json.loads(r.content)\n except Exception as e:\n LOGGER.error('Could not get status of this volume: %s. Exception is: %s' % (self.url_status, e))\n result = None\n return result",
"def send_volume_command(self, room: Room, speakers: List[Speaker], volumes: List[int]) -> None:\n self.room_info[room.room_id]['current_volume'] = volumes\n self.room_info[room.room_id]['volume_confirmed'] = False\n self.room_info[room.room_id]['last_volume_change'] = time()\n\n command = SonosVolumeCommand(speakers, volumes)\n self.sonos.send_command(command)",
"def get_status(self):\n r = requests.get(self.url_status)\n try:\n result = json.loads(r.content)\n except Exception as e:\n LOGGER.error('Could not get status of this volume: %s. Exception is: %s' % (self.url_status, e))\n result = None\n return result",
"def volume_options_list_info(self, volume):\n return self.request( \"volume-options-list-info\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n }, {\n 'options': [ VolumeOptionInfo, True ],\n } )",
"def _display_oci_volume_list(volumes, output_mode, details, truncate):\n\n def _get_displayable_size(_, volume):\n return volume.get_size(format_str=OCI_VOLUME_SIZE_FMT.HUMAN.name)\n\n def _get_attached_instance_name(_, volume):\n global _this_instance_ocid\n if not volume.is_attached():\n return '-'\n _vol_instance_attach_to = volume.get_instance()\n if _vol_instance_attach_to.get_ocid() == _this_instance_ocid:\n return \"this instance\"\n pip = _vol_instance_attach_to.get_public_ip()\n if pip:\n return \"%s (%s)\" % (_vol_instance_attach_to.get_display_name(), _vol_instance_attach_to.get_public_ip())\n return _vol_instance_attach_to.get_display_name()\n\n def _get_comp_name(_, volume):\n \"\"\" keep track of compartment per ID as it may be expensive info to fetch \"\"\"\n _map = getattr(_get_comp_name, 'c_id_to_name', {})\n if volume.get_compartment_id() not in _map:\n _map[volume.get_compartment_id()] = volume.get_compartment().get_display_name()\n setattr(_get_comp_name, 'c_id_to_name', _map)\n return _map[volume.get_compartment_id()]\n\n if len(volumes) == 0:\n print('No other volumes found.')\n else:\n _title = 'Block volumes information'\n _columns = [['Name', 32, 'get_display_name'],\n ['Size', 6, _get_displayable_size],\n ['Attached to', 32, _get_attached_instance_name],\n ['OCID', 32, 'get_ocid']]\n if details:\n _columns.extend((['IQN', 14, 'get_iqn'],\n ['Compartment', 14, _get_comp_name],\n ['Availability domain', 19, 'get_availability_domain_name']))\n if output_mode == 'compat':\n printerKlass = get_row_printer_impl('text')\n else:\n printerKlass = get_row_printer_impl(output_mode)\n\n printer = printerKlass(title=_title, columns=_columns, text_truncate=truncate)\n printer.printHeader()\n for vol in volumes:\n printer.printRow(vol)\n printer.rowBreak()\n printer.printFooter()\n printer.finish()",
"def test_volume_info(self):\n pass",
"def volume_handler(vols):\n global snap_create_message, snap_delete_message\n snap_create_message = \"List of snapshots created:\\n\"\n snap_delete_message = \"List of snapshots deleted:\\n\"\n \n for vol in vols:\n successful = make_snapshot(vol)\n if successful:\n remove_old_snapshots(vol)\n else:\n error = 'Error processing volume id ' + vol.id\n snap_create_message += error + '\\n'",
"def get_volume_stats(self):\n self.conf.update_config_value()\n self._update_volume_stats()",
"def get_volume_stats(self, refresh=False):\n if self._volume_stats is None or refresh:\n self._update_volume_stats()\n\n LOG.info(\n 'Successfully update volume stats. '\n 'backend: %(volume_backend_name)s, '\n 'vendor: %(vendor_name)s, '\n 'model_type: %(model_type)s, '\n 'system_id: %(system_id)s, '\n 'status: %(status)s, '\n 'driver_version: %(driver_version)s, '\n 'storage_protocol: %(storage_protocol)s.', self._volume_stats)\n\n return self._volume_stats",
"def describe_volumes(self, xml_bytes):\n root = XML(xml_bytes)\n result = []\n for volume_data in root.find(\"volumeSet\"):\n volume_id = volume_data.findtext(\"volumeId\")\n size = int(volume_data.findtext(\"size\"))\n snapshot_id = volume_data.findtext(\"snapshotId\")\n availability_zone = volume_data.findtext(\"availabilityZone\")\n status = volume_data.findtext(\"status\")\n create_time = volume_data.findtext(\"createTime\")\n create_time = datetime.strptime(\n create_time[:19], \"%Y-%m-%dT%H:%M:%S\")\n volume = model.Volume(\n volume_id, size, status, create_time, availability_zone,\n snapshot_id)\n result.append(volume)\n for attachment_data in volume_data.find(\"attachmentSet\"):\n instance_id = attachment_data.findtext(\"instanceId\")\n device = attachment_data.findtext(\"device\")\n status = attachment_data.findtext(\"status\")\n attach_time = attachment_data.findtext(\"attachTime\")\n attach_time = datetime.strptime(\n attach_time[:19], \"%Y-%m-%dT%H:%M:%S\")\n attachment = model.Attachment(\n instance_id, device, status, attach_time)\n volume.attachments.append(attachment)\n return result",
"def list(connection):\n volumes = get_watched_volumes(connection)\n\n if not volumes:\n logger.info('No watched volumes found')\n return\n\n logger.info(\n '+-----------------------'\n '+----------------------'\n '+--------------'\n '+------------+')\n logger.info(\n '| {volume:<21} '\n '| {volume_name:<20.20} '\n '| {interval:<12} '\n '| {retention:<10} |'.format(\n volume='Volume ID',\n volume_name='Volume name',\n interval='Interval',\n retention='Retention'))\n logger.info(\n '+-----------------------'\n '+----------------------'\n '+--------------'\n '+------------+')\n\n for volume in volumes:\n if 'AutomatedEBSSnapshots' not in volume.tags:\n interval = 'Interval tag not found'\n elif volume.tags['AutomatedEBSSnapshots'] not in VALID_INTERVALS:\n interval = 'Invalid interval'\n else:\n interval = volume.tags['AutomatedEBSSnapshots']\n\n if 'AutomatedEBSSnapshotsRetention' not in volume.tags:\n retention = 0\n else:\n retention = volume.tags['AutomatedEBSSnapshotsRetention']\n\n # Get the volume name\n try:\n volume_name = volume.tags['Name']\n except KeyError:\n volume_name = ''\n\n logger.info(\n '| {volume_id:<14} '\n '| {volume_name:<20.20} '\n '| {interval:<12} '\n '| {retention:<10} |'.format(\n volume_id=volume.id,\n volume_name=volume_name,\n interval=interval,\n retention=retention))\n\n logger.info(\n '+-----------------------'\n '+----------------------'\n '+--------------'\n '+------------+')",
"def status(ctx: click.Context) -> None:\n info = get(\"status\", lambda: status_call(ctx.obj[\"session\"]))\n click.echo(json_pretty(info))",
"def test_01_list_volumes(self):\n list_volume_response = Volume.list(\n self.apiclient,\n ids=[self.vm1_root_volume.id, self.vm2_root_volume.id, self.vm3_root_volume.id],\n type='ROOT',\n listAll=True\n )\n self.assertEqual(\n isinstance(list_volume_response, list),\n True,\n \"List Volume response was not a valid list\"\n )\n self.assertEqual(\n len(list_volume_response),\n 3,\n \"ListVolumes response expected 3 Volumes, received %s\" % len(list_volume_response)\n )",
"def ListVolumeStatsByVirtualVolume(ctx,\n virtual_volume_ids = None):\n if ctx.element is None:\n ctx.logger.error(\"You must establish at least one connection and specify which you intend to use.\")\n exit()\n\n\n\n virtual_volume_ids = parser.parse_array(virtual_volume_ids)\n\n ctx.logger.info(\"\"\"virtual_volume_ids = \"\"\"+str(virtual_volume_ids)+\"\"\";\"\"\"+\"\")\n try:\n ListVolumeStatsByVirtualVolumeResult = ctx.element.list_volume_stats_by_virtual_volume(virtual_volume_ids=virtual_volume_ids)\n except common.ApiServerError as e:\n ctx.logger.error(e.message)\n exit()\n except BaseException as e:\n ctx.logger.error(e.__str__())\n exit()\n\n cli_utils.print_result(ListVolumeStatsByVirtualVolumeResult, ctx.logger, as_json=ctx.json, depth=ctx.depth, filter_tree=ctx.filter_tree)",
"def get_status(self, vacuum_pump):\n vacuum_obj = self.vacuum[vacuum_pump]\n self.logger.info(vacuum_obj.query_status())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the specified EBS volumes. If you are describing a long list of volumes, you can paginate the output to make the list more manageable. The MaxResults parameter sets the maximum number of results returned in a single page. If the list of results exceeds your MaxResults value, then that number of results is returned along with a NextToken value that can be passed to a subsequent DescribeVolumes request to retrieve the remaining results. For more information about EBS volumes, see Amazon EBS Volumes in the Amazon Elastic Compute Cloud User Guide .
|
def describe_volumes(DryRun=None, VolumeIds=None, Filters=None, NextToken=None, MaxResults=None):
pass
|
[
"def list(self,\n **kwargs\n ):\n\n # dont filter_name=None,\n # dont filter_value=None,\n # dryrun=False):\n\n #:param filter_name (string)\n #:param filter_value (string)\n #:param volume_ids (list): The volume IDs\n\n # filter = \"[[\n # {\n # 'Name': 'xyz',\n # 'Values': [\n # 'abc',\n # ]\n # },\n # ]\"\n\n # filter = eval(filter)\n\n #banner('print kwargs')\n #print(kwargs)\n #print(kwargs['output'])\n\n client = boto3.client('ec2')\n dryrun = kwargs['--dryrun']\n #region = kwargs['--region']\n #vm = kwargs['--vm']# will need vm id from mongo records\n result = client.describe_volumes(\n DryRun=dryrun,\n # Filters=[\n # {\n # 'Name': {},\n # 'Values': [\n # filter_value,\n # ]\n # },\n # ],\n )\n #banner(\"raw results\")\n #print(result)\n #banner(\"raw results end\")\n result = self.update_dict(result)\n\n #print(self.Print(result, kind='volume', output=kwargs['output']))\n\n return result",
"def _display_oci_volume_list(volumes, output_mode, details, truncate):\n\n def _get_displayable_size(_, volume):\n return volume.get_size(format_str=OCI_VOLUME_SIZE_FMT.HUMAN.name)\n\n def _get_attached_instance_name(_, volume):\n global _this_instance_ocid\n if not volume.is_attached():\n return '-'\n _vol_instance_attach_to = volume.get_instance()\n if _vol_instance_attach_to.get_ocid() == _this_instance_ocid:\n return \"this instance\"\n pip = _vol_instance_attach_to.get_public_ip()\n if pip:\n return \"%s (%s)\" % (_vol_instance_attach_to.get_display_name(), _vol_instance_attach_to.get_public_ip())\n return _vol_instance_attach_to.get_display_name()\n\n def _get_comp_name(_, volume):\n \"\"\" keep track of compartment per ID as it may be expensive info to fetch \"\"\"\n _map = getattr(_get_comp_name, 'c_id_to_name', {})\n if volume.get_compartment_id() not in _map:\n _map[volume.get_compartment_id()] = volume.get_compartment().get_display_name()\n setattr(_get_comp_name, 'c_id_to_name', _map)\n return _map[volume.get_compartment_id()]\n\n if len(volumes) == 0:\n print('No other volumes found.')\n else:\n _title = 'Block volumes information'\n _columns = [['Name', 32, 'get_display_name'],\n ['Size', 6, _get_displayable_size],\n ['Attached to', 32, _get_attached_instance_name],\n ['OCID', 32, 'get_ocid']]\n if details:\n _columns.extend((['IQN', 14, 'get_iqn'],\n ['Compartment', 14, _get_comp_name],\n ['Availability domain', 19, 'get_availability_domain_name']))\n if output_mode == 'compat':\n printerKlass = get_row_printer_impl('text')\n else:\n printerKlass = get_row_printer_impl(output_mode)\n\n printer = printerKlass(title=_title, columns=_columns, text_truncate=truncate)\n printer.printHeader()\n for vol in volumes:\n printer.printRow(vol)\n printer.rowBreak()\n printer.printFooter()\n printer.finish()",
"def describe_volume_status(DryRun=None, VolumeIds=None, Filters=None, NextToken=None, MaxResults=None):\n pass",
"def list_vol(tag=None, device=None):\n conn = _ec2connect()\n vols = conn.get_all_volumes(filters=_get_filters(tag))\n if not vols:\n print('\\tNone.')\n return\n for v in vols:\n t = v.tags.get(TAG_NAME, 'root')\n s = v.attachment_state()\n z = v.size\n i = v.attach_data.instance_id\n d = v.attach_data.device\n print('\\t{0:25} {1:2}GB {2:15} {3:15} {4} {5}'.format(t, z, v.id, s, i, d ))",
"def describe_volumes(self, xml_bytes):\n root = XML(xml_bytes)\n result = []\n for volume_data in root.find(\"volumeSet\"):\n volume_id = volume_data.findtext(\"volumeId\")\n size = int(volume_data.findtext(\"size\"))\n snapshot_id = volume_data.findtext(\"snapshotId\")\n availability_zone = volume_data.findtext(\"availabilityZone\")\n status = volume_data.findtext(\"status\")\n create_time = volume_data.findtext(\"createTime\")\n create_time = datetime.strptime(\n create_time[:19], \"%Y-%m-%dT%H:%M:%S\")\n volume = model.Volume(\n volume_id, size, status, create_time, availability_zone,\n snapshot_id)\n result.append(volume)\n for attachment_data in volume_data.find(\"attachmentSet\"):\n instance_id = attachment_data.findtext(\"instanceId\")\n device = attachment_data.findtext(\"device\")\n status = attachment_data.findtext(\"status\")\n attach_time = attachment_data.findtext(\"attachTime\")\n attach_time = datetime.strptime(\n attach_time[:19], \"%Y-%m-%dT%H:%M:%S\")\n attachment = model.Attachment(\n instance_id, device, status, attach_time)\n volume.attachments.append(attachment)\n return result",
"def volume_list(search_opts=None):\r\n c_client = cinderclient()\r\n if c_client is None:\r\n return []\r\n # print c_client.volumes.list(search_opts=search_opts)\r\n return c_client.volumes.list(search_opts=search_opts)",
"def volume_list(mnode):\n return RestClient(mnode).handle_request(\n \"GET\", \"/v1/volumes\", httplib.OK, None)",
"def get_volumes(self):\n\tapi = NaElement(\"volume-get-iter\")\n\txi = NaElement(\"desired-attributes\")\n\tapi.child_add(xi)\n\t## This specifies max number of volume records to pull from sdk api\n\t## Default is 20. 20000 is enough for most clusters\n\tapi.child_add_string(\"max-records\",self.MAX_VOLUMES)\n\txi1 = NaElement(\"volume-attributes\")\n\txi.child_add(xi1)\n\txi41 = NaElement(\"volume-id-attributes\")\n\txi41.child_add_string(\"instance-uuid\",\"<instance-uuid>\")\n\txi41.child_add_string(\"name\",\"<name>\")\n\txi41.child_add_string(\"owning-vserver-name\",\"<owning-vserver-name>\")\n\txi41.child_add_string(\"uuid\",\"<uuid>\")\n\txi1.child_add(xi41)\n\txo = self.s.invoke_elem(api)\n\tself.sd.incr(\"api.invoke\")\n\tf = xmltodict.parse(xo.sprintf())\n\tvolumes = f['results']['attributes-list']['volume-attributes']\n\tvol_list = []\n\tfor volume in volumes:\n\t vol_list.append({'cluster-name':self.CLUSTER_NAME,\n\t\t\t 'owning-vserver-name':volume['volume-id-attributes']['owning-vserver-name'],\n\t\t\t 'name':volume['volume-id-attributes']['name'],\n\t\t\t 'instance-uuid':volume['volume-id-attributes']['instance-uuid']\n\t\t\t })\n\treturn vol_list",
"def show_asm_volumes(self):\n sql = \"select NAME from v$asm_diskgroup_stat ORDER BY 1\"\n self.cur.execute(sql)\n res = self.cur.fetchall()\n key = ['{#ASMVOLUME}']\n lst = []\n for i in res:\n d = dict(zip(key, i))\n lst.append(d)\n print ( json.dumps({'data': lst}) )",
"def delete_ebs_volumes():\n client = boto3.client('ec2')\n\n print('Deleting EBS volumes')\n volumes_resp = client.describe_volumes(\n MaxResults=500\n )\n while True:\n for vol in volumes_resp['Volumes']:\n volume_id = vol['VolumeId']\n print('Deleting Volume {}'.format(volume_id))\n client.delete_volume(\n VolumeId=volume_id\n )\n time.sleep(0.25) # REST API is throttled\n if 'NextMarker' in volumes_resp:\n volumes_resp = client.describe_volumes(\n Marker=volumes_resp['NextMarker'],\n MaxResults=500\n )\n else:\n break\n\n while client.describe_volumes()['Volumes']:\n time.sleep(5)\n print('EBS volumes deleted')\n\n print('Deleting EBS snapshots')\n for page in client.get_paginator('describe_snapshots').paginate(\n OwnerIds=[get_account_id()]\n ):\n for snapshot in page['Snapshots']:\n snapshot_id = snapshot['SnapshotId']\n print('Deleting EBS snapshot {}'.format(snapshot_id))\n client.delete_snapshot(\n SnapshotId=snapshot_id,\n )\n while client.describe_snapshots(\n OwnerIds=[get_account_id()]\n )['Snapshots']:\n time.sleep(5)\n\n print('EBS snapshots deleted')",
"def ListVolumes(self) -> Dict[str, 'ebs.AWSVolume']:\n\n return self.aws_account.ListVolumes(\n filters=[{\n 'Name': 'attachment.instance-id',\n 'Values': [self.instance_id]}])",
"def show_volume(svm_name) -> None:\n print()\n print(\"Getting Volume Details\")\n print(\"===================\")\n try:\n for volume in Volume.get_collection(\n **{\"svm.name\": svm_name}, fields=\"uuid\"):\n print(\n \"Volume name:-%s ; Volume uuid:-%s \" %\n (volume.name, volume.uuid))\n except NetAppRestError as error:\n print(\"Error:- \" % error.http_err_response.http_response.text)\n print(\"Exception caught :\" + str(error))",
"def test_01_list_volumes(self):\n list_volume_response = Volume.list(\n self.apiclient,\n ids=[self.vm1_root_volume.id, self.vm2_root_volume.id, self.vm3_root_volume.id],\n type='ROOT',\n listAll=True\n )\n self.assertEqual(\n isinstance(list_volume_response, list),\n True,\n \"List Volume response was not a valid list\"\n )\n self.assertEqual(\n len(list_volume_response),\n 3,\n \"ListVolumes response expected 3 Volumes, received %s\" % len(list_volume_response)\n )",
"def volume_info(mnode, volname):\n return RestClient(mnode).handle_request(\"GET\",\n \"/v1/volumes/%s\" % volname,\n httplib.OK, None)",
"def volume_list_info_iter_next(self, tag, maximum):\n return self.request( \"volume-list-info-iter-next\", {\n 'tag': tag,\n 'maximum': [ maximum, 'maximum', [ int, 'None' ], False ],\n }, {\n 'records': [ int, False ],\n 'volumes': [ VolumeInfo, True ],\n } )",
"def ebs_volumes(self) -> 'outputs.DetectorDatasourcesMalwareProtectionScanEc2InstanceWithFindingsEbsVolumes':\n return pulumi.get(self, \"ebs_volumes\")",
"def list_volumes( fields ):\n global conf\n\n volume_names = VOLUME_NAMES( conf )\n ret = []\n \n for name in volume_names:\n vol_conf = read_volume( name, fields )\n vol_conf['NAME'] = name\n ret.append( vol_conf )\n\n return ret",
"def test_azure_service_api_volumes_get(self):\n pass",
"def use_sdk():\n print('VOLUMES -------------------------------------')\n ec2 = boto3.client('ec2')\n for volume in ec2.describe_volumes()['Volumes']:\n print(f\"Volume found: {volume['VolumeId']}\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Reports the current modification status of EBS volumes. Currentgeneration EBS volumes support modification of attributes including type, size, and (for io1 volumes) IOPS provisioning while either attached to or detached from an instance. Following an action from the API or the console to modify a volume, the status of the modification may be modifying , optimizing , completed , or failed . If a volume has never been modified, then certain elements of the returned VolumeModification objects are null. You can also use CloudWatch Events to check the status of a modification to an EBS volume. For information about CloudWatch Events, see the Amazon CloudWatch Events User Guide . For more information, see Monitoring Volume Modifications" .
|
def describe_volumes_modifications(DryRun=None, VolumeIds=None, Filters=None, NextToken=None, MaxResults=None):
pass
|
[
"def volume_status(mnode, volname):\n return RestClient(mnode).handle_request(\n \"GET\", \"/v1/volumes/%s/status\" % volname,\n httplib.OK, None)",
"def describe_volume_status(DryRun=None, VolumeIds=None, Filters=None, NextToken=None, MaxResults=None):\n pass",
"def volume_status(self, volume):\r\n volume = self._get_volume(volume)\r\n raid = self._get_raid(volume[\"devicefile\"])\r\n if volume is not None and raid is not None:\r\n return raid[\"state\"]",
"def describe_reserved_instances_modifications(ReservedInstancesModificationIds=None, NextToken=None, Filters=None):\n pass",
"def modify_volume_snapshot(self, snapshot_id, name=None, description=None,\n expiration_timestamp=None):\n LOG.info(\"Modifying volume snapshot: '%s'\" % snapshot_id)\n payload = self._prepare_create_modify_snapshot_payload(\n name=name, description=description,\n expiration_timestamp=expiration_timestamp\n )\n self.rest_client.request(\n constants.PATCH,\n constants.MODIFY_VOLUME_URL.format(self.server_ip, snapshot_id),\n payload\n )\n return self.get_volume_snapshot_details(snapshot_id)",
"def get_volume_stats(self):\n self.conf.update_config_value()\n self._update_volume_stats()",
"def test_volume_detached_after_rebuild(self):\n volume_after_rebuild = self.blockstorage_client.get_volume_info(\n self.volume.id_).entity\n self.assertEqual(volume_after_rebuild.status, 'available')",
"def get_volume_stats(self, refresh=False):\n if self._volume_stats is None or refresh:\n self._update_volume_stats()\n\n LOG.info(\n 'Successfully update volume stats. '\n 'backend: %(volume_backend_name)s, '\n 'vendor: %(vendor_name)s, '\n 'model_type: %(model_type)s, '\n 'system_id: %(system_id)s, '\n 'status: %(status)s, '\n 'driver_version: %(driver_version)s, '\n 'storage_protocol: %(storage_protocol)s.', self._volume_stats)\n\n return self._volume_stats",
"def __getModifiedItems(self):\n modifiedItems = []\n for itm in self.statusList.selectedItems():\n if itm.text(self.__statusColumn) in self.modifiedIndicators:\n modifiedItems.append(itm)\n return modifiedItems",
"def changes(self) -> List[str]:\n output: List[str] = []\n if self.status() is self.UNMODIFIED:\n output = [self.formatter % (\" \", self.key, self.old_value)]\n elif self.status() is self.ADDED:\n output.append(self.formatter % (\"+\", self.key, self.new_value))\n elif self.status() is self.REMOVED:\n output.append(self.formatter % (\"-\", self.key, self.old_value))\n elif self.status() is self.MODIFIED:\n output.append(self.formatter % (\"-\", self.key, self.old_value))\n output.append(self.formatter % (\"+\", self.key, self.new_value))\n return output",
"def test_volumes_replace(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n svc.volumes = [\n sm.Volume(\"foo\", \"bar\"),\n sm.Volume(\"bar\", \"baz\"),\n ]\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n if not \"bar\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n for v in svc.volumes:\n if v.owner == \"foo\":\n self.assertEqual(v.permission, \"bar\")\n if v.owner == \"bar\":\n self.assertEqual(v.permission, \"baz\")\n self.assertEqual(len(svc.volumes), 2)",
"def test_volumes_add(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 8)\n svc.volumes.append(sm.Volume(\"foo\", \"bar\"))\n svc.volumes.append(sm.Volume(\"bar\", \"baz\"))\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n if not \"bar\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n for v in svc.volumes:\n if v.owner == \"foo\":\n self.assertEqual(v.permission, \"bar\")\n if v.owner == \"bar\":\n self.assertEqual(v.permission, \"baz\")\n self.assertEqual(len(svc.volumes), 10)",
"def volumes(self) -> List:\n if self.node is None:\n return []\n # Removing boot volume from the list\n volume_attachments = []\n for i in self.node[\"volume_attachments\"]:\n volume_detail = self.service.get_volume(i[\"volume\"][\"id\"])\n for vol in volume_detail.get_result()[\"volume_attachments\"]:\n if vol[\"type\"] == \"data\":\n volume_attachments.append(vol)\n return volume_attachments",
"def get_modification(self) -> str:\n return self._root[\"Modification\"]",
"def list_modified_files(self):\n return gitinfo.list_staged_files(gitinfo.current_commit())",
"def status(self) -> str:\n if self.old_value == self.new_value:\n return self.UNMODIFIED\n if self.old_value is None:\n return self.ADDED\n if self.new_value is None:\n return self.REMOVED\n return self.MODIFIED",
"def volume_options_list_info(self, volume):\n return self.request( \"volume-options-list-info\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n }, {\n 'options': [ VolumeOptionInfo, True ],\n } )",
"def evaluate_modifications(self, diff_policy: DiffPolicy) \\\n -> Union[DiffResult, SuspiciousModification]:\n\n if self.coverage < SignatureCoverageLevel.ENTIRE_REVISION:\n return SuspiciousModification(\n 'Nonstandard signature coverage level'\n )\n elif self.coverage == SignatureCoverageLevel.ENTIRE_FILE:\n return DiffResult(ModificationLevel.NONE, set())\n\n return diff_policy.review_file(\n self.reader, self.signed_revision,\n field_mdp_spec=self.fieldmdp, doc_mdp=self.docmdp_level\n )",
"def info(self):\n ret = libvirtmod.virStorageVolGetInfo(self._o)\n if ret is None: raise libvirtError ('virStorageVolGetInfo() failed', vol=self)\n return ret",
"def volume_snapshot_statuses(self):\n return self._volume_snapshot_statuses"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the specified attribute of the specified VPC. You can specify only one attribute at a time.
|
def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):
pass
|
[
"def describe_attr_value(attr, die, section_offset):\r\n descr_func = _ATTR_DESCRIPTION_MAP[attr.form]\r\n val_description = descr_func(attr, die, section_offset)\r\n\r\n # For some attributes we can display further information\r\n extra_info_func = _EXTRA_INFO_DESCRIPTION_MAP[attr.name]\r\n extra_info = extra_info_func(attr, die, section_offset)\r\n return str(val_description) + '\\t' + extra_info",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def describe_volume_attribute(DryRun=None, VolumeId=None, Attribute=None):\n pass",
"def describe_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def describe_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, Attribute=None):\n pass",
"def describe_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None):\n pass",
"def attributeInfo(multi=bool, inherited=bool, bool=bool, internal=bool, type=\"string\", hidden=bool, enumerated=bool, allAttributes=bool, logicalAnd=bool, writable=bool, userInterface=bool, leaf=bool, short=bool):\n pass",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def describe(\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n vpc_id = _find_vpcs(\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as err:\n boto_err = __utils__[\"boto.get_error\"](err)\n if boto_err.get(\"aws\", {}).get(\"code\") == \"InvalidVpcID.NotFound\":\n # VPC was not found: handle the error and return None.\n return {\"vpc\": None}\n return {\"error\": boto_err}\n\n if not vpc_id:\n return {\"vpc\": None}\n\n filter_parameters = {\"vpc_ids\": vpc_id}\n\n try:\n vpcs = conn.get_all_vpcs(**filter_parameters)\n except BotoServerError as err:\n return {\"error\": __utils__[\"boto.get_error\"](err)}\n\n if vpcs:\n vpc = vpcs[0] # Found!\n log.debug(\"Found VPC: %s\", vpc.id)\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n return {\"vpc\": _r}\n else:\n return {\"vpc\": None}",
"def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def showattribute(self, vname=None, device=None):\n if device is None:\n device = sys.stdout\n if vname is None:\n vname = self.default_variable_name\n device.write(\"Attributes of \")\n device.write(vname)\n device.write(\" in file \")\n device.write(self.id)\n device.write(\":\\n\")\n device.write(str(self.listattribute(vname)))\n device.write(\"\\n\")",
"def print_attribute_list(self):\n p = prettytable.PrettyTable((\"VISA name\", \"Constant\", \"Python name\", \"val\"))\n for attr in getattr(self.current, \"visa_attributes_classes\", ()):\n try:\n val = self.current.get_visa_attribute(attr.attribute_id)\n except VisaIOError as e:\n val = e.abbreviation\n except Exception as e:\n val = str(e)\n if len(val) > 10:\n val = val[:10] + \"...\"\n p.add_row((attr.visa_name, attr.attribute_id, attr.py_name, val))\n\n print(p.get_string(sortby=\"VISA name\"))",
"def describe(self, access, element):\n self._prepare(access)\n # Accumulate the descriptor sets from each ability, then turn into a string.\n tags = set()\n for c in self.abilities:\n tags |= c.describe(access, element)\n return ' '.join(list(tags)).lower()",
"def score_resource_cost(event, attributes):\n score = 0\n\n for attribute in attributes:\n if attribute[\"category\"] == \"Network activity\":\n ty = attribute[\"type\"]\n if ty == \"domain\":\n score += 20\n elif ty == \"hostname\" or ty == \"url\" or ty == \"ip-src\":\n score += 20\n elif attribute[\"category\"] == \"Payload delivery\" or attribute[\"category\"] == \"Payload installation\" or \\\n attribute[\"category\"] == \"Artifacts dropped\":\n ty = attribute[\"type\"]\n if ty == \"vulnerability\":\n score += 10\n elif ty == \"malware-sample\":\n score += 10\n elif ty == \"filename\" or ty == \"filename|md5\" or ty == \"filename|sha1\" or ty == \"filename|sha256\" or ty == \"attachment\":\n score += 10\n elif ty == \"md5\" or ty == \"sha1\" or ty == \"sha256\":\n score += 10\n elif attribute[\"category\"] == \"External analysis\":\n ty = attribute[\"type\"]\n if ty == \"vulnerability\":\n score += 10000\n elif ty == \"filename\" or ty == \"filename|md5\" or ty == \"filename|sha1\" or ty == \"filename|sha256\":\n score += 10\n elif ty == \"md5\" or ty == \"sha1\" or ty == \"sha256\":\n score += 10\n\n return score",
"def stack_attribute_values(self, environment):\n if environment != 'uncategorized':\n stack_attribute_dict = self.ah_obj.create_nested_defaultdict()\n organization_list = self.aws_helperobj.get_organizations()\n region_list = self.aws_helperobj.get_regions()\n stack_attributes_from_config = self.module_config_data['stack_attributes']\n attributes_list = stack_attributes_from_config.keys()\n subnet_list = self.get_subnet_list(environment)\n graphite_query_dict = self.queries_for_graphite(subnet_list)\n for organization in organization_list:\n for region in region_list:\n vpc_list = self.aws_helperobj.get_vpc_in_region(region)\n if vpc_list:\n for vpc in vpc_list:\n for subnet in subnet_list:\n for attribute in stack_attributes_from_config:\n stack_list = stack_attributes_from_config[attribute]['stack']\n attribute_value=\"\"\n suffix=\"\"\n if 'suffix' in stack_attributes_from_config[attribute]: \n suffix = stack_attributes_from_config[attribute]['suffix'] \n display_name= \"\"\n if 'display_name' in stack_attributes_from_config[attribute]:\n display_name = stack_attributes_from_config[attribute]['display_name']\n report = self.generate_report(graphite_query_dict[subnet][attribute])\n if report:\n target = self.ah_obj.split_string(report[0]['target'], ('.'))\n if subnet in target and attribute in target:\n for index in range(len(report[0]['datapoints'])-1, 0, -1):\n if report and report[0]['datapoints'][index][0] is not None:\n attribute_value = str(int(report[0]['datapoints'][index][0]))+\" \"+suffix\n break\n else: attribute_value = \"null\"\n else:attribute_value = \"null\"\n for stack in stack_list:\n stack_attribute_dict[region][vpc][subnet][stack][display_name] = attribute_value \n return self.ah_obj.defaultdict_to_dict(stack_attribute_dict)",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def _ip_address_spec(output, ipaddress, netmask, interface, scope, active ):\n output.beginAssembling(\"IPaddressSpec\")\n output.setVirtualNameValue(\"IPaddress\", ipaddress)\n output.setVirtualNameValue(\"IPnetmask\", netmask)\n output.setVirtualNameValue(\"InterfaceName\", interface)\n output.setVirtualNameValue(\"Active\", scope)\n output.setVirtualNameValue(\"Scope\", active)\n output.endAssembling(\"IPaddressSpec\")",
"def Attributes(self) -> _n_5_t_17:",
"def attr_summary(self):\n\n print(self._attr_repr())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the ClassicLink status of one or more VPCs.
|
def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):
pass
|
[
"def getvpcs(show):\n vpclist=[]\n \n try:\n vpcs=ec2.describe_vpcs()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting vpc data: \\n\\n\\n\")\n print(e)\n for vpc in vpcs['Vpcs']:\n name=vpc['VpcId']\n cidr=vpc['CidrBlock']\n if show:\n print(\"VPC Id: \"+name+\" CIDR: \"+cidr)\n vpclist.append({ \"name\":name})\n return vpclist",
"def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):\n pass",
"def get_vpc_info(self):\n if not self.base['cluster'].get('vpc'):\n res = self.ec2.describe_vpcs()\n self.base['cluster']['vpc'] = [vpc['VpcId'] for vpc in res['Vpcs'] if vpc['IsDefault']][0]\n logger.info('No vpc selected, using default vpc')\n logger.info(self.base['cluster']['vpc'])",
"def describe_vpcs(\n vpc_id=None,\n name=None,\n cidr=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {\"filters\": {}}\n\n if vpc_id:\n filter_parameters[\"vpc_ids\"] = [vpc_id]\n\n if cidr:\n filter_parameters[\"filters\"][\"cidr\"] = cidr\n\n if name:\n filter_parameters[\"filters\"][\"tag:Name\"] = name\n\n if tags:\n for tag_name, tag_value in tags.items():\n filter_parameters[\"filters\"][\"tag:{}\".format(tag_name)] = tag_value\n\n vpcs = conn.get_all_vpcs(**filter_parameters)\n\n if vpcs:\n ret = []\n for vpc in vpcs:\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n ret.append(_r)\n return {\"vpcs\": ret}\n else:\n return {\"vpcs\": []}\n\n except BotoServerError as e:\n return {\"error\": __utils__[\"boto.get_error\"](e)}",
"def describe(\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n vpc_id = _find_vpcs(\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as err:\n boto_err = __utils__[\"boto.get_error\"](err)\n if boto_err.get(\"aws\", {}).get(\"code\") == \"InvalidVpcID.NotFound\":\n # VPC was not found: handle the error and return None.\n return {\"vpc\": None}\n return {\"error\": boto_err}\n\n if not vpc_id:\n return {\"vpc\": None}\n\n filter_parameters = {\"vpc_ids\": vpc_id}\n\n try:\n vpcs = conn.get_all_vpcs(**filter_parameters)\n except BotoServerError as err:\n return {\"error\": __utils__[\"boto.get_error\"](err)}\n\n if vpcs:\n vpc = vpcs[0] # Found!\n log.debug(\"Found VPC: %s\", vpc.id)\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n return {\"vpc\": _r}\n else:\n return {\"vpc\": None}",
"def connectivity_status(self) -> str:\n return pulumi.get(self, \"connectivity_status\")",
"def dumpConnectionStatus():\n print(\"+++ ALL CONNECTIONS +++\")\n for connection in allInstancesOf(DiagnosticConnectionWrapper):\n print(connection.label, connection.state)\n print(\"--- CONNECTIONS END ---\")",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def vpc_classic_link_id(self) -> str:\n warnings.warn(\"\"\"With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\", DeprecationWarning)\n pulumi.log.warn(\"\"\"vpc_classic_link_id is deprecated: With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\")\n\n return pulumi.get(self, \"vpc_classic_link_id\")",
"def vpnlinks_status(self, vpnlink_id, tenant_id=None, api_version=\"v2.1\"):\n\n if tenant_id is None and self._parent_class.tenant_id:\n # Pull tenant_id from parent namespace cache.\n tenant_id = self._parent_class.tenant_id\n elif not tenant_id:\n # No value for tenant_id.\n raise TypeError(\"tenant_id is required but not set or cached.\")\n cur_ctlr = self._parent_class.controller\n\n url = str(cur_ctlr) + \"/{}/api/tenants/{}/vpnlinks/{}/status\".format(api_version,\n tenant_id,\n vpnlink_id)\n\n api_logger.debug(\"URL = %s\", url)\n return self._parent_class.rest_call(url, \"get\")",
"def describe_vpn_connections(DryRun=None, VpnConnectionIds=None, Filters=None):\n pass",
"def cluster_status():\n cluster_json = H2OConnection.get_json(\"Cloud?skip_ticks=true\")\n\n print(\"Version: {0}\".format(cluster_json['version']))\n print(\"Cloud name: {0}\".format(cluster_json['cloud_name']))\n print(\"Cloud size: {0}\".format(cluster_json['cloud_size']))\n if cluster_json['locked']: print(\"Cloud is locked\\n\")\n else: print(\"Accepting new members\\n\")\n if cluster_json['nodes'] == None or len(cluster_json['nodes']) == 0:\n print(\"No nodes found\")\n return\n\n status = []\n for node in cluster_json['nodes']:\n for k, v in zip(node.keys(),node.values()):\n if k in [\"h2o\", \"healthy\", \"last_ping\", \"num_cpus\", \"sys_load\", \n \"mem_value_size\", \"free_mem\", \"pojo_mem\", \"swap_mem\",\n \"free_disk\", \"max_disk\", \"pid\", \"num_keys\", \"tcps_active\",\n \"open_fds\", \"rpcs_active\"]: status.append(k+\": {0}\".format(v))\n print(', '.join(status))\n print()",
"def describe_vpc_peering_connection(\n name, region=None, key=None, keyid=None, profile=None\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n return {\"VPC-Peerings\": _get_peering_connection_ids(name, conn)}",
"def status(self) -> Optional[pulumi.Input['SharedPrivateLinkResourceStatus']]:\n return pulumi.get(self, \"status\")",
"def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):\n pass",
"def listVpnConnection(cls, api_client, **kwargs):\n cmd = {}\n cmd.update(kwargs)\n return super(Vpn, cls).list(api_client.listVpnConnections(**cmd).get('vpnconnection', []))",
"def _PrintConciseConnectivityTestResult(self, response):\n details = response.reachabilityDetails\n if details:\n log.status.Print('Network Connectivity Test Result: {0}\\n'.format(\n details.result))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes the ClassicLink DNS support status of one or more VPCs. If enabled, the DNS hostname of a linked EC2Classic instance resolves to its private IP address when addressed from an instance in the VPC to which it's linked. Similarly, the DNS hostname of an instance in a VPC resolves to its private IP address when addressed from a linked EC2Classic instance. For more information, see ClassicLink in the Amazon Elastic Compute Cloud User Guide .
|
def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):
pass
|
[
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def test_dnssec_available():\n response = zone.dnssec_available('example.com')\n assert response.success\n\n payload = response.payload\n assert payload['url'] == 'https://api.cloudns.net/dns/is-dnssec-available.json' # noqa: E501",
"def test_08_VPC_Network_Restarts_With_InternalDns(self):\n\n # Validate the following\n # 1. Create a VPC and Tier network by using DNS network offering.\n # 2. Deploy vm1 in Tier network network1.\n # 3. Verify dhcp option 06 and 0f for subnet\n # 4. Verify dhcp option 06,15 and 0f for vm Interface.\n # 5. Deploy Vm2.\n # 6. Verify end to end by pinging with hostname while restarting\n # VPC and Tier without and with cleanup.\n\n cmd = updateZone.updateZoneCmd()\n cmd.id = self.zone.id\n cmd.domain = VPC_DOMAIN_NAME\n self.apiclient.updateZone(cmd)\n\n vpc_off = self.create_VpcOffering(self.dnsdata[\"vpc_offering\"])\n self.validate_VpcOffering(vpc_off, state=\"Enabled\")\n vpc = self.create_Vpc(vpc_off, cidr='10.1.0.0/16', cleanup=False)\n\n self.debug(\"Creating Nuage Vsp VPC Network offering...\")\n network_offering = self.create_NetworkOffering(\n self.dnsdata[\"vpc_network_offering\"])\n self.validate_NetworkOffering(network_offering, state=\"Enabled\")\n network_1 = self.create_Network(\n network_offering, gateway='10.1.1.1', vpc=vpc)\n\n vm_1 = self.create_VM(network_1)\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_vm(vm_1)\n # Internal DNS check point on VSD\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", network_1)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, network_1)\n for nic in vm_1.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm1\", nic, True)\n\n self.test_data[\"virtual_machine\"][\"displayname\"] = \"vm2\"\n self.test_data[\"virtual_machine\"][\"name\"] = \"vm2\"\n vm_2 = self.create_VM(network_1)\n self.test_data[\"virtual_machine\"][\"displayname\"] = \"vm1\"\n self.test_data[\"virtual_machine\"][\"name\"] = \"vm1\"\n self.verify_vsd_vm(vm_2)\n for nic in vm_2.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm2\", nic, True)\n\n public_ip_1 = self.acquire_PublicIPAddress(network_1, vpc)\n self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)\n # Adding Network ACL rule in the Public tier\n self.debug(\"Adding Network ACL rule to make the created NAT rule \"\n \"(SSH) accessible...\")\n public_ssh_rule = self.create_NetworkAclRule(\n self.test_data[\"ingress_rule\"], network=network_1)\n\n # VSD verification\n self.verify_vsd_firewall_rule(public_ssh_rule)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC network (cleanup = false)\n self.debug(\"Restarting the created VPC network without cleanup...\")\n Network.restart(network_1, self.api_client, cleanup=False)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n self.verify_vsd_vm(vm_2)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC network (cleanup = true)\n self.debug(\"Restarting the created VPC network with cleanup...\")\n Network.restart(network_1, self.api_client, cleanup=True)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n self.verify_vsd_vm(vm_2)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC (cleanup = false)\n self.debug(\"Restarting the VPC without cleanup...\")\n self.restart_Vpc(vpc, cleanup=False)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC (cleanup = true)\n self.debug(\"Restarting the VPC with cleanup...\")\n self.restart_Vpc(vpc, cleanup=True)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def test_06_VPC_Network_With_InternalDns(self):\n\n # Validate the following\n # 1. Create a VPC and tier network by using DNS network offering.\n # 2. Deploy vm1 in tier network.\n # 3. Verify dhcp option 06 and 0f for subnet\n # 4. Verify dhcp option 06,15 and 0f for vm Interface.\n cmd = updateZone.updateZoneCmd()\n cmd.id = self.zone.id\n cmd.domain = VPC_DOMAIN_NAME\n self.apiclient.updateZone(cmd)\n vpc_off = self.create_VpcOffering(self.dnsdata[\"vpc_offering\"])\n self.validate_VpcOffering(vpc_off, state=\"Enabled\")\n\n vpc = self.create_Vpc(vpc_off, cidr='10.1.0.0/16', cleanup=False)\n\n self.debug(\"Creating Nuage Vsp VPC Network offering...\")\n network_offering = self.create_NetworkOffering(\n self.dnsdata[\"vpc_network_offering\"])\n self.validate_NetworkOffering(network_offering, state=\"Enabled\")\n network_1 = self.create_Network(\n network_offering, gateway='10.1.1.1', vpc=vpc)\n\n vm_1 = self.create_VM(network_1)\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_vm(vm_1)\n\n # Internal DNS check point on VSD\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", network_1)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, network_1)\n for nic in vm_1.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm1\", nic, True)",
"def dhcp_enabled(self):\n ret = self._get_attr(\"DHCPEnabled\")\n return ret",
"def enhanced_vpc_routing(self) -> pulumi.Output[bool]:\n return pulumi.get(self, \"enhanced_vpc_routing\")",
"def enable_dhcp(self, ip_host_num):\n return [\"ip-host %s dhcp-enable true ping-response true traceroute-response true\" % ip_host_num]",
"def test_dnssec_activate():\n response = zone.dnssec_activate('example.com')\n assert response.success\n\n payload = response.payload\n assert payload['url'] == 'https://api.cloudns.net/dns/activate-dnssec.json'",
"def ActiveProtocols(self, instance):\n instanceName = \"master\"\n if instance : instanceName = instance.Name\n if self._runningRoutingProtocols.get(instanceName, None) == None:\n self._runningRoutingProtocols[instanceName] = []\n if len(self._runningRoutingProtocols[instanceName]) == 0 :\n # OSPF\n if instanceName.lower() == \"master\" : \n cmd = \"show ospf overview\"\n else :\n cmd = \"show ospf overview instance {0}\".format(instanceName)\n response = Session.ExecCommand(cmd)\n if (not (\"not running\" in response)): \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.OSPF)\n # RIP\n if instanceName.lower() == \"master\" : \n cmd = \"show rip neighbor\" \n else : \n cmd = \"show rip neighbor instance {0}\".format(instanceName)\n response = Session.ExecCommand(cmd)\n if (not (\"not running\" in response)): \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.RIP) \n # BGP\n cmd = \"show bgp neighbor instance {0}\".format(instanceName)\n response = Session.ExecCommand(cmd)\n if (not (\"not running\" in response)): \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.BGP)\n # ISIS\n cmd = \"show isis overview instance {0}\".format(instanceName)\n response = Session.ExecCommand(cmd)\n if (not (\"not running\" in response)): \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.ISIS)\n # STATIC \n # TODO : \"not running\" is invalid in this context\n if instanceName.lower() == \"master\" : \n cmd = \"show configuration routing-options static\" \n else : \n cmd = \"show configuration routing-instances {0} routing-options static\".format(instanceName)\n response = Session.ExecCommand(cmd)\n if (not (\"not running\" in response)): \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.STATIC) \n # LLDP - only for default instance\n if instanceName.lower() == \"master\":\n response = Session.ExecCommand(\"show lldp\")\n lldpenabled = re.findall(r\"LLDP\\s+:\\s+Enabled\", response)\n if len(lldpenabled) == 1 : \n self._runningRoutingProtocols[instanceName].Add(L3Discovery.NeighborProtocol.LLDP)\n return self._runningRoutingProtocols[instanceName]",
"def _get_ip_cfg_status(self):\n self.navigate_to(self.CONFIGURE, self.CONFIGURE_SYSTEM, 2)\n if self.s.is_checked(self.info['loc_cfg_system_ip_manual_radio']):\n return \"static\"\n\n else:\n return \"dhcp\"",
"def check_networks_configuration(\n vm_name, check_nic=False, dns_search=None, dns_servers=None\n):\n status = True\n if check_nic:\n logger.info(\"Check the NIC file name exists\")\n cmd = config_virt.CHECK_NIC_EXIST\n if check_data_on_vm(vm_name, cmd, config_virt.CLOUD_INIT_NIC_NAME):\n logger.info(\"NIC file name exist\")\n else:\n logger.error(\"NIC file name doesn't exist\")\n status = False\n if dns_search:\n logger.info(\"Check DNS search, expected: %s\", dns_search)\n cmd = config_virt.CHECK_DNS_IN_GUEST % dns_search\n if check_data_on_vm(vm_name, cmd, dns_search):\n logger.info(\"DNS search check pass\")\n else:\n logger.error(\"DNS search check failed\")\n status = False\n if dns_servers:\n logger.info(\"Check DNS servers, expected: %s\", dns_servers)\n cmd = config_virt.CHECK_DNS_IN_GUEST % dns_servers\n if check_data_on_vm(vm_name, cmd, dns_servers):\n logger.info(\"DNS servers check pass\")\n else:\n logger.error(\"DNS servers check failed\")\n status = False\n return status",
"def __virtual__():\n\tif dns_support:\n\t\treturn 'ddns'\n\treturn False",
"def describe_vpc_endpoint_services(DryRun=None, MaxResults=None, NextToken=None):\n pass",
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def find_visa_connected():\n\n mgr = visa.ResourceManager()\n resources = mgr.list_resources()\n print('Found VISA devices: ')\n for d in resources:\n if any([d.startswith(prefix) for prefix in INSTR_PREFIXES]):\n print(d)\n return resources",
"def neigh_options(config):\r\n\r\n next_hop = [\"Yes\" for k in dict.fromkeys(config) if k == \"next-hop-self\"]\r\n if not next_hop:\r\n next_hop = [\"No\"]\r\n\r\n reflector = [\"Yes\" for k in dict.fromkeys(config) if k == \"route-reflector-client\"]\r\n if not reflector:\r\n reflector = [\"No\"]\r\n\r\n soft_reconfig = [v for k, v in config.items() if k == \"soft-reconfiguration\"]\r\n if not soft_reconfig:\r\n soft_reconfig = [\"No\"]\r\n\r\n activate = [\"Yes\" for k in dict.fromkeys(config) if k == \"activate\"]\r\n if not reflector:\r\n activate = [\"No\"]\r\n\r\n return next_hop, reflector, soft_reconfig, activate",
"def compat_show_vnics_information():\n\n def _display_subnet(_, vnic):\n \"\"\"return subnet display name of this vnic \"\"\"\n return vnic.get_subnet().get_display_name()\n def _display_secondary_ip_subnet(_, privip):\n _sn = privip.get_subnet()\n return '%s (%s)' % (_sn.get_display_name() ,_sn.get_cidr_block())\n def _display_vnic_name(_, vn):\n if vn.is_primary():\n return '%s (primary)' % vn.get_display_name()\n return vn.get_display_name()\n\n sess = get_oci_api_session()\n if sess is None:\n _logger.error(\"Failed to get API session.\")\n return\n _logger.debug('getting instance ')\n inst = sess.this_instance()\n if inst is None:\n _logger.error(\"Failed to get information from OCI.\")\n return\n _logger.debug('getting all vnics ')\n vnics = inst.all_vnics()\n _logger.debug('got for printing')\n\n _title = 'VNIC configuration for instance %s' % inst.get_display_name()\n\n _columns=(['Name',32,_display_vnic_name],\n ['Hostname',25,'get_hostname'],\n ['MAC',17,'get_mac_address'],\n ['Public IP',15,'get_public_ip'],\n ['Private IP(s)',15,'get_private_ip'],\n ['Subnet',18,_display_subnet],\n ['OCID',90,'get_ocid'])\n\n\n printer = TextPrinter(title=_title, columns=_columns, column_separator='')\n ips_printer = TextPrinter(title='Private IP addresses:',\n columns=(['IP address',15,'get_address'],['OCID','90','get_ocid'],['Hostname',25,'get_hostname'],\n ['Subnet',24,_display_secondary_ip_subnet]),printer=IndentPrinter(3))\n\n printer.printHeader()\n for vnic in vnics:\n printer.printRow(vnic)\n _all_p_ips = vnic.all_private_ips()\n if len(_all_p_ips) > 1:\n # _all_p_ips include the primary we won't print (>1)\n ips_printer.printHeader()\n for p_ip in _all_p_ips:\n if not p_ip.is_primary():\n # primary already displayed\n ips_printer.printRow(p_ip)\n printer.rowBreak()\n ips_printer.printFooter()\n ips_printer.finish()\n printer.printFooter()\n printer.finish()",
"def describe_addresses(DryRun=None, PublicIps=None, Filters=None, AllocationIds=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes all supported AWS services that can be specified when creating a VPC endpoint.
|
def describe_vpc_endpoint_services(DryRun=None, MaxResults=None, NextToken=None):
pass
|
[
"def aws_services(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AssessmentAwsServiceArgs']]]]:\n return pulumi.get(self, \"aws_services\")",
"def _add_services(self):\n this_service = {'name': 'designate'}\n other_services = [\n {'name': 'percona-cluster', 'constraints': {'mem': '3072M'}},\n {'name': 'rabbitmq-server'},\n {'name': 'keystone'},\n {'name': 'memcached', 'location': 'cs:memcached'},\n {'name': 'designate-bind'},\n {'name': 'neutron-api'}\n ]\n\n use_source = [\n 'percona-cluster',\n 'rabbitmq-server',\n ]\n\n no_origin = [\n 'designate-bind',\n 'memcached',\n ]\n\n super(DesignateBasicDeployment, self)._add_services(this_service,\n other_services,\n use_source,\n no_origin)",
"def deferrable_services():\n _svcs = services()\n _svcs.extend(['ovs-vswitchd', 'ovsdb-server',\n 'openvswitch-switch', 'ovs-record-hostname'])\n return list(set(_svcs))",
"def list_services(ctx):\n\n ctx.respond(ctx._(\"I am running: {services}\").format(\n services=\", \".join(ctx.bot.services))\n )",
"def describe_services(\n ecs, cluster: str, services: typing.Set[str]\n) -> typing.List[typing.Dict[str, typing.Any]]:\n result: typing.List[typing.Dict[str, typing.Any]] = []\n services_list = list(services)\n for i in range(0, len(services_list), 10):\n response = ecs.describe_services(\n cluster=cluster, services=services_list[i : i + 10]\n )\n result.extend(response[\"services\"])\n return result",
"def services_all(ctx):\n ctx.run(KUBERNETES_GET_SERVICES_ALL_CMD)",
"def delete_vpc_endpoint_resources():\n print('Deleting VPC endpoints')\n ec2 = boto3.client('ec2')\n endpoint_ids = []\n for endpoint in ec2.describe_vpc_endpoints()['VpcEndpoints']:\n print('Deleting VPC Endpoint - {}'.format(endpoint['ServiceName']))\n endpoint_ids.append(endpoint['VpcEndpointId'])\n\n if endpoint_ids:\n ec2.delete_vpc_endpoints(\n VpcEndpointIds=endpoint_ids\n )\n\n print('Waiting for VPC endpoints to get deleted')\n while ec2.describe_vpc_endpoints()['VpcEndpoints']:\n time.sleep(5)\n\n print('VPC endpoints deleted')\n\n # VPC endpoints connections\n print('Deleting VPC endpoint connections')\n service_ids = []\n for connection in ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n service_id = connection['ServiceId']\n state = connection['VpcEndpointState']\n\n if state in ['PendingAcceptance', 'Pending', 'Available', 'Rejected', 'Failed', 'Expired']:\n print('Deleting VPC Endpoint Service - {}'.format(service_id))\n service_ids.append(service_id)\n\n ec2.reject_vpc_endpoint_connections(\n ServiceId=service_id,\n VpcEndpointIds=[\n connection['VpcEndpointId'],\n ]\n )\n\n if service_ids:\n ec2.delete_vpc_endpoint_service_configurations(\n ServiceIds=service_ids\n )\n\n print('Waiting for VPC endpoint services to be destroyed')\n while ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n time.sleep(5)\n\n print('VPC endpoint connections deleted')",
"def _configure_services(self):\n keystone_config = {\n 'admin-password': 'openstack',\n 'admin-token': 'ubuntutesting'\n }\n pxc_config = {\n 'dataset-size': '25%',\n 'max-connections': 1000,\n 'root-password': 'ChangeMe123',\n 'sst-password': 'ChangeMe123',\n }\n designate_config = {\n 'nameservers': ' '.join([self.TEST_NS1_RECORD,\n self.TEST_NS2_RECORD])\n }\n configs = {\n 'keystone': keystone_config,\n 'percona-cluster': pxc_config,\n 'designate': designate_config,\n }\n super(DesignateBasicDeployment, self)._configure_services(configs)",
"def _configure_services(self):\n if self.series == 'trusty':\n keystone_config = {'admin-password': 'openstack',\n 'admin-token': 'ubuntutesting',\n 'openstack-origin': 'cloud:trusty-mitaka'}\n designate_config = {'openstack-origin': 'cloud:trusty-mitaka',\n 'nameservers': 'ns1.mojotest.com.'}\n else:\n keystone_config = {'admin-password': 'openstack',\n 'admin-token': 'ubuntutesting'}\n designate_config = {'nameservers': 'ns1.mojotest.com.'}\n\n pxc_config = {\n 'dataset-size': '25%',\n 'max-connections': 1000,\n 'root-password': 'ChangeMe123',\n 'sst-password': 'ChangeMe123',\n }\n\n configs = {\n 'keystone': keystone_config,\n 'designate': designate_config,\n 'percona-cluster': pxc_config,\n }\n\n super(DesignateBindDeployment, self)._configure_services(configs)",
"def get_service_choices(self):\n return [\n ServiceChoice('fast', _('Fast')),\n ServiceChoice('slow', _('Slow'))\n ]",
"def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def _get_services_container_names(self):\n services = {}\n sellables = set(os.listdir(Two1Composer.SERVICES_DIR)).intersection(\n set(Two1Composer.GRID_SERVICES))\n for service in sellables:\n services[service] = \"sell_\" + service\n return services",
"def test_list_services(self):\n services = (self.admin_volume_services_client.list_services()\n ['services'])\n self.assertNotEmpty(services)",
"def get_availables_services(self):\r\n self._service_locator.get_availables_services()",
"def services(\n self,\n ) -> google.protobuf.internal.containers.MessageMap[\n builtins.str, global___GapicMetadata.ServiceForTransport\n ]:",
"def services(self):\n _log.debug('get service list')\n result = self._requestJSON('services', '')\n return self._getKey(result, 'name')",
"def get_services(self):\n\n # try to get services\n try:\n\n # get services\n command = str('kubectl get services')\n subprocess.call(command.split())\n\n # handle exception\n except:\n\n # raise Exception\n raise Exception('I could not get the list of services')",
"def test_services_list(self):\n pass",
"def find_service_providers(self, service: ServiceDescriptor) -> list:\n return ['ALICE', ]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your VPC endpoints.
|
def describe_vpc_endpoints(DryRun=None, VpcEndpointIds=None, Filters=None, MaxResults=None, NextToken=None):
pass
|
[
"def describe_vpc_endpoint_services(DryRun=None, MaxResults=None, NextToken=None):\n pass",
"def delete_vpc_endpoint_resources():\n print('Deleting VPC endpoints')\n ec2 = boto3.client('ec2')\n endpoint_ids = []\n for endpoint in ec2.describe_vpc_endpoints()['VpcEndpoints']:\n print('Deleting VPC Endpoint - {}'.format(endpoint['ServiceName']))\n endpoint_ids.append(endpoint['VpcEndpointId'])\n\n if endpoint_ids:\n ec2.delete_vpc_endpoints(\n VpcEndpointIds=endpoint_ids\n )\n\n print('Waiting for VPC endpoints to get deleted')\n while ec2.describe_vpc_endpoints()['VpcEndpoints']:\n time.sleep(5)\n\n print('VPC endpoints deleted')\n\n # VPC endpoints connections\n print('Deleting VPC endpoint connections')\n service_ids = []\n for connection in ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n service_id = connection['ServiceId']\n state = connection['VpcEndpointState']\n\n if state in ['PendingAcceptance', 'Pending', 'Available', 'Rejected', 'Failed', 'Expired']:\n print('Deleting VPC Endpoint Service - {}'.format(service_id))\n service_ids.append(service_id)\n\n ec2.reject_vpc_endpoint_connections(\n ServiceId=service_id,\n VpcEndpointIds=[\n connection['VpcEndpointId'],\n ]\n )\n\n if service_ids:\n ec2.delete_vpc_endpoint_service_configurations(\n ServiceIds=service_ids\n )\n\n print('Waiting for VPC endpoint services to be destroyed')\n while ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n time.sleep(5)\n\n print('VPC endpoint connections deleted')",
"def vpc_stack_with_endpoints(region, request, key_name):\n\n logging.info(\"Creating VPC stack with endpoints\")\n credential = request.config.getoption(\"credential\")\n stack_factory = CfnStacksFactory(request.config.getoption(\"credential\"))\n\n def _create_stack(request, template, region, default_az_id, az_ids, stack_factory):\n # TODO: be able to reuse an existing VPC endpoint stack\n stack = CfnVpcStack(\n name=generate_stack_name(\"integ-tests-vpc-endpoints\", request.config.getoption(\"stackname_suffix\")),\n region=region,\n template=template.to_json(),\n default_az_id=default_az_id,\n az_ids=az_ids,\n )\n stack_factory.create_stack(stack)\n return stack\n\n # tests with VPC endpoints are not using multi-AZ\n default_az_id, default_az_name, _ = get_az_setup_for_region(region, credential)\n\n bastion_subnet = SubnetConfig(\n name=subnet_name(visibility=\"Public\", az_id=default_az_id),\n cidr=CIDR_FOR_PUBLIC_SUBNETS[0],\n map_public_ip_on_launch=True,\n has_nat_gateway=True,\n availability_zone=default_az_name,\n default_gateway=Gateways.INTERNET_GATEWAY,\n )\n\n no_internet_subnet = SubnetConfig(\n name=subnet_name(visibility=\"Private\", flavor=\"NoInternet\"),\n cidr=CIDR_FOR_PRIVATE_SUBNETS[0],\n map_public_ip_on_launch=False,\n has_nat_gateway=False,\n availability_zone=default_az_name,\n default_gateway=Gateways.NONE,\n )\n\n vpc_config = VPCConfig(\n cidr=\"192.168.0.0/17\",\n additional_cidr_blocks=[\"192.168.128.0/17\"],\n subnets=[\n bastion_subnet,\n no_internet_subnet,\n ],\n )\n\n with aws_credential_provider(region, credential):\n bastion_image_id = retrieve_latest_ami(region, \"alinux2\")\n\n template = NetworkTemplateBuilder(\n vpc_configuration=vpc_config,\n default_availability_zone=default_az_name,\n create_vpc_endpoints=True,\n bastion_key_name=key_name,\n bastion_image_id=bastion_image_id,\n region=region,\n ).build()\n\n yield _create_stack(request, template, region, default_az_id, [default_az_id], stack_factory)\n\n if not request.config.getoption(\"no_delete\"):\n stack_factory.delete_all_stacks()\n else:\n logging.warning(\"Skipping deletion of CFN VPC endpoints stack because --no-delete option is set\")",
"def describe_addresses(DryRun=None, PublicIps=None, Filters=None, AllocationIds=None):\n pass",
"def list_endpoints(self, **kwargs):\n\n all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method list_endpoints\" % key\n )\n params[key] = val\n del params['kwargs']\n\n\n resource_path = '/api/v1/endpoints'.replace('{format}', 'json')\n method = 'GET'\n\n path_params = {}\n\n query_params = {}\n if 'pretty' in params:\n query_params['pretty'] = params['pretty']\n if 'label_selector' in params:\n query_params['labelSelector'] = params['label_selector']\n if 'field_selector' in params:\n query_params['fieldSelector'] = params['field_selector']\n if 'watch' in params:\n query_params['watch'] = params['watch']\n if 'resource_version' in params:\n query_params['resourceVersion'] = params['resource_version']\n if 'timeout_seconds' in params:\n query_params['timeoutSeconds'] = params['timeout_seconds']\n\n header_params = {}\n\n form_params = {}\n files = {}\n\n body_params = None\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json', 'application/yaml'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type(['*/*'])\n\n # Authentication setting\n auth_settings = []\n\n response = self.api_client.call_api(resource_path, method,\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=files,\n response_type='V1EndpointsList',\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response",
"def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def create_vpc_endpoint(DryRun=None, VpcId=None, ServiceName=None, PolicyDocument=None, RouteTableIds=None, ClientToken=None):\n pass",
"def get_endpoints(configuration):\n pass",
"def test_114_designate_api_endpoint(self):\n u.log.debug('Checking designate api endpoint data...')\n endpoints = self.keystone.endpoints.list()\n u.log.debug(endpoints)\n admin_port = internal_port = public_port = '9001'\n expected = {'id': u.not_null,\n 'region': 'RegionOne',\n 'adminurl': u.valid_url,\n 'internalurl': u.valid_url,\n 'publicurl': u.valid_url,\n 'service_id': u.not_null}\n\n ret = u.validate_endpoint_data(\n endpoints,\n admin_port,\n internal_port,\n public_port,\n expected,\n openstack_release=self._get_openstack_release())\n if ret:\n message = 'Designate endpoint: {}'.format(ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n u.log.debug('OK')",
"def endpoints(self) -> object:\n return self._endpoints",
"def test_endpoints_add(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.endpoints), 9)\n svc.endpoints.append(sm.Endpoint(\"foo\", \"bar\"))\n svc.endpoints.append(sm.Endpoint(\"bar\", \"baz\"))\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n if not \"bar\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n for ep in svc.endpoints:\n if ep.name == \"foo\":\n self.assertEqual(ep.purpose, \"bar\")\n if ep.name == \"bar\":\n self.assertEqual(ep.purpose, \"baz\")\n self.assertEqual(len(svc.endpoints), 11)",
"def modify_vpc_endpoint(DryRun=None, VpcEndpointId=None, ResetPolicy=None, PolicyDocument=None, AddRouteTableIds=None, RemoveRouteTableIds=None):\n pass",
"def test_endpoints_replace(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n svc.endpoints = [\n sm.Endpoint(\"foo\", \"bar\"),\n sm.Endpoint(\"bar\", \"baz\"),\n ]\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n if not \"bar\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n for ep in svc.endpoints:\n if ep.name == \"foo\":\n self.assertEqual(ep.purpose, \"bar\")\n if ep.name == \"bar\":\n self.assertEqual(ep.purpose, \"baz\")\n self.assertEqual(len(svc.endpoints), 2)",
"def instance_endpoint(self) -> \"Endpoint\":\n ...",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def get_endpoints(self):\n\n return self._get_component_metadata()['endpoints']",
"def endpoints(self, endpoints: object):\n\n self._endpoints = endpoints",
"def get_endpoints(self, data_type: str):\n # return GET /endpoints\n return self._handle_response(self._http_handler.get(data_type=data_type, path=\"endpoints\"))",
"def describe_egress_only_internet_gateways(DryRun=None, EgressOnlyInternetGatewayIds=None, MaxResults=None, NextToken=None):\n pass",
"def endpoints(self) -> pulumi.Input[Sequence[pulumi.Input['ServiceMonitorSpecEndpointsArgs']]]:\n return pulumi.get(self, \"endpoints\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your VPC peering connections.
|
def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):
pass
|
[
"def describe_vpc_peering_connection(\n name, region=None, key=None, keyid=None, profile=None\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n return {\"VPC-Peerings\": _get_peering_connection_ids(name, conn)}",
"def describe_vpn_connections(DryRun=None, VpnConnectionIds=None, Filters=None):\n pass",
"def list_connections(self):\n path = self.build_url(\"/connections\")\n return self.request('get', path)",
"def peerings(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteCircuitPeeringArgs']]]]:\n return pulumi.get(self, \"peerings\")",
"def request_vpc_peering_connection(\n requester_vpc_id=None,\n requester_vpc_name=None,\n peer_vpc_id=None,\n peer_vpc_name=None,\n name=None,\n peer_owner_id=None,\n peer_region=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n dry_run=False,\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n\n if name and _vpc_peering_conn_id_for_name(name, conn):\n raise SaltInvocationError(\n \"A VPC peering connection with this name already \"\n \"exists! Please specify a different name.\"\n )\n\n if not _exactly_one((requester_vpc_id, requester_vpc_name)):\n raise SaltInvocationError(\n \"Exactly one of requester_vpc_id or requester_vpc_name is required\"\n )\n if not _exactly_one((peer_vpc_id, peer_vpc_name)):\n raise SaltInvocationError(\n \"Exactly one of peer_vpc_id or peer_vpc_name is required.\"\n )\n\n if requester_vpc_name:\n requester_vpc_id = _get_id(\n vpc_name=requester_vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not requester_vpc_id:\n return {\n \"error\": \"Could not resolve VPC name {} to an ID\".format(\n requester_vpc_name\n )\n }\n if peer_vpc_name:\n peer_vpc_id = _get_id(\n vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not peer_vpc_id:\n return {\n \"error\": \"Could not resolve VPC name {} to an ID\".format(peer_vpc_name)\n }\n\n peering_params = {\n \"VpcId\": requester_vpc_id,\n \"PeerVpcId\": peer_vpc_id,\n \"DryRun\": dry_run,\n }\n\n if peer_owner_id:\n peering_params.update({\"PeerOwnerId\": peer_owner_id})\n if peer_region:\n peering_params.update({\"PeerRegion\": peer_region})\n\n try:\n log.debug(\"Trying to request vpc peering connection\")\n if not peer_owner_id:\n vpc_peering = conn.create_vpc_peering_connection(**peering_params)\n else:\n vpc_peering = conn.create_vpc_peering_connection(**peering_params)\n peering = vpc_peering.get(\"VpcPeeringConnection\", {})\n peering_conn_id = peering.get(\"VpcPeeringConnectionId\", \"ERROR\")\n msg = \"VPC peering {} requested.\".format(peering_conn_id)\n log.debug(msg)\n\n if name:\n log.debug(\"Adding name tag to vpc peering connection\")\n conn.create_tags(\n Resources=[peering_conn_id], Tags=[{\"Key\": \"Name\", \"Value\": name}]\n )\n log.debug(\"Applied name tag to vpc peering connection\")\n msg += \" With name {}.\".format(name)\n\n return {\"msg\": msg}\n except botocore.exceptions.ClientError as err:\n log.error(\"Got an error while trying to request vpc peering\")\n return {\"error\": __utils__[\"boto.get_error\"](err)}",
"def show_connections(self, **kwargs):\n status, data = self.run_gerrit_command('show-connections', **kwargs)\n\n return status, data",
"def get_connections(self):\n return self.connections",
"def list_connections(self):\n url = self._get_management_url(\"connections\")\n conns = self._call_management(url)\n\n return conns",
"def getConnections(self):\n self.gLogging.debug(\"getConnections invoked\")\n try:\n if len(self.connections) > 0:\n connected = [x for x, y in self.connections]\n lines = self.gHosts.pickHosts(_printing=False)\n for line in lines:\n if 'group' in line:\n #group = gutils.trim_ansi(line).split('id')[0].split(\":\")[1].strip()\n group = \"id\".join(gutils.trim_ansi(line).split('id')[:-1]).split(\":\")[1].strip()\n if 'host' in line:\n #line must be cleaned up from ansi escape sequences\n host = \"id\".join(gutils.trim_ansi(line).split('id')[:-1]).split(\":\")[1].strip()\n if host in connected:\n details = self.gHosts.searchHostName(host)[0]\n print(\"\\t\" + host, gutils.color_pick(self.gConfig, '[connected, ip: {}, port: {}]'.format(details['host'], details['port']), self.gConfig['JSON']['pick_yes']))\n else:\n print(\"\\t\" + host, gutils.color_pick(self.gConfig, '[no connected]', self.gConfig['JSON']['pick_no']))\n else:\n self.gLogging.show(\"there is no active connection\")\n except Exception:\n self.gLogging.error(\"cannot get connections list\")",
"def listVpnConnection(cls, api_client, **kwargs):\n cmd = {}\n cmd.update(kwargs)\n return super(Vpn, cls).list(api_client.listVpnConnections(**cmd).get('vpnconnection', []))",
"def private_endpoint_connections(self) -> Sequence['outputs.PrivateEndpointConnectionDataModelResponse']:\n return pulumi.get(self, \"private_endpoint_connections\")",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def DumpConnections(self):\n print \"Connections:\"\n for k in self._connections.keys():\n print \" %s --> %s\" % (`k`, `self._connections[k]`)\n print \"--\"",
"def accept_vpc_peering_connection( # pylint: disable=too-many-arguments\n conn_id=\"\", name=\"\", region=None, key=None, keyid=None, profile=None, dry_run=False\n):\n if not _exactly_one((conn_id, name)):\n raise SaltInvocationError(\n \"One (but not both) of vpc_peering_connection_id or name must be provided.\"\n )\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n\n if name:\n conn_id = _vpc_peering_conn_id_for_name(name, conn)\n if not conn_id:\n raise SaltInvocationError(\n \"No ID found for this \"\n \"VPC peering connection! ({}) \"\n \"Please make sure this VPC peering \"\n \"connection exists \"\n \"or invoke this function with \"\n \"a VPC peering connection \"\n \"ID\".format(name)\n )\n try:\n log.debug(\"Trying to accept vpc peering connection\")\n conn.accept_vpc_peering_connection(\n DryRun=dry_run, VpcPeeringConnectionId=conn_id\n )\n return {\"msg\": \"VPC peering connection accepted.\"}\n except botocore.exceptions.ClientError as err:\n log.error(\"Got an error while trying to accept vpc peering\")\n return {\"error\": __utils__[\"boto.get_error\"](err)}",
"def peer_list_old_format(self):\n return '\\n'.join([f'(\"{ip}\", {port})' for ip, port in self.peer_dict.items()])",
"def connections(self):\n return self.inboundConnections.values() + self.outboundConnections.values()",
"def peering_connection_pending_from_vpc(\n conn_id=None,\n conn_name=None,\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n if not _exactly_one((conn_id, conn_name)):\n raise SaltInvocationError(\n \"Exactly one of conn_id or conn_name must be provided.\"\n )\n\n if not _exactly_one((vpc_id, vpc_name)):\n raise SaltInvocationError(\"Exactly one of vpc_id or vpc_name must be provided.\")\n\n if vpc_name:\n vpc_id = check_vpc(\n vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not vpc_id:\n log.warning(\"Could not resolve VPC name %s to an ID\", vpc_name)\n return False\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n filters = [\n {\"Name\": \"requester-vpc-info.vpc-id\", \"Values\": [vpc_id]},\n {\"Name\": \"status-code\", \"Values\": [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]},\n ]\n if conn_id:\n filters += [{\"Name\": \"vpc-peering-connection-id\", \"Values\": [conn_id]}]\n else:\n filters += [{\"Name\": \"tag:Name\", \"Values\": [conn_name]}]\n\n vpcs = conn.describe_vpc_peering_connections(Filters=filters).get(\n \"VpcPeeringConnections\", []\n )\n\n if not vpcs:\n return False\n elif len(vpcs) > 1:\n raise SaltInvocationError(\n \"Found more than one ID for the VPC peering \"\n \"connection ({}). Please call this function \"\n \"with an ID instead.\".format(conn_id or conn_name)\n )\n else:\n status = vpcs[0][\"Status\"][\"Code\"]\n\n return bool(status == PENDING_ACCEPTANCE)",
"def listConnections(destination=bool, shapes=bool, type=\"string\", source=bool, connections=bool, skipConversionNodes=bool, plugs=bool, exactType=bool):\n pass",
"def getNumConnections(self) -> \"int\":\n return _coin.SoField_getNumConnections(self)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your VPCs.
|
def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):
pass
|
[
"def describe(\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n vpc_id = _find_vpcs(\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as err:\n boto_err = __utils__[\"boto.get_error\"](err)\n if boto_err.get(\"aws\", {}).get(\"code\") == \"InvalidVpcID.NotFound\":\n # VPC was not found: handle the error and return None.\n return {\"vpc\": None}\n return {\"error\": boto_err}\n\n if not vpc_id:\n return {\"vpc\": None}\n\n filter_parameters = {\"vpc_ids\": vpc_id}\n\n try:\n vpcs = conn.get_all_vpcs(**filter_parameters)\n except BotoServerError as err:\n return {\"error\": __utils__[\"boto.get_error\"](err)}\n\n if vpcs:\n vpc = vpcs[0] # Found!\n log.debug(\"Found VPC: %s\", vpc.id)\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n return {\"vpc\": _r}\n else:\n return {\"vpc\": None}",
"def describe_vpcs(\n vpc_id=None,\n name=None,\n cidr=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n keys = (\n \"id\",\n \"cidr_block\",\n \"is_default\",\n \"state\",\n \"tags\",\n \"dhcp_options_id\",\n \"instance_tenancy\",\n )\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {\"filters\": {}}\n\n if vpc_id:\n filter_parameters[\"vpc_ids\"] = [vpc_id]\n\n if cidr:\n filter_parameters[\"filters\"][\"cidr\"] = cidr\n\n if name:\n filter_parameters[\"filters\"][\"tag:Name\"] = name\n\n if tags:\n for tag_name, tag_value in tags.items():\n filter_parameters[\"filters\"][\"tag:{}\".format(tag_name)] = tag_value\n\n vpcs = conn.get_all_vpcs(**filter_parameters)\n\n if vpcs:\n ret = []\n for vpc in vpcs:\n _r = {k: getattr(vpc, k) for k in keys}\n _r.update({\"region\": getattr(vpc, \"region\").name})\n ret.append(_r)\n return {\"vpcs\": ret}\n else:\n return {\"vpcs\": []}\n\n except BotoServerError as e:\n return {\"error\": __utils__[\"boto.get_error\"](e)}",
"def getvpcs(show):\n vpclist=[]\n \n try:\n vpcs=ec2.describe_vpcs()\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while getting vpc data: \\n\\n\\n\")\n print(e)\n for vpc in vpcs['Vpcs']:\n name=vpc['VpcId']\n cidr=vpc['CidrBlock']\n if show:\n print(\"VPC Id: \"+name+\" CIDR: \"+cidr)\n vpclist.append({ \"name\":name})\n return vpclist",
"def get_vpc_info(self):\n if not self.base['cluster'].get('vpc'):\n res = self.ec2.describe_vpcs()\n self.base['cluster']['vpc'] = [vpc['VpcId'] for vpc in res['Vpcs'] if vpc['IsDefault']][0]\n logger.info('No vpc selected, using default vpc')\n logger.info(self.base['cluster']['vpc'])",
"def _find_vpcs(\n vpc_id=None,\n vpc_name=None,\n cidr=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if all((vpc_id, vpc_name)):\n raise SaltInvocationError(\"Only one of vpc_name or vpc_id may be provided.\")\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n filter_parameters = {\"filters\": {}}\n\n if vpc_id:\n filter_parameters[\"vpc_ids\"] = [vpc_id]\n\n if cidr:\n filter_parameters[\"filters\"][\"cidr\"] = cidr\n\n if vpc_name:\n filter_parameters[\"filters\"][\"tag:Name\"] = vpc_name\n\n if tags:\n for tag_name, tag_value in tags.items():\n filter_parameters[\"filters\"][\"tag:{}\".format(tag_name)] = tag_value\n\n vpcs = conn.get_all_vpcs(**filter_parameters)\n log.debug(\n \"The filters criteria %s matched the following VPCs:%s\", filter_parameters, vpcs\n )\n\n if vpcs:\n if not any((vpc_id, vpc_name, cidr, tags)):\n return [vpc.id for vpc in vpcs if vpc.is_default]\n else:\n return [vpc.id for vpc in vpcs]\n else:\n return []",
"def describe_vpc_endpoint_services(DryRun=None, MaxResults=None, NextToken=None):\n pass",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def _provide_subnets(self):\n if not self.cfg.aws.subnet:\n logging.debug(\"Subnets are not provided\")\n # Try to get subnet from default VPC or VPC set in aws-vpc config parameter\n vpc = self._provide_vpc()\n if vpc:\n subnet_list = vpc.subnets.all()\n self.vpc_id = vpc.id\n self.subnets = ','.join(map(lambda x: x.id, subnet_list))\n else:\n # Ensure that VPC is set and that subnets provided belong to it\n subnets = [x.strip() for x in self.cfg.aws.subnet.split(',')]\n # If aws-vpc parameter is set, use this VPC, otherwise use VPC of the\n # first subnet\n logging.debug(f\"Subnets are provided: {' ,'.join(subnets)}\")\n vpc = None\n if self.vpc_id:\n if self.vpc_id.lower() == 'none':\n return None\n vpc = self.ec2.Vpc(self.vpc_id)\n for subnet_name in subnets:\n subnet = self.ec2.Subnet(subnet_name)\n if not vpc:\n vpc = subnet.vpc # if subnet is invalid - will throw an exception botocore.exceptions.ClientError with InvalidSubnetID.NotFound\n else:\n if subnet.vpc != vpc:\n raise UserReportError(returncode=INPUT_ERROR, message=\"Subnets set in aws-subnet parameter belong to different VPCs\")\n self.vpc_id = vpc.id\n self.subnets = ','.join(subnets)\n logging.debug(f\"Using VPC {self.vpc_id}, subnet(s) {self.subnets}\")",
"def deletevpc(vpc_choices):\n progressbar(\"Deleting VPC\")\n vpcname=vpc_choices['vpc'][0]\n try:\n ec2.delete_vpc(VpcId=str(vpcname))\n print(\"\\n \\n vpc \" +vpcname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting vpc: \\n\\n\\n\")\n print(e)",
"def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):\n pass",
"def delete(\n vpc_id=None,\n name=None,\n vpc_name=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if name:\n log.warning(\n \"boto_vpc.delete: name parameter is deprecated use vpc_name instead.\"\n )\n vpc_name = name\n\n if not _exactly_one((vpc_name, vpc_id)):\n raise SaltInvocationError(\n \"One (but not both) of vpc_name or vpc_id must be provided.\"\n )\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if not vpc_id:\n vpc_id = _get_id(\n vpc_name=vpc_name,\n tags=tags,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not vpc_id:\n return {\n \"deleted\": False,\n \"error\": {\"message\": \"VPC {} not found\".format(vpc_name)},\n }\n\n if conn.delete_vpc(vpc_id):\n log.info(\"VPC %s was deleted.\", vpc_id)\n if vpc_name:\n _cache_id(\n vpc_name,\n resource_id=vpc_id,\n invalidate=True,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n return {\"deleted\": True}\n else:\n log.warning(\"VPC %s was not deleted.\", vpc_id)\n return {\"deleted\": False}\n except BotoServerError as e:\n return {\"deleted\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def DescribeVpcInstances(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DescribeVpcInstances\", params, headers=headers)\n response = json.loads(body)\n model = models.DescribeVpcInstancesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def vpc_configurations(self) -> Optional[Sequence['outputs.ApplicationVpcConfiguration']]:\n return pulumi.get(self, \"vpc_configurations\")",
"def get_subnets(connection, vpc_id):\n return connection.get_all_subnets(filters={'vpc_id': vpc_id})",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def main(azs, region, keyid, secret, cidr, owner, env):\n\n # Validate the region\n myregion = boto.ec2.get_region(region_name=region)\n if myregion == None:\n print(\"Unknown region.\")\n exit(1)\n\n # Establish a VPC service connection\n try:\n conn = boto.vpc.VPCConnection(aws_access_key_id=keyid, aws_secret_access_key=secret, region=myregion)\n except boto.exception.EC2ResponseError as e:\n print(e.message)\n exit(1)\n\n # Grab the availability-zones\n zones = []\n all_zones = conn.get_all_zones()\n for zone in all_zones:\n if zone.state != 'available':\n continue\n zones.append(zone.name)\n\n subnets = subnet_sizes(azs, cidr) # Calculate the subnet sizes\n name = owner.lower() + '-' + env.lower() + '-' # Used for tagging\n\n vpc_id = create_vpc(conn, name, region, cidr)\n igw_id = create_igw(conn, name, region, vpc_id)\n sub_ids = create_sub(conn, name, region, vpc_id, azs, subnets, zones)\n rtb_ids = create_rtb(conn, name, region, vpc_id, azs, sub_ids, igw_id)\n acl_ids = create_acl(conn, name, region, vpc_id, azs, sub_ids, cidr)\n flow_id = create_flows(vpc_id, keyid, secret, region)",
"def get_usable_vpc(config):\n _, _, compute, _ = construct_clients_from_provider_config(config[\"provider\"])\n\n # For backward compatibility, reuse the VPC if the VM is launched.\n resource = GCPCompute(\n compute,\n config[\"provider\"][\"project_id\"],\n config[\"provider\"][\"availability_zone\"],\n config[\"cluster_name\"],\n )\n node = resource._list_instances(label_filters=None, status_filter=None)\n if len(node) > 0:\n netInterfaces = node[0].get(\"networkInterfaces\", [])\n if len(netInterfaces) > 0:\n vpc_name = netInterfaces[0][\"network\"].split(\"/\")[-1]\n return vpc_name\n\n vpcnets_all = _list_vpcnets(config, compute)\n\n usable_vpc_name = None\n for vpc in vpcnets_all:\n if _check_firewall_rules(vpc[\"name\"], config, compute):\n usable_vpc_name = vpc[\"name\"]\n break\n\n proj_id = config[\"provider\"][\"project_id\"]\n if usable_vpc_name is None:\n logger.info(f\"Creating a default VPC network, {SKYPILOT_VPC_NAME}...\")\n\n # Create a SkyPilot VPC network if it doesn't exist\n vpc_list = _list_vpcnets(config, compute, filter=f\"name={SKYPILOT_VPC_NAME}\")\n if len(vpc_list) == 0:\n body = VPC_TEMPLATE.copy()\n body[\"name\"] = body[\"name\"].format(VPC_NAME=SKYPILOT_VPC_NAME)\n body[\"selfLink\"] = body[\"selfLink\"].format(\n PROJ_ID=proj_id, VPC_NAME=SKYPILOT_VPC_NAME\n )\n _create_vpcnet(config, compute, body)\n\n _create_rules(\n config, compute, FIREWALL_RULES_TEMPLATE, SKYPILOT_VPC_NAME, proj_id\n )\n\n usable_vpc_name = SKYPILOT_VPC_NAME\n logger.info(f\"A VPC network {SKYPILOT_VPC_NAME} created.\")\n\n # Configure user specified rules\n ports = config[\"provider\"].get(\"ports\", [])\n user_rules = []\n for port in ports:\n cluster_name_hash = common_utils.truncate_and_hash_cluster_name(\n config[\"cluster_name\"]\n )\n name = f\"user-ports-{cluster_name_hash}-{port}\"\n user_rules.append(\n {\n \"name\": name,\n \"description\": f\"Allow user-specified port {port} for cluster {config['cluster_name']}\",\n \"network\": \"projects/{PROJ_ID}/global/networks/{VPC_NAME}\",\n \"selfLink\": \"projects/{PROJ_ID}/global/firewalls/\" + name,\n \"direction\": \"INGRESS\",\n \"priority\": 65534,\n \"allowed\": [\n {\n \"IPProtocol\": \"tcp\",\n \"ports\": [str(port)],\n },\n ],\n \"sourceRanges\": [\"0.0.0.0/0\"],\n \"targetTags\": [config[\"cluster_name\"]],\n }\n )\n\n _create_rules(config, compute, user_rules, usable_vpc_name, proj_id)\n\n return usable_vpc_name",
"def from_dict(cls, _dict: Dict) -> 'VPC':\n args = {}\n if 'classic_access' in _dict:\n args['classic_access'] = _dict.get('classic_access')\n else:\n raise ValueError('Required property \\'classic_access\\' not present in VPC JSON')\n if 'created_at' in _dict:\n args['created_at'] = string_to_datetime(_dict.get('created_at'))\n else:\n raise ValueError('Required property \\'created_at\\' not present in VPC JSON')\n if 'crn' in _dict:\n args['crn'] = _dict.get('crn')\n else:\n raise ValueError('Required property \\'crn\\' not present in VPC JSON')\n if 'cse_source_ips' in _dict:\n args['cse_source_ips'] = [VPCCSESourceIP.from_dict(x) for x in _dict.get('cse_source_ips')]\n if 'default_network_acl' in _dict:\n args['default_network_acl'] = NetworkACLReference.from_dict(_dict.get('default_network_acl'))\n else:\n raise ValueError('Required property \\'default_network_acl\\' not present in VPC JSON')\n if 'default_routing_table' in _dict:\n args['default_routing_table'] = RoutingTableReference.from_dict(_dict.get('default_routing_table'))\n else:\n raise ValueError('Required property \\'default_routing_table\\' not present in VPC JSON')\n if 'default_security_group' in _dict:\n args['default_security_group'] = SecurityGroupReference.from_dict(_dict.get('default_security_group'))\n else:\n raise ValueError('Required property \\'default_security_group\\' not present in VPC JSON')\n if 'href' in _dict:\n args['href'] = _dict.get('href')\n else:\n raise ValueError('Required property \\'href\\' not present in VPC JSON')\n if 'id' in _dict:\n args['id'] = _dict.get('id')\n else:\n raise ValueError('Required property \\'id\\' not present in VPC JSON')\n if 'name' in _dict:\n args['name'] = _dict.get('name')\n else:\n raise ValueError('Required property \\'name\\' not present in VPC JSON')\n if 'resource_group' in _dict:\n args['resource_group'] = ResourceGroupReference.from_dict(_dict.get('resource_group'))\n else:\n raise ValueError('Required property \\'resource_group\\' not present in VPC JSON')\n if 'status' in _dict:\n args['status'] = _dict.get('status')\n else:\n raise ValueError('Required property \\'status\\' not present in VPC JSON')\n return cls(**args)",
"def create_vpc(DryRun=None, CidrBlock=None, InstanceTenancy=None, AmazonProvidedIpv6CidrBlock=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your VPN connections. For more information about VPN connections, see Adding a Hardware Virtual Private Gateway to Your VPC in the Amazon Virtual Private Cloud User Guide .
|
def describe_vpn_connections(DryRun=None, VpnConnectionIds=None, Filters=None):
pass
|
[
"def listVpnConnection(cls, api_client, **kwargs):\n cmd = {}\n cmd.update(kwargs)\n return super(Vpn, cls).list(api_client.listVpnConnections(**cmd).get('vpnconnection', []))",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def create_vpn_connection(DryRun=None, Type=None, CustomerGatewayId=None, VpnGatewayId=None, Options=None):\n pass",
"def describe_vpn_gateways(DryRun=None, VpnGatewayIds=None, Filters=None):\n pass",
"def show_connections(self, **kwargs):\n status, data = self.run_gerrit_command('show-connections', **kwargs)\n\n return status, data",
"def __init__(self,\n connections: List['VPNGatewayConnection']) -> None:\n self.connections = connections",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def listConnections(destination=bool, shapes=bool, type=\"string\", source=bool, connections=bool, skipConversionNodes=bool, plugs=bool, exactType=bool):\n pass",
"def _set_vpn(self, str_vpn):\n # The VPN name is passed as a varaible to get the right commands to use.\n if str_vpn is not None:\n dict_vpn = VPN.dict_vpn\n self.vpn_status = dict_vpn['vpn_is_on'][str_vpn]\n self.vpn_connect = dict_vpn['vpn_new_connection'][str_vpn]\n\n request = ConnectionManager.request(url='https://nordvpn.com/api/server')\n soup = BeautifulSoup(request, 'lxml')\n lst_servers = json.loads(soup.text)\n\n servers = pd.DataFrame({'Country': [serv['country'] for serv in lst_servers],\n 'Domain': [serv['domain'] for serv in lst_servers]})\n\n servers['Flag'] = servers['Domain'].astype(str).str.extract(r'^([a-z]{2})\\d{2,4}.nordvpn.com$')\n servers['ID'] = servers['Domain'].astype(str).str.extract(r'^[a-z]{2}(\\d{2,4}).nordvpn.com$')\n\n self.servers = servers\n else:\n self.vpn_status = None\n self.vpn_connect = None",
"def describe_vpc_peering_connection(\n name, region=None, key=None, keyid=None, profile=None\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n return {\"VPC-Peerings\": _get_peering_connection_ids(name, conn)}",
"def listVpnGateway(cls, api_client, **kwargs):\n cmd = {}\n cmd.update(kwargs)\n return super(Vpn, cls).list(api_client.listVpnGateways(**cmd))",
"def _info():\n\n # This is what prints out in the default command page, it should be\n # as short as possible.\n emitter.publish(\"Proxy and VPN access to DC/OS cluster\")\n return 0",
"def test_01_vpc_remote_access_vpn(self):\n # 1) Create VPC\n vpc = VPC.create(\n api_client=self.apiclient,\n services=self.services[\"vpc\"],\n networkDomain=\"vpc.vpn\",\n vpcofferingid=self.vpc_offering.id,\n zoneid=self.zone.id,\n account=self.account.name,\n domainid=self.domain.id\n )\n\n self.assertIsNotNone(vpc, \"VPC creation failed\")\n self.logger.debug(\"VPC %s created\" % (vpc.id))\n\n self.cleanup.append(vpc)\n\n # 2) Create network in VPC\n ntwk = Network.create(\n api_client=self.apiclient,\n services=self.services[\"network_1\"],\n accountid=self.account.name,\n domainid=self.domain.id,\n networkofferingid=self.network_offering.id,\n zoneid=self.zone.id,\n vpcid=vpc.id\n )\n\n self.assertIsNotNone(ntwk, \"Network failed to create\")\n self.logger.debug(\"Network %s created in VPC %s\" % (ntwk.id, vpc.id))\n\n self.cleanup.append(ntwk)\n\n # 3) Deploy a vm\n vm = VirtualMachine.create(self.apiclient, services=self.services[\"virtual_machine\"],\n templateid=self.template.id,\n zoneid=self.zone.id,\n accountid=self.account.name,\n domainid=self.domain.id,\n serviceofferingid=self.virtual_machine_offering.id,\n networkids=ntwk.id,\n hypervisor=self.hypervisor\n )\n self.assertIsNotNone(vm, \"VM failed to deploy\")\n self.assertEquals(vm.state, 'Running', \"VM is not running\")\n self.debug(\"VM %s deployed in VPC %s\" % (vm.id, vpc.id))\n\n self.logger.debug(\"Deployed virtual machine: OK\")\n self.cleanup.append(vm)\n\n # 4) Enable VPN for VPC\n src_nat_list = PublicIPAddress.list(\n self.apiclient,\n account=self.account.name,\n domainid=self.account.domainid,\n listall=True,\n issourcenat=True,\n vpcid=vpc.id\n )\n ip = src_nat_list[0]\n\n self.logger.debug(\"Acquired public ip address: OK\")\n\n vpn = Vpn.create(self.apiclient,\n publicipid=ip.id,\n account=self.account.name,\n domainid=self.account.domainid,\n iprange=self.services[\"vpn\"][\"iprange\"],\n fordisplay=self.services[\"vpn\"][\"fordisplay\"]\n )\n\n self.assertIsNotNone(vpn, \"Failed to create Remote Access VPN\")\n self.logger.debug(\"Created Remote Access VPN: OK\")\n\n vpn_user = None\n # 5) Add VPN user for VPC\n vpn_user = VpnUser.create(self.apiclient,\n account=self.account.name,\n domainid=self.account.domainid,\n username=self.services[\"vpn\"][\"vpn_user\"],\n password=self.services[\"vpn\"][\"vpn_pass\"]\n )\n\n self.assertIsNotNone(vpn_user, \"Failed to create Remote Access VPN User\")\n self.logger.debug(\"Created VPN User: OK\")\n\n # TODO: Add an actual remote vpn connection test from a remote vpc\n\n # 9) Disable VPN for VPC\n vpn.delete(self.apiclient)\n\n self.logger.debug(\"Deleted the Remote Access VPN: OK\")",
"def showNetwork(self):\n print(\"-------------------\")\n print(\" vascularNetwork \", self.name, \"\\n\")\n for variable, value in iteritems(self.__dict__):\n try:\n print(\" {:<20} {:>8}\".format(variable, value))\n except Exception: print(\" {:<20} {:>8}\".format(variable, 'None'))",
"def connections():\n return jsonify({v.alias: v.connection.to_json() for v in omegas.values()})",
"def _vpn(port, config_file, user, privileged, ssh_port, host, verbose,\n openvpn_container, vpn_client, docker_cmd):\n\n if verbose:\n set_verbose()\n\n if privileged:\n os.environ[constants.privileged] = '1'\n\n if sys.platform == 'win32':\n logger.error(\"*** VPN is currently unsupported on Windows\")\n return 1\n\n if not is_privileged():\n logger.error(\"*** You don't have permission to run this command.\" +\n \"\\n{}\".format(constants.unprivileged_suggestion))\n return 1\n\n if not ((os.path.isfile(vpn_client) and os.access(vpn_client, os.X_OK)) or\n shutil.which(vpn_client)):\n msg = \"*** Not a valid executable: {}\"\n logger.error(msg.format(vpn_client))\n return 1\n\n port = validate_port(port, default=1194)\n if port is None:\n return 1\n client = sshclient(config_file, user, ssh_port, host)\n\n if not distutils.spawn.find_executable(vpn_client):\n msg = (\"You don't seem to have the '{}' executable. Please add it to \"\n \"your $PATH or equivalent.\")\n logger.error(msg.format(vpn_client))\n return 1\n\n docker_cmd = resolve_docker_cmd(client, docker_cmd)\n\n mesos_hosts, dns_hosts = gen_hosts(client)\n container_name = \"openvpn-{}\".format(rand_str(8))\n remote_openvpn_dir = \"/etc/openvpn\"\n remote_keyfile = \"{}/static.key\".format(remote_openvpn_dir)\n remote_clientfile = \"{}/client.ovpn\".format(remote_openvpn_dir)\n\n emitter.publish(\"\\nATTENTION: IF DNS DOESN'T WORK, add these DNS servers!\")\n for host in dns_hosts:\n emitter.publish(host)\n\n parsed_routes = ','.join(mesos_hosts)\n parsed_dns = ','.join(dns_hosts)\n\n with util.temptext() as server_tup, \\\n util.temptext() as key_tup, \\\n util.temptext() as config_tup, \\\n util.temptext() as client_tup:\n\n serverfile, serverpath = server_tup\n keyfile, keypath = key_tup\n clientconfigfile, clientconfigpath = config_tup\n clientfile, clientpath = client_tup\n\n scom = \"\"\"\\\n {} run --rm --cap-add=NET_ADMIN -p 0:1194 \\\n -e \"OPENVPN_ROUTES={}\" -e \"OPENVPN_DNS={}\" --name {} {}\\\n \"\"\".format(docker_cmd, parsed_routes, parsed_dns,\n container_name, openvpn_container)\n\n # FDs created when python opens a file have O_CLOEXEC set, which\n # makes them invalid in new threads (cloning). So we duplicate the\n # FD, which creates one without O_CLOEXEC.\n serverfile_dup = os.dup(serverfile)\n # XXX This FD is never closed because it would cause the vpn server\n # thread to crash\n\n vpn_server = threading.Thread(target=logging_exec,\n args=(client, scom, serverfile_dup,\n True),\n daemon=True)\n vpn_server.start()\n\n msg = \"\\nWaiting for VPN server in container '{}' to come up...\"\n emitter.publish(msg.format(container_name))\n\n scom = (\"until \"\n \"\"\"[ \"$(%s inspect --format='{{ .State.Running }}' \"\"\"\n \"\"\"%s 2>/dev/null)\" = \"true\" ] 2>/dev/null; do sleep 0.5; \"\"\"\n \"\"\"done\"\"\") % (docker_cmd, container_name)\n scom += (\" && \"\n \"\"\"{} exec {} sh -c 'until [ -s {} ]; do sleep 0.5; \"\"\"\n \"\"\"done' \"\"\").format(docker_cmd, container_name,\n remote_keyfile)\n scom += (\" && \"\n \"\"\"{} exec {} sh -c 'until [ -s {} ]; do sleep 0.5; \"\"\"\n \"\"\"done' \"\"\").format(docker_cmd, container_name,\n remote_clientfile)\n ssh_exec_fatal(client, scom)\n\n scom = (\"\"\"%s inspect --format='\"\"\"\n \"\"\"{{range $p, $conf := .NetworkSettings.Ports}}\"\"\"\n \"\"\"{{(index $conf 0).HostPort}}{{end}}' %s\"\"\"\n ) % (docker_cmd, container_name)\n remote_port = int(ssh_exec_fatal(client, scom).read().decode().strip())\n\n def tunnel_def():\n ssh_transport = client.get_transport()\n forward_tunnel(port, '127.0.0.1', remote_port, ssh_transport)\n tunnel = threading.Thread(target=tunnel_def, daemon=True)\n tunnel.start()\n\n container_cp(client, container_name, remote_keyfile, keyfile,\n docker_cmd)\n container_cp(client, container_name, remote_clientfile,\n clientconfigfile, docker_cmd)\n\n vpn_com = '{} --config {} --secret {} --port {}'\n vpn_com = vpn_com.format(vpn_client, clientconfigpath, keypath, port)\n\n emitter.publish(\"\\nVPN server output at {}\".format(serverpath))\n emitter.publish(\"VPN client output at {}\\n\".format(clientpath))\n ret = run_vpn(vpn_com, clientfile)\n\n client.close()\n input('Exited. Temporary files will be gone once you hit <Return>.')\n return ret",
"def addvpn():\n error = None\n if 'name' not in request.args:\n error = 'Name of VPN not found in query. '\n elif 'lng' not in request.args or not isnumber(request.args['lng']):\n error = 'Invalid longitude. '\n elif 'lat' not in request.args or not isnumber(request.args['lat']):\n error = 'Invalid latitude. '\n \n if error:\n return error+'Desired url format: '+gethostname()+':5000/addvpn?name=<name>&lng=<lng>&lat=<lat>'\n else:\n g.db.execute(\"INSERT OR REPLACE INTO vpns ('name','lng','lat') VALUES (?,?,?)\",\n [request.args['name'], request.args['lng'], request.args['lat']])\n g.db.commit()\n return \"Added vpn: \"+','.join([request.args['name'],request.args['lng'],request.args['lat']])",
"def listvpns():\n error = None\n if 'lng' not in request.args or not isnumber(request.args['lng']):\n error = 'Invalid longitude. '\n elif 'lat' not in request.args or not isnumber(request.args['lat']):\n error = 'Invalid latitude. '\n \n if error:\n return error+'Desired url format: '+gethostname()+':5000/?lng=<lng>&lat=<lat>'\n\n else:\n cur = g.db.execute('SELECT * FROM vpns')\n vpns = [[str(row[0]),row[1],row[2]] for row in cur.fetchall()]\n \n # Calculate the distance to each vpn\n for vpn in vpns:\n vpnlng = vpn[1]\n vpnlat = vpn[2]\n phi1 = radians(float(request.args['lat']))\n phi2 = radians(vpnlat)\n deltaphi = radians(vpnlat-float(request.args['lat']))\n deltalambda = radians(vpnlng-float(request.args['lng']))\n\n R = 3959 # radius of the earth\n a = pow(sin(deltaphi/2),2) + cos(phi1) * cos(phi2) * pow(sin(deltalambda/2),2)\n c = 2 * atan2(sqrt(a), sqrt(1-a))\n distance = R*c\n \n vpn.append(distance)\n\n vpn_output = ''\n for vpn in sorted(vpns, key=lambda vpn: vpn[3]):\n vpn_output += vpn[0]+'<br>'\n\n return vpn_output",
"def DescribeVpnGateways(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DescribeVpnGateways\", params, headers=headers)\n response = json.loads(body)\n model = models.DescribeVpnGatewaysResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Describes one or more of your virtual private gateways. For more information about virtual private gateways, see Adding an IPsec Hardware VPN to Your VPC in the Amazon Virtual Private Cloud User Guide .
|
def describe_vpn_gateways(DryRun=None, VpnGatewayIds=None, Filters=None):
pass
|
[
"def delete_virtual_gateways():\n client = boto3.client('ec2')\n print('Deleting VPN Gateways')\n gw_resp = client.describe_vpn_gateways()\n while True:\n for gateway in gw_resp['VpnGateways']:\n gw_id = gateway['VpnGatewayId']\n gw_attachments = gateway['VpcAttachments']\n for attachment in gw_attachments:\n if attachment['State'] == 'attached':\n vpc_id = attachment['VpcId']\n print('Detaching virtual gateway {} from vpc {}'.format(gw_id, vpc_id))\n client.detach_vpn_gateway(\n VpcId=vpc_id,\n VpnGatewayId=gw_id\n )\n print('Deleting VPN gateway {}'.format(gw_id))\n client.delete_vpn_gateway(\n VpnGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_vpn_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_vpn_gateways()['VpnGateways']:\n all_deleted = True\n for gateway in client.describe_vpn_gateways()['VpnGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n print('VPN Gateways deleted')",
"def describe_internet_gateways(DryRun=None, InternetGatewayIds=None, Filters=None):\n pass",
"def describe_customer_gateways(DryRun=None, CustomerGatewayIds=None, Filters=None):\n pass",
"def describe_nat_gateways(\n nat_gateway_id=None,\n subnet_id=None,\n subnet_name=None,\n vpc_id=None,\n vpc_name=None,\n states=(\"pending\", \"available\"),\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n return _find_nat_gateways(\n nat_gateway_id=nat_gateway_id,\n subnet_id=subnet_id,\n subnet_name=subnet_name,\n vpc_id=vpc_id,\n vpc_name=vpc_name,\n states=states,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )",
"def describe_nat_gateways(NatGatewayIds=None, Filters=None, MaxResults=None, NextToken=None):\n pass",
"def listVpnGateway(cls, api_client, **kwargs):\n cmd = {}\n cmd.update(kwargs)\n return super(Vpn, cls).list(api_client.listVpnGateways(**cmd))",
"def DescribeVpnGateways(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DescribeVpnGateways\", params, headers=headers)\n response = json.loads(body)\n model = models.DescribeVpnGatewaysResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"async def test_multiple_gateways(caplog):\n async with Context() as context:\n await Py4JComponent(gateways={\n 'java1': {},\n 'java2': {}\n }).start(context)\n assert isinstance(context.java1, JavaGateway)\n assert isinstance(context.java2, JavaGateway)\n\n records = [record for record in caplog.records if record.name == 'asphalt.py4j.component']\n records.sort(key=lambda r: r.message)\n assert len(records) == 4\n assert records[0].message.startswith(\"Configured Py4J gateway \"\n \"(java1 / ctx.java1; address=127.0.0.1, port=\")\n assert records[1].message.startswith(\"Configured Py4J gateway \"\n \"(java2 / ctx.java2; address=127.0.0.1, port=\")\n assert records[2].message == 'Py4J gateway (java1) shut down'\n assert records[3].message == 'Py4J gateway (java2) shut down'",
"def create_vpn_gateway(DryRun=None, Type=None, AvailabilityZone=None):\n pass",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def describe_vpn_connections(DryRun=None, VpnConnectionIds=None, Filters=None):\n pass",
"def _find_nat_gateways(\n nat_gateway_id=None,\n subnet_id=None,\n subnet_name=None,\n vpc_id=None,\n vpc_name=None,\n states=(\"pending\", \"available\"),\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)):\n raise SaltInvocationError(\n \"At least one of the following must be \"\n \"provided: nat_gateway_id, subnet_id, \"\n \"subnet_name, vpc_id, or vpc_name.\"\n )\n filter_parameters = {\"Filter\": []}\n\n if nat_gateway_id:\n filter_parameters[\"NatGatewayIds\"] = [nat_gateway_id]\n\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\", subnet_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not subnet_id:\n return False\n\n if subnet_id:\n filter_parameters[\"Filter\"].append({\"Name\": \"subnet-id\", \"Values\": [subnet_id]})\n\n if vpc_name:\n vpc_id = _get_resource_id(\n \"vpc\", vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not vpc_id:\n return False\n\n if vpc_id:\n filter_parameters[\"Filter\"].append({\"Name\": \"vpc-id\", \"Values\": [vpc_id]})\n\n conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n nat_gateways = []\n for ret in __utils__[\"boto3.paged_call\"](\n conn3.describe_nat_gateways,\n marker_flag=\"NextToken\",\n marker_arg=\"NextToken\",\n **filter_parameters\n ):\n for gw in ret.get(\"NatGateways\", []):\n if gw.get(\"State\") in states:\n nat_gateways.append(gw)\n log.debug(\n \"The filters criteria %s matched the following nat gateways: %s\",\n filter_parameters,\n nat_gateways,\n )\n\n if nat_gateways:\n return nat_gateways\n else:\n return False",
"def describe_vpc_endpoint_services(DryRun=None, MaxResults=None, NextToken=None):\n pass",
"def delete_nat_gateways():\n print('Deleting NAT gateways')\n ec2 = boto3.client('ec2')\n for page in ec2.get_paginator('describe_nat_gateways').paginate():\n for nat_gateway in page['NatGateways']:\n nat_gateway_id = nat_gateway['NatGatewayId']\n print('Deleting Nat Gateway - {}'.format(nat_gateway_id))\n ec2.delete_nat_gateway(\n NatGatewayId=nat_gateway_id\n )\n\n while ec2.describe_nat_gateways()['NatGateways']:\n all_deleted = True\n for gateway in ec2.describe_nat_gateways()['NatGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n\n print('NAT gateways deleted')",
"def describe_egress_only_internet_gateways(DryRun=None, EgressOnlyInternetGatewayIds=None, MaxResults=None, NextToken=None):\n pass",
"def create_vpn_connection(DryRun=None, Type=None, CustomerGatewayId=None, VpnGatewayId=None, Options=None):\n pass",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def describe_vpcs(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def neigh_options(config):\r\n\r\n next_hop = [\"Yes\" for k in dict.fromkeys(config) if k == \"next-hop-self\"]\r\n if not next_hop:\r\n next_hop = [\"No\"]\r\n\r\n reflector = [\"Yes\" for k in dict.fromkeys(config) if k == \"route-reflector-client\"]\r\n if not reflector:\r\n reflector = [\"No\"]\r\n\r\n soft_reconfig = [v for k, v in config.items() if k == \"soft-reconfiguration\"]\r\n if not soft_reconfig:\r\n soft_reconfig = [\"No\"]\r\n\r\n activate = [\"Yes\" for k in dict.fromkeys(config) if k == \"activate\"]\r\n if not reflector:\r\n activate = [\"No\"]\r\n\r\n return next_hop, reflector, soft_reconfig, activate"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Unlinks (detaches) a linked EC2Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped.
|
def detach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None):
pass
|
[
"def terminate_instance(instance_id):\n\n client = boto3.client('ec2')\n response = client.terminate_instances(InstanceIds=instance_id)",
"def terminate(session):\n logging.info(\"Terminating instances\")\n session.clients[\"ec2\"].terminate_instances(InstanceIds=list(session.instances))",
"def TerminateInstance(*, session, instanceid):\n ec2conn = session.connect_to(\"ec2\")\n return ec2conn.terminate_instances(instance_ids=[instanceid,])",
"def stop_instance(stackName, instanceName=None):\n control_instance(stackName=stackName, action='stop', instanceName=instanceName)",
"def stop():\n local('aws ec2 stop-instances --instance-ids %s'%(AWS_INSTANCE_ID))",
"def StopInstance(*, session, instanceid):\n ec2conn = session.connect_to(\"ec2\")\n ret = ec2.stop_instances(instance_ids=[instanceid,])\n return True",
"def terminate_instance(conn, instance_id):\n\n # Terminate an instance based on a user provided id\n conn.terminate_instances(instance_id)",
"def DetachCcnInstances(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DetachCcnInstances\", params, headers=headers)\n response = json.loads(body)\n model = models.DetachCcnInstancesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def stop() -> None:\n config = load_config_file()\n instance_ips = [i.public_ip_address for i in get_running_instances(config)]\n if not instance_ips:\n raise Exception('ERROR: No instances with public IPs found. Exiting.')\n try:\n execute_commands_on_linux_instances(\n config,\n [\n COMMAND_KILL\n ],\n instance_ips\n )\n except Exception as e:\n logging.error(\"Something went wrong.\")\n raise\n logging.info('Done!')",
"def stopinstances():\n username, conn = _getbotoconn(auth_user)\n print \"stopping instances running under the %s account\" % username\n\n running_instances = _getrunninginstances(conn)\n for instid, instance in running_instances.iteritems():\n instance.stop()\n print \"instance %s stopped\" % instid",
"def terminate_instance(id):\n for region in boto.ec2.regions():\n conn = region.connect()\n for reservation in conn.get_all_instances():\n for instance in reservation.instances:\n if instance.id == id:\n print \"Terminating instance: {0}\".format(id)\n instance.terminate()\n return\n print \"Unable to terminate instance: {0}\".format(id)",
"def delete_load_balancers_v2():\n print('Deleting Load Balancers v2')\n elbv2 = boto3.client('elbv2')\n\n for load_balancer in elbv2.describe_load_balancers()['LoadBalancers']:\n lb_arn = load_balancer['LoadBalancerArn']\n print('Deleting LB v2 - {}'.format(lb_arn))\n\n elbv2.delete_load_balancer(\n LoadBalancerArn=lb_arn\n )\n\n if elbv2.describe_load_balancers()['LoadBalancers']:\n print('Waiting for LB v2 to be destroyed')\n while elbv2.describe_load_balancers()['LoadBalancers']:\n time.sleep(5)\n print('Load Balancers v2 deleted')",
"def destroy(self, context, instance, network_info, block_device_info=None,\n destroy_disks=True):\n LOG.debug(_(\"Enter to destroy instance of %(uuid)s\") % instance)\n responseValue = self._service.destroy(instance)\n LOG.debug(_(\"Exit to destroy instance of %(uuid)s\") % instance)\n return responseValue",
"def do_detach_vnic(detach_options, vnic_utils):\n\n sess = get_oci_api_session()\n if sess is None:\n raise Exception(\"Failed to get API session.\")\n vnics = sess.this_instance().all_vnics()\n for vnic in vnics:\n if vnic.get_ocid() == detach_options.ocid or \\\n vnic.get_private_ip() == detach_options.ip_address:\n if not vnic.is_primary():\n vnic_utils.delete_all_private_ips(vnic.get_ocid())\n vnic.detach()\n break\n raise Exception(\"The primary VNIC cannot be detached.\")",
"def removeNetwork(conn):\n try:\n net = conn.networkLookupByName('vauto')\n except libvirt.libvirtError, e:\n logging.warn(\"Cannot find vauto network.\")\n return\n if net.isActive():\n net.destroy()\n if net.isPersistent():\n net.undefine()",
"def terminate_instances(self):\n\n if self._reservation and self._reservation.instances:\n for instance in self._reservation.instances:\n instance.terminate()\n msg = 'EC2 instance terminated.'\n log.info(msg)\n self._store_message(msg)",
"def test_05_destroy_instance_in_network(self):\n\n # Validate the following\n # 1. Destory the virtual machines.\n # 2. Rules should be still configured on virtual router.\n # 3. Recover the virtual machines.\n # 4. Vm should be in stopped state. State both the instances\n # 5. Make sure that all the PF,LB and Static NAT rules on this VM\n # works as expected.\n # 6. Make sure that we are able to access google.com from this user Vm\n\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n self.debug(\"Destroying the virtual machines in account: %s\" %\n self.account.name)\n try:\n self.vm_1.delete(self.apiclient, expunge=False)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Destroyed',\n \"VM state should be destroyed\"\n )\n\n except Exception as e:\n self.fail(\"Failed to stop the virtual instances, %s\" % e)\n\n # Check if the network rules still exists after Vm stop\n self.debug(\"Checking if NAT rules \")\n nat_rules = NATRule.list(\n self.apiclient,\n id=self.nat_rule.id,\n listall=True\n )\n self.assertEqual(\n isinstance(nat_rules, list),\n True,\n \"List NAT rules shall return a valid list\"\n )\n\n lb_rules = LoadBalancerRule.list(\n self.apiclient,\n id=self.lb_rule.id,\n listall=True\n )\n self.assertEqual(\n isinstance(lb_rules, list),\n True,\n \"List LB rules shall return a valid list\"\n )\n\n self.debug(\"Recovering the expunged virtual machine vm1 in account: %s\" %\n self.account.name)\n try:\n self.vm_1.recover(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Stopped',\n \"VM state should be stopped\"\n )\n\n except Exception as e:\n self.fail(\"Failed to recover the virtual instances, %s\" % e)\n\n try:\n self.vm_2.delete(self.apiclient, expunge=False)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Destroyed',\n \"VM state should be destroyed\"\n )\n\n except Exception as e:\n self.fail(\"Failed to stop the virtual instances, %s\" % e)\n\n self.debug(\"Recovering the expunged virtual machine vm2 in account: %s\" %\n self.account.name)\n try:\n self.vm_2.recover(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Stopped',\n \"VM state should be stopped\"\n )\n except Exception as e:\n self.fail(\"Failed to recover the virtual instances, %s\" % e)\n\n self.debug(\"Starting the two instances..\")\n try:\n self.vm_1.start(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Running',\n \"VM state should be running\"\n )\n\n self.vm_2.start(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Running',\n \"VM state should be running\"\n )\n except Exception as e:\n self.fail(\"Failed to start the instances, %s\" % e)\n\n # Wait until vms are up\n time.sleep(120)\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n return",
"def test_05_destroy_instance_in_network(self):\n\n # Validate the following\n # 1. Destory the virtual machines.\n # 2. Rules should be still configured on virtual router.\n # 3. Recover the virtual machines.\n # 4. Vm should be in stopped state. State both the instances\n # 5. Make sure that all the PF,LB and Static NAT rules on this VM\n # works as expected.\n # 6. Make sure that we are able to access google.com from this user Vm\n\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n self.debug(\"Destroying the virtual machines in account: %s\" %\n self.account.name)\n try:\n self.vm_1.delete(self.apiclient, expunge=False)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Destroyed',\n \"VM state should be destroyed\"\n )\n\n except Exception as e:\n self.fail(\"Failed to stop the virtual instances, %s\" % e)\n\n # Check if the network rules still exists after Vm stop\n self.debug(\"Checking if NAT rules \")\n nat_rules = NATRule.list(\n self.apiclient,\n id=self.nat_rule.id,\n listall=True\n )\n self.assertEqual(\n isinstance(nat_rules, list),\n True,\n \"List NAT rules shall return a valid list\"\n )\n\n lb_rules = LoadBalancerRule.list(\n self.apiclient,\n id=self.lb_rule.id,\n listall=True\n )\n self.assertEqual(\n isinstance(lb_rules, list),\n True,\n \"List LB rules shall return a valid list\"\n )\n\n self.debug(\"Recovering the expunged virtual machine vm1 in account: %s\" %\n self.account.name)\n try:\n self.vm_1.recover(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Stopped',\n \"VM state should be stopped\"\n )\n\n except Exception as e:\n self.fail(\"Failed to recover the virtual instances, %s\" % e)\n\n try:\n self.vm_2.delete(self.apiclient, expunge=False)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Destroyed',\n \"VM state should be destroyed\"\n )\n\n\n\n\n except Exception as e:\n self.fail(\"Failed to stop the virtual instances, %s\" % e)\n\n self.debug(\"Recovering the expunged virtual machine vm2 in account: %s\" %\n self.account.name)\n try:\n self.vm_2.recover(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Stopped',\n \"VM state should be stopped\"\n )\n except Exception as e:\n self.fail(\"Failed to recover the virtual instances, %s\" % e)\n\n self.debug(\"Starting the two instances..\")\n try:\n self.vm_1.start(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_1.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Running',\n \"VM state should be running\"\n )\n\n self.vm_2.start(self.apiclient)\n\n list_vm_response = list_virtual_machines(\n self.apiclient,\n id=self.vm_2.id\n )\n\n vm_response = list_vm_response[0]\n\n self.assertEqual(\n vm_response.state,\n 'Running',\n \"VM state should be running\"\n )\n except Exception as e:\n self.fail(\"Failed to start the instances, %s\" % e)\n\n # Wait until vms are up\n time.sleep(120)\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n return",
"def detach_outdated_instances(session):\n logging.info(\"Detaching old instances\")\n detached_instances = []\n\n for asg_name in session.asgs:\n\n asg_info = session.clients[\"autoscaling\"].describe_auto_scaling_groups(\n AutoScalingGroupNames=[asg_name], MaxRecords=100\n )\n instance_ids = [\n instance[\"InstanceId\"]\n for instance in asg_info[\"AutoScalingGroups\"][0][\"Instances\"]\n ]\n\n # detach_instances can only handle max 20 instances in a call\n def chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i : i + n]\n\n id_groups = list(chunks(instance_ids, 20))\n\n for group in id_groups:\n response = session.clients[\"autoscaling\"].detach_instances(\n InstanceIds=group,\n AutoScalingGroupName=asg_name,\n ShouldDecrementDesiredCapacity=False,\n )\n # Getting instance id from description\n for item in response[\"Activities\"]:\n if item[\"Description\"].startswith(\"Detaching\"):\n detached_instances.append(item[\"Description\"].split(\" \")[-1])\n\n return set(detached_instances)",
"def undeploy_system_instance(id=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Detaches an Internet gateway from a VPC, disabling connectivity between the Internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses.
|
def detach_internet_gateway(DryRun=None, InternetGatewayId=None, VpcId=None):
pass
|
[
"def delete_internet_gateways():\n print('Deleting Internet Gateways')\n client = boto3.resource('ec2')\n for igw in client.internet_gateways.all():\n for attachment in igw.attachments:\n if 'State' in attachment and attachment['State'] == 'available':\n vpc_id = attachment['VpcId']\n print('Detaching internet gateway {} from vpc {}'.format(igw.id, vpc_id))\n igw.detach_from_vpc(\n VpcId=vpc_id\n )\n print('Deleting Internet Gateway {}'.format(igw.id))\n igw.delete()\n\n while [igw for igw in client.internet_gateways.all()]:\n time.sleep(5)\n print('Internet Gateways deleted')",
"def detach_vpn_gateway(DryRun=None, VpnGatewayId=None, VpcId=None):\n pass",
"def delete_virtual_gateways():\n client = boto3.client('ec2')\n print('Deleting VPN Gateways')\n gw_resp = client.describe_vpn_gateways()\n while True:\n for gateway in gw_resp['VpnGateways']:\n gw_id = gateway['VpnGatewayId']\n gw_attachments = gateway['VpcAttachments']\n for attachment in gw_attachments:\n if attachment['State'] == 'attached':\n vpc_id = attachment['VpcId']\n print('Detaching virtual gateway {} from vpc {}'.format(gw_id, vpc_id))\n client.detach_vpn_gateway(\n VpcId=vpc_id,\n VpnGatewayId=gw_id\n )\n print('Deleting VPN gateway {}'.format(gw_id))\n client.delete_vpn_gateway(\n VpnGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_vpn_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_vpn_gateways()['VpnGateways']:\n all_deleted = True\n for gateway in client.describe_vpn_gateways()['VpnGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n print('VPN Gateways deleted')",
"def delete_egress_only_internet_gateways():\n client = boto3.client('ec2')\n print('Deleting Egress Only Internet Gateways')\n gw_resp = client.describe_egress_only_internet_gateways()\n while True:\n for gateway in gw_resp['EgressOnlyInternetGateways']:\n gw_id = gateway['EgressOnlyInternetGatewayId']\n client.delete_egress_only_internet_gateway(\n EgressOnlyInternetGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_egress_only_internet_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_egress_only_internet_gateways()['EgressOnlyInternetGateways']:\n time.sleep(5)\n print('Egress Only Internet Gateways deleted')",
"def __unexpose_machine(self, machine_id):\n # We need to access the edge device that the machine is connected to the internet via\n # To do this, we first get the machine details, then the vdc details\n app = ET.fromstring(self.api_request('GET', 'vApp/{}'.format(machine_id)).text)\n gateway = self.__gateway_from_app(app)\n if gateway is None:\n raise BadConfigurationError('Could not find edge gateway')\n # Find our internal IP address\n internal_ip = self.__internal_ip_from_app(app)\n if internal_ip is None:\n return\n # Get the current edge gateway configuration\n # If none exists, there aren't any NAT rules\n gateway_config = gateway.find('.//vcd:EdgeGatewayServiceConfiguration', _NS)\n if gateway_config is None:\n return\n # Get the NAT service section\n # If there is no NAT service section, there aren't any NAT rules\n nat_service = gateway_config.find('vcd:NatService', _NS)\n if nat_service is None:\n return\n # Remove any NAT rules from the service that apply specifically to our internal IP\n # As we go, we save the mapped external ip in order to remove firewall rules after\n nat_rules = nat_service.findall('vcd:NatRule', _NS)\n external_ip = None\n for rule in nat_rules:\n rule_type = rule.find('vcd:RuleType', _NS).text.upper()\n if rule_type == 'SNAT':\n # For SNAT rules, we check the original ip\n # The default SNAT rule has a /24 network, so we need to catch the AddressValueError\n try:\n original = IPv4Address(rule.find('.//vcd:OriginalIp', _NS).text)\n if original == internal_ip:\n nat_service.remove(rule)\n # The external IP is the translated ip, and should NEVER be a network\n external_ip = IPv4Address(rule.find('.//vcd:TranslatedIp', _NS).text)\n except AddressValueError:\n # We should only get to here if original ip is a network, which we ignore\n pass\n elif rule_type == 'DNAT':\n # For DNAT rules, we check the translated ip, which should NEVER be a network\n translated = IPv4Address(rule.find('.//vcd:TranslatedIp', _NS).text)\n if translated == internal_ip:\n nat_service.remove(rule)\n # The external ip is the original ip\n external_ip = IPv4Address(rule.find('.//vcd:OriginalIp', _NS).text)\n # If we didn't find an external ip, the machine must not be exposed\n if external_ip is None:\n return\n # Remove any firewall rules (inbound or outbound) that apply specifically to the ip\n firewall = gateway_config.find('vcd:FirewallService', _NS)\n if firewall is None:\n # If we get to here, we would expect a firewall config to exist\n raise BadConfigurationError('No firewall configuration defined')\n firewall_rules = firewall.findall('vcd:FirewallRule', _NS)\n for rule in firewall_rules:\n # Try the source and destination ips independently\n # We ignore AddressValueErrors, since the ip couldn't possibly match\n try:\n source_ip = IPv4Address(rule.find('vcd:SourceIp', _NS).text)\n if source_ip == external_ip:\n firewall.remove(rule)\n except AddressValueError:\n pass\n try:\n dest_ip = IPv4Address(rule.find('vcd:DestinationIp', _NS).text)\n if dest_ip == external_ip:\n firewall.remove(rule)\n except AddressValueError:\n pass\n # Make the changes\n edit_url = '{}/action/configureServices'.format(gateway.attrib['href'])\n task = ET.fromstring(self.api_request(\n 'POST', edit_url, ET.tostring(gateway_config),\n headers = { 'Content-Type' : 'application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml' }\n ).text)\n try:\n self.wait_for_task(task.attrib['href'])\n except TaskFailedError as e:\n raise NetworkingError('{} while applying network configuration'.format(e)) from e",
"def unisolate(self, timeout=None):\n self.network_isolation_enabled = False\n self.save()\n\n start_time = time.time()\n\n while self.is_isolating:\n if timeout and time.time() - start_time > timeout:\n raise TimeoutError(message=\"timed out waiting for isolation to be removed\")\n time.sleep(1)\n self.refresh()\n\n return True",
"def delete_internet_gateway(\n internet_gateway_id=None,\n internet_gateway_name=None,\n detach=False,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n try:\n if internet_gateway_name:\n internet_gateway_id = _get_resource_id(\n \"internet_gateway\",\n internet_gateway_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not internet_gateway_id:\n return {\n \"deleted\": False,\n \"error\": {\n \"message\": \"internet gateway {} does not exist.\".format(\n internet_gateway_name\n )\n },\n }\n\n if detach:\n igw = _get_resource(\n \"internet_gateway\",\n resource_id=internet_gateway_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n\n if not igw:\n return {\n \"deleted\": False,\n \"error\": {\n \"message\": \"internet gateway {} does not exist.\".format(\n internet_gateway_id\n )\n },\n }\n\n if igw.attachments:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.detach_internet_gateway(\n internet_gateway_id, igw.attachments[0].vpc_id\n )\n return _delete_resource(\n \"internet_gateway\",\n resource_id=internet_gateway_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n except BotoServerError as e:\n return {\"deleted\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def delete_nat_gateways():\n print('Deleting NAT gateways')\n ec2 = boto3.client('ec2')\n for page in ec2.get_paginator('describe_nat_gateways').paginate():\n for nat_gateway in page['NatGateways']:\n nat_gateway_id = nat_gateway['NatGatewayId']\n print('Deleting Nat Gateway - {}'.format(nat_gateway_id))\n ec2.delete_nat_gateway(\n NatGatewayId=nat_gateway_id\n )\n\n while ec2.describe_nat_gateways()['NatGateways']:\n all_deleted = True\n for gateway in ec2.describe_nat_gateways()['NatGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n\n print('NAT gateways deleted')",
"def removeNetwork(conn):\n try:\n net = conn.networkLookupByName('vauto')\n except libvirt.libvirtError, e:\n logging.warn(\"Cannot find vauto network.\")\n return\n if net.isActive():\n net.destroy()\n if net.isPersistent():\n net.undefine()",
"def delGw(interface):\n logging.debugv(\"functions/linux.py->delGw(interface)\", [interface])\n logging.info(\"removing default gateway of device \" + interface)\n cmd = [\"ip\", \"route\", \"del\", \"default\", \"dev\", interface]\n runWrapper(cmd)",
"def delete_default_vpc(client, account_id, dry_run=False):\n # Check and remove default VPC\n default_vpc_id = None\n\n # Retrying the describe_vpcs call. Sometimes the VPC service is not ready when\n # you have just created a new account.\n max_retry_seconds = 180\n while True:\n try:\n vpc_response = client.describe_vpcs()\n break\n except Exception as e:\n logger.warning(f'Could not retrieve VPCs: {e}. Sleeping for 1 second before trying again.')\n max_retry_seconds - 2\n sleep(2)\n if max_retry_seconds <= 0:\n raise Exception(\"Could not describe VPCs within retry limit.\")\n\n for vpc in vpc_response[\"Vpcs\"]:\n if vpc[\"IsDefault\"] is True:\n default_vpc_id = vpc[\"VpcId\"]\n break\n\n if default_vpc_id is None:\n logging.info(f\"No default VPC found in account {account_id}\")\n return\n\n logging.info(f\"Found default VPC Id {default_vpc_id}\")\n subnet_response = client.describe_subnets()\n default_subnets = [\n subnet\n for subnet in subnet_response[\"Subnets\"]\n if subnet[\"VpcId\"] == default_vpc_id\n ]\n\n logging.info(f\"Deleting default {len(default_subnets )} subnets\")\n subnet_delete_response = [\n client.delete_subnet(SubnetId=subnet[\"SubnetId\"], DryRun=dry_run)\n for subnet in default_subnets\n ]\n\n igw_response = client.describe_internet_gateways()\n try:\n default_igw = [\n igw[\"InternetGatewayId\"]\n for igw in igw_response[\"InternetGateways\"]\n for attachment in igw[\"Attachments\"]\n if attachment[\"VpcId\"] == default_vpc_id\n ][0]\n except IndexError:\n default_igw = None\n\n if default_igw:\n logging.info(f\"Detaching Internet Gateway {default_igw}\")\n detach_default_igw_response = client.detach_internet_gateway(\n InternetGatewayId=default_igw, VpcId=default_vpc_id, DryRun=dry_run\n )\n\n logging.info(f\"Deleting Internet Gateway {default_igw}\")\n delete_internet_gateway_response = client.delete_internet_gateway(\n InternetGatewayId=default_igw\n )\n\n sleep(10) # It takes a bit of time for the dependencies to clear\n logging.info(f\"Deleting Default VPC {default_vpc_id}\")\n delete_vpc_response = client.delete_vpc(VpcId=default_vpc_id, DryRun=dry_run)\n\n return delete_vpc_response",
"def DisableWirelessInterface(self):\n result = self.wifi.DisableInterface()\n return result",
"def disable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'disable'])\n print(\"Disable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'disable'])\n print(\"Disable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" disable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" disable', None, 1)",
"def disable_vgw_route_propagation(RouteTableId=None, GatewayId=None):\n pass",
"def delete_vpc(DryRun=None, VpcId=None):\n pass",
"def disable(self, retain_port=False):\n pid = self.pid\n\n if self.active:\n cmd = ['kill', '-9', pid]\n if self.namespace:\n ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)\n ip_wrapper.netns.execute(cmd)\n else:\n utils.execute(cmd, self.root_helper)\n\n if not retain_port:\n self.device_delegate.destroy(self.network, self.interface_name)\n\n elif pid:\n LOG.debug(_('DHCP for %s pid %d is stale, ignoring command') %\n (self.network.id, pid))\n else:\n LOG.debug(_('No DHCP started for %s') % self.network.id)",
"def delete_vpn_gateway(DryRun=None, VpnGatewayId=None):\n pass",
"def DisconnectWireless(self):\n self.wifi.Disconnect()\n self.daemon.UpdateState()",
"def DisassociateDirectConnectGatewayNatGateway(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateDirectConnectGatewayNatGateway\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateDirectConnectGatewayNatGatewayResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. For more information, see Detaching an Amazon EBS Volume in the Amazon Elastic Compute Cloud User Guide .
|
def detach_volume(DryRun=None, VolumeId=None, InstanceId=None, Device=None, Force=None):
pass
|
[
"def detach_volume(self, instance_name, mountpoint):\n\n # Find the instance ref so we can pass it to the\n # _container_script_modify method.\n meta = self._find_by_name(instance_name)\n instance = db.instance_get(context.get_admin_context(), meta['id'])\n self._container_script_modify(instance, None, None, mountpoint, 'del')",
"def detach_volume(self, node, volume):\r\n url = REST_BASE + '/instances/%s' % (node.id)\r\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\r\n data = {'storageID': volume.id, 'type': 'detach'}\r\n resp = self.connection.request(action=url,\r\n method='PUT',\r\n headers=headers,\r\n data=data)\r\n return int(resp.status) == 200",
"def detach(self, args):\n parser = OptionParser(usage=\"volume detach <options>\")\n parser.add_option(\"-n\", \"--name\", dest=\"name\",\n help=\"The name of the volume to detach\")\n (options, args) = parser.parse_args(args)\n if not options.name:\n parser.print_help()\n return\n\n try:\n volume = helper.find_volume(self._context, options.name)\n if not volume:\n print \"No volume found with name: %s\" % options.name\n return\n\n vm = helper.get_attached_vm(self._context, volume)\n if not vm:\n print (\"Volume %s is not attached \"\n \"to any virtual machine\") % options.name\n return\n\n log.debug(\"Detaching volume %s from %s...\" % (options.name,\n vm.getInternalName()))\n if vm.getState().existsInHypervisor():\n print \"Detaching volume from a running virtual machine.\",\n print \"This may take some time...\"\n\n disks = [disk for disk in vm.listVirtualDisks()\n if disk.getId() != volume.getId()]\n vm.setVirtualDisks(disks)\n\n pprint_volumes([helper.refresh_volume(self._context, volume)])\n except (AbiquoException, AuthorizationException), ex:\n print \"Error: %s\" % ex.getMessage()",
"def detach(self, volume):\r\n return volume.detach()",
"def detach_volume(self, instance_obj, volume_obj):\n # Get the session id\n sid = None\n cmd = ['iscsiadm', '-m', 'session']\n stdout, _ = processutils.execute(*cmd)\n iqn = None\n if instance_obj.custom_iqn:\n iqn = instance_obj.custom_iqn\n else:\n iqn = instance_obj.uuid\n\n for line in stdout.split('\\n'):\n if iqn in line:\n sid = line.split()[1][1]\n if not sid:\n raise exception.IscsiSessionIdNotFound(\n volume_uuid=volume_obj.uuid, output=stdout)\n\n # Get lun info\n host_num = ''\n device_scsi = ''\n device_name = ''\n\n cmd = ['iscsiadm', '-m', 'session', '--sid', sid, '-P', '3']\n stdout, _ = processutils.execute(*cmd)\n # Use the flag to tag find the lun dev\n flag = False\n for line in stdout.split('\\n'):\n # Construct device scsi id, example: '11:0:0:3'\n if 'Host Number' in line:\n host_num = line.split()[2]\n elif 'Lun: {}'.format(volume_obj.device_id) in line:\n s = line.split()\n device_scsi = '{h}:{c}:{t}:{l}'.format(\n h=int(host_num),\n c=int(s[2]),\n t=int(s[4]),\n l=int(s[6]))\n flag = True\n continue\n # Get device name, example: 'sdc'\n if flag:\n s = line.split()\n device_name = s[3]\n break\n\n if not device_name or not device_scsi:\n msg = 'failed to find iscsi device, {volume_uuid}: {device_id}, skip detach device'.format(\n volume_uuid=volume_obj.uuid, device_id=volume_obj.device_id)\n LOG.warning(msg)\n return\n\n # Make sure the device_name and device_scsi are same device\n block_path = ('/sys/class/scsi_device/{device_scsi}/'\n 'device/block/').format(device_scsi=device_scsi)\n if device_name not in os.listdir(block_path):\n raise exception.IscsiDeviceNotMatch(\n volume_uuid=volume_obj.uuid,\n device_id=volume_obj.device_id,\n device_name=device_name)\n\n delete_path = ('/sys/class/scsi_device/{device_scsi}/'\n 'device/delete').format(device_scsi=device_scsi)\n cmd = 'echo 1 > {path}'.format(path=delete_path)\n processutils.execute(cmd, shell=True)",
"def delete_ec2_volume(name, timeout=600):\n def _force_detach_volume(volume):\n log.info(\"Force detaching all volume attachments.\")\n for attachment in volume.attachments:\n try:\n log.info(\"Volume has attachment: {}\".format(attachment))\n log.info(\"Detaching volume from instance: {}\".format(attachment['InstanceId']))\n volume.detach_from_instance(\n DryRun=False,\n InstanceId=attachment['InstanceId'],\n Device=attachment['Device'],\n Force=True)\n except exceptions.ClientError as exc:\n log.exception(\"Failed to detach volume\")\n # See the following link for the structure of the exception:\n # https://github.com/boto/botocore/blob/4d4c86b2bdd4b7a8e110e02abd4367f07137ca47/botocore/exceptions.py#L346\n err_message = exc.response['Error']['Message']\n err_code = exc.response['Error']['Code']\n # See the following link for details of the error message:\n # https://jira.mesosphere.com/browse/DCOS-37441?focusedCommentId=156163&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-156163\n available_msg = \"is in the 'available' state\"\n if err_code == 'IncorrectState' and available_msg in err_message:\n log.info(\"Ignoring benign exception\")\n return\n raise\n\n @retrying.retry(wait_fixed=30 * 1000, stop_max_delay=timeout * 1000,\n retry_on_exception=lambda exc: isinstance(exc, exceptions.ClientError))\n def _delete_volume(volume):\n log.info(\"Trying to delete volume...\")\n _force_detach_volume(volume)\n try:\n log.info(\"Issuing volume.delete()\")\n volume.delete() # Raises ClientError (VolumeInUse) if the volume is still attached.\n except exceptions.ClientError:\n log.exception(\"volume.delete() failed.\")\n raise\n\n def _get_current_aws_region():\n try:\n return requests.get('http://169.254.169.254/latest/meta-data/placement/availability-zone').text.strip()[:-1]\n except requests.RequestException as ex:\n print(\"Can't get AWS region from instance metadata: {}\".format(ex))\n return None\n\n # Remove AWS environment variables to force boto to use IAM credentials.\n with _remove_env_vars('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'):\n volumes = list(boto3.session.Session(\n # We assume we're running these tests from a cluster node, so we\n # can assume the region for the instance on which we're running is\n # the same region in which any volumes were created.\n region_name=_get_current_aws_region(),\n ).resource('ec2').volumes.filter(Filters=[{'Name': 'tag:Name', 'Values': [name]}]))\n\n if len(volumes) == 0:\n raise Exception('no volumes found with name {}'.format(name))\n elif len(volumes) > 1:\n raise Exception('multiple volumes found with name {}'.format(name))\n volume = volumes[0]\n log.info(\"Found volume {}\".format(volume))\n\n try:\n _delete_volume(volume)\n except retrying.RetryError as ex:\n raise Exception('Operation was not completed within {} seconds'.format(timeout)) from ex",
"def Detach(self):\n detach_cmd = [FLAGS.gcloud_path,\n 'compute',\n 'instances',\n 'detach-disk',\n self.attached_vm_name,\n '--device-name', self.name]\n detach_cmd.extend(util.GetDefaultGcloudFlags(self))\n vm_util.IssueRetryableCommand(detach_cmd)\n self.attached_vm_name = None",
"def get_detach_cdrom_to_instance_from_image_param(version=openapi_version.V2):\n if version == openapi_version.V3:\n pass\n else:\n body = {\n \"cdrom-detach\":\"null\"\n }\n return body",
"def do_destroy_volume(sess, ocid):\n _logger.debug(\"Destroying volume [%s]\", ocid)\n try:\n vol = sess.get_volume(ocid)\n except Exception as e:\n _logger.debug(\"Failed to retrieve Volume details\", exc_info=True)\n raise Exception(\"Failed to retrieve Volume details: %s\" % ocid) from e\n\n if vol is None:\n raise Exception(\"Volume not found: %s\" % ocid)\n\n if vol.is_attached():\n raise Exception(\"Cannot destroy an attached volume\")\n\n try:\n _logger.debug('destroying volume %s:%s', vol.get_display_name(), vol.get_ocid())\n vol.destroy()\n except Exception as e:\n _logger.debug(\"Failed to destroy volume %s\", ocid, exc_info=True)\n raise Exception(\"Failed to destroy volume\") from e",
"def detach(client, attachment_id, volume_id, host, conn, connection_info,\n device):\n\n with __manager__.get_state() as attach_state:\n attach_state.detach(client, attachment_id, volume_id, host, conn,\n connection_info, device)",
"def detach_and_delete_vols(self, volumes):\n for v in volumes:\n if v.status == \"in-use\":\n v.detach()\n v.get()\n sample = TimeoutSampler(\n 100,\n 5,\n self.check_expected_vol_status,\n vol=v,\n expected_state=\"available\",\n )\n if not sample.wait_for_func_status(True):\n logger.error(f\"Volume {v.name} failed to detach\")\n raise exceptions.PSIVolumeNotInExpectedState()\n\n v.delete()\n sample = TimeoutSampler(100, 5, self.check_vol_deleted, vol=v)\n if not sample.wait_for_func_status(True):\n logger.error(f\"Failed to delete Volume {v.name}\")\n raise exceptions.PSIVolumeDeletionFailed()",
"def delete_ebs_volumes():\n client = boto3.client('ec2')\n\n print('Deleting EBS volumes')\n volumes_resp = client.describe_volumes(\n MaxResults=500\n )\n while True:\n for vol in volumes_resp['Volumes']:\n volume_id = vol['VolumeId']\n print('Deleting Volume {}'.format(volume_id))\n client.delete_volume(\n VolumeId=volume_id\n )\n time.sleep(0.25) # REST API is throttled\n if 'NextMarker' in volumes_resp:\n volumes_resp = client.describe_volumes(\n Marker=volumes_resp['NextMarker'],\n MaxResults=500\n )\n else:\n break\n\n while client.describe_volumes()['Volumes']:\n time.sleep(5)\n print('EBS volumes deleted')\n\n print('Deleting EBS snapshots')\n for page in client.get_paginator('describe_snapshots').paginate(\n OwnerIds=[get_account_id()]\n ):\n for snapshot in page['Snapshots']:\n snapshot_id = snapshot['SnapshotId']\n print('Deleting EBS snapshot {}'.format(snapshot_id))\n client.delete_snapshot(\n SnapshotId=snapshot_id,\n )\n while client.describe_snapshots(\n OwnerIds=[get_account_id()]\n )['Snapshots']:\n time.sleep(5)\n\n print('EBS snapshots deleted')",
"def test007_detach_boot_disks(self):\n self.lg('%s STARTED' % self._testID)\n\n self.lg('Create virtual machines (VM1)')\n machine_id = self.cloudapi_create_machine(cloudspace_id=self.cloudspace_id)\n\n self.lg('Stop VM1, should succeed')\n self.api.cloudapi.machines.stop(machineId=machine_id)\n self.assertEqual(self.api.cloudapi.machines.get(machineId=machine_id)['status'], 'HALTED')\n\n self.lg(\"Detach VM1's boot disk, should fail\")\n disk_id = self.api.cloudapi.machines.get(machineId=machine_id)['disks'][0]['id']\n\n with self.assertRaises(HTTPError) as e:\n self.api.cloudapi.machines.detachDisk(machineId=machine_id, diskId=disk_id)\n\n self.assertTrue(e.exception.status_code, 400)\n\n self.lg('%s ENDED' % self._testID)",
"def do_detach_vnic(detach_options, vnic_utils):\n\n sess = get_oci_api_session()\n if sess is None:\n raise Exception(\"Failed to get API session.\")\n vnics = sess.this_instance().all_vnics()\n for vnic in vnics:\n if vnic.get_ocid() == detach_options.ocid or \\\n vnic.get_private_ip() == detach_options.ip_address:\n if not vnic.is_primary():\n vnic_utils.delete_all_private_ips(vnic.get_ocid())\n vnic.detach()\n break\n raise Exception(\"The primary VNIC cannot be detached.\")",
"def volume_destroy(self, name, force=None, unmount_and_offline=None):\n return self.request( \"volume-destroy\", {\n 'force': [ force, 'force', [ bool, 'None' ], False ],\n 'name': [ name, 'name', [ basestring, 'None' ], False ],\n 'unmount_and_offline': [ unmount_and_offline, 'unmount-and-offline', [ bool, 'None' ], False ],\n }, {\n } )",
"def vm_ejectiso(vmname: str):\n subprocess.run(\"virsh --connect qemu:///system change-media {0} sda --eject --config\".format(vmname), shell=True, check=False)",
"def shutdown_lvm(device):\n device = block.sys_block_path(device)\n # lvm devices have a dm directory that containes a file 'name' containing\n # '{volume group}-{logical volume}'. The volume can be freed using lvremove\n name_file = os.path.join(device, 'dm', 'name')\n (vg_name, lv_name) = lvm.split_lvm_name(util.load_file(name_file))\n # use two --force flags here in case the volume group that this lv is\n # attached two has been damaged\n LOG.debug('running lvremove on %s/%s', vg_name, lv_name)\n util.subp(['lvremove', '--force', '--force',\n '{}/{}'.format(vg_name, lv_name)], rcs=[0, 5])\n # if that was the last lvol in the volgroup, get rid of volgroup\n if len(lvm.get_lvols_in_volgroup(vg_name)) == 0:\n util.subp(['vgremove', '--force', '--force', vg_name], rcs=[0, 5])\n # refresh lvmetad\n lvm.lvm_scan()",
"def test_delete_volume(self):\n self._driver.create_volume(self.TEST_VOLUME)\n self._driver.delete_volume(self.TEST_VOLUME)\n self.assertFalse(os.path.isfile(self.TEST_VOLPATH))",
"def attachment_delete(self,\n context: context.RequestContext,\n attachment_id: str,\n vref: objects.Volume) -> None:\n volume_utils.require_driver_initialized(self.driver)\n attachment = objects.VolumeAttachment.get_by_id(context, attachment_id)\n\n self._notify_about_volume_usage(context, vref, \"detach.start\")\n has_shared_connection = self._connection_terminate(context,\n vref,\n attachment)\n try:\n LOG.debug('Deleting attachment %(attachment_id)s.',\n {'attachment_id': attachment.id},\n resource=vref)\n if has_shared_connection is not None and not has_shared_connection:\n self.driver.remove_export(context.elevated(), vref)\n except Exception as exc:\n # Failures on detach_volume and remove_export are not considered\n # failures in terms of detaching the volume.\n LOG.warning('Failed to detach volume on the backend, ignoring '\n 'failure %s', exc)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Detaches a virtual private gateway from a VPC. You do this if you're planning to turn off the VPC and not use it anymore. You can confirm a virtual private gateway has been completely detached from a VPC by describing the virtual private gateway (any attachments to the virtual private gateway are also described). You must wait for the attachment's state to switch to detached before you can delete the VPC or attach a different VPC to the virtual private gateway.
|
def detach_vpn_gateway(DryRun=None, VpnGatewayId=None, VpcId=None):
pass
|
[
"def Detach(self):\n detach_cmd = [FLAGS.gcloud_path,\n 'compute',\n 'instances',\n 'detach-disk',\n self.attached_vm_name,\n '--device-name', self.name]\n detach_cmd.extend(util.GetDefaultGcloudFlags(self))\n vm_util.IssueRetryableCommand(detach_cmd)\n self.attached_vm_name = None",
"def do_detach_vnic(detach_options, vnic_utils):\n\n sess = get_oci_api_session()\n if sess is None:\n raise Exception(\"Failed to get API session.\")\n vnics = sess.this_instance().all_vnics()\n for vnic in vnics:\n if vnic.get_ocid() == detach_options.ocid or \\\n vnic.get_private_ip() == detach_options.ip_address:\n if not vnic.is_primary():\n vnic_utils.delete_all_private_ips(vnic.get_ocid())\n vnic.detach()\n break\n raise Exception(\"The primary VNIC cannot be detached.\")",
"def delete_virtual_gateways():\n client = boto3.client('ec2')\n print('Deleting VPN Gateways')\n gw_resp = client.describe_vpn_gateways()\n while True:\n for gateway in gw_resp['VpnGateways']:\n gw_id = gateway['VpnGatewayId']\n gw_attachments = gateway['VpcAttachments']\n for attachment in gw_attachments:\n if attachment['State'] == 'attached':\n vpc_id = attachment['VpcId']\n print('Detaching virtual gateway {} from vpc {}'.format(gw_id, vpc_id))\n client.detach_vpn_gateway(\n VpcId=vpc_id,\n VpnGatewayId=gw_id\n )\n print('Deleting VPN gateway {}'.format(gw_id))\n client.delete_vpn_gateway(\n VpnGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_vpn_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_vpn_gateways()['VpnGateways']:\n all_deleted = True\n for gateway in client.describe_vpn_gateways()['VpnGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n print('VPN Gateways deleted')",
"def delete_vpc(DryRun=None, VpcId=None):\n pass",
"def delete_ec2_volume(name, timeout=600):\n def _force_detach_volume(volume):\n log.info(\"Force detaching all volume attachments.\")\n for attachment in volume.attachments:\n try:\n log.info(\"Volume has attachment: {}\".format(attachment))\n log.info(\"Detaching volume from instance: {}\".format(attachment['InstanceId']))\n volume.detach_from_instance(\n DryRun=False,\n InstanceId=attachment['InstanceId'],\n Device=attachment['Device'],\n Force=True)\n except exceptions.ClientError as exc:\n log.exception(\"Failed to detach volume\")\n # See the following link for the structure of the exception:\n # https://github.com/boto/botocore/blob/4d4c86b2bdd4b7a8e110e02abd4367f07137ca47/botocore/exceptions.py#L346\n err_message = exc.response['Error']['Message']\n err_code = exc.response['Error']['Code']\n # See the following link for details of the error message:\n # https://jira.mesosphere.com/browse/DCOS-37441?focusedCommentId=156163&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-156163\n available_msg = \"is in the 'available' state\"\n if err_code == 'IncorrectState' and available_msg in err_message:\n log.info(\"Ignoring benign exception\")\n return\n raise\n\n @retrying.retry(wait_fixed=30 * 1000, stop_max_delay=timeout * 1000,\n retry_on_exception=lambda exc: isinstance(exc, exceptions.ClientError))\n def _delete_volume(volume):\n log.info(\"Trying to delete volume...\")\n _force_detach_volume(volume)\n try:\n log.info(\"Issuing volume.delete()\")\n volume.delete() # Raises ClientError (VolumeInUse) if the volume is still attached.\n except exceptions.ClientError:\n log.exception(\"volume.delete() failed.\")\n raise\n\n def _get_current_aws_region():\n try:\n return requests.get('http://169.254.169.254/latest/meta-data/placement/availability-zone').text.strip()[:-1]\n except requests.RequestException as ex:\n print(\"Can't get AWS region from instance metadata: {}\".format(ex))\n return None\n\n # Remove AWS environment variables to force boto to use IAM credentials.\n with _remove_env_vars('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'):\n volumes = list(boto3.session.Session(\n # We assume we're running these tests from a cluster node, so we\n # can assume the region for the instance on which we're running is\n # the same region in which any volumes were created.\n region_name=_get_current_aws_region(),\n ).resource('ec2').volumes.filter(Filters=[{'Name': 'tag:Name', 'Values': [name]}]))\n\n if len(volumes) == 0:\n raise Exception('no volumes found with name {}'.format(name))\n elif len(volumes) > 1:\n raise Exception('multiple volumes found with name {}'.format(name))\n volume = volumes[0]\n log.info(\"Found volume {}\".format(volume))\n\n try:\n _delete_volume(volume)\n except retrying.RetryError as ex:\n raise Exception('Operation was not completed within {} seconds'.format(timeout)) from ex",
"def detach(client, attachment_id, volume_id, host, conn, connection_info,\n device):\n\n with __manager__.get_state() as attach_state:\n attach_state.detach(client, attachment_id, volume_id, host, conn,\n connection_info, device)",
"def virtdisk_DetachVirtualDisk(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"VirtualDiskHandle\", \"Flags\", \"ProviderSpecificFlags\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)",
"def deletevpc(vpc_choices):\n progressbar(\"Deleting VPC\")\n vpcname=vpc_choices['vpc'][0]\n try:\n ec2.delete_vpc(VpcId=str(vpcname))\n print(\"\\n \\n vpc \" +vpcname +\" has been deleted \\n \\n\")\n except botocore.exceptions.ClientError as e:\n coloredtext(\"There was an error while deleting vpc: \\n\\n\\n\")\n print(e)",
"def terminate_vm_on_network(tenant_name, vm_name, network_id):\n pdb.set_trace() \n tenant_credentials = get_tenant_nova_credentials(tenant_name)\n nova = nvclient.Client(**tenant_credentials)\n nova.quotas.delete(tenant_name)\n try:\n instance = nova.servers.find(name=vm_name)\n nova.servers.delete(instance.id)\n print \" * Instance terminated on network: \" + str(network_id)\n except Exception:\n print \" * Instance Not Found on network: \" + str(network_id)\n pass\n return True",
"def get_detach_cdrom_to_instance_from_image_param(version=openapi_version.V2):\n if version == openapi_version.V3:\n pass\n else:\n body = {\n \"cdrom-detach\":\"null\"\n }\n return body",
"def detach(self, args):\n parser = OptionParser(usage=\"volume detach <options>\")\n parser.add_option(\"-n\", \"--name\", dest=\"name\",\n help=\"The name of the volume to detach\")\n (options, args) = parser.parse_args(args)\n if not options.name:\n parser.print_help()\n return\n\n try:\n volume = helper.find_volume(self._context, options.name)\n if not volume:\n print \"No volume found with name: %s\" % options.name\n return\n\n vm = helper.get_attached_vm(self._context, volume)\n if not vm:\n print (\"Volume %s is not attached \"\n \"to any virtual machine\") % options.name\n return\n\n log.debug(\"Detaching volume %s from %s...\" % (options.name,\n vm.getInternalName()))\n if vm.getState().existsInHypervisor():\n print \"Detaching volume from a running virtual machine.\",\n print \"This may take some time...\"\n\n disks = [disk for disk in vm.listVirtualDisks()\n if disk.getId() != volume.getId()]\n vm.setVirtualDisks(disks)\n\n pprint_volumes([helper.refresh_volume(self._context, volume)])\n except (AbiquoException, AuthorizationException), ex:\n print \"Error: %s\" % ex.getMessage()",
"def attachment_delete(self,\n context: context.RequestContext,\n attachment_id: str,\n vref: objects.Volume) -> None:\n volume_utils.require_driver_initialized(self.driver)\n attachment = objects.VolumeAttachment.get_by_id(context, attachment_id)\n\n self._notify_about_volume_usage(context, vref, \"detach.start\")\n has_shared_connection = self._connection_terminate(context,\n vref,\n attachment)\n try:\n LOG.debug('Deleting attachment %(attachment_id)s.',\n {'attachment_id': attachment.id},\n resource=vref)\n if has_shared_connection is not None and not has_shared_connection:\n self.driver.remove_export(context.elevated(), vref)\n except Exception as exc:\n # Failures on detach_volume and remove_export are not considered\n # failures in terms of detaching the volume.\n LOG.warning('Failed to detach volume on the backend, ignoring '\n 'failure %s', exc)",
"def stop_VM(self, host):\n # Stop the VM: the call to deallocate returns immediately, and then we\n # have to execute the returned instruction and wait for it to complete.\n # Note that we need to call deallocate and not power_off, since the\n # latter only stops the machine but continues charging for it.\n action = self.cmc.virtual_machines.deallocate(group_name(host), vm_name(host))\n action.wait()",
"def detach(self, volume):\r\n return volume.detach()",
"def detach_volume(DryRun=None, VolumeId=None, InstanceId=None, Device=None, Force=None):\n pass",
"def delete_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def detach(self, instance_id):\n if self.instance_id and self.instance_id == instance_id:\n return self.connection.detach_network_interface(network_interface_id=self.id, instance_id=instance_id)\n return False",
"def deleteVpg(self, vpgid, body): \n return requests.delete(self.zvmip + self.endPoint + '/' + vpgid, data=body, headers=self.headerwithkey, verify=False)",
"def delete_gwlbe(gwlbe_ids):\n logging.info(\"Deleting VPC Endpoint Service:\")\n try:\n response = ec2.delete_vpc_endpoints(\n VpcEndpointIds=gwlbe_ids\n )\n return response\n except ClientError as e:\n logging.error(e)\n return None"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disables a virtual private gateway (VGW) from propagating routes to a specified route table of a VPC.
|
def disable_vgw_route_propagation(RouteTableId=None, GatewayId=None):
pass
|
[
"def enable_vgw_route_propagation(RouteTableId=None, GatewayId=None):\n pass",
"def delete_virtual_gateways():\n client = boto3.client('ec2')\n print('Deleting VPN Gateways')\n gw_resp = client.describe_vpn_gateways()\n while True:\n for gateway in gw_resp['VpnGateways']:\n gw_id = gateway['VpnGatewayId']\n gw_attachments = gateway['VpcAttachments']\n for attachment in gw_attachments:\n if attachment['State'] == 'attached':\n vpc_id = attachment['VpcId']\n print('Detaching virtual gateway {} from vpc {}'.format(gw_id, vpc_id))\n client.detach_vpn_gateway(\n VpcId=vpc_id,\n VpnGatewayId=gw_id\n )\n print('Deleting VPN gateway {}'.format(gw_id))\n client.delete_vpn_gateway(\n VpnGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_vpn_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_vpn_gateways()['VpnGateways']:\n all_deleted = True\n for gateway in client.describe_vpn_gateways()['VpnGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n print('VPN Gateways deleted')",
"def configure_routing(vpc):\n internet_gateways = list(vpc.internet_gateways.all())\n if len(internet_gateways) == 1:\n internet_gateway = internet_gateways[0]\n elif len(internet_gateways) == 0:\n raise CraftingTableError(\"No internet gateway found\")\n else:\n raise CraftingTableError(f\"Multiple internet gateways found: {id_list(internet_gateways)}\")\n\n route_tables = list(vpc.route_tables.filter(Filters=[{\"Name\": \"association.main\", \"Values\": [\"true\"]}]))\n if len(route_tables) == 1:\n route_table = route_tables[0]\n elif len(route_tables) == 0:\n raise CraftingTableError(\"No route table found\")\n if len(route_tables) != 1:\n raise CraftingTableError(f\"Multiple route tables found: {id_list(route_tables)}\")\n\n for route in route_table.routes:\n if route.gateway_id == internet_gateway.id:\n break\n else:\n route_table.create_route(DestinationCidrBlock=\"0.0.0.0/0\", GatewayId=internet_gateway.id)\n click.echo(f\"Created default route to {internet_gateway.id}\")",
"def remove_default_gw(self):\n (retcode,routes) = run('ip route list table main dev {}'.format(self.device))\n if retcode == 0:\n if 'default ' in routes:\n print(run('ip route del default table main dev {}'.format(self.device),dry_run=self.dry_run))",
"def disassociate_route_table(DryRun=None, AssociationId=None):\n pass",
"def delete_egress_only_internet_gateways():\n client = boto3.client('ec2')\n print('Deleting Egress Only Internet Gateways')\n gw_resp = client.describe_egress_only_internet_gateways()\n while True:\n for gateway in gw_resp['EgressOnlyInternetGateways']:\n gw_id = gateway['EgressOnlyInternetGatewayId']\n client.delete_egress_only_internet_gateway(\n EgressOnlyInternetGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_egress_only_internet_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_egress_only_internet_gateways()['EgressOnlyInternetGateways']:\n time.sleep(5)\n print('Egress Only Internet Gateways deleted')",
"def detach_vpn_gateway(DryRun=None, VpnGatewayId=None, VpcId=None):\n pass",
"def delete_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def statement_deny_cost_explorer(self) -> Statement:\n return Statement(\n Action=[\n Action(\"account\", \"*\"),\n Action(\"aws-portal\", \"*\"),\n Action(\"ce\", \"*\"),\n Action(\"cur\", \"*\"),\n Action(\"savingsplans\", \"*\"),\n ],\n Effect=Deny,\n Resource=[\"*\"],\n Sid=\"DenyCostAndBilling\",\n )",
"def unblock_traffic(org: str, space: str, appname: str, configuration: Configuration) -> Dict[str, Any]:\n def f():\n if configuration.get('database'):\n # TODO: Implement reading from a DB what we last targeted\n assert False\n else:\n app = App(org, space, appname)\n app.find_hosts(configuration)\n\n app.unblock(configuration)\n return app\n\n return _run(f, \"Unblocking all traffic to {}...\".format(appname))",
"def disableTable(self, tableName):\n self.send_disableTable(tableName)\n self.recv_disableTable()",
"def delete_internet_gateways():\n print('Deleting Internet Gateways')\n client = boto3.resource('ec2')\n for igw in client.internet_gateways.all():\n for attachment in igw.attachments:\n if 'State' in attachment and attachment['State'] == 'available':\n vpc_id = attachment['VpcId']\n print('Detaching internet gateway {} from vpc {}'.format(igw.id, vpc_id))\n igw.detach_from_vpc(\n VpcId=vpc_id\n )\n print('Deleting Internet Gateway {}'.format(igw.id))\n igw.delete()\n\n while [igw for igw in client.internet_gateways.all()]:\n time.sleep(5)\n print('Internet Gateways deleted')",
"def delete_nat_gateways():\n print('Deleting NAT gateways')\n ec2 = boto3.client('ec2')\n for page in ec2.get_paginator('describe_nat_gateways').paginate():\n for nat_gateway in page['NatGateways']:\n nat_gateway_id = nat_gateway['NatGatewayId']\n print('Deleting Nat Gateway - {}'.format(nat_gateway_id))\n ec2.delete_nat_gateway(\n NatGatewayId=nat_gateway_id\n )\n\n while ec2.describe_nat_gateways()['NatGateways']:\n all_deleted = True\n for gateway in ec2.describe_nat_gateways()['NatGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n\n print('NAT gateways deleted')",
"def delGw(interface):\n logging.debugv(\"functions/linux.py->delGw(interface)\", [interface])\n logging.info(\"removing default gateway of device \" + interface)\n cmd = [\"ip\", \"route\", \"del\", \"default\", \"dev\", interface]\n runWrapper(cmd)",
"def delete_route(DryRun=None, RouteTableId=None, DestinationCidrBlock=None, DestinationIpv6CidrBlock=None):\n pass",
"def create_egress_only_internet_gateway(DryRun=None, VpcId=None, ClientToken=None):\n pass",
"def move_networks_off_controller_1():\n cmd = (\"UPDATE networkdhcpagentbindings SET dhcp_agent_id=\"\n \"(SELECT id FROM agents WHERE agent_type='DHCP agent'\"\n \" AND host='controller-0') WHERE dhcp_agent_id IN\"\n \" (SELECT id FROM agents WHERE agent_type='DHCP agent'\"\n \" AND host='controller-1') AND (SELECT count(id)\"\n \" FROM agents WHERE agent_type='DHCP agent'\"\n \" AND host='controller-0')=1;\")\n run_cmd_postgres(cmd)",
"def unblock_services(org: str, space: str, appname: str, configuration: Configuration, services=None) -> Dict[str, Any]:\n def f():\n app = App(org, space, appname)\n if configuration.get('database'):\n # TODO: Implement reading from a DB what we targeted\n assert False\n else:\n app.find_hosts(configuration)\n app.find_services(configuration)\n app.unblock_services(configuration, services=services)\n return app\n\n msg = \"Unblocking traffic to {} bound to {}...\".format(services, appname) if services \\\n else \"Unblocking traffic to all services bound to {}...\".format(appname)\n return _run(f, msg)",
"def delete_custom_route(self, purge_routes, vpc_id):\n params = {}\n results = []\n vrouter_table_id = None\n changed = False\n\n # Describe Vpc for getting VRouterId \n desc_vpc_param = {}\n self.build_list_params(desc_vpc_param, vpc_id, 'VpcId')\n desc_vpc_response = self.get_status('DescribeVpcs', desc_vpc_param)\n if int(desc_vpc_response[u'TotalCount']) > 0:\n vrouter_id = str(desc_vpc_response[u'Vpcs'][u'Vpc'][0][u'VRouterId']) \n \n # Describe Route Tables for getting RouteTable Id \n desc_route_table_param = {}\n self.build_list_params(desc_route_table_param, vrouter_id, 'VRouterId')\n desc_route_table_response = self.get_status('DescribeRouteTables', desc_route_table_param)\n if int(desc_route_table_response[u'TotalCount']) > 0:\n vrouter_table_id = str(desc_route_table_response[u'RouteTables'][u'RouteTable'][0][u'RouteTableId'])\n\n if 'route_table_id' in purge_routes:\n if 'next_hop_id' in purge_routes:\n if vrouter_table_id == purge_routes[\"route_table_id\"]: \n self.build_list_params(params, purge_routes[\"route_table_id\"], 'RouteTableId') \n fixed_dest_cidr_block = None\n if 'dest' in purge_routes:\n fixed_dest_cidr_block = purge_routes[\"dest\"]\n if 'destination_cidrblock' in purge_routes:\n fixed_dest_cidr_block = purge_routes[\"destination_cidrblock\"]\n if fixed_dest_cidr_block:\n self.build_list_params(params, fixed_dest_cidr_block, 'DestinationCidrBlock')\n \n self.build_list_params(params, purge_routes[\"next_hop_id\"], 'NextHopId')\n\n try:\n results = self.get_status('DeleteRouteEntry', params)\n changed = True\n except Exception as ex:\n error_code = ex.error_code\n error_msg = ex.message\n results.append({\"Error Code\": error_code, \"Error Message\": error_msg})\n else:\n changed = False\n results.append({ \"Error Message\": \"RouteTableId or VpcId does not exist\"})\n else:\n results.append({\"Error Message\": \"next_hop_id is required to delete route entry\"})\n else:\n results.append({\"Error Message\": \"route_table_id is required to delete route entry\"})\n\n return changed, results"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2Classic instances linked to it.
|
def disable_vpc_classic_link(DryRun=None, VpcId=None):
pass
|
[
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def disable_catalog_allow_links(self, catalog_id):\r\n\r\n logging.info(\"Disabling catalog links for catalog: '\"+catalog_id)\r\n\r\n #prepare patch data to be sent to mediasite\r\n patch_data = {\"AllowCatalogLinks\":\"False\"}\r\n\r\n #make the mediasite request using the catalog id and the patch data found above to enable downloads\r\n result = self.mediasite.api_client.request(\"patch\", \"Catalogs('\"+catalog_id+\"')/Settings\", \"\", patch_data)\r\n \r\n if self.mediasite.experienced_request_errors(result):\r\n return result\r\n else:\r\n return result",
"def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):\n pass",
"def disable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'disable'])\n print(\"Disable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'disable'])\n print(\"Disable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" disable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" disable', None, 1)",
"def vpc_classic_link_id(self) -> str:\n warnings.warn(\"\"\"With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\", DeprecationWarning)\n pulumi.log.warn(\"\"\"vpc_classic_link_id is deprecated: With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\")\n\n return pulumi.get(self, \"vpc_classic_link_id\")",
"def disable_module(address, name, module):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.disable_module(module)",
"def _disable_native_tag(self, interface):\n url = self._construct_url(interface, suffix='trunk/tag/native-vlan')\n self._make_request('DELETE', url, acceptable_error_codes=(404,))",
"def delete_classic_load_balancers():\n print('Deleting classic load balancers')\n elb = boto3.client('elb')\n\n for load_balancer in elb.describe_load_balancers()['LoadBalancerDescriptions']:\n lb_name = load_balancer['LoadBalancerName']\n print('Deleting LB - {}'.format(lb_name))\n\n elb.delete_load_balancer(\n LoadBalancerName=lb_name\n )\n\n while [lb for lb in elb.describe_load_balancers()['LoadBalancerDescriptions']]:\n time.sleep(5)\n\n print('Classic load balancers deleted')",
"def try_disable_insecure_reclaim():\n if is_leader():\n try:\n subprocess.check_call([\n 'ceph', '--id', 'admin',\n 'config', 'set', 'mon',\n 'auth_allow_insecure_global_id_reclaim', 'false'])\n except subprocess.CalledProcessError as e:\n log(\"Could not disable insecure reclaim: {}\".format(e),\n level='ERROR')",
"def delete_egress_only_internet_gateways():\n client = boto3.client('ec2')\n print('Deleting Egress Only Internet Gateways')\n gw_resp = client.describe_egress_only_internet_gateways()\n while True:\n for gateway in gw_resp['EgressOnlyInternetGateways']:\n gw_id = gateway['EgressOnlyInternetGatewayId']\n client.delete_egress_only_internet_gateway(\n EgressOnlyInternetGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_egress_only_internet_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_egress_only_internet_gateways()['EgressOnlyInternetGateways']:\n time.sleep(5)\n print('Egress Only Internet Gateways deleted')",
"def delete_default_vpc(client, account_id, dry_run=False):\n # Check and remove default VPC\n default_vpc_id = None\n\n # Retrying the describe_vpcs call. Sometimes the VPC service is not ready when\n # you have just created a new account.\n max_retry_seconds = 180\n while True:\n try:\n vpc_response = client.describe_vpcs()\n break\n except Exception as e:\n logger.warning(f'Could not retrieve VPCs: {e}. Sleeping for 1 second before trying again.')\n max_retry_seconds - 2\n sleep(2)\n if max_retry_seconds <= 0:\n raise Exception(\"Could not describe VPCs within retry limit.\")\n\n for vpc in vpc_response[\"Vpcs\"]:\n if vpc[\"IsDefault\"] is True:\n default_vpc_id = vpc[\"VpcId\"]\n break\n\n if default_vpc_id is None:\n logging.info(f\"No default VPC found in account {account_id}\")\n return\n\n logging.info(f\"Found default VPC Id {default_vpc_id}\")\n subnet_response = client.describe_subnets()\n default_subnets = [\n subnet\n for subnet in subnet_response[\"Subnets\"]\n if subnet[\"VpcId\"] == default_vpc_id\n ]\n\n logging.info(f\"Deleting default {len(default_subnets )} subnets\")\n subnet_delete_response = [\n client.delete_subnet(SubnetId=subnet[\"SubnetId\"], DryRun=dry_run)\n for subnet in default_subnets\n ]\n\n igw_response = client.describe_internet_gateways()\n try:\n default_igw = [\n igw[\"InternetGatewayId\"]\n for igw in igw_response[\"InternetGateways\"]\n for attachment in igw[\"Attachments\"]\n if attachment[\"VpcId\"] == default_vpc_id\n ][0]\n except IndexError:\n default_igw = None\n\n if default_igw:\n logging.info(f\"Detaching Internet Gateway {default_igw}\")\n detach_default_igw_response = client.detach_internet_gateway(\n InternetGatewayId=default_igw, VpcId=default_vpc_id, DryRun=dry_run\n )\n\n logging.info(f\"Deleting Internet Gateway {default_igw}\")\n delete_internet_gateway_response = client.delete_internet_gateway(\n InternetGatewayId=default_igw\n )\n\n sleep(10) # It takes a bit of time for the dependencies to clear\n logging.info(f\"Deleting Default VPC {default_vpc_id}\")\n delete_vpc_response = client.delete_vpc(VpcId=default_vpc_id, DryRun=dry_run)\n\n return delete_vpc_response",
"def reject_private_endpoint_connection(client, resource_group_name, account_name, private_endpoint_connection_name,\n description=None):\n\n return _update_private_endpoint_connection_status(\n client, resource_group_name, account_name, private_endpoint_connection_name, is_approved=False,\n description=description\n )",
"def vpc_classic_link_security_groups(self) -> Sequence[str]:\n warnings.warn(\"\"\"With the retirement of EC2-Classic the vpc_classic_link_security_groups attribute has been deprecated and will be removed in a future version.\"\"\", DeprecationWarning)\n pulumi.log.warn(\"\"\"vpc_classic_link_security_groups is deprecated: With the retirement of EC2-Classic the vpc_classic_link_security_groups attribute has been deprecated and will be removed in a future version.\"\"\")\n\n return pulumi.get(self, \"vpc_classic_link_security_groups\")",
"def disable_pairing(self):\n try:\n out = self.get_output(\"discoverable off\")\n out = self.get_output(\"pairable off\")\n\n except e:\n print(e)\n return None",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def enable_private_networking(self):\n return self.act_on_droplets(type='enable_private_networking')",
"def disable_backup(self):\r\n request_json = self._request_json_('Backup', False)\r\n\r\n flag, response = self._cvpysdk_object.make_request('POST', self._AGENT, request_json)\r\n\r\n if flag:\r\n if response.json() and 'response' in response.json():\r\n error_code = response.json()['response'][0]['errorCode']\r\n\r\n if error_code == 0:\r\n return\r\n elif 'errorString' in response.json()['response'][0]:\r\n error_message = response.json()['response'][0]['errorString']\r\n\r\n o_str = 'Failed to disable Backup\\nError: \"{0}\"'.format(error_message)\r\n raise SDKException('Agent', '102', o_str)\r\n else:\r\n raise SDKException('Response', '102')\r\n else:\r\n raise SDKException('Response', '101', self._update_response_(response.text))",
"def DisableWirelessInterface(self):\n result = self.wifi.DisableInterface()\n return result",
"def disable_secure_nat(self, hubname: str):\n return self._request_handler(json={\n \"jsonrpc\": \"2.0\",\n \"id\": \"rpc_call_id\",\n \"method\": \"DisableSecureNAT\",\n \"params\": {\n \"HubName_str\": hubname\n }\n })"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disables ClassicLink DNS support for a VPC. If disabled, DNS hostnames resolve to public IP addresses when addressed between a linked EC2Classic instance and instances in the VPC to which it's linked. For more information about ClassicLink, see ClassicLink in the Amazon Elastic Compute Cloud User Guide .
|
def disable_vpc_classic_link_dns_support(VpcId=None):
pass
|
[
"def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):\n pass",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def disable_public_ip_addresses(self) -> bool:\n return pulumi.get(self, \"disable_public_ip_addresses\")",
"def disable_secure_nat(self, hubname: str):\n return self._request_handler(json={\n \"jsonrpc\": \"2.0\",\n \"id\": \"rpc_call_id\",\n \"method\": \"DisableSecureNAT\",\n \"params\": {\n \"HubName_str\": hubname\n }\n })",
"def enableDHCPClick():\n os.system(\"mount -o rw,remount /\")\n os.system(\"cp netctl/ethernet-dhcp /etc/netctl/eth0\")\n os.system(\"mount -o ro,remount /\")\n lcdPrint(\"Obtaining IP...\")\n lcd.setCursor(15,0)\n lcd.ToggleBlink()\n os.system(\"ip link set eth0 down\")\n os.system(\"netctl restart eth0\")\n ip = socket.gethostbyname(socket.getfqdn())\n lcd.ToggleBlink()\n lcdPrint(\"Enabled DHCP:\\n\"+ip, 2)",
"def remove_dns_entries(name, app_type):\n try:\n aws_cfg\n except NameError:\n aws_cfg = load_aws_cfg()\n\n try:\n app_settings\n except NameError:\n app_settings = loadsettings(app_type)\n\n try:\n ec2host = open(\"fab_hosts/{}.txt\".format(name)).readline().strip() + \".\"\n except IOError:\n print _red(\"{name} is not reachable. either run fab getec2instances or fab create_ec2:{name} to create the instance\".format(name=name))\n return 1\n ec2ip = '.'.join(ec2host.split('.')[0].split('-')[1:5])\n app_zone_name = app_settings[\"DOMAIN_NAME\"] + \".\"\n\n print _green(\"Deleting DNS entries that point to \" + name + \"/\" + ec2host)\n conn = connect_to_r53()\n\n zone = conn.get_zone(app_zone_name)\n records = zone.get_records()\n\n for record in records:\n if (record.type == 'CNAME') and (record.to_print() == ec2host):\n print _yellow(\"...dropping cname \" + _green(record.name) + \"...\")\n zone.delete_cname(record.name)\n elif (record.type == 'A') and (record.to_print() == ec2ip):\n print _yellow(\"...dropping address record \" + _green(record.name) + \"...\")\n zone.delete_a(record.name)",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def disable_module(address, name, module):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.disable_module(module)",
"def test_08_VPC_Network_Restarts_With_InternalDns(self):\n\n # Validate the following\n # 1. Create a VPC and Tier network by using DNS network offering.\n # 2. Deploy vm1 in Tier network network1.\n # 3. Verify dhcp option 06 and 0f for subnet\n # 4. Verify dhcp option 06,15 and 0f for vm Interface.\n # 5. Deploy Vm2.\n # 6. Verify end to end by pinging with hostname while restarting\n # VPC and Tier without and with cleanup.\n\n cmd = updateZone.updateZoneCmd()\n cmd.id = self.zone.id\n cmd.domain = VPC_DOMAIN_NAME\n self.apiclient.updateZone(cmd)\n\n vpc_off = self.create_VpcOffering(self.dnsdata[\"vpc_offering\"])\n self.validate_VpcOffering(vpc_off, state=\"Enabled\")\n vpc = self.create_Vpc(vpc_off, cidr='10.1.0.0/16', cleanup=False)\n\n self.debug(\"Creating Nuage Vsp VPC Network offering...\")\n network_offering = self.create_NetworkOffering(\n self.dnsdata[\"vpc_network_offering\"])\n self.validate_NetworkOffering(network_offering, state=\"Enabled\")\n network_1 = self.create_Network(\n network_offering, gateway='10.1.1.1', vpc=vpc)\n\n vm_1 = self.create_VM(network_1)\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_vm(vm_1)\n # Internal DNS check point on VSD\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", network_1)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, network_1)\n for nic in vm_1.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm1\", nic, True)\n\n self.test_data[\"virtual_machine\"][\"displayname\"] = \"vm2\"\n self.test_data[\"virtual_machine\"][\"name\"] = \"vm2\"\n vm_2 = self.create_VM(network_1)\n self.test_data[\"virtual_machine\"][\"displayname\"] = \"vm1\"\n self.test_data[\"virtual_machine\"][\"name\"] = \"vm1\"\n self.verify_vsd_vm(vm_2)\n for nic in vm_2.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm2\", nic, True)\n\n public_ip_1 = self.acquire_PublicIPAddress(network_1, vpc)\n self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)\n # Adding Network ACL rule in the Public tier\n self.debug(\"Adding Network ACL rule to make the created NAT rule \"\n \"(SSH) accessible...\")\n public_ssh_rule = self.create_NetworkAclRule(\n self.test_data[\"ingress_rule\"], network=network_1)\n\n # VSD verification\n self.verify_vsd_firewall_rule(public_ssh_rule)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC network (cleanup = false)\n self.debug(\"Restarting the created VPC network without cleanup...\")\n Network.restart(network_1, self.api_client, cleanup=False)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n self.verify_vsd_vm(vm_2)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC network (cleanup = true)\n self.debug(\"Restarting the created VPC network with cleanup...\")\n Network.restart(network_1, self.api_client, cleanup=True)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n self.verify_vsd_vm(vm_2)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC (cleanup = false)\n self.debug(\"Restarting the VPC without cleanup...\")\n self.restart_Vpc(vpc, cleanup=False)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)\n\n # Restarting VPC (cleanup = true)\n self.debug(\"Restarting the VPC with cleanup...\")\n self.restart_Vpc(vpc, cleanup=True)\n self.validate_Network(network_1, state=\"Implemented\")\n vr = self.get_Router(network_1)\n self.check_Router_state(vr, state=\"Running\")\n self.check_VM_state(vm_1, state=\"Running\")\n self.check_VM_state(vm_2, state=\"Running\")\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_router(vr)\n self.verify_vsd_vm(vm_1)\n\n self.vm_verify_ping(vm_1, public_ip_1, vm_2, VPC_DOMAIN_NAME)",
"def ex_release_public_ip(self, address):\r\n return self.driver.ex_release_public_ip(self, address)",
"def test_06_VPC_Network_With_InternalDns(self):\n\n # Validate the following\n # 1. Create a VPC and tier network by using DNS network offering.\n # 2. Deploy vm1 in tier network.\n # 3. Verify dhcp option 06 and 0f for subnet\n # 4. Verify dhcp option 06,15 and 0f for vm Interface.\n cmd = updateZone.updateZoneCmd()\n cmd.id = self.zone.id\n cmd.domain = VPC_DOMAIN_NAME\n self.apiclient.updateZone(cmd)\n vpc_off = self.create_VpcOffering(self.dnsdata[\"vpc_offering\"])\n self.validate_VpcOffering(vpc_off, state=\"Enabled\")\n\n vpc = self.create_Vpc(vpc_off, cidr='10.1.0.0/16', cleanup=False)\n\n self.debug(\"Creating Nuage Vsp VPC Network offering...\")\n network_offering = self.create_NetworkOffering(\n self.dnsdata[\"vpc_network_offering\"])\n self.validate_NetworkOffering(network_offering, state=\"Enabled\")\n network_1 = self.create_Network(\n network_offering, gateway='10.1.1.1', vpc=vpc)\n\n vm_1 = self.create_VM(network_1)\n\n # VSD verification\n self.verify_vsd_network(self.domain.id, network_1, vpc)\n self.verify_vsd_vm(vm_1)\n\n # Internal DNS check point on VSD\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", network_1)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, network_1)\n for nic in vm_1.nic:\n self.verify_vsd_dhcp_option(self.DNS, \"10.1.1.2\", nic, True)\n self.verify_vsd_dhcp_option(self.DOMAINNAME, VPC_DOMAIN_NAME, nic, True)\n self.verify_vsd_dhcp_option(self.HOSTNAME, \"vm1\", nic, True)",
"def enable_private_networking(self):\n return self.act_on_droplets(type='enable_private_networking')",
"def noop_reachability( # pylint: disable=unused-argument\n address: Address, reachability: AddressReachability\n) -> None:",
"def set_protection_from_displayname(displayname, is_protected):\n\n asg = boto3.client('autoscaling')\n ec2 = boto3.client('ec2')\n hostname = displayname.rsplit('-', 1)[0] # Jenkins adds some string like `-23452345` to the hostname\n filters = [{\"Name\": \"private-dns-name\", \"Values\": [hostname]}]\n instance = ec2.describe_instances(Filters=filters)['Reservations'][0]['Instances'][0]\n id = instance['InstanceId']\n asg_name = [x for x in instance['Tags'] if x['Key'] == 'aws:autoscaling:groupName'][0]['Value']\n asg.set_instance_protection(InstanceIds=[id], AutoScalingGroupName=asg_name, ProtectedFromScaleIn=is_protected)",
"def restore_address_to_classic(DryRun=None, PublicIp=None):\n pass",
"def killAllDhcp():\n logging.debugv(\"functions/linux.py->killAllDhcp()\", [])\n cmd=[locations.KILLALL, '-q', locations.DHCLIENT]\n runWrapper(cmd, ignoreError=True)\n return True",
"def delete_egress_only_internet_gateways():\n client = boto3.client('ec2')\n print('Deleting Egress Only Internet Gateways')\n gw_resp = client.describe_egress_only_internet_gateways()\n while True:\n for gateway in gw_resp['EgressOnlyInternetGateways']:\n gw_id = gateway['EgressOnlyInternetGatewayId']\n client.delete_egress_only_internet_gateway(\n EgressOnlyInternetGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_egress_only_internet_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_egress_only_internet_gateways()['EgressOnlyInternetGateways']:\n time.sleep(5)\n print('Egress Only Internet Gateways deleted')",
"def enable_dhcp(self, ip_host_num):\n return [\"ip-host %s dhcp-enable true ping-response true traceroute-response true\" % ip_host_num]",
"def disable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'disable'])\n print(\"Disable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'disable'])\n print(\"Disable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" disable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" disable', None, 1)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disassociates an Elastic IP address from the instance or network interface it's associated with. An Elastic IP address is for use in either the EC2Classic platform or in a VPC. For more information, see Elastic IP Addresses in the Amazon Elastic Compute Cloud User Guide . This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error.
|
def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):
pass
|
[
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def delete_elastic_ips():\n client = boto3.client('ec2')\n print('Deleting Elastic IPs')\n for eip in client.describe_addresses()['Addresses']:\n allocation_id = eip['AllocationId']\n print('Releasing EIP {}'.format(allocation_id))\n client.release_address(\n AllocationId=allocation_id\n )\n\n print('Elastic IPs deleted')",
"def delete_address(self, ip_address):\n str_command = 'netsh interface ipv4 delete address \"{}\" addr={}'.format(self.name, ip_address)\n command = Popen(str_command) \n stdout, stderr = command.communicate()\n if stdout is None and stderr is None:\n print('Success - {} removed from {}'.format(ip_address, self.name))\n else:\n print('Failure - {} was not removed from {}'.format(ip_address, self.name))\n print('\\t' + str(stdout))\n print('\\t' + str(stderr))\n self = self.__init__(self.interface)",
"def clean_ipaddresses(cls, instances, **kwargs):\n for instance in instances:\n for ip in instance.ipaddresses.exclude(is_management=True):\n logger.warning('Deleting %s IP address', ip)\n eth = ip.ethernet\n ip.delete()\n if not any([eth.mac, eth.label]):\n logger.warning('Deleting %s (%s) ethernet', eth, eth.id)\n eth.delete()",
"def associate_address(DryRun=None, InstanceId=None, PublicIp=None, AllocationId=None, NetworkInterfaceId=None, PrivateIpAddress=None, AllowReassociation=None):\n pass",
"def invalidate_email_address():\n schema = InvalidateEmailAddressRequest()\n request_data = request.get_json()\n\n try:\n req = schema.load(request_data)\n except ValidationError as e:\n abort(400, str(e.normalized_messages()))\n\n user = user_service.find_user_by_email_address(req['email_address'])\n\n if user is None:\n abort(404, 'Unknown email address')\n\n event = email_address_verification_service.invalidate_email_address(\n user.id, req['reason']\n )\n\n user_signals.email_address_invalidated.send(None, event=event)",
"def test_ip_addresses_delete(self):\n pass",
"def ex_static_ip_destroy(self, ip_address):\r\n response = self.connection.request(\r\n action='/resources/ip/%s/destroy' % (ip_address), method='GET')\r\n\r\n return response.status == 204",
"def release_elastic_ip(self, eip):\n\n eip_obj = None\n try:\n eip_obj = self.conn.get_all_addresses(addresses=[eip])[0]\n except IndexError:\n return True\n\n if eip_obj:\n retries=0\n done=False\n while not done and retries < 3:\n try:\n status=eip_obj.release()\n done=True\n except:\n retries+=1\n time.sleep(15)\n try:\n eip_obj = self.conn.get_all_addresses(addresses=[eip])[0]\n except IndexError:\n return True\n\n if not done:\n return False\n\n if status:\n del self.eip_obj_dict[eip]\n \n return status\n\n else:\n return False",
"def delete_ip(self, key: str):\n\t\tuser_to_del = self.__ip[key]\n\t\tdel self.__ip[key]\n\t\tdel self.__user[user_to_del]",
"def ex_release_public_ip(self, address):\r\n return self.driver.ex_release_public_ip(self, address)",
"def del_address_from_address_groups(ip_addr, address_groups):\n address_group = find_address_in_same_subnet(ip_addr, address_groups)\n if address_group:\n sec_addr = address_group.get('secondaryAddresses')\n if sec_addr and ip_addr in sec_addr['ipAddress']:\n sec_addr['ipAddress'].remove(ip_addr)\n return True\n return False",
"def UndeleteEmailVerifiedAddress(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def ex_release_address(self, elastic_ip, domain=None):\r\n params = {'Action': 'ReleaseAddress'}\r\n\r\n if domain is not None and domain != 'vpc':\r\n raise AttributeError('Domain can only be set to vpc')\r\n\r\n if domain is None:\r\n params['PublicIp'] = elastic_ip.ip\r\n else:\r\n params['AllocationId'] = elastic_ip.extra['allocation_id']\r\n\r\n response = self.connection.request(self.path, params=params).object\r\n return self._get_boolean(response)",
"def ifDelIp(interface):\n logging.debugv(\"functions/linux.py->ifDelIp(interface)\", [interface])\n logging.info(\"Removing IP address from %s\" % interface)\n cmd = [locations.IFCONFIG, interface, \"0.0.0.0\", \"up\"]\n if runWrapper(cmd):\n return True\n else:\n return False",
"def remove_ip(self, hostname, floating_ip):\n LOG.debug('In remove_ip')\n\n if not self._ipa_client_configured():\n LOG.debug('IPA is not configured')\n return\n\n LOG.debug('Current a no-op')",
"def remove_floating_ip(server, address):\n return IMPL.remove_floating_ip(server, address)",
"def ElasticIps(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n return self.reservation"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disassociates an IAM instance profile from a running or stopped instance. Use DescribeIamInstanceProfileAssociations to get the association ID.
|
def disassociate_iam_instance_profile(AssociationId=None):
pass
|
[
"def delete_profile(self):\n response = self.client.delete_instance_profile(\n InstanceProfileName=self.ProfileName\n )",
"def TerminateInstance(*, session, instanceid):\n ec2conn = session.connect_to(\"ec2\")\n return ec2conn.terminate_instances(instance_ids=[instanceid,])",
"def delete_profile_for_user(sender, instance=None, **kwargs):\n if instance:\n user_profile = UserProfile.objects.get(user=instance)\n user_profile.delete()",
"def unpause_instance(self, ctxt, instance):\n self.msg_runner.unpause_instance(ctxt, instance)",
"def disassociate_flavor_from_service_profile(\n self, flavor, service_profile\n ):\n flavor = self._get_resource(_flavor.Flavor, flavor)\n service_profile = self._get_resource(\n _service_profile.ServiceProfile, service_profile\n )\n return flavor.disassociate_flavor_from_service_profile(\n self, service_profile.id\n )",
"def terminate_instance(instance_id):\n\n client = boto3.client('ec2')\n response = client.terminate_instances(InstanceIds=instance_id)",
"def StopInstance(*, session, instanceid):\n ec2conn = session.connect_to(\"ec2\")\n ret = ec2.stop_instances(instance_ids=[instanceid,])\n return True",
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def delete_profile(self):\n pass",
"def stopinstances():\n username, conn = _getbotoconn(auth_user)\n print \"stopping instances running under the %s account\" % username\n\n running_instances = _getrunninginstances(conn)\n for instid, instance in running_instances.iteritems():\n instance.stop()\n print \"instance %s stopped\" % instid",
"def DeactivateDisks(opts, args):\n instance_name = args[0]\n op = opcodes.OpInstanceDeactivateDisks(instance_name=instance_name,\n force=opts.force)\n SubmitOrSend(op, opts)\n return 0",
"def delete_network_profile(self, context, prof_id):\n # Check whether the network profile is in use.\n if self._network_profile_in_use(context.session, prof_id):\n raise n1kv_exc.NetworkProfileInUse(profile=prof_id)\n # Check whether default network profile is being deleted.\n np = self._get_network_profile(context.session, prof_id)\n if self._is_reserved_name(np['name']):\n raise n1kv_exc.ProfileDeletionNotSupported(profile=np['name'])\n nprofile = self._remove_network_profile(prof_id, context.session)\n return self._make_network_profile_dict(nprofile)",
"def delete_instance(self, inst):\n cognipy_call(self._uid, \"RemoveInstance\", inst)\n if self._verbose:\n markdown = \"(\"+inst+\")\"\n display(Markdown(markdown))",
"def disassociate_route_table(\n association_id, region=None, key=None, keyid=None, profile=None\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if conn.disassociate_route_table(association_id):\n log.info(\n \"Route table with association id %s has been disassociated.\",\n association_id,\n )\n return {\"disassociated\": True}\n else:\n log.warning(\n \"Route table with association id %s has not been disassociated.\",\n association_id,\n )\n return {\"disassociated\": False}\n except BotoServerError as e:\n return {\"disassociated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"async def uninstall_apparmor(self) -> None:\n if not self.sys_host.apparmor.exists(self.slug):\n return\n await self.sys_host.apparmor.remove_profile(self.slug)",
"def delete_instance_id(instance_id, app=None):\n _get_iid_service(app).delete_instance_id(instance_id)",
"def terminate(session):\n logging.info(\"Terminating instances\")\n session.clients[\"ec2\"].terminate_instances(InstanceIds=list(session.instances))",
"def unset_values():\n return \"unset {0} AWS_PROFILE; \".format(' '.join(aws_dict.keys()))",
"def terminate_instance(conn, instance_id):\n\n # Terminate an instance based on a user provided id\n conn.terminate_instances(instance_id)",
"def deregister(session):\n logging.info(\"Deregistering instances\")\n result = session.clients[\"ecs\"].list_container_instances(\n cluster=session.cluster, filter=f\"attribute:ecs.ami-id != {session.ami}\"\n )\n for instance in result[\"containerInstanceArns\"]:\n session.clients[\"ecs\"].deregister_container_instance(\n cluster=session.cluster, containerInstance=instance, force=False\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disassociates a subnet from a route table. After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see Route Tables in the Amazon Virtual Private Cloud User Guide .
|
def disassociate_route_table(DryRun=None, AssociationId=None):
pass
|
[
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def disassociate_network_acl(\n subnet_id=None,\n vpc_id=None,\n subnet_name=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not _exactly_one((subnet_name, subnet_id)):\n raise SaltInvocationError(\n \"One (but not both) of subnet_id or subnet_name must be provided.\"\n )\n\n if all((vpc_name, vpc_id)):\n raise SaltInvocationError(\"Only one of vpc_id or vpc_name may be provided.\")\n try:\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\",\n subnet_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not subnet_id:\n return {\n \"disassociated\": False,\n \"error\": {\n \"message\": \"Subnet {} does not exist.\".format(subnet_name)\n },\n }\n\n if vpc_name or vpc_id:\n vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile)\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id)\n return {\"disassociated\": True, \"association_id\": association_id}\n except BotoServerError as e:\n return {\"disassociated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def disassociate_route_table(\n association_id, region=None, key=None, keyid=None, profile=None\n):\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if conn.disassociate_route_table(association_id):\n log.info(\n \"Route table with association id %s has been disassociated.\",\n association_id,\n )\n return {\"disassociated\": True}\n else:\n log.warning(\n \"Route table with association id %s has not been disassociated.\",\n association_id,\n )\n return {\"disassociated\": False}\n except BotoServerError as e:\n return {\"disassociated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def DisassociateNetworkAclSubnets(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkAclSubnets\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkAclSubnetsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def subnet_delete(ctx, subnet_id):\n ctx.obj['nc'].delete(\"subnets/%s\" %subnet_id)",
"def delete_route(route_table_id, destination_cidr_block):\n ec2 = boto3.client('ec2')\n resp = ec2.delete_route(\n DestinationCidrBlock=destination_cidr_block,\n RouteTableId=route_table_id,\n )\n logger.info(\"Got response to delete_route {} \".format(resp))\n return resp",
"def delete_route(DryRun=None, RouteTableId=None, DestinationCidrBlock=None, DestinationIpv6CidrBlock=None):\n pass",
"def delete_subnet(\n subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None\n):\n\n return _delete_resource(\n resource=\"subnet\",\n name=subnet_name,\n resource_id=subnet_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )",
"def delete_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def unbind(self, uuid):\n try:\n route = Route.objects.get(uuid=uuid)\n except Route.DoesNotExist:\n pass\n else:\n route.delete()",
"def associate_route_table(\n route_table_id=None,\n subnet_id=None,\n route_table_name=None,\n subnet_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if all((subnet_id, subnet_name)):\n raise SaltInvocationError(\n \"Only one of subnet_name or subnet_id may be provided.\"\n )\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\", subnet_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not subnet_id:\n return {\n \"associated\": False,\n \"error\": {\"message\": \"Subnet {} does not exist.\".format(subnet_name)},\n }\n\n if all((route_table_id, route_table_name)):\n raise SaltInvocationError(\n \"Only one of route_table_name or route_table_id may be provided.\"\n )\n if route_table_name:\n route_table_id = _get_resource_id(\n \"route_table\",\n route_table_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not route_table_id:\n return {\n \"associated\": False,\n \"error\": {\n \"message\": \"Route table {} does not exist.\".format(route_table_name)\n },\n }\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n association_id = conn.associate_route_table(route_table_id, subnet_id)\n log.info(\n \"Route table %s was associated with subnet %s\", route_table_id, subnet_id\n )\n return {\"association_id\": association_id}\n except BotoServerError as e:\n return {\"associated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def subnet_delete_api(subnetid=None):\r\n try:\r\n if not subnetid:\r\n return err_return('subnetId is required', 'ParameterInvalid',\r\n '', HTTP_BAD_REQUEST)\r\n cidr = subnet_db_get_one('cidr', id=subnetid)\r\n if not cidr:\r\n return err_return('subnetId does not exist', 'ParameterInvalid',\r\n '', HTTP_NOT_FOUND)\r\n\r\n if port_ip_db_get_all(subnet_id=subnetid):\r\n return err_return('subnet in use', 'ParameterInvalid',\r\n '', HTTP_BAD_REQUEST)\r\n networkid = subnetid_to_networkid(subnetid)\r\n external = network_db_get_one('external', id=networkid)\r\n log.debug('external=%s' % external)\r\n if external:\r\n ret, desc = delete_subnet_by_networkid(networkid)\r\n if not ret:\r\n return err_return(desc, 'SubnetDeleteFail',\r\n '', HTTP_BAD_REQUEST)\r\n return Response(), HTTP_OK\r\n vl2lcid = yynetworkid_to_lcvl2id(networkid)\r\n nets = [{\"prefix\": VFW_TOR_LINK_NET_PRE,\r\n \"netmask\": VFW_TOR_LINK_NET_MASK}]\r\n subnets = get_subnets_by_network(networkid)\r\n for subnet in subnets:\r\n if str(subnet['id']) == subnetid:\r\n continue\r\n cidr = subnet['cidr'].split('/')\r\n nets.append({\"prefix\": cidr[0], \"netmask\": int(cidr[1])})\r\n nw_name = network_db_get_one('name', id=networkid)\r\n payload = json.dumps({\"name\": nw_name, \"nets\": nets})\r\n r = lcapi.patch(conf.livecloud_url + '/v1/vl2s/%s' % vl2lcid,\r\n data=payload)\r\n if r.status_code != HTTP_OK:\r\n err = r.json()['DESCRIPTION']\r\n log.error(r.json()['DESCRIPTION'])\r\n return err_return(err, 'Fail', '', HTTP_BAD_REQUEST)\r\n subnet_db_delete(id=subnetid)\r\n return Response(), HTTP_OK\r\n except Exception as e:\r\n log.error(e)\r\n return Response(json.dumps(NEUTRON_500)), HTTP_INTERNAL_SERVER_ERROR",
"def UnassignIpv6SubnetCidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6SubnetCidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6SubnetCidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def _assert_nat_in_subnet_route(ec2_client, subnet_id):\n response = ec2_client.describe_route_tables(Filters=[{\"Name\": \"association.subnet-id\", \"Values\": [subnet_id]}])\n routes = response[\"RouteTables\"][0][\"Routes\"]\n assert_that(next(route for route in routes if route[\"DestinationCidrBlock\"] == \"0.0.0.0/0\")).contains(\n \"NatGatewayId\"\n )",
"def UnassignIpv6CidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6CidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6CidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def associate_route_table(DryRun=None, SubnetId=None, RouteTableId=None):\n pass",
"def remove_route(self, rte):\n self.lock.acquire()\n try:\n self.table.remove_rte(rte)\n finally:\n self.lock.release()",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disassociates a CIDR block from a subnet. Currently, you can disassociate an IPv6 CIDR block only. You must detach or delete all gateways and resources that are associated with the CIDR block before you can disassociate it.
|
def disassociate_subnet_cidr_block(AssociationId=None):
pass
|
[
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def UnassignIpv6CidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6CidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6CidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def disassociate_network_acl(\n subnet_id=None,\n vpc_id=None,\n subnet_name=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not _exactly_one((subnet_name, subnet_id)):\n raise SaltInvocationError(\n \"One (but not both) of subnet_id or subnet_name must be provided.\"\n )\n\n if all((vpc_name, vpc_id)):\n raise SaltInvocationError(\"Only one of vpc_id or vpc_name may be provided.\")\n try:\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\",\n subnet_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not subnet_id:\n return {\n \"disassociated\": False,\n \"error\": {\n \"message\": \"Subnet {} does not exist.\".format(subnet_name)\n },\n }\n\n if vpc_name or vpc_id:\n vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile)\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id)\n return {\"disassociated\": True, \"association_id\": association_id}\n except BotoServerError as e:\n return {\"disassociated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def UnassignIpv6SubnetCidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6SubnetCidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6SubnetCidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def DisassociateNetworkAclSubnets(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkAclSubnets\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkAclSubnetsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def associate_subnet_cidr_block(SubnetId=None, Ipv6CidrBlock=None):\n pass",
"def subnet_delete(ctx, subnet_id):\n ctx.obj['nc'].delete(\"subnets/%s\" %subnet_id)",
"def disassociate_route_table(DryRun=None, AssociationId=None):\n pass",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def remove_loadbalanced_nic(self, datacenter_id,\n loadbalancer_id, nic_id):\n response = self._perform_request(\n url='/datacenters/%s/loadbalancers/%s/balancednics/%s' % (\n datacenter_id,\n loadbalancer_id,\n nic_id),\n method='DELETE')\n\n return response",
"def unassign_ipv6_addresses(NetworkInterfaceId=None, Ipv6Addresses=None):\n pass",
"def deallocate_segment(db_session, network_type, vni):\n alloc_table = 'ml2_{}_allocations'.format(network_type)\n vni_row = vni_row_name(network_type)\n\n # De-allocate VNI\n stmt = sqlalchemy.text(\n 'UPDATE {} SET allocated=0 WHERE {}=:vni'.format(alloc_table, vni_row))\n db_session.execute(stmt, {'vni': vni})",
"def set_subnet_cidr(value, yaml_file):\n yaml_content = get_yaml(elife_global_yaml)\n yaml_content[\"defaults\"][\"aws\"][\"subnet-cidr\"] = value\n write_yaml(yaml_content, yaml_file)",
"def associate_vpc_cidr_block(VpcId=None, AmazonProvidedIpv6CidrBlock=None):\n pass",
"def removeNetwork(conn):\n try:\n net = conn.networkLookupByName('vauto')\n except libvirt.libvirtError, e:\n logging.warn(\"Cannot find vauto network.\")\n return\n if net.isActive():\n net.destroy()\n if net.isPersistent():\n net.undefine()",
"def free_cidr(cidr, uuid):\n if cidr is None:\n return False\n\n global __current_ip\n int_ip = Net.cidr_2_int(cidr)\n\n global lock\n lock.acquire()\n\n if int_ip in __issued_ips and __issued_ips[int_ip] == uuid:\n del __issued_ips[int_ip]\n if int_ip < __current_ip:\n __current_ip = int_ip\n lock.release()\n return True\n lock.release()\n return False",
"def DisassociateNetworkInterfaceSecurityGroups(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkInterfaceSecurityGroups\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkInterfaceSecurityGroupsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def delete_subnet(\n subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None\n):\n\n return _delete_resource(\n resource=\"subnet\",\n name=subnet_name,\n resource_id=subnet_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )",
"def removeblockroad(self,roadid,id):\n tableuso = \"tablep_\" + id\n tablecusto = \"table_cost_\" + id\n try:\n conn = psycopg2.connect(\"dbname=\" + str(self.dbname) + \" user=\" + str(self.user) + \" host=\" + str(self.host) + \" password=\" + str(self.password) + \"\")\n except:\n print(\"I am unable to connect to the database\")\n return jsonify({\"Error\": \"Não é possivel conectar a base de dados.\"})\n cur = conn.cursor()\n cur.execute(\"SELECT ref_wayid FROM road_blocked where id=%s\", (roadid,))\n result = cur.fetchone()\n #adquirir o custo original\n cur.execute(sql.SQL(\"SELECT km FROM {} WHERE id = %s\").format(sql.Identifier(tablecusto)), [result[0]])\n originalCost = cur.fetchone()\n cur.execute(sql.SQL(\"UPDATE {} SET km=%s WHERE id = %s\").format(sql.Identifier(tableuso)), [originalCost[0],result[0]])\n conn.commit()\n cur.execute(\"DELETE FROM road_blocked WHERE id=%s and ref_userid=%s\", (roadid,id,))\n conn.commit()\n cur.close()\n conn.close()\n return jsonify({'success': True})"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disassociates a CIDR block from a VPC. Currently, you can disassociate an IPv6 CIDR block only. You must detach or delete all gateways and resources that are associated with the CIDR block before you can disassociate it.
|
def disassociate_vpc_cidr_block(AssociationId=None):
pass
|
[
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def UnassignIpv6CidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6CidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6CidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def disassociate_network_acl(\n subnet_id=None,\n vpc_id=None,\n subnet_name=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n if not _exactly_one((subnet_name, subnet_id)):\n raise SaltInvocationError(\n \"One (but not both) of subnet_id or subnet_name must be provided.\"\n )\n\n if all((vpc_name, vpc_id)):\n raise SaltInvocationError(\"Only one of vpc_id or vpc_name may be provided.\")\n try:\n if subnet_name:\n subnet_id = _get_resource_id(\n \"subnet\",\n subnet_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not subnet_id:\n return {\n \"disassociated\": False,\n \"error\": {\n \"message\": \"Subnet {} does not exist.\".format(subnet_name)\n },\n }\n\n if vpc_name or vpc_id:\n vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile)\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id)\n return {\"disassociated\": True, \"association_id\": association_id}\n except BotoServerError as e:\n return {\"disassociated\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def associate_vpc_cidr_block(VpcId=None, AmazonProvidedIpv6CidrBlock=None):\n pass",
"def UnassignIpv6SubnetCidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6SubnetCidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6SubnetCidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def DisassociateNetworkAclSubnets(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkAclSubnets\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkAclSubnetsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def disassociate_route_table(DryRun=None, AssociationId=None):\n pass",
"def delete_default_vpc(client, account_id, dry_run=False):\n # Check and remove default VPC\n default_vpc_id = None\n\n # Retrying the describe_vpcs call. Sometimes the VPC service is not ready when\n # you have just created a new account.\n max_retry_seconds = 180\n while True:\n try:\n vpc_response = client.describe_vpcs()\n break\n except Exception as e:\n logger.warning(f'Could not retrieve VPCs: {e}. Sleeping for 1 second before trying again.')\n max_retry_seconds - 2\n sleep(2)\n if max_retry_seconds <= 0:\n raise Exception(\"Could not describe VPCs within retry limit.\")\n\n for vpc in vpc_response[\"Vpcs\"]:\n if vpc[\"IsDefault\"] is True:\n default_vpc_id = vpc[\"VpcId\"]\n break\n\n if default_vpc_id is None:\n logging.info(f\"No default VPC found in account {account_id}\")\n return\n\n logging.info(f\"Found default VPC Id {default_vpc_id}\")\n subnet_response = client.describe_subnets()\n default_subnets = [\n subnet\n for subnet in subnet_response[\"Subnets\"]\n if subnet[\"VpcId\"] == default_vpc_id\n ]\n\n logging.info(f\"Deleting default {len(default_subnets )} subnets\")\n subnet_delete_response = [\n client.delete_subnet(SubnetId=subnet[\"SubnetId\"], DryRun=dry_run)\n for subnet in default_subnets\n ]\n\n igw_response = client.describe_internet_gateways()\n try:\n default_igw = [\n igw[\"InternetGatewayId\"]\n for igw in igw_response[\"InternetGateways\"]\n for attachment in igw[\"Attachments\"]\n if attachment[\"VpcId\"] == default_vpc_id\n ][0]\n except IndexError:\n default_igw = None\n\n if default_igw:\n logging.info(f\"Detaching Internet Gateway {default_igw}\")\n detach_default_igw_response = client.detach_internet_gateway(\n InternetGatewayId=default_igw, VpcId=default_vpc_id, DryRun=dry_run\n )\n\n logging.info(f\"Deleting Internet Gateway {default_igw}\")\n delete_internet_gateway_response = client.delete_internet_gateway(\n InternetGatewayId=default_igw\n )\n\n sleep(10) # It takes a bit of time for the dependencies to clear\n logging.info(f\"Deleting Default VPC {default_vpc_id}\")\n delete_vpc_response = client.delete_vpc(VpcId=default_vpc_id, DryRun=dry_run)\n\n return delete_vpc_response",
"def deallocate_segment(db_session, network_type, vni):\n alloc_table = 'ml2_{}_allocations'.format(network_type)\n vni_row = vni_row_name(network_type)\n\n # De-allocate VNI\n stmt = sqlalchemy.text(\n 'UPDATE {} SET allocated=0 WHERE {}=:vni'.format(alloc_table, vni_row))\n db_session.execute(stmt, {'vni': vni})",
"def DisassociateNetworkInterfaceSecurityGroups(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkInterfaceSecurityGroups\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkInterfaceSecurityGroupsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def delete_internet_gateways():\n print('Deleting Internet Gateways')\n client = boto3.resource('ec2')\n for igw in client.internet_gateways.all():\n for attachment in igw.attachments:\n if 'State' in attachment and attachment['State'] == 'available':\n vpc_id = attachment['VpcId']\n print('Detaching internet gateway {} from vpc {}'.format(igw.id, vpc_id))\n igw.detach_from_vpc(\n VpcId=vpc_id\n )\n print('Deleting Internet Gateway {}'.format(igw.id))\n igw.delete()\n\n while [igw for igw in client.internet_gateways.all()]:\n time.sleep(5)\n print('Internet Gateways deleted')",
"def delete_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def removeblockroad(self,roadid,id):\n tableuso = \"tablep_\" + id\n tablecusto = \"table_cost_\" + id\n try:\n conn = psycopg2.connect(\"dbname=\" + str(self.dbname) + \" user=\" + str(self.user) + \" host=\" + str(self.host) + \" password=\" + str(self.password) + \"\")\n except:\n print(\"I am unable to connect to the database\")\n return jsonify({\"Error\": \"Não é possivel conectar a base de dados.\"})\n cur = conn.cursor()\n cur.execute(\"SELECT ref_wayid FROM road_blocked where id=%s\", (roadid,))\n result = cur.fetchone()\n #adquirir o custo original\n cur.execute(sql.SQL(\"SELECT km FROM {} WHERE id = %s\").format(sql.Identifier(tablecusto)), [result[0]])\n originalCost = cur.fetchone()\n cur.execute(sql.SQL(\"UPDATE {} SET km=%s WHERE id = %s\").format(sql.Identifier(tableuso)), [originalCost[0],result[0]])\n conn.commit()\n cur.execute(\"DELETE FROM road_blocked WHERE id=%s and ref_userid=%s\", (roadid,id,))\n conn.commit()\n cur.close()\n conn.close()\n return jsonify({'success': True})",
"def free_cidr(cidr, uuid):\n if cidr is None:\n return False\n\n global __current_ip\n int_ip = Net.cidr_2_int(cidr)\n\n global lock\n lock.acquire()\n\n if int_ip in __issued_ips and __issued_ips[int_ip] == uuid:\n del __issued_ips[int_ip]\n if int_ip < __current_ip:\n __current_ip = int_ip\n lock.release()\n return True\n lock.release()\n return False",
"def unassign_ipv6_addresses(NetworkInterfaceId=None, Ipv6Addresses=None):\n pass",
"def associate_subnet_cidr_block(SubnetId=None, Ipv6CidrBlock=None):\n pass",
"def unblock_pin(self, puk: str, new_pin: str) -> None:\n logger.debug(\"Using PUK to set new PIN\")\n self._change_reference(INS_RESET_RETRY, PIN_P2, puk, new_pin)\n logger.info(\"New PIN set\")",
"def detach_vpn_gateway(DryRun=None, VpnGatewayId=None, VpcId=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Enables a virtual private gateway (VGW) to propagate routes to the specified route table of a VPC.
|
def enable_vgw_route_propagation(RouteTableId=None, GatewayId=None):
pass
|
[
"def configure_routing(vpc):\n internet_gateways = list(vpc.internet_gateways.all())\n if len(internet_gateways) == 1:\n internet_gateway = internet_gateways[0]\n elif len(internet_gateways) == 0:\n raise CraftingTableError(\"No internet gateway found\")\n else:\n raise CraftingTableError(f\"Multiple internet gateways found: {id_list(internet_gateways)}\")\n\n route_tables = list(vpc.route_tables.filter(Filters=[{\"Name\": \"association.main\", \"Values\": [\"true\"]}]))\n if len(route_tables) == 1:\n route_table = route_tables[0]\n elif len(route_tables) == 0:\n raise CraftingTableError(\"No route table found\")\n if len(route_tables) != 1:\n raise CraftingTableError(f\"Multiple route tables found: {id_list(route_tables)}\")\n\n for route in route_table.routes:\n if route.gateway_id == internet_gateway.id:\n break\n else:\n route_table.create_route(DestinationCidrBlock=\"0.0.0.0/0\", GatewayId=internet_gateway.id)\n click.echo(f\"Created default route to {internet_gateway.id}\")",
"def disable_vgw_route_propagation(RouteTableId=None, GatewayId=None):\n pass",
"def add_route_tgw_nh(route_table_id, destination_cidr_block, transit_gateway_id):\n ec2 = boto3.client('ec2')\n\n resp = ec2.create_route(\n DryRun=False,\n RouteTableId=route_table_id,\n DestinationCidrBlock=destination_cidr_block,\n TransitGatewayId=transit_gateway_id,\n )\n logger.info(\"Got response to add_route_tgw_nh {} \".format(resp))\n return resp",
"def create_route(vserver_name: str, net_gateway_ip: str) -> None:\n \"\"\"The default destination will be set to \"0.0.0.0/0\" for IPv4 gateway addresses\"\"\" \n\n data = {\n 'gateway': net_gateway_ip,\n 'svm': {'name': vserver_name}\n }\n\n route = NetworkRoute(**data)\n\n try:\n route.post()\n print(\"Route %s created successfully\" % route.gateway)\n except NetAppRestError as err:\n print(\"Error: Route was not created: %s\" % err)\n return",
"def create_route_entry(self, route_tables, vpc_id):\n params = {}\n results = []\n changed = False \n vrouter_table_id = None\n\n # Describe Vpc for getting VRouterId \n desc_vpc_param = {}\n self.build_list_params(desc_vpc_param, vpc_id, 'VpcId')\n desc_vpc_response = self.get_status('DescribeVpcs', desc_vpc_param)\n if int(desc_vpc_response[u'TotalCount']) > 0:\n vrouter_id = str(desc_vpc_response[u'Vpcs'][u'Vpc'][0][u'VRouterId']) \n\n # Describe Route Tables for getting RouteTable Id \n desc_route_table_param = {}\n self.build_list_params(desc_route_table_param, vrouter_id, 'VRouterId')\n desc_route_table_response = self.get_status('DescribeRouteTables', desc_route_table_param)\n if int(desc_route_table_response[u'TotalCount']) > 0:\n vrouter_table_id = str(desc_route_table_response[u'RouteTables'][u'RouteTable'][0][u'RouteTableId'])\n\n for vroute in route_tables:\n self.build_list_params(params, vrouter_table_id , 'RouteTableId') \n if \"next_hop_id\" in vroute:\n if (\"dest\" in vroute) or (\"destination_cidrblock\" in vroute):\n fixed_dest_cidr_block = None\n if 'dest' in vroute:\n fixed_dest_cidr_block = vroute[\"dest\"]\n if 'destination_cidrblock' in vroute:\n fixed_dest_cidr_block = vroute[\"destination_cidrblock\"]\n if fixed_dest_cidr_block:\n self.build_list_params(params, fixed_dest_cidr_block, 'DestinationCidrBlock')\n\n if 'next_hop_type' in vroute:\n self.build_list_params(params, vroute[\"next_hop_type\"], 'NextHopType')\n\n if 'next_hop_id' in vroute:\n self.build_list_params(params, vroute[\"next_hop_id\"], 'NextHopId')\n \n try:\n instance_result = self.get_instance_info()\n flag = False\n if instance_result:\n for instances in instance_result[0][u'Instances'][u'Instance']:\n if vroute[\"next_hop_id\"] == instances['InstanceId']:\n flag = True\n break\n if flag: \n response = self.get_status('CreateRouteEntry', params)\n results.append(response)\n changed = True\n time.sleep(10)\n else:\n results.append({\"Error Message\": str(vroute[\"next_hop_id\"])+\" Instance not found\"})\n except Exception as ex:\n error_code = ex.error_code\n error_msg = ex.message\n results.append({\"Error Code\": error_code, \"Error Message\": error_msg})\n else:\n results.append({\"Error Message\": \"destination_cidrblock is required to create custom route entry\"})\n else:\n results.append({\"Error Message\": \"next_hop_id is required to create custom route entry\"})\n else:\n results.append({\"Error Message\": \"vpc_id is not valid\"})\n \n return changed, results",
"def create_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def create_route(DryRun=None, RouteTableId=None, DestinationCidrBlock=None, GatewayId=None, DestinationIpv6CidrBlock=None, EgressOnlyInternetGatewayId=None, InstanceId=None, NetworkInterfaceId=None, VpcPeeringConnectionId=None, NatGatewayId=None):\n pass",
"def enhanced_vpc_routing(self) -> pulumi.Output[bool]:\n return pulumi.get(self, \"enhanced_vpc_routing\")",
"def attach_vpn_gateway(DryRun=None, VpnGatewayId=None, VpcId=None):\n pass",
"def addGw(ip):\n logging.debugv(\"functions/linux.py->addGw(ip)\", [ip])\n logging.info(\"setting default gateway to %s\" % (ip) )\n cmd = [\"ip\", \"route\", \"add\", \"default\", \"via\", ip]\n runWrapper(cmd)",
"def associate_route_table(DryRun=None, SubnetId=None, RouteTableId=None):\n pass",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def create_vpc_endpoint(self, vpc_id, route_table_id, service_name):\n params = {'VpcId': vpc_id, 'RouteTableId.1': route_table_id,\n 'ServiceName': service_name}\n return self.get_object('CreateVpcEndpoint', params, VPCEndpoint,\n verb='POST')",
"def create_vpc_endpoint(DryRun=None, VpcId=None, ServiceName=None, PolicyDocument=None, RouteTableIds=None, ClientToken=None):\n pass",
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def create_route(\n route_table_id=None,\n destination_cidr_block=None,\n route_table_name=None,\n gateway_id=None,\n internet_gateway_name=None,\n instance_id=None,\n interface_id=None,\n vpc_peering_connection_id=None,\n vpc_peering_connection_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n nat_gateway_id=None,\n nat_gateway_subnet_name=None,\n nat_gateway_subnet_id=None,\n):\n\n if not _exactly_one((route_table_name, route_table_id)):\n raise SaltInvocationError(\n \"One (but not both) of route_table_id or route_table_name must be provided.\"\n )\n\n if not _exactly_one(\n (\n gateway_id,\n internet_gateway_name,\n instance_id,\n interface_id,\n vpc_peering_connection_id,\n nat_gateway_id,\n nat_gateway_subnet_id,\n nat_gateway_subnet_name,\n vpc_peering_connection_name,\n )\n ):\n raise SaltInvocationError(\n \"Only one of gateway_id, internet_gateway_name, instance_id, interface_id,\"\n \" vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id,\"\n \" nat_gateway_subnet_name or vpc_peering_connection_name may be provided.\"\n )\n\n if destination_cidr_block is None:\n raise SaltInvocationError(\"destination_cidr_block is required.\")\n\n try:\n if route_table_name:\n route_table_id = _get_resource_id(\n \"route_table\",\n route_table_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not route_table_id:\n return {\n \"created\": False,\n \"error\": {\n \"message\": \"route table {} does not exist.\".format(\n route_table_name\n )\n },\n }\n\n if internet_gateway_name:\n gateway_id = _get_resource_id(\n \"internet_gateway\",\n internet_gateway_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not gateway_id:\n return {\n \"created\": False,\n \"error\": {\n \"message\": \"internet gateway {} does not exist.\".format(\n internet_gateway_name\n )\n },\n }\n\n if vpc_peering_connection_name:\n vpc_peering_connection_id = _get_resource_id(\n \"vpc_peering_connection\",\n vpc_peering_connection_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not vpc_peering_connection_id:\n return {\n \"created\": False,\n \"error\": {\n \"message\": \"VPC peering connection {} does not exist.\".format(\n vpc_peering_connection_name\n )\n },\n }\n\n if nat_gateway_subnet_name:\n gws = describe_nat_gateways(\n subnet_name=nat_gateway_subnet_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not gws:\n return {\n \"created\": False,\n \"error\": {\n \"message\": \"nat gateway for {} does not exist.\".format(\n nat_gateway_subnet_name\n )\n },\n }\n nat_gateway_id = gws[0][\"NatGatewayId\"]\n\n if nat_gateway_subnet_id:\n gws = describe_nat_gateways(\n subnet_id=nat_gateway_subnet_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not gws:\n return {\n \"created\": False,\n \"error\": {\n \"message\": \"nat gateway for {} does not exist.\".format(\n nat_gateway_subnet_id\n )\n },\n }\n nat_gateway_id = gws[0][\"NatGatewayId\"]\n\n except BotoServerError as e:\n return {\"created\": False, \"error\": __utils__[\"boto.get_error\"](e)}\n\n if not nat_gateway_id:\n return _create_resource(\n \"route\",\n route_table_id=route_table_id,\n destination_cidr_block=destination_cidr_block,\n gateway_id=gateway_id,\n instance_id=instance_id,\n interface_id=interface_id,\n vpc_peering_connection_id=vpc_peering_connection_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n # for nat gateway, boto3 is required\n try:\n conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n ret = conn3.create_route(\n RouteTableId=route_table_id,\n DestinationCidrBlock=destination_cidr_block,\n NatGatewayId=nat_gateway_id,\n )\n return {\"created\": True, \"id\": ret.get(\"NatGatewayId\")}\n except BotoServerError as e:\n return {\"created\": False, \"error\": __utils__[\"boto.get_error\"](e)}",
"def route(src_ip, provider):\n cur.execute(\"\"\"SELECT id FROM provider WHERE name = ?\"\"\", (provider,))\n provider_id = cur.fetchone()[0]\n if not provider_id:\n return 9\n ret = os.system(\"\"\"\n sudo /sbin/iptables -t mangle -A PREROUTING -s %s -j MARK --set-mark %i\n \"\"\" % (src_ip, int(provider_id)))\n if ret == 0:\n ret = ret | back(src_ip)\n cur.execute(\"\"\"INSERT INTO active_routes \n (src_ip, provider_id) VALUES (?, ?)\"\"\", (src_ip, int(provider_id)))\n con.commit()\n return ret",
"def delete_virtual_gateways():\n client = boto3.client('ec2')\n print('Deleting VPN Gateways')\n gw_resp = client.describe_vpn_gateways()\n while True:\n for gateway in gw_resp['VpnGateways']:\n gw_id = gateway['VpnGatewayId']\n gw_attachments = gateway['VpcAttachments']\n for attachment in gw_attachments:\n if attachment['State'] == 'attached':\n vpc_id = attachment['VpcId']\n print('Detaching virtual gateway {} from vpc {}'.format(gw_id, vpc_id))\n client.detach_vpn_gateway(\n VpcId=vpc_id,\n VpnGatewayId=gw_id\n )\n print('Deleting VPN gateway {}'.format(gw_id))\n client.delete_vpn_gateway(\n VpnGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_vpn_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_vpn_gateways()['VpnGateways']:\n all_deleted = True\n for gateway in client.describe_vpn_gateways()['VpnGateways']:\n if gateway['State'] != 'deleted':\n all_deleted = False\n break\n if all_deleted:\n break\n else:\n time.sleep(5)\n print('VPN Gateways deleted')",
"def insert_route(self, match_vRouter_number,\n match_ipv4address,\n action_dest_mac,\n action_egress_port):\n\n entry = shell.TableEntry(\"MyIngress.ipv4NextHopLPM\")(\n action=\"MyIngress.ipv4Forward\")\n entry.match[\"vRouterNumber\"] = str(match_vRouter_number)\n entry.match[\"hdr.ipv4.dstAddr\"] = str(match_ipv4address)\n entry.action[\"port\"] = str(action_egress_port)\n entry.action[\"dstAddr\"] = str(action_dest_mac)\n entry.insert()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent.
|
def enable_volume_io(DryRun=None, VolumeId=None):
pass
|
[
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def toggleControl_AOFile(self):\n\n self.Voltage_ReadFromFile = True\n self.Voltage_Input.setDisabled(True)",
"def enable(self):\n for volume in self.volumes:\n try:\n self._renderer.AddVolume(volume)\n except:\n pass # TBD: any error logging.",
"def enable_api(event, data):\n DriveDevice.storage.api_enabled = data",
"def toggleControl_AOGUI(self):\n \n self.Voltage_ReadFromFile = False\n self.Voltage_Input.setDisabled(False)",
"def rescan_vols(op_code):\n\n with open_scini_device() as fd:\n ioctl(fd, op_code, struct.pack('Q', 0))",
"def system_exclusive(self, data):",
"def onExtendedVolume(self, widget):\n self.extended = self.chk0.get_active()\n self.updateScreens()",
"def async_turn_off_ac_volume(self):\n yield from self._try_command(\n \"Setting volume off of the miio AC failed.\",\n self._device.set_volume, \"off\")",
"def _ienable(self, alt):\n if self.poisoned:\n return True\n if self.buffer.empty():\n self._ialt = alt\n return False\n return True",
"def change_operation(self, context):\n info = self.operations_settings[self.operation]\n params = info['params']\n for i in range(3):\n if i in params:\n self.inputs[i].enabled = True\n self.inputs[i].name = params[i]\n else:\n self.inputs[i].enabled = False\n if BLENDER_VERSION >= \"3.1\" and context:\n self.socket_value_update(context)",
"def enable_storage(self):\n self.storage_enabled = True",
"def _update_use_internal_mod_flag(self):\n device_param = f\"{self._awg.name}_internal_modulation\"\n device_value = self.pulsar.get(device_param) \\\n if hasattr(self.pulsar, device_param) else False\n\n channel_param = f\"{self.i_channel_name}_internal_modulation\"\n channel_value = self.pulsar.get(channel_param) \\\n if hasattr(self.pulsar, channel_param) else False\n\n self._use_internal_mod = device_value | channel_value",
"def on_volume_setting(self):\n print(\"on_volume_setting was triggered\")",
"def system_exclusive(self, data):\n pass",
"def isReadOnly():\n\n # XXX Note that this method doesn't really buy us much,\n # especially since we have to account for the fact that a\n # ostensibly non-read-only storage may be read-only\n # transiently. It would be better to just have read-only errors.",
"def disable(self):\n for volume in self.volumes:\n try:\n self._renderer.RemoveVolume(volume)\n except:\n pass # TBD: any error logging.",
"def powerOn(self):\n self.instr.write(\"OUTP ON\")",
"def _disable_async_replication(self, volume):\n\n current_array = self._get_current_array()\n LOG.debug(\"Disabling replication for volume %(id)s residing on \"\n \"array %(backend_id)s.\",\n {\"id\": volume[\"id\"],\n \"backend_id\": current_array.backend_id})\n try:\n current_array.set_pgroup(self._replication_pg_name,\n remvollist=([self._get_vol_name(volume)]))\n except purestorage.PureHTTPError as err:\n with excutils.save_and_reraise_exception() as ctxt:\n if (err.code == 400 and\n ERR_MSG_COULD_NOT_BE_FOUND in err.text):\n ctxt.reraise = False\n LOG.warning(\"Disable replication on volume failed: \"\n \"already disabled: %s\", err.text)\n else:\n LOG.error(\"Disable replication on volume failed with \"\n \"message: %s\", err.text)",
"def HV1Enable(self, enable = 0):\n name = \"FIO3\"\n logging.debug(\"Inhibit HV1 : {0}\".format(not bool(enable)))\n self.DigitalIO5V(name, not enable)\n self.hv1_enable = enable"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Enables a VPC for ClassicLink. You can then link EC2Classic instances to your ClassicLinkenabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC's route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see ClassicLink in the Amazon Elastic Compute Cloud User Guide .
|
def enable_vpc_classic_link(DryRun=None, VpcId=None):
pass
|
[
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def describe_vpc_classic_link(DryRun=None, VpcIds=None, Filters=None):\n pass",
"def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):\n pass",
"def configure_routing(vpc):\n internet_gateways = list(vpc.internet_gateways.all())\n if len(internet_gateways) == 1:\n internet_gateway = internet_gateways[0]\n elif len(internet_gateways) == 0:\n raise CraftingTableError(\"No internet gateway found\")\n else:\n raise CraftingTableError(f\"Multiple internet gateways found: {id_list(internet_gateways)}\")\n\n route_tables = list(vpc.route_tables.filter(Filters=[{\"Name\": \"association.main\", \"Values\": [\"true\"]}]))\n if len(route_tables) == 1:\n route_table = route_tables[0]\n elif len(route_tables) == 0:\n raise CraftingTableError(\"No route table found\")\n if len(route_tables) != 1:\n raise CraftingTableError(f\"Multiple route tables found: {id_list(route_tables)}\")\n\n for route in route_table.routes:\n if route.gateway_id == internet_gateway.id:\n break\n else:\n route_table.create_route(DestinationCidrBlock=\"0.0.0.0/0\", GatewayId=internet_gateway.id)\n click.echo(f\"Created default route to {internet_gateway.id}\")",
"def enhanced_vpc_routing(self) -> pulumi.Output[bool]:\n return pulumi.get(self, \"enhanced_vpc_routing\")",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def associate_vpc_cidr_block(VpcId=None, AmazonProvidedIpv6CidrBlock=None):\n pass",
"def associate_address(DryRun=None, InstanceId=None, PublicIp=None, AllocationId=None, NetworkInterfaceId=None, PrivateIpAddress=None, AllowReassociation=None):\n pass",
"def enable_private_networking(self):\n return self.act_on_droplets(type='enable_private_networking')",
"def add_vpc(template, key_pair_name, nat_ip,\n nat_image_id=DEFAULT_NAT_IMAGE_ID,\n nat_instance_type=DEFAULT_NAT_INSTANCE_TYPE):\n vpc_id = \"VPC\"\n vpc = template.add_resource(ec2.VPC(\n vpc_id,\n CidrBlock=\"10.0.0.0/16\",\n Tags=Tags(\n Name=name_tag(vpc_id)\n ),\n ))\n public_subnet = _add_public_subnet(template, vpc)\n nat = _add_nat(template, vpc, public_subnet, nat_image_id, nat_instance_type,\n key_pair_name, nat_ip)\n _add_private_subnet(template, vpc, nat)\n return vpc",
"def enableDHCPClick():\n os.system(\"mount -o rw,remount /\")\n os.system(\"cp netctl/ethernet-dhcp /etc/netctl/eth0\")\n os.system(\"mount -o ro,remount /\")\n lcdPrint(\"Obtaining IP...\")\n lcd.setCursor(15,0)\n lcd.ToggleBlink()\n os.system(\"ip link set eth0 down\")\n os.system(\"netctl restart eth0\")\n ip = socket.gethostbyname(socket.getfqdn())\n lcd.ToggleBlink()\n lcdPrint(\"Enabled DHCP:\\n\"+ip, 2)",
"def enable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'enable'])\n print(\"Enable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'enable'])\n print(\"Enable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" enable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" enable', None, 1)",
"def enable_sr_iov(self, instance, ssh_client):\n conn = self.conn or self.vpc_conn\n log.info('Enabling SR-IOV on {}'.format(instance.id))\n if ssh_client:\n util_path = os.path.dirname(os.path.realpath(__file__))\n ssh_client.put_file(os.path.join(util_path, 'tests', 'enable_sr_iov.sh'),\n '/tmp/enable_sr_iov.sh')\n ssh_client.run('chmod +x /tmp/enable_sr_iov.sh')\n ssh_client.run(\"sed -i 's/\\r//' /tmp/enable_sr_iov.sh\")\n ssh_client.run('/tmp/enable_sr_iov.sh {}'.format(self.instancetype))\n conn.stop_instances(instance_ids=[instance.id])\n self.wait_for_state(instance, 'state', 'stopped')\n if self.instancetype in [constants.AWS_P28XLARGE, constants.AWS_M416XLARGE]:\n log.info('Enabling ENA for instance: {}'.format(self.instancetype))\n import boto3\n client = boto3.client('ec2', region_name=self.region, aws_access_key_id=self.keyid,\n aws_secret_access_key=self.secret)\n client.modify_instance_attribute(InstanceId=instance.id, Attribute='enaSupport',\n Value='true')\n log.info('ENA support: {}'.format(client.__dict__))\n try:\n log.info(conn.get_instance_attribute(instance.id, 'enaSupport'))\n except Exception as e:\n log.info(e)\n pass\n # conn.modify_instance_attribute(instance.id, 'enaSupport', True)\n # ena_status = conn.get_instance_attribute(instance.id, 'enaSupport')\n # log.info('ENA status for {} instance: {}'.format(constants.AWS_P28XLARGE,\n # ena_status))\n elif self.instancetype == constants.AWS_D24XLARGE:\n conn.modify_instance_attribute(instance.id, 'sriovNetSupport', 'simple')\n sriov_status = conn.get_instance_attribute(instance.id, 'sriovNetSupport')\n log.info(\"SR-IOV status is: {}\".format(sriov_status))\n else:\n log.error('Instance type {} unhandled for SRIOV'.format(self.instancetype))\n return None\n conn.start_instances(instance_ids=[instance.id])\n self.wait_for_state(instance, 'state', 'running')\n\n return self.wait_for_ping(instance)",
"def create_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None):\n pass",
"def test_102_tune_nat_instance(self):\n instance = self.ctx.nat_instance\n address = instance.ip_address\n ssh = remote_client.RemoteClient(address,\n self.ssh_user,\n pkey=self.keypair.material)\n\n ssh.exec_command(\"sudo iptables -t nat -A POSTROUTING -s %s \"\n \"-o eth0 -j MASQUERADE\" % str(self.vpc_cidr))\n ssh.exec_command(\"sudo sysctl -w net.ipv4.ip_forward=1\")\n ssh.exec_command(\"echo $'auto eth1\\niface eth1 inet dhcp\\n' \"\n \"| sudo tee -a /etc/network/interfaces.d/eth1.cfg\")\n ssh.exec_command(\"sudo ifup eth1\")",
"def enable_module(address, name, module):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.enable_module(module)",
"def submit_post_req_to_enable_kytos_link(link_id):\n\n enable_api_url = kytos_topology_url + \"/links/\" + link_id + \"/enable\"\n try:\n response = requests.post(enable_api_url, headers=new_headers)\n except Exception as err:\n print(\"Error connecting to Kytos topology API to enable link\")\n print(err)\n sys.exit(1)\n\n if response.status_code != 201:\n raise Exception(\"Return code is not 200, response = %s\" % response.content)",
"def allowInternetConnection(network, bridge):\n\n cmds = []\n cmds.append('ip -4 route add dev {} {} proto static'.format(bridge, network))\n cmds.append(\n 'iptables -A FORWARD -o {} -t filter -m comment --comment \"generated for Distrinet Admin Network\" -j ACCEPT'.format(\n bridge))\n cmds.append(\n 'iptables -A FORWARD -i {} -t filter -m comment --comment \"generated for Distrinet Admin Network\" -j ACCEPT'.format(\n bridge))\n cmds.append(\n 'iptables -A POSTROUTING -t nat -m comment --comment \"generated for Distrinet Admin Network\" -s {} ! -d {} -j MASQUERADE'.format(\n network, network))\n cmds.append('sysctl -w net.ipv4.ip_forward=1')\n return cmds",
"def EnableCcnRoutes(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"EnableCcnRoutes\", params, headers=headers)\n response = json.loads(body)\n model = models.EnableCcnRoutesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def vpc_classic_link_id(self) -> str:\n warnings.warn(\"\"\"With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\", DeprecationWarning)\n pulumi.log.warn(\"\"\"vpc_classic_link_id is deprecated: With the retirement of EC2-Classic the vpc_classic_link_id attribute has been deprecated and will be removed in a future version.\"\"\")\n\n return pulumi.get(self, \"vpc_classic_link_id\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Enables a VPC to support DNS hostname resolution for ClassicLink. If enabled, the DNS hostname of a linked EC2Classic instance resolves to its private IP address when addressed from an instance in the VPC to which it's linked. Similarly, the DNS hostname of an instance in a VPC resolves to its private IP address when addressed from a linked EC2Classic instance. For more information about ClassicLink, see ClassicLink in the Amazon Elastic Compute Cloud User Guide .
|
def enable_vpc_classic_link_dns_support(VpcId=None):
pass
|
[
"def describe_vpc_classic_link_dns_support(VpcIds=None, MaxResults=None, NextToken=None):\n pass",
"def setup_dns(self, instance_identifier):\n start_time = time.time()\n instance_endpoint = keep_trying(RDS_STARTUP_TIMEOUT, self._get_instance_address, instance_identifier)\n logging.info(\"Waited %s seconds for RDS to get an address\", time.time() - start_time)\n disco_route53 = DiscoRoute53()\n instance_record_name = '{0}.{1}.'.format(instance_identifier, self.domain_name)\n\n # Delete and recreate DNS record for this Instance\n disco_route53.delete_record(self.domain_name, instance_record_name, 'CNAME')\n disco_route53.create_record(self.domain_name, instance_record_name, 'CNAME', instance_endpoint)",
"def attach_classic_link_vpc(DryRun=None, InstanceId=None, VpcId=None, Groups=None):\n pass",
"def resolve_address(self, hostname, callback, allow_cname = True):\n raise NotImplementedError",
"def dns_use_host_resolver(self):\n ret = self._get_attr(\"DNSUseHostResolver\")\n return ret",
"def test_dNSNameHostname(self):\n options = sslverify.optionsForClientTLS(u'example.com')\n self.assertTrue(options._hostnameIsDnsName)",
"def resolveHost(hostname):\n try:\n aRec = dns.resolver.query(str(hostname), 'A')\n answer = aRec\n for hData in answer:\n print(\"%s - %s\" % (str(hostname), str(hData)))\n except:\n print(\"%s - no ip found\" % (str(hostname)))",
"def test_IPv4AddressHostname(self):\n options = sslverify.optionsForClientTLS(u'127.0.0.1')\n self.assertFalse(options._hostnameIsDnsName)",
"def enableDHCPClick():\n os.system(\"mount -o rw,remount /\")\n os.system(\"cp netctl/ethernet-dhcp /etc/netctl/eth0\")\n os.system(\"mount -o ro,remount /\")\n lcdPrint(\"Obtaining IP...\")\n lcd.setCursor(15,0)\n lcd.ToggleBlink()\n os.system(\"ip link set eth0 down\")\n os.system(\"netctl restart eth0\")\n ip = socket.gethostbyname(socket.getfqdn())\n lcd.ToggleBlink()\n lcdPrint(\"Enabled DHCP:\\n\"+ip, 2)",
"def enable_dhcp(self, ip_host_num):\n return [\"ip-host %s dhcp-enable true ping-response true traceroute-response true\" % ip_host_num]",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def create_route53_ec2_dns(name, app_type):\n try:\n aws_cfg\n except NameError:\n aws_cfg = load_aws_cfg()\n\n try:\n app_settings\n except NameError:\n app_settings = loadsettings(app_type)\n\n try:\n ec2host = open(\"fab_hosts/{}.txt\".format(name)).readline().strip() + \".\"\n except IOError:\n print _red(\"{name} is not reachable. either run fab getec2instances or fab create_ec2:{name} to create the instance\".format(name=name))\n return 1\n\n app_zone_name = app_settings[\"DOMAIN_NAME\"] + \".\"\n app_host_name = app_settings[\"HOST_NAME\"] + \".\"\n\n print _green(\"Creating DNS for \" + name + \" and app_type \" + app_type)\n conn = connect_to_r53()\n if conn.get_zone(app_zone_name) is None:\n print _yellow(\"creating zone \" + _green(app_zone_name))\n zone = conn.create_zone(app_zone_name)\n else:\n print _yellow(\"zone \" + _green(app_zone_name) + _yellow(\" already exists. skipping creation\"))\n zone = conn.get_zone(app_zone_name)\n\n if app_type == 'app':\n # TODO: cleanup parser\n # ex: ec2-54-204-216-244.compute-1.amazonaws.com\n ec2ip = '.'.join(ec2host.split('.')[0].split('-')[1:5])\n try:\n apex = zone.add_a(app_zone_name, ec2ip, ttl=300)\n while apex.status != 'INSYNC':\n print _yellow(\"creation of A record: \" + _green(app_zone_name + \" \" + ec2ip) + _yellow(\" is \") + _red(apex.status))\n apex.update()\n time.sleep(10)\n print _green(\"creation of A record: \" + app_zone_name + \" is now \" + apex.status)\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"address record \" + _green(app_zone_name + \" \" + ec2ip) + _yellow(\" already exists. skipping creation\"))\n else:\n raise\n\n try:\n cname = zone.add_cname(app_host_name, ec2host, ttl=300, comment=\"expa \" + app_type + \" entry\")\n while cname.status != 'INSYNC':\n print _yellow(\"creation of cname: \" + _green(app_host_name) + _yellow(\" is \") + _red(cname.status))\n cname.update()\n time.sleep(10)\n print _green(\"creation of cname: \" + app_host_name + \" is now \" + cname.status)\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"cname record \" + _green(app_host_name) + _yellow(\" already exists. skipping creation\"))\n else:\n raise",
"def dnslink(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"dnslink\")",
"def test_dnssec_activate():\n response = zone.dnssec_activate('example.com')\n assert response.success\n\n payload = response.payload\n assert payload['url'] == 'https://api.cloudns.net/dns/activate-dnssec.json'",
"def set_hostname(self, name):\n self.update(hostname=name)",
"def fix_missing_hostname():\n ssh_client = store.current_appliance.ssh_client\n logger.info(\"Checking appliance's /etc/hosts for its own hostname\")\n if ssh_client.run_command('grep $(hostname) /etc/hosts').rc != 0:\n logger.info(\"Adding it's hostname to its /etc/hosts\")\n # Append hostname to the first line (127.0.0.1)\n ret = ssh_client.run_command('sed -i \"1 s/$/ $(hostname)/\" /etc/hosts')\n if ret.rc == 0:\n logger.info(\"Hostname added\")\n else:\n logger.error(\"Failed to add hostname\")",
"def cloud_dns(self):\r\n return self._get_client(\"dns\")",
"def get_hostname(event):\n\n ec2 = boto3.client('ec2')\n\n instance_id = event['detail']['EC2InstanceId']\n\n # if we fail to get the private DNS, go ahead and fail since we can't do much else\n try:\n private_dns = ec2.describe_instances(InstanceIds=[instance_id]) \\\n ['Reservations'][0]['Instances'][0]['PrivateDnsName']\n except ClientError as e:\n print(\"Exception when converting %s to private DNS: %s\" % (instance_id, e))\n sys.exit(1)\n\n return private_dns",
"def check_forward_dns_lookup(host_name, dict_to_modify):\n try:\n host_ip = socket.gethostbyname(host_name)\n DictionaryHandling.add_to_dictionary(forward_lookup_dict, host_name, \"IP Address\", host_ip)\n except socket.gaierror:\n try:\n socket.inet_aton(host_name)\n print(\"You should be using FQDN instead of IPs in your ansible host file!\")\n pass\n except socket.error:\n pass\n DictionaryHandling.add_to_dictionary(dict_to_modify, host_name, \"IP Address\", None)",
"def create_route53_elb_dns(elb_name, app_type):\n try:\n aws_cfg\n except NameError:\n aws_cfg = load_aws_cfg()\n\n try:\n app_settings\n except NameError:\n app_settings = loadsettings(app_type)\n\n elb = connect_to_elb()\n r53 = connect_to_r53()\n\n lb = elb.get_all_load_balancers(load_balancer_names=elb_name)[0]\n app_zone_name = app_settings[\"DOMAIN_NAME\"] + \".\"\n app_host_name = app_settings[\"HOST_NAME\"] + \".\"\n\n print _green(\"Creating DNS for \" + elb_name + \" and app_type \" + app_type)\n if r53.get_zone(app_zone_name) is None:\n print _yellow(\"creating zone \" + _green(app_zone_name))\n zone = r53.create_zone(app_zone_name)\n else:\n # print _yellow(\"zone \" + _green(app_zone_name) + _yellow(\" already exists. skipping creation\"))\n zone = r53.get_zone(app_zone_name)\n\n records = r53.get_all_rrsets(zone.id)\n\n if app_type == 'app':\n try:\n change = records.add_change('CREATE', zone.name, 'A', ttl=300, alias_hosted_zone_id=lb.canonical_hosted_zone_name_id, alias_dns_name=lb.canonical_hosted_zone_name)\n change.add_value('ALIAS %s (%s)' % (lb.canonical_hosted_zone_name, lb.canonical_hosted_zone_name_id))\n change_id = records.commit()['ChangeResourceRecordSetsResponse']['ChangeInfo']['Id'].split('/')[-1]\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n spinner = Spinner(_yellow('[%s]waiting for route53 change to coalesce... ' % zone.name), hide_cursor=False)\n while status != 'INSYNC':\n spinner.next()\n time.sleep(1)\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n print(_green('\\n[%s]route53 change coalesced' % zone.name))\n except Exception as error:\n if 'already exists' in error.message:\n # print _yellow(\"address record \" + _green(app_zone_name + \" \" + lb.canonical_hosted_zone_name) + _yellow(\" already exists. skipping creation\"))\n pass\n else:\n raise\n\n try:\n change = records.add_change('CREATE', app_host_name, 'A', ttl=300, alias_hosted_zone_id=lb.canonical_hosted_zone_name_id, alias_dns_name=lb.canonical_hosted_zone_name)\n change.add_value('ALIAS %s (%s)' % (lb.canonical_hosted_zone_name, lb.canonical_hosted_zone_name_id))\n change_id = records.commit()['ChangeResourceRecordSetsResponse']['ChangeInfo']['Id'].split('/')[-1]\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n spinner = Spinner(_yellow('[%s]waiting for route53 change to coalesce... ' % app_host_name), hide_cursor=False)\n while status != 'INSYNC':\n spinner.next()\n time.sleep(1)\n status = r53.get_change(change_id)['GetChangeResponse']['ChangeInfo']['Status']\n print(_green('\\n[%s]route53 change coalesced' % app_host_name))\n except Exception as error:\n if 'already exists' in error.message:\n print _yellow(\"cname record \" + _green(app_host_name) + _yellow(\" already exists. skipping creation\"))\n else:\n raise"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Preview a reservation purchase with configurations that match those of your Dedicated Host. You must have active Dedicated Hosts in your account before you purchase a reservation. This is a preview of the PurchaseHostReservation action and does not result in the offering being purchased.
|
def get_host_reservation_purchase_preview(OfferingId=None, HostIdSet=None):
pass
|
[
"def purchase_host_reservation(OfferingId=None, HostIdSet=None, LimitPrice=None, CurrencyCode=None, ClientToken=None):\n pass",
"def describe_host_reservations(HostReservationIdSet=None, Filters=None, MaxResults=None, NextToken=None):\n pass",
"def describe_host_reservation_offerings(OfferingId=None, MinDuration=None, MaxDuration=None, Filters=None, MaxResults=None, NextToken=None):\n pass",
"def test_Computer_getSoftwareReleaseList_AccountingResource_ConfirmedState(self):\n sequence_list = SequenceList()\n sequence_string = \\\n self.prepare_software_release_purchase_packing_list_accounting_resource + '\\\n SlapLoginCurrentComputer \\\n CheckEmptyComputerGetSoftwareReleaseListCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def test_host_detail(self, mocker_request, mocker_res, mocker_client_id):\n from RiskSense import get_host_detail_command\n mocker_client_id.return_value = CLIENT_DETAILS\n mocker_request.return_value = {\n\n \"filters\": [\n {\n \"operator\": \"EXACT\",\n \"field\": \"hostname\",\n \"value\": \"test-hostname\",\n \"exclusive\": \"false\"\n }\n ],\n \"projection\": \"detail\"\n }\n\n with open(\"./TestData/hosts_res.json\", encoding='utf-8') as f:\n expected_res = json.load(f)\n mocker_res.return_value = expected_res\n\n hr, ec, resp = get_host_detail_command(self.client, {})\n with open(\"./TestData/hosts_ec.json\") as f:\n expected_ec = json.load(f)\n assert expected_res == resp\n assert expected_ec == ec",
"def select_destinations(\n self, context, request_spec=None,\n filter_properties=None, spec_obj=_sentinel, instance_uuids=None,\n return_objects=False, return_alternates=False,\n ):\n LOG.debug(\"Starting to schedule for instances: %s\", instance_uuids)\n\n # TODO(sbauza): Change the method signature to only accept a spec_obj\n # argument once API v5 is provided.\n if spec_obj is self._sentinel:\n spec_obj = objects.RequestSpec.from_primitives(\n context, request_spec, filter_properties)\n\n is_rebuild = utils.request_is_rebuild(spec_obj)\n alloc_reqs_by_rp_uuid, provider_summaries, allocation_request_version \\\n = None, None, None\n if not is_rebuild:\n try:\n request_filter.process_reqspec(context, spec_obj)\n except exception.RequestFilterFailed as e:\n raise exception.NoValidHost(reason=e.message)\n\n resources = utils.resources_from_request_spec(\n context, spec_obj, self.host_manager,\n enable_pinning_translate=True)\n res = self.placement_client.get_allocation_candidates(\n context, resources)\n if res is None:\n # We have to handle the case that we failed to connect to the\n # Placement service and the safe_connect decorator on\n # get_allocation_candidates returns None.\n res = None, None, None\n\n alloc_reqs, provider_summaries, allocation_request_version = res\n alloc_reqs = alloc_reqs or []\n provider_summaries = provider_summaries or {}\n\n # if the user requested pinned CPUs, we make a second query to\n # placement for allocation candidates using VCPUs instead of PCPUs.\n # This is necessary because users might not have modified all (or\n # any) of their compute nodes meaning said compute nodes will not\n # be reporting PCPUs yet. This is okay to do because the\n # NUMATopologyFilter (scheduler) or virt driver (compute node) will\n # weed out hosts that are actually using new style configuration\n # but simply don't have enough free PCPUs (or any PCPUs).\n # TODO(stephenfin): Remove when we drop support for 'vcpu_pin_set'\n if (\n resources.cpu_pinning_requested and\n not CONF.workarounds.disable_fallback_pcpu_query\n ):\n LOG.debug(\n 'Requesting fallback allocation candidates with '\n 'VCPU instead of PCPU'\n )\n resources = utils.resources_from_request_spec(\n context, spec_obj, self.host_manager,\n enable_pinning_translate=False)\n res = self.placement_client.get_allocation_candidates(\n context, resources)\n if res:\n # merge the allocation requests and provider summaries from\n # the two requests together\n alloc_reqs_fallback, provider_summaries_fallback, _ = res\n\n alloc_reqs.extend(alloc_reqs_fallback)\n provider_summaries.update(provider_summaries_fallback)\n\n if not alloc_reqs:\n LOG.info(\n \"Got no allocation candidates from the Placement API. \"\n \"This could be due to insufficient resources or a \"\n \"temporary occurrence as compute nodes start up.\"\n )\n raise exception.NoValidHost(reason=\"\")\n\n # Build a dict of lists of allocation requests, keyed by\n # provider UUID, so that when we attempt to claim resources for\n # a host, we can grab an allocation request easily\n alloc_reqs_by_rp_uuid = collections.defaultdict(list)\n for ar in alloc_reqs:\n for rp_uuid in ar['allocations']:\n alloc_reqs_by_rp_uuid[rp_uuid].append(ar)\n\n # Only return alternates if both return_objects and return_alternates\n # are True.\n return_alternates = return_alternates and return_objects\n\n selections = self._select_destinations(\n context, spec_obj, instance_uuids, alloc_reqs_by_rp_uuid,\n provider_summaries, allocation_request_version, return_alternates)\n\n # If `return_objects` is False, we need to convert the selections to\n # the older format, which is a list of host state dicts.\n if not return_objects:\n selection_dicts = [sel[0].to_dict() for sel in selections]\n return jsonutils.to_primitive(selection_dicts)\n\n return selections",
"def guest_wizard(self):\n self.wiz_guest = wiz.PromptWizard(\n name=\"Guest Configuration for PVP and PVVP Scenarios\",\n description=\"Guest configurations\",\n steps=(\n wiz.WizardStep(\n id='image',\n name='Enter the Path for the iamge',\n help='Complete path where image resides',\n default='/home/opnfv/vloop-vnf-ubuntu-14.04_20160823.qcow2',\n ),\n wiz.WizardStep(\n id='mode',\n name='Enter the forwarding mode to use',\n help='one of io|mac|mac_retry|macswap|flowgen|rxonly|....',\n default='io',\n ),\n wiz.WizardStep(\n id='smp',\n name='Number of SMP to use?',\n help='While Spawning the guest, how many SMPs to use?',\n default='2',\n ),\n wiz.WizardStep(\n id='cores',\n name=\"Guest Core binding. For 2 cores a & b: ['a', 'b']\",\n help='Enter the cores to use in the specified format',\n default=\"['8', '9']\",\n ),\n )\n )",
"def test_hosting_subscription_security_on_partition_with_destroyed(self):\n\n sequence_list = SequenceList()\n sequence_string = self.prepare_destroyed_computer_partition + \\\n \"\"\"\n LoginDefaultUser\n CheckComputerPartitionInstanceSetupSalePackingListDelivered\n CheckComputerPartitionInstanceHostingSalePackingListDelivered\n CheckComputerPartitionInstanceCleanupSalePackingListDelivered\n\n # Marked busy in order to simulate previous wrong behaviour\n MarkBusyComputerPartition\n Tic\n\n UpdateLocalRolesOnComputerPartition\n Tic\n\n # All related packing lists are delivered, so no local roles for\n # Hosting Subscription shall be defined\n CheckNoHostingSubscriptionComputerPartitionLocalRoles\n Logout\n\n LoginERP5TypeTestCase\n CheckSiteConsistency\n Logout\n \"\"\"\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def accept_vendor_offer(request):\n if request.user.is_vendor:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n try:\n vendor_offer = VendorOffer.objects.get(pk=request.data['vendor_offer'])\n except VendorOffer.DoesNotExist:\n return Response({'errors': 'No Vendor Offer with ID ' + request.data.vendor_offer}, status=status.HTTP_400_BAD_REQUEST)\n\n print_job = vendor_offer.print_job\n print_job.accepted_vendor_offer = vendor_offer\n print_job.save()\n\n return Response(status=status.HTTP_204_NO_CONTENT)",
"def run_guestwiz(self):\n if self.main_values['guest'] == 'YES':\n self.guest_wizard()\n self.guest_values = self.wiz_guest.run(self.shell)",
"def attemptPurchases(order):\n print(\"\\n\")\n # here we sort out the availability zones\n hasOrdersAssigned = True\n\n for az in order.AvailabilityZones:\n if az.ordered is None:\n az.ordered = 0\n if az.Number is None:\n hasOrdersAssigned = False\n\n if hasOrdersAssigned == False:\n remainder = int(order.Number) % len(order.AvailabilityZones)\n eachOrderGets = int((int(order.Number) - remainder) /\n len(order.AvailabilityZones))\n # here we assign all the orders\n for az in order.AvailabilityZones:\n az.Number = eachOrderGets\n if remainder != 0:\n az.Number += 1\n remainder -= 1\n\n # this client can be used for all the az's\n print(order.Region)\n client = boto3.client('ec2', region_name=order.Region,aws_access_key_id=order.aws_access_key_id,aws_secret_access_key=order.aws_secret_access_key)\n for az in order.AvailabilityZones:\n\n # for each AZ we're buying from\n kwargs = order.getKwargs(az.Name)\n response = client.describe_reserved_instances_offerings(**kwargs)\n ReservedInstancesOfferings = response[\"ReservedInstancesOfferings\"]\n\n # we search for all instance types, not just fixed or hourly, then sort when we recieve results\n # do the sorting of the reserved instances by price, cheapest first\n allOfferings = []\n\n # get all the offerings objects\n for instanceOffering in ReservedInstancesOfferings:\n # isFixed and isHourly completely filter out or in whether or not those instance types get included\n # if both are true, then all types of instances get included regardless of payment type\n\n # for limits, 0 means no limit, everything else abides by the limit\n\n iOffering = getInstanceOffering(instanceOffering)\n fixedPrice = iOffering.FixedPrice\n recurringAmount = iOffering.RecurringAmount\n fixedPriceExists = False\n recurringAmountExists = False\n\n if fixedPrice is not None and fixedPrice != 0:\n fixedPriceExists = True\n if recurringAmount is not None and recurringAmount != 0:\n recurringAmountExists = True\n\n MaxFixedPrice = 0\n if order.MaxFixedPrice is not None:\n MaxFixedPrice = order.MaxFixedPrice\n\n MaxRecurringPrice = 0\n if order.MaxHourlyPrice is not None:\n MaxRecurringPrice = order.MaxHourlyPrice\n\n if order.isFixedPrice == True and order.isHourlyPrice == True:\n # either hourly or fixed or both\n if fixedPriceExists and recurringAmountExists:\n if (MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice) and (MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice):\n allOfferings.append(iOffering)\n elif fixedPriceExists:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n elif recurringAmountExists:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n elif order.isFixedPrice == True:\n # only fixed price servers\n if fixedPriceExists and recurringAmountExists == False:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n\n elif order.isHourlyPrice == True:\n # only hourly servers\n if recurringAmountExists and fixedPriceExists == False:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n # sort into cost effectiveness, and these all have the correct AZ\n allOfferings.sort(key=lambda x: x.EffectiveHourlyRate)\n\n # print(order.Number)\n if order.Number is not None and order.Number > 0:\n if order.ordered is None:\n # brand new order bring it up to speed\n order.ordered = 0\n\n if az.ordered >= az.Number:\n print(\"AZ\", az.Name, \"has already been fulfilled with\",\n az.ordered, \"instances\")\n # buy until finished\n purchasedJustNow = 0\n previouslyPurchased = az.ordered\n for instanceOffering in allOfferings:\n # instanceOffering.print()\n # also we might want to write to the file, like keep it open, and update it for each order bought\n # something might go wrong\n # print(instanceOffering, \"\\n\")\n if order.ordered < order.Number and az.ordered < az.Number:\n # do purchase\n order.ordered += 1\n az.ordered += 1\n purchasedJustNow += 1\n instance = allOfferings.pop(0)\n kwargs = instance.getKwargs(order.DryRun)\n response = None\n try:\n response = client.purchase_reserved_instances_offering(\n **kwargs)\n print(response)\n except:\n pass\n print(\"Just Purchased:\")\n instanceOffering.print()\n order.PurchasedInstances.append(instanceOffering)\n\n if order.ordered >= order.Number or az.ordered >= az.Number:\n break\n\n print(purchasedJustNow,\n \"Reserved Instances were just purchased for:\", az.Name)\n print(previouslyPurchased, \"instances had been purchased previously\")\n if az.ordered >= az.Number:\n print(\"Purchased all\", az.ordered,\n \"Reserved Instances for:\", az.Name, \"\\n\")\n else:\n print(\"Still need\", int(az.Number - az.ordered), \"instances for availability zone:\",\n az.Name, \", will attempt to purchase the rest during the next run\", \"\\n\")\n\n if order.ordered >= order.Number:\n print(\"Purchased all\", order.ordered,\n \"Reserved Instances for this order\\n\\n\")\n else:\n print(\"Could only purchase\", order.ordered,\n \"Reserved Instances for this order, will attempt to purchase the rest at a later date.\\n\\n\")\n return",
"def select_hosts(self, context, request_spec, filter_properties):\n instance_uuids = request_spec.get('instance_uuids')\n hosts = [host.obj.host for host in self._schedule(context, request_spec, filter_properties, instance_uuids)]\n if not hosts:\n raise exception.NoValidHost(reason=\"\")\n return hosts",
"def purchase_scheduled_instances(DryRun=None, ClientToken=None, PurchaseRequests=None):\n pass",
"def view_appointment(self):\n stage = 0\n while True:\n Parser.print_clean()\n while stage == 0:\n print(f\"Viewing confirmed appointments for GP {self.username}.\")\n user_input = Parser.selection_parser(options={\"T\": \"View today's appointments\", \"D\": \"Select by Date\",\n \"--back\": \"to go back\"})\n if user_input == \"T\":\n selected_date = datetime.datetime.today().date()\n print(str(selected_date))\n stage = 1\n elif user_input == \"--back\":\n print(\"\\n\")\n return\n else:\n selected_date = Parser.date_parser(question=\"Select a Date:\")\n if selected_date == \"--back\":\n return\n else:\n stage = 1\n while stage == 1:\n bookings_result = SQLQuery(\"SELECT visit.BookingNo, visit.Timeslot, visit.NHSNo, users.firstName, \"\n \"users.lastName, visit.Confirmed FROM visit INNER JOIN users ON \"\n \"visit.NHSNo = users.ID WHERE visit.StaffID = ? AND visit.Timeslot >= ? AND \"\n \"visit.Timeslot <= ? AND visit.Confirmed = 'T' ORDER BY visit.Timeslot ASC\")\\\n .fetch_all(decrypter=EncryptionHelper(), parameters=(self.ID, selected_date,\n selected_date + datetime.timedelta(days=1)))\n message = f\"for {selected_date.strftime('%Y-%m-%d')} (confirmed).\"\n booking_no = GP.print_select_bookings(bookings_result, message)\n if not booking_no:\n stage = 0\n else:\n GP.start_appointment(booking_no[1])",
"def get_details(self):\n try:\n return self.api_session.GetReservationDetails(self.id)\n except:\n err = \"Failed to get the Sandbox's details. Unexpected error: \" + str(sys.exc_info()[0])\n self.report_error(error_message=err)",
"def do_show_reservation_status (self, line):\n if self.trex.is_reserved():\n print \"T-Rex is reserved\"\n else:\n print \"T-Rex is NOT reserved\"\n print termstyle.green(\"*** End of reservation status prompt ***\")",
"def test_Computer_getSoftwareReleaseList_SetupResource_ConfirmedState(self):\n sequence_list = SequenceList()\n sequence_string = self.prepare_software_release_purchase_packing_list + '\\\n SlapLoginCurrentComputer \\\n CheckSuccessComputerGetSoftwareReleaseListCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def test_Computer_getSoftwareReleaseList_AccountingResource_DeliveredState(self):\n sequence_list = SequenceList()\n sequence_string = \\\n self.prepare_software_release_purchase_packing_list_accounting_resource + '\\\n LoginDefaultUser \\\n StartPurchasePackingList \\\n Tic \\\n StopPurchasePackingList \\\n Tic \\\n DeliverPurchasePackingList \\\n Tic \\\n Logout \\\n SlapLoginCurrentComputer \\\n CheckEmptyComputerGetSoftwareReleaseListCall \\\n SlapLogout \\\n LoginERP5TypeTestCase \\\n CheckSiteConsistency \\\n Logout \\\n '\n sequence_list.addSequenceString(sequence_string)\n sequence_list.play(self)",
"def test_hosts(self, mocker_request, mocker_res, mocker_client_id):\n from RiskSense import get_hosts_command\n mocker_client_id.return_value = CLIENT_DETAILS\n mocker_request.return_value = {\n \"size\": \"10\",\n \"projection\": \"detail\",\n \"filters\": [\n {\n \"operator\": \"EXACT\",\n \"field\": \"hostname\",\n \"value\": \"test-hostname\",\n \"exclusive\": \"false\"\n }\n ],\n \"page\": \"0\"\n }\n\n with open(\"./TestData/hosts_res.json\", encoding='utf-8') as f:\n expected_res = json.load(f)\n\n mocker_res.return_value = expected_res\n\n hr, ec, resp = get_hosts_command(self.client, {})\n\n with open(\"./TestData/hosts_ec.json\") as f:\n expected_ec = json.load(f)\n\n assert expected_res == resp\n assert expected_ec == ec"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Import single or multivolume disk images or EBS snapshots into an Amazon Machine Image (AMI). For more information, see Importing a VM as an Image Using VM Import/Export in the VM Import/Export User Guide .
|
def import_image(DryRun=None, Description=None, DiskContainers=None, LicenseType=None, Hypervisor=None, Architecture=None, Platform=None, ClientData=None, ClientToken=None, RoleName=None):
pass
|
[
"def import_instance(DryRun=None, Description=None, LaunchSpecification=None, DiskImages=None, Platform=None):\n pass",
"def image_import(self, image_name, url, image_meta, remote_host=None):\n image_info = []\n try:\n image_info = self._ImageDbOperator.image_query_record(image_name)\n except exception.SDKObjectNotExistError:\n msg = (\"The image record %s doens't exist in SDK image datebase,\"\n \" will import the image and create record now\" % image_name)\n LOG.info(msg)\n\n # Ensure the specified image is not exist in image DB\n if image_info:\n msg = (\"The image name %s has already exist in SDK image \"\n \"database, please check if they are same image or consider\"\n \" to use a different image name for import\" % image_name)\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=13, img=image_name)\n\n try:\n image_os_version = image_meta['os_version'].lower()\n target_folder = self._pathutils.create_import_image_repository(\n image_os_version, const.IMAGE_TYPE['DEPLOY'],\n image_name)\n except Exception as err:\n msg = ('Failed to create repository to store image %(img)s with '\n 'error: %(err)s, please make sure there are enough space '\n 'on zvmsdk server and proper permission to create the '\n 'repository' % {'img': image_name,\n 'err': six.text_type(err)})\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=14, msg=msg)\n\n if self.is_rhcos(image_os_version):\n image_disk_type = image_meta.get('disk_type')\n if ((image_disk_type is None) or\n ((image_disk_type.upper() != \"DASD\" and\n image_disk_type.upper() != \"SCSI\"))):\n msg = ('Disk type is required for RHCOS image import, '\n 'the value should be DASD or SCSI')\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=14, msg=msg)\n else:\n comments = {'disk_type': image_disk_type.upper()}\n comments = str(comments)\n else:\n comments = None\n\n try:\n import_image_fn = urlparse.urlparse(url).path.split('/')[-1]\n import_image_fpath = '/'.join([target_folder, import_image_fn])\n self._scheme2backend(urlparse.urlparse(url).scheme).image_import(\n image_name, url,\n import_image_fpath,\n remote_host=remote_host)\n\n # Check md5 after import to ensure import a correct image\n # TODO change to use query image name in DB\n expect_md5sum = image_meta.get('md5sum')\n real_md5sum = self._get_md5sum(import_image_fpath)\n if expect_md5sum and expect_md5sum != real_md5sum:\n msg = (\"The md5sum after import is not same as source image,\"\n \" the image has been broken\")\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=4)\n\n # After import to image repository, figure out the image type is\n # single disk image or multiple-disk image,if multiple disks image,\n # extract it, if it's single image, rename its name to be same as\n # specific vdev\n # TODO: (nafei) use sub-function to check the image type\n image_type = 'rootonly'\n if image_type == 'rootonly':\n final_image_fpath = '/'.join([target_folder,\n CONF.zvm.user_root_vdev])\n os.rename(import_image_fpath, final_image_fpath)\n elif image_type == 'alldisks':\n # For multiple disks image, extract it, after extract, the\n # content under image folder is like: 0100, 0101, 0102\n # and remove the image file 0100-0101-0102.tgz\n pass\n\n # TODO: put multiple disk image into consideration, update the\n # disk_size_units and image_size db field\n if not self.is_rhcos(image_os_version):\n disk_size_units = self._get_disk_size_units(final_image_fpath)\n else:\n disk_size_units = self._get_disk_size_units_rhcos(\n final_image_fpath)\n image_size = self._get_image_size(final_image_fpath)\n\n # TODO: update the real_md5sum field to include each disk image\n self._ImageDbOperator.image_add_record(image_name,\n image_os_version,\n real_md5sum,\n disk_size_units,\n image_size,\n image_type,\n comments=comments)\n LOG.info(\"Image %s is import successfully\" % image_name)\n except Exception:\n # Cleanup the image from image repository\n self._pathutils.clean_temp_folder(target_folder)\n raise",
"def import_snapshot(DryRun=None, Description=None, DiskContainer=None, ClientData=None, ClientToken=None, RoleName=None):\n pass",
"def cli(env, identifier, notes):\n\n iscsi_mgr = SoftLayer.ISCSIManager(env.client)\n iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, identifier, 'iSCSI')\n iscsi_mgr.create_snapshot(iscsi_id, notes)",
"def test_import_exiftool():\n cwd = os.getcwd()\n test_image_1 = os.path.join(cwd, TEST_IMAGE_1)\n runner = CliRunner()\n result = runner.invoke(\n import_cli,\n [\n \"--verbose\",\n \"--clear-metadata\",\n \"--exiftool\",\n test_image_1,\n ],\n terminal_width=TERMINAL_WIDTH,\n )\n\n assert result.exit_code == 0\n\n import_data = parse_import_output(result.output)\n file_1 = pathlib.Path(test_image_1).name\n uuid_1 = import_data[file_1]\n photo_1 = Photo(uuid_1)\n\n assert photo_1.filename == file_1\n assert photo_1.title == TEST_DATA[TEST_IMAGE_1][\"title\"]\n assert photo_1.description == TEST_DATA[TEST_IMAGE_1][\"description\"]\n assert photo_1.keywords == TEST_DATA[TEST_IMAGE_1][\"keywords\"]\n lat, lon = photo_1.location\n assert lat == approx(TEST_DATA[TEST_IMAGE_1][\"lat\"])\n assert lon == approx(TEST_DATA[TEST_IMAGE_1][\"lon\"])",
"def test_vm_create_from_image_vg_nic_ipam():\n results = []\n cluster_obj = prism.Cluster(api_client=_api())\n clusters = cluster_obj.get_all_uuids()\n vms_obj = prism.Vms(api_client=_api())\n for each_uuid in clusters:\n result = False\n vm_config = {\n 'name': 'api_test_v2_image_vg_nic_ipam_{0}'.format(random_string),\n 'cores': 1,\n 'memory_gb': 0.1,\n 'add_cdrom': True,\n 'power_state': 'off',\n 'disks': [\n {\n 'image_name': 'api_test_image1',\n },\n {\n 'volume_group_name': 'TEST_VG',\n },\n ],\n 'nics': [\n {\n 'network_name': '192.168.1.0',\n 'connect': True,\n 'ipam': True,\n }\n ]\n }\n\n result = vms_obj.create(clusteruuid=each_uuid, **vm_config)\n if result:\n vm_cleanup.append(vm_config['name'])\n results.append(result)\n assert all(results)",
"def vm_createimage(img_path: str, size_gb: int):\n subprocess.run(\"qemu-img create -f qcow2 -o compat=1.1,lazy_refcounts=on '{0}' {1}G\".format(img_path, size_gb), shell=True, check=True)",
"def AMI_builder(\n AWS_access_key_id,\n AWS_secret_access_key,\n region_name,\n base_image_id,\n os,\n security_group_id,\n AMI_name,\n RPM_package_version,\n APT_OSS_version,\n):\n try:\n instance = Instance(\n AWS_access_key_id=AWS_access_key_id,\n AWS_secret_access_key=AWS_secret_access_key,\n region_name=region_name,\n base_image_id=base_image_id,\n os=os, # ubuntu, amazonLinux\n security_group_id=security_group_id,\n AMI_name=AMI_name,\n RPM_package_version=RPM_package_version,\n APT_OSS_version=APT_OSS_version,\n )\n except Exception as err:\n logging.error(\"Could not bring up the instance. \" + str(err))\n sys.exit(-1)\n AMI_id = \"\"\n installation_failed = False\n try:\n instance.wait_until_ready()\n except Exception as err:\n logging.error(\n \"Could not bring the instance to ready state. \" + str(err))\n installation_failed = True\n else:\n try:\n instance.install_ODFE()\n AMI_id = instance.create_AMI()\n except Exception as err:\n installation_failed = True\n logging.error(\n \"AMI creation failed there was an error see the logs. \" + str(err))\n finally:\n try:\n instance.cleanup_instance()\n except Exception as err:\n logging.error(\n \"Could not cleanup the instance. There could be an instance currently running, terminate it. \" + str(err))\n installation_failed = True\n if installation_failed:\n sys.exit(-1)\n # copy the AMI to the required regions\n ec2_client = boto3.client(\n \"ec2\",\n aws_access_key_id=AWS_access_key_id,\n aws_secret_access_key=AWS_secret_access_key,\n region_name=region_name,\n )\n AMI_copy_regions = [region[\"RegionName\"]\n for region in ec2_client.describe_regions()[\"Regions\"]]\n AMI_copy_regions.remove(region_name) # since AMI is created here\n copy_AMI_to_regions(\n AWS_access_key_id=AWS_access_key_id,\n AWS_secret_access_key=AWS_secret_access_key,\n AMI_id=AMI_id,\n AMI_name=AMI_name,\n AMI_source_region=region_name,\n AMI_copy_regions=AMI_copy_regions,\n )",
"def _prepare_iso_image_on_host(self, context, instance, local_img_dir,\n host_dir, image_meta):\n pvm_op = self.pvm_operator\n\n # Check if media library exists. Error out if it's not there.\n if not pvm_op.check_media_library_exists():\n LOG.error(_(\"There is no media library\"))\n raise exception.IBMPowerVMMediaLibraryNotAvailable()\n\n # Create vopt with name being the glance ID/UUID.\n vopt_img_name = image_meta['id']\n if not pvm_op.check_vopt_exists(name=vopt_img_name):\n\n # check for space within CONF.powervm_img_local_path\n self._check_space(local_img_dir, image_meta['size'])\n\n # It's not VIOS yet:\n # Check available space in IVM staging area and media repository\n free_space = pvm_op.get_vopt_size()\n free_padmin_space = pvm_op.get_staging_size(host_dir)\n\n free_rep_mb = int(free_space[0])\n free_staging_mb = int(free_padmin_space[0]) / 1024\n iso_size_mb = image_meta['size'] / (1024 * 1024)\n\n LOG.debug(\"Free repository space: %s MB\" % free_rep_mb)\n LOG.debug(\"Free VIOS staging space: %s MB\" % free_staging_mb)\n LOG.debug(\"ISO file size: %s MB\" % iso_size_mb)\n\n if iso_size_mb > free_rep_mb:\n raise common_ex.IBMPowerVMMediaRepOutOfSpace(\n size=iso_size_mb, free=free_rep_mb)\n\n if iso_size_mb > free_staging_mb:\n raise exception.IBMPowerVMStagingAreaOutOfSpace(\n dir=host_dir, size=iso_size_mb, free=free_staging_mb)\n\n # Fetch ISO from Glance\n\n file_path = '%s/%s.%s.%s' % (local_img_dir,\n image_meta['id'],\n CONF.host,\n image_meta['disk_format'])\n LOG.debug(\"Fetching image '%(img-name)s' from glance \"\n \"to %(img-path)s\" %\n {'img-name': image_meta['name'],\n 'img-path': file_path})\n images.fetch(context, image_meta['id'], file_path,\n instance['user_id'],\n instance['project_id'])\n if (os.path.isfile(file_path)):\n # transfer ISO to VIOS\n try:\n\n iso_remote_path, iso_size = self.\\\n _copy_image_file(file_path,\n host_dir,\n context,\n image_meta)\n\n self.pvm_operator.create_vopt_device(\n vopt_img_name, iso_remote_path)\n # The create vopt device command copies\n # the ISO into the media repository. The file at\n # iso_remote_path can be removed now.\n try:\n self.pvm_operator.remove_ovf_env_iso(\n iso_remote_path)\n except (exception.IBMPowerVMCommandFailed, Exception) as e:\n msg = (_('Error cleaning up ISO:'\n ' %(iso_remote_path)s') %\n locals())\n LOG.exception(msg)\n raise e\n finally:\n os.remove(file_path)\n else:\n raise exception.IBMPowerVMISOFileNotFound(\n ISO_file=file_path)\n else:\n LOG.debug(\"Image with id %s already on VIOS.\" % image_meta['id'])\n\n return vopt_img_name",
"def _prepare_iso_image_on_host(self, context, instance, local_img_dir,\n host_dir, image_meta):\n pvm_op = self.pvm_operator\n\n # Check if media library exists. Error out if it's not there.\n if not pvm_op.check_media_library_exists():\n LOG.error(_(\"There is no media library\"))\n raise exception.IBMPowerVMMediaLibraryNotAvailable()\n\n # Create vopt with name being the glance ID/UUID.\n vopt_img_name = image_meta['id']\n if not pvm_op.check_vopt_exists(name=vopt_img_name):\n # check for space within CONF.powervm_img_local_path\n self._check_space(local_img_dir, image_meta['size'])\n\n # It's not VIOS yet:\n # Check available space in IVM staging area and media repository\n free_space = pvm_op.get_vopt_size()\n free_padmin_space = pvm_op.get_staging_size(host_dir)\n\n free_rep_mb = int(free_space[0])\n free_staging_mb = int(free_padmin_space[0]) / 1024\n iso_size_mb = image_meta['size'] / (1024 * 1024)\n\n LOG.debug(\"Free repository space: %s MB\" % free_rep_mb)\n LOG.debug(\"Free VIOS staging space: %s MB\" % free_staging_mb)\n LOG.debug(\"ISO file size: %s MB\" % iso_size_mb)\n\n if iso_size_mb > free_rep_mb:\n raise common_ex.IBMPowerVMMediaRepOutOfSpace(\n size=iso_size_mb, free=free_rep_mb)\n\n if iso_size_mb > free_staging_mb:\n raise exception.IBMPowerVMStagingAreaOutOfSpace(\n dir=host_dir, size=iso_size_mb, free=free_staging_mb)\n\n # Fetch ISO from Glance\n\n file_path = '%s/%s.%s.%s' % (local_img_dir,\n image_meta['id'],\n CONF.host,\n image_meta['disk_format'])\n LOG.debug(\"Fetching image '%(img-name)s' from glance \"\n \"to %(img-path)s\" %\n {'img-name': image_meta['name'],\n 'img-path': file_path})\n images.fetch(context, image_meta['id'], file_path,\n instance['user_id'],\n instance['project_id'])\n if (os.path.isfile(file_path)):\n # transfer ISO to VIOS\n try:\n\n iso_remote_path, iso_size = self.copy_image_file(file_path,\n host_dir)\n\n self.pvm_operator.create_vopt_device(\n vopt_img_name, iso_remote_path)\n # The create vopt device command copies\n # the ISO into the media repository. The file at\n # iso_remote_path can be removed now.\n try:\n self.pvm_operator.remove_ovf_env_iso(iso_remote_path)\n except Exception:\n msg = (_('Error cleaning up ISO:'\n ' %(iso_remote_path)s') %\n locals())\n LOG.exception(msg)\n finally:\n os.remove(file_path)\n else:\n raise exception.IBMPowerVMISOFileNotFound(\n ISO_file=file_path)\n else:\n LOG.debug(\"Image with id %s already on VIOS.\"\n % image_meta['id'])\n\n return vopt_img_name",
"def snapshot(self, context, instance, image_id, update_task_state):\n vm_ref = vm_util.get_vm_ref(self._session, instance)\n\n def _get_vm_and_vmdk_attribs():\n # Get the vmdk info that the VM is pointing to\n vmdk = vm_util.get_vmdk_info(self._session, vm_ref,\n instance.uuid)\n if not vmdk.path:\n LOG.debug(\"No root disk defined. Unable to snapshot.\",\n instance=instance)\n raise error_util.NoRootDiskDefined()\n\n lst_properties = [\"datastore\", \"summary.config.guestId\"]\n props = self._session._call_method(vutil,\n \"get_object_properties_dict\",\n vm_ref,\n lst_properties)\n os_type = props['summary.config.guestId']\n datastores = props['datastore']\n return (vmdk, datastores, os_type)\n\n vmdk, datastores, os_type = _get_vm_and_vmdk_attribs()\n ds_ref = datastores.ManagedObjectReference[0]\n dc_info = self.get_datacenter_ref_and_name(ds_ref)\n\n update_task_state(task_state=task_states.IMAGE_PENDING_UPLOAD)\n\n # TODO(vui): convert to creating plain vm clone and uploading from it\n # instead of using live vm snapshot.\n\n snapshot_ref = None\n\n snapshot_vm_ref = None\n\n try:\n # If we do linked clones, we need to have a snapshot\n if CONF.vmware.clone_from_snapshot or not\\\n CONF.vmware.full_clone_snapshots:\n snapshot_ref = self._create_vm_snapshot(instance, vm_ref,\n image_id=image_id)\n\n if not CONF.vmware.full_clone_snapshots:\n disk_move_type = \"createNewChildDiskBacking\"\n else:\n disk_move_type = None\n\n snapshot_vm_ref = self._create_vm_clone(instance,\n vm_ref,\n snapshot_ref,\n dc_info,\n disk_move_type=disk_move_type,\n image_id=image_id,\n disks=[vmdk])\n\n update_task_state(task_state=task_states.IMAGE_UPLOADING,\n expected_state=task_states.IMAGE_PENDING_UPLOAD)\n images.upload_image_stream_optimized(\n context, image_id, instance, self._session, vm=snapshot_vm_ref,\n vmdk_size=vmdk.capacity_in_bytes)\n finally:\n if snapshot_vm_ref:\n vm_util.destroy_vm(self._session, instance, snapshot_vm_ref)\n # Deleting the snapshot after destroying the temporary VM created\n # based on it allows the instance vm's disks to be consolidated.\n # TODO(vui) Add handling for when vmdk volume is attached.\n if snapshot_ref:\n self._delete_vm_snapshot(instance, vm_ref, snapshot_ref)",
"def test_copy_vm_disks_with_snapshot(self, storage):\n testflow.step(\"Taking snapshot of VM %s\", self.vm_name)\n assert ll_vms.addSnapshot(\n True, self.vm_name, self.snapshot_description\n ), (\"Failed to create snapshot for vm %s\" % self.vm_name)\n ll_jobs.wait_for_jobs([config.JOB_CREATE_SNAPSHOT])\n\n self.basic_copy(self.vm_name)\n helpers.attach_new_disks_to_vm(self.test_vm_name, self.new_disks)\n assert helpers.check_file_existence(\n self.test_vm_name, storage_type=storage\n )",
"def test_import_exiftool_video():\n cwd = os.getcwd()\n test_image_1 = os.path.join(cwd, TEST_VIDEO_1)\n runner = CliRunner()\n result = runner.invoke(\n import_cli,\n [\n \"--verbose\",\n \"--clear-metadata\",\n \"--exiftool\",\n test_image_1,\n ],\n terminal_width=TERMINAL_WIDTH,\n )\n\n assert result.exit_code == 0\n\n import_data = parse_import_output(result.output)\n file_1 = pathlib.Path(test_image_1).name\n uuid_1 = import_data[file_1]\n photo_1 = Photo(uuid_1)\n\n assert photo_1.filename == file_1\n assert photo_1.title == TEST_DATA[TEST_VIDEO_1][\"title\"]\n assert photo_1.description == TEST_DATA[TEST_VIDEO_1][\"description\"]\n assert photo_1.keywords == TEST_DATA[TEST_VIDEO_1][\"keywords\"]\n lat, lon = photo_1.location\n assert lat == approx(TEST_DATA[TEST_VIDEO_1][\"lat\"])\n assert lon == approx(TEST_DATA[TEST_VIDEO_1][\"lon\"])",
"def just_import(ova):\n name = os.path.split(ova)[1].split('.')[0]\n v_machine = VirtualMachine(name)\n # This must throw exception if such VM already exists.\n try:\n v_machine.checkvm()\n except VirtualMachineExistsError:\n print(\"WARNING: %s already exists. Skipping...\" % name)\n else:\n v_machine.importvm(ova)\n return name",
"def import_image(imgfn):\n r = rio.open(imgfn)\n metadata = r.meta.copy()\n img = r.read()\n \n return img, metadata",
"def test_import_exiftool_video_no_metadata():\n cwd = os.getcwd()\n test_image_1 = os.path.join(cwd, TEST_VIDEO_2)\n runner = CliRunner()\n result = runner.invoke(\n import_cli,\n [\n \"--verbose\",\n \"--clear-metadata\",\n \"--exiftool\",\n test_image_1,\n ],\n terminal_width=TERMINAL_WIDTH,\n )\n\n assert result.exit_code == 0\n\n import_data = parse_import_output(result.output)\n file_1 = pathlib.Path(test_image_1).name\n uuid_1 = import_data[file_1]\n photo_1 = Photo(uuid_1)\n\n assert photo_1.filename == file_1\n assert photo_1.title == \"\"\n assert photo_1.description == \"\"\n assert photo_1.keywords == []\n lat, lon = photo_1.location\n assert lat is None\n assert lon is None",
"def test_copy_image_to_volume(self):\n self.mox.StubOutWithMock(image_utils, 'fetch_to_raw')\n\n image_utils.fetch_to_raw(context,\n self.TEST_IMAGE_SERVICE,\n self.TEST_IMAGE_ID,\n self.TEST_VOLPATH,\n mox_lib.IgnoreArg(),\n size=self.TEST_VOLSIZE)\n\n self.mox.ReplayAll()\n\n self._driver.copy_image_to_volume(context,\n self.TEST_VOLUME,\n self.TEST_IMAGE_SERVICE,\n self.TEST_IMAGE_ID)",
"def import_images(config, env_names):\n for args in _get_args(config, env_names):\n ImageImporter.do_import(*args)",
"def test_remote_import(self):\n self._require_import_method('glance-direct')\n\n if not CONF.image.alternate_image_endpoint:\n raise self.skipException('No image_remote service to test '\n 'against')\n\n image_id = self._stage_and_check()\n # import image from staging to backend, but on the alternate worker\n self.os_primary.image_client_remote.image_import(\n image_id, method='glance-direct')\n waiters.wait_for_image_imported_to_stores(self.client, image_id)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates an import instance task using metadata from the specified disk image. ImportInstance only supports singlevolume VMs. To import multivolume VMs, use ImportImage . For more information, see Importing a Virtual Machine Using the Amazon EC2 CLI . For information about the import manifest referenced by this API action, see VM Import Manifest .
|
def import_instance(DryRun=None, Description=None, LaunchSpecification=None, DiskImages=None, Platform=None):
pass
|
[
"def import_task(self, img, cont, img_format=None, img_name=None):\r\n return self._tasks_manager.create(\"import\", img=img, cont=cont,\r\n img_format=img_format, img_name=img_name)",
"def import_image(DryRun=None, Description=None, DiskContainers=None, LicenseType=None, Hypervisor=None, Architecture=None, Platform=None, ClientData=None, ClientToken=None, RoleName=None):\n pass",
"def import_snapshot(DryRun=None, Description=None, DiskContainer=None, ClientData=None, ClientToken=None, RoleName=None):\n pass",
"def create_instance_export_task(Description=None, InstanceId=None, TargetEnvironment=None, ExportToS3Task=None):\n pass",
"def process_docker_import(self, param_import):",
"def image_import(self, image_name, url, image_meta, remote_host=None):\n image_info = []\n try:\n image_info = self._ImageDbOperator.image_query_record(image_name)\n except exception.SDKObjectNotExistError:\n msg = (\"The image record %s doens't exist in SDK image datebase,\"\n \" will import the image and create record now\" % image_name)\n LOG.info(msg)\n\n # Ensure the specified image is not exist in image DB\n if image_info:\n msg = (\"The image name %s has already exist in SDK image \"\n \"database, please check if they are same image or consider\"\n \" to use a different image name for import\" % image_name)\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=13, img=image_name)\n\n try:\n image_os_version = image_meta['os_version'].lower()\n target_folder = self._pathutils.create_import_image_repository(\n image_os_version, const.IMAGE_TYPE['DEPLOY'],\n image_name)\n except Exception as err:\n msg = ('Failed to create repository to store image %(img)s with '\n 'error: %(err)s, please make sure there are enough space '\n 'on zvmsdk server and proper permission to create the '\n 'repository' % {'img': image_name,\n 'err': six.text_type(err)})\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=14, msg=msg)\n\n if self.is_rhcos(image_os_version):\n image_disk_type = image_meta.get('disk_type')\n if ((image_disk_type is None) or\n ((image_disk_type.upper() != \"DASD\" and\n image_disk_type.upper() != \"SCSI\"))):\n msg = ('Disk type is required for RHCOS image import, '\n 'the value should be DASD or SCSI')\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=14, msg=msg)\n else:\n comments = {'disk_type': image_disk_type.upper()}\n comments = str(comments)\n else:\n comments = None\n\n try:\n import_image_fn = urlparse.urlparse(url).path.split('/')[-1]\n import_image_fpath = '/'.join([target_folder, import_image_fn])\n self._scheme2backend(urlparse.urlparse(url).scheme).image_import(\n image_name, url,\n import_image_fpath,\n remote_host=remote_host)\n\n # Check md5 after import to ensure import a correct image\n # TODO change to use query image name in DB\n expect_md5sum = image_meta.get('md5sum')\n real_md5sum = self._get_md5sum(import_image_fpath)\n if expect_md5sum and expect_md5sum != real_md5sum:\n msg = (\"The md5sum after import is not same as source image,\"\n \" the image has been broken\")\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=4)\n\n # After import to image repository, figure out the image type is\n # single disk image or multiple-disk image,if multiple disks image,\n # extract it, if it's single image, rename its name to be same as\n # specific vdev\n # TODO: (nafei) use sub-function to check the image type\n image_type = 'rootonly'\n if image_type == 'rootonly':\n final_image_fpath = '/'.join([target_folder,\n CONF.zvm.user_root_vdev])\n os.rename(import_image_fpath, final_image_fpath)\n elif image_type == 'alldisks':\n # For multiple disks image, extract it, after extract, the\n # content under image folder is like: 0100, 0101, 0102\n # and remove the image file 0100-0101-0102.tgz\n pass\n\n # TODO: put multiple disk image into consideration, update the\n # disk_size_units and image_size db field\n if not self.is_rhcos(image_os_version):\n disk_size_units = self._get_disk_size_units(final_image_fpath)\n else:\n disk_size_units = self._get_disk_size_units_rhcos(\n final_image_fpath)\n image_size = self._get_image_size(final_image_fpath)\n\n # TODO: update the real_md5sum field to include each disk image\n self._ImageDbOperator.image_add_record(image_name,\n image_os_version,\n real_md5sum,\n disk_size_units,\n image_size,\n image_type,\n comments=comments)\n LOG.info(\"Image %s is import successfully\" % image_name)\n except Exception:\n # Cleanup the image from image repository\n self._pathutils.clean_temp_folder(target_folder)\n raise",
"def import_target(device_type, path, pacemaker_ha_operation):\n blockdevice = BlockDevice(device_type, path)\n\n error = blockdevice.import_(False)\n if error:\n if '-f' in error and pacemaker_ha_operation:\n error = blockdevice.import_(True)\n\n if error:\n console_log.error(\"Error importing pool: '%s'\", error)\n\n return agent_ok_or_error(error)",
"def _import_dag(dag, catalogue, collection=None, **kwargs):\n step_names = [\"read\", \"update_model\", \"compare\", \"upload\", \"apply_events\"]\n return _workflow(dag, \"import\", step_names, catalogue, collection, **kwargs)",
"def prepare_instance(self, task):\n node = task.node\n\n boot_option = deploy_utils.get_boot_option(node)\n\n self.clean_up_instance(task)\n\n remote_image_server = node.driver_info.get('remote_image_server')\n remote_image_share_root = node.driver_info.get(\n 'remote_image_share_root')\n\n remote_server_data = {}\n remote_server_data['remote_image_share_type'] = (\n node.driver_info.get('remote_image_share_type'))\n remote_server_data['remote_image_user_name'] = (\n node.driver_info.get('remote_image_user_name', None))\n remote_server_data['remote_image_user_password'] = (\n node.driver_info.get('remote_image_user_password', None))\n\n # Need to enable secure boot, if being requested.\n # update_secure_boot_mode checks and enables secure boot only if the\n # deploy has requested secure boot\n sdflex_common.update_secure_boot_mode(task, True)\n iwdi = node.driver_internal_info.get('is_whole_disk_image')\n if boot_option == \"local\" or iwdi:\n self._set_boot_device(\n task, boot_devices.DISK, persistent=True)\n\n LOG.debug(\"Node %(node)s is set to permanently boot from local \"\n \"%(device)s\", {'node': task.node.uuid,\n 'device': boot_devices.DISK})\n return\n\n params = {}\n\n if boot_option != 'ramdisk':\n root_uuid = node.driver_internal_info.get('root_uuid_or_disk_id')\n\n if not root_uuid and task.driver.storage.should_write_image(task):\n LOG.warning(\n \"The UUID of the root partition could not be found for \"\n \"node %s. Booting instance from disk anyway.\", node.uuid)\n\n self._set_boot_device(\n task, boot_devices.DISK, persistent=True)\n\n return\n\n params.update(root_uuid=root_uuid)\n\n iso_ref = self._prepare_boot_iso(task, **params)\n\n url = (remote_server_data['remote_image_share_type'] + \"://\" +\n remote_image_server + \"/\" + remote_image_share_root + \"/\" +\n iso_ref)\n\n sdflex_common.eject_vmedia(task,\n vmedia_device)\n sdflex_common.insert_vmedia(task, url,\n vmedia_device,\n remote_server_data)\n\n boot_mode_utils.sync_boot_mode(task)\n\n self._set_boot_device(\n task, boot_devices.CD.value.lower(), persistent=True)\n\n LOG.debug(\"Node %(node)s is set to permanently boot from \"\n \"%(device)s\", {'node': task.node.uuid,\n 'device': boot_devices.CD})",
"def create_instance_from_image(self, my_image, zone):\n\n\t\t# Get the image requested\n\t\timage = self.compute.images().get(project=self.project, image=my_image).execute()\n\t\tsource_disk_image = image['selfLink']\n\t\t\n\t\t# Configure the machine\n\t\tmachine_type = 'zones/' + zone + '/machineTypes/f1-micro'\n\n\t\t# Read in the startup-script\n\t\tstartup_script = open('startup.sh', 'r').read()\n\n\t\t# Setup the config\n\t\tconfig = {\n\t\t\t'name': 'restserver-'+str(self.get_count_of_servers_with_name('restserver')),\n\t\t\t'machineType': machine_type,\n\n\t\t\t'tags': {\n\t\t\t\t'items': [\n\t\t\t\t\t'http-server',\n\t\t\t\t\t'https-server'\n\t\t\t\t]\n\t\t\t},\n\n\t\t\t# Specify the boot disk and the image to use as a source\n\t\t\t'disks': [\n\t\t\t\t{\n\t\t\t\t\t'boot': True,\n\t\t\t\t\t'autoDelete': True,\n\t\t\t\t\t'initializeParams': {\n\t\t\t\t\t\t'sourceImage': source_disk_image,\n\t\t\t\t\t},\n\t\t\t\t\t'deviceName':'restserver-'+str(self.get_count_of_servers_with_name('restserver'))\n\t\t\t\t}\n\t\t\t],\n\t\t\n\t\t\t# Specify a network interface with NAT to acces the public internet\n\t\t\t'networkInterfaces': [{\n\t\t\t\t'network': 'global/networks/default',\n\t\t\t\t'accessConfigs': [\n\t\t\t\t\t{'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}\n\t\t\t\t]\n\t\t\t}],\n\n\t\t\t# Allow the instance to acces cloud storage and logging\n\t\t\t'serviceAccounts': [{\n\t\t\t\t'email': 'default',\n\t\t\t\t'scopes': [\n\t\t\t\t\t'https://www.googleapis.com/auth/devstorage.read_write',\n\t\t\t\t\t'https://www.googleapis.com/auth/logging.write'\n\t\t\t\t]\n\t\t\t}],\n\n\t\t\t# Metadata is readable from the instance and allows you to pass configuration\n\t\t\t# from deployment scripts to instances\n\t\t\t'metadata': {\n\t\t\t\t'items': [{\n\t\t\t\t\t# Startup script is automatically executed by the instance upon startup\n\t\t\t\t\t'key': 'startup-script',\n\t\t\t\t\t'value': startup_script\n\t\t\t\t}]\n\t\t\t}\t\n\t\t}\n\t\n\t\t# Now create the instace and return it\n\t\treturn self.compute.instances().insert(project=self.project, zone=zone, body=config).execute()",
"def import_image_from_glance(request, storage):\n self = request.node.cls\n\n self.glance_template_name = getattr(\n self, 'glance_template_name',\n storage_helpers.create_unique_object_name(\n self.__name__, config.OBJECT_TYPE_TEMPLATE\n )\n )\n\n storage_domain = getattr(\n self, 'new_storage_domain', self.storage_domain\n )\n\n self.disk_alias = storage_helpers.create_unique_object_name(\n self.__name__, config.OBJECT_TYPE_DISK\n )\n\n import_as_template = getattr(self, 'import_as_template', True)\n cluster = getattr(self, 'cluster_name', config.CLUSTER_NAME)\n glance_image = getattr(self, 'image_name', config.GOLDEN_GLANCE_IMAGE)\n\n assert ll_sd.import_glance_image(\n config.GLANCE_DOMAIN, glance_image,\n target_storage_domain=storage_domain, target_cluster=cluster,\n new_disk_alias=self.disk_alias,\n new_template_name=self.glance_template_name,\n import_as_template=import_as_template, async=False\n ), \"\"\"Importing glance image %s from repository %s to storage\n domain %s failed\"\"\" % (\n storage_domain, config.GOLDEN_GLANCE_IMAGE, config.GLANCE_DOMAIN\n )\n\n ll_jobs.wait_for_jobs([config.JOB_IMPORT_IMAGE])\n ll_templates.waitForTemplatesStates([self.glance_template_name])\n # initialize for remove_templates fixture\n self.templates_names.append(self.glance_template_name)",
"def test_remote_import(self):\n self._require_import_method('glance-direct')\n\n if not CONF.image.alternate_image_endpoint:\n raise self.skipException('No image_remote service to test '\n 'against')\n\n image_id = self._stage_and_check()\n # import image from staging to backend, but on the alternate worker\n self.os_primary.image_client_remote.image_import(\n image_id, method='glance-direct')\n waiters.wait_for_image_imported_to_stores(self.client, image_id)",
"def launch_vm_on_network(tenant_name, vm_name, network_id):\n #pdb.set_trace()\n instance=None \n tenant_credentials = get_tenant_nova_credentials(tenant_name)\n \n nova = nvclient.Client(**tenant_credentials)\n nova.quotas.update(tenant_name, instances=-1, cores=-1, ram=-1, fixed_ips=-1, floating_ips=-1)\n with open('user.txt') as userdata:\n user_data = userdata.read()\n try:\n\timage_list=nova.images.find(name=\"ubuntu\")\n except NotFound:\n\tupload_image_glance()\n\n #for img in image:\n #if img.name == 'ubuntu':\n #print \"image found\"\n try:\n\n flavor = nova.flavors.find(name='traffic')\n except:\n flavor = nova.flavors.create(name=\"traffic\",ram=\"2048\",vcpus=\"1\",disk=\"10\")\n\n \n try:\n \n instance = nova.servers.create(name=vm_name, image=image_list,\n flavor=flavor,\n key_name=\"admin\",\n nics=[{'net-id': network_id}],userdata=user_data)\n except Exception:\n pass\n\n # Poll at 15 second intervals, until the status is no longer 'BUILD'\n print \" * Instance <%s> created on network <%s>: \"%(vm_name,str(network_id))\n status = instance.status\n while status == 'BUILD':\n time.sleep(15)\n # Retrieve the instance again so the status field updates\n instance = nova.servers.get(instance.id)\n status = instance.status\n\n print \" - Current status: %s\" % status\n if FLOATING_IP_CREATION:\n add_floating_ip_for_vm(tenant_name, instance)\n\n ins_data = {'instance_name': vm_name, 'status': status}\n return ins_data",
"def makeInstanceFromImage(self , imageid , initialconfig, instancename):\n chars = string.letters + string.digits\n length = 8\n createdata = \"name \" + instancename + \"\\n\" + \"cpu 1000\"+\"\\n\"+\"persistent true\"+\"\\n\"+\"password \"+(''.join(sample(chars,length)))+\"\\nmem 1024\"+\\\n \"\\nide:0:0 disk\"+\"\\nboot ide:0:0\"+\"\\nide:0:0 \"+imageid+\"\\nnic:0:model e1000\"+\"\\nnic:0:dhcp auto\"+\"\\nvnc auto\"+\"\\nsmp auto\";\n\n response = self.__EH.post(self.__hostname+\"/servers/create/stopped\" , data=createdata)\n if response.status_code != 200:\n logging.warning(\"!Unexpected status code returned by the ElasticHosts request: \" + str(response) + \" \" + str(response.text))\n logging.warning(\"Headers: %s \\n\" , str(response.request.headers) )\n response.raise_for_status()\n instanceid = response.json()[u'server']\n logging.info(\">>>>>>>>>>> New server \" + instancename + \"(\"+ instanceid +\") created\");\n return EHInstance.EHInstance(instanceid, self.__EH, self.__hostname)",
"def image_import(cls, image_name, url, target, **kwargs):\n source = urlparse.urlparse(url).path\n if kwargs['remote_host']:\n if '@' in kwargs['remote_host']:\n source_path = ':'.join([kwargs['remote_host'], source])\n command = ' '.join(['/usr/bin/scp',\n \"-P\", CONF.zvm.remotehost_sshd_port,\n \"-o StrictHostKeyChecking=no\",\n '-r ', source_path, target])\n (rc, output) = zvmutils.execute(command)\n if rc:\n msg = (\"Copying image file from remote filesystem failed\"\n \" with reason: %s\" % output)\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=10, err=output)\n else:\n msg = (\"The specified remote_host %s format invalid\" %\n kwargs['remote_host'])\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=11,\n rh=kwargs['remote_host'])\n else:\n LOG.debug(\"Remote_host not specified, will copy from local\")\n try:\n shutil.copyfile(source, target)\n except Exception as err:\n msg = (\"Import image from local file system failed\"\n \" with reason %s\" % six.text_type(err))\n LOG.error(msg)\n raise exception.SDKImageOperationError(rs=12,\n err=six.text_type(err))",
"def test_import_function_template():\n cwd = os.getcwd()\n test_image_1 = os.path.join(cwd, TEST_IMAGE_1)\n function = os.path.join(cwd, \"examples/template_function_import.py\")\n with TemporaryDirectory() as tempdir:\n test_image = shutil.copy(\n test_image_1, os.path.join(tempdir, \"MyAlbum_IMG_0001.jpg\")\n )\n runner = CliRunner()\n result = runner.invoke(\n import_cli,\n [\n \"--verbose\",\n \"--album\",\n \"{function:\" + function + \"::example}\",\n test_image,\n ],\n terminal_width=TERMINAL_WIDTH,\n )\n\n assert result.exit_code == 0\n\n import_data = parse_import_output(result.output)\n file_1 = pathlib.Path(test_image).name\n uuid_1 = import_data[file_1]\n photo_1 = Photo(uuid_1)\n\n assert photo_1.filename == file_1\n albums = [a.title for a in photo_1.albums]\n assert albums == [\"MyAlbum\"]",
"def make_task(\n name: str = '',\n run_name: str = '',\n install_script: str = '',\n instance_type: str = '',\n image_name: str = '',\n disk_size: int = 0,\n preemptible: Union[None, bool] = None,\n job: Job = None,\n task: backend.Task = None,\n create_resources=True,\n) -> Task:\n\n assert not preemptible, \"Not implemented\"\n\n def log(*_args):\n if task:\n task.log(*_args)\n else:\n util.log(*_args)\n\n # if name not specified, use name which is the same across script invocations for given image/instance-type\n name = maybe_create_name(name, instance_type, image_name)\n run_name = maybe_create_run_name(run_name, name)\n if run_name and job:\n assert run_name == job.run_.name, \"Provided Run object and run_name, but run_.name is {run_.name} while run_name is {run_name}\"\n\n if job is None:\n run_: backend.Run = backend.Run(run_name)\n else:\n run_ = job.run_\n\n if not instance_type:\n instance_type = os.environ.get('NCLUSTER_INSTANCE', 't3.micro')\n log(\"Using instance \" + instance_type)\n\n set_aws_environment()\n if create_resources:\n maybe_create_resources(task=task)\n else:\n pass\n\n placement_group = ''\n if u.instance_supports_placement_groups(instance_type):\n placement_group = run_.aws_placement_group_name\n # log(f\"Launching into placement group {placement_group}\")\n u.maybe_create_placement_group(placement_group)\n\n if not image_name:\n image_name = os.environ.get('NCLUSTER_IMAGE',\n 'amzn2-ami-hvm-2.0.20180622.1-x86_64-gp2')\n log(\"Using image \" + image_name)\n\n if preemptible is None:\n preemptible = os.environ.get('NCLUSTER_PREEMPTIBLE', False)\n preemptible = bool(preemptible)\n if preemptible:\n log(\"Using preemptible instances\")\n\n image = u.lookup_image(image_name)\n keypair = u.get_keypair()\n security_group = u.get_security_group()\n # subnet = u.get_subnet()\n ec2 = u.get_ec2_resource()\n\n instance = u.lookup_instance(name, instance_type,\n image_name)\n maybe_start_instance(instance)\n maybe_wait_for_initializing_instance(instance)\n\n # create the instance if not present\n if instance:\n log(f\"Reusing {instance}\")\n else:\n log(f\"Allocating {instance_type} for task {name}\")\n args = {'ImageId': image.id,\n 'InstanceType': instance_type,\n 'MinCount': 1,\n 'MaxCount': 1,\n 'SecurityGroupIds': [security_group.id],\n 'KeyName': keypair.name}\n\n args['TagSpecifications'] = [{\n 'ResourceType': 'instance',\n 'Tags': [{\n 'Key': 'Name',\n 'Value': name\n }]\n }]\n\n # args['NetworkInterfaces'] = [{'SubnetId': subnet.id,\n # 'DeviceIndex': 0,\n # 'AssociatePublicIpAddress': True,\n # 'Groups': [security_group.id]}]\n # placement_specs = {'AvailabilityZone': u.get_zone()}\n placement_specs = {}\n if placement_group:\n placement_specs['GroupName'] = placement_group\n\n args['Placement'] = placement_specs\n args['Monitoring'] = {'Enabled': True}\n\n if disk_size:\n assert disk_size > 0\n ebs = {\n 'VolumeSize': disk_size,\n 'VolumeType': 'gp2',\n }\n\n args['BlockDeviceMappings'] = [{\n 'DeviceName': '/dev/sda1',\n 'Ebs': ebs\n }]\n\n # Use high throughput disk (0.065/iops-month = about $1/hour)\n if 'NCLUSTER_AWS_FAST_ROOTDISK' in os.environ:\n assert not disk_size, f\"Specified both disk_size {disk_size} and $NCLUSTER_AWS_FAST_ROOTDISK, they are incompatible as $NCLUSTER_AWS_FAST_ROOTDISK hardwired disk size\"\n\n ebs = {\n 'VolumeSize': 500,\n 'VolumeType': 'io1',\n 'Iops': 11500\n }\n\n args['BlockDeviceMappings'] = [{\n 'DeviceName': '/dev/sda1',\n 'Ebs': ebs\n }]\n\n instances = []\n try:\n instances = ec2.create_instances(**args)\n except Exception as e:\n log(f\"Instance creation for {name} failed with ({e})\")\n log(\n \"You can change availability zone using export NCLUSTER_ZONE=...\")\n log(\"Terminating\")\n os.kill(os.getpid(),\n signal.SIGINT) # sys.exit() doesn't work inside thread\n\n assert instances, f\"ec2.create_instances returned {instances}\"\n log(f\"Allocated {len(instances)} instances\")\n instance = instances[0]\n\n task = Task(name, instance, # propagate optional args\n install_script=install_script,\n image_name=image_name,\n instance_type=instance_type)\n\n # have internal task/job/run hierarchy, in case of single task\n # manually initialize it\n if job is None:\n job = Job(name=name, run_=run_, tasks=[task])\n\n run_.jobs.append(job)\n\n return task",
"def just_import(ova):\n name = os.path.split(ova)[1].split('.')[0]\n v_machine = VirtualMachine(name)\n # This must throw exception if such VM already exists.\n try:\n v_machine.checkvm()\n except VirtualMachineExistsError:\n print(\"WARNING: %s already exists. Skipping...\" % name)\n else:\n v_machine.importvm(ova)\n return name",
"def startinstance(imagename, instance_type='m1.large'):\n if not settings.get_image(imagename):\n raise SystemExit(\"Invalid imagename '%s'\" % imagename)\n\n username, conn = _getbotoconn(auth_user)\n\n print \"starting an instance from the %s image under the %s account of \" \\\n \"type %s\" % \\\n (imagename, username, instance_type)\n\n username, accesskey, secretkey, pkname = settings.get_user(username)\n imagename, imageid = settings.get_image(imagename)\n\n image = conn.get_image(imageid)\n reservation = None\n if pkname:\n reservation = image.run(instance_type=instance_type, key_name=pkname)\n else:\n reservation = image.run(instance_type=instance_type)\n\n instance = reservation.instances[0]\n\n # The image has been started in the pending state, wait for it to transition\n # into the running state\n while True:\n if instance.update() == u'running':\n # [AN] it would be nice if the user knew it was still working\n break\n time.sleep(1)\n\n print \"\"\n print \"Instance started\"\n print \"DNS name: %s\" % instance.dns_name"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Imports the public key from an RSA key pair that you created with a thirdparty tool. Compare this with CreateKeyPair , in which AWS creates the key pair and gives the keys to you (AWS keeps a copy of the public key). With ImportKeyPair, you create the key pair and give AWS just the public key. The private key is never transferred between you and AWS. For more information about key pairs, see Key Pairs in the Amazon Elastic Compute Cloud User Guide .
|
def import_key_pair(DryRun=None, KeyName=None, PublicKeyMaterial=None):
pass
|
[
"def import_keypair(self, keypair: str) -> None:\n try:\n assert type(keypair) == str\n except AssertionError:\n print(\"Keypair not of type Str.\")\n return\n\n try:\n assert len(keypair) == 88\n except AssertionError:\n print(\"Keypair not of length 88\")\n return\n\n self.keypair = keypair\n self.public_key = keypair[:44]\n self.private_key = keypair[44:]\n pass",
"def get_keypair():\n public, private = rsa.newkeys(1024)\n return (private.save_pkcs1().decode('ascii'),\n public.save_pkcs1().decode('ascii'))",
"def generate_key_pair(self):\n assert self.public_key is None, 'This user already has a public key'\n assert self.private_key is None, 'This user already has a private key'\n key_pair = RSA.generate(NUM_KEY_BITS)\n self.private_key = key_pair.export_key().decode()\n self.public_key = key_pair.publickey().export_key().decode()",
"def pre_import_ssh_public_key(\n self,\n request: oslogin.ImportSshPublicKeyRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[oslogin.ImportSshPublicKeyRequest, Sequence[Tuple[str, str]]]:\n return request, metadata",
"def load_rsa_key(filename): \n\n return paramiko.RSAKey.from_private_key_file(prepend_home_dir(filename))",
"def add_key_pair(self, args):\n key_pair_name = args.key_pair_name\n # If we were provided with a private key file, we use that to generate the public\n # key using RSA. If not we will use the public key file (assuming the private key exists).\n key_file = args.private_key_file if args.private_key_file else args.public_key_file\n key_file_path = os.path.join(args.key_file_path, key_file)\n\n if not os.path.exists(key_file_path):\n raise YBOpsRuntimeError(\"Key: {} file not found\".format(key_file_path))\n\n # This call would throw a exception if the file is not valid key file.\n rsa_key = validated_key_file(key_file_path)\n\n # Validate the key pair if name already exists in AWS\n result = list(self.list_key_pair(args).values())[0]\n if len(result) > 0:\n # Try to validate the keypair with KeyPair fingerprint in AWS\n fingerprint = result[0][1]\n possible_fingerprints = self._generate_fingerprints(key_file_path)\n if fingerprint in possible_fingerprints:\n return False\n raise YBOpsRuntimeError(\"KeyPair {} already exists but fingerprint is invalid.\"\n .format(key_pair_name))\n\n result = {}\n for region, client in self._get_clients(args.region).items():\n result[region] = client.import_key_pair(\n KeyName=key_pair_name,\n PublicKeyMaterial=format_rsa_key(rsa_key, public_key=True)\n )\n return True",
"def import_pub_keys(self, receiver_name, receiver_public_keyring):\n self.public_keys[receiver_name] = receiver_public_keyring[receiver_name]",
"def get_key_pair(key_size=512):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=key_size,\n backend=default_backend()\n )\n public_key = private_key.public_key()\n return public_key, private_key",
"def key_upload(self, key=None):\n\n # The gey is stored in the database, we do not create a new keypair,\n # we upload our local key to aws\n # BUG name=None, wrong?\n # ~/.ssh/id_rsa.pub\n key_name = key[\"name\"]\n cloud = self.cloud\n Console.msg(f\"uploading the key: {key_name} -> {cloud}\")\n try:\n r = self.ec2_client.import_key_pair(KeyName=key_name,\n PublicKeyMaterial=key[\n 'public_key'])\n except ClientError as e:\n # Console.error(\"Key already exists\")\n VERBOSE(e)\n raise ValueError # this is raised because key.py catches valueerror\n return r",
"def get_public_key(private_key):\n return private_key.public_key()",
"def import_key(byteStream):\n content = None\n if isinstance(byteStream, bytes):\n content = byteStream\n else:\n with open(byteStream, \"rb\") as inputStream:\n content = inputStream.read()\n rsa_key = RSA.importKey(content)\n return rsa_key",
"def importprivkey(self, privkey, password=None):\n if not self.wallet.can_import_privkey():\n return (\n \"Error: This type of wallet cannot import private keys. Try to create a\"\n \" new wallet with that key.\"\n )\n try:\n addr = self.wallet.import_private_key(privkey, password)\n out = \"Keypair imported: \" + addr\n except Exception as e:\n out = \"Error: \" + str(e)\n return out",
"def import_public_ec_key_from_file(filename):\n public_key = import_public_key_from_pem_file(filename)\n if isinstance(public_key, ec.EllipticCurvePublicKey):\n return public_key\n else:\n return ValueError(\"Not a Elliptic Curve key\")",
"def post_import_ssh_public_key(\n self, response: oslogin.ImportSshPublicKeyResponse\n ) -> oslogin.ImportSshPublicKeyResponse:\n return response",
"def load_public_key( config, key_type, object_id ):\n key_path = conf.object_key_path( config, key_type, object_id, public=True )\n return read_public_key( key_path )",
"def generateKeyPair(cls):\n private_key = cls.PrivateKey.generate()\n public_key = private_key.public_key()\n return Key_Pair( cls, private_key, public_key )",
"def import_ec_key(pem_data):\n public_key = import_public_key_from_pem_data(pem_data)\n if isinstance(public_key, ec.EllipticCurvePublicKey):\n return public_key\n else:\n return ValueError(\"Not a Elliptic Curve key\")",
"def copy_with_public_key(self, pub_key):\n rc = RSA(self.keysize)\n rc.set_key_pair(pub_key, None)\n return rc",
"def put_key(\n self,\n slot: SLOT,\n private_key: Union[\n rsa.RSAPrivateKeyWithSerialization,\n ec.EllipticCurvePrivateKeyWithSerialization,\n ],\n pin_policy: PIN_POLICY = PIN_POLICY.DEFAULT,\n touch_policy: TOUCH_POLICY = TOUCH_POLICY.DEFAULT,\n ) -> None:\n slot = SLOT(slot)\n key_type = KEY_TYPE.from_public_key(private_key.public_key())\n check_key_support(self.version, key_type, pin_policy, touch_policy, False)\n ln = key_type.bit_len // 8\n numbers = private_key.private_numbers()\n if key_type.algorithm == ALGORITHM.RSA:\n numbers = cast(rsa.RSAPrivateNumbers, numbers)\n if numbers.public_numbers.e != 65537:\n raise NotSupportedError(\"RSA exponent must be 65537\")\n ln //= 2\n data = (\n Tlv(0x01, int2bytes(numbers.p, ln))\n + Tlv(0x02, int2bytes(numbers.q, ln))\n + Tlv(0x03, int2bytes(numbers.dmp1, ln))\n + Tlv(0x04, int2bytes(numbers.dmq1, ln))\n + Tlv(0x05, int2bytes(numbers.iqmp, ln))\n )\n else:\n numbers = cast(ec.EllipticCurvePrivateNumbers, numbers)\n data = Tlv(0x06, int2bytes(numbers.private_value, ln))\n if pin_policy:\n data += Tlv(TAG_PIN_POLICY, int2bytes(pin_policy))\n if touch_policy:\n data += Tlv(TAG_TOUCH_POLICY, int2bytes(touch_policy))\n\n logger.debug(\n f\"Importing key with pin_policy={pin_policy}, touch_policy={touch_policy}\"\n )\n self.protocol.send_apdu(0, INS_IMPORT_KEY, key_type, slot, data)\n logger.info(f\"Private key imported in slot {slot} of type {key_type}\")\n return key_type"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Imports a disk into an EBS snapshot.
|
def import_snapshot(DryRun=None, Description=None, DiskContainer=None, ClientData=None, ClientToken=None, RoleName=None):
pass
|
[
"def test_copy_vm_disks_with_snapshot(self, storage):\n testflow.step(\"Taking snapshot of VM %s\", self.vm_name)\n assert ll_vms.addSnapshot(\n True, self.vm_name, self.snapshot_description\n ), (\"Failed to create snapshot for vm %s\" % self.vm_name)\n ll_jobs.wait_for_jobs([config.JOB_CREATE_SNAPSHOT])\n\n self.basic_copy(self.vm_name)\n helpers.attach_new_disks_to_vm(self.test_vm_name, self.new_disks)\n assert helpers.check_file_existence(\n self.test_vm_name, storage_type=storage\n )",
"def create_disk_from_snapshot(compute, new_disk_name, snapshot_url, project, zone):\n\trequest_body = {\n\t\t\"kind\" : \"compute#disk\",\n\t\t\"name\" : new_disk_name,\n\t\t\"sourceSnapshot\" : snapshot_url\n\t}\n\ttry:\n\t\tbackup_logger.debug(\"Creating new disk with name %s from snapshot url %s\", new_disk_name, snapshot_url)\n\t\tresult = compute.disks().insert(project=project, zone=zone, body=request_body).execute()\n\texcept HttpError:\n\t\tbackup_logger.error(\"Error with HTTP Request made to create disk from snapshot\")\n\t\tsys.exit(1)\n\treturn result",
"def upload_disk_snapshot(disk_path):\n disk_snapshot_id = os.path.basename(disk_path)\n transfer_service = get_transfer_service(disk_snapshot_id)\n\n try:\n transfer = transfer_service.get()\n proxy_url = urlparse(transfer.proxy_url)\n proxy_connection = get_proxy_connection(proxy_url)\n path = disk_path\n\n # Set needed headers for uploading:\n upload_headers = {\n 'Authorization': transfer.signed_ticket,\n }\n\n with open(path, \"rb\") as disk:\n size = os.path.getsize(path)\n chunk_size = 1024 * 1024 * 8\n pos = 0\n while pos < size:\n # Extend the transfer session.\n transfer_service.extend()\n # Set the content range, according to the chunk being sent.\n upload_headers['Content-Range'] = \"bytes %d-%d/%d\" % (pos, min(pos + chunk_size, size) - 1, size)\n # Perform the request.\n proxy_connection.request(\n 'PUT',\n proxy_url.path,\n disk.read(chunk_size),\n headers=upload_headers,\n )\n # Print response\n r = proxy_connection.getresponse()\n print(r.status, r.reason, \"Completed\", \"{:.0%}\".format(pos / float(size)))\n # Continue to next chunk.\n pos += chunk_size\n\n print(\"Completed\", \"{:.0%}\".format(pos / float(size)))\n finally:\n # Finalize the session.\n transfer_service.finalize()\n\n # Waiting for finalize to complete\n try:\n while transfer_service.get():\n time.sleep(1)\n except sdk.NotFoundError:\n pass",
"def create_snapshot_of_disk(compute, disk_name, project, zone, body):\n\tbackup_logger.debug(\"Creating snapshot for disk %s\", disk_name)\n\ttry:\n\t\tresult = compute.disks().createSnapshot(disk=disk_name, project=project, zone=zone, body=body).execute()\n\texcept HttpError:\n\t\tbackup_logger.error(\"Error with HTTP Request made to create disk snapshot\")\n\t\tsys.exit(1)\n\treturn result",
"def start_import_load(self, context, path_to_iso, path_to_sig,\n import_type=None):\n loads = self.dbapi.load_get_list()\n\n active_load = cutils.get_active_load(loads)\n\n if import_type != constants.ACTIVE_LOAD_IMPORT:\n cutils.validate_loads_for_import(loads)\n\n current_version = active_load.software_version\n\n if not os.path.exists(path_to_iso):\n raise exception.SysinvException(_(\"Specified path not found %s\") %\n path_to_iso)\n\n if not os.path.exists(path_to_sig):\n raise exception.SysinvException(_(\"Specified path not found %s\") %\n path_to_sig)\n\n if not verify_files([path_to_iso], path_to_sig):\n raise exception.SysinvException(_(\"Signature %s could not be verified\") %\n path_to_sig)\n\n mounted_iso = None\n mntdir = tempfile.mkdtemp(dir='/tmp')\n # Attempt to mount iso\n try:\n mounted_iso = cutils.ISO(path_to_iso, mntdir)\n # Note: iso will be unmounted when object goes out of scope\n\n except subprocess.CalledProcessError:\n raise exception.SysinvException(_(\n \"Unable to mount iso\"))\n\n metadata_file_path = mntdir + '/upgrades/metadata.xml'\n\n if not os.path.exists(metadata_file_path):\n self._unmount_iso(mounted_iso, mntdir)\n raise exception.SysinvException(_(\"Metadata file not found\"))\n\n # Read in the metadata file\n try:\n metadata_file = open(metadata_file_path, 'r')\n root = ElementTree.fromstring(metadata_file.read())\n metadata_file.close()\n except Exception:\n self._unmount_iso(mounted_iso, mntdir)\n raise exception.SysinvException(_(\n \"Unable to read metadata file\"))\n\n new_version = root.findtext('version')\n committed_patches = []\n if import_type == constants.INACTIVE_LOAD_IMPORT:\n committed_patches = self._get_committed_patches_from_iso(new_version, mntdir)\n\n # unmount iso\n self._unmount_iso(mounted_iso, mntdir)\n\n if import_type == constants.ACTIVE_LOAD_IMPORT:\n if new_version != current_version:\n raise exception.SysinvException(\n _(\"Active version and import version must match (%s)\")\n % current_version)\n\n # return the matching (active) load in the database\n loads = self.dbapi.load_get_list()\n\n for load in loads:\n if load.software_version == new_version:\n break\n else:\n raise exception.SysinvException(\n _(\"Active load not found (%s)\") % current_version)\n\n return load\n\n elif import_type == constants.INACTIVE_LOAD_IMPORT:\n if LooseVersion(new_version) >= LooseVersion(current_version):\n raise exception.SysinvException(\n _(\"Inactive load (%s) must be an older load than the current active (%s).\")\n % (new_version, current_version))\n\n supported_versions = self._get_current_supported_upgrade_versions()\n is_version_upgradable = False\n\n for upgrade_path in supported_versions:\n if new_version == upgrade_path[\"version\"]:\n is_version_upgradable = True\n patches = upgrade_path['required_patch']\n for patch in patches:\n if patch not in committed_patches:\n is_version_upgradable = False\n break\n\n if not is_version_upgradable:\n msg = \"\"\"\n Inactive version must be upgradable to the\n current version (%s), please check the version\n and patches.\n \"\"\" % current_version\n raise exception.SysinvException(_(msg))\n\n self.dbapi.load_update(active_load['id'], {'compatible_version': new_version,\n 'required_patches': '\\n'.join(patches)})\n\n patch = dict()\n patch['state'] = constants.IMPORTING_LOAD_STATE\n\n patch['software_version'] = new_version\n patch['compatible_version'] = \"\"\n patch['required_patches'] = \"\"\n new_load = self.dbapi.load_create(patch)\n return new_load\n\n else:\n if new_version == current_version:\n raise exception.SysinvException(\n _(\"Active version and import version match (%s)\")\n % current_version)\n\n supported_upgrades_elm = root.find('supported_upgrades')\n if not supported_upgrades_elm:\n raise exception.SysinvException(\n _(\"Invalid Metadata XML\"))\n\n path_found = False\n upgrade_path = None\n upgrade_paths = supported_upgrades_elm.findall('upgrade')\n\n for upgrade_element in upgrade_paths:\n valid_from_version = upgrade_element.findtext('version')\n valid_from_versions = valid_from_version.split(\",\")\n if current_version in valid_from_versions:\n path_found = True\n upgrade_path = upgrade_element\n break\n\n if not path_found:\n raise exception.SysinvException(\n _(\"No valid upgrade path found\"))\n\n # Create a patch with the values from the metadata\n patch = dict()\n\n patch['state'] = constants.IMPORTING_LOAD_STATE\n patch['software_version'] = new_version\n patch['compatible_version'] = current_version\n\n required_patches = []\n\n if upgrade_path:\n patch_elements = upgrade_path.findall('required_patch')\n for patch_element in patch_elements:\n required_patches.append(patch_element.text)\n\n patch['required_patches'] = \"\\n\".join(required_patches)\n\n # create the new imported load in the database\n new_load = self.dbapi.load_create(patch)\n\n return new_load",
"def test_filesystem_snapshot(self):\n pool_name = make_test_pool(StratisCertify.DISKS[0:1])\n filesystem_name = make_test_filesystem(pool_name)\n snapshot_name = fs_n()\n self.unittest_command(\n [\n _STRATIS_CLI,\n \"filesystem\",\n \"snapshot\",\n pool_name,\n filesystem_name,\n snapshot_name,\n ],\n 0,\n True,\n True,\n )",
"def add_disk_to_vm_on_iscsi(request, storage):\n self = request.node.cls\n\n vm_disk_2 = storage_helpers.create_unique_object_name(\n self.__name__, config.OBJECT_TYPE_DISK\n )\n testflow.setup(\n \"Adding disk %s to VM %s on storage domain %s\", vm_disk_2,\n self.vm_name, self.storage_domains[config.ISCSI]\n )\n helpers.add_disk_to_sd(\n vm_disk_2, self.storage_domains[config.ISCSI],\n attach_to_vm=self.vm_name\n )",
"def import_snapshot(self, snapshot:Snapshot):\n if snapshot.uid not in self.snapshot_ids:\n raise RuntimeError('This snapshot does not belong to the Experiment!')\n Task.init_import()\n # check out the relevant commit\n self.repo.head.reference = self.repo.commit(snapshot.commit_sha)\n self.repo.head.reset(index=True, working_tree=True)\n # import the correct file from the correct location\n backup_path = sys.path\n sys.path = [self.repo_path]\n module_name, _ = os.path.splitext(snapshot.filename)\n # the imported module triggers the other end of the mechanism\n importlib.import_module(module_name)\n # return to the original master head\n self.repo.head.reference = self.repo.heads[0]\n self.repo.head.reset(index=True, working_tree=True)\n # retrieve the imported object and clean up\n task_object = Task.retrieve_instance()\n sys.path = backup_path\n # before returning the object, link it with the Snapshot instance\n task_object.snapshot = snapshot\n return task_object",
"def cli(env, identifier, notes):\n\n iscsi_mgr = SoftLayer.ISCSIManager(env.client)\n iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, identifier, 'iSCSI')\n iscsi_mgr.create_snapshot(iscsi_id, notes)",
"def create_disk_snapshot(chain, disk_bytes, raw_flag):\n pass",
"def test_attach_detach_disk(self):\n # prepare the target profile\n data = next(self._get_next_entry)\n prof_id = self._request_and_assert('create', 'admin:a', data)\n\n # restore original system owner on test end/failure to avoid causing\n # problems with other tests\n sys_obj = models.System.query.filter_by(\n name=self._target_lpar).one()\n orig_sys_owner = sys_obj.owner\n def restore_owner():\n \"\"\"Helper cleanup\"\"\"\n # reset flask user to admin\n self._do_request('list', 'admin:a')\n\n sys_obj = models.System.query.filter_by(\n name=self._target_lpar).one()\n sys_obj.owner = orig_sys_owner\n self.db.session.add(sys_obj)\n self.db.session.commit()\n self.addCleanup(restore_owner)\n\n # create target disk\n disk_name = '1111_test_attach_detach_disk'\n disk_obj = models.StorageVolume(\n server='DSK8_x_0',\n system=self._target_lpar,\n volume_id=disk_name,\n type='DASD',\n size=10000,\n part_table=None,\n system_attributes={},\n owner='admin',\n modifier='admin',\n project=self._db_entries['Project'][0]['name'],\n desc='some description'\n )\n self.db.session.add(disk_obj)\n self.db.session.commit()\n disk_id = disk_obj.id\n\n def assert_actions(login, disk_owner, sys_owner, assign,\n error_msg=None, http_code=403):\n \"\"\"\n Helper to prepare environment and validate attach/detach actions\n \"\"\"\n # set system ownership\n # reset flask user to admin\n self._do_request('list', 'user_hw_admin@domain.com:a')\n\n sys_obj = models.System.query.filter_by(\n name=self._target_lpar).one()\n sys_obj.owner = sys_owner\n self.db.session.add(sys_obj)\n self.db.session.commit()\n\n # disk assignment to system\n disk_obj = models.StorageVolume.query.filter_by(\n volume_id=disk_name).one()\n if assign:\n disk_obj.system = sys_obj.name\n else:\n disk_obj.system = None\n # disk ownership\n disk_obj.owner = disk_owner\n self.db.session.add(disk_obj)\n self.db.session.commit()\n\n # removing existing disk associations first\n models.StorageVolumeProfileAssociation.query.filter_by(\n volume_id=disk_id, profile_id=prof_id).delete()\n self.db.session.commit()\n\n args = [disk_id, prof_id, '{}:a'.format(login)]\n # no error msg expected: expect a 200 response\n if not error_msg:\n self._req_att_disk(*args)\n self._req_det_disk(*args)\n\n # disk was not assigned to system: validate that it is now\n if not assign:\n disk_obj = models.StorageVolume.query.filter_by(\n volume_id=disk_name).one()\n self.assertEqual(\n disk_obj.system, self._target_lpar,\n 'Disk was not assigned to system after attach')\n return\n\n resp = self._req_att_disk(*args, validate=False)\n self._validate_resp(resp, error_msg, http_code)\n\n # prepare association for detach\n assoc_obj = models.StorageVolumeProfileAssociation(\n volume_id=disk_id, profile_id=prof_id)\n self.db.session.add(assoc_obj)\n self.db.session.commit()\n # try detach\n resp = self._req_det_disk(*args, validate=False)\n self._validate_resp(resp, error_msg, http_code)\n # assert_actions()\n\n # logins with no update role\n logins_no_role = ('user_user@domain.com', 'user_restricted@domain.com')\n for login in logins_no_role:\n # attach disk assigned to system, user has no permission to system\n # nor disk (fails)\n if login == 'user_restricted@domain.com':\n msg = (\"No associated item found with value \"\n \"'25' for field 'profile_id'\")\n http_code = 422\n else:\n msg = 'User has no UPDATE permission for the specified system'\n http_code = 403\n assert_actions(login, 'admin', 'admin', assign=True, error_msg=msg,\n http_code=http_code)\n\n # attach disk assigned to system, user is owner of system but\n # no permission to disk (works)\n assert_actions(login, 'admin', login, assign=True)\n\n # attach disk assigned to system, user is owner of system and\n # disk (works)\n assert_actions(login, login, login, assign=True)\n\n # attach disk unassigned to system, user is owner of system but\n # no permission to disk (fails)\n if login == 'user_restricted@domain.com':\n msg = (\"No associated item found with value \"\n \"'6' for field 'volume_id'\")\n http_code = 422\n else:\n msg = 'User has no UPDATE permission for the specified volume'\n http_code = 403\n assert_actions(login, 'admin', login, assign=False, error_msg=msg,\n http_code=http_code)\n\n # logins with an update-system role but no update-disk\n logins_sys_no_disk = (\n 'user_privileged@domain.com', 'user_project_admin@domain.com')\n for login in logins_sys_no_disk:\n # attach disk assigned to system, user has permission to system but\n # not to disk (works)\n assert_actions(login, 'admin', 'admin', assign=True)\n\n # attach disk assigned to system, user has permission to system and\n # is owner of disk (works)\n assert_actions(login, login, 'admin', assign=True)\n\n # attach disk unassigned to system, user has permission to system\n # but not to disk (fails)\n msg = 'User has no UPDATE permission for the specified volume'\n assert_actions(login, 'admin', 'admin', assign=False,\n error_msg=msg)\n\n # attach disk unassigned to system, user has permission to system\n # and is owner of disk (works)\n assert_actions(login, login, 'admin', assign=False)\n\n logins_with_both_roles = (\n 'user_hw_admin@domain.com', 'user_admin@domain.com')\n for login in logins_with_both_roles:\n # attach disk assigned to system, user has permission to system and\n # disk (works)\n assert_actions(login, 'admin', 'admin', assign=True)\n\n # attach disk unassigned system, user has permission to system and\n # disk (works)\n assert_actions(login, 'admin', 'admin', assign=False)\n\n # test the case where the disk is already assigned to another system\n sys_2_obj = models.System(\n name=\"lpar test_attach_detach_disk\",\n state=\"AVAILABLE\",\n modifier='admin',\n type=\"LPAR\",\n hostname=\"lpar.domain.com\",\n project=self._project_name,\n model=\"ZEC12_H20\",\n owner='admin',\n )\n self.db.session.add(sys_2_obj)\n self.db.session.commit()\n for login in (logins_no_role + logins_sys_no_disk +\n logins_with_both_roles):\n # set ownerships\n # reset flask user to admin\n self._do_request('list', 'admin:a')\n sys_obj = models.System.query.filter_by(\n name=self._target_lpar).one()\n sys_obj.owner = login\n self.db.session.add(sys_obj)\n sys_2_obj.owner = login\n self.db.session.add(sys_2_obj)\n disk_obj = models.StorageVolume.query.filter_by(\n volume_id=disk_name).one()\n disk_obj.owner = login\n disk_obj.system = sys_2_obj.name\n self.db.session.add(disk_obj)\n self.db.session.commit()\n\n resp = self._req_att_disk(\n disk_id, prof_id, '{}:a'.format(login), validate=False)\n msg = 'The volume is already assigned to system {}'.format(\n sys_2_obj.name)\n self._validate_resp(resp, msg, 409)\n\n # test the case where the disk is already attached to the profile\n # reset flask user to admin\n self._do_request('list', 'admin:a')\n disk_obj = models.StorageVolume.query.filter_by(\n volume_id=disk_name).one()\n disk_obj.system = sys_obj.name\n self.db.session.add(disk_obj)\n self.db.session.commit()\n self._req_att_disk(disk_id, prof_id, 'admin:a')\n resp = self._req_att_disk(\n disk_id, prof_id, 'admin:a', validate=False)\n self._validate_resp(\n resp, 'The volume specified is already attached to the profile',\n 409)\n # test trying to detach when it is not attached\n self._req_det_disk(disk_id, prof_id, 'admin:a')\n resp = self._req_det_disk(\n disk_id, prof_id, 'admin:a', validate=False)\n self._validate_resp(\n resp, 'The volume specified is not attached to the profile', 404)\n\n # clean up\n self.db.session.delete(sys_2_obj)\n self.db.session.delete(disk_obj)\n self.db.session.commit()",
"def add_snapshot(self, *params):\n if not params or len(params)==0:\n raise TypeError(\"add_snapshot takes at lease 1 argument 0 given.\")\n elif params and len(params)>2:\n raise TypeError(\"add_snapshot takes at lease 1 argument %u given.\" %(len(params)))\n destdisk=params[0]\n sourcedisk=params[1]\n properties=destdisk.getProperties()\n properties.setProperty(\"vdisk\", sourcedisk.getAttribute(\"name\"))\n return self._add(\"snapshot\", destdisk.getAttribute(\"name\"), properties)",
"def test_copy_vm_disks_after_cloned_as_thin(self, storage):\n self.copy_with_template(storage=storage, clone=False)",
"def test006_attach_same_disk_to_two_vms(self):\n # Note: try this scenario for data and boot disks\n\n self.lg('%s STARTED' % self._testID)\n\n self.lg('Create VM1 and VM2')\n VM1_id = self.cloudapi_create_machine(cloudspace_id=self.cloudspace_id)\n VM2_id = self.cloudapi_create_machine(cloudspace_id=self.cloudspace_id)\n\n self.lg(' Create disk DS1.')\n disk_id = self.create_disk(self.account_id)\n self.assertTrue(disk_id)\n\n self.lg('Attach DS1 to VM1, should succeed.')\n response = self.api.cloudapi.machines.attachDisk(machineId=VM1_id, diskId=disk_id)\n self.assertTrue(response)\n\n self.lg('Attach DS1 to VM2, should fail.')\n with self.assertRaises(HTTPError) as e:\n self.api.cloudapi.machines.attachDisk(machineId=VM2_id, diskId=disk_id)\n\n self.lg('- expected error raised %s' % e.exception.status_code)\n self.assertEqual(e.exception.status_code, 400)\n\n self.lg('Delete disk after detaching it, should succeed')\n response = self.api.cloudapi.disks.delete(diskId=disk_id, detach=True)\n self.assertTrue(response)\n\n self.lg('%s ENDED' % self._testID)",
"async def migrate_disk(self, new_disk: str) -> None:\n # Force a dbus update first so all info is up to date\n await self.sys_dbus.udisks2.update()\n\n target_disk: list[Disk] = [\n disk\n for disk in self.available_disks\n if disk.id == new_disk or disk.device_path.as_posix() == new_disk\n ]\n if len(target_disk) != 1:\n raise HassOSDataDiskError(\n f\"'{new_disk}' not a valid data disk target!\", _LOGGER.error\n ) from None\n\n # If any other partition is named \"hassos-data-external\" error and ask for its removal\n # otherwise it will create a race condition at startup\n if self.disk_used and (\n conflicts := [\n block\n for block in self.sys_dbus.udisks2.block_devices\n if block.partition\n and block.partition.name_ == PARTITION_NAME_EXTERNAL_DATA_DISK\n and block.device != self.disk_used.device_path\n and block.drive != target_disk[0].object_path\n ]\n ):\n raise HassOSDataDiskError(\n f\"Partition(s) {', '.join([conflict.device.as_posix() for conflict in conflicts])} have name 'hassos-data-external' which prevents migration. Remove or rename them first.\",\n _LOGGER.error,\n )\n\n # Older OS did not have mark data move API. Must let OS do disk format & migration\n if self.sys_dbus.agent.version < OS_AGENT_MARK_DATA_MOVE_VERSION:\n try:\n await self.sys_dbus.agent.datadisk.change_device(\n target_disk[0].device_path\n )\n except DBusError as err:\n raise HassOSDataDiskError(\n f\"Can't move data partition to {new_disk!s}: {err!s}\", _LOGGER.error\n ) from err\n else:\n # Format disk then tell OS to migrate next reboot\n current_block = (\n self.sys_dbus.udisks2.get_block_device(\n self.disk_used.device_object_path\n )\n if self.disk_used\n else None\n )\n\n # If migrating from one external data disk to another, rename the old one to prevent conflicts\n # Do this first because otherwise a subsequent failure could create a race condition on reboot\n if (\n current_block\n and current_block.partition\n and current_block.partition.name_ == PARTITION_NAME_EXTERNAL_DATA_DISK\n ):\n try:\n await current_block.partition.set_name(\n PARTITION_NAME_OLD_EXTERNAL_DATA_DISK\n )\n except DBusError as err:\n raise HassOSDataDiskError(\n f\"Could not rename existing external data disk to prevent name conflict: {err!s}\",\n _LOGGER.error,\n ) from err\n\n partition = await self._format_device_with_single_partition(target_disk[0])\n\n if current_block and current_block.size > partition.size:\n raise HassOSDataDiskError(\n f\"Cannot use {new_disk} as data disk as it is smaller then the current one (new: {partition.size}, current: {current_block.size})\",\n _LOGGER.error,\n )\n\n try:\n await self.sys_dbus.agent.datadisk.mark_data_move()\n except DBusError as err:\n raise HassOSDataDiskError(\n f\"Unable to create data disk migration marker: {err!s}\",\n _LOGGER.error,\n ) from err\n\n # Restart Host for finish the process\n try:\n await self.sys_host.control.reboot()\n except HostError as err:\n raise HassOSError(\n f\"Can't restart device to finish disk migration: {err!s}\",\n _LOGGER.warning,\n ) from err",
"def make_snapshot(ec2,vol,retention,description):\n\n snap = ec2.create_snapshot(VolumeId=vol,Description=description)\n return snap",
"def attach_disk(self, instance, size=10, volume_type=None, iops=None, device=None):\n conn = self.conn or self.vpc_conn\n # Add EBS volume DONE\n ebs_vol = conn.create_volume(size, self.zone, volume_type=volume_type, iops=iops)\n self.wait_for_state(ebs_vol, 'status', 'available')\n if not device:\n device = '/dev/sdx'\n conn.attach_volume(ebs_vol.id, instance.id, device=device)\n self.ebs_vols.append(ebs_vol)\n return ebs_vol",
"def test_copy_vm_disks_after_cloned_as_clone(self, storage):\n self.copy_with_template(storage=storage)",
"def test_create_volume_from_snapshot(self, snapshot, volumes_steps_ui):\n volumes_steps_ui.create_volume_from_snapshot(snapshot.name)\n volumes_steps_ui.delete_volume(snapshot.name)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modify the autoplacement setting of a Dedicated Host. When autoplacement is enabled, AWS will place instances that you launch with a tenancy of host , but without targeting a specific host ID, onto any available Dedicated Host in your account which has autoplacement enabled. When autoplacement is disabled, you need to provide a host ID if you want the instance to launch onto a specific host. If no host ID is provided, the instance will be launched onto a suitable host which has autoplacement enabled.
|
def modify_hosts(HostIds=None, AutoPlacement=None):
pass
|
[
"def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):\n pass",
"def enable_dhcp(self, ip_host_num):\n return [\"ip-host %s dhcp-enable true ping-response true traceroute-response true\" % ip_host_num]",
"def host(self, value):\n if self._host:\n raise RuntimeError(\"HostManager already set!\")\n self._host = value",
"def update_aws_hosts(self):\n deploy_config = False\n all_instances = self.list_instances()\n # pprint.pprint(all_instances)\n for account in all_instances:\n for instance in all_instances[account]:\n exists = subprocess.call([\"icingacli\", \"director\", \"host\", \"exists\", instance['InstanceId']])\n if exists == 0:\n pass\n elif exists == 1 or exists == NoneType:\n deploy_config = True\n nodename = self.get_instance_name_from_tags(instance)\n instance_desc = {\n \"imports\": \"aws-host\",\n \"address\": instance['PublicIpAddress'],\n \"display_name\": \"AWS-\" + account + \"-\" + nodename,\n \"groups\": [ \"aws-\" + account ],\n \"vars.location\": \"AWS \" + account,\n \"vars.imageid\": instance['ImageId'],\n \"vars.instanceid\": instance['InstanceId'],\n \"vars.instancetype\": instance['InstanceType'],\n \"vars.ip\": instance['PublicIpAddress'],\n \"vars.keyname\": instance['KeyName']\n }\n for tag in instance['Tags']:\n instance_desc['vars.tag_'+tag['Key']] = tag['Value']\n\n subprocess.call([\"icingacli\", \"director\", \"host\", \"create\", instance['InstanceId'], \"--json\", json.dumps(instance_desc)])\n print \"added node \" + instance['InstanceId'] + \" (\" + nodename + \")\"\n else:\n pass\n if deploy_config:\n subprocess.call([\"icingacli\", \"director\", \"config\", \"deploy\"])",
"def host_gateway(self, value):\n\n self._host_gateway.set(value)",
"def set_host_enabled(self, *args, **kwargs):\n raise NotImplementedError()",
"def set_ping_host(self, host_ip_address):\n self.ping_host_ip_address = host_ip_address",
"def update_instance_host(self, context, instance):\n self._service.update_correct_host(context, instance)",
"def SetHost(self, host):\n self._host = host",
"def host_address(self, host_address):\n\n self._host_address = host_address",
"def modify_host(self, host_id, name=None, description=None,\n remove_initiators=None, add_initiators=None,\n modify_initiators=None):\n LOG.info(\"Modifying host: '%s'\" % host_id)\n payload = self._prepare_modify_host_payload(name,\n description,\n remove_initiators,\n add_initiators,\n modify_initiators)\n return self.client.request(\n constants.PATCH, constants.MODIFY_HOST_URL.format(\n self.server_ip, host_id),\n payload)",
"def _configure_controller_host(self, context, host):\n if self.host_load_matches_sw_version(host):\n # update the config if the host is running the same version as\n # the active controller.\n if (host.administrative == constants.ADMIN_UNLOCKED or\n host.action == constants.FORCE_UNLOCK_ACTION or\n host.action == constants.UNLOCK_ACTION):\n\n # Update host configuration\n self._puppet.update_host_config(host)\n else:\n # from active controller, update hieradata for upgrade\n host_uuids = [host.uuid]\n config_uuid = self._config_update_hosts(\n context,\n [constants.CONTROLLER],\n host_uuids,\n reboot=True)\n host_upgrade = self.dbapi.host_upgrade_get_by_host(host.id)\n target_load = self.dbapi.load_get(host_upgrade.target_load)\n self._puppet.update_host_config_upgrade(\n host,\n target_load.software_version,\n config_uuid\n )\n\n self._allocate_addresses_for_host(context, host)\n # Set up the PXE config file for this host so it can run the installer\n self._update_pxe_config(host)\n self._ceph_mon_create(host)\n\n if (os.path.isfile(constants.ANSIBLE_BOOTSTRAP_FLAG) and\n host.availability == constants.AVAILABILITY_ONLINE):\n # This must be the initial controller host unlock request.\n personalities = [constants.CONTROLLER]\n if not cutils.is_aio_system(self.dbapi):\n # Standard system, touch the unlock ready flag\n cutils.touch(constants.UNLOCK_READY_FLAG)\n else:\n # AIO, must update grub before the unlock. Sysinv agent expects\n # this exact set of manifests in order to touch the unlock ready\n # flag after they have been applied.\n config_uuid = self._config_update_hosts(context, personalities,\n host_uuids=[host.uuid])\n if utils.config_is_reboot_required(host.config_target):\n config_uuid = self._config_set_reboot_required(config_uuid)\n\n config_dict = {\n \"personalities\": personalities,\n \"host_uuids\": [host.uuid],\n \"classes\": ['platform::compute::grub::runtime',\n 'platform::compute::config::runtime']\n }\n self._config_apply_runtime_manifest(\n context, config_uuid, config_dict, force=True)\n\n # Regenerate config target uuid, node is going for reboot!\n config_uuid = self._config_update_hosts(context, personalities)\n if utils.config_is_reboot_required(host.config_target):\n config_uuid = self._config_set_reboot_required(config_uuid)\n self._puppet.update_host_config(host, config_uuid)",
"def associate_address(DryRun=None, InstanceId=None, PublicIp=None, AllocationId=None, NetworkInterfaceId=None, PrivateIpAddress=None, AllowReassociation=None):\n pass",
"def associate_dhcp_options(DryRun=None, DhcpOptionsId=None, VpcId=None):\n pass",
"def write_default_host(self, host_address):\n self.write(\"host\", host_address)",
"def set_local_ip_to_dhcp(name = \"V54Adapter\"):\n os.system(\"netsh interface ip set address \\\"%s\\\" dhcp\" % name)",
"def enableDHCPClick():\n os.system(\"mount -o rw,remount /\")\n os.system(\"cp netctl/ethernet-dhcp /etc/netctl/eth0\")\n os.system(\"mount -o ro,remount /\")\n lcdPrint(\"Obtaining IP...\")\n lcd.setCursor(15,0)\n lcd.ToggleBlink()\n os.system(\"ip link set eth0 down\")\n os.system(\"netctl restart eth0\")\n ip = socket.gethostbyname(socket.getfqdn())\n lcd.ToggleBlink()\n lcdPrint(\"Enabled DHCP:\\n\"+ip, 2)",
"def set_deploy_config():\n\n\n host = \"ec2-174-129-125-34.compute-1.amazonaws.com:8000\"\n\n # BROKEN until fix yoeman build - wtf\n # Set directory for distribution scripts: \n # Assumes parallelspider/spiderweb/dist/scripts/ \n #directory_path = path + \"spiderweb/dist/scripts/\"\n directory_path = path\n\n # Find renamed services file\n contents = os.listdir(directory_path)\n for f in contents:\n if \"service\" in f:\n # avoid backups\n if \"~\" not in f:\n service_file = f\n\n # Replace host and mock info in dist version of config service file\n file_path = directory_path + service_file\n for line in fileinput.input(file_path, inplace=1):\n new_host_line = line.replace(\"localhost:8000\", host)\n # not setting mock yet\n new_mock_line = new_host_line.replace(\"mock = true\", \"mock = false\")\n print \"%s\" % (new_mock_line),\n #print \"%s\" % (new_host_line),",
"def update_host(ipaddress, hostname):\n if not 'linux' in sys.platform:\n error_message('Host update is only required in linux systems')\n return False\n\n filename = '/etc/hosts'\n tmp_filename = '/tmp/hosts.tmp'\n\n original = open(filename, 'rt')\n contents = original.read() + \"\\n\" + ipaddress + \"\\t\" + hostname + \"\\n\"\n original.close()\n tmp = open(tmp_filename, 'wb')\n tmp.write(contents)\n tmp.close()\n\n os.system('sudo mv ' + tmp_filename + ' ' + filename)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the ID format of a resource for a specified IAM user, IAM role, or the root user for an account; or all IAM users, IAM roles, and the root user for an account. You can specify that resources should receive longer IDs (17character IDs) when they are created.
|
def modify_identity_id_format(Resource=None, UseLongIds=None, PrincipalArn=None):
pass
|
[
"def update_resource(\n self,\n education_user_id, # type: str\n education_assignment_id, # type: str\n education_assignment_resource_id, # type: str\n id=None, # type: Optional[str]\n distribute_for_student_work=None, # type: Optional[bool]\n created_date_time=None, # type: Optional[datetime.datetime]\n display_name=None, # type: Optional[str]\n last_modified_date_time=None, # type: Optional[datetime.datetime]\n microsoft_graph_identity_display_name=None, # type: Optional[str]\n microsoft_graph_identity_id=None, # type: Optional[str]\n display_name1=None, # type: Optional[str]\n id1=None, # type: Optional[str]\n display_name2=None, # type: Optional[str]\n id2=None, # type: Optional[str]\n display_name3=None, # type: Optional[str]\n id3=None, # type: Optional[str]\n display_name4=None, # type: Optional[str]\n id4=None, # type: Optional[str]\n display_name5=None, # type: Optional[str]\n id5=None, # type: Optional[str]\n **kwargs # type: Any\n ):\n # type: (...) -> None\n cls = kwargs.pop('cls', None) # type: ClsType[None]\n error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}\n error_map.update(kwargs.pop('error_map', {}))\n\n _body = models.MicrosoftGraphEducationAssignmentResource(id=id, distribute_for_student_work=distribute_for_student_work, created_date_time=created_date_time, display_name_resource_display_name=display_name, last_modified_date_time=last_modified_date_time, display_name_resource_last_modified_by_user_display_name=microsoft_graph_identity_display_name, id_resource_last_modified_by_user_id=microsoft_graph_identity_id, display_name_resource_last_modified_by_device_display_name=display_name1, id_resource_last_modified_by_device_id=id1, display_name_resource_last_modified_by_application_display_name=display_name2, id_resource_last_modified_by_application_id=id2, display_name_resource_created_by_user_display_name=display_name3, id_resource_created_by_user_id=id3, display_name_resource_created_by_device_display_name=display_name4, id_resource_created_by_device_id=id4, display_name_resource_created_by_application_display_name=display_name5, id_resource_created_by_application_id=id5)\n content_type = kwargs.pop(\"content_type\", \"application/json\")\n accept = \"application/json\"\n\n # Construct URL\n url = self.update_resource.metadata['url'] # type: ignore\n path_format_arguments = {\n 'educationUser-id': self._serialize.url(\"education_user_id\", education_user_id, 'str'),\n 'educationAssignment-id': self._serialize.url(\"education_assignment_id\", education_assignment_id, 'str'),\n 'educationAssignmentResource-id': self._serialize.url(\"education_assignment_resource_id\", education_assignment_resource_id, 'str'),\n }\n url = self._client.format_url(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = {} # type: Dict[str, Any]\n\n # Construct headers\n header_parameters = {} # type: Dict[str, Any]\n header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str')\n header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str')\n\n body_content_kwargs = {} # type: Dict[str, Any]\n body_content = self._serialize.body(_body, 'MicrosoftGraphEducationAssignmentResource')\n body_content_kwargs['content'] = body_content\n request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)\n\n pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)\n response = pipeline_response.http_response\n\n if response.status_code not in [204]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n error = self._deserialize(models.OdataError, response)\n raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)\n\n if cls:\n return cls(pipeline_response, None, {})",
"def _get_id(self, resource):\n if hasattr(resource, 'id'):\n resource_id = \\\n resource.id() if callable(resource.id) else resource.id\n elif hasattr(resource, 'get_id'):\n resource_id = resource.get_id()\n elif 'id' in resource:\n resource_id = resource['id']\n else:\n raise Exception('Could not determine the resource id.')\n return str(resource_id)",
"def transform(cls, clients, resource_config):\n if \"name\" not in resource_config and \"regex\" not in resource_config:\n # NOTE(wtakase): gets resource name from OpenStack id\n glanceclient = clients.glance()\n resource_name = _name_from_id(resource_config=resource_config,\n resources=list(\n glanceclient.images.list()),\n typename=\"image\")\n resource_config[\"name\"] = resource_name\n\n # NOTE(wtakase): gets EC2 resource id from name or regex\n ec2client = clients.ec2()\n resource_ec2_id = _id_from_name(resource_config=resource_config,\n resources=list(\n ec2client.get_all_images()),\n typename=\"ec2_image\")\n return resource_ec2_id",
"def note_setdata_resource_conversion(resource, id, class_):\n note = Note()\n data = {\n 'resource': resource,\n 'resource_id': id\n }\n _data = note.format_data_set(data)\n assert isinstance(_data['resource'], class_)",
"def _id_format(resp):\r\n if 'StackId' in resp:\r\n identity = identifier.HeatIdentifier(**resp['StackId'])\r\n resp['StackId'] = identity.arn()\r\n if 'EventId' in resp:\r\n identity = identifier.EventIdentifier(**resp['EventId'])\r\n resp['EventId'] = identity.event_id\r\n return resp",
"def _generate_id(cls, user_id: str, exploration_id: str) -> str:\n return '%s.%s' % (user_id, exploration_id)",
"def describe_identity_id_format(Resource=None, PrincipalArn=None):\n pass",
"def update(event, context, helper): # pylint: disable=unused-argument\n try:\n grant_id = create(event, context, helper)\n except Auth0Error as err:\n logger.error(err)\n if err.status_code != 409:\n raise err\n grant_id = event['PhysicalResourceId']\n\n helper.Data['GrantId'] = grant_id\n return grant_id",
"def task_setdata_resource_conversion(resource, id, class_):\n note = Task()\n data = {\n 'resource': resource,\n 'resource_id': id\n }\n _data = note.format_data_set(data)\n assert isinstance(_data['resource'], class_)",
"def construct_model_id(cls, user_id: str, skill_id: str) -> str:\n return '%s.%s' % (user_id, skill_id)",
"def int_id_str(self, user_info):\n user_info['id_str'] = int(user_info['id_str'])\n return user_info",
"def changeId(self, newId):\n self.userInput.id = newId\n self.userInput.name = newId\n self.formError.name = newId\n self.id = newId + \"Field\"",
"def get_id(self) -> str:\r\n return self.resource_id",
"def transform(cls, clients, resource_config):\n resource_id = resource_config.get(\"id\")\n if not resource_id:\n cinderclient = clients.cinder()\n resource_id = _id_from_name(resource_config=resource_config,\n resources=cinderclient.\n volume_types.list(),\n typename=\"volume_type\")\n return resource_id",
"def resource_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"resource_id\")",
"def modify_resource(self):\n \"\"\" Create or update resources \"\"\"\n json_payload = cherrypy.request.json\n if not self._verify_auth_token(json.dumps(json_payload)):\n return json.dumps({'success': False, 'msg': 'User operation not authorized!'})\n\n payload = json_payload['json']\n name = payload['filename']\n vendor = payload['server']\n url = payload['url']\n type = payload['type']\n desc = payload['desc']\n session = cherrypy.request.db\n try:\n resource = Resource.get_resource_by_name_vendor(session, name, vendor)\n if not resource:\n resource = Resource(name, desc, type, vendor, url)\n session.add(resource)\n else:\n resource.name = name\n resource.vendor = vendor\n resource.url = url\n resource.type = type\n resource.description = desc\n session.commit()\n except DBAPIError, err:\n log.error('Database operation error %s' % err)\n return json.dumps({'success': False, 'msg': 'Sync resource failed!'})\n return json.dumps({'success': True, 'msg': 'Sync resource success!'})",
"def _get_parsed_resource_ids(resource_ids):\n if not resource_ids:\n return None\n\n for rid in resource_ids:\n if not is_valid_resource_id(rid):\n raise CLIError('az resource: error: argument --ids: invalid ResourceId value: \\'%s\\'' % rid)\n\n return ({'resource_id': rid} for rid in resource_ids)",
"def _generate_id(cls, user_id, thread_id):\n return '.'.join([user_id, thread_id])",
"def generate_ARN_for_resource(resourceId, isCluster):\n\tresourceType = \":cluster:\" if isCluster else \":db:\"\n\treturn \"arn:aws:rds:\" + regionName + \":\" + accountNumber + resourceType + resourceId"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the specified attribute of the specified AMI. You can specify only one attribute at a time.
|
def modify_image_attribute(DryRun=None, ImageId=None, Attribute=None, OperationType=None, UserIds=None, UserGroups=None, ProductCodes=None, Value=None, LaunchPermission=None, Description=None):
pass
|
[
"def update(self, attribute, data):\n return self.call('catalog_product_attribute.update', [attribute, data])",
"def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):\n pass",
"def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):\n pass",
"def set_attribute(self,att,val):\r\n self.attributes[att] = val",
"def setAttribute(self, attributename, attributevalue):\n\n self.send('setAttribute(\"' + attributename + '\", \"'\n + attributevalue + '\");')",
"def update(self, attr):\n assert attr is not MispAttribute\n attr.timestamp = datetime.datetime.now()\n raw = attr.to_xml()\n raw = self.server.POST('/attributes/%d' % attr.id, raw)\n return MispAttribute.from_xml(raw)",
"def update(self, attr):\n assert attr is not MispShadowAttribute\n raw = attr.to_xml()\n raw = self.server.POST('/shadow_attributes/edit/%d' % attr.id, raw)\n response = objectify.fromstring(raw)\n return MispShadowAttribute.from_xml_object(response.ShadowAttribute)",
"def lock_unlock_attribute(element, attribute, state):\n\n try:\n cmds.setAttr(\"{}.{}\".format(element, attribute), lock=state)\n return True\n except RuntimeError:\n return False",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def updateAttribute(self,\n instid,\n attrid,\n attr,\n commitComment=None):\n path = \"api/v1/inst/%(instid)s/%(attrid)s\"\n path_params = {\"instid\": instid,\n \"attrid\": attrid}\n query_params = {}\n form_params = {\"attr\": attr,\n \"commitComment\": commitComment}\n result = self.conn.invoke_method(\"PUT\", path, path_params,\n query_params, form_params)\n if result.error:\n raise IbisException(result.error)\n return result.attribute",
"def reset_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def attribute_rename_cmd(oldattr, newattr):\n def processor(cm):\n print_cmd_status('Rename attribute: \"%s\" => \"%s\"' % (oldattr, newattr))\n cm.rename_attribute(oldattr, newattr)\n return cm\n return processor",
"def updateAttribute(self,\n scheme,\n identifier,\n attrid,\n attr,\n commitComment=None):\n path = \"api/v1/person/%(scheme)s/%(identifier)s/%(attrid)s\"\n path_params = {\"scheme\": scheme,\n \"identifier\": identifier,\n \"attrid\": attrid}\n query_params = {}\n form_params = {\"attr\": attr,\n \"commitComment\": commitComment}\n result = self.conn.invoke_method(\"PUT\", path, path_params,\n query_params, form_params)\n if result.error:\n raise IbisException(result.error)\n return result.attribute",
"def replace_attributes(soup: BeautifulSoup, attribute: str, value: str, new_value: str) -> None:\n for target in soup.find_all(attrs={attribute: value}):\n target: Tag\n target.attrs[attribute] = new_value",
"def renameAttribute(*args, **kwargs):\n \n pass",
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def set_attribute(self,attr,value,add = None):\n\t\tif (add is None):\n\t\t\tadd = False \n\t\tif (attr is None):\n\t\t\traise ValueError(\"You must specify an attribute\")\n\t\tif (value is None):\n\t\t\traise ValueError(\"You must specify a value\")\n\t\tif ((not add) and (attr not in self._Attributes)):\n\t\t\traise ValueError(\"Attribute \" + attr + \" unrecognized\")\n\t\tself._Attributes[attr] = value",
"def set_attr_2(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr2\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the specified attribute of the specified instance. You can specify only one attribute at a time. To modify some attributes, the instance must be stopped. For more information, see Modifying Attributes of a Stopped Instance in the Amazon Elastic Compute Cloud User Guide .
|
def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):
pass
|
[
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def set_attr_2(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr2\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)",
"def update(self, attr):\n assert attr is not MispAttribute\n attr.timestamp = datetime.datetime.now()\n raw = attr.to_xml()\n raw = self.server.POST('/attributes/%d' % attr.id, raw)\n return MispAttribute.from_xml(raw)",
"def update(self, attribute, data):\n return self.call('catalog_product_attribute.update', [attribute, data])",
"def modify_image_attribute(DryRun=None, ImageId=None, Attribute=None, OperationType=None, UserIds=None, UserGroups=None, ProductCodes=None, Value=None, LaunchPermission=None, Description=None):\n pass",
"def updateAttribute(self, attributeName, attributeType, attributeValueChangeSpecData, defaultValue, description, showInTriage):\n attributeDefinitionId= self.__ConfServiceclient.factory.create(\"attributeDefinitionDataObj\")\n attributeDefinitionId= attributeName\n attributeDefinitionSpec= self.__ConfServiceclient.factory.create(\"attributeDefinitionSpecDataObj\")\n attributeDefinitionSpec.attributeName= None\n attributeDefinitionSpec.attributeType= attributeType\n attributeDefinitionSpec.attributeValueChangeSpec= attributeValueChangeSpecData\n attributeDefinitionSpec.defaultValue= defaultValue\n attributeDefinitionSpec.description= description\n attributeDefinitionSpec.showInTriage= showInTriage\n try:\n self.__ConfServiceclient.service.updateAttribute(attributeDefinitionId, attributeDefinitionSpec)\n except suds.WebFault as detail:\n return detail",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def change_instance_state(cls, ec2_resource, POST):\n\n if 'stop_instance_id' in POST.dict():\n posted_form = StopInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['stop_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).stop()\n elif 'start_instance_id' in POST.dict():\n posted_form = StartInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['start_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).start()\n else:\n posted_form = TerminateInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['terminate_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).terminate()",
"def update(self, attr):\n assert attr is not MispShadowAttribute\n raw = attr.to_xml()\n raw = self.server.POST('/shadow_attributes/edit/%d' % attr.id, raw)\n response = objectify.fromstring(raw)\n return MispShadowAttribute.from_xml_object(response.ShadowAttribute)",
"def update_attribute(self, instance, name, field, value):\n field_setter = getattr(self, f\"set_{name}\", None)\n if field_setter:\n field_setter(instance, name, field, value)\n else:\n setattr(instance, name, value)",
"def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):\n pass",
"def change_instance_metadata(self, *args, **kwargs):\n pass",
"def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):\n pass",
"def update_attributes_instability(attrs_inst: Dict[Attribute, float]):\n for attribute, attribute_instability in attrs_inst.items():\n attributes_instability[attribute] = attribute_instability",
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def set_attr_3(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr3\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)",
"def attribute_rename_cmd(oldattr, newattr):\n def processor(cm):\n print_cmd_status('Rename attribute: \"%s\" => \"%s\"' % (oldattr, newattr))\n cm.rename_attribute(oldattr, newattr)\n return cm\n return processor",
"def lock_unlock_attribute(element, attribute, state):\n\n try:\n cmds.setAttr(\"{}.{}\".format(element, attribute), lock=state)\n return True\n except RuntimeError:\n return False",
"def set_attr_1(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr1\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Set the instance affinity value for a specific stopped instance and modify the instance tenancy setting. Instance affinity is disabled by default. When instance affinity is host and it is not associated with a specific Dedicated Host, the next time it is launched it will automatically be associated with the host it lands on. This relationship will persist if the instance is stopped/started, or rebooted. You can modify the host ID associated with a stopped instance. If a stopped instance has a new host ID association, the instance will target that host when restarted. You can modify the tenancy of a stopped instance with a tenancy of host or dedicated . Affinity, hostID, and tenancy are not required parameters, but at least one of them must be specified in the request. Affinity and tenancy can be modified in the same request, but tenancy can only be modified on instances that are stopped.
|
def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):
pass
|
[
"def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):\n pass",
"def set_affinity(irqId,affinity):\n attributes = {'cpu':affinity}\n req = requests.put(_url('/irqsummary/'+str(irqId)),data={'cpu' : affinity})\n if 'old affinity' in req.json():\n print(\"Affinity for IRQ %s changed from %s to %s\" % (irqId, req.json()['old affinity'],req.json()['new affinity']))\n if 'message' in req.json():\n print(req.json()['message'])",
"def set_affinity_strategy(self, affinity, strategy_t):\n self.affinity_strategies[affinity] = strategy_t(self)",
"def qemu_set_affinity(self, *host_cpus):\n for _ in range(3):\n try:\n qemu_cpus = self.get_qemu_pids()\n\n if len(qemu_cpus) != len(host_cpus):\n sleep(1)\n continue\n for qemu_cpu, host_cpu in zip(qemu_cpus, host_cpus):\n command = ('taskset -pc {host_cpu} {thread}'.\n format(host_cpu=host_cpu, thread=qemu_cpu))\n message = ('QEMU: Set affinity failed on {host}!'.\n format(host=self._node['host']))\n exec_cmd_no_error(self._node, command, sudo=True,\n message=message)\n break\n except (RuntimeError, ValueError):\n self.qemu_kill_all()\n raise\n else:\n self.qemu_kill_all()\n raise RuntimeError('Failed to set Qemu threads affinity!')",
"def update_instance_host(self, context, instance):\n self._service.update_correct_host(context, instance)",
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def vm_affinity_rule(\n name,\n affinity,\n vm_names,\n cluster_name,\n datacenter_name,\n enabled=True,\n mandatory=None,\n service_instance=None,\n):\n log.debug(f\"Configuring a vm to vm DRS rule {name} on cluster {cluster_name}.\")\n if service_instance is None:\n service_instance = get_service_instance(opts=__opts__, pillar=__pillar__)\n dc_ref = utils_common.get_datacenter(service_instance, datacenter_name)\n cluster_ref = utils_cluster.get_cluster(dc_ref, cluster_name)\n vm_refs = []\n missing_vms = []\n for vm_name in vm_names:\n vm_ref = utils_common.get_mor_by_property(service_instance, vim.VirtualMachine, vm_name)\n if not vm_ref:\n missing_vms.append(vm_name)\n vm_refs.append(vm_ref)\n if missing_vms:\n raise salt.exceptions.VMwareApiError({f\"Could not find virtual machines {missing_vms}\"})\n rules = cluster_ref.configuration.rule\n rule_ref = None\n if rules:\n for rule in rules:\n if rule.name == name:\n rule_info = utils_cluster.drs_rule_info(rule)\n if utils_cluster.check_affinity(rule) != affinity:\n return {\n \"updated\": False,\n \"message\": f\"Existing rule of name {name} has an affinity of {not affinity} and cannot be changed, make new rule.\",\n }\n if (\n rule_info[\"vms\"] == vm_names\n and rule_info[\"enabled\"] == enabled\n and rule_info[\"mandatory\"] == mandatory\n ):\n return {\n \"updated\": True,\n \"message\": \"Exact rule already exists.\",\n }\n rule_ref = rule\n\n if rule_ref:\n utils_cluster.update_drs_rule(rule_ref, vm_refs, enabled, mandatory, cluster_ref)\n return {\"updated\": True}\n else:\n utils_cluster.create_drs_rule(name, affinity, vm_refs, enabled, mandatory, cluster_ref)\n return {\"created\": True}",
"def config_numa_affinity(self, session, vmname, vmnic):\n if self.verify_numa_affinity(session, vmname, vmnic):\n return True\n else:\n data = vmUtil.read_vmx(session, vmname)\n _LOGGER.debug(f' Executing command : cat vmfs/volumes/{vmUtil.get_datastore(session, vmname)}/{vmname}/{vmname}.vmx | grep \"numa.nodeAffinity =\" -i')\n stdin, stdout, stderr = session.exec_command(f'cat vmfs/volumes/{vmUtil.get_datastore(session, vmname)}/{vmname}/{vmname}.vmx | grep \"numa.nodeAffinity =\" -i')\n a = stdout.read().decode()\n e = vmUtil.get_numa_node(session, vmname)\n if a:\n _LOGGER.debug(f'Adding : numa.nodeAffinity = \"{e}\" in vmx file ')\n data += f'numa.nodeAffinity = \"{e}\"'\n data = data.replace('\"', '\\\\\"')\n _LOGGER.debug(f'Adding changes for NUMA affinity in vmx file.')\n stdin, stdout, stderr = session.exec_command(f'echo \"{data}\" > vmfs/volumes/{vmUtil.get_datastore(session, vmname)}/{vmname}/{vmname}.vmx')\n return False if stderr.read() else True\n # return True\n else:\n _LOGGER.debug(f'Executing command : vsish -e get /net/pNics/{vmnic}/properties | grep NUMA ')\n stdin, stdout, stderr = session.exec_command(f'vsish -e get /net/pNics/{vmnic}/properties | grep NUMA')\n r = stdout.read().decode()\n st = re.search('\\d', r)\n if st:\n numa = st.group()\n old = vmUtil.get_numa_node(session, vmname)\n _LOGGER.debug(f'Replacing : numa.nodeAffinity = \\\"{old}\\\" to numa.nodeAffinity = \\\"{numa}\\\"')\n data = data.replace(f'numa.nodeAffinity = \"{old}\"', f'numa.nodeAffinity = \"{numa}\"')\n data = data.replace('\"', '\\\\\"')\n _LOGGER.debug(f'Adding changes for NUMA affinity in vmx file.')\n stdin, stdout, stderr = session.exec_command(f'echo \"{data}\" > vmfs/volumes/{vmUtil.get_datastore(session, vmname)}/{vmname}/{vmname}.vmx')\n return False if stderr.read() else True\n else:\n _LOGGER.error(f'unable to configure node affinity for vmnic : {vmnic}')",
"def update_instance_info(self, context, host_name, instance_info):\n self.host_manager.update_instance_info(\n context, host_name, instance_info)",
"def set_affinity(\n gpu_id,\n nproc_per_node,\n *,\n mode=\"unique_contiguous\",\n scope=\"node\",\n cores=\"all_logical\",\n balanced=True,\n min_cores=1,\n max_cores=None,\n):\n pynvml.nvmlInit()\n\n if mode == \"all\":\n affinity = get_all(nproc_per_node, scope, cores, min_cores, max_cores)\n elif mode == \"single\":\n affinity = get_single(nproc_per_node, scope, cores)\n elif mode == \"single_unique\":\n affinity = get_single_unique(nproc_per_node, scope, cores)\n elif mode == \"unique_interleaved\" or mode == \"unique_contiguous\":\n affinity = get_unique(\n nproc_per_node,\n scope,\n cores,\n mode,\n min_cores,\n max_cores,\n balanced,\n )\n else:\n raise RuntimeError(\"Unknown affinity mode\")\n\n os.sched_setaffinity(0, affinity[gpu_id])\n set_affinity = os.sched_getaffinity(0)\n return set_affinity",
"def __init__(__self__, *,\n pod_affinity_term: 'outputs.InfinispanSpecAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm',\n weight: int):\n pulumi.set(__self__, \"pod_affinity_term\", pod_affinity_term)\n pulumi.set(__self__, \"weight\", weight)",
"def update_affinity_group(self, api_client, affinitygroupids=None,\n affinitygroupnames=None):\n cmd = {'id': self.id}\n\n if affinitygroupids:\n cmd['affinitygroupids'] = affinitygroupids\n\n if affinitygroupnames:\n cmd['affinitygroupnames'] = affinitygroupnames\n\n return api_client.updateVMAffinityGroup(**cmd)",
"def start(self, accelerator=None, accel_parameters=None, stop_mode=None,\n image_id=None, instance_type=None):\n # Updates stop mode\n self.stop_mode = stop_mode\n\n # Starts instance only if not already started\n if self._host_ip is None:\n\n # Get parameters from accelerator\n self._set_accelerator_requirements(\n accelerator=accelerator, accel_parameters=accel_parameters,\n image_id=image_id, instance_type=instance_type)\n\n # Checks CSP credential\n self._check_credential()\n\n # Creates and starts instance if not exists\n if self.instance_id is None:\n _get_logger().info(\n \"Configuring host on %s instance...\", self._host_type)\n\n with self._stop_silently_on_exception():\n self._create_instance()\n\n with self._stop_silently_on_exception():\n self._instance, self._instance_id = \\\n self._start_new_instance()\n\n _get_logger().debug(_utl.gen_msg(\n 'created_named', 'instance', self._instance_id))\n\n # If exists, starts it directly\n else:\n self._start_existing_instance(self._status())\n\n # Waiting for instance provisioning\n with self._stop_silently_on_exception():\n self._wait_instance_ready()\n\n # Update instance URL\n self._host_ip = self.host_ip\n self._url = _utl.format_url(\n self._host_ip, force_secure=bool(self._ssl_cert_crt))\n\n # Waiting for the instance to boot\n self._wait_instance_boot()\n\n _get_logger().info(\"Host ready\")\n\n # If Host IP exists exists, checks if reachable\n elif self.ALLOW_PORTS and not _utl.check_port(self.host_ip, 80):\n raise _exc.HostRuntimeException(\n gen_msg=('unable_reach_port', self.host_ip, 80))",
"def test_instance_update_instance_type(self):\r\n return_server = self.fc.servers.list()[1]\r\n return_server.id = '1234'\r\n instance = self._create_test_instance(return_server,\r\n 'ud_type')\r\n\r\n update_template = copy.deepcopy(instance.t)\r\n update_template['Properties']['InstanceType'] = 'm1.small'\r\n\r\n self.m.StubOutWithMock(self.fc.servers, 'get')\r\n self.fc.servers.get('1234').AndReturn(return_server)\r\n\r\n def activate_status(server):\r\n server.status = 'VERIFY_RESIZE'\r\n return_server.get = activate_status.__get__(return_server)\r\n\r\n self.m.StubOutWithMock(self.fc.client, 'post_servers_1234_action')\r\n self.fc.client.post_servers_1234_action(\r\n body={'resize': {'flavorRef': 2}}).AndReturn((202, None))\r\n self.fc.client.post_servers_1234_action(\r\n body={'confirmResize': None}).AndReturn((202, None))\r\n self.m.ReplayAll()\r\n\r\n scheduler.TaskRunner(instance.update, update_template)()\r\n self.assertEqual((instance.UPDATE, instance.COMPLETE), instance.state)\r\n self.m.VerifyAll()",
"def _set_service_instance(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name=\"service-instance\", rest_name=\"service-instance\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)\n except (TypeError, ValueError):\n raise ValueError({\n 'error-string': \"\"\"service_instance must be of a type compatible with uint32\"\"\",\n 'defined-type': \"uint32\",\n 'generated-type': \"\"\"YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name=\"service-instance\", rest_name=\"service-instance\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='uint32', is_config=False)\"\"\",\n })\n\n self.__service_instance = t\n if hasattr(self, '_set'):\n self._set()",
"def set_schedule(self, schedule):\n data = {'propagateToInstances':True, 'schedule':schedule}\n return self.client.put_asg_scaling_schedule(environment=self.env, asgname=self.name, data=data)",
"def set_hvac_mode(self, hvac_mode):\n if hvac_mode == HVAC_MODE_HEAT:\n # heat\n url = f\"http://{self._ip_addr}/cmd?heater_2=1\"\n r = requests.get(url)\n self._current_hvac_mode = HVAC_MODE_HEAT\n elif hvac_mode == HVAC_MODE_FAN_ONLY:\n # pump only\n url = f\"http://{self._ip_addr}/cmd?heater_general=0\"\n r = requests.get(url)\n url = f\"http://{self._ip_addr}/cmd?water_pump=1\"\n r = requests.get(url)\n self._current_hvac_mode = HVAC_MODE_FAN_ONLY\n elif hvac_mode == HVAC_MODE_OFF:\n # all off\n url = f\"http://{self._ip_addr}/cmd?water_pump=0\"\n r = requests.get(url)\n self._current_hvac_mode = HVAC_MODE_OFF",
"def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu):\r\n self._validate_vm_cpu(vm_cpu)\r\n self._change_vm_cpu(vapp_or_vm_id, vm_cpu)",
"def user32_SetWindowDisplayAffinity(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"hWnd\", \"dwAffinity\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the specified network interface attribute. You can specify only one attribute at a time.
|
def modify_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, Description=None, SourceDestCheck=None, Groups=None, Attachment=None):
pass
|
[
"def ModifyNetworkInterfaceAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyNetworkInterfaceAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyNetworkInterfaceAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def set_attribute(self,att,val):\r\n self.attributes[att] = val",
"def setPaintAttribute(self, attribute, on=True):\r\n if on:\r\n self.__data.paintAttributes |= attribute\r\n else:\r\n self.__data.paintAttributes &= ~attribute",
"def setLayoutAttribute(self, attribute, on=True):\r\n if on:\r\n self.__data.layoutAttributes |= attribute\r\n else:\r\n self.__data.layoutAttributes &= ~attribute",
"def update(self, attribute, data):\n return self.call('catalog_product_attribute.update', [attribute, data])",
"def modify_image_attribute(DryRun=None, ImageId=None, Attribute=None, OperationType=None, UserIds=None, UserGroups=None, ProductCodes=None, Value=None, LaunchPermission=None, Description=None):\n pass",
"def describe_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, Attribute=None):\n pass",
"def set_linux_interface_promisc(\n node, interface, namespace=None, vf_id=None, state=u\"on\"):\n promisc_str = f\"vf {vf_id} promisc {state}\" if vf_id is not None \\\n else f\"promisc {state}\"\n ns_str = f\"ip netns exec {namespace}\" if namespace else u\"\"\n\n cmd = f\"{ns_str} ip link set dev {interface} {promisc_str}\"\n exec_cmd_no_error(node, cmd, sudo=True)",
"def setAttribute(self, attributename, attributevalue):\n\n self.send('setAttribute(\"' + attributename + '\", \"'\n + attributevalue + '\");')",
"def updateAttribute(self,\n instid,\n attrid,\n attr,\n commitComment=None):\n path = \"api/v1/inst/%(instid)s/%(attrid)s\"\n path_params = {\"instid\": instid,\n \"attrid\": attrid}\n query_params = {}\n form_params = {\"attr\": attr,\n \"commitComment\": commitComment}\n result = self.conn.invoke_method(\"PUT\", path, path_params,\n query_params, form_params)\n if result.error:\n raise IbisException(result.error)\n return result.attribute",
"def set_linux_interface_state(\n node, interface, namespace=None, state=u\"up\"):\n ns_str = f\"ip netns exec {namespace}\" if namespace else u\"\"\n\n cmd = f\"{ns_str} ip link set dev {interface} {state}\"\n exec_cmd_no_error(node, cmd, sudo=True)",
"def change_macaddr(interface: str, new_macaddr: str) -> None:\n subprocess.call(['ifconfig', interface, 'down'])\n subprocess.call(['ifconfig', interface, 'hw', 'ether', new_macaddr])\n subprocess.call(['ifconfig', interface, 'up'])",
"def SetWirelessInterface(self, interface):\n print \"setting wireless interface %s\" % (str(interface))\n self.wifi.wireless_interface = noneToBlankString(interface)\n self.config.set(\"Settings\", \"wireless_interface\", interface, write=True)",
"def change_mac(interface, new_mac):\n print(f\"[+] Changing MAC address for {interface} to {new_mac}\")\n\n try:\n subprocess.call([\"ip\", \"link\", \"set\", interface, \"down\"])\n subprocess.call([\"ip\", \"link\", \"set\", interface, \"address\", new_mac])\n subprocess.call([\"ip\", \"link\", \"set\", interface, \"up\"])\n except Exception as e:\n print(e)\n return -1",
"def lock_unlock_attribute(element, attribute, state):\n\n try:\n cmds.setAttr(\"{}.{}\".format(element, attribute), lock=state)\n return True\n except RuntimeError:\n return False",
"def update(self, attr):\n assert attr is not MispShadowAttribute\n raw = attr.to_xml()\n raw = self.server.POST('/shadow_attributes/edit/%d' % attr.id, raw)\n response = objectify.fromstring(raw)\n return MispShadowAttribute.from_xml_object(response.ShadowAttribute)",
"def vpp_set_interface_mac(node, interface, mac):\n cmd = u\"sw_interface_set_mac_address\"\n args = dict(\n sw_if_index=InterfaceUtil.get_interface_index(node, interface),\n mac_address=L2Util.mac_to_bin(mac)\n )\n err_msg = f\"Failed to set MAC address of interface {interface}\" \\\n f\"on host {node[u'host']}\"\n with PapiSocketExecutor(node) as papi_exec:\n papi_exec.add(cmd, **args).get_reply(err_msg)",
"def replace_attr(self, attr, value, force = True):\r\n # One or the other\r\n if force or self.get(attr) is None:\r\n self[attr] = value",
"def set_linux_interface_mac(\n node, interface, mac, namespace=None, vf_id=None):\n mac_str = f\"vf {vf_id} mac {mac}\" if vf_id is not None \\\n else f\"address {mac}\"\n ns_str = f\"ip netns exec {namespace}\" if namespace else u\"\"\n\n cmd = f\"{ns_str} ip link set {interface} {mac_str}\"\n exec_cmd_no_error(node, cmd, sudo=True)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the Availability Zone, instance count, instance type, or network platform (EC2Classic or EC2VPC) of your Standard Reserved Instances. The Reserved Instances to be modified must be identical, except for Availability Zone, network platform, and instance type. For more information, see Modifying Reserved Instances in the Amazon Elastic Compute Cloud User Guide.
|
def modify_reserved_instances(ClientToken=None, ReservedInstancesIds=None, TargetConfigurations=None):
pass
|
[
"def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):\n pass",
"def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):\n pass",
"def ElasticIps(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n return self.reservation",
"def optimizeReservation(verbose,region):\n print(\"WARNING: As it's not possible to get OS through AWS API, All \"\\\n \"Linux are reported as Linux (no RedHat, Suse, etc)\\n\"\\\n \"This issue will be address in a future update\\n\\n\")\n shouldReserved = {}\n dreserved = getReservedInstances(False)\n dinstances = listInstances(False)\n dflavors = getInstanceTypes(region)\n count_by_type_os = countInstanceByTypeByOS(False, dinstances)\n resp = \"\"\n for typos, nb in count_by_type_os.items():\n if typos in dreserved:\n if int(count_by_type_os[typos]) - int(dreserved[typos]) >= 0:\n count_by_type_os[typos] = int(count_by_type_os[typos]) - int(dreserved[typos])\n resp += \"Reservation fully used for \"+typos+\"\\n\"\n else:\n print(\"Reservation not fully used for \"+typos+\": \"+dreserved[typos]+\"reserved but only \"+count_by_type_os[typos]+\" instances\")\n for typos, nb in dreserved.items():\n if typos not in count_by_type_os:\n resp += \"Reservation is not used for \"+typos+\"\\n\"\n #Provide tips for better reservations\n #Begin by removing instances that have reservation\n for instanceId in list(dinstances):\n if dinstances[instanceId]['flavor'] in dreserved:\n if int(dreserved[dinstances[instanceId]['flavor']]) > 0:\n dreserved[dinstances[instanceId]['flavor']] -= 1\n del dinstances[instanceId]\n today = datetime.datetime.now(datetime.timezone.utc)\n months6 = today-datetime.timedelta(days=180)\n for k, v in dinstances.items():\n if v['LaunchTime'] < months6:\n try:\n shouldReserved[v['flavor']+\";\"+v['platform']] += 1\n except:\n shouldReserved[v['flavor']+\";\"+v['platform']] = 1\n resp += \"\\nBased on instances older than 6 months, you should buy following reservations:\\n\"\n saveno, savepa = 0, 0\n for k, v in shouldReserved.items():\n resp += k+\":\"+str(v)+\"\\n\"\n saveno += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1yno'])) * v\n savepa += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1ypa'])) * v\n resp += \"You can save up to \"+str(saveno)+\"$/hour with no upfront reservation\\n\"\n resp += \"You can save up to \"+str(savepa)+\"$/hour with partial upfront reservation\\n\"\n if verbose:\n resp += \"\\nInstances below doesn't have reservation:\\n\"\n for k, v in count_by_type_os.items():\n resp += k+\":\"+str(v)+\"\\n\"\n return saveno, resp",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def getReservedInstances(verbose):\n lres = {}\n jResp = EC2C.describe_reserved_instances()\n for reserved in jResp['ReservedInstances']:\n if reserved['State'] == 'active':\n if verbose:\n lres[reserved['InstanceType']] = str(reserved['Start'])+\";\"+\\\n str(reserved['End'])+\";\"+\\\n str(reserved['InstanceCount'])+\";\"+\\\n reserved['ProductDescription']+\";\"+\\\n str(reserved['UsagePrice'])\n else:\n if re.search(\"win\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"windows\"\n elif re.search(\"red hat\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"redhat\"\n elif re.search(\"suse\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"suse\"\n else:\n os = \"linux\"\n lres[reserved['InstanceType']+\";\"+os] = str(reserved['InstanceCount'])\n return lres",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def describe_reserved_instances_modifications(ReservedInstancesModificationIds=None, NextToken=None, Filters=None):\n pass",
"def terminate_instances(self):\n\n if self._reservation and self._reservation.instances:\n for instance in self._reservation.instances:\n instance.terminate()\n msg = 'EC2 instance terminated.'\n log.info(msg)\n self._store_message(msg)",
"def control_instance(stackName, action, instanceName=None):\n try:\n aws_cfg\n except NameError:\n try:\n aws_cfg = load_aws_cfg()\n except Exception, error:\n print(_red(\"error loading config. please provide an AWS conifguration based on aws.cfg-dist to proceed. %s\" % error))\n return 1\n\n stackName = stackName.lower()\n opsworks = connect_to_opsworks()\n stacks = opsworks.describe_stacks()\n stackId = [stack['StackId'] for stack in stacks['Stacks'] if stack['Name'] == stackName]\n if stackId == []:\n print(_red(\"stack %s not found\" % stackName))\n return 1\n instances = opsworks.describe_instances(stack_id=stackId[0])['Instances']\n if instanceName is not None:\n instances = [instance for instance in instances if instance['Hostname'] == instanceName]\n\n ec2 = connect_to_ec2()\n for instance in instances:\n if action == 'start':\n print(_green(\"starting instance: %s\" % instance['Hostname']))\n try:\n opsworks.start_instance(instance_id=instance['InstanceId'])\n except ValidationException:\n pass\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n spinner = Spinner(_yellow(\"[%s]Waiting for reservation \" % myinstance['Hostname']), hide_cursor=False)\n while myinstance['Status'] == 'requested':\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks instance status: %s\" % (myinstance['Hostname'], myinstance['Status'])))\n ec2Instance = ec2.get_only_instances(instance_ids=[myinstance['Ec2InstanceId']])[0]\n spinner = Spinner(_yellow(\"[%s]Booting ec2 instance \" % myinstance['Hostname']), hide_cursor=False)\n while ec2Instance.state != u'running':\n spinner.next()\n time.sleep(1)\n ec2Instance.update()\n print(_green(\"\\n[%s]ec2 Instance state: %s\" % (myinstance['Hostname'], ec2Instance.state)))\n spinner = Spinner(_yellow(\"[%s]Running OpsWorks setup \" % myinstance['Hostname']), hide_cursor=False)\n while myinstance['Status'] != 'online':\n if myinstance['Status'] == 'setup_failed':\n print(_red(\"\\n[%s]OpsWorks instance failed\" % myinstance['Hostname']))\n return 1\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks Instance state: %s\" % (myinstance['Hostname'], myinstance['Status'])))\n getec2instances()\n elif action == 'stop':\n if 'Ec2InstanceId' in instance.keys():\n print(_green(\"Stopping instance %s\" % instance['Hostname']))\n opsworks.stop_instance(instance_id=instance['InstanceId'])\n ec2Instance = ec2.get_only_instances(instance_ids=[instance['Ec2InstanceId']])[0]\n spinner = Spinner(_yellow(\"[%s]Waiting for ec2 instance to stop \" % instance['Hostname']), hide_cursor=False)\n while ec2Instance.state != u'stopped':\n spinner.next()\n time.sleep(1)\n ec2Instance.update()\n print(_green(\"\\n[%s]ec2 Instance state: %s\" % (instance['Hostname'], ec2Instance.state)))\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n spinner = Spinner(_yellow(\"[%s]Stopping OpsWorks Instance \" % instance['Hostname']), hide_cursor=False)\n while myinstance['Status'] != 'stopped':\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks Instance state: %s\" % (instance['Hostname'], myinstance['Status'])))\n else:\n print(_green(\"%s in %s already stopped\" % (instance['Hostname'], stackName)))\n try:\n print(_green(\"removing %s from ssh config...\" % instance['PublicDns']))\n removefromsshconfig(dns=instance['PublicDns'])\n except Exception:\n pass",
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def PrivateIPAddressing(self, zone = None):\n self.private_addressing = True\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name, private_addressing=self.private_addressing, zone=zone)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n if (instance.public_dns_name != instance.private_dns_name):\n self.tester.critical(\"Instance received a new public IP: \" + instance.public_dns_name)\n return self.reservation",
"def enable_sr_iov(self, instance, ssh_client):\n conn = self.conn or self.vpc_conn\n log.info('Enabling SR-IOV on {}'.format(instance.id))\n if ssh_client:\n util_path = os.path.dirname(os.path.realpath(__file__))\n ssh_client.put_file(os.path.join(util_path, 'tests', 'enable_sr_iov.sh'),\n '/tmp/enable_sr_iov.sh')\n ssh_client.run('chmod +x /tmp/enable_sr_iov.sh')\n ssh_client.run(\"sed -i 's/\\r//' /tmp/enable_sr_iov.sh\")\n ssh_client.run('/tmp/enable_sr_iov.sh {}'.format(self.instancetype))\n conn.stop_instances(instance_ids=[instance.id])\n self.wait_for_state(instance, 'state', 'stopped')\n if self.instancetype in [constants.AWS_P28XLARGE, constants.AWS_M416XLARGE]:\n log.info('Enabling ENA for instance: {}'.format(self.instancetype))\n import boto3\n client = boto3.client('ec2', region_name=self.region, aws_access_key_id=self.keyid,\n aws_secret_access_key=self.secret)\n client.modify_instance_attribute(InstanceId=instance.id, Attribute='enaSupport',\n Value='true')\n log.info('ENA support: {}'.format(client.__dict__))\n try:\n log.info(conn.get_instance_attribute(instance.id, 'enaSupport'))\n except Exception as e:\n log.info(e)\n pass\n # conn.modify_instance_attribute(instance.id, 'enaSupport', True)\n # ena_status = conn.get_instance_attribute(instance.id, 'enaSupport')\n # log.info('ENA status for {} instance: {}'.format(constants.AWS_P28XLARGE,\n # ena_status))\n elif self.instancetype == constants.AWS_D24XLARGE:\n conn.modify_instance_attribute(instance.id, 'sriovNetSupport', 'simple')\n sriov_status = conn.get_instance_attribute(instance.id, 'sriovNetSupport')\n log.info(\"SR-IOV status is: {}\".format(sriov_status))\n else:\n log.error('Instance type {} unhandled for SRIOV'.format(self.instancetype))\n return None\n conn.start_instances(instance_ids=[instance.id])\n self.wait_for_state(instance, 'state', 'running')\n\n return self.wait_for_ping(instance)",
"def change_instance_state(cls, ec2_resource, POST):\n\n if 'stop_instance_id' in POST.dict():\n posted_form = StopInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['stop_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).stop()\n elif 'start_instance_id' in POST.dict():\n posted_form = StartInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['start_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).start()\n else:\n posted_form = TerminateInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['terminate_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).terminate()",
"def create_instance(config):\n\n try:\n client = boto3.client('ec2')\n except Exception as e:\n print(f'An error occurred while creating the boto3 client: {e}')\n sys.exit(1)\n\n ami_id = _get_ami_id(client, config.ami_type, config.architecture, config.root_device_type, config.virtualization_type)\n default_vpc_id = _ensure_default_vpc(client)\n key_pair_names = _create_key_pairs(client, config)\n\n blockDeviceMappings = []\n for volume in config.volumes:\n blockDeviceMappings.append({\n 'DeviceName': volume.device,\n 'Ebs': {\n 'DeleteOnTermination': True,\n 'VolumeSize': volume.size_gb,\n 'VolumeType': 'gp2',\n },\n })\n\n res = client.run_instances(\n BlockDeviceMappings=blockDeviceMappings,\n\n ImageId=ami_id,\n InstanceType=config.instance_type,\n\n MaxCount=config.max_count,\n MinCount=config.min_count,\n\n SecurityGroupIds=[\n _create_security_group(client, default_vpc_id)\n ],\n\n UserData=_user_data_script(config),\n )\n\n ec2 = boto3.resource('ec2')\n instances = res['Instances']\n\n for i, instance in enumerate(instances):\n public_ip = ec2.Instance(instance['InstanceId']).public_ip_address\n print(f'instance {i} public ip address = {public_ip}')",
"def tag_instance(request):\n log('Tagging instance with: {}', request.instance_tags)\n _azure('vm', 'update',\n '--name', request.vm_name,\n '--resource-group', request.resource_group,\n '--set', *['tags.{}={}'.format(tag, value)\n for tag, value in request.instance_tags.items()])",
"def update_instances(self, collection, instances):\n for instance in instances:\n self.database[collection].update_one({'_id': instance['_id']}, {\"$set\": {'need_update': False}})",
"def testUpdateFromStdIn(self):\n self.WriteInput(export_util.Export(self._modified_instance))\n self._RunUpdate('instance-1 --zone=zone-1 --project=my-project')\n self.CheckRequests([(self.compute.instances, 'Update',\n self.messages.ComputeInstancesUpdateRequest(\n instance='instance-1',\n zone='zone-1',\n project='my-project',\n instanceResource=self._modified_instance))])",
"def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCount=None, OfferingClass=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single API call. If you need to both add and remove account IDs for a snapshot, you must use multiple API calls. For more information on modifying snapshot permissions, see Sharing Snapshots in the Amazon Elastic Compute Cloud User Guide .
|
def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):
pass
|
[
"def modify_snap_access_mode(self, snapshot_id, snap_access_mode):\n\n try:\n self.powerflex_conn.volume.set_volume_access_mode_limit(\n volume_id=snapshot_id, access_mode_limit=snap_access_mode)\n return True\n except Exception as e:\n errormsg = \"Modify access mode of snapshot %s operation \" \\\n \"failed with error %s\" % (snapshot_id, str(e))\n LOG.error(errormsg)\n self.module.fail_json(msg=errormsg)",
"def add_snapshot_rules_to_protection_policy(self, policy_id,\n add_snapshot_rule_ids):\n LOG.info(\"Adding snapshot_rules: '%s' to policy: '%s'\"\n % (add_snapshot_rule_ids, policy_id))\n return self.modify_protection_policy(\n policy_id=policy_id, add_snapshot_rule_ids=add_snapshot_rule_ids\n )",
"def modify_filesystem_snapshot(self, snapshot_id, **kwargs):\n LOG.info(\"Modifying filesystem snapshot: '%s' with param: '%s'\"\n % (snapshot_id, kwargs))\n return self.rest_client.request(\n constants.PATCH, constants.MODIFY_FILESYSTEM_URL.format(\n self.server_ip, snapshot_id), payload=kwargs)",
"def modify_access_mode(self, snapshot_id, access_mode_list):\n\n try:\n changed = False\n for temp in access_mode_list:\n if temp['accessMode']:\n self.powerflex_conn.volume.set_access_mode_for_sdc(\n volume_id=snapshot_id, sdc_id=temp['sdc_id'],\n access_mode=temp['accessMode'])\n changed = True\n return changed\n except Exception as e:\n errormsg = \"Modify access mode of SDC %s operation failed \" \\\n \"with error %s\" % (temp['sdc_id'], str(e))\n LOG.error(errormsg)\n self.module.fail_json(msg=errormsg)",
"def test_filesystem_snapshot_permissions(self):\n pool_name = make_test_pool(StratisCertify.DISKS[0:1])\n filesystem_name = make_test_filesystem(pool_name)\n snapshot_name = fs_n()\n self._test_permissions(\n [\n _STRATIS_CLI,\n \"filesystem\",\n \"snapshot\",\n pool_name,\n filesystem_name,\n snapshot_name,\n ],\n True,\n True,\n )",
"def snapshotModifyKeyCtx(image1=\"string\", history=bool, exists=bool, image2=\"string\", name=\"string\", image3=\"string\"):\n pass",
"def modify_volume_snapshot(self, snapshot_id, name=None, description=None,\n expiration_timestamp=None):\n LOG.info(\"Modifying volume snapshot: '%s'\" % snapshot_id)\n payload = self._prepare_create_modify_snapshot_payload(\n name=name, description=description,\n expiration_timestamp=expiration_timestamp\n )\n self.rest_client.request(\n constants.PATCH,\n constants.MODIFY_VOLUME_URL.format(self.server_ip, snapshot_id),\n payload\n )\n return self.get_volume_snapshot_details(snapshot_id)",
"def update_image_permissions(instance, action, reverse, model, pk_set, **_):\n if action not in [\"post_add\", \"post_remove\", \"pre_clear\"]:\n # nothing to do for the other actions\n return\n\n if reverse:\n images = Image.objects.filter(pk=instance.pk)\n if pk_set is None:\n # When using a _clear action, pk_set is None\n # https://docs.djangoproject.com/en/2.2/ref/signals/#m2m-changed\n archives = instance.archive_set.all()\n else:\n archives = model.objects.filter(pk__in=pk_set)\n\n archives = archives.select_related(\"users_group\", \"editors_group\")\n else:\n archives = [instance]\n if pk_set is None:\n # When using a _clear action, pk_set is None\n # https://docs.djangoproject.com/en/2.2/ref/signals/#m2m-changed\n images = instance.images.all()\n else:\n images = model.objects.filter(pk__in=pk_set)\n\n op = assign_perm if \"add\" in action else remove_perm\n\n for archive in archives:\n op(\"view_image\", archive.editors_group, images)\n op(\"view_image\", archive.uploaders_group, images)\n op(\"view_image\", archive.users_group, images)",
"def update_object_permissions(self, user, account, container, name,\n permissions):\n return",
"def SetPermissions(self, script):\n\n self.CountChildMetadata()\n\n def recurse(item, current):\n # current is the (uid, gid, dmode, fmode) tuple that the current\n # item (and all its children) have already been set to. We only\n # need to issue set_perm/set_perm_recursive commands if we're\n # supposed to be something different.\n if item.dir:\n if current != item.best_subtree:\n script.SetPermissionsRecursive(\"/\"+item.name, *item.best_subtree)\n current = item.best_subtree\n\n if item.uid != current[0] or item.gid != current[1] or \\\n item.mode != current[2]:\n if item.uid is not None and item.gid is not None:\n script.SetPermissions(\"/\"+item.name, item.uid, item.gid, item.mode)\n\n for i in item.children:\n recurse(i, current)\n else:\n if item.uid != current[0] or item.gid != current[1] or \\\n item.mode != current[3]:\n script.SetPermissions(\"/\"+item.name, item.uid, item.gid, item.mode)\n\n recurse(self, (-1, -1, -1, -1))",
"def ModifySnapshotPolicies(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifySnapshotPolicies\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifySnapshotPoliciesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def manage(self, share, provider_location,\n driver_options=None,\n name=None, description=None):\n driver_options = driver_options if driver_options else {}\n body = {\n 'share_id': base.getid(share),\n 'provider_location': provider_location,\n 'driver_options': driver_options,\n 'name': name,\n 'description': description,\n }\n return self._create('/snapshots/manage', {'snapshot': body},\n 'snapshot')",
"def test_edit_volume_snapshot(self, snapshot, volumes_steps_ui):\n new_snapshot_name = snapshot.name + '(updated)'\n with snapshot.put(name=new_snapshot_name):\n volumes_steps_ui.update_snapshot(snapshot.name, new_snapshot_name)",
"def test_create_volume_from_snapshot(self, snapshot, volumes_steps_ui):\n volumes_steps_ui.create_volume_from_snapshot(snapshot.name)\n volumes_steps_ui.delete_volume(snapshot.name)",
"def modify_volume_group_snapshot(self, snapshot_id, name=None,\n description=None,\n expiration_timestamp=None):\n LOG.info(\"Modifying volumegroup snapshot: '%s'\" % snapshot_id)\n payload = self._prepare_create_modify_snapshot_payload(\n name=name, description=description,\n expiration_timestamp=expiration_timestamp\n )\n self.rest_client.request(\n constants.PATCH,\n constants.MODIFY_VOLUME_GROUP_URL.format(self.server_ip,\n snapshot_id),\n payload\n )\n return self.get_volume_group_snapshot_details(snapshot_id)",
"def set_api_permissions(sender, instance=None, created=False, **kwargs):\n # pylint: disable=import-outside-toplevel\n from onadata.libs.utils.user_auth import set_api_permissions_for_user\n\n if created:\n set_api_permissions_for_user(instance)",
"def _set_user_permissions_for_volumes(users, volumes):\n\n group_name = 'volumes'\n\n user_data_script_section = f\"\"\"\ngroupadd {group_name}\n\"\"\"\n\n for user in users:\n user_data_script_section += f\"\"\"\nusermod -a -G {group_name} {user.login}\n\"\"\"\n for volume in volumes:\n user_data_script_section += f\"\"\"\nchgrp -R {group_name} {volume.mount}\nchmod -R 2775 {volume.mount} \n\"\"\"\n\n return user_data_script_section",
"def test_manage_snapshot_route(self, mock_service_get,\n mock_create_snapshot, mock_rpcapi):\n mock_service_get.return_value = fake_service.fake_service_obj(\n self._admin_ctxt,\n binary='cinder-volume')\n\n body = {'snapshot': {'volume_id': fake.VOLUME_ID, 'ref': 'fake_ref'}}\n res = self._get_resp_post(body)\n self.assertEqual(202, res.status_int, res)",
"def modify_permissions(self, sdi_id: str, data: Dict[str, Any]) -> APIResponse:\n return self._put(\"permissions\", {\"pk\": self.user_pk, \"sdi_id\": sdi_id}, data)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the specified Spot fleet request. While the Spot fleet request is being modified, it is in the modifying state. To scale up your Spot fleet, increase its target capacity. The Spot fleet launches the additional Spot instances according to the allocation strategy for the Spot fleet request. If the allocation strategy is lowestPrice , the Spot fleet launches instances using the Spot pool with the lowest price. If the allocation strategy is diversified , the Spot fleet distributes the instances across the Spot pools. To scale down your Spot fleet, decrease its target capacity. First, the Spot fleet cancels any open bids that exceed the new target capacity. You can request that the Spot fleet terminate Spot instances until the size of the fleet no longer exceeds the new target capacity. If the allocation strategy is lowestPrice , the Spot fleet terminates the instances with the highest price per unit. If the allocation strategy is diversified , the Spot fleet terminates instances across the Spot pools. Alternatively, you can request that the Spot fleet keep the fleet at its current size, but not replace any Spot instances that are interrupted or that you terminate manually.
|
def modify_spot_fleet_request(SpotFleetRequestId=None, TargetCapacity=None, ExcessCapacityTerminationPolicy=None):
pass
|
[
"def update_request():",
"def put(self, request, *args, **kwargs):\n\n data = request.DATA\n json_validate(SPECS.get('equipment_put')).validate(data)\n response = facade.update_equipment(data['equipments'], request.user)\n\n return Response(response, status=status.HTTP_200_OK)",
"def modify_parameters(\n self,\n request: gpdb_20160503_models.ModifyParametersRequest,\n ) -> gpdb_20160503_models.ModifyParametersResponse:\n runtime = util_models.RuntimeOptions()\n return self.modify_parameters_with_options(request, runtime)",
"def putRequest(self,tripRequest):\n\t\t\"\"\"Cannot modify a trip request after the deadlne and can only modify the time range + mode\"\"\"\n\t\tparser-reqparse.RequestParser()\n\t\tparser.add_argument(\"id\")\n\t\targs=parser.parse_args()\n\n\t\tif TripRequest[id] in TripRequests:\n\t\t\treturn \"That trip does not exist\", 404\n\n\t\tt=datetime.datetime.now()\n\n\t\tif t.hour > 15 :\n\t\t \treturn 'The deadline to modify a trip for today has passed', 404\n\t\telif t.hour > 21:\n\t\t \treturn ' The deadline to modiy a trip for tomorrow AM has passed', 404\n\t\telse:\t\t\n\t\t\ttripRequest[id] = {\n\t\t\tmode: args[mode],\n\t\t\tselectedTimeRange: args[DateTimeRange]\n\t\t\t}\n\t\treturn tripRequest, 200",
"def BumpFee(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def __call__(\n self,\n request: securitycenter_service.UpdateSecurityMarksRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> gcs_security_marks.SecurityMarks:\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=folders/*/assets/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=projects/*/assets/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n {\n \"method\": \"patch\",\n \"uri\": \"/v1p1beta1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}\",\n \"body\": \"security_marks\",\n },\n ]\n request, metadata = self._interceptor.pre_update_security_marks(\n request, metadata\n )\n pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = gcs_security_marks.SecurityMarks()\n pb_resp = gcs_security_marks.SecurityMarks.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_update_security_marks(resp)\n return resp",
"def test_request_can_updated_successfully(self):\r\n request_model.requests.clear()\r\n res = self.client().post('/api/v1/request', data=json.dumps(self.request),\r\n headers={\"content-type\": \"application/json\",\r\n \"access-token\": self.token})\r\n res2 = self.client().put('/api/v1/request/1', data=json.dumps(self.update_request),\r\n headers={\"content-type\": \"application/json\",\r\n \"access-token\": self.token})\r\n self.assertEqual(res2.status_code, 202)\r\n self.assertIn(\"request updated!\",str(res2.data))",
"def UpdateShoppingList(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def Modify(self, request_iterator, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def ModifyGrafanaInstance(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyGrafanaInstance\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyGrafanaInstanceResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def put(self, request, *args, **kwargs):\n\n server_pools = request.DATA\n json_validate(SPECS.get('pool_put')).validate(server_pools)\n verify_ports(server_pools)\n locks_list = facade.create_lock(server_pools.get('server_pools'))\n try:\n response = facade_pool_deploy.update_real_pool(server_pools, request.user)\n except Exception, exception:\n log.error(exception)\n raise rest_exceptions.NetworkAPIException(exception)\n finally:\n facade.destroy_lock(locks_list)\n return Response(response)",
"def render_PUT(self, request):\n err_msg = (\"argument is not correctly formatted.\\n\\n\" \\\n \"Follow 'period [sec]' to update period to observe resource\" \\\n \"[sec] > 2.\\n\\n\").encode(UTF8)\n err_response = aiocoap.Message(code=aiocoap.BAD_REQUEST, payload=err_msg)\n err_response.opt.content_format = r_defs.TEXT_PLAIN_CODE\n\n args = request.payload.decode(UTF8).split()\n if len(args) != 2:\n return err_response\n \n # Observe with period = 0 is not allowed\n if (args[0] == 'period') and (args[1].isdigit() and args[1] != '0'):\n new_period = int(args[1])\n # Physical constraint of the sensor does not allow update faster than 1 sec;\n # double the value to improve reliability\n if new_period <= 2:\n return err_response\n self.observe_period = new_period\n # PUT new value to non-data field requires updating payload wrapper content\n self.payload.set_sample_rate(self.observe_period)\n elif args[0] == 'min':\n self.min = int(args[1])\n elif args[0] == 'max':\n self.max = int(args[1])\n elif args[0] == 'channel':\n self.channel = int(args[1])\n elif args[0] == 'decimal':\n self.fp_format = '.{}f'.format(int(args[1]))\n else:\n return err_response\n \n payload = (\"PUT %s=%s to resource\" % (args[0], args[1])).encode(UTF8)\n response = aiocoap.Message(code=aiocoap.CHANGED, payload=payload)\n response.opt.content_format = r_defs.TEXT_PLAIN_CODE\n \n return response",
"def updatePendingRequests(requestList, newData):\n\trequestList = newData",
"async def editStreetsResource(self, request: IRequest) -> KleinRenderable:\n await self.config.authProvider.authorizeRequest(\n request, None, Authorization.imsAdmin\n )\n\n store = self.config.store\n\n try:\n edits = objectFromJSONBytesIO(request.content)\n except JSONDecodeError as e:\n return invalidJSONResponse(request, e)\n\n for eventID, _streets in edits.items():\n existing = await store.concentricStreets(eventID)\n\n for _streetID, _streetName in existing.items():\n raise NotAuthorizedError(\"Removal of streets is not allowed.\")\n\n for eventID, streets in edits.items():\n existing = await store.concentricStreets(eventID)\n\n for streetID, streetName in streets.items():\n if streetID not in existing:\n await store.createConcentricStreet(\n eventID, streetID, streetName\n )\n\n return noContentResponse(request)",
"def edit_product(req):\n\n name = req.get('name', \"\")\n promo_category_id = req.get('promo_category_id', None)\n product_prices = req.get('product_prices', [])\n is_available = req.get('is_available', 1)\n product_id = int(req['product_id'])\n c = get_cursor()\n c.execute(\"\"\"delete from product_price\n where product_id = %s\"\"\",\n (product_id, ))\n c.execute(\"\"\"update product\n set name = %s,\n promo_category_id = %s,\n is_available = %s\n where product_id = %s\"\"\",\n (name, promo_category_id, is_available, product_id))\n for price in product_prices:\n c.execute(\"\"\"insert into product_price \n (product_id, min_quantity, price, sale_price)\n values (%s, %s, %s, %s)\"\"\",\n (product_id, price['min_quantity'], price['price'], price['sale_price']))\n Db.cache_invalidate()\n return { 'product': Statics.products.get_id(product_id) }",
"def put(self, name):\n # Check the content type and parse the argument appropriately\n parameters = self.parse_request_body(urlencoded_accepted = False)\n model_params = self.validate_parameters_put(name, parameters)\n\n # Build the mission object and store it in the datastore\n mission_to_update = model_params['mission']\n mission_to_update.waypoints = model_params['waypoints']\n mission_to_update.put()\n\n # Return a response with the newly created object id.\n self.build_base_response()\n response_results = {'name' : mission_to_update.name,\n 'content_url' : self.uri_for('missions-resource-named',\n name=mission_to_update.name,\n _full=True)}\n self.response.out.write(json.dumps(response_results))",
"async def limit_maker(symbol, side, quantity, price, new_client_order_id, iceberg_qty, recv_window,\n new_order_resp_type):\n payload = {\n 'symbol': symbol,\n 'side': side,\n 'type': \"LIMIT_MAKER\",\n 'quantity': quantity,\n 'price': price,\n 'newOrderRespType': new_order_resp_type,\n 'recvWindow': recv_window,\n 'timestamp': get_timestamp()\n }\n\n builder = LimitMakerBuilder(endpoint='api/v3/order', payload=payload, method='POST') \\\n .add_optional_params_to_payload(new_client_order_id=new_client_order_id,\n iceberg_qty=iceberg_qty) \\\n .set_security()\n\n await builder.send_http_req()\n\n builder.handle_response().generate_output()",
"def ModifyPrometheusConfig(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyPrometheusConfig\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyPrometheusConfigResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def update_subnet(self, request):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies a subnet attribute. You can only modify one attribute at a time.
|
def modify_subnet_attribute(SubnetId=None, MapPublicIpOnLaunch=None, AssignIpv6AddressOnCreation=None):
pass
|
[
"def update_subnet(self, request):",
"def update_subnet(self, context, _id, subnet):\n t_ctx = t_context.get_context_from_neutron_context(context)\n b_subnet = self.core_plugin.get_subnet(context, _id)\n origin_enable_dhcp = b_subnet['enable_dhcp']\n req_enable_dhcp = subnet['subnet']['enable_dhcp']\n # when request enable dhcp, and origin dhcp is disabled,\n # ensure subnet dhcp port is created\n if req_enable_dhcp and not origin_enable_dhcp:\n self._ensure_subnet_dhcp_port(t_ctx, context, b_subnet)\n res = self.core_plugin.update_subnet(context, _id, subnet)\n return res",
"def update_subnet_pool(self, subnet_pool, **attrs):\n return self._update(_subnet_pool.SubnetPool, subnet_pool, **attrs)",
"def subnet_put_api(subnetid=None):\r\n try:\r\n if not subnetid:\r\n return err_return('subnetId is required', \"ParameterInvalid\",\r\n \"\", HTTP_BAD_REQUEST)\r\n db_subnet = subnet_db_get_one('*', id=subnetid)\r\n if not db_subnet:\r\n return err_return('subnetId does not exist', \"ParameterInvalid\",\r\n \"\", HTTP_NOT_FOUND)\r\n cidr = db_subnet['cidr']\r\n try:\r\n req = models.Subnet(request.json)\r\n req.validate()\r\n except Exception as e:\r\n log.error(e)\r\n return err_return('Parameter Invalid', \"ParameterInvalid\",\r\n \"\", HTTP_BAD_REQUEST)\r\n with MySQLdb.connect(**DB_INFO) as cursor:\r\n if req.subnet_name is not None:\r\n if len(req.subnet_name) > NAME_MAX_LEN:\r\n return err_return('Length of name must be less than 255',\r\n 'ParameterInvalid', '', HTTP_BAD_REQUEST)\r\n sql = \"UPDATE neutron_subnets SET name=%s WHERE id=%s\"\r\n cursor.execute(sql, (req.subnet_name, subnetid))\r\n if req.dns_nameservers is not None:\r\n sql = (\"UPDATE neutron_subnets SET \"\r\n \"dns_nameservers=%s WHERE id=%s\")\r\n cursor.execute(sql,\r\n (json.dumps(req.dns_nameservers), subnetid))\r\n if req.allocation_pools is not None:\r\n allocation_pools = []\r\n for all_pool in req.allocation_pools:\r\n allocation_pools.append(all_pool.to_primitive())\r\n req.allocation_pools = allocation_pools\r\n for pool in req.allocation_pools:\r\n if ip_to_bin(pool['start']) > ip_to_bin(pool['end']):\r\n return err_return(\"end_ip must be more than start_ip\",\r\n \"IPRangeError\", \"\", HTTP_BAD_REQUEST)\r\n networkid = subnetid_to_networkid(subnetid)\r\n db_network = network_db_get_one('*', id=networkid)\r\n external = db_network['external']\r\n log.debug('external=%s' % external)\r\n if external:\r\n if req.allocation_pools is not None:\r\n old_alloc_pools = json.loads(db_subnet['allocation_pools'])\r\n old_alloc_ips = alloc_pools_to_ip_list(old_alloc_pools)\r\n new_alloc_ips = alloc_pools_to_ip_list(req.allocation_pools)\r\n tmp_nips = copy.deepcopy(new_alloc_ips)\r\n for new_ip in tmp_nips:\r\n if new_ip in old_alloc_ips:\r\n new_alloc_ips.remove(new_ip)\r\n old_alloc_ips.remove(new_ip)\r\n isp = lc_vl2_db_get_one('isp', lcuuid=db_network['lcuuid'])\r\n items = lc_ip_res_db_get_all(req='ip, userid, vifid',\r\n isp=isp)\r\n isp_all_ips = []\r\n ip_to_userid = {}\r\n ip_to_vifid = {}\r\n for it in items:\r\n isp_all_ips.append(it['ip'])\r\n ip_to_userid[it['ip']] = it['userid']\r\n ip_to_vifid[it['ip']] = it['vifid']\r\n for new_alloc_ip in new_alloc_ips:\r\n if new_alloc_ip not in isp_all_ips:\r\n return err_return(\"%s invalid\" % new_alloc_ip,\r\n \"IPInvalid\", \"\", HTTP_BAD_REQUEST)\r\n if ip_to_userid[new_alloc_ip] != 0:\r\n return err_return(\"%s in use\" % new_alloc_ip,\r\n \"IPInUse\", \"\", HTTP_BAD_REQUEST)\r\n for old_alloc_ip in old_alloc_ips:\r\n if ip_to_vifid[old_alloc_ip] != 0:\r\n return err_return(\"%s in use\" % old_alloc_ip,\r\n \"IPInUse\", \"\", HTTP_BAD_REQUEST)\r\n sql = (\"UPDATE neutron_subnets SET allocation_pools='%s' \"\r\n \"WHERE id='%s'\" % (json.dumps(req.allocation_pools),\r\n subnetid))\r\n with MySQLdb.connect(**DB_INFO) as cursor:\r\n cursor.execute(sql)\r\n sql = (\"UPDATE ip_resource_v2_2 SET userid=0 \"\r\n \"WHERE ip in ('-1',\")\r\n for ip in old_alloc_ips:\r\n sql += \"'%s',\" % ip\r\n sql = sql[:-1]\r\n sql += \")\"\r\n sql2 = (\"UPDATE ip_resource_v2_2 SET userid=%s \"\r\n \"WHERE ip in ('-1',\")\r\n for ip in new_alloc_ips:\r\n sql2 += \"'%s',\" % ip\r\n sql2 = sql2[:-1]\r\n sql2 += \")\"\r\n with MySQLdb.connect(**LCDB_INFO) as cursor:\r\n cursor.execute(sql)\r\n cursor.execute(sql2, conf.livecloud_userid)\r\n return subnet_get(subnetid=subnetid)\r\n\r\n if req.gateway_ip is not None:\r\n with MySQLdb.connect(**DB_INFO) as cursor:\r\n sql = \"UPDATE neutron_subnets SET gateway_ip=%s WHERE id=%s\"\r\n cursor.execute(sql, (req.gateway_ip, subnetid))\r\n log.debug('old_cidr=%s, new_cidr=%s' % (cidr, req.cidr))\r\n if req.cidr and cidr != req.cidr:\r\n vl2lcid = yynetworkid_to_lcvl2id(networkid)\r\n nets = [{\"prefix\": VFW_TOR_LINK_NET_PRE,\r\n \"netmask\": VFW_TOR_LINK_NET_MASK}]\r\n subnets = get_subnets_by_network(networkid)\r\n for subnet in subnets:\r\n if str(subnet['id']) == subnetid:\r\n continue\r\n cidr = subnet['cidr'].split('/')\r\n nets.append({\"prefix\": cidr[0], \"netmask\": int(cidr[1])})\r\n cidr = str(req.cidr).split('/')\r\n log.debug('netmask=%s' % cidr[1])\r\n nets.append({\"prefix\": cidr[0], \"netmask\": int(cidr[1])})\r\n nw_name = network_db_get_one('name', id=networkid)\r\n payload = json.dumps({\"name\": nw_name, \"nets\": nets})\r\n log.debug('patch vl2 data=%s' % payload)\r\n r = lcapi.patch(conf.livecloud_url + '/v1/vl2s/%s' % vl2lcid,\r\n data=payload)\r\n if r.status_code != HTTP_OK:\r\n err = r.json()['DESCRIPTION']\r\n log.error(err)\r\n return err_return(err, 'Fail', '', HTTP_BAD_REQUEST)\r\n nets = r.json()['DATA']['NETS']\r\n for net in nets:\r\n if subnet_equ(net['PREFIX'], cidr[0],\r\n net['NETMASK'], int(cidr[1])):\r\n sb_lcuuid = net['LCUUID']\r\n sb_idx = net['NET_INDEX']\r\n break\r\n else:\r\n log.error('sb_lcuuid no found')\r\n return Response(json.dumps(NEUTRON_500)), \\\r\n HTTP_INTERNAL_SERVER_ERROR\r\n if req.allocation_pools is None:\r\n req.allocation_pools = []\r\n else:\r\n req.cidr = db_subnet['cidr']\r\n sb_lcuuid = db_subnet['lcuuid']\r\n sb_idx = db_subnet['net_idx']\r\n if req.allocation_pools is None:\r\n return subnet_get(subnetid=subnetid)\r\n new_alloc_ips = alloc_pools_to_ip_list(req.allocation_pools)\r\n vl2id = lc_vl2_db_get_one('id', lcuuid=sb_lcuuid)\r\n used_ips = lc_vif_ip_db_get_all('ip', vl2id=vl2id,\r\n net_index=sb_idx)\r\n for used_ip in used_ips:\r\n ip = used_ip['ip']\r\n if ip not in new_alloc_ips:\r\n return err_return('used ip(%s) not in alloc pool' % ip,\r\n 'ParameterInvalid', '', HTTP_BAD_REQUEST)\r\n\r\n sql = (\"UPDATE neutron_subnets SET cidr='%s', \"\r\n \"allocation_pools='%s', lcuuid='%s', net_idx=%s \"\r\n \"WHERE id='%s'\" %\r\n (req.cidr, json.dumps(req.allocation_pools),\r\n sb_lcuuid, sb_idx, subnetid))\r\n log.debug('sql=%s' % sql)\r\n with MySQLdb.connect(**DB_INFO) as cursor:\r\n cursor.execute(sql)\r\n return subnet_get(subnetid=subnetid)\r\n except Exception as e:\r\n log.error(e)\r\n return Response(json.dumps(NEUTRON_500)), HTTP_INTERNAL_SERVER_ERROR",
"def set_subnet_cidr(value, yaml_file):\n yaml_content = get_yaml(elife_global_yaml)\n yaml_content[\"defaults\"][\"aws\"][\"subnet-cidr\"] = value\n write_yaml(yaml_content, yaml_file)",
"def edit_note_subnet(self, subnet_id, note):\n return self.subnet.editNote(note, id=subnet_id)",
"def set_subnet_id(value, yaml_file):\n yaml_content = get_yaml(elife_global_yaml)\n yaml_content[\"defaults\"][\"aws\"][\"subnet-id\"] = value\n write_yaml(yaml_content, yaml_file)",
"def set_subnet_ipddress_note(self, identifier, note):\n result = self.client.call('SoftLayer_Network_Subnet_IpAddress', 'editObject', note, id=identifier)\n return result",
"def set_tags_subnet(self, subnet_id, tags):\n return self.subnet.setTags(tags, id=subnet_id)",
"def update_subnet(self, rollback_list, subnet_request):\n neutron_subnet = self._build_subnet_from_request(subnet_request)\n ib_network = self._get_ib_network(neutron_subnet['id'],\n neutron_subnet['ip_version'])\n if not ib_network:\n raise exc.InfobloxCannotFindSubnet(subnet_id=neutron_subnet['id'],\n cidr=neutron_subnet['cidr'])\n\n ib_cxt = ib_context.InfobloxContext(\n self._context,\n self._context.user_id,\n None,\n neutron_subnet,\n self._grid_config,\n plugin=self._plugin,\n ib_network=ib_network)\n\n ipam_controller = ipam.IpamSyncController(ib_cxt)\n dns_controller = dns.DnsController(ib_cxt)\n\n ipam_controller.update_subnet_allocation_pools(rollback_list)\n\n if self._is_new_zone_required(neutron_subnet, ib_network):\n # subnet name is used in the domain suffix pattern and the name\n # has been changed; we need to create new zones.\n dns_controller.create_dns_zones(rollback_list)\n\n ipam_controller.update_subnet_details(ib_network)",
"def set_net_mask(self, mask):\n self.update(net_mask=mask)",
"def ModifyNetworkAclAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyNetworkAclAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyNetworkAclAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def subnet(self, subnet=None):\n handle = _internal._subnet(self, subnet)\n return handle",
"def allocate_subnet(self, request):",
"def ModifyNetworkInterfaceAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyNetworkInterfaceAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyNetworkInterfaceAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def modify_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, Description=None, SourceDestCheck=None, Groups=None, Attachment=None):\n pass",
"def get_subnet(self, subnet_id):",
"def subnet_id(self, subnet_id):\n # type: (string_types) -> None\n\n if subnet_id is not None:\n if not isinstance(subnet_id, string_types):\n raise TypeError(\"Invalid type for `subnet_id`, type has to be `string_types`\")\n\n self._subnet_id = subnet_id",
"def _assert_subnet_property(region, subnet_id, expected_autoassign_ip_value, expected_availability_zone=\"\"):\n subnet = boto3.resource(\"ec2\", region_name=region).Subnet(subnet_id)\n assert_that(subnet.map_public_ip_on_launch).is_equal_to(expected_autoassign_ip_value)\n if expected_availability_zone:\n assert_that(subnet.availability_zone).is_equal_to(expected_availability_zone)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
You can modify several parameters of an existing EBS volume, including volume size, volume type, and IOPS capacity. If your EBS volume is attached to a currentgeneration EC2 instance type, you may be able to apply these changes without stopping the instance or detaching the volume from it. For more information about modifying an EBS volume running Linux, see Modifying the Size, IOPS, or Type of an EBS Volume on Linux . For more information about modifying an EBS volume running Windows, see Modifying the Size, IOPS, or Type of an EBS Volume on Windows . When you complete a resize operation on your volume, you need to extend the volume's filesystem size to take advantage of the new storage capacity. For information about extending a Linux file system, see Extending a Linux File System . For information about extending a Windows file system, see Extending a Windows File System . You can use CloudWatch Events to check the status of a modification to an EBS volume. For information about CloudWatch Events, see the Amazon CloudWatch Events User Guide . You can also track the status of a modification using the DescribeVolumesModifications API. For information about tracking status changes using either method, see Monitoring Volume Modifications .
|
def modify_volume(DryRun=None, VolumeId=None, Size=None, VolumeType=None, Iops=None):
pass
|
[
"def _extend_volume(self, name, new_size):\n LOG.debug('_extend__volume name: %s', name)\n params = {}\n params['volsize'] = ix_utils.get_bytes_from_gb(new_size)\n jparams = json.dumps(params)\n jparams = jparams.encode('utf8')\n request_urn = ('%s/id/%s') % (\n FreeNASServer.REST_API_VOLUME,\n urllib.parse.quote_plus(\n self.configuration.ixsystems_dataset_path + '/' + name))\n ret = self.handle.invoke_command(FreeNASServer.UPDATE_COMMAND,\n request_urn, jparams)\n if ret['status'] != FreeNASServer.STATUS_OK:\n msg = ('Error while extending volume: %s' % ret['response'])\n raise FreeNASApiError('Unexpected error', msg)",
"def VolumeExtend(new_size,\n gib,\n#pylint: disable=unused-argument\n volume_names,\n volume_ids,\n volume_prefix,\n volume_regex,\n volume_count,\n source_account,\n source_account_id,\n test,\n mvip,\n username,\n password):\n#pylint: enable=unused-argument\n options = copy.deepcopy(locals())\n options.pop(\"new_size\", None)\n options.pop(\"gib\", None)\n\n if gib:\n multiplier = 1024 * 1024 * 1024\n else:\n multiplier = 1000 * 1000 * 1000\n\n new_size = new_size * multiplier\n post_value = new_size\n if new_size % 4096 != 0:\n post_value = int((new_size // 4096 + 1) * 4096)\n\n return VolumeModify(property_name=\"totalSize\",\n property_value=new_size,\n post_value=post_value,\n **options)",
"def volume_size(self, volume, new_size=None):\n return self.request( \"volume-size\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n 'new_size': [ new_size, 'new-size', [ basestring, 'None' ], False ],\n }, {\n 'is-fixed-size-flex-volume': [ bool, False ],\n 'is-readonly-flex-volume': [ bool, False ],\n 'is-replica-flex-volume': [ bool, False ],\n 'volume-size': [ basestring, False ],\n } )",
"def test_extend_volume(self):\n self.mox.StubOutWithMock(self._driver, '_create_file')\n\n new_size = self._driver._size_bytes(self.TEST_NEWSIZE)\n self._driver._create_file(self.TEST_VOLPATH, new_size)\n\n self.mox.ReplayAll()\n\n self._driver.extend_volume(self.TEST_VOLUME, self.TEST_NEWSIZE)",
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def edit_volumes(self):\n change_volumes = input(\"[A]dd or [R]emove volumes, or leave \"\n \"blank if unchanged: \").strip()\n\n # Add Volumes\n if change_volumes in ('a', 'A'):\n volumes_to_add = input(\n \"Enter volumes to add (ex. 1, 3-5): \")\n\n volumes_to_add = generate_volumes_owned(volumes_to_add)\n vol_arr_to_add = [int(x) for x in\n volumes_to_add.split(\",\")]\n self.vol_arr = [x | y for x, y in\n zip(vol_arr_to_add, self.vol_arr)]\n\n # update related fields\n self.next_volume = self.calculate_next_volume()\n self.volumes_owned_readable = \"\"\n self.volumes_owned = generate_volumes_owned(\n self.get_volumes_owned())\n\n # Remove Volumes\n if change_volumes in ('r', 'R'):\n volumes_to_rmv = input(\n \"Enter volumes to remove (ex. 1, 3-5): \")\n\n volumes_to_rmv = generate_volumes_owned(volumes_to_rmv)\n vol_arr_to_remove = [int(x) for x in\n volumes_to_rmv.split(\",\")]\n self.vol_arr = [~x & y for x, y in\n zip(vol_arr_to_remove, self.vol_arr)]\n\n print(self.vol_arr)\n if all(not x for x in self.vol_arr):\n user_input = input(\"No volumes owned for series. \"\n \"Remove from database? (y/N): \").strip()\n if user_input in ('y', 'Y'):\n return True\n\n # update related fields\n self.next_volume = self.calculate_next_volume()\n self.volumes_owned_readable = \"\"\n self.volumes_owned = generate_volumes_owned(\n self.get_volumes_owned())\n\n return False",
"def block_modify(mnode, volname, blockname, auth=None, size=None, force=False):\n force_block_modify = ''\n if force is True:\n force_block_modify = \"force\"\n\n if size is None:\n cmd = (\"gluster-block modify %s/%s auth %s %s --json-pretty\" %\n (volname, blockname, auth, force_block_modify))\n else:\n cmd = (\"gluster-block modify %s/%s size %s %s --json-pretty \" %\n (volname, blockname, size, force_block_modify))\n\n return g.run(mnode, cmd)",
"def resize_volume(self, size):\r\n curr_size = self.volume.size\r\n if size <= curr_size:\r\n raise exc.InvalidVolumeResize(\"The new volume size must be larger \"\r\n \"than the current volume size of '%s'.\" % curr_size)\r\n body = {\"volume\": {\"size\": size}}\r\n self.manager.action(self, \"resize\", body=body)",
"def test_volumes_add(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 8)\n svc.volumes.append(sm.Volume(\"foo\", \"bar\"))\n svc.volumes.append(sm.Volume(\"bar\", \"baz\"))\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n if not \"bar\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n for v in svc.volumes:\n if v.owner == \"foo\":\n self.assertEqual(v.permission, \"bar\")\n if v.owner == \"bar\":\n self.assertEqual(v.permission, \"baz\")\n self.assertEqual(len(svc.volumes), 10)",
"def volume(ctx, *args, **kwargs):",
"def test_volumes_replace(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n svc.volumes = [\n sm.Volume(\"foo\", \"bar\"),\n sm.Volume(\"bar\", \"baz\"),\n ]\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n if not \"bar\" in [v.owner for v in svc.volumes]:\n raise ValueError(\"Failed to alter volumes.\")\n for v in svc.volumes:\n if v.owner == \"foo\":\n self.assertEqual(v.permission, \"bar\")\n if v.owner == \"bar\":\n self.assertEqual(v.permission, \"baz\")\n self.assertEqual(len(svc.volumes), 2)",
"async def async_api_adjust_volume(\n hass: ha.HomeAssistant,\n config: AbstractConfig,\n directive: AlexaDirective,\n context: ha.Context,\n) -> AlexaResponse:\n volume_delta = int(directive.payload[\"volume\"])\n\n entity = directive.entity\n current_level = entity.attributes[media_player.const.ATTR_MEDIA_VOLUME_LEVEL]\n\n # read current state\n try:\n current = math.floor(int(current_level * 100))\n except ZeroDivisionError:\n current = 0\n\n volume = float(max(0, volume_delta + current) / 100)\n\n data: dict[str, Any] = {\n ATTR_ENTITY_ID: entity.entity_id,\n media_player.const.ATTR_MEDIA_VOLUME_LEVEL: volume,\n }\n\n await hass.services.async_call(\n entity.domain, SERVICE_VOLUME_SET, data, blocking=False, context=context\n )\n\n return directive.response()",
"def test_12_pblocksize_setting(request):\n depends(request, [\"pool_04\", \"iscsi_cmd_00\"], scope=\"session\")\n iqn = f'{basename}:{target_name}'\n with configured_target_to_file_extent(target_name, pool_name, dataset_name, file_name) as iscsi_config:\n extent_config = iscsi_config['extent']\n with iscsi_scsi_connection(ip, iqn) as s:\n TUR(s)\n data = s.readcapacity16().result\n # By default 512 << 3 == 4096\n assert data['lbppbe'] == 3, data\n\n # First let's just change the blocksize to 2K\n payload = {'blocksize': 2048}\n results = PUT(f\"/iscsi/extent/id/{extent_config['id']}\", payload)\n assert results.status_code == 200, results.text\n\n TUR(s)\n data = s.readcapacity16().result\n assert data['block_length'] == 2048, data\n assert data['lbppbe'] == 1, data\n\n # Now let's change it back to 512, but also set pblocksize\n payload = {'blocksize': 512, 'pblocksize': True}\n results = PUT(f\"/iscsi/extent/id/{extent_config['id']}\", payload)\n assert results.status_code == 200, results.text\n\n TUR(s)\n data = s.readcapacity16().result\n assert data['block_length'] == 512, data\n assert data['lbppbe'] == 0, data\n\n with configured_target_to_zvol_extent(target_name, zvol) as iscsi_config:\n extent_config = iscsi_config['extent']\n with iscsi_scsi_connection(ip, iqn) as s:\n TUR(s)\n data = s.readcapacity16().result\n # We created a vol with volblocksize == 16K (512 << 5)\n assert data['lbppbe'] == 5, data\n\n # First let's just change the blocksize to 4K\n payload = {'blocksize': 4096}\n results = PUT(f\"/iscsi/extent/id/{extent_config['id']}\", payload)\n assert results.status_code == 200, results.text\n\n TUR(s)\n data = s.readcapacity16().result\n assert data['block_length'] == 4096, data\n assert data['lbppbe'] == 2, data\n\n # Now let's also set pblocksize\n payload = {'pblocksize': True}\n results = PUT(f\"/iscsi/extent/id/{extent_config['id']}\", payload)\n assert results.status_code == 200, results.text\n\n TUR(s)\n data = s.readcapacity16().result\n assert data['block_length'] == 4096, data\n assert data['lbppbe'] == 0, data",
"def _adjust_volume(avr, points, operation):\n current_vol = avr.volume\n new_vol = operation(current_vol, (points * 0.5))\n\n try:\n avr.volume = new_vol\n click.echo(new_vol)\n except ReponseException:\n click.echo(\n click.style(\"New volume must be out of range.\",\n fg='red')\n )",
"def editVolumeSettingsObject(self, vpgid, vmid, volumeid, body):\n\n return requests.put(self.zvmip + self.endPoint + '/' + vpgid + '/vms/' + vmid + '/volumes/' + volumeid, body=body, headers=self.headerwithkey, verify=False)",
"def _volume(self, value: object = None):\n if value is None:\n return int(self._player_info().get(\"vol\"))\n try:\n if isinstance(value, str) and (value.startswith('+') or value.startswith('-')):\n self._logger.debug(\"Adjusting volume by \" + str(value) + \". Getting old volume...\")\n new_volume = max(0, min(100, self._volume()+int(math.floor(float(value)))))\n self._logger.debug(\"Adjusting volume \"+str(value)+\" to \"+str(new_volume)+\"...\")\n else:\n new_volume = max(0, min(100, int(math.floor(float(value)))))\n self._logger.debug(\"Setting volume to \" + str(int(new_volume)))\n except ValueError:\n raise AttributeError(\"Volume must be between 0 and 100 or -100 to +100, inclusive, not '\"+str(value)+\"'\")\n response = self._send(\"setPlayerCmd:vol:\" + str(new_volume))\n if response.status_code != 200:\n raise linkplayctl.APIException(\"Failed to set volume to '\"+str(new_volume)+\"'\")\n return response.content.decode(\"utf-8\")",
"def volume_set_option(self, volume, option_value, option_name):\n return self.request( \"volume-set-option\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n 'option_value': [ option_value, 'option-value', [ basestring, 'None' ], False ],\n 'option_name': [ option_name, 'option-name', [ basestring, 'None' ], False ],\n }, {\n } )",
"def volume(ctx, vol):\n avr = ctx.obj['avr']\n if vol:\n try:\n avr.volume = vol\n click.echo(avr.volume)\n except ReponseException as e:\n if \"Volume\" in str(e):\n msg = \"Volume must be specified in -0.5 increments.\"\n err = click.style(msg, fg='red')\n click.echo(err, err=True)\n else:\n click.echo(avr.volume)",
"def test_update_config_ebs_size2():\n randomstr = 'test-' + create_jobid()\n s3 = boto3.client('s3')\n s3.put_object(Body='haha'.encode('utf-8'),\n Bucket='tibanna-output', Key=randomstr)\n input_dict = {'args': {'input_files': {'input_file': {'bucket_name': 'tibanna-output',\n 'object_key': randomstr}},\n 'output_S3_bucket': 'somebucket',\n 'app_name': 'md5',\n 'cwl_main_filename': 'md5.cwl',\n 'cwl_directory_url': 'someurl'},\n 'config': {'log_bucket': 'tibanna-output', 'ebs_size': '5000000000x'}}\n execution = Execution(input_dict)\n execution.input_size_in_bytes = execution.get_input_size_in_bytes()\n execution.update_config_ebs_size()\n assert execution.cfg.ebs_size == 19\n # cleanup afterwards\n s3.delete_objects(Bucket='tibanna-output',\n Delete={'Objects': [{'Key': randomstr}]})",
"def test_volumes_remove(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 8)\n svc.volumes = filter(lambda r: r.resourcePath not in [\"zenjobs\", \"zenoss-export\"], svc.volumes)\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n self.assertEqual(len(svc.volumes), 6)\n for v in svc.volumes:\n if v.resourcePath in [\"zenjobs\", \"zenoss-export\"]:\n raise ValueError(\"Error removing volume.\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies a volume attribute. By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable.
|
def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):
pass
|
[
"def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):\n pass",
"async def async_api_adjust_volume(\n hass: ha.HomeAssistant,\n config: AbstractConfig,\n directive: AlexaDirective,\n context: ha.Context,\n) -> AlexaResponse:\n volume_delta = int(directive.payload[\"volume\"])\n\n entity = directive.entity\n current_level = entity.attributes[media_player.const.ATTR_MEDIA_VOLUME_LEVEL]\n\n # read current state\n try:\n current = math.floor(int(current_level * 100))\n except ZeroDivisionError:\n current = 0\n\n volume = float(max(0, volume_delta + current) / 100)\n\n data: dict[str, Any] = {\n ATTR_ENTITY_ID: entity.entity_id,\n media_player.const.ATTR_MEDIA_VOLUME_LEVEL: volume,\n }\n\n await hass.services.async_call(\n entity.domain, SERVICE_VOLUME_SET, data, blocking=False, context=context\n )\n\n return directive.response()",
"def set_volume_level(self, volume):\n self.soco.volume = str(int(volume * 100))",
"def set_volume_level(self, volume: float) -> None:\n self.send_command([\"mixer\", \"volume\", volume * 100])",
"def update(self, attribute, data):\n return self.call('catalog_product_attribute.update', [attribute, data])",
"def async_turn_off_ac_volume(self):\n yield from self._try_command(\n \"Setting volume off of the miio AC failed.\",\n self._device.set_volume, \"off\")",
"def do_attr(self, args): # noqa: C901\n\n if not self.current:\n print('There are no resources in use. Use the command \"open\".')\n return\n\n args = args.strip()\n\n if not args:\n self.print_attribute_list()\n return\n\n args = args.split(\" \")\n\n if len(args) > 2:\n print(\n \"Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set\"\n )\n return\n\n if len(args) == 1:\n # Get a given attribute\n attr_name = args[0]\n if attr_name.startswith(\"VI_\"):\n try:\n print(\n self.current.get_visa_attribute(getattr(constants, attr_name))\n )\n except Exception as e:\n print(e)\n else:\n try:\n print(getattr(self.current, attr_name))\n except Exception as e:\n print(e)\n return\n\n # Set the specified attribute value\n attr_name, attr_state = args[0], args[1]\n if attr_name.startswith(\"VI_\"):\n try:\n attributeId = getattr(constants, attr_name)\n attr = attributes.AttributesByID[attributeId]\n datatype = attr.visa_type\n retcode = None\n if datatype == \"ViBoolean\":\n if attr_state == \"True\":\n attr_state = True\n elif attr_state == \"False\":\n attr_state = False\n else:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n elif datatype in [\n \"ViUInt8\",\n \"ViUInt16\",\n \"ViUInt32\",\n \"ViInt8\",\n \"ViInt16\",\n \"ViInt32\",\n ]:\n try:\n attr_state = int(attr_state)\n except ValueError:\n retcode = (\n constants.StatusCode.error_nonsupported_attribute_state\n )\n if not retcode:\n retcode = self.current.set_visa_attribute(attributeId, attr_state)\n if retcode:\n print(\"Error {}\".format(str(retcode)))\n else:\n print(\"Done\")\n except Exception as e:\n print(e)\n else:\n print(\"Setting Resource Attributes by python name is not yet supported.\")\n return",
"def change_volume(self, volume):\n self.signalPlayer.volume = volume",
"def volume(vol):\n ReceiverManager().set_volume(vol)\n return jsonify(volume = vol, status = \"Ok\")",
"def _adjust_volume(avr, points, operation):\n current_vol = avr.volume\n new_vol = operation(current_vol, (points * 0.5))\n\n try:\n avr.volume = new_vol\n click.echo(new_vol)\n except ReponseException:\n click.echo(\n click.style(\"New volume must be out of range.\",\n fg='red')\n )",
"def modify_image_attribute(DryRun=None, ImageId=None, Attribute=None, OperationType=None, UserIds=None, UserGroups=None, ProductCodes=None, Value=None, LaunchPermission=None, Description=None):\n pass",
"def describe_volume_attribute(DryRun=None, VolumeId=None, Attribute=None):\n pass",
"def volume(ctx, vol):\n avr = ctx.obj['avr']\n if vol:\n try:\n avr.volume = vol\n click.echo(avr.volume)\n except ReponseException as e:\n if \"Volume\" in str(e):\n msg = \"Volume must be specified in -0.5 increments.\"\n err = click.style(msg, fg='red')\n click.echo(err, err=True)\n else:\n click.echo(avr.volume)",
"def set_volume(self, zone: int, volume: int):\n raise NotImplemented()",
"def lock_unlock_attribute(element, attribute, state):\n\n try:\n cmds.setAttr(\"{}.{}\".format(element, attribute), lock=state)\n return True\n except RuntimeError:\n return False",
"def set_volume(self, speaker: Speaker, volume: int):\n raise NotImplementedError()",
"def increase_volume(self):\n if self.is_playing:\n self.volume = self.volume / 0.8 + 0.008",
"def update(self, volume, display_name=None, display_description=None):\r\n return self._manager.update(volume, display_name=display_name,\r\n display_description=display_description)",
"async def async_set_mic_volume(self, level):\n await self.upv_object.set_mic_volume(self._device_id, level)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies the specified attribute of the specified VPC.
|
def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):
pass
|
[
"def ModifyVpcEndPointServiceAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyVpcEndPointServiceAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyVpcEndPointServiceAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):\n pass",
"def describe_vpc_attribute(DryRun=None, VpcId=None, Attribute=None):\n pass",
"def modify_cattr(self, name, data):\n return self.complex_configuration_manager.modify_cattr(name, data)",
"def modify_vpc_endpoint(DryRun=None, VpcEndpointId=None, ResetPolicy=None, PolicyDocument=None, AddRouteTableIds=None, RemoveRouteTableIds=None):\n pass",
"def updateVpcTable(tableName,data,paGroupName):\n try:\n #VpcCidr is the primary key for VpcTable\n table=dynamodb.Table(tableName)\n item={\n 'VpcId': data['VpcId'],\n 'VpcCidr': data['VpcCidr'],\n 'Region': data['Region'],\n 'SubscriberSnsArn': data['SubscriberSnsArn'],\n 'SubscriberAssumeRoleArn': data['SubscriberAssumeRoleArn'],\n 'PaGroupName': paGroupName,\n 'CurrentStatus': 'Inprogress'\n }\n response=table.put_item(Item=item)\n except Exception as e:\n logger.error(\"Updating Transit VpcTalbe is Failed, Error: {}\".format(str(e)))",
"def modify_subnet_attribute(SubnetId=None, MapPublicIpOnLaunch=None, AssignIpv6AddressOnCreation=None):\n pass",
"def updateVpcTable(tableName,data,status):\n try:\n #VpcId is the primary key for VpcTable\n table=dynamodb.Table(tableName)\n response=table.update_item(Key={'VpcId':data['VpcId']},AttributeUpdates={'CurrentStatus':{'Value':status,'Action':'PUT'},'Node1VpnId':{'Value':data['VpnN1'],'Action':'PUT'},'Node2VpnId':{'Value':data['VpnN2'],'Action':'PUT'}, 'Region':{'Value':data['Region'],'Action':'PUT'}, 'IpSegment':{'Value':data['IpSegment'],'Action':'PUT'}})\n logger.info('Updated table {} with '.format(tableName,data['VpnN1'],data['VpnN2'],data['Region'],data['IpSegment']))\n except Exception as e:\n logger.error(\"Updating Transit VpcTalbe is Failed, Error: {}\".format(str(e)))",
"def set_attr_3(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr3\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)",
"def ModifyAddressTemplateAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyAddressTemplateAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyAddressTemplateAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def aws_attribute_name(self, aws_attribute_name):\n\n self._aws_attribute_name = aws_attribute_name",
"def modify_snapshot_attribute(DryRun=None, SnapshotId=None, Attribute=None, OperationType=None, UserIds=None, GroupNames=None, CreateVolumePermission=None):\n pass",
"def update(self, attr):\n assert attr is not MispShadowAttribute\n raw = attr.to_xml()\n raw = self.server.POST('/shadow_attributes/edit/%d' % attr.id, raw)\n response = objectify.fromstring(raw)\n return MispShadowAttribute.from_xml_object(response.ShadowAttribute)",
"def ModifyCcnAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyCcnAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyCcnAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):\n pass",
"def ModifyAddressTemplateGroupAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyAddressTemplateGroupAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyAddressTemplateGroupAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def modify_volume_attribute(DryRun=None, VolumeId=None, AutoEnableIO=None):\n pass",
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def set_attr_2(self, value):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.attr2\", self._object._eco_id, value)\r\n p2e._app.Exec(arg_str)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Modifies attributes of a specified VPC endpoint. You can modify the policy associated with the endpoint, and you can add and remove route tables associated with the endpoint.
|
def modify_vpc_endpoint(DryRun=None, VpcEndpointId=None, ResetPolicy=None, PolicyDocument=None, AddRouteTableIds=None, RemoveRouteTableIds=None):
pass
|
[
"def ModifyVpcEndPointServiceAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyVpcEndPointServiceAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyVpcEndPointServiceAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def endpoint_update(**kwargs):\n # validate params. Requires a get call to check the endpoint type\n client = get_client()\n endpoint_id = kwargs.pop(\"endpoint_id\")\n get_res = client.get_endpoint(endpoint_id)\n\n if get_res[\"host_endpoint_id\"]:\n endpoint_type = \"shared\"\n elif get_res[\"is_globus_connect\"]:\n endpoint_type = \"personal\"\n elif get_res[\"s3_url\"]:\n endpoint_type = \"s3\"\n else:\n endpoint_type = \"server\"\n validate_endpoint_create_and_update_params(\n endpoint_type, get_res[\"subscription_id\"], kwargs\n )\n\n # make the update\n ep_doc = assemble_generic_doc(\"endpoint\", **kwargs)\n res = client.update_endpoint(endpoint_id, ep_doc)\n formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key=\"message\")",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def updateVpcTable(tableName,data,status):\n try:\n #VpcId is the primary key for VpcTable\n table=dynamodb.Table(tableName)\n response=table.update_item(Key={'VpcId':data['VpcId']},AttributeUpdates={'CurrentStatus':{'Value':status,'Action':'PUT'},'Node1VpnId':{'Value':data['VpnN1'],'Action':'PUT'},'Node2VpnId':{'Value':data['VpnN2'],'Action':'PUT'}, 'Region':{'Value':data['Region'],'Action':'PUT'}, 'IpSegment':{'Value':data['IpSegment'],'Action':'PUT'}})\n logger.info('Updated table {} with '.format(tableName,data['VpnN1'],data['VpnN2'],data['Region'],data['IpSegment']))\n except Exception as e:\n logger.error(\"Updating Transit VpcTalbe is Failed, Error: {}\".format(str(e)))",
"def with_endpoint(self, endpoint):\n self.__endpoint = endpoint\n return self",
"def delete_vpc_endpoint_resources():\n print('Deleting VPC endpoints')\n ec2 = boto3.client('ec2')\n endpoint_ids = []\n for endpoint in ec2.describe_vpc_endpoints()['VpcEndpoints']:\n print('Deleting VPC Endpoint - {}'.format(endpoint['ServiceName']))\n endpoint_ids.append(endpoint['VpcEndpointId'])\n\n if endpoint_ids:\n ec2.delete_vpc_endpoints(\n VpcEndpointIds=endpoint_ids\n )\n\n print('Waiting for VPC endpoints to get deleted')\n while ec2.describe_vpc_endpoints()['VpcEndpoints']:\n time.sleep(5)\n\n print('VPC endpoints deleted')\n\n # VPC endpoints connections\n print('Deleting VPC endpoint connections')\n service_ids = []\n for connection in ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n service_id = connection['ServiceId']\n state = connection['VpcEndpointState']\n\n if state in ['PendingAcceptance', 'Pending', 'Available', 'Rejected', 'Failed', 'Expired']:\n print('Deleting VPC Endpoint Service - {}'.format(service_id))\n service_ids.append(service_id)\n\n ec2.reject_vpc_endpoint_connections(\n ServiceId=service_id,\n VpcEndpointIds=[\n connection['VpcEndpointId'],\n ]\n )\n\n if service_ids:\n ec2.delete_vpc_endpoint_service_configurations(\n ServiceIds=service_ids\n )\n\n print('Waiting for VPC endpoint services to be destroyed')\n while ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n time.sleep(5)\n\n print('VPC endpoint connections deleted')",
"def updateVpcTable(tableName,data,paGroupName):\n try:\n #VpcCidr is the primary key for VpcTable\n table=dynamodb.Table(tableName)\n item={\n 'VpcId': data['VpcId'],\n 'VpcCidr': data['VpcCidr'],\n 'Region': data['Region'],\n 'SubscriberSnsArn': data['SubscriberSnsArn'],\n 'SubscriberAssumeRoleArn': data['SubscriberAssumeRoleArn'],\n 'PaGroupName': paGroupName,\n 'CurrentStatus': 'Inprogress'\n }\n response=table.put_item(Item=item)\n except Exception as e:\n logger.error(\"Updating Transit VpcTalbe is Failed, Error: {}\".format(str(e)))",
"def set_endpoint_url(self, new_endpoint_url):\n self.endpoint_url = new_endpoint_url",
"def set_endpoint_rolearn(config):\n print(\"- Setting ENDPOINT and ROLE_ARN in configuration file\")\n global DWH_ENDPOINT, DWH_ROLE_ARN\n # set new value\n config.set('RedShift', 'DWH_ENDPOINT', DWH_ENDPOINT)\n config.set('RedShift', 'DWH_ROLE_ARN', DWH_ROLE_ARN)\n\n # save the file\n with open('../aws/credentials.cfg', 'w') as configfile:\n config.write(configfile)",
"def test_crud_for_policy_for_explicit_endpoint(self):\n\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints/%(endpoint_id)s') % {\n 'policy_id': self.policy['id'],\n 'endpoint_id': self.endpoint['id']}\n\n self.put(url, expected_status=204)\n self.get(url, expected_status=204)\n self.head(url, expected_status=204)\n self.delete(url, expected_status=204)",
"def add_endpoint(self, endpoint):\n self.endpoints[endpoint.name] = endpoint",
"def test_endpoints_replace(self):\n ctx = sm.ServiceContext(INFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n svc.endpoints = [\n sm.Endpoint(\"foo\", \"bar\"),\n sm.Endpoint(\"bar\", \"baz\"),\n ]\n ctx.commit(OUTFILENAME)\n ctx = sm.ServiceContext(OUTFILENAME)\n svc = filter(lambda x: x.description == \"Zope server\", ctx.services)[0]\n if not \"foo\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n if not \"bar\" in [ep.name for ep in svc.endpoints]:\n raise ValueError(\"Failed to alter endpoints.\")\n for ep in svc.endpoints:\n if ep.name == \"foo\":\n self.assertEqual(ep.purpose, \"bar\")\n if ep.name == \"bar\":\n self.assertEqual(ep.purpose, \"baz\")\n self.assertEqual(len(svc.endpoints), 2)",
"def create_vpc_endpoint(DryRun=None, VpcId=None, ServiceName=None, PolicyDocument=None, RouteTableIds=None, ClientToken=None):\n pass",
"def modify_spot_fleet_request(SpotFleetRequestId=None, TargetCapacity=None, ExcessCapacityTerminationPolicy=None):\n pass",
"def updateAttribute(self, attributeName, attributeType, attributeValueChangeSpecData, defaultValue, description, showInTriage):\n attributeDefinitionId= self.__ConfServiceclient.factory.create(\"attributeDefinitionDataObj\")\n attributeDefinitionId= attributeName\n attributeDefinitionSpec= self.__ConfServiceclient.factory.create(\"attributeDefinitionSpecDataObj\")\n attributeDefinitionSpec.attributeName= None\n attributeDefinitionSpec.attributeType= attributeType\n attributeDefinitionSpec.attributeValueChangeSpec= attributeValueChangeSpecData\n attributeDefinitionSpec.defaultValue= defaultValue\n attributeDefinitionSpec.description= description\n attributeDefinitionSpec.showInTriage= showInTriage\n try:\n self.__ConfServiceclient.service.updateAttribute(attributeDefinitionId, attributeDefinitionSpec)\n except suds.WebFault as detail:\n return detail",
"def prepare_endpoint(self, endpoint):\n pass",
"def update_export(self, endpoint, new_name, old_properties):\n with self.__lock:\n if new_name in self.__endpoints:\n # Reject the new name\n raise NameError(\"New name of %s already used: %s\",\n endpoint.name, new_name)\n\n # Update storage\n self.__endpoints[new_name] = self.__endpoints.pop(endpoint.name)\n\n # Update the endpoint\n endpoint.name = new_name",
"def create_policy_association_for_endpoint(self, context,\n policy_id, endpoint_id):\n self.policy_api.get_policy(policy_id)\n self.catalog_api.get_endpoint(endpoint_id)\n self.endpoint_policy_api.create_policy_association(\n policy_id, endpoint_id=endpoint_id)",
"def updateBgpTunnelIpPool(bgpTableName,ipSegment):\n try:\n table=dynamodb.Table(bgpTableName)\n #Update BgpTunnelIpPool table Attribute \"Available\"=\"YES\"\n table.update_item(Key={'IpSegment':ipSegment},AttributeUpdates={'Available':{'Value':'YES','Action':'PUT'}})\n logger.info(\"Successfully Updated BgpTunnleIpPool Table attribute Available=YES\")\n except Exception as e:\n logger.error(\"Update BgpTunnelIpPool is failed, Error: {}\".format(str(e)))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Moves an Elastic IP address from the EC2Classic platform to the EC2VPC platform. The Elastic IP address must be allocated to your account for more than 24 hours, and it must not be associated with an instance. After the Elastic IP address is moved, it is no longer available for use in the EC2Classic platform, unless you move it back using the RestoreAddressToClassic request. You cannot move an Elastic IP address that was originally allocated for use in the EC2VPC platform to the EC2Classic platform.
|
def move_address_to_vpc(DryRun=None, PublicIp=None):
pass
|
[
"def restore_address_to_classic(DryRun=None, PublicIp=None):\n pass",
"def ElasticIps(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n return self.reservation",
"def delete_elastic_ips():\n client = boto3.client('ec2')\n print('Deleting Elastic IPs')\n for eip in client.describe_addresses()['Addresses']:\n allocation_id = eip['AllocationId']\n print('Releasing EIP {}'.format(allocation_id))\n client.release_address(\n AllocationId=allocation_id\n )\n\n print('Elastic IPs deleted')",
"def ex_release_public_ip(self, address):\r\n return self.driver.ex_release_public_ip(self, address)",
"def PrivateIPAddressing(self, zone = None):\n self.private_addressing = True\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name, private_addressing=self.private_addressing, zone=zone)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n if (instance.public_dns_name != instance.private_dns_name):\n self.tester.critical(\"Instance received a new public IP: \" + instance.public_dns_name)\n return self.reservation",
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def move_address(self, address):\n to_change = {}\n to_move = {}\n to_insert = {}\n to_clean = []\n mp = 0\n oa = 0\n (buildings, parts) = self.index_of_building_and_parts()\n exp = \"NOT(localId ~ '_')\"\n ppv, geometries = self.get_parents_per_vertex_and_geometries(exp)\n pbar = self.get_progressbar(_(\"Move addresses\"), address.featureCount())\n for ad in address.getFeatures():\n refcat = self.get_id(ad)\n building_count = len(buildings.get(refcat, []))\n ad_buildings = buildings[refcat]\n ad_parts = parts[refcat]\n if building_count == 0:\n to_clean.append(ad.id())\n oa += 1\n else:\n if ad[\"spec\"] == \"Entrance\":\n self.move_entrance(\n ad,\n ad_buildings,\n ad_parts,\n to_move,\n to_insert,\n ppv,\n )\n if ad[\"spec\"] != \"Entrance\" and building_count > 1:\n to_clean.append(ad.id())\n mp += 1\n if ad[\"spec\"] != \"Parcel\" and building_count == 1:\n to_change[ad.id()] = get_attributes(ad)\n if len(to_insert) > BUFFER_SIZE:\n self.writer.changeGeometryValues(to_insert)\n to_insert = {}\n pbar.update()\n pbar.close()\n address.writer.changeAttributeValues(to_change)\n address.writer.changeGeometryValues(to_move)\n if len(to_insert) > 0:\n self.writer.changeGeometryValues(to_insert)\n msg = _(\"Moved %d addresses to entrance, %d specification changed\")\n log.debug(msg, len(to_move), len(to_change))\n if len(to_clean) > 0:\n address.writer.deleteFeatures(to_clean)\n if oa > 0:\n msg = _(\"Deleted %d addresses without associated building\")\n log.debug(msg, oa)\n report.pool_addresses = oa\n if mp > 0:\n msg = _(\"Refused %d addresses belonging to multiple buildings\")\n log.debug(msg, mp)\n report.multiple_addresses = mp",
"def associate_address(DryRun=None, InstanceId=None, PublicIp=None, AllocationId=None, NetworkInterfaceId=None, PrivateIpAddress=None, AllowReassociation=None):\n pass",
"def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None, HostId=None):\n pass",
"def associate_vpc_cidr_block(VpcId=None, AmazonProvidedIpv6CidrBlock=None):\n pass",
"def _assign_secondary_ip_():\n interface_idx = 0\n node = env.nodes[0]\n cidr='%s/%s' % (env.secondary_ip,env.secondary_ip_cidr_prefix_size)\n\n if (_get_secondary_ip_node_().id == node.id):\n debug(\"VPC Secondary IP %s already assigned to %s\" % (cidr, pretty_instance(node)))\n else:\n info(\"Assigning VPC Secondary IP %s to %s\" % (cidr, pretty_instance(node)))\n connect().assign_private_ip_addresses(node.interfaces[interface_idx].id, env.secondary_ip, allow_reassignment=True)\n # Notify opsys that it has a new address (This seems to only happen automatically with Elastic IPs). Write to /etc to make persistent.\n has_address = run('ip addr | grep %s' % cidr, quiet=True)\n if not has_address:\n sudo('ip addr add %s dev eth0' % cidr)\n append('/etc/network/interfaces','up ip addr add %s dev eth%d' % (cidr,interface_idx),use_sudo=True)",
"def ReuseAddresses(self, zone = None):\n prev_address = None\n if zone is None:\n zone = self.zone\n ### Run the test 5 times in a row\n for i in xrange(5):\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name, zone=zone)\n for instance in self.reservation.instances:\n if prev_address is not None:\n self.assertTrue(re.search(str(prev_address) ,str(instance.public_dns_name)), str(prev_address) +\" Address did not get reused but rather \" + str(instance.public_dns_name))\n prev_address = instance.public_dns_name\n self.tester.terminate_instances(self.reservation)",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def ex_release_address(self, elastic_ip, domain=None):\r\n params = {'Action': 'ReleaseAddress'}\r\n\r\n if domain is not None and domain != 'vpc':\r\n raise AttributeError('Domain can only be set to vpc')\r\n\r\n if domain is None:\r\n params['PublicIp'] = elastic_ip.ip\r\n else:\r\n params['AllocationId'] = elastic_ip.extra['allocation_id']\r\n\r\n response = self.connection.request(self.path, params=params).object\r\n return self._get_boolean(response)",
"def modify_vpc_endpoint(DryRun=None, VpcEndpointId=None, ResetPolicy=None, PolicyDocument=None, AddRouteTableIds=None, RemoveRouteTableIds=None):\n pass",
"def assign_elastic_ip(node = None, elastic_ip=None):\n node = node or env.nodes[0]\n elastic_ip = elastic_ip or env.elastic_ip\n if elastic_ip == ip_address(node):\n debug(\"ElasticIP %s already assigned to %s\" % (elastic_ip, pretty_instance(node)))\n else:\n info(\"Assigning ElasticIP %s to %s\" % (elastic_ip, pretty_instance(node)))\n connect().associate_address(node.id, elastic_ip)",
"def assign_private_ip_addresses(NetworkInterfaceId=None, PrivateIpAddresses=None, SecondaryPrivateIpAddressCount=None, AllowReassignment=None):\n pass",
"def set_cidr_ip(value, yaml_file):\n\n new_ports = [22, {4506: {\"cidr-ip\": value}}, {4505: {\"cidr-ip\": value}} ]\n\n print \"setting cidr_ip \" + value\n yaml_content = get_yaml(yaml_file)\n yaml_content[\"master-server\"][\"aws\"][\"ports\"] = new_ports\n write_yaml(yaml_content, yaml_file)",
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def associate_address(self, instance_id, address):\n query = self.query_factory(\n action=\"AssociateAddress\", creds=self.creds,\n endpoint=self.endpoint,\n other_params={\"InstanceId\": instance_id, \"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Purchase a reservation with configurations that match those of your Dedicated Host. You must have active Dedicated Hosts in your account before you purchase a reservation. This action results in the specified reservation being purchased and charged to your account.
|
def purchase_host_reservation(OfferingId=None, HostIdSet=None, LimitPrice=None, CurrencyCode=None, ClientToken=None):
pass
|
[
"def attemptPurchases(order):\n print(\"\\n\")\n # here we sort out the availability zones\n hasOrdersAssigned = True\n\n for az in order.AvailabilityZones:\n if az.ordered is None:\n az.ordered = 0\n if az.Number is None:\n hasOrdersAssigned = False\n\n if hasOrdersAssigned == False:\n remainder = int(order.Number) % len(order.AvailabilityZones)\n eachOrderGets = int((int(order.Number) - remainder) /\n len(order.AvailabilityZones))\n # here we assign all the orders\n for az in order.AvailabilityZones:\n az.Number = eachOrderGets\n if remainder != 0:\n az.Number += 1\n remainder -= 1\n\n # this client can be used for all the az's\n print(order.Region)\n client = boto3.client('ec2', region_name=order.Region,aws_access_key_id=order.aws_access_key_id,aws_secret_access_key=order.aws_secret_access_key)\n for az in order.AvailabilityZones:\n\n # for each AZ we're buying from\n kwargs = order.getKwargs(az.Name)\n response = client.describe_reserved_instances_offerings(**kwargs)\n ReservedInstancesOfferings = response[\"ReservedInstancesOfferings\"]\n\n # we search for all instance types, not just fixed or hourly, then sort when we recieve results\n # do the sorting of the reserved instances by price, cheapest first\n allOfferings = []\n\n # get all the offerings objects\n for instanceOffering in ReservedInstancesOfferings:\n # isFixed and isHourly completely filter out or in whether or not those instance types get included\n # if both are true, then all types of instances get included regardless of payment type\n\n # for limits, 0 means no limit, everything else abides by the limit\n\n iOffering = getInstanceOffering(instanceOffering)\n fixedPrice = iOffering.FixedPrice\n recurringAmount = iOffering.RecurringAmount\n fixedPriceExists = False\n recurringAmountExists = False\n\n if fixedPrice is not None and fixedPrice != 0:\n fixedPriceExists = True\n if recurringAmount is not None and recurringAmount != 0:\n recurringAmountExists = True\n\n MaxFixedPrice = 0\n if order.MaxFixedPrice is not None:\n MaxFixedPrice = order.MaxFixedPrice\n\n MaxRecurringPrice = 0\n if order.MaxHourlyPrice is not None:\n MaxRecurringPrice = order.MaxHourlyPrice\n\n if order.isFixedPrice == True and order.isHourlyPrice == True:\n # either hourly or fixed or both\n if fixedPriceExists and recurringAmountExists:\n if (MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice) and (MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice):\n allOfferings.append(iOffering)\n elif fixedPriceExists:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n elif recurringAmountExists:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n elif order.isFixedPrice == True:\n # only fixed price servers\n if fixedPriceExists and recurringAmountExists == False:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n\n elif order.isHourlyPrice == True:\n # only hourly servers\n if recurringAmountExists and fixedPriceExists == False:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n # sort into cost effectiveness, and these all have the correct AZ\n allOfferings.sort(key=lambda x: x.EffectiveHourlyRate)\n\n # print(order.Number)\n if order.Number is not None and order.Number > 0:\n if order.ordered is None:\n # brand new order bring it up to speed\n order.ordered = 0\n\n if az.ordered >= az.Number:\n print(\"AZ\", az.Name, \"has already been fulfilled with\",\n az.ordered, \"instances\")\n # buy until finished\n purchasedJustNow = 0\n previouslyPurchased = az.ordered\n for instanceOffering in allOfferings:\n # instanceOffering.print()\n # also we might want to write to the file, like keep it open, and update it for each order bought\n # something might go wrong\n # print(instanceOffering, \"\\n\")\n if order.ordered < order.Number and az.ordered < az.Number:\n # do purchase\n order.ordered += 1\n az.ordered += 1\n purchasedJustNow += 1\n instance = allOfferings.pop(0)\n kwargs = instance.getKwargs(order.DryRun)\n response = None\n try:\n response = client.purchase_reserved_instances_offering(\n **kwargs)\n print(response)\n except:\n pass\n print(\"Just Purchased:\")\n instanceOffering.print()\n order.PurchasedInstances.append(instanceOffering)\n\n if order.ordered >= order.Number or az.ordered >= az.Number:\n break\n\n print(purchasedJustNow,\n \"Reserved Instances were just purchased for:\", az.Name)\n print(previouslyPurchased, \"instances had been purchased previously\")\n if az.ordered >= az.Number:\n print(\"Purchased all\", az.ordered,\n \"Reserved Instances for:\", az.Name, \"\\n\")\n else:\n print(\"Still need\", int(az.Number - az.ordered), \"instances for availability zone:\",\n az.Name, \", will attempt to purchase the rest during the next run\", \"\\n\")\n\n if order.ordered >= order.Number:\n print(\"Purchased all\", order.ordered,\n \"Reserved Instances for this order\\n\\n\")\n else:\n print(\"Could only purchase\", order.ordered,\n \"Reserved Instances for this order, will attempt to purchase the rest at a later date.\\n\\n\")\n return",
"def purchase_scheduled_instances(DryRun=None, ClientToken=None, PurchaseRequests=None):\n pass",
"def reserve_booking(booking):\n try:\n id = str(uuid.uuid4())\n booking_item = {\n \"id\": id,\n \"stateExecutionId\": booking[\"name\"],\n \"__typename\": \"Booking\",\n \"bookingOutboundFlightId\": booking[\"outboundFlightId\"],\n \"checkedIn\": False,\n \"customer\": booking[\"customerId\"],\n \"paymentToken\": booking[\"chargeId\"],\n \"status\": \"UNCONFIRMED\",\n \"createdAt\": str(datetime.datetime.now()),\n }\n\n table.put_item(Item=booking_item)\n\n return {\"bookingId\": id}\n except ClientError as e:\n raise BookingReservationException(e.response[\"Error\"][\"Message\"])",
"def select_destinations(\n self, context, request_spec=None,\n filter_properties=None, spec_obj=_sentinel, instance_uuids=None,\n return_objects=False, return_alternates=False,\n ):\n LOG.debug(\"Starting to schedule for instances: %s\", instance_uuids)\n\n # TODO(sbauza): Change the method signature to only accept a spec_obj\n # argument once API v5 is provided.\n if spec_obj is self._sentinel:\n spec_obj = objects.RequestSpec.from_primitives(\n context, request_spec, filter_properties)\n\n is_rebuild = utils.request_is_rebuild(spec_obj)\n alloc_reqs_by_rp_uuid, provider_summaries, allocation_request_version \\\n = None, None, None\n if not is_rebuild:\n try:\n request_filter.process_reqspec(context, spec_obj)\n except exception.RequestFilterFailed as e:\n raise exception.NoValidHost(reason=e.message)\n\n resources = utils.resources_from_request_spec(\n context, spec_obj, self.host_manager,\n enable_pinning_translate=True)\n res = self.placement_client.get_allocation_candidates(\n context, resources)\n if res is None:\n # We have to handle the case that we failed to connect to the\n # Placement service and the safe_connect decorator on\n # get_allocation_candidates returns None.\n res = None, None, None\n\n alloc_reqs, provider_summaries, allocation_request_version = res\n alloc_reqs = alloc_reqs or []\n provider_summaries = provider_summaries or {}\n\n # if the user requested pinned CPUs, we make a second query to\n # placement for allocation candidates using VCPUs instead of PCPUs.\n # This is necessary because users might not have modified all (or\n # any) of their compute nodes meaning said compute nodes will not\n # be reporting PCPUs yet. This is okay to do because the\n # NUMATopologyFilter (scheduler) or virt driver (compute node) will\n # weed out hosts that are actually using new style configuration\n # but simply don't have enough free PCPUs (or any PCPUs).\n # TODO(stephenfin): Remove when we drop support for 'vcpu_pin_set'\n if (\n resources.cpu_pinning_requested and\n not CONF.workarounds.disable_fallback_pcpu_query\n ):\n LOG.debug(\n 'Requesting fallback allocation candidates with '\n 'VCPU instead of PCPU'\n )\n resources = utils.resources_from_request_spec(\n context, spec_obj, self.host_manager,\n enable_pinning_translate=False)\n res = self.placement_client.get_allocation_candidates(\n context, resources)\n if res:\n # merge the allocation requests and provider summaries from\n # the two requests together\n alloc_reqs_fallback, provider_summaries_fallback, _ = res\n\n alloc_reqs.extend(alloc_reqs_fallback)\n provider_summaries.update(provider_summaries_fallback)\n\n if not alloc_reqs:\n LOG.info(\n \"Got no allocation candidates from the Placement API. \"\n \"This could be due to insufficient resources or a \"\n \"temporary occurrence as compute nodes start up.\"\n )\n raise exception.NoValidHost(reason=\"\")\n\n # Build a dict of lists of allocation requests, keyed by\n # provider UUID, so that when we attempt to claim resources for\n # a host, we can grab an allocation request easily\n alloc_reqs_by_rp_uuid = collections.defaultdict(list)\n for ar in alloc_reqs:\n for rp_uuid in ar['allocations']:\n alloc_reqs_by_rp_uuid[rp_uuid].append(ar)\n\n # Only return alternates if both return_objects and return_alternates\n # are True.\n return_alternates = return_alternates and return_objects\n\n selections = self._select_destinations(\n context, spec_obj, instance_uuids, alloc_reqs_by_rp_uuid,\n provider_summaries, allocation_request_version, return_alternates)\n\n # If `return_objects` is False, we need to convert the selections to\n # the older format, which is a list of host state dicts.\n if not return_objects:\n selection_dicts = [sel[0].to_dict() for sel in selections]\n return jsonutils.to_primitive(selection_dicts)\n\n return selections",
"def confirmBooking(self, account, acl, reservation, project, booking_reqs=None):\n\n booking = self._getBooking(account, acl, reservation)\n\n if not booking:\n raise BookingError(\"There is no booking associated with booking ID '%s'\" % reservation)\n\n if booking.status != Booking.reserved():\n raise BookingError(\"You cannot confirm a booking that is not in the 'reserved' state.\",\n detail=BookingInfo(booking))\n\n if booking_reqs:\n booking.requirements = booking_reqs.reqs_id\n\n booking.project = to_string(project)\n\n item_reqs = self.getRequirements()\n\n if item_reqs and item_reqs.needs_authorisation:\n booking.status = Booking.pendingAuthorisation()\n else:\n booking.status = Booking.confirmed()\n\n # Add the event to the google calendar so that it is visible\n event = self.getCalendar(account).addEvent(account, BookingInfo(booking).toEvent())\n\n if event:\n booking.gcal_id = event.gcal_id\n\n booking.put()\n\n return BookingInfo(booking)",
"def reservation_conversion(self):\n \n if(self.order_type == OrderType.PURCHASE_ORDER):\n # this is already a purchase, nothing else to do\n return\n \n if(self.order_type == OrderType.RESERVATION_ORDER and self.reservation):\n self.order_type = OrderType.PURCHASE_ORDER\n self.converted_from_reservation = True\n self.save()\n # TODO: create purchase from reservation",
"def _release_purse_reservation(transaction: DbTransaction) -> None:\n if transaction.purse_reservation_id is not None:\n try:\n delete_reservation(transaction.wallet.purse_id, transaction.purse_reservation_id)\n transaction.purse_reservation_id = None\n transaction.save()\n except ApiException as ae:\n logger.error(\"Failed to delete purse reservation, purse=%s, reservation=%s\",\n transaction.wallet.purse_id, transaction.purse_reservation_id, exc_info=ae)",
"def purchase_reserved_instances_offering(DryRun=None, ReservedInstancesOfferingId=None, InstanceCount=None, LimitPrice=None):\n pass",
"def create(cls, equipment, account, start_time, end_time, registry=DEFAULT_BOOKING_REGISTRY):\n \n # get the parent key\n parent_key = ndb.Key(Equipment, equipment.idstring, parent=bookings_key(registry))\n\n # get a new ID from the datastore\n new_id = ndb.Model.allocate_ids(size = 1, parent = parent_key)[0]\n\n # create a reservation and place it into the database\n my_booking = Booking()\n my_booking.key = ndb.Key(Booking, new_id, parent=parent_key)\n my_booking.start_time = start_time\n my_booking.end_time = end_time\n my_booking.booking_time = get_now_time()\n my_booking.user = account.email\n my_booking.status = Booking.reserved()\n\n my_booking.put()\n\n # now see whether or not this reservation clashes with anyone else...\n bookings = Booking.getEquipmentQuery(equipment.idstring,registry) \\\n .filter(Booking.end_time > start_time).fetch()\n clashing_bookings = []\n\n for booking in bookings:\n if booking.key != my_booking.key:\n if booking.start_time < end_time:\n # we have a clash - is this booking confirmed?\n if booking.status == Booking.confirmed():\n clashing_bookings.append( BookingInfo(booking) )\n elif booking.status == Booking.reserved():\n # we are both trying to book at once. The winner is the person\n # who booked first...\n if booking.booking_time < my_booking.booking_time:\n clashing_bookings.append( BookingInfo(booking) )\n elif booking.booking_time == my_booking.booking_time:\n # we booked at the same time - the winner is the one with the alphabetically\n # later email address\n if booking.user < my_booking.user:\n booking.status = Booking.cancelled()\n booking.put()\n else:\n clashing_bookings.append( BookingInfo(booking) )\n else:\n # we have won - automatically cancel the other booking\n booking.status = Booking.cancelled()\n booking.put()\n\n if len(clashing_bookings) > 0:\n # we cannot get a unique booking\n my_booking.key.delete()\n raise BookingError(\"\"\"Cannot create a reservation for this time as someone else has already\n created a booking. '%s'\"\"\" % cls._describeBookings(clashing_bookings),\n detail=clashing_bookings)\n\n return BookingInfo(my_booking)",
"def post(self, request):\n print('creating reservation')\n body = request.data\n responseData = {\n 'result': True,\n 'message': 'Reservation created successfully!'\n }\n try:\n if not Reservation.reservationAvailable(date=body['date'], time=body['time'], location=body['location']):\n raise OutstandingReservationExists() \n result_tuple = Client.objects.get_or_create(email=body['email'])\n client = result_tuple[0]\n desiredLocation = Location.objects.get(pk=int(body['location']))\n newReservation = Reservation.objects.create(date=body['date'], time=body['time'], client=client, location=desiredLocation, requests=body['requests'], confirmation_nonce=nonce(12))\n newReservation.save()\n responseData['result'] = Client.sendReservationConfirmation(client, newReservation)\n if not responseData['result']:\n raise Exception()\n print('reservation created')\n except Location.DoesNotExist as e:\n responseData['message'] = 'Invalid location'\n responseData['result'] = False\n except OutstandingReservationExists as e:\n responseData['message'] = 'Reservation already exists'\n responseData['result'] = False\n except Exception as e:\n print(e)\n responseData['message'] = 'Something went wrong'\n responseData['result'] = False\n finally:\n return Response(responseData)",
"def reserve_board(self, board_name, attempts = 3):\n # ----------------------------------------------------------------------- #\n # This method seems to match the desired reservation behavior. It tries #\n # to reserve for a given number of tries and, if the operation failes, #\n # an exception is raised. #\n # It is advisable to work on extending this (already implemented) method #\n # and make it perform additional tasks, if needed (for example, to also #\n # try logging on to the board in order to confirm its' operational state) #\n # ----------------------------------------------------------------------- #\n # Create a \"shell\" object. We use pexpect and not pxssh, because the command is passed\n #_shell = pexpect.spawn(\"bash\")\n #_shell.logfile = logfile\n\n self.logger.info(self.constants.INFO[\"reservationattempt\"] % board_name)\n reserved = False\n reservation_id = None\n\n reserve_cmd = self.constants.COMMANDS[\"reservetarget\"] % (board_name, \"5M\")\n self.logger.debug(reserve_cmd)\n reservation_id = self.run_command(reserve_cmd)\n\n #for i in range(attempts):\n # reserve_cmd = self.constants.COMMANDS[\"reservetarget\"] % (\"5M\", board_name)\n # self.logger.debug(reserve_cmd)\n #_shell.sendline(reserve_cmd)\n #found = _shell.expect([\"Reservation confirmed\",\"Reservation Exception\",pexpect.TIMEOUT])\n # reservation_id = self.run_command(reserve_cmd)\n # This is present in the original version, since commands were executed on remote machines,\n # via SSH. Omitting this in this context, since we run a local shell\n #self._shell.prompt(timeout=10)\n #if found==0:\n # self.logger.info(self.constants.INFO[\"reservationconfirmed\"] % board_name)\n # reserved=True\n\n # reservation_id = _shell.before[5:-2]\n # break\n #elif found==1:\n # self.logger.info(self.constants.INFO[\"targetalreadyreserved\"] % board_name)\n\n # Here we will need to invoke our ExceptionHandler, and error triage will be\n # done there. So, whenever an exception should be raised, it will be passed\n # 'blindly' to the ExceptionHandler \n # TODO: Use a custom exception instead of plain log errors\n # self.logger.error(self.constants.ERRORS[\"targetreserved\"])\n #else:\n # self.logger.info(self.constants.INFO[\"targetalreadyreserved\"] % (board_name, str(i)))\n #if not reserved:\n # self.logger.info(self.constants.ERRORS[\"unabletoreserve\"] % (board_name, attempts))\n\n return reservation_id",
"def test_reserve_card(test_gamestate):\n gamestate.GameState.reserve_card(test_gamestate, 0, test_gamestate.development_cards[0][0], 0, None)\n assert len(test_gamestate.players[0].reservations) == 1",
"def reserve_space(request, space_id):\n\n space = Space.objects.get(pk=space_id)\n\n if request.method == 'POST':\n form = ReserveSpaceForm(request.POST, space_id=space_id)\n\n if form.is_valid():\n\n # Compared id of date and time slot to confirm date and time are correct\n # should not fail as date/time slots are linked on front-end\n date = form.cleaned_data['reserve_date']\n time_slot = form.cleaned_data['reserve_time_slot']\n\n if date.pk == time_slot.pk:\n sp_slot = SpaceDateTime.objects.get(pk=time_slot.pk)\n sp_slot.space_dt_reserved_by = request.user.username\n sp_slot.space_dt_reserved = True\n sp_slot.save()\n\n return HttpResponseRedirect(reverse('account'))\n\n else:\n form = ReserveSpaceForm(space_id=space_id)\n\n else:\n form = ReserveSpaceForm(space_id=space_id)\n\n context = {\n \"form\": form,\n \"space\": space,\n \"space_id\": space_id,\n }\n\n return render(request, 'sharedspaces/reserve_space.html', context=context)",
"def get_host_reservation_purchase_preview(OfferingId=None, HostIdSet=None):\n pass",
"def changeReservation(self):\n\t\tres,car = None,None \t# Save the reservation we're changing with it's previous car\n\t\tchosenCar = None \t\t# Save the new car we are going to assign to the reservation\n\t\tdelete = []\t\t\t# Keep a list of reservations which need to be deleted\n\t\twhile True:\t\t\t\t# Search for a reservation with more than 1 possible car\n\t\t\tres,car = random.choice(list(self.resCars.items()))\n\t\t\tcarCount = res.getCarsObj()\n\t\t\tif len(carCount) > 1:\n\t\t\t\twhile True:\t\t# Search for another car for this reservation which is not the previous car\n\t\t\t\t\tchosenCar = random.choice(carCount)\n\t\t\t\t\tif chosenCar is not car:\n\t\t\t\t\t\tself.resCars[res] = chosenCar\n\t\t\t\t\t\tbreak\n\t\t\t\tbreak\n\t\tfor i in range(len(self.usedCars[car])):\t\t\t# Find the used timeslot of the reservation for the old car and remove it\n\t\t\tif int(self.usedCars[car][i][0]) == int(res.getStart()):\n\t\t\t\tself.usedCars[car].pop(i)\n\t\t\t\tbreak\n\t\tif not self.checkZone(res.getZoneObj(),chosenCar):\t# If the car is in the wrong zone, ...\n\t\t\tmatchingZone = 0\n\t\t\tfor z in res.getZoneObj().getZonesObj():\t\t# Search for neighbouring zones which will work with the reservation\n\t\t\t\tif (self.checkZone(z,chosenCar)):\n\t\t\t\t\tself.carZones[chosenCar] = z \t\t\t# Change the zone of the car\n\t\t\t\t\tmatchingZone = 1\n\t\t\t\t\tbreak\n\t\t\tif not matchingZone:\t\t\t\t\t\t\t# If their are no neighbouring matching zones, ...\n\t\t\t\tself.carZones[chosenCar] = res.getZoneObj() # change the car to the zone of the reservation\n\n\t\tfor r,c in self.resCars.items():\t# Check for all reservations who use this car if they are still feasible\n\t\t\tif c is chosenCar:\n\t\t\t\tif not self.checkZone(r.getZoneObj(),c):\n\t\t\t\t\tdelete.append(r)\t\t# Otherwise, add them to the delete list\n\t\t\t\t\tfor i in range(len(self.usedCars[c])):\t# And remove their timeslot from the car\n\t\t\t\t\t\tif int(self.usedCars[c][i][0]) == int(r.getStart()):\n\t\t\t\t\t\t\tself.usedCars[c].pop(i)\n\t\t\t\t\t\t\tbreak\n\t\tfor resDel in delete:\t\t\t\t# Remove the reservations from the list\n\t\t\tdel self.resCars[resDel]\n\t\t\tself.unassigned.append(resDel)\t# Add the removed reservations to the unassigned list\n\n\t\tdelete = []\t# Empty the list of cars to delete\n\t\tdeletepop = []\t# Create a new list of timeslot to delete from the car\n\t\ttimeslot = self.checkTime(chosenCar,res.getStart(),res.getDuration())\t# Check if the reservation fits in the schedule of the car\n\t\tif timeslot > 0:\t\t# If so, add it to the schedule\n\t\t\tself.addTimeslot(timeslot, res, chosenCar)\n\t\telse:\t\t\t\t\t# If not, remove all conflicting reservations\n\t\t\ts2 = int(res.getStart())\n\t\t\td2 = int(res.getDuration())\n\t\t\tfor i in range(len(self.usedCars[chosenCar])):\n\t\t\t\ts1 = int(self.usedCars[chosenCar][i][0])\n\t\t\t\td1 = int(self.usedCars[chosenCar][i][1])\n\t\t\t\tif (((s1 < s2) and (s1 + d1 >= s2)) or ((s1 > s2) and (s1 <= s2 + d2))):\n\t\t\t\t\tdeletepop.append(i)\n\t\t\t\t\tfor r,c in self.resCars.items():\n\t\t\t\t\t\tif c is chosenCar and int(r.getStart()) == s1 :\n\t\t\t\t\t\t\tdelete.append(r)\n\t\t\tfor res in delete:\t\t\t\t\t\t\t\t# Remove the reservations from the list\n\t\t\t\tdel self.resCars[res]\n\t\t\t\tself.unassigned.append(res)\n\t\t\tfor c,i in enumerate(deletepop):\t\t\t\t# Remove conflicting timeslots\n\t\t\t\tself.usedCars[chosenCar].pop(i-c)\n\n\t\t\ttimeslot = self.checkTime(chosenCar,res.getStart(),res.getDuration())\t# If no further conflicts ...\n\t\t\tif timeslot > 0:\n\t\t\t\tself.addTimeslot(timeslot, res, chosenCar)\t# Add the reservation in the schedule\n\t\tself.reassign() # Try to reassign as much of the unassigned reservations as possible",
"def test_reserve_enforcement(node_factory, executor):\n l1, l2 = node_factory.line_graph(2, opts={'may_reconnect': True,\n 'dev-no-reconnect': None,\n 'allow_warning': True})\n\n # Pay 1000 satoshi to l2.\n l1.pay(l2, 1000000)\n l2.stop()\n\n # They should both aim for 1%.\n reserves = l2.db.query('SELECT channel_reserve_satoshis FROM channel_configs')\n assert reserves == [{'channel_reserve_satoshis': 10**6 // 100}] * 2\n\n # Edit db to reduce reserve to 0 so it will try to violate it.\n l2.db.execute('UPDATE channel_configs SET channel_reserve_satoshis=0')\n\n l2.start()\n l2.rpc.connect(l1.info['id'], 'localhost', l1.port)\n\n # This should be impossible to pay entire thing back: l1 should warn and\n # close connection for trying to violate reserve.\n executor.submit(l2.pay, l1, 1000000)\n l1.daemon.wait_for_log(\n 'Peer transient failure in CHANNELD_NORMAL: channeld.*'\n ' CHANNEL_ERR_CHANNEL_CAPACITY_EXCEEDED'\n )\n wait_for(lambda: only_one(l1.rpc.listpeers()['peers'])['connected'] is False)",
"def makeReservation(self, account, acl, start_time, end_time, is_demo=False):\n acl.assertValid(account, self)\n\n # first validate that the times don't violate any of the constraints\n if self.constraints:\n (start_time, end_time) = self.constraints.validate(start_time, end_time)\n\n # ensure we start before we finish!\n if start_time > end_time:\n tmp = start_time\n start_time = end_time\n end_time = tmp\n\n if start_time == end_time:\n raise BookingError(\"Could not create a reservation as the start time (%s) equals the end time (%s)\" % \\\n (to_string(start_time),to_string(end_time)))\n \n now_time = get_now_time()\n\n if start_time < now_time:\n raise BookingError(\"Could not create a reservation as the start time (%s) is in the past (now is %s)\" % \\\n (to_string(start_time),to_string(now_time)))\n\n if not is_demo:\n # try to create a new booking object that exists in the time for this \n # booking\n my_booking = BookingInfo.create(self, account, start_time, end_time)\n\n if not my_booking:\n raise BookingError(\"Could not create the booking!\")\n\n return my_booking",
"def reassign(self):\n\t\tdelete = []\t\t\t# Empty the list of reservations to delete\n\t\trandom.shuffle(self.unassigned)\t# Shuffle the unassigned reservations to make sure we're not always starting with the same one\n\t\tfor idx,r in enumerate(self.unassigned):\t# For all unassigned reservations ...\n\t\t\tmatch = 0\t# Found a matching car?\n\t\t\ttimeslot = 0\t# Is there a possible timeslot? If so, where is it?\n\t\t\tfor c in r.getCarsObj():\t# Check all possible cars for this reservation\n\t\t\t\ttimeslot = self.checkTime(c, r.getStart(), r.getDuration())\t# Is there a usable timeslot in this cars schedule?\n\t\t\t\tif timeslot > 0:\n\t\t\t\t\tif self.checkZone(r.getZoneObj(), c): \t# Is the assigned zone okay for the reservation\n\t\t\t\t\t\tself.resCars[r] = c \t\t\t\t# If yes, match found. This car will be assigned to the reservation\n\t\t\t\t\t\tmatch = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\tif match:\t\t\t\t\t# If there was a car found ...\n\t\t\t\tdelete.append(idx)\t\t# Delete the reservation from the unassigned\n\t\t\t\ti = self.resCars[r]\n\t\t\t\tself.addTimeslot(timeslot, r, i)\t# Add the timeslot to the schedule of the car\n\n\t\tfor c,i in enumerate(delete):\t# Remove all matched reservations\n\t\t\tself.unassigned.pop(i-c)",
"def describe_host_reservations(HostReservationIdSet=None, Filters=None, MaxResults=None, NextToken=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Purchases a Reserved Instance for use with your account. With Reserved Instances, you pay a lower hourly rate compared to OnDemand instance pricing. Use DescribeReservedInstancesOfferings to get a list of Reserved Instance offerings that match your specifications. After you've purchased a Reserved Instance, you can check for your new Reserved Instance with DescribeReservedInstances . For more information, see Reserved Instances and Reserved Instance Marketplace in the Amazon Elastic Compute Cloud User Guide .
|
def purchase_reserved_instances_offering(DryRun=None, ReservedInstancesOfferingId=None, InstanceCount=None, LimitPrice=None):
pass
|
[
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def describe_reserved_instances_offerings(DryRun=None, ReservedInstancesOfferingIds=None, InstanceType=None, AvailabilityZone=None, ProductDescription=None, Filters=None, InstanceTenancy=None, OfferingType=None, NextToken=None, MaxResults=None, IncludeMarketplace=None, MinDuration=None, MaxDuration=None, MaxInstanceCount=None, OfferingClass=None):\n pass",
"def attemptPurchases(order):\n print(\"\\n\")\n # here we sort out the availability zones\n hasOrdersAssigned = True\n\n for az in order.AvailabilityZones:\n if az.ordered is None:\n az.ordered = 0\n if az.Number is None:\n hasOrdersAssigned = False\n\n if hasOrdersAssigned == False:\n remainder = int(order.Number) % len(order.AvailabilityZones)\n eachOrderGets = int((int(order.Number) - remainder) /\n len(order.AvailabilityZones))\n # here we assign all the orders\n for az in order.AvailabilityZones:\n az.Number = eachOrderGets\n if remainder != 0:\n az.Number += 1\n remainder -= 1\n\n # this client can be used for all the az's\n print(order.Region)\n client = boto3.client('ec2', region_name=order.Region,aws_access_key_id=order.aws_access_key_id,aws_secret_access_key=order.aws_secret_access_key)\n for az in order.AvailabilityZones:\n\n # for each AZ we're buying from\n kwargs = order.getKwargs(az.Name)\n response = client.describe_reserved_instances_offerings(**kwargs)\n ReservedInstancesOfferings = response[\"ReservedInstancesOfferings\"]\n\n # we search for all instance types, not just fixed or hourly, then sort when we recieve results\n # do the sorting of the reserved instances by price, cheapest first\n allOfferings = []\n\n # get all the offerings objects\n for instanceOffering in ReservedInstancesOfferings:\n # isFixed and isHourly completely filter out or in whether or not those instance types get included\n # if both are true, then all types of instances get included regardless of payment type\n\n # for limits, 0 means no limit, everything else abides by the limit\n\n iOffering = getInstanceOffering(instanceOffering)\n fixedPrice = iOffering.FixedPrice\n recurringAmount = iOffering.RecurringAmount\n fixedPriceExists = False\n recurringAmountExists = False\n\n if fixedPrice is not None and fixedPrice != 0:\n fixedPriceExists = True\n if recurringAmount is not None and recurringAmount != 0:\n recurringAmountExists = True\n\n MaxFixedPrice = 0\n if order.MaxFixedPrice is not None:\n MaxFixedPrice = order.MaxFixedPrice\n\n MaxRecurringPrice = 0\n if order.MaxHourlyPrice is not None:\n MaxRecurringPrice = order.MaxHourlyPrice\n\n if order.isFixedPrice == True and order.isHourlyPrice == True:\n # either hourly or fixed or both\n if fixedPriceExists and recurringAmountExists:\n if (MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice) and (MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice):\n allOfferings.append(iOffering)\n elif fixedPriceExists:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n elif recurringAmountExists:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n elif order.isFixedPrice == True:\n # only fixed price servers\n if fixedPriceExists and recurringAmountExists == False:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n\n elif order.isHourlyPrice == True:\n # only hourly servers\n if recurringAmountExists and fixedPriceExists == False:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n # sort into cost effectiveness, and these all have the correct AZ\n allOfferings.sort(key=lambda x: x.EffectiveHourlyRate)\n\n # print(order.Number)\n if order.Number is not None and order.Number > 0:\n if order.ordered is None:\n # brand new order bring it up to speed\n order.ordered = 0\n\n if az.ordered >= az.Number:\n print(\"AZ\", az.Name, \"has already been fulfilled with\",\n az.ordered, \"instances\")\n # buy until finished\n purchasedJustNow = 0\n previouslyPurchased = az.ordered\n for instanceOffering in allOfferings:\n # instanceOffering.print()\n # also we might want to write to the file, like keep it open, and update it for each order bought\n # something might go wrong\n # print(instanceOffering, \"\\n\")\n if order.ordered < order.Number and az.ordered < az.Number:\n # do purchase\n order.ordered += 1\n az.ordered += 1\n purchasedJustNow += 1\n instance = allOfferings.pop(0)\n kwargs = instance.getKwargs(order.DryRun)\n response = None\n try:\n response = client.purchase_reserved_instances_offering(\n **kwargs)\n print(response)\n except:\n pass\n print(\"Just Purchased:\")\n instanceOffering.print()\n order.PurchasedInstances.append(instanceOffering)\n\n if order.ordered >= order.Number or az.ordered >= az.Number:\n break\n\n print(purchasedJustNow,\n \"Reserved Instances were just purchased for:\", az.Name)\n print(previouslyPurchased, \"instances had been purchased previously\")\n if az.ordered >= az.Number:\n print(\"Purchased all\", az.ordered,\n \"Reserved Instances for:\", az.Name, \"\\n\")\n else:\n print(\"Still need\", int(az.Number - az.ordered), \"instances for availability zone:\",\n az.Name, \", will attempt to purchase the rest during the next run\", \"\\n\")\n\n if order.ordered >= order.Number:\n print(\"Purchased all\", order.ordered,\n \"Reserved Instances for this order\\n\\n\")\n else:\n print(\"Could only purchase\", order.ordered,\n \"Reserved Instances for this order, will attempt to purchase the rest at a later date.\\n\\n\")\n return",
"def describe_reserved_instances(DryRun=None, ReservedInstancesIds=None, Filters=None, OfferingType=None, OfferingClass=None):\n pass",
"def purchase_scheduled_instances(DryRun=None, ClientToken=None, PurchaseRequests=None):\n pass",
"def getReservedInstances(verbose):\n lres = {}\n jResp = EC2C.describe_reserved_instances()\n for reserved in jResp['ReservedInstances']:\n if reserved['State'] == 'active':\n if verbose:\n lres[reserved['InstanceType']] = str(reserved['Start'])+\";\"+\\\n str(reserved['End'])+\";\"+\\\n str(reserved['InstanceCount'])+\";\"+\\\n reserved['ProductDescription']+\";\"+\\\n str(reserved['UsagePrice'])\n else:\n if re.search(\"win\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"windows\"\n elif re.search(\"red hat\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"redhat\"\n elif re.search(\"suse\", reserved['ProductDescription'], re.IGNORECASE):\n os = \"suse\"\n else:\n os = \"linux\"\n lres[reserved['InstanceType']+\";\"+os] = str(reserved['InstanceCount'])\n return lres",
"def purchase_host_reservation(OfferingId=None, HostIdSet=None, LimitPrice=None, CurrencyCode=None, ClientToken=None):\n pass",
"def optimizeReservation(verbose,region):\n print(\"WARNING: As it's not possible to get OS through AWS API, All \"\\\n \"Linux are reported as Linux (no RedHat, Suse, etc)\\n\"\\\n \"This issue will be address in a future update\\n\\n\")\n shouldReserved = {}\n dreserved = getReservedInstances(False)\n dinstances = listInstances(False)\n dflavors = getInstanceTypes(region)\n count_by_type_os = countInstanceByTypeByOS(False, dinstances)\n resp = \"\"\n for typos, nb in count_by_type_os.items():\n if typos in dreserved:\n if int(count_by_type_os[typos]) - int(dreserved[typos]) >= 0:\n count_by_type_os[typos] = int(count_by_type_os[typos]) - int(dreserved[typos])\n resp += \"Reservation fully used for \"+typos+\"\\n\"\n else:\n print(\"Reservation not fully used for \"+typos+\": \"+dreserved[typos]+\"reserved but only \"+count_by_type_os[typos]+\" instances\")\n for typos, nb in dreserved.items():\n if typos not in count_by_type_os:\n resp += \"Reservation is not used for \"+typos+\"\\n\"\n #Provide tips for better reservations\n #Begin by removing instances that have reservation\n for instanceId in list(dinstances):\n if dinstances[instanceId]['flavor'] in dreserved:\n if int(dreserved[dinstances[instanceId]['flavor']]) > 0:\n dreserved[dinstances[instanceId]['flavor']] -= 1\n del dinstances[instanceId]\n today = datetime.datetime.now(datetime.timezone.utc)\n months6 = today-datetime.timedelta(days=180)\n for k, v in dinstances.items():\n if v['LaunchTime'] < months6:\n try:\n shouldReserved[v['flavor']+\";\"+v['platform']] += 1\n except:\n shouldReserved[v['flavor']+\";\"+v['platform']] = 1\n resp += \"\\nBased on instances older than 6 months, you should buy following reservations:\\n\"\n saveno, savepa = 0, 0\n for k, v in shouldReserved.items():\n resp += k+\":\"+str(v)+\"\\n\"\n saveno += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1yno'])) * v\n savepa += (float(dflavors[k]['ondemand']) - float(dflavors[k]['reserved1ypa'])) * v\n resp += \"You can save up to \"+str(saveno)+\"$/hour with no upfront reservation\\n\"\n resp += \"You can save up to \"+str(savepa)+\"$/hour with partial upfront reservation\\n\"\n if verbose:\n resp += \"\\nInstances below doesn't have reservation:\\n\"\n for k, v in count_by_type_os.items():\n resp += k+\":\"+str(v)+\"\\n\"\n return saveno, resp",
"def modify_reserved_instances(ClientToken=None, ReservedInstancesIds=None, TargetConfigurations=None):\n pass",
"def confirm_product_instance(DryRun=None, ProductCode=None, InstanceId=None):\n pass",
"def _to_reserved_node(self, element):\r\n\r\n # Get our extra dictionary\r\n extra = self._get_extra_dict(\r\n element, RESOURCE_EXTRA_ATTRIBUTES_MAP['reserved_node'])\r\n\r\n try:\r\n size = [size for size in self.list_sizes() if\r\n size.id == extra['instance_type']][0]\r\n except IndexError:\r\n size = None\r\n\r\n return EC2ReservedNode(id=findtext(element=element,\r\n xpath='reservedInstancesId',\r\n namespace=NAMESPACE),\r\n state=findattr(element=element,\r\n xpath='state',\r\n namespace=NAMESPACE),\r\n driver=self,\r\n size=size,\r\n extra=extra)",
"def reserve_booking(booking):\n try:\n id = str(uuid.uuid4())\n booking_item = {\n \"id\": id,\n \"stateExecutionId\": booking[\"name\"],\n \"__typename\": \"Booking\",\n \"bookingOutboundFlightId\": booking[\"outboundFlightId\"],\n \"checkedIn\": False,\n \"customer\": booking[\"customerId\"],\n \"paymentToken\": booking[\"chargeId\"],\n \"status\": \"UNCONFIRMED\",\n \"createdAt\": str(datetime.datetime.now()),\n }\n\n table.put_item(Item=booking_item)\n\n return {\"bookingId\": id}\n except ClientError as e:\n raise BookingReservationException(e.response[\"Error\"][\"Message\"])",
"def MaxSmallInstances(self, available_small=None,zone = None):\n if available_small is None:\n available_small = self.tester.get_available_vms()\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(self.image,keypair=self.keypair.name, group=self.group.name,min=available_small, max=available_small, zone=zone)\n self.assertTrue( self.tester.wait_for_reservation(self.reservation) ,'Not all instances went to running')\n return self.reservation",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def LargestInstance(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(self.image,keypair=self.keypair.name, group=self.group.name,type=\"c1.xlarge\")\n self.assertTrue( self.tester.wait_for_reservation(self.reservation) ,'Not all instances went to running')\n return self.reservation",
"def create_ec2_instace(name=\"shopply\", security_group=\"dwd\"):\n conn = boto.connect_ec2()\n reservation = conn.run_instances(\n AMI,\n key_name = KEYPAIR,\n instance_type = 't1.micro',\n security_groups = [security_group],\n instance_initiated_shutdown_behavior = \"stop\"\n )\n \n instance = reservation.instances[0]\n instance.add_tag(\"Name\", name)\n \n \n print \"Launching instance: \", instance.public_dns_name",
"def _menu_aws_compute_new_instance():\n # AMIs dict\n amis = {'1': 'ami-31328842', '2': 'ami-8b8c57f8', '3': 'ami-f95ef58a', '4': 'ami-c6972fb5'}\n # Ask user to enter instance name\n i_name = raw_input(\"Enter instance name: \")\n # Ask user to choose OS\n print \"Creating new instance.. Choose OS:\"\n print \"\\t1. Amazon Linux\"\n print \"\\t2. Red Hat Enterprise Linux 7.2\"\n print \"\\t3. Ubuntu Server 14.04 LTS\"\n print \"\\t4. Microsoft Windows Server 2012 R2 Base\"\n op = raw_input(\"Enter option: \")\n # Validating entered option\n op = __op_validation(r'^([1-4]|\\\\q)$', op)\n if op == \"\\\\q\":\n _menu_aws_compute()\n else:\n # Create new fresh instance\n ec2i.start_new_instance(ec2conn, amis[op], i_name)",
"def ElasticIps(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n return self.reservation",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Purchases one or more Scheduled Instances with the specified schedule. Scheduled Instances enable you to purchase Amazon EC2 compute capacity by the hour for a oneyear term. Before you can purchase a Scheduled Instance, you must call DescribeScheduledInstanceAvailability to check for available schedules and obtain a purchase token. After you purchase a Scheduled Instance, you must call RunScheduledInstances during each scheduled time period. After you purchase a Scheduled Instance, you can't cancel, modify, or resell your purchase.
|
def purchase_scheduled_instances(DryRun=None, ClientToken=None, PurchaseRequests=None):
pass
|
[
"def run_scheduled_instances(DryRun=None, ClientToken=None, InstanceCount=None, ScheduledInstanceId=None, LaunchSpecification=None):\n pass",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"async def set_charge_schedules(\n self, schedules: list[models.ChargeSchedule]\n ) -> models.KamereonVehicleChargeScheduleActionData:\n return await self._vehicle.set_charge_schedules(schedules)",
"def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):\n pass",
"def set_schedule(self, schedule):\n data = {'propagateToInstances':True, 'schedule':schedule}\n return self.client.put_asg_scaling_schedule(environment=self.env, asgname=self.name, data=data)",
"def run(**kwargs):\n from apscheduler.scheduler import Scheduler\n\n sched = Scheduler(**kwargs)\n\n for task, kwargs in schedule.tasks.iteritems():\n sched.add_cron_job(task.run, name=task.__name__, **kwargs)\n\n sched.start() # main loop",
"def attemptPurchases(order):\n print(\"\\n\")\n # here we sort out the availability zones\n hasOrdersAssigned = True\n\n for az in order.AvailabilityZones:\n if az.ordered is None:\n az.ordered = 0\n if az.Number is None:\n hasOrdersAssigned = False\n\n if hasOrdersAssigned == False:\n remainder = int(order.Number) % len(order.AvailabilityZones)\n eachOrderGets = int((int(order.Number) - remainder) /\n len(order.AvailabilityZones))\n # here we assign all the orders\n for az in order.AvailabilityZones:\n az.Number = eachOrderGets\n if remainder != 0:\n az.Number += 1\n remainder -= 1\n\n # this client can be used for all the az's\n print(order.Region)\n client = boto3.client('ec2', region_name=order.Region,aws_access_key_id=order.aws_access_key_id,aws_secret_access_key=order.aws_secret_access_key)\n for az in order.AvailabilityZones:\n\n # for each AZ we're buying from\n kwargs = order.getKwargs(az.Name)\n response = client.describe_reserved_instances_offerings(**kwargs)\n ReservedInstancesOfferings = response[\"ReservedInstancesOfferings\"]\n\n # we search for all instance types, not just fixed or hourly, then sort when we recieve results\n # do the sorting of the reserved instances by price, cheapest first\n allOfferings = []\n\n # get all the offerings objects\n for instanceOffering in ReservedInstancesOfferings:\n # isFixed and isHourly completely filter out or in whether or not those instance types get included\n # if both are true, then all types of instances get included regardless of payment type\n\n # for limits, 0 means no limit, everything else abides by the limit\n\n iOffering = getInstanceOffering(instanceOffering)\n fixedPrice = iOffering.FixedPrice\n recurringAmount = iOffering.RecurringAmount\n fixedPriceExists = False\n recurringAmountExists = False\n\n if fixedPrice is not None and fixedPrice != 0:\n fixedPriceExists = True\n if recurringAmount is not None and recurringAmount != 0:\n recurringAmountExists = True\n\n MaxFixedPrice = 0\n if order.MaxFixedPrice is not None:\n MaxFixedPrice = order.MaxFixedPrice\n\n MaxRecurringPrice = 0\n if order.MaxHourlyPrice is not None:\n MaxRecurringPrice = order.MaxHourlyPrice\n\n if order.isFixedPrice == True and order.isHourlyPrice == True:\n # either hourly or fixed or both\n if fixedPriceExists and recurringAmountExists:\n if (MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice) and (MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice):\n allOfferings.append(iOffering)\n elif fixedPriceExists:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n elif recurringAmountExists:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n elif order.isFixedPrice == True:\n # only fixed price servers\n if fixedPriceExists and recurringAmountExists == False:\n if MaxFixedPrice == 0 or iOffering.FixedPrice <= MaxFixedPrice:\n allOfferings.append(iOffering)\n\n elif order.isHourlyPrice == True:\n # only hourly servers\n if recurringAmountExists and fixedPriceExists == False:\n if MaxRecurringPrice == 0 or iOffering.RecurringAmount <= MaxRecurringPrice:\n allOfferings.append(iOffering)\n\n # sort into cost effectiveness, and these all have the correct AZ\n allOfferings.sort(key=lambda x: x.EffectiveHourlyRate)\n\n # print(order.Number)\n if order.Number is not None and order.Number > 0:\n if order.ordered is None:\n # brand new order bring it up to speed\n order.ordered = 0\n\n if az.ordered >= az.Number:\n print(\"AZ\", az.Name, \"has already been fulfilled with\",\n az.ordered, \"instances\")\n # buy until finished\n purchasedJustNow = 0\n previouslyPurchased = az.ordered\n for instanceOffering in allOfferings:\n # instanceOffering.print()\n # also we might want to write to the file, like keep it open, and update it for each order bought\n # something might go wrong\n # print(instanceOffering, \"\\n\")\n if order.ordered < order.Number and az.ordered < az.Number:\n # do purchase\n order.ordered += 1\n az.ordered += 1\n purchasedJustNow += 1\n instance = allOfferings.pop(0)\n kwargs = instance.getKwargs(order.DryRun)\n response = None\n try:\n response = client.purchase_reserved_instances_offering(\n **kwargs)\n print(response)\n except:\n pass\n print(\"Just Purchased:\")\n instanceOffering.print()\n order.PurchasedInstances.append(instanceOffering)\n\n if order.ordered >= order.Number or az.ordered >= az.Number:\n break\n\n print(purchasedJustNow,\n \"Reserved Instances were just purchased for:\", az.Name)\n print(previouslyPurchased, \"instances had been purchased previously\")\n if az.ordered >= az.Number:\n print(\"Purchased all\", az.ordered,\n \"Reserved Instances for:\", az.Name, \"\\n\")\n else:\n print(\"Still need\", int(az.Number - az.ordered), \"instances for availability zone:\",\n az.Name, \", will attempt to purchase the rest during the next run\", \"\\n\")\n\n if order.ordered >= order.Number:\n print(\"Purchased all\", order.ordered,\n \"Reserved Instances for this order\\n\\n\")\n else:\n print(\"Could only purchase\", order.ordered,\n \"Reserved Instances for this order, will attempt to purchase the rest at a later date.\\n\\n\")\n return",
"def _create_scheduled_actions(conn, as_name, scheduled_actions):\n if scheduled_actions:\n for name, action in scheduled_actions.items():\n if \"start_time\" in action and isinstance(action[\"start_time\"], str):\n action[\"start_time\"] = datetime.datetime.strptime(\n action[\"start_time\"], DATE_FORMAT\n )\n if \"end_time\" in action and isinstance(action[\"end_time\"], str):\n action[\"end_time\"] = datetime.datetime.strptime(\n action[\"end_time\"], DATE_FORMAT\n )\n conn.create_scheduled_group_action(\n as_name,\n name,\n desired_capacity=action.get(\"desired_capacity\"),\n min_size=action.get(\"min_size\"),\n max_size=action.get(\"max_size\"),\n start_time=action.get(\"start_time\"),\n end_time=action.get(\"end_time\"),\n recurrence=action.get(\"recurrence\"),\n )",
"def ec2_schedule(schedule_action, tag_key, tag_value):\n if schedule_action == \"stop\":\n ec2_stop_instances(tag_key, tag_value)\n elif schedule_action == \"start\":\n ec2_start_instances(tag_key, tag_value)\n else:\n logging.error(\"Bad scheduler action\")",
"def test_jenkins_autoscaling_schedules_set(self) -> None:\n self.assertTrue(all([\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-morning',\n recurrence='0 11 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-morning',\n recurrence='0 12 * * *',\n max_size=0,\n min_size=0,\n desired_size=0),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-evening',\n recurrence='0 22 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-evening',\n recurrence='0 23 * * *',\n max_size=0,\n min_size=0,\n desired_size=0\n )\n ]))",
"def test_schedule(self):\r\n template = copy.deepcopy(self.policy_template)\r\n props = template['Resources']['my_policy']['Properties']\r\n props['type'] = 'schedule'\r\n props['args'] = {'cron': '0 0 0 * *'}\r\n self._setup_test_stack(template)\r\n self.assertEqual(\r\n {\r\n 'name': '+10 on webhook',\r\n 'scaling_group': 'my-group-id',\r\n 'change': 10,\r\n 'cooldown': 0,\r\n 'policy_type': 'schedule',\r\n 'args': {'cron': '0 0 0 * *'}},\r\n self.fake_auto_scale.policies['0'].kwargs)",
"def purchase_reserved_instances_offering(DryRun=None, ReservedInstancesOfferingId=None, InstanceCount=None, LimitPrice=None):\n pass",
"def set_schedule(self, schedule):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.object.schedule\", self._object._eco_id, schedule)\r\n p2e._app.Exec(arg_str)",
"def create_schedule(self, schedule_form):\n return # osid.calendaring.Schedule",
"def delete_schedule(self, schedule_id):\n pass",
"def scheduled(self, scheduler):",
"def export_product_prices_using_cron(cls, channels): # pragma: nocover\n for channel in channels:\n try:\n channel.export_product_prices()\n except UserError:\n # Silently pass if method is not implemented\n pass",
"def create_cron_task_instance(self, execute_date, cron_list, session=None):\n scheduelr_time = datetime.now()\n task_ids = []\n instance_list = []\n for cron_conf in cron_list:\n instance = TaskInstance(\n etl_day=execute_date,\n task_id=cron_conf.task_id,\n name=cron_conf.name,\n task_type=State.TASK_CRON,\n module=\"bi\",\n status=State.QUEUED,\n scheduler_time=scheduelr_time,\n scheduler_retry=0,\n worker_retry=0,\n )\n task_ids.append(instance.task_id)\n instance_list.append(instance)\n session.add_all(instance_list)\n session.commit()\n\n # refresh\n task_instance = session.query(TaskInstance).filter(TaskInstance.task_id.in_(task_ids)) \\\n .filter(TaskInstance.etl_day == execute_date) \\\n .filter(func.cast(TaskInstance.scheduler_time, DateTime) == func.cast(scheduelr_time, DateTime)) \\\n .all()\n return task_instance",
"def cleanup_scheduled(self, statuses=[COMPLETED],expiration=24*3600):\n db = self.db\n now = datetime.now()\n db(db.task_scheduled.status.belongs(statuses))\\\n (db.task_scheduled.last_run_time+expiration<now).delete()\n db.commit()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Requests a reboot of one or more instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. If an instance does not cleanly shut down within four minutes, Amazon EC2 performs a hard reboot. For more information about troubleshooting, see Getting Console Output and Rebooting Instances in the Amazon Elastic Compute Cloud User Guide .
|
def reboot_instances(DryRun=None, InstanceIds=None):
pass
|
[
"def rebootInstances(self, api_client):\n\n cmd = {'group': self.id}\n return api_client.rebootVirtualMachine(**cmd)",
"def restart() -> None:\n config = load_config_file()\n instance_ips = [i.public_ip_address for i in get_running_instances(config)]\n if not instance_ips:\n raise Exception('ERROR: No instances with public IPs found. Exiting.')\n try:\n execute_commands_on_linux_instances(\n config,\n [\n COMMAND_KILL,\n COMMAND_CLEAN,\n COMMAND_DOWNLOAD,\n COMMAND_START\n ],\n instance_ips\n )\n except Exception as e:\n logging.error(\"Something went wrong.\")\n raise\n logging.info('Done!')",
"def reboot(self):\n LOG.info('Reboot nodes: %s', self)\n task = {'command': 'reboot now'}\n self.cloud_management.execute_on_cloud(self.get_ips(), task)",
"def poll_rebooting_instances(self, *args, **kwargs):\n raise NotImplementedError()",
"def server_reboot(self):\n return self._post(Endpoint.REBOOT_SERVER)",
"def Reboot(self, zone=None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(self.image, keypair=self.keypair.name, group=self.group.name, zone=zone)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n ### Create 1GB volume in first AZ\n self.assertTrue(self.create_attach_volume(instance, 1), \"Was not able to attach volume\")\n ### Reboot instance\n instance.reboot()\n self.tester.sleep(30) \n self.tester.debug(\"Restarting SSH session to instance\")\n instance.reset_ssh_connection()\n ### Check for device in instance\n ### Make sure volume is still attached after reboot\n if self.volume_device is None:\n self.assertTrue(False, \"Failed to find volume on instance\")\n instance.assertFilePresent(self.volume_device) \n self.assertTrue(self.tester.detach_volume(self.volume), \"Unable to detach volume\")\n self.assertTrue(self.tester.delete_volume(self.volume), \"Unable to delete volume\")\n return self.reservation",
"def test_04_reboot_instance_in_network(self):\n\n # Validate the following\n # 1. Reboot the virtual machines.\n # 2. Vm should be started successfully.\n # 3. Make sure that all the PF,LB and Static NAT rules on this VM\n # works as expected.\n # 3. Make sure that we are able to access google.com from this user Vm\n\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n self.debug(\"Starting the virtual machines in account: %s\" %\n self.account.name)\n try:\n self.vm_1.reboot(self.apiclient)\n self.vm_2.reboot(self.apiclient)\n except Exception as e:\n self.fail(\"Failed to reboot the virtual instances, %s\" % e)\n\n # Wait until vms are up\n time.sleep(120)\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n return",
"def terminate_instances(self):\n\n if self._reservation and self._reservation.instances:\n for instance in self._reservation.instances:\n instance.terminate()\n msg = 'EC2 instance terminated.'\n log.info(msg)\n self._store_message(msg)",
"def reboot(self):\n self.send_command(api.reboot)",
"def _RebootInstance(name, opts):\n return opcodes.OpInstanceReboot(instance_name=name,\n reboot_type=opts.reboot_type,\n ignore_secondaries=opts.ignore_secondaries,\n shutdown_timeout=opts.shutdown_timeout)",
"def test_04_reboot_instance_in_network(self):\n\n # Validate the following\n # 1. Reboot the virtual machines.\n # 2. Vm should be started successfully.\n # 3. Make sure that all the PF,LB and Static NAT rules on this VM\n # works as expected.\n # 3. Make sure that we are able to access google.com from this user Vm\n\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n\n self.debug(\"Starting the virtual machines in account: %s\" %\n self.account.name)\n try:\n self.vm_1.reboot(self.apiclient)\n self.vm_2.reboot(self.apiclient)\n except Exception as e:\n self.fail(\"Failed to reboot the virtual instances, %s\" % e)\n\n self.debug(\"Validating if the network rules work properly or not?\")\n self.validate_network_rules()\n return",
"def stopinstances():\n username, conn = _getbotoconn(auth_user)\n print \"stopping instances running under the %s account\" % username\n\n running_instances = _getrunninginstances(conn)\n for instid, instance in running_instances.iteritems():\n instance.stop()\n print \"instance %s stopped\" % instid",
"def delete_ec2_instances():\n print('Deleting EC2 instances')\n ec2 = boto3.resource('ec2')\n\n active_ec2_instance_count = 0\n for instance in ec2.instances.all():\n disable_api_termination = instance.describe_attribute(\n Attribute='disableApiTermination'\n )\n if disable_api_termination['DisableApiTermination']['Value']:\n print('Stopping instance to enable API termination - {}'.format(instance.instance_id))\n instance.stop()\n active_ec2_instance_count = active_ec2_instance_count + 1\n else:\n if instance.state['Code'] != 48: # code 48 is 'terminated'\n print('Terminating instance - {}'.format(instance.instance_id))\n instance.terminate()\n active_ec2_instance_count = active_ec2_instance_count + 1\n\n if active_ec2_instance_count > 0:\n print('Waiting for ec2 instances to stop or terminate')\n while [instance for instance in ec2.instances.all()]:\n all_terminated = True\n for instance in ec2.instances.all():\n disable_api_termination = instance.describe_attribute(\n Attribute='disableApiTermination'\n )\n if (disable_api_termination['DisableApiTermination']['Value'] and\n instance.state['Code'] == 80):\n # code 80 is 'stopped'\n # instance has termination protection switched on and is stopped\n # switch it off and terminate the instance\n instance.modify_attribute(\n DisableApiTermination={\n 'Value': False\n }\n )\n instance.terminate()\n if instance.state['Code'] != 48: # code 48 is 'terminated'\n all_terminated = False\n\n if all_terminated:\n break\n else:\n time.sleep(5)\n\n print('EC2 instances deleted')",
"def cmd_reboot(self):\n self.send(Command.from_attr(Command.REBOOT))",
"def analysis_instance_reboot_success(instance_uuid, instance_name, records,\n action=False, guest_hb=False):\n def callback(idx, record):\n record_data = record['data']\n if record_data['type'] == NFV_VIM.INSTANCE_GUEST_SERVICES_NOTIFY:\n if record_data['restart_timeout'] == 0:\n return False\n return True\n\n always = True\n\n possible_records \\\n = [(action, NFV_VIM.INSTANCE_NFVI_ACTION_START),\n (always, NFV_VIM.INSTANCE_REBOOT_STATE),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_VOTE),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_VOTE_CALLBACK),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_VOTE_RESULT),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_PRE_NOTIFY),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_PRE_NOTIFY_CALLBACK),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_DISABLE),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_DISABLE_CALLBACK),\n (always, NFV_VIM.INSTANCE_REBOOT_CALLBACK),\n (always, NFV_VIM.INSTANCE_REBOOT_STATE_COMPLETED),\n (always, NFV_VIM.INSTANCE_INITIAL_STATE),\n (guest_hb, NFV_VIM.INSTANCE_GUEST_SERVICES_NOTIFY)]\n\n expected_records = list()\n for allowed, data_type in possible_records:\n if allowed:\n expected_records.append(data_type)\n\n return _analysis_instances_success(instance_uuid, instance_name, records,\n expected_records, action_types=['reboot'],\n callback=callback)",
"def wait_for_instances_to_stop(conn, instance_ids, pending_ids):\n reservations = conn.get_all_instances(instance_ids=pending_ids)\n for reservation in reservations:\n for instance in reservation.instances:\n print \"State: \" + instance.state\n if instance.state == 'terminated':\n print \"instance `{\" + instance.id + \"}` terminated!\"\n pending_ids.pop(pending_ids.index(instance.id))\n else:\n print \"instance `{\" + instance.id + \"}` stopping...\"\n if len(pending_ids) == 0:\n print \"all instances terminated!\"\n else:\n time.sleep(10)\n wait_for_instances_to_stop(conn, instance_ids, pending_ids)",
"async def failure_handler(self, instances):\n log.debug(\n \"The following '%s' instances are failing: %s\",\n self.config['service'], instances\n )\n\n # Select eligible rescuers\n ntw = self.raft.network\n rescuers = [ipv4 for ipv4, uid in ntw.items() if uid not in instances]\n\n # Iterate over all failing instances\n for ifrom in instances:\n\n # Fetch the list of workflows for a given failing instance.\n index = self.memory.key(ifrom, 'workflows', 'instances')\n for wflow in await self.memory.store.smembers(index):\n wflow = wflow.decode('utf-8')\n\n # Get the report shared by the failing instance\n try:\n report = await self.read_report(wflow, ifrom)\n except KeyError:\n log.error(\"Workflow %s memory has been wiped out\", wflow)\n break\n\n shuffle(rescuers)\n report = json.dumps(report, default=serialize_object)\n\n # Send a failover request to a valid, not failing, instance.\n for ito in rescuers:\n request = {\n 'url': 'http://{}:{}/v1/workflow/instances'.format(\n ito, self.api._port\n ),\n 'headers': {'Content-Type': 'application/json'},\n 'data': report\n }\n async with aiohttp.ClientSession() as session:\n async with session.put(**request) as resp:\n if resp.status == 200:\n # `ito` rescuer has taken over the workflow\n break\n else:\n log.error(\"Workflow %s hasn't be rescued properly\", wflow)\n continue\n asyncio.ensure_future(self.clear_report(wflow, ifrom=ifrom))",
"def reboot(request, server_ids, server_id):\n try:\n if int(server_id) not in server_ids:\n raise Exception(\"Forbidden: specified Server does not belong to specified Service.\")\n\n server = Server.objects.get(pk=server_id)\n result = solus.rebootVirtualServer(server.sid)\n\n if \"status\" in result and result[\"status\"] == \"success\": \n ActionLogger().log(request.user, \"modified\", \"Reboot\", \"vServer %s\" % server.sid)\n return format_ajax_response(True, \"Server rebooted successfully.\")\n else:\n raise Exception(\"Solusvm library call to rebootVirtualServer(%s) returned False.\" % server.sid)\n except Exception as ex:\n logger.error(\"Failed to reboot: %s\" % ex)\n return format_ajax_response(False, \"There was an error rebooting the server.\")",
"def terminate_instance(instance_id):\n\n client = boto3.client('ec2')\n response = client.terminate_instances(InstanceIds=instance_id)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Registers an AMI. When you're creating an AMI, this is the final step you must complete before you can launch an instance from the AMI. For more information about creating AMIs, see Creating Your Own AMIs in the Amazon Elastic Compute Cloud User Guide . You can also use RegisterImage to create an Amazon EBSbacked Linux AMI from a snapshot of a root device volume. You specify the snapshot using the block device mapping. For more information, see Launching a Linux Instance from a Backup in the Amazon Elastic Compute Cloud User Guide . You can't register an image where a secondary (nonroot) snapshot has AWS Marketplace product codes. Some Linux distributions, such as Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code associated with an AMI to verify the subscription status for package updates. Creating an AMI from an EBS snapshot does not maintain this billing code, and subsequent instances launched from such an AMI will not be able to connect to package update infrastructure. To create an AMI that must retain billing codes, see CreateImage . If needed, you can deregister an AMI at any time. Any modifications you make to an AMI backed by an instance store volume invalidates its registration. If you make changes to an image, deregister the previous image and register the new image.
|
def register_image(DryRun=None, ImageLocation=None, Name=None, Description=None, Architecture=None, KernelId=None, RamdiskId=None, BillingProducts=None, RootDeviceName=None, BlockDeviceMappings=None, VirtualizationType=None, SriovNetSupport=None, EnaSupport=None):
pass
|
[
"def create_ami(self,instance_id,instance_name):\n #instance_name = conn.get_instance_attribute(instance_id, 'name')\n\n root_device = '/dev/sda1'\n\n block_map = self.block_device_map_for_instance(instance_id) # all the action starts here\n #description for daily\n if options.daily:\n b=(time.strftime('%A %d %b'))\n c=instance_id\n AMI_description = \"{} {} {}\".format('daily', b, c)\n\n #description for weekly\n if options.weekly:\n b=(datetime.now().strftime('%U'))\n c=instance_id\n AMI_description = \"{} {} {}\".format('weekly', b, c)\n\n #description for monthly\n if options.monthly:\n b=(datetime.now().strftime('%B %Y'))\n c=instance_id\n AMI_description = \"{} {} {}\".format('monthly', b, c)\n\n logger.info(\"AMI-Name [%s] AMI-Description [%s]\" % (AMI_description, AMI_description))\n\n instkernel = self.get_instance_kernel(instance_id)\n\n image_id = conn.register_image(name=AMI_description, description=AMI_description, root_device_name=root_device, block_device_map=block_map, architecture='x86_64', kernel_id=instkernel)\n logger.info(\"AMI Registered Successfully with AMI-ID [%s]\" % (image_id))\n\n #we sleep a little to be sure that the next query for the ami-id will return successfully - we got some errors that AMI-ID is not found, even it was successfully created...\n time.sleep(5)\n\n images = conn.get_all_images(image_ids=[image_id]) # get again the image id as object, because the first is string and is not valid for add_tag...\n for image in images:\n if instance_name != '':\n image.add_tag('Name', instance_name)\n else:\n image.add_tag('Name', instance_id)\n return image_id",
"def register(self, context, image_location):\n image_id = utils.generate_uid('ami')\n self._conn(context).make_request(\n method='PUT',\n bucket='_images',\n query_args=self._qs({'image_location': image_location,\n 'image_id': image_id}))\n return image_id",
"def AMI_builder(\n AWS_access_key_id,\n AWS_secret_access_key,\n region_name,\n base_image_id,\n os,\n security_group_id,\n AMI_name,\n RPM_package_version,\n APT_OSS_version,\n):\n try:\n instance = Instance(\n AWS_access_key_id=AWS_access_key_id,\n AWS_secret_access_key=AWS_secret_access_key,\n region_name=region_name,\n base_image_id=base_image_id,\n os=os, # ubuntu, amazonLinux\n security_group_id=security_group_id,\n AMI_name=AMI_name,\n RPM_package_version=RPM_package_version,\n APT_OSS_version=APT_OSS_version,\n )\n except Exception as err:\n logging.error(\"Could not bring up the instance. \" + str(err))\n sys.exit(-1)\n AMI_id = \"\"\n installation_failed = False\n try:\n instance.wait_until_ready()\n except Exception as err:\n logging.error(\n \"Could not bring the instance to ready state. \" + str(err))\n installation_failed = True\n else:\n try:\n instance.install_ODFE()\n AMI_id = instance.create_AMI()\n except Exception as err:\n installation_failed = True\n logging.error(\n \"AMI creation failed there was an error see the logs. \" + str(err))\n finally:\n try:\n instance.cleanup_instance()\n except Exception as err:\n logging.error(\n \"Could not cleanup the instance. There could be an instance currently running, terminate it. \" + str(err))\n installation_failed = True\n if installation_failed:\n sys.exit(-1)\n # copy the AMI to the required regions\n ec2_client = boto3.client(\n \"ec2\",\n aws_access_key_id=AWS_access_key_id,\n aws_secret_access_key=AWS_secret_access_key,\n region_name=region_name,\n )\n AMI_copy_regions = [region[\"RegionName\"]\n for region in ec2_client.describe_regions()[\"Regions\"]]\n AMI_copy_regions.remove(region_name) # since AMI is created here\n copy_AMI_to_regions(\n AWS_access_key_id=AWS_access_key_id,\n AWS_secret_access_key=AWS_secret_access_key,\n AMI_id=AMI_id,\n AMI_name=AMI_name,\n AMI_source_region=region_name,\n AMI_copy_regions=AMI_copy_regions,\n )",
"def create_instance_with_ami(conn, ami):\n\n # Start an instance with the desired ami, in this case I decided to hard code the type to a free tier machine\n conn.run_instances(ami, key_name=config.get('Credentials', 'key_name'), instance_type=\"t2.micro\")",
"def ex_register_image(self, name, description=None, architecture=None,\r\n root_device_name=None, block_device_mapping=None):\r\n return super(OutscaleNodeDriver, self).ex_register_image(\r\n name, description=description, architecture=architecture,\r\n root_device_name=root_device_name,\r\n block_device_mapping=block_device_mapping)",
"def start_ami(ami, key_name=DefaultKeypair, instance_type='m1.large',\r\n user_data=None):\r\n\r\n access_key = os.environ['EC2_ACCESS_KEY']\r\n secret_key = os.environ['EC2_SECRET_ACCESS_KEY']\r\n ec2 = boto.connect_ec2(access_key, secret_key)\r\n access_key = 'DEADBEEF'\r\n secret_key = 'DEADBEEF'\r\n del access_key, secret_key\r\n\r\n if user_data is None:\r\n user_data = ''\r\n\r\n reservation = ec2.run_instances(image_id=ami, key_name=key_name,\r\n instance_type=instance_type,\r\n user_data=user_data)\r\n # got some sort of race - \"instance not found\"? - try waiting a bit\r\n time.sleep(1)\r\n\r\n # Wait a minute or two while it boots\r\n instance = reservation.instances[0]\r\n while True:\r\n instance.update()\r\n if instance.state == 'running':\r\n break\r\n time.sleep(1)\r\n\r\n return instance",
"def register_image(self):\n logging.info('Registering image \\'' + self.name + '\\'')\n\n # Add creation date to image attributes, it is the date of image registering (current date)\n self.image_class = self.__class__.__name__\n self.creation_date = datetime.today().strftime('%Y-%m-%d')\n\n file_content = 'image_data:\\n '\n\n # For all image attributes\n for attribute, value in self.__dict__.items():\n # Register attribute\n file_content = file_content + '\\n ' + attribute + ': ' + str(value)\n\n # Creating or edit the image_data file that contains image attributes in yaml\n logging.debug('Writing image attributs inside ' + self.IMAGE_DIRECTORY + 'image_data.yml')\n with open(self.IMAGE_DIRECTORY + '/image_data.yml', \"w\") as ff:\n ff.write(file_content)",
"def create_image(self, **kw):\n cmd = \"rbd create \" + kw.get(\"image_name\") + \" -s 1G\"\n if kw.get(\"features\"):\n cmd = cmd + \" --image-feature \" + kw[\"features\"]\n self.exec_cmd(cmd)",
"def _execute_img_registration(self, item):\n logging.debug('.. execute image registration as command line')\n path_dir_reg = self._get_path_reg_dir(item)\n\n commands = self._generate_regist_command(item)\n # in case it is just one command\n if not isinstance(commands, (list, tuple)):\n commands = [commands]\n\n path_log = os.path.join(path_dir_reg, self.NAME_LOG_REGISTRATION)\n # TODO, add lock to single thread, create pool with possible thread ids\n # (USE taskset [native], numactl [need install])\n if not isinstance(commands, (list, tuple)):\n commands = [commands]\n # measure execution time\n cmd_result = exec_commands(commands, path_log, timeout=self.EXECUTE_TIMEOUT)\n # if the experiment failed, return back None\n if not cmd_result:\n item = None\n return item",
"def startinstance(imagename, instance_type='m1.large'):\n if not settings.get_image(imagename):\n raise SystemExit(\"Invalid imagename '%s'\" % imagename)\n\n username, conn = _getbotoconn(auth_user)\n\n print \"starting an instance from the %s image under the %s account of \" \\\n \"type %s\" % \\\n (imagename, username, instance_type)\n\n username, accesskey, secretkey, pkname = settings.get_user(username)\n imagename, imageid = settings.get_image(imagename)\n\n image = conn.get_image(imageid)\n reservation = None\n if pkname:\n reservation = image.run(instance_type=instance_type, key_name=pkname)\n else:\n reservation = image.run(instance_type=instance_type)\n\n instance = reservation.instances[0]\n\n # The image has been started in the pending state, wait for it to transition\n # into the running state\n while True:\n if instance.update() == u'running':\n # [AN] it would be nice if the user knew it was still working\n break\n time.sleep(1)\n\n print \"\"\n print \"Instance started\"\n print \"DNS name: %s\" % instance.dns_name",
"def push(self, image, registry=None, server=None):\n if registry:\n raw_image_name = image.split(\"/\")[1]\n new_image = \"%s/%s\" % (registry, raw_image_name)\n tag = self.docker + ' ' + self.tag_cmd + ' ' + image + ' ' + new_image\n logging.warning(tag)\n self._execute_cmd(tag, server, read_output=False)\n else:\n new_image = image\n push = self.docker + ' ' + self.push_cmd + ' ' + new_image\n logging.warning(push)\n child = self._execute_cmd(push, server, read_output=False)\n return self._continuous_print(child, \"uploading image...\")",
"def register_baremetal(self):\n try:\n req_data = self.data[api.DATA]\n baremetal_data = self._get_baremetal_data(req_data)\n self.eon_client.add_resource(baremetal_data)\n self.response[api.DATA] = self._(\n \"Baremetal registered successfully\")\n self.response.complete()\n except Exception as e:\n self.response.error(e.details)",
"def test_ami_exists(self) -> None:\n owner = self.sts.get_caller_identity().get('Account')\n amis = self.ec2.describe_images(\n Owners=[owner],\n Filters=[{\n 'Name': 'name',\n 'Values': ['global-jenkins-server*']\n }]\n )\n self.assertTrue(len(amis.get('Images')) > 0)",
"def AddImageArg(parser, required=True, image='gcr.io/cloudrun/hello:latest'):\n parser.add_argument(\n '--image',\n required=required,\n help='Name of the container image to deploy (e.g. `{image}`).'.format(\n image=image\n ),\n )",
"def makeInstanceFromImage(self , imageid , initialconfig, instancename):\n chars = string.letters + string.digits\n length = 8\n createdata = \"name \" + instancename + \"\\n\" + \"cpu 1000\"+\"\\n\"+\"persistent true\"+\"\\n\"+\"password \"+(''.join(sample(chars,length)))+\"\\nmem 1024\"+\\\n \"\\nide:0:0 disk\"+\"\\nboot ide:0:0\"+\"\\nide:0:0 \"+imageid+\"\\nnic:0:model e1000\"+\"\\nnic:0:dhcp auto\"+\"\\nvnc auto\"+\"\\nsmp auto\";\n\n response = self.__EH.post(self.__hostname+\"/servers/create/stopped\" , data=createdata)\n if response.status_code != 200:\n logging.warning(\"!Unexpected status code returned by the ElasticHosts request: \" + str(response) + \" \" + str(response.text))\n logging.warning(\"Headers: %s \\n\" , str(response.request.headers) )\n response.raise_for_status()\n instanceid = response.json()[u'server']\n logging.info(\">>>>>>>>>>> New server \" + instancename + \"(\"+ instanceid +\") created\");\n return EHInstance.EHInstance(instanceid, self.__EH, self.__hostname)",
"def register(self):\n with VirtualBoxException.ExceptionHandler():\n self._vbox.registerMachine(self.getIMachine())",
"def test_create_image_tag(self):\n image = self._create_image()\n\n with self.override_role():\n self.image_client.add_image_tag(\n image['id'],\n data_utils.rand_name(self.__class__.__name__ + '-tag'))",
"def register_pi():\n global video_village_pi_id\n result = requests.post(VILLAGE_REGISTER_ENDPOINT,\n headers=VILLAGE_REQUEST_HEADERS,\n json={'mac_address': PI_HARDWARE_ADDRESS})\n if result.status_code == 200:\n registration_info = result.json()\n video_village_pi_id = registration_info.get('id')\n return True\n\n return False",
"def create_new_image(self):\n logging.info('Starting image \\'' + self.name + '\\' creation')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Rejects a VPC peering connection request. The VPC peering connection must be in the pendingacceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection .
|
def reject_vpc_peering_connection(DryRun=None, VpcPeeringConnectionId=None):
pass
|
[
"def reject_private_endpoint_connection(client, resource_group_name, account_name, private_endpoint_connection_name,\n description=None):\n\n return _update_private_endpoint_connection_status(\n client, resource_group_name, account_name, private_endpoint_connection_name, is_approved=False,\n description=description\n )",
"def reject(self):\n self.status = self.REJECTED\n self.save(update_fields=['status'])\n friend_request_rejected.send(sender=self.__class__, from_account=self.from_account, to_account=self.to_account)",
"def peering_connection_pending_from_vpc(\n conn_id=None,\n conn_name=None,\n vpc_id=None,\n vpc_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n if not _exactly_one((conn_id, conn_name)):\n raise SaltInvocationError(\n \"Exactly one of conn_id or conn_name must be provided.\"\n )\n\n if not _exactly_one((vpc_id, vpc_name)):\n raise SaltInvocationError(\"Exactly one of vpc_id or vpc_name must be provided.\")\n\n if vpc_name:\n vpc_id = check_vpc(\n vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not vpc_id:\n log.warning(\"Could not resolve VPC name %s to an ID\", vpc_name)\n return False\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n filters = [\n {\"Name\": \"requester-vpc-info.vpc-id\", \"Values\": [vpc_id]},\n {\"Name\": \"status-code\", \"Values\": [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]},\n ]\n if conn_id:\n filters += [{\"Name\": \"vpc-peering-connection-id\", \"Values\": [conn_id]}]\n else:\n filters += [{\"Name\": \"tag:Name\", \"Values\": [conn_name]}]\n\n vpcs = conn.describe_vpc_peering_connections(Filters=filters).get(\n \"VpcPeeringConnections\", []\n )\n\n if not vpcs:\n return False\n elif len(vpcs) > 1:\n raise SaltInvocationError(\n \"Found more than one ID for the VPC peering \"\n \"connection ({}). Please call this function \"\n \"with an ID instead.\".format(conn_id or conn_name)\n )\n else:\n status = vpcs[0][\"Status\"][\"Code\"]\n\n return bool(status == PENDING_ACCEPTANCE)",
"def delete_vpc_peering_connection(\n conn_id=None,\n conn_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n dry_run=False,\n):\n if not _exactly_one((conn_id, conn_name)):\n raise SaltInvocationError(\n \"Exactly one of conn_id or conn_name must be provided.\"\n )\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n if conn_name:\n conn_id = _vpc_peering_conn_id_for_name(conn_name, conn)\n if not conn_id:\n raise SaltInvocationError(\n \"Couldn't resolve VPC peering connection {} to an ID\".format(conn_name)\n )\n try:\n log.debug(\"Trying to delete vpc peering connection\")\n conn.delete_vpc_peering_connection(\n DryRun=dry_run, VpcPeeringConnectionId=conn_id\n )\n return {\"msg\": \"VPC peering connection deleted.\"}\n except botocore.exceptions.ClientError as err:\n e = __utils__[\"boto.get_error\"](err)\n log.error(\"Failed to delete VPC peering %s: %s\", conn_name or conn_id, e)\n return {\"error\": e}",
"def reject_portability_request(portability_request):\n if portability_request.state != PortabilityRequestState.PENDING.value:\n raise PortabilityTransitionException()\n portability_request.state = PortabilityRequestState.REJECTED.value\n portability_request.save(update_fields=(\"state\",))",
"def describe_vpc_peering_connections(DryRun=None, VpcPeeringConnectionIds=None, Filters=None):\n pass",
"def request_vpc_peering_connection(\n requester_vpc_id=None,\n requester_vpc_name=None,\n peer_vpc_id=None,\n peer_vpc_name=None,\n name=None,\n peer_owner_id=None,\n peer_region=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n dry_run=False,\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n\n if name and _vpc_peering_conn_id_for_name(name, conn):\n raise SaltInvocationError(\n \"A VPC peering connection with this name already \"\n \"exists! Please specify a different name.\"\n )\n\n if not _exactly_one((requester_vpc_id, requester_vpc_name)):\n raise SaltInvocationError(\n \"Exactly one of requester_vpc_id or requester_vpc_name is required\"\n )\n if not _exactly_one((peer_vpc_id, peer_vpc_name)):\n raise SaltInvocationError(\n \"Exactly one of peer_vpc_id or peer_vpc_name is required.\"\n )\n\n if requester_vpc_name:\n requester_vpc_id = _get_id(\n vpc_name=requester_vpc_name,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not requester_vpc_id:\n return {\n \"error\": \"Could not resolve VPC name {} to an ID\".format(\n requester_vpc_name\n )\n }\n if peer_vpc_name:\n peer_vpc_id = _get_id(\n vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile\n )\n if not peer_vpc_id:\n return {\n \"error\": \"Could not resolve VPC name {} to an ID\".format(peer_vpc_name)\n }\n\n peering_params = {\n \"VpcId\": requester_vpc_id,\n \"PeerVpcId\": peer_vpc_id,\n \"DryRun\": dry_run,\n }\n\n if peer_owner_id:\n peering_params.update({\"PeerOwnerId\": peer_owner_id})\n if peer_region:\n peering_params.update({\"PeerRegion\": peer_region})\n\n try:\n log.debug(\"Trying to request vpc peering connection\")\n if not peer_owner_id:\n vpc_peering = conn.create_vpc_peering_connection(**peering_params)\n else:\n vpc_peering = conn.create_vpc_peering_connection(**peering_params)\n peering = vpc_peering.get(\"VpcPeeringConnection\", {})\n peering_conn_id = peering.get(\"VpcPeeringConnectionId\", \"ERROR\")\n msg = \"VPC peering {} requested.\".format(peering_conn_id)\n log.debug(msg)\n\n if name:\n log.debug(\"Adding name tag to vpc peering connection\")\n conn.create_tags(\n Resources=[peering_conn_id], Tags=[{\"Key\": \"Name\", \"Value\": name}]\n )\n log.debug(\"Applied name tag to vpc peering connection\")\n msg += \" With name {}.\".format(name)\n\n return {\"msg\": msg}\n except botocore.exceptions.ClientError as err:\n log.error(\"Got an error while trying to request vpc peering\")\n return {\"error\": __utils__[\"boto.get_error\"](err)}",
"def reject_invitation(GraphArn=None):\n pass",
"def answer_rejected(self, reason = REQUEST_REJECTED_FAILED, dst_ip = '0.0.0.0', dst_port = 0):\r\n self.answer(reason, dst_ip, dst_port)",
"def accept_vpc_peering_connection( # pylint: disable=too-many-arguments\n conn_id=\"\", name=\"\", region=None, key=None, keyid=None, profile=None, dry_run=False\n):\n if not _exactly_one((conn_id, name)):\n raise SaltInvocationError(\n \"One (but not both) of vpc_peering_connection_id or name must be provided.\"\n )\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n\n if name:\n conn_id = _vpc_peering_conn_id_for_name(name, conn)\n if not conn_id:\n raise SaltInvocationError(\n \"No ID found for this \"\n \"VPC peering connection! ({}) \"\n \"Please make sure this VPC peering \"\n \"connection exists \"\n \"or invoke this function with \"\n \"a VPC peering connection \"\n \"ID\".format(name)\n )\n try:\n log.debug(\"Trying to accept vpc peering connection\")\n conn.accept_vpc_peering_connection(\n DryRun=dry_run, VpcPeeringConnectionId=conn_id\n )\n return {\"msg\": \"VPC peering connection accepted.\"}\n except botocore.exceptions.ClientError as err:\n log.error(\"Got an error while trying to accept vpc peering\")\n return {\"error\": __utils__[\"boto.get_error\"](err)}",
"def reject(self):\n # print(\"REJECTING REQUEST RN\")\n self.rejected = timezone.now\n # self.save()\n signals.follow_request_rejected.send(sender=self)\n self.delete()",
"def is_peering_connection_pending(\n conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None\n):\n if not _exactly_one((conn_id, conn_name)):\n raise SaltInvocationError(\n \"Exactly one of conn_id or conn_name must be provided.\"\n )\n\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n\n if conn_id:\n vpcs = conn.describe_vpc_peering_connections(\n VpcPeeringConnectionIds=[conn_id]\n ).get(\"VpcPeeringConnections\", [])\n else:\n filters = [\n {\"Name\": \"tag:Name\", \"Values\": [conn_name]},\n {\n \"Name\": \"status-code\",\n \"Values\": [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING],\n },\n ]\n vpcs = conn.describe_vpc_peering_connections(Filters=filters).get(\n \"VpcPeeringConnections\", []\n )\n\n if not vpcs:\n return False\n elif len(vpcs) > 1:\n raise SaltInvocationError(\n \"Found more than one ID for the VPC peering \"\n \"connection ({}). Please call this function \"\n \"with an ID instead.\".format(conn_id or conn_name)\n )\n else:\n status = vpcs[0][\"Status\"][\"Code\"]\n\n return status == PENDING_ACCEPTANCE",
"def reject_selected_request(self):\n self.click_on_element_by_css(adpl.REJECT_REQUEST_BUTTON)\n self.find_element_by_css(adpl.SUCCESSFUL_ALERT)",
"def RejectAttachCcnInstances(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"RejectAttachCcnInstances\", params, headers=headers)\n response = json.loads(body)\n model = models.RejectAttachCcnInstancesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def reject(self, invitation_id, invitation_secret):\n cmd = {\n \"type\": \"biz_reject_invitation\",\n \"uuid\": self.api.generate_uuid(),\n \"args\": {\n \"invitation_id\": invitation_id,\n \"invitation_secret\": invitation_secret,\n },\n }\n self.queue.append(cmd)",
"def describe_vpc_peering_connection(\n name, region=None, key=None, keyid=None, profile=None\n):\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n return {\"VPC-Peerings\": _get_peering_connection_ids(name, conn)}",
"def delete_vpc_endpoint_resources():\n print('Deleting VPC endpoints')\n ec2 = boto3.client('ec2')\n endpoint_ids = []\n for endpoint in ec2.describe_vpc_endpoints()['VpcEndpoints']:\n print('Deleting VPC Endpoint - {}'.format(endpoint['ServiceName']))\n endpoint_ids.append(endpoint['VpcEndpointId'])\n\n if endpoint_ids:\n ec2.delete_vpc_endpoints(\n VpcEndpointIds=endpoint_ids\n )\n\n print('Waiting for VPC endpoints to get deleted')\n while ec2.describe_vpc_endpoints()['VpcEndpoints']:\n time.sleep(5)\n\n print('VPC endpoints deleted')\n\n # VPC endpoints connections\n print('Deleting VPC endpoint connections')\n service_ids = []\n for connection in ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n service_id = connection['ServiceId']\n state = connection['VpcEndpointState']\n\n if state in ['PendingAcceptance', 'Pending', 'Available', 'Rejected', 'Failed', 'Expired']:\n print('Deleting VPC Endpoint Service - {}'.format(service_id))\n service_ids.append(service_id)\n\n ec2.reject_vpc_endpoint_connections(\n ServiceId=service_id,\n VpcEndpointIds=[\n connection['VpcEndpointId'],\n ]\n )\n\n if service_ids:\n ec2.delete_vpc_endpoint_service_configurations(\n ServiceIds=service_ids\n )\n\n print('Waiting for VPC endpoint services to be destroyed')\n while ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n time.sleep(5)\n\n print('VPC endpoint connections deleted')",
"def refused(self, peer, query):\n self.checkstat(\"refused\")",
"def clean_conn_peer(self):\n # Remove closed connection\n for connection in connections:\n if '[closed]' in str(connection):\n # connections.remove(connection)\n\n # Remove peer\n remove_peer_ip = '@{}'.format(connection[1][0])\n remove_peer_port = '/{}'.format(connection[1][1])\n for peer in peers_online:\n if str(remove_peer_ip) and str(remove_peer_port) in str(peer):\n peers_online.remove(peer)\n print('Peer disconnected: {}'.format(peer))\n time.sleep(0.8)\n\n # TASK 3: Broadcast peers\n # Send updated peers list to all peers\n self.broadcast_peers()",
"async def reject_users_proposals(next_id, request):\n # Get all open proposals associated with the user\n conn = await create_connection()\n proposals = await proposals_query.fetch_open_proposals_by_user(conn, next_id)\n conn.close()\n\n # Update to rejected:\n txn_key, txn_user_id = await get_transactor_key(request=request)\n for proposal in proposals:\n if proposal[\"opener\"] == next_id:\n reason = \"Opener was deleted\"\n else:\n reason = \"Assigned Appover was deleted.\"\n\n batch_list = PROPOSAL_TRANSACTION[proposal[\"proposal_type\"]][\n \"REJECTED\"\n ].batch_list(\n signer_keypair=txn_key,\n signer_user_id=txn_user_id,\n proposal_id=proposal[\"proposal_id\"],\n object_id=proposal[\"object_id\"],\n related_id=proposal[\"related_id\"],\n reason=reason,\n )\n await send(request.app.config.VAL_CONN, batch_list, request.app.config.TIMEOUT)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
When you no longer want to use an OnDemand Dedicated Host it can be released. OnDemand billing is stopped and the host goes into released state. The host ID of Dedicated Hosts that have been released can no longer be specified in another request, e.g., ModifyHosts. You must stop or terminate all instances on a host before it can be released. When Dedicated Hosts are released, it make take some time for them to stop counting toward your limit and you may receive capacity errors when trying to allocate new Dedicated hosts. Try waiting a few minutes, and then try again. Released hosts will still appear in a DescribeHosts response.
|
def release_hosts(HostIds=None):
pass
|
[
"def deactivate_host_if_up(host, host_resource=None):\n if not ll_hosts.is_host_in_maintenance(positive=True, host=host):\n return ll_hosts.deactivate_host(\n positive=True, host=host, host_resource=host_resource\n )\n return True",
"def cleanup_hosts(context):\n host1_name = context.testbed.config['ESX_HOST1']\n host2_name = context.testbed.config['ESX_HOST2']\n names = set([host1_name, host2_name])\n\n host_summaries = context.client.vcenter.Host.list(\n Host.FilterSpec(names=names))\n print('Found {} Hosts matching names {}'.\n format(len(host_summaries), ', '.\n join([\"'{}'\".format(n) for n in names])))\n\n for host_summary in host_summaries:\n host = host_summary.host\n print(\"Deleting Host '{}' ({})\".format(host_summary.name, host))\n context.client.vcenter.Host.delete(host)",
"def host_delete(context, host_name, session=None):\n if session is None:\n session = nova_db_sa_api.get_session()\n with session.begin(subtransactions=True):\n nwkasn_list = network_association_find_all(context, host_name,\n session=session)\n for nwkasn in nwkasn_list:\n nwkasn.delete(context, session=session)\n # Delete dependents before host: VioServers\n vios_list = vio_server_find_all(context, host_name, session=session)\n for vios in vios_list:\n vios.delete(context, session=session)\n # Also need to clean up the entry in the HMC Hosts DB Table\n hmc_query = model_query(\n context, pvc_models.HmcHostsDTO, session=session)\n hmc_query = hmc_query.filter_by(host_name=host_name)\n hmc_query.soft_delete(synchronize_session=False)\n # Need to query the Service based on the Host to know what to delete\n query = model_query(context, nova_db_sa_models.Service,\n session=session)\n svc = query.filter_by(host=host_name).filter_by(topic='compute').\\\n first()\n # If the Service did exist, then we will delete it from the Database\n if svc is not None:\n query = model_query(\n context, nova_db_sa_models.ComputeNode, session=session)\n compute_node = query.filter_by(service_id=svc.id).first()\n # If the Compute Node exists, then we will delete it from the DB\n if compute_node is not None:\n nova_db_api.compute_node_delete(context, compute_node.id)\n # Clean up the Service and Compute Host entries from the Database\n nova_db_api.service_destroy(context, svc.id)",
"def deregister(host_id):\n host_id = string.join([_host_prefix(), host_id], '/')\n api = _conjur_api()\n api.layer(_client_layer_id()).remove_host(host_id)",
"def purchase_host_reservation(OfferingId=None, HostIdSet=None, LimitPrice=None, CurrencyCode=None, ClientToken=None):\n pass",
"def deletehost(hostid):\n\n\t#print \"hostid to delete\",hostid\n obj3 = {\"jsonrpc\": \"2.0\",\"method\": \"host.delete\",\"params\": hostid,\"auth\": hash_pass,\"id\": 2}\n data3 = json.dumps(obj3)\n request3 = urllib2.Request(url, data3, {'Content-Type': 'application/json'})\n response3 = urllib2.urlopen(request3)\n res3 = json.load(response3)",
"def makeHostExpired(self, name):\n host = (name, )\n self.cursor.execute(\"UPDATE hosts SET status = 3 WHERE name=?\", host)\n self.database.commit()",
"def hmc_host_delete(context, host_name, session=None):\n # If we weren't given a session, then we need to create a new one\n if not session:\n session = nova_db_sa_api.get_session()\n # Create a Transaction around the delete in the Database\n with session.begin():\n query = model_query(\n context, pvc_models.HmcHostsDTO, session=session)\n query = query.filter_by(host_name=host_name)\n query.soft_delete(synchronize_session=False)",
"def __host_down(host):\n\n ping = [\"ping\", \"-c\", \"1\", host]\n output = subprocess.Popen(\n ping, stdout = subprocess.PIPE).communicate()[0]\n\n if \"Unreachable\" in output:\n return True\n\n return False",
"def remove_computehost(self, pool, hosts):\n\n if not isinstance(hosts, list):\n hosts = [hosts]\n\n agg = self.get_aggregate_from_name_or_id(pool)\n\n try:\n freepool_agg = self.get(self.freepool_name)\n except manager_exceptions.AggregateNotFound:\n raise manager_exceptions.NoFreePool()\n\n hosts_failing_to_remove = []\n hosts_failing_to_add = []\n hosts_not_in_freepool = []\n for host in hosts:\n if freepool_agg.id == agg.id:\n if host not in freepool_agg.hosts:\n hosts_not_in_freepool.append(host)\n continue\n try:\n self.nova.aggregates.remove_host(agg.id, host)\n except nova_exceptions.ClientException:\n hosts_failing_to_remove.append(host)\n if freepool_agg.id != agg.id:\n # NOTE(sbauza) : We don't want to put again the host in\n # freepool if the requested pool is the freepool...\n try:\n self.nova.aggregates.add_host(freepool_agg.id, host)\n except nova_exceptions.ClientException:\n hosts_failing_to_add.append(host)\n\n if hosts_failing_to_remove:\n raise manager_exceptions.CantRemoveHost(\n host=hosts_failing_to_remove, pool=agg)\n if hosts_failing_to_add:\n raise manager_exceptions.CantAddHost(host=hosts_failing_to_add,\n pool=freepool_agg)\n if hosts_not_in_freepool:\n raise manager_exceptions.HostNotInFreePool(\n host=hosts_not_in_freepool, freepool_name=freepool_agg.name)",
"def delete(self, *args, **kwargs):\n if self.virtual_machines.all():\n children = [vm.hostname for vm in self.virtual_machines.all()]\n raise RuntimeError('cannot delete host until its VMs have been reassigned: {}'.format(children))\n super(Host, self).delete(*args, **kwargs)",
"def delete_ehost(self, name):\n return self.execution_host_manager.delete_object(name)",
"def test_remotehosts_id_delete(self):\n pass",
"def _ensure_sufficient_hosts(\n self, context, hosts, required_count, claimed_uuids=None,\n ):\n if len(hosts) == required_count:\n # We have enough hosts.\n return\n\n if claimed_uuids:\n self._cleanup_allocations(context, claimed_uuids)\n\n # NOTE(Rui Chen): If multiple creates failed, set the updated time\n # of selected HostState to None so that these HostStates are\n # refreshed according to database in next schedule, and release\n # the resource consumed by instance in the process of selecting\n # host.\n for host in hosts:\n host.updated = None\n\n # Log the details but don't put those into the reason since\n # we don't want to give away too much information about our\n # actual environment.\n LOG.debug(\n 'There are %(hosts)d hosts available but '\n '%(required_count)d instances requested to build.',\n {'hosts': len(hosts), 'required_count': required_count})\n reason = _('There are not enough hosts available.')\n raise exception.NoValidHost(reason=reason)",
"def remove_available_server(self, host_ip):\n\t\tself.swarm_manager.remove_available_server(host_ip)",
"def delete_hosts(ec2_conn, ipa_client, hostnames):\n for hostname in hostnames:\n _LOGGER.debug('Unenroll host from IPA: %s', hostname)\n try:\n ipa_client.unenroll_host(hostname=hostname)\n except (KeyError, ipaclient.NotFoundError):\n _LOGGER.debug('Host not found: %s', hostname)\n\n _LOGGER.debug('Delete instances: %r', hostnames)\n while hostnames:\n batch = hostnames[:_EC2_DELETE_BATCH]\n hostnames = hostnames[_EC2_DELETE_BATCH:]\n ec2client.delete_instances(ec2_conn=ec2_conn, hostnames=batch)",
"def hosting_devices_removed(self, context, hosting_data, deconfigure,\n host):\n if hosting_data:\n self._host_notification(context, 'hosting_devices_removed',\n {'hosting_data': hosting_data,\n 'deconfigure': deconfigure}, host)",
"def _hmc_update_hosts(context, hmc_uuid, hosts, session):\n # If we weren't given any Hosts, then there is nothing to do\n if hosts is None:\n return\n # Query the list of Host that are associated with this HMC\n db_hosts = _hmc_get_hosts(context, hmc_uuid, session)\n # For each Host provided that doesn't exist, add it to the database\n for host in hosts:\n if host not in db_hosts:\n hmchosts_ref = pvc_models.HmcHostsDTO()\n hmchosts_ref.update(dict(hmc_uuid=hmc_uuid, host_name=host))\n hmchosts_ref.save(session=session)\n # For each Host that is in the DB but not provided, remove from database\n for db_host in db_hosts:\n if db_host not in hosts:\n query = model_query(\n context, pvc_models.HmcHostsDTO, session=session)\n query = query.filter_by(hmc_uuid=hmc_uuid, host_name=db_host)\n query.soft_delete(synchronize_session=False)",
"def _remove_addresses_for_host(self, host):\n hostname = host.hostname\n self._remove_address(hostname, constants.NETWORK_TYPE_MGMT)\n self._remove_address(hostname, constants.NETWORK_TYPE_CLUSTER_HOST)\n self._remove_leases_by_mac_address(host.mgmt_mac)\n self._generate_dnsmasq_hosts_file(deleted_host=host)",
"def recover_host(self, host: str) -> None:\n self.failed_hosts.discard(host)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Replaces an IAM instance profile for the specified running instance. You can use this action to change the IAM instance profile that's associated with an instance without having to disassociate the existing IAM instance profile first. Use DescribeIamInstanceProfileAssociations to get the association ID.
|
def replace_iam_instance_profile_association(IamInstanceProfile=None, AssociationId=None):
pass
|
[
"def update_policy_profile(self, profile, body=None):\n return self._put(self.policy_profile_path % (profile), body=body)",
"def delete_profile(self):\n response = self.client.delete_instance_profile(\n InstanceProfileName=self.ProfileName\n )",
"def update(self, profile_id, profile, etag):\n\n response = self._session.put(\n path=self._session.urljoin(self.RESOURCE_PATH, profile_id).format(\n base_api=self.base_api\n ),\n headers={\n 'Accept': self._accept_header(),\n 'Content-Type': 'application/json',\n 'If-Match': etag,\n },\n data=json.dumps(profile),\n )\n\n etag = response.headers['ETag']\n return ElasticAgentProfile(session=self._session, data=response.json(), etag=etag)",
"def rename_profile(self, new_name, profile=None):\n # get the current Profile object\n if profile is None:\n profile = self.profile\n elif isinstance(profile, str):\n profile = self._profileman[profile]\n\n self.LOGGER << f\"Renaming profile: {profile.name!r}->{new_name!r}\"\n self._profileman.rename_profile(profile, new_name)\n\n if profile is self.profile:\n self._configman.update_genvalue(ks_ini.LAST_PROFILE,\n profile.name)",
"def update_profile(self, new_profile):\n url = f'{self._okta.api}/users/{self.id}'\n response = self._okta.session.post(url, data=json.dumps(new_profile))\n if not response.ok:\n self._logger.error(response.text)\n return response.ok",
"def _init_instance_profile(self):\n iam_client = self._session.client('iam')\n\n # Create instance profile\n instance_profile_name = 'AccelizeLoadFPGA'\n with _ExceptionHandler.catch(filter_error_codes='EntityAlreadyExists'):\n iam_client.create_instance_profile(\n InstanceProfileName=instance_profile_name)\n\n _get_logger().info(\n _utl.gen_msg('created_object', 'instance profile',\n instance_profile_name))\n\n _time.sleep(5)\n\n # Attach role to instance profile\n with _ExceptionHandler.catch(filter_error_codes='LimitExceeded'):\n iam_client.add_role_to_instance_profile(\n InstanceProfileName=instance_profile_name, RoleName=self._role)\n\n _get_logger().info(\n _utl.gen_msg('attached_to', 'role', self._role,\n 'instance profile', instance_profile_name))",
"def iam_instance_profile(self) -> pulumi.Output[Optional['outputs.LaunchTemplateIamInstanceProfile']]:\n return pulumi.get(self, \"iam_instance_profile\")",
"def iam_instance_profile(self) -> Optional[pulumi.Input['LaunchTemplateIamInstanceProfileArgs']]:\n return pulumi.get(self, \"iam_instance_profile\")",
"def edit_profile(self, profile, opts):\n self._configure_profile(profile.name, opts)\n \n if profile == self.config.current_profile:\n self._configure_connection(profile)",
"def create_iam_instance_profile(iam):\n try:\n inst_profile = iam.create_instance_profile(InstanceProfileName=instance_data['role'])\n usr_log(f'IAM: Created Instance Profile: {inst_profile}', 'info')\n return inst_profile\n except Exception as error:\n usr_log(f'IAM: Error creating instance profile: {error}', 'error')\n return None",
"def update_profile(client: testclient.TestClient, _id: uuid.UUID, updated_profile: dict) -> Response:\n pass",
"def find_profile(iam, profile_name):\n\n profile = None\n try:\n response = iam.get_instance_profile(\n InstanceProfileName=profile_name,\n )\n profile = response['InstanceProfile']\n\n except ClientError as e:\n if e.response['Error']['Code'] != 'NoSuchEntity':\n raise\n\n return profile",
"def erasure_code_profile_update(self, *args, **kwargs):\n banner(\"PCC.Update Erasure Code Profile\")\n self._load_kwargs(kwargs)\n\n payload = {\n \"id\":int(self.Id),\n \"name\":self.Name,\n \"directory\":self.Directory,\n \"plugin\":self.Plugin,\n \"stripeUnit\":self.StripeUnit,\n \"crushFailureDomain\":self.CrushFailureDomain,\n \"dataChunks\":int(self.DataChunks),\n \"codingChunks\":int(self.CodingChunks),\n \"cephClusterId\":int(self.CephClusterId)\n }\n\n conn = BuiltIn().get_variable_value(\"${PCC_CONN}\")\n return pcc.modify_erasure_code_profile(conn, data=payload)",
"def update_application_profile(self, profile_name, pki_profile_ref,\n tenant_ref, name, avi_config, sysdict):\n\n try:\n if profile_name:\n app_profile = [p for p in (sysdict['ApplicationProfile'] +\n avi_config['ApplicationProfile']) if\n p['name'] ==\n profile_name]\n if app_profile:\n app_profile[0][\"http_profile\"]['pki_profile_ref'] = \\\n pki_profile_ref\n LOG.debug('Added PKI profile to application profile '\n 'successfully : %s' % (\n profile_name, pki_profile_ref))\n else:\n app_profile = dict()\n app_profile['name'] = name + '-%s-%s' % (\n random.randrange(0, 1000),\n ns_constants.PLACE_HOLDER_STR)\n app_profile['tenant_ref'] = tenant_ref\n app_profile['type'] = 'APPLICATION_PROFILE_TYPE_HTTP'\n http_profile = dict()\n http_profile['connection_multiplexing_enabled'] = False\n http_profile['xff_enabled'] = False\n # TODO: clientIpHdrExpr conversion to xff_alternate_name\n http_profile['websockets_enabled'] = False\n http_profile['pki_profile_ref'] = pki_profile_ref\n app_profile[\"http_profile\"] = http_profile\n avi_config['ApplicationProfile'].append(app_profile)\n LOG.debug(\n \"Conversion completed successfully for httpProfile: %s\" %\n app_profile['name'])\n return app_profile['name']\n except:\n update_count('error')\n LOG.error(\"Error in convertion of httpProfile\", exc_info=True)",
"def update_profile(self):\n pass",
"def update(self, customer_id: int, profile_id: int, type_: str, value: str) -> int:\n response = self.base_post_request(\n f\"{self.base_url}/{customer_id}/social-profiles/{profile_id}\",\n type=type_,\n value=value,\n )\n\n return self.process_result_with_status_code(response, 204)",
"def resume_instance(self, ctxt, instance):\n self.msg_runner.resume_instance(ctxt, instance)",
"def update(self, instance, validated_data):\n if validated_data.get('profile', ):\n profile_data = validated_data.get('profile', )\n profile_serializer = ProfileSerializer(data=profile_data)\n\n if profile_serializer.is_valid():\n profile = profile_serializer.update(instance=instance.profile)\n validated_data['profile'] = profile\n\n return super(UserSerializer, self).update(instance, validated_data)",
"def get_profilearn(self):\n try:\n response = self.client.get_instance_profile(InstanceProfileName=self.ProfileName)\n self.ProfileArn=response[\"InstanceProfile\"][\"Arn\"]\n except ClientError:\n self.ProfileArn=\"\"\n return self.ProfileArn",
"def TerminateInstance(*, session, instanceid):\n ec2conn = session.connect_to(\"ec2\")\n return ec2conn.terminate_instances(instance_ids=[instanceid,])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Replaces an entry (rule) in a network ACL. For more information about network ACLs, see Network ACLs in the Amazon Virtual Private Cloud User Guide .
|
def replace_network_acl_entry(DryRun=None, NetworkAclId=None, RuleNumber=None, Protocol=None, RuleAction=None, Egress=None, CidrBlock=None, Ipv6CidrBlock=None, IcmpTypeCode=None, PortRange=None):
pass
|
[
"def replace_network_acl_entry(\n network_acl_id=None,\n rule_number=None,\n protocol=None,\n rule_action=None,\n cidr_block=None,\n egress=None,\n network_acl_name=None,\n icmp_code=None,\n icmp_type=None,\n port_range_from=None,\n port_range_to=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n):\n\n kwargs = locals()\n return _create_network_acl_entry(replace=True, **kwargs)",
"def edit_acl_rule(self, old_acl_name, new_acl_name = \"\", is_added_mac = False, mac_list = [],\n is_modified_policy = False, new_policy = False, old_mac_addr = \"\"):\n self.navigate_to(self.CONFIGURE, self.CONFIGURE_ACCESS_CONTROLS, 5)\n\n ##zj 20140410 fixed ZF-8015\n if self.s.is_element_present(self.info['loc_cfg_acl_icon_expand']):\n pass\n elif self.s.is_element_present(self.info['loc_cfg_acl_icon_collapse']): \n self.s.click_and_wait(self.info['loc_cfg_acl_icon_collapse']) \n ##zj 20140410 fixed ZF-8015 \n\n #cwang@2010-9-30, checking element first, for scaling test.\n try:\n self._fill_search_txt(self.info['loc_cfg_l2_acl_search_textbox'], old_acl_name, is_refresh = False)\n except Exception, e:\n logging.debug(e.message)\n self._fill_search_txt(self.info['loc_cfg_l2_acl_search_textbox'], old_acl_name, is_refresh = True)\n\n try:\n\n if not self._wait_for_element(self.info['loc_cfg_total_acls_span'], is_refresh = True):\n raise Exception('Element [%s] not found' % self.info['loc_cfg_total_acls_span'])\n\n total_acls = self._get_total_number(self.info['loc_cfg_total_acls_span'], \"Access Controls\")\n max_acls_row = int(self.info['const_cfg_max_acl_rows'])\n traverse_row = 1\n i = 0\n\n if total_acls == u'0':\n logging.info(\"There's no acl rules in the Access Controls table\")\n return\n\n while i < int(total_acls):\n find_acl_name = self.info['loc_cfg_acl_name_cell']\n find_acl_name = find_acl_name.replace('$_$', str(traverse_row))\n get_acl_name = self.s.get_text(find_acl_name)\n\n if get_acl_name == old_acl_name:\n acl_edit = self.info['loc_cfg_acl_edit_span']\n acl_edit = acl_edit.replace('$_$', str(i))\n self.s.click_and_wait(acl_edit)\n\n if new_acl_name:\n self.s.type_text(self.info['loc_cfg_acl_name_textbox'], new_acl_name)\n if is_added_mac:\n if len(mac_list) == 1:\n self._delete_mac_addr_in_acl(old_mac_addr)\n self.s.type_text(self.info['loc_cfg_acl_mac_textbox'], mac_list[0])\n self.s.click_and_wait(self.info['loc_cfg_acl_createnew_station_button'])\n self.s.get_alert(self.info['loc_cfg_acl_cancel_button'])\n\n else:\n self._delete_all_mac_addrs_in_acl()\n for mac in mac_list:\n self.s.type_text(self.info['loc_cfg_acl_mac_textbox'], mac)\n self.s.click_and_wait(self.info['loc_cfg_acl_createnew_station_button'])\n self.s.get_alert(self.info['loc_cfg_acl_cancel_button'])\n time.sleep(1)\n\n if is_modified_policy:\n if new_policy:\n self.s.click_and_wait(self.info['loc_cfg_acl_allowall_radio'])\n else:\n self.s.click_and_wait(self.info['loc_cfg_acl_denyall_radio'])\n\n self.s.click_and_wait(self.info['loc_cfg_acl_ok_button'])\n self.s.get_alert(self.info['loc_cfg_acl_cancel_button'])\n\n return\n\n\n if traverse_row == max_acls_row:\n traverse_row = 0\n self.s.click_and_wait(self.info['loc_cfg_acl_next_image'])\n traverse_row += 1\n i += 1\n time.sleep(1)\n\n logging.info(\"No ACL rule named %s existed in the ACL table\" % old_acl_name)\n\n finally:\n self._fill_search_txt(self.info['loc_cfg_l2_acl_search_textbox'], '')",
"def ModifyNetworkAclAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyNetworkAclAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyNetworkAclAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def create_network_acl_entry(DryRun=None, NetworkAclId=None, RuleNumber=None, Protocol=None, RuleAction=None, Egress=None, CidrBlock=None, Ipv6CidrBlock=None, IcmpTypeCode=None, PortRange=None):\n pass",
"def update_entry_acl(self, acl_cql):\n cfg = get_config(None)\n session = connection.get_session()\n keyspace = cfg.get('KEYSPACE', 'drastic')\n session.set_keyspace(keyspace)\n query = SimpleStatement(u\"\"\"UPDATE tree_entry SET acl=acl+{}\n WHERE container=%s and name=%s\"\"\".format(acl_cql))\n session.execute(query, (self.container, self.name,))",
"def update_access(self, share, access_rules, add_rules,\n delete_rules, share_server):",
"def setAccessControlList(acl):",
"def clone_acl_rule(self, old_acl_name, new_acl_name):\n self.navigate_to(self.CONFIGURE, self.CONFIGURE_ACCESS_CONTROLS, 3)\n ##zj 20140410 fixed ZF-8015\n if self.s.is_element_present(self.info['loc_cfg_acl_icon_expand']):\n pass\n elif self.s.is_element_present(self.info['loc_cfg_acl_icon_collapse']): \n self.s.click_and_wait(self.info['loc_cfg_acl_icon_collapse']) \n ##zj 20140410 fixed ZF-8015 \n total_acls = self._get_total_number(self.info['loc_cfg_total_acls_span'], \"Access Controls\")\n max_acls_row = int(self.info['const_cfg_max_acl_rows'])\n traverse_row = 1\n i = 0\n\n if total_acls == u'0':\n logging.info(\"There's no acl rules in the Access Controls table\")\n return\n\n while i < int(total_acls):\n find_acl_name = self.info['loc_cfg_acl_name_cell']\n find_acl_name = find_acl_name.replace('$_$', str(traverse_row))\n get_acl_name = self.s.get_text(find_acl_name)\n\n if get_acl_name == old_acl_name:\n acl_edit = self.info['loc_cfg_acl_clone_span']\n acl_edit = acl_edit.replace('$_$', str(i))\n self.s.click_and_wait(acl_edit)\n\n if new_acl_name:\n self.s.type_text(self.info['loc_cfg_acl_name_textbox'], new_acl_name)\n\n self.s.click_and_wait(self.info['loc_cfg_acl_ok_button'])\n self.s.get_alert(self.info['loc_cfg_acl_cancel_button'])\n return\n\n if traverse_row == max_acls_row:\n traverse_row = 0\n self.s.click_and_wait(self.info['loc_cfg_acl_next_image'])\n\n traverse_row += 1\n i += 1\n time.sleep(1)\n\n logging.info(\"No ACL rule named %s existed in the ACL table\" % old_acl_name)",
"def delete_network_acl_entry(DryRun=None, NetworkAclId=None, RuleNumber=None, Egress=None):\n pass",
"def create_or_update(\n self,\n resource_group_name: str,\n network_security_perimeter_name: str,\n profile_name: str,\n access_rule_name: str,\n parameters: IO,\n *,\n content_type: str = \"application/json\",\n **kwargs: Any\n ) -> _models.NspAccessRule:",
"def s3_update_acl(self, role, c=None, f=None, t=None, oacl=None, uacl=None):\n\n table = self.permission.table\n\n if c is None and f is None and t is None:\n return None\n\n if t is not None:\n c = f = None\n\n if oacl is None:\n oacl = self.permission.NONE\n if uacl is None:\n uacl = self.permission.NONE\n\n if role:\n query = ((table.group_id == role) &\n (table.controller == c) &\n (table.function == f) &\n (table.tablename == f))\n record = self.db(query).select(table.id, limitby=(0,1)).first()\n acl = dict(group_id=role,\n controller=c,\n function=f,\n tablename=t,\n oacl=oacl,\n uacl=uacl)\n if record:\n success = record.update_record(**acl)\n else:\n success = table.insert(**acl)\n\n return success",
"def update_network_acl(self,\n id: str,\n network_acl_patch: 'NetworkACLPatch',\n **kwargs\n ) -> DetailedResponse:\n\n if id is None:\n raise ValueError('id must be provided')\n if network_acl_patch is None:\n raise ValueError('network_acl_patch must be provided')\n if isinstance(network_acl_patch, NetworkACLPatch):\n network_acl_patch = convert_model(network_acl_patch)\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='update_network_acl')\n headers.update(sdk_headers)\n\n params = {\n 'version': self.version,\n 'generation': self.generation\n }\n\n data = json.dumps(network_acl_patch)\n headers['content-type'] = 'application/merge-patch+json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n path_param_keys = ['id']\n path_param_values = self.encode_path_vars(id)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/network_acls/{id}'.format(**path_param_dict)\n request = self.prepare_request(method='PATCH',\n url=url,\n headers=headers,\n params=params,\n data=data)\n\n response = self.send(request)\n return response",
"def replace_rule(self, *args):\n return _wali.EWPDS_replace_rule(self, *args)",
"def create_or_update(\n self,\n resource_group_name: str,\n network_security_perimeter_name: str,\n profile_name: str,\n access_rule_name: str,\n parameters: _models.NspAccessRule,\n *,\n content_type: str = \"application/json\",\n **kwargs: Any\n ) -> _models.NspAccessRule:",
"def update_container_acl(self, acl_cql):\n cfg = get_config(None)\n session = connection.get_session()\n keyspace = cfg.get('KEYSPACE', 'drastic')\n session.set_keyspace(keyspace)\n query = SimpleStatement(u\"\"\"UPDATE tree_entry SET container_acl=container_acl+{}\n WHERE container=%s\"\"\".format(acl_cql))\n session.execute(query, (self.container,))",
"def action_bucket__set_canned_acl(args, params=None): # pylint: disable=unused-argument\n bucket = cached_get_bucket(args.conn, args.bucket_name)\n filestr = 'private'\n if isinstance(params, dict):\n filestr = params['str']\n elif isinstance(params, str):\n filestr = params\n rest = bucket.set_canned_acl(filestr)\n handle_result(args, res)",
"def action_key__set_canned_acl(args, params=None): # pylint: disable=unused-argument\n bucket = cached_get_bucket(args.conn, args.bucket_name)\n filestr = 'private'\n if isinstance(params, dict):\n filestr = params['str']\n elif isinstance(params, str):\n filestr = params\n key = bucket.get_key(args.key_name)\n res = key.set_canned_acl(filestr)\n handle_result(args, res)",
"def replace_rule(self, *args):\n return _wali.WPDS_replace_rule(self, *args)",
"def modify_acl_entries(self, path, acl_spec, recursive=False, number_of_sub_process=None):\n if recursive:\n multi_processor_change_acl(adl=self, path=path, method_name=\"mod_acl\", acl_spec=acl_spec,\n number_of_sub_process=number_of_sub_process)\n else:\n self._acl_call('MODIFYACLENTRIES', path, acl_spec, invalidate_cache=True)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Submits feedback about the status of an instance. The instance must be in the running state. If your experience with the instance differs from the instance status returned by DescribeInstanceStatus , use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. Use of this action does not change the value returned by DescribeInstanceStatus .
|
def report_instance_status(DryRun=None, Instances=None, Status=None, StartTime=None, EndTime=None, ReasonCodes=None, Description=None):
pass
|
[
"def _UpdateInstanceStatus(filename, instances):\n _WriteInstanceStatus(filename, [(inst.name, inst.status)\n for inst in instances])",
"def _wait_for_instance_running_state(self):\n\n assert self._instance\n\n tries = 0\n start_time = time.time()\n while True:\n try:\n tries += 1\n msg = 'Waiting for instance to run, tries=%s.' % (tries,)\n log.info(msg)\n self._store_message(msg)\n self._instance.update()\n if self._instance.state == 'running':\n break\n except Exception, e:\n msg = 'ERROR %s: %s' % (type(e), e)\n log.exception(msg)\n self._store_message(msg, 'error')\n\n if (self._running_state_check_timeout and\n time.time() - start_time >\n self._running_state_check_timeout):\n msg = 'Gave up trying to wait for EC2 instance to run.'\n log.error(msg)\n self._store_message(msg, 'error')\n break\n time.sleep(0.1)",
"def control_instance(stackName, action, instanceName=None):\n try:\n aws_cfg\n except NameError:\n try:\n aws_cfg = load_aws_cfg()\n except Exception, error:\n print(_red(\"error loading config. please provide an AWS conifguration based on aws.cfg-dist to proceed. %s\" % error))\n return 1\n\n stackName = stackName.lower()\n opsworks = connect_to_opsworks()\n stacks = opsworks.describe_stacks()\n stackId = [stack['StackId'] for stack in stacks['Stacks'] if stack['Name'] == stackName]\n if stackId == []:\n print(_red(\"stack %s not found\" % stackName))\n return 1\n instances = opsworks.describe_instances(stack_id=stackId[0])['Instances']\n if instanceName is not None:\n instances = [instance for instance in instances if instance['Hostname'] == instanceName]\n\n ec2 = connect_to_ec2()\n for instance in instances:\n if action == 'start':\n print(_green(\"starting instance: %s\" % instance['Hostname']))\n try:\n opsworks.start_instance(instance_id=instance['InstanceId'])\n except ValidationException:\n pass\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n spinner = Spinner(_yellow(\"[%s]Waiting for reservation \" % myinstance['Hostname']), hide_cursor=False)\n while myinstance['Status'] == 'requested':\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks instance status: %s\" % (myinstance['Hostname'], myinstance['Status'])))\n ec2Instance = ec2.get_only_instances(instance_ids=[myinstance['Ec2InstanceId']])[0]\n spinner = Spinner(_yellow(\"[%s]Booting ec2 instance \" % myinstance['Hostname']), hide_cursor=False)\n while ec2Instance.state != u'running':\n spinner.next()\n time.sleep(1)\n ec2Instance.update()\n print(_green(\"\\n[%s]ec2 Instance state: %s\" % (myinstance['Hostname'], ec2Instance.state)))\n spinner = Spinner(_yellow(\"[%s]Running OpsWorks setup \" % myinstance['Hostname']), hide_cursor=False)\n while myinstance['Status'] != 'online':\n if myinstance['Status'] == 'setup_failed':\n print(_red(\"\\n[%s]OpsWorks instance failed\" % myinstance['Hostname']))\n return 1\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks Instance state: %s\" % (myinstance['Hostname'], myinstance['Status'])))\n getec2instances()\n elif action == 'stop':\n if 'Ec2InstanceId' in instance.keys():\n print(_green(\"Stopping instance %s\" % instance['Hostname']))\n opsworks.stop_instance(instance_id=instance['InstanceId'])\n ec2Instance = ec2.get_only_instances(instance_ids=[instance['Ec2InstanceId']])[0]\n spinner = Spinner(_yellow(\"[%s]Waiting for ec2 instance to stop \" % instance['Hostname']), hide_cursor=False)\n while ec2Instance.state != u'stopped':\n spinner.next()\n time.sleep(1)\n ec2Instance.update()\n print(_green(\"\\n[%s]ec2 Instance state: %s\" % (instance['Hostname'], ec2Instance.state)))\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n spinner = Spinner(_yellow(\"[%s]Stopping OpsWorks Instance \" % instance['Hostname']), hide_cursor=False)\n while myinstance['Status'] != 'stopped':\n spinner.next()\n time.sleep(1)\n myinstance = opsworks.describe_instances(instance_ids=[instance['InstanceId']])['Instances'][0]\n print(_green(\"\\n[%s]OpsWorks Instance state: %s\" % (instance['Hostname'], myinstance['Status'])))\n else:\n print(_green(\"%s in %s already stopped\" % (instance['Hostname'], stackName)))\n try:\n print(_green(\"removing %s from ssh config...\" % instance['PublicDns']))\n removefromsshconfig(dns=instance['PublicDns'])\n except Exception:\n pass",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def change_instance_state(cls, ec2_resource, POST):\n\n if 'stop_instance_id' in POST.dict():\n posted_form = StopInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['stop_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).stop()\n elif 'start_instance_id' in POST.dict():\n posted_form = StartInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['start_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).start()\n else:\n posted_form = TerminateInstanceForm(POST)\n if posted_form.is_valid():\n instance_id = posted_form.cleaned_data['terminate_instance_id']\n ec2_resource.instances.filter(InstanceIds=[instance_id]).terminate()",
"def status(uid):\n if not uid:\n uid = Data['_last_submission_code']\n resp = get_data('submissions', uid)\n logger.debug(resp)\n click.secho('Submission ID: {}'.format(uid))\n click.secho('Problem Code: ' + resp['problemCode'], fg='green')\n click.secho('Contest Code: ' + resp['contestCode'])\n if resp['result'] == 'CTE':\n click.echo(\n 'Result: ' +\n click.style('Compile time Error', bg='red', fg='black')\n )\n elif resp['result'] == 'AC':\n click.echo(\n 'Result: ' +\n click.style('All Correct', bg='green', fg='black')\n )\n else:\n click.echo(\n 'Result: ' + resp['result']\n )",
"def assess_status():\n BarbicanCharm.singleton.assess_status()",
"def _WriteInstanceStatus(filename, data):\n logging.debug(\"Updating instance status file '%s' with %s instances\",\n filename, len(data))\n\n utils.WriteFile(filename,\n data=\"\\n\".join(\"%s %s\" % (n, s) for (n, s) in sorted(data)))",
"def mstp_instances_status(self, site_id, element_id, mstp_instance_id, tenant_id=None, api_version=\"v2.0\"):\n\n if tenant_id is None and self._parent_class.tenant_id:\n # Pull tenant_id from parent namespace cache.\n tenant_id = self._parent_class.tenant_id\n elif not tenant_id:\n # No value for tenant_id.\n raise TypeError(\"tenant_id is required but not set or cached.\")\n cur_ctlr = self._parent_class.controller\n\n url = str(cur_ctlr) + \"/{}/api/tenants/{}/sites/{}/elements/{}/mstp_instances/{}/status\".format(api_version,\n tenant_id,\n site_id,\n element_id,\n mstp_instance_id)\n\n api_logger.debug(\"URL = %s\", url)\n return self._parent_class.rest_call(url, \"get\")",
"def status(ctx: click.Context) -> None:\n info = get(\"status\", lambda: status_call(ctx.obj[\"session\"]))\n click.echo(json_pretty(info))",
"def get_instance_status(self, prop):\n conn = self._get_conn(prop)\n cont_prop = conn.inspect_container(prop[\"instance\"])\n if cont_prop[\"State\"][\"Paused\"]:\n return \"paused\"\n elif cont_prop[\"State\"][\"Running\"]:\n return \"running\"\n else:\n return \"stopped\"",
"def submit_action(self, instance, options={}):\n requested_resource = instance.request\n reason_for_request = instance.description\n username = self.request.user.username\n email.resource_request_email(self.request, username,\n requested_resource,\n reason_for_request,\n options)",
"def _WaitForAllInstancesRunning(self):\n size = self.params.size\n while True:\n logging.info('Checking instance status...')\n status_count = {}\n for index in xrange(size):\n instance_info = self._GetGceApi().GetInstance(\n self._MakeInstanceName(index))\n if instance_info:\n status = instance_info['status']\n else:\n status = 'NOT YET CREATED'\n status_count[status] = status_count.get(status, 0) + 1\n logging.info('Total instances: %d', size)\n for status, count in status_count.items():\n logging.info(' %s: %d', status, count)\n if status_count.get('RUNNING', 0) == size:\n break\n logging.info('Wait for instances RUNNING...')\n time.sleep(GCE_STATUS_CHECK_INTERVAL)",
"def status(self) -> 'outputs.UpdateRunStatusResponse':\n return pulumi.get(self, \"status\")",
"def lambda_handler(event, context):\n client = boto3.client(\"ec2\", region_name=event[\"region\"])\n\n instance_id = event[\"instance_id\"]\n get_status = client.describe_instances(InstanceIds=[instance_id])\n current_status = get_status[\"Reservations\"][0][\"Instances\"][0][\"State\"]\n\n if current_status[\"Name\"] == \"running\":\n response = client.stop_instances(InstanceIds=[instance_id])\n if current_status[\"Name\"] == \"stopped\":\n response = client.start_instances(InstanceIds=[instance_id])\n\n return response",
"def active(message):\n status_set(WorkloadState.ACTIVE, message)",
"def run_status(self, ticket_id, status=None):\n ticket_id = text.validate_id(ticket_id)\n\n self.login()\n\n # Get all the available actions for this ticket\n r = self.get(\"/ticket/%d\" % ticket_id)\n timestamp = text.extract_timestamp(r.content)\n statuses = text.extract_statuses(r.content)\n\n # A ``status`` was provided, try to find the exact match, else just\n # display the current status for this ticket, and the available ones.\n if status:\n status = text.fuzzy_find(status, statuses)\n\n if not status:\n raise exceptions.FatalError(\"bad status (for this ticket: %s)\" % \\\n \", \".join(statuses))\n else:\n status = text.extract_status_from_ticket_page(r.content)\n print(\"Current status: %s\" % status)\n print(\"Available statuses: %s\" % \", \".join(statuses))\n return\n\n if self.message:\n comment = self.message\n elif self.add_comment:\n comment = self._read_comment()\n else:\n comment = \"\"\n\n r = self.post(\"/ticket/%d\" % ticket_id, {\n \"ts\": timestamp,\n \"action\": status,\n \"comment\": comment,\n })\n\n if \"system-message\" in r.content or r.status_code != 200:\n raise exceptions.FatalError(\"unable to set status\")",
"def current_status(self):\n self.screen.blit(f\"Humanoid is currently {self.model.action()}\\\n \\n Try to keep them alive.\")",
"def set_proc_status(assessor_obj, status, xsitype=XnatUtils.DEFAULT_DATATYPE):\n assessor_obj.attrs.set(xsitype+'/procstatus', status)\n if status == dax.task.NEED_INPUTS or status == dax.task.NEED_TO_RUN:\n assessor_obj.attrs.mset({xsitype+'/validation/status':'Job Pending',\n xsitype+'/jobid':'NULL',\n xsitype+'/memused':'NULL',\n xsitype+'/walltimeused':'NULL',\n xsitype+'/jobnode':'NULL',\n xsitype+'/jobstartdate':'NULL',\n xsitype+'/validation/validated_by':'NULL',\n xsitype+'/validation/date':'NULL',\n xsitype+'/validation/notes':'NULL',\n xsitype+'/validation/method':'NULL'})\n sys.stdout.write(' - Job Status on Assessor %s changed to %s\\n' % (assessor_obj.label(), status))\n if status == dax.task.COMPLETE:\n set_qc_status(assessor_obj, dax.task.NEEDS_QA, xsitype=xsitype)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a Spot fleet request. You can submit a single request that includes multiple launch specifications that vary by instance type, AMI, Availability Zone, or subnet. By default, the Spot fleet requests Spot instances in the Spot pool where the price per unit is the lowest. Each launch specification can include its own instance weighting that reflects the value of the instance type to your application workload. Alternatively, you can specify that the Spot fleet distribute the target capacity across the Spot pools included in its launch specifications. By ensuring that the Spot instances in your Spot fleet are in different Spot pools, you can improve the availability of your fleet. For more information, see Spot Fleet Requests in the Amazon Elastic Compute Cloud User Guide .
|
def request_spot_fleet(DryRun=None, SpotFleetRequestConfig=None):
pass
|
[
"def create_fleet(Name=None, Description=None, BuildId=None, ServerLaunchPath=None, ServerLaunchParameters=None, LogPaths=None, EC2InstanceType=None, EC2InboundPermissions=None, NewGameSessionProtectionPolicy=None, RuntimeConfiguration=None, ResourceCreationLimitPolicy=None, MetricGroups=None):\n pass",
"def modify_spot_fleet_request(SpotFleetRequestId=None, TargetCapacity=None, ExcessCapacityTerminationPolicy=None):\n pass",
"def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):\n pass",
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def create_fleet(region, boto3_config, create_fleet_kwargs):\n try:\n from slurm_plugin.overrides import create_fleet\n\n logger.info(\"Launching instances with create_fleet override API. Parameters: %s\", create_fleet_kwargs)\n return create_fleet(region=region, boto3_config=boto3_config, **create_fleet_kwargs)\n except ImportError:\n logger.info(\"Launching instances with create_fleet API. Parameters: %s\", create_fleet_kwargs)\n ec2_client = boto3.client(\"ec2\", region_name=region, config=boto3_config)\n return ec2_client.create_fleet(**create_fleet_kwargs)",
"def create_fleet(ai_settings, screen,ship, startreks):\n\t# create a startrek and find the number of startreks in a row\n\t# spacing between each startrek is equal to one ufo width\n\tstartrek = Ufo(ai_settings, screen)\n\tnumber_startreks_x = get_number_startreks(ai_settings, startrek.rect.width )\n\tnumber_rows = get_number_rows(ai_settings, ship.rect.height, startrek.rect.height)\n\n\n\n\t# create the fleet of startreks\n\tfor row_number in range(number_rows):\n\t\tfor startrek_number in range(number_startreks_x):\n\t\t# create a startrek and place it in the row\n\t\t\tcreate_startrek(ai_settings, screen, startreks, startrek_number, row_number)",
"def __init__(self,\n fleet_subnet_type=None,\n fleet_tag_vec=None,\n network_params=None,\n network_params_map=None,\n network_params_vec=None):\n\n # Initialize members of the class\n self.fleet_subnet_type = fleet_subnet_type\n self.fleet_tag_vec = fleet_tag_vec\n self.network_params = network_params\n self.network_params_map = network_params_map\n self.network_params_vec = network_params_vec",
"def create_request(self):\n date_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')\n present_time = date_time[0:-3] + 'Z'\n # Using the web service post() method to create request\n response = requests.post(url=bid_url, headers={'Authorization': self.api_key}, json={\n \"type\": self.bid_type.get(),\n \"initiatorId\": self.current_user.id,\n \"dateCreated\": present_time,\n \"subjectId\": Subject().get_id_by_name(self.subject.get()),\n \"additionalInfo\": {\"competency\": self.competency.get(), \"hours_per_week\": self.hours_per_session.get(),\n \"sessions_per_week\": self.sessions_per_week.get(),\n \"rate_per_session\": self.rate_per_session.get()}\n }\n )\n json_data = response.json()\n # Destroying current window and jumping to next screen by calling the main() method from the NewRequestDetails \n # class\n self.window.destroy()\n NewRequestDetails(json_data).main()",
"def create_req(self):\n \n pass",
"def create_or_resume(name, spec, **_):\n\n # deploy mysql for placement\n utils.ensure_mysql_cluster(\"placement\", spec[\"mysql\"])\n\n # deploy placement api\n utils.create_or_update('placement/daemonset.yml.j2', spec=spec)\n utils.create_or_update('placement/service.yml.j2', spec=spec)\n\n # Create application credential\n identity.ensure_application_credential(name=\"placement\")\n\n url = None\n if \"ingress\" in spec:\n utils.create_or_update('placement/ingress.yml.j2',\n name=name, spec=spec)\n url = spec[\"ingress\"][\"host\"]\n\n if \"endpoint\" not in spec:\n spec[\"endpoint\"] = True\n if spec[\"endpoint\"]:\n identity.ensure_service(name=\"placement\", service_type=\"placement\",\n url=url, desc=\"Placement Service\")",
"def describe_spot_fleet_requests(DryRun=None, SpotFleetRequestIds=None, NextToken=None, MaxResults=None):\n pass",
"def __init__(__self__,\n resource_name: str,\n opts: Optional[pulumi.ResourceOptions] = None,\n block_device_mappings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['LaunchTemplateBlockDeviceMappingArgs']]]]] = None,\n capacity_reservation_specification: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateCapacityReservationSpecificationArgs']]] = None,\n cpu_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateCpuOptionsArgs']]] = None,\n credit_specification: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateCreditSpecificationArgs']]] = None,\n default_version: Optional[pulumi.Input[int]] = None,\n description: Optional[pulumi.Input[str]] = None,\n disable_api_stop: Optional[pulumi.Input[bool]] = None,\n disable_api_termination: Optional[pulumi.Input[bool]] = None,\n ebs_optimized: Optional[pulumi.Input[str]] = None,\n elastic_gpu_specifications: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['LaunchTemplateElasticGpuSpecificationArgs']]]]] = None,\n elastic_inference_accelerator: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateElasticInferenceAcceleratorArgs']]] = None,\n enclave_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateEnclaveOptionsArgs']]] = None,\n hibernation_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateHibernationOptionsArgs']]] = None,\n iam_instance_profile: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateIamInstanceProfileArgs']]] = None,\n image_id: Optional[pulumi.Input[str]] = None,\n instance_initiated_shutdown_behavior: Optional[pulumi.Input[str]] = None,\n instance_market_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateInstanceMarketOptionsArgs']]] = None,\n instance_requirements: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateInstanceRequirementsArgs']]] = None,\n instance_type: Optional[pulumi.Input[str]] = None,\n kernel_id: Optional[pulumi.Input[str]] = None,\n key_name: Optional[pulumi.Input[str]] = None,\n license_specifications: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['LaunchTemplateLicenseSpecificationArgs']]]]] = None,\n maintenance_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateMaintenanceOptionsArgs']]] = None,\n metadata_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateMetadataOptionsArgs']]] = None,\n monitoring: Optional[pulumi.Input[pulumi.InputType['LaunchTemplateMonitoringArgs']]] = None,\n name: Optional[pulumi.Input[str]] = None,\n name_prefix: Optional[pulumi.Input[str]] = None,\n network_interfaces: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['LaunchTemplateNetworkInterfaceArgs']]]]] = None,\n placement: Optional[pulumi.Input[pulumi.InputType['LaunchTemplatePlacementArgs']]] = None,\n private_dns_name_options: Optional[pulumi.Input[pulumi.InputType['LaunchTemplatePrivateDnsNameOptionsArgs']]] = None,\n ram_disk_id: Optional[pulumi.Input[str]] = None,\n security_group_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n tag_specifications: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['LaunchTemplateTagSpecificationArgs']]]]] = None,\n tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n update_default_version: Optional[pulumi.Input[bool]] = None,\n user_data: Optional[pulumi.Input[str]] = None,\n vpc_security_group_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n __props__=None):\n ...",
"def _create_fleet(self):\n\t\t# create a virus and find the number of viruses in a row\n\t\t# spacing between each virus is equal to one virus width\n\t\tvirus = Virus(self)\n\t\tvirus_width, virus_height = virus.rect.size\n\t\tavailable_space_x = self.settings.screen_width - (2 * virus_width)\n\t\tnumber_viruses_x = available_space_x // (2 * virus_width)\n\n\t\t# determine the number of rows of viruses that fit on the screen\n\t\tnurse_height = self.nurse.rect.height\n\t\tavailable_space_y = (self.settings.screen_height - (3 * virus_height) - nurse_height)\n\t\tnumber_rows = available_space_y // (2 * virus_height)\n\n\t\t# create full fleet of viruses\n\t\tfor row_number in range(number_rows):\n\t\t\tfor virus_number in range(number_viruses_x):\n\t\t\t\tself._create_virus(virus_number, row_number)",
"def create_vm(request: VMRequest):\n id = len(deployments)\n\n item = VMInstance(id=id)\n item.vmname = \"vg1111yr\"\n item.az = request.az\n item.dc = request.dc\n item.rd = request.rd\n item.size = request.size\n item.os = request.os\n print(item.dict())\n\n deployments.append(item.dict())\n return item",
"def assignRequest(self, requestName, teamName, acqEra, procVer, dashActivity,\n siteWhitelist = [], siteBlacklist = [],\n mergedLFNBase = \"/store/data\", unmergedLFNBase = \"/store/unmerged\",\n minMergeSize = 2147483648, maxMergeSize = 4294967296,\n maxMergeEvents = 50000, maxRSS = 2394967, maxVSize = 4294967296,\n softTimeout = 171600, gracePeriod = 300):\n reqParams = {\"action\": \"Assign\",\n \"Team\" + teamName: \"checked\",\n \"SiteWhitelist\": site,\n \"SiteBlacklist\": [],\n \"MergedLFNBase\": \"/store/mc\",\n \"UnmergedLFNBase\": \"/store/unmerged\",\n \"MinMergeSize\": 2147483648,\n \"MaxMergeSize\": 4294967296,\n \"MaxMergeEvents\": 50000,\n \"AcquisitionEra\": era,\n \"ProcessingVersion\": procversion,\n \"MaxRSS\": 2394967,\n \"MaxVSize\": 4294967296,\n \"Dashboard\": activity,\n \"SoftTimeout\":171600,\n \"GracePeriod\":300,\n \"checkbox\" + requestName: \"checked\"}\n\n \n return",
"def __init__(__self__,\n resource_name: str,\n opts: Optional[pulumi.ResourceOptions] = None,\n autoscale_headrooms: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecAutoscaleHeadroomArgs']]]]] = None,\n autoscale_headrooms_automatics: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecAutoscaleHeadroomsAutomaticArgs']]]]] = None,\n instance_types: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n labels: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecLabelArgs']]]]] = None,\n metadatas: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecMetadataArgs']]]]] = None,\n name: Optional[pulumi.Input[str]] = None,\n network_interfaces: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecNetworkInterfaceArgs']]]]] = None,\n node_pool_name: Optional[pulumi.Input[str]] = None,\n ocean_id: Optional[pulumi.Input[str]] = None,\n resource_limits: Optional[pulumi.Input[pulumi.InputType['OceanLaunchSpecResourceLimitsArgs']]] = None,\n restrict_scale_down: Optional[pulumi.Input[bool]] = None,\n root_volume_size: Optional[pulumi.Input[int]] = None,\n root_volume_type: Optional[pulumi.Input[str]] = None,\n scheduling_tasks: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecSchedulingTaskArgs']]]]] = None,\n service_account: Optional[pulumi.Input[str]] = None,\n shielded_instance_config: Optional[pulumi.Input[pulumi.InputType['OceanLaunchSpecShieldedInstanceConfigArgs']]] = None,\n source_image: Optional[pulumi.Input[str]] = None,\n storage: Optional[pulumi.Input[pulumi.InputType['OceanLaunchSpecStorageArgs']]] = None,\n strategies: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecStrategyArgs']]]]] = None,\n tags: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n taints: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OceanLaunchSpecTaintArgs']]]]] = None,\n update_policy: Optional[pulumi.Input[pulumi.InputType['OceanLaunchSpecUpdatePolicyArgs']]] = None,\n __props__=None):\n ...",
"def optimal_parking(intent_request):\n\n # Find optimal parking lot\n sorted_lots = helper.get_optimal_lots()\n parking_lot = sorted_lots['First']['Name']\n\n # Use of sessionAttributes to store information that can be used to guide\n # conversation. Session attributes are pieces of information that the user\n # has provided to the chatbot either in a previous intent or the current\n # one.\n if intent_request['sessionAttributes'] is not None:\n session_attributes = intent_request['sessionAttributes']\n else:\n session_attributes = {}\n\n # Load slot value history for parking lots\n parking_request = json.dumps({\n 'ParkingRequest': 'OptimalLot',\n 'ParkingLot': parking_lot\n })\n\n # Track current parking request.\n session_attributes['currentParkingRequest'] = parking_request\n\n source = intent_request['invocationSource']\n\n if source == 'FulfillmentCodeHook':\n # Called once the user has provided all information to fulfill the.\n # intent. In this case it is called immediately because there are no\n # slots for this intent.\n lamfunc.logger.debug(\n 'request for optimal parking={}'.format(parking_request)\n )\n\n # Clear settings from sessionAttributes\n helper.try_ex(lambda: session_attributes.pop('currentParkingRequest'))\n\n # Keep track of what was the last parking lot the user requested\n # information for.\n session_attributes['lastParkingRequest'] = parking_request\n\n # End the intent.\n return response.close(\n intent_request['sessionAttributes'],\n 'Fulfilled', {\n 'contentType': 'PlainText',\n 'content': helper.build_optimal_msg(sorted_lots)\n }\n )\n\n raise Exception('Error fulfilling OptimalParking intent')",
"def spotify(self, app_region, template):\n if app_region.spot is None:\n return\n\n resources = template['Resources']\n parameters = template['Parameters']\n self._add_spot_fleet(app_region, resources, parameters)\n self._clean_up_asg(template)",
"def create_system_instance(tags=None, definition=None, target=None, greengrassGroupName=None, s3BucketName=None, metricsConfiguration=None, flowActionsRoleArn=None):\n pass",
"def wait_for_fulfillment(self, timeout=50, request_ids=None):\n logger.debug(\"waiting for requests to be fulfilled\") \n\n if request_ids is None:\n spot_req_ids = self.spot_req_ids\n else:\n spot_req_ids = request_ids\n\n processed_dict=dict()\n for sir_id in spot_req_ids:\n processed_dict[sir_id] = False\n #status_dict[sir_id] = None\n\n ### wait for a disposition for each spot request (basically when sir.state is not open)\n loop_count=0\n while not all( processed_dict.values()) and loop_count <= timeout:\n loop_count+=1\n try:\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n except boto.exception.EC2ResponseError:\n ### need to wait a little time for AWS to register the requests, if this function called\n ### right after create_spot_instances\n time.sleep(3)\n continue\n for sir in spot_reqs:\n if sir.state != 'open':\n processed_dict[sir.id] = True\n\n if not all ( processed_dict.values()):\n time.sleep(15)\n\n\n ### get disposition of each spot instance request\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n instance_ids = list()\n instance_ready = dict()\n for sir in spot_reqs:\n if sir.state == 'open':\n self.request_status_dict[sir.id] = 'timed out'\n else:\n self.request_status_dict[sir.id] = sir.status.code\n\n if sir.status.code == 'fulfilled':\n instance_ids.append(sir.instance_id)\n instance_ready[sir.instance_id] = False\n else:\n self.failed_req_ids.append(sir.id)\n \n ### wait for ready states in the fulfilled instances\n while not all ( instance_ready.values()) and loop_count <= timeout:\n loop_count+=1\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'pending':\n instance_ready[inst.id] = True\n \n if not all (instance_ready.values()):\n time.sleep(15)\n\n ### get final dispositions of instances\n good_instances =0\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'running':\n sir_id = inst.spot_instance_request_id\n self.failed_req_ids.append(sir_id)\n if inst.state == 'pending':\n self.request_status_dict[sir_id] = 'timed out'\n else:\n self.request_status_dict[sir_id] = 'post-fulfillment premature instance termination'\n else:\n if self.use_private_ips:\n ipaddr=inst.private_ip_address\n else:\n ipaddr=inst.ip_address\n self.instance_ids.append(inst.id)\n self.ip_dict[inst.id] = ipaddr\n self.rev_ip_dict[ipaddr] = inst.id\n self.request_status_dict[sir_id] = 'running'\n good_instances+=1\n\n\n ### might have to sleep a little bit after running status toggles before it can accept ssh connections\n # put a 30 second delay in\n time.sleep(30)\n\n return (len (spot_req_ids), good_instances) \n\n ### to retrieve good instances: awsobj.instance_ids[-good_instances:]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a Spot instance request. Spot instances are instances that Amazon EC2 launches when the bid price that you specify exceeds the current Spot price. Amazon EC2 periodically sets the Spot price based on available Spot Instance capacity and current Spot instance requests. For more information, see Spot Instance Requests in the Amazon Elastic Compute Cloud User Guide .
|
def request_spot_instances(DryRun=None, SpotPrice=None, ClientToken=None, InstanceCount=None, Type=None, ValidFrom=None, ValidUntil=None, LaunchGroup=None, AvailabilityZoneGroup=None, BlockDurationMinutes=None, LaunchSpecification=None):
pass
|
[
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def start_server():\n log.info(\"Logging into AWS\")\n\n if _server_is_running():\n sys.exit(\"There is already a g2.2xlarge instance running\")\n\n log.info(\"Creating spot instance request for ${}\"\n .format(MAX_DOLLARS_PER_HOUR))\n output = ec2.meta.client.request_spot_instances(\n DryRun=False,\n SpotPrice=MAX_DOLLARS_PER_HOUR,\n InstanceCount=1,\n LaunchSpecification={\n 'ImageId': 'ami-ee897b8e',\n 'InstanceType': 'g2.2xlarge',\n 'KeyName': KEYNAME}\n )\n if output['ResponseMetadata']['HTTPStatusCode'] != 200:\n sys.exit(\"There was an issue with the request.\")\n else:\n log.info(\"Success! Your spot request is pending fufillment.\")\n request_id = output['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n\n _is_spot_fufilled(request_id)\n log.info(\"Server successfully provisioned\")\n\n while not _server_is_running():\n log.info(\"Still waiting for the server to be ready\")\n sleep(10)\n\n self.log(\"sleeping a bit\")\n sleep(60)\n\n log.info(\"Setting up instance\")\n set_up_server()\n ip = _get_ip_address()\n log.info(\"ssh -i {} ec2-user@{}\".format(PATH_TO_PEM, ip))",
"def modify_spot_fleet_request(SpotFleetRequestId=None, TargetCapacity=None, ExcessCapacityTerminationPolicy=None):\n pass",
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def reserve_parking_spot():\n req_data = request.get_json()\n if req_data is None:\n return ResponseUtil.send_bad_request(message='Please provide valid parking spot to book')\n\n user = req_data.get('user', None)\n parking_spot = req_data.get('parking_spot', None)\n\n if not (ValidationUtil.is_mongo_id(user) and ValidationUtil.is_mongo_id(parking_spot)):\n # invalid parking spot or user\n return ResponseUtil.send_bad_request(message='Please provide valid parking spot to book')\n\n if not (ParkingSpot.objects(id=parking_spot).count() and User.objects(id=user).count()):\n # no parking spot or user\n return ResponseUtil.send_bad_request(message='Please provide valid parking spot to book and user id')\n\n booking = Booking(user=user, parking_spot=parking_spot).save().fetch()\n return ResponseUtil.send_success(booking)",
"def wait_for_fulfillment(self, timeout=50, request_ids=None):\n logger.debug(\"waiting for requests to be fulfilled\") \n\n if request_ids is None:\n spot_req_ids = self.spot_req_ids\n else:\n spot_req_ids = request_ids\n\n processed_dict=dict()\n for sir_id in spot_req_ids:\n processed_dict[sir_id] = False\n #status_dict[sir_id] = None\n\n ### wait for a disposition for each spot request (basically when sir.state is not open)\n loop_count=0\n while not all( processed_dict.values()) and loop_count <= timeout:\n loop_count+=1\n try:\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n except boto.exception.EC2ResponseError:\n ### need to wait a little time for AWS to register the requests, if this function called\n ### right after create_spot_instances\n time.sleep(3)\n continue\n for sir in spot_reqs:\n if sir.state != 'open':\n processed_dict[sir.id] = True\n\n if not all ( processed_dict.values()):\n time.sleep(15)\n\n\n ### get disposition of each spot instance request\n spot_reqs = self.conn.get_all_spot_instance_requests(request_ids = spot_req_ids)\n instance_ids = list()\n instance_ready = dict()\n for sir in spot_reqs:\n if sir.state == 'open':\n self.request_status_dict[sir.id] = 'timed out'\n else:\n self.request_status_dict[sir.id] = sir.status.code\n\n if sir.status.code == 'fulfilled':\n instance_ids.append(sir.instance_id)\n instance_ready[sir.instance_id] = False\n else:\n self.failed_req_ids.append(sir.id)\n \n ### wait for ready states in the fulfilled instances\n while not all ( instance_ready.values()) and loop_count <= timeout:\n loop_count+=1\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'pending':\n instance_ready[inst.id] = True\n \n if not all (instance_ready.values()):\n time.sleep(15)\n\n ### get final dispositions of instances\n good_instances =0\n instances = self.conn.get_only_instances(instance_ids = instance_ids)\n for inst in instances:\n if inst.state != 'running':\n sir_id = inst.spot_instance_request_id\n self.failed_req_ids.append(sir_id)\n if inst.state == 'pending':\n self.request_status_dict[sir_id] = 'timed out'\n else:\n self.request_status_dict[sir_id] = 'post-fulfillment premature instance termination'\n else:\n if self.use_private_ips:\n ipaddr=inst.private_ip_address\n else:\n ipaddr=inst.ip_address\n self.instance_ids.append(inst.id)\n self.ip_dict[inst.id] = ipaddr\n self.rev_ip_dict[ipaddr] = inst.id\n self.request_status_dict[sir_id] = 'running'\n good_instances+=1\n\n\n ### might have to sleep a little bit after running status toggles before it can accept ssh connections\n # put a 30 second delay in\n time.sleep(30)\n\n return (len (spot_req_ids), good_instances) \n\n ### to retrieve good instances: awsobj.instance_ids[-good_instances:]",
"async def limit_maker(symbol, side, quantity, price, new_client_order_id, iceberg_qty, recv_window,\n new_order_resp_type):\n payload = {\n 'symbol': symbol,\n 'side': side,\n 'type': \"LIMIT_MAKER\",\n 'quantity': quantity,\n 'price': price,\n 'newOrderRespType': new_order_resp_type,\n 'recvWindow': recv_window,\n 'timestamp': get_timestamp()\n }\n\n builder = LimitMakerBuilder(endpoint='api/v3/order', payload=payload, method='POST') \\\n .add_optional_params_to_payload(new_client_order_id=new_client_order_id,\n iceberg_qty=iceberg_qty) \\\n .set_security()\n\n await builder.send_http_req()\n\n builder.handle_response().generate_output()",
"def offer_create(self, **kwargs):\n if not self.token:\n return Exception('No token found!')\n response = self.api_request(method='POST', path='offer/', **kwargs)\n return response",
"def instamojo_create_offer(self, **kwargs):\n if not self.mojo_token:\n return Exception('Cannot create offer without token')\n res = self.instamojo_api_request(method='POST', path='offer/', **kwargs)\n return res",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def create_request(self):\n date_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')\n present_time = date_time[0:-3] + 'Z'\n # Using the web service post() method to create request\n response = requests.post(url=bid_url, headers={'Authorization': self.api_key}, json={\n \"type\": self.bid_type.get(),\n \"initiatorId\": self.current_user.id,\n \"dateCreated\": present_time,\n \"subjectId\": Subject().get_id_by_name(self.subject.get()),\n \"additionalInfo\": {\"competency\": self.competency.get(), \"hours_per_week\": self.hours_per_session.get(),\n \"sessions_per_week\": self.sessions_per_week.get(),\n \"rate_per_session\": self.rate_per_session.get()}\n }\n )\n json_data = response.json()\n # Destroying current window and jumping to next screen by calling the main() method from the NewRequestDetails \n # class\n self.window.destroy()\n NewRequestDetails(json_data).main()",
"async def take_profit_limit(symbol, side, time_in_force, quantity, price, new_client_order_id,\n stop_price, iceberg_qty, recv_window, new_order_resp_type):\n payload = {\n 'symbol': symbol,\n 'side': side,\n 'type': \"TAKE_PROFIT_LIMIT\",\n 'timeInForce': time_in_force,\n 'quantity': quantity,\n 'price': price,\n 'stopPrice': stop_price,\n 'newOrderRespType': new_order_resp_type,\n 'recvWindow': recv_window,\n 'timestamp': get_timestamp()\n }\n\n builder = TakeProfitLimitBuilder(endpoint='api/v3/order', payload=payload, method='POST') \\\n .add_optional_params_to_payload(new_client_order_id=new_client_order_id,\n iceberg_qty=iceberg_qty) \\\n .set_security()\n\n await builder.send_http_req()\n\n builder.handle_response().generate_output()",
"def create_server():\n conn = boto.connect_ec2(ec2_key, ec2_secret)\n image = conn.get_all_images(ec2_amis)\n\n reservation = image[0].run(1, 1, ec2_keypair, ec2_secgroups,\n instance_type=ec2_instancetype)\n\n instance = reservation.instances[0]\n\n while instance.state == u'pending':\n print \"Instance state: %s\" % instance.state\n time.sleep(10)\n instance.update()\n\n print \"Instance state: %s\" % instance.state\n local(\"echo %s | pbcopy\" % instance.public_dns_name)\n print \"Public dns: %s\" % instance.public_dns_name\n \n print \"*** Edit env.hosts to include hostname, then run 'setup_instance' ***\"",
"def create_instance(sg_name, options):\n\n client = boto3.client(\"ec2\")\n\n # The instance should be started up with a script that will install docker and\n # then start 2 containers (one for the db server, another for the scheduler server)\n DEPLOY_SCRIPT = \"my-init.sh\"\n txt = open(DEPLOY_SCRIPT)\n user_data = txt.read()\n\n key_name = options[\"key_name\"]\n\n # Try to launch an ec2 instance\n try:\n\n response = client.run_instances(\n #ImageId=\"ami-c229c0a2\",\n #ImageId=\"ami-fb890097\",\n ImageId=\"ami-27b3094b\",\n MinCount=1,\n MaxCount=1,\n InstanceType=\"t2.micro\",\n SecurityGroups=[\"default\", sg_name],\n KeyName=key_name,\n UserData=user_data\n )\n\n # Bail out if there's something wrong with the key pair supplied\n #except botocore.exceptions.ClientError as e:\n except Exception as e:\n print e\n if e.response['Error']['Code'] == 'InvalidKeyPair.NotFound':\n print \"Key pair name(%s) was not accepted. \" % key_name\n sys.exit(4)\n\n instance_id = response[\"Instances\"][0][\"InstanceId\"]\n\n # Wait for the public dns name gets ready. This is normally unavailable\n # right after the instance creation, but it shouldnt take too long\n public_dns_name = \"\"\n while public_dns_name == \"\":\n print \"Hold on...\"\n sleep(10)\n response = client.describe_instances(InstanceIds=[instance_id])\n public_dns_name = response[\"Reservations\"][\n 0][\"Instances\"][0][\"PublicDnsName\"]\n\n return [instance_id, public_dns_name]",
"def create_ec2_instace(name=\"shopply\", security_group=\"dwd\"):\n conn = boto.connect_ec2()\n reservation = conn.run_instances(\n AMI,\n key_name = KEYPAIR,\n instance_type = 't1.micro',\n security_groups = [security_group],\n instance_initiated_shutdown_behavior = \"stop\"\n )\n \n instance = reservation.instances[0]\n instance.add_tag(\"Name\", name)\n \n \n print \"Launching instance: \", instance.public_dns_name",
"def create_ec2_instances(count=1):\n conn = get_ec2_connection()\n user_data = get_user_data()\n reservation = conn.run_instances(image_id=settings.EC2_IMAGE_ID,\n min_count=count,\n max_count=count,\n instance_type=settings.EC2_INSTANCE_TYPE,\n user_data=user_data)\n return reservation.instances",
"def describe_spot_instance_requests(DryRun=None, SpotInstanceRequestIds=None, Filters=None):\n pass",
"def create_vm(request: VMRequest):\n id = len(deployments)\n\n item = VMInstance(id=id)\n item.vmname = \"vg1111yr\"\n item.az = request.az\n item.dc = request.dc\n item.rd = request.rd\n item.size = request.size\n item.os = request.os\n print(item.dict())\n\n deployments.append(item.dict())\n return item",
"def _menu_aws_compute_new_instance():\n # AMIs dict\n amis = {'1': 'ami-31328842', '2': 'ami-8b8c57f8', '3': 'ami-f95ef58a', '4': 'ami-c6972fb5'}\n # Ask user to enter instance name\n i_name = raw_input(\"Enter instance name: \")\n # Ask user to choose OS\n print \"Creating new instance.. Choose OS:\"\n print \"\\t1. Amazon Linux\"\n print \"\\t2. Red Hat Enterprise Linux 7.2\"\n print \"\\t3. Ubuntu Server 14.04 LTS\"\n print \"\\t4. Microsoft Windows Server 2012 R2 Base\"\n op = raw_input(\"Enter option: \")\n # Validating entered option\n op = __op_validation(r'^([1-4]|\\\\q)$', op)\n if op == \"\\\\q\":\n _menu_aws_compute()\n else:\n # Create new fresh instance\n ec2i.start_new_instance(ec2conn, amis[op], i_name)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resets an attribute of an AMI to its default value.
|
def reset_image_attribute(DryRun=None, ImageId=None, Attribute=None):
pass
|
[
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def default_attribute(self, default_attribute):\n\n self._default_attribute = default_attribute",
"def reset(self):\n self._value = self._default_value",
"def _restore_attribute(\n cls, obj: CommonTypes.MLRunInterfaceableType, attribute_name: str\n ):\n # Get the original attribute:\n original_attribute_name = cls._ORIGINAL_ATTRIBUTE_NAME.format(attribute_name)\n original_attribute = getattr(obj, original_attribute_name)\n\n # Set the attribute to point back to the original attribute:\n setattr(obj, attribute_name, original_attribute)\n\n # Remove the original backup attribute:\n setattr(obj, original_attribute_name, None)\n delattr(obj, original_attribute_name)",
"def reset(self):\n for attribute in self._trained_attributes:\n setattr(self, attribute, None)\n return None",
"def reset_value(self):\n if not isinstance(self._default_value, _NoWidgetValue):\n self.set_value(self._default_value)",
"def setZero(self):\n self.image.setZero()",
"def reset(self):\n self._opts.update(self._defaults)",
"def set_default(self, default=None):\r\n self.default = default",
"def replace_attr(self, attr, value, force = True):\r\n # One or the other\r\n if force or self.get(attr) is None:\r\n self[attr] = value",
"def reset(value):",
"def reset(self):\n self.clear()\n dict.update(self, self.defaults)",
"def set_default_node_attributes(self):\n if self._set_default_node_attribute == 'cno':\n for node in self.nodes():\n attrs = self.get_node_attributes(node)\n for k, v in attrs.items():\n self.node[node][k] = v",
"def ResetField(self):\n self._field_value = 0",
"def defaultvalue(self, defaultvalue):\n\n self._defaultvalue = defaultvalue",
"def reset(self):\n if (self.val != self.valinit):\n self.set_val(self.valinit)",
"def setInitialAttribute(self, initial: 'char const *') -> \"void\":\n return _coin.ScXMLStateElt_setInitialAttribute(self, initial)",
"def ensure_default(self):\n if self.__default_value is None:\n self.__default_value = self.value",
"def default_(self, default_):\n\n self._default_ = default_"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see NAT Instances in the Amazon Virtual Private Cloud User Guide .
|
def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):
pass
|
[
"def modify_instance_attribute(DryRun=None, InstanceId=None, Attribute=None, Value=None, BlockDeviceMappings=None, SourceDestCheck=None, DisableApiTermination=None, InstanceType=None, Kernel=None, Ramdisk=None, UserData=None, InstanceInitiatedShutdownBehavior=None, Groups=None, EbsOptimized=None, SriovNetSupport=None, EnaSupport=None):\n pass",
"def reset_state(self):\n if not self.is_active():\n return\n self.clear_alarm(\"Reset by change node config\")\n self.state.active = False",
"def reset_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def reset_network(self, ctxt, instance):\n self.msg_runner.reset_network(ctxt, instance)",
"def reset(self):\n self.state = self.env.reset()",
"def reset(targets='all'):",
"def reset_class(cls):\n cls.infected.clear()\n cls.healthy.clear()\n cls.__is_running = True",
"def reset(self):\n self._value = self._default_value",
"def soft_reset(address, name):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.reset_soft()",
"def reset(self):\n self.status = UNDEF",
"def leave_update(self):\n self.port = None\n self.flag = False\n self.ttl = 0",
"def reset_tuning(self):\n return",
"def reset(self, new_ref = False):\r\n self.action_count = 0\r\n self.img = np.zeros(np.shape(self.ref), np.uint8)\r\n #self.actions_taken = [None]\r\n self.previous_states = np.zeros((1,self.height,self.width))\r\n if new_ref == True:\r\n self.generate_ref()\r\n return",
"def reset(self, do_resets=None):\n pass",
"def reset_node(self, action):\n pass",
"def reset(self):\n printMsg('Resetting %s back to %f' % (self.scanCorPv1.pvname, self.initVal1))\n self.scanCorPv1.put(self.initVal1)\n printMsg('Resetting %s back to %f' % (self.scanCorPv2.pvname, self.initVal2))\n self.scanCorPv2.put(self.initVal2)",
"def reset(self):\n self._opts.update(self._defaults)",
"def state_reset(self):\r\n self.action = self.INIT\r\n self.status = self.COMPLETE",
"def reset(value):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Resets a network interface attribute. You can specify only one attribute at a time.
|
def reset_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, SourceDestCheck=None):
pass
|
[
"def _restore_attribute(\n cls, obj: CommonTypes.MLRunInterfaceableType, attribute_name: str\n ):\n # Get the original attribute:\n original_attribute_name = cls._ORIGINAL_ATTRIBUTE_NAME.format(attribute_name)\n original_attribute = getattr(obj, original_attribute_name)\n\n # Set the attribute to point back to the original attribute:\n setattr(obj, attribute_name, original_attribute)\n\n # Remove the original backup attribute:\n setattr(obj, original_attribute_name, None)\n delattr(obj, original_attribute_name)",
"def reset_image_attribute(DryRun=None, ImageId=None, Attribute=None):\n pass",
"def reset_instance_attribute(DryRun=None, InstanceId=None, Attribute=None):\n pass",
"def reset_network(self, ctxt, instance):\n self.msg_runner.reset_network(ctxt, instance)",
"def modify_network_interface_attribute(DryRun=None, NetworkInterfaceId=None, Description=None, SourceDestCheck=None, Groups=None, Attachment=None):\n pass",
"def reset_interface_nicid(self):\n return self.data.get('reset_interface_nicid')",
"def clear_network(net_index: int):\n _controller.clear_network(net_index)",
"def remove_attribute(self, attr):\n self.sender.graph_attr_removed(self.source_id_buff, self.time_id, attr)\n self.time_id += 1",
"def ModifyNetworkInterfaceAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyNetworkInterfaceAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyNetworkInterfaceAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def reset_device(self):\n\t\treturn self.send_byte([0xF0, 0x00, 0x00])",
"def reset(self, state=None):\n self.channel_reset(state)\n #print \"broadcast reset on\",self.name\n self.emit('reset', self.channel_state())",
"def reset_imu(self):\n\t\treturn self.send_byte([0xFA, 0x00, 0x00])",
"def reset(self):\n return CALL('ResetDevice',self)",
"def change_macaddr(interface: str, new_macaddr: str) -> None:\n subprocess.call(['ifconfig', interface, 'down'])\n subprocess.call(['ifconfig', interface, 'hw', 'ether', new_macaddr])\n subprocess.call(['ifconfig', interface, 'up'])",
"def remove_edge_attribute(self, edge, attr):\n self.sender.edge_attr_removed(self.source_id_buff, self.time_id, edge, attr)\n self.time_id += 1",
"def disable_network(self):\n if self._is_admin():\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Wi-Fi\"', 'disable'])\n print(\"Disable Wi-Fi \", completed.returncode)\n completed = subprocess.run(args=['netsh', 'interface', 'set', 'interface', '\"Ethernet\"', 'disable'])\n print(\"Disable Ethernet\", completed.returncode)\n else:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Wi-Fi\" disable', None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", 'netsh', ' interface set interface \"Ethernet\" disable', None, 1)",
"def soft_reset(address, name):\n explore = explorepy.explore.Explore()\n explore.connect(mac_address=address, device_name=name)\n explore.reset_soft()",
"def clearAdminIface(self, ifaceJson, node):\n for iface in ifaceJson:\n if iface['mac'] == node.macs['admin']:\n iface['assigned_networks'] = [{\n \"id\": 1,\n \"name\": \"fuelweb_admin\"\n }]",
"def reset(self):\n for attribute in self._trained_attributes:\n setattr(self, attribute, None)\n return None",
"def decr_attr(self, name, value = 1):\n try:\n self.attributes_dict[name] -= value\n except ValueError:\n print 'Expected a numerical value'"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Restores an Elastic IP address that was previously moved to the EC2VPC platform back to the EC2Classic platform. You cannot move an Elastic IP address that was originally allocated for use in EC2VPC. The Elastic IP address must not be associated with an instance or network interface.
|
def restore_address_to_classic(DryRun=None, PublicIp=None):
pass
|
[
"def ex_release_public_ip(self, address):\r\n return self.driver.ex_release_public_ip(self, address)",
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def _assign_secondary_ip_():\n interface_idx = 0\n node = env.nodes[0]\n cidr='%s/%s' % (env.secondary_ip,env.secondary_ip_cidr_prefix_size)\n\n if (_get_secondary_ip_node_().id == node.id):\n debug(\"VPC Secondary IP %s already assigned to %s\" % (cidr, pretty_instance(node)))\n else:\n info(\"Assigning VPC Secondary IP %s to %s\" % (cidr, pretty_instance(node)))\n connect().assign_private_ip_addresses(node.interfaces[interface_idx].id, env.secondary_ip, allow_reassignment=True)\n # Notify opsys that it has a new address (This seems to only happen automatically with Elastic IPs). Write to /etc to make persistent.\n has_address = run('ip addr | grep %s' % cidr, quiet=True)\n if not has_address:\n sudo('ip addr add %s dev eth0' % cidr)\n append('/etc/network/interfaces','up ip addr add %s dev eth%d' % (cidr,interface_idx),use_sudo=True)",
"def delete_elastic_ips():\n client = boto3.client('ec2')\n print('Deleting Elastic IPs')\n for eip in client.describe_addresses()['Addresses']:\n allocation_id = eip['AllocationId']\n print('Releasing EIP {}'.format(allocation_id))\n client.release_address(\n AllocationId=allocation_id\n )\n\n print('Elastic IPs deleted')",
"def assign_elastic_ip(node = None, elastic_ip=None):\n node = node or env.nodes[0]\n elastic_ip = elastic_ip or env.elastic_ip\n if elastic_ip == ip_address(node):\n debug(\"ElasticIP %s already assigned to %s\" % (elastic_ip, pretty_instance(node)))\n else:\n info(\"Assigning ElasticIP %s to %s\" % (elastic_ip, pretty_instance(node)))\n connect().associate_address(node.id, elastic_ip)",
"def ElasticIps(self, zone = None):\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n return self.reservation",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def PrivateIPAddressing(self, zone = None):\n self.private_addressing = True\n if zone is None:\n zone = self.zone\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name, private_addressing=self.private_addressing, zone=zone)\n self.tester.sleep(10)\n for instance in self.reservation.instances:\n address = self.tester.allocate_address()\n self.assertTrue(address,'Unable to allocate address')\n self.assertTrue(self.tester.associate_address(instance, address))\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.disassociate()\n self.tester.sleep(30)\n instance.update()\n self.assertTrue( self.tester.ping(instance.public_dns_name), \"Could not ping instance with new IP\")\n address.release()\n if (instance.public_dns_name != instance.private_dns_name):\n self.tester.critical(\"Instance received a new public IP: \" + instance.public_dns_name)\n return self.reservation",
"def restore(target_ip=\"10.0.2.1\", target_mac=\"\", des_ip=\"10.0.2.1\"):\n # Op=2 para response, no request\n # pdst=\"10.0.2.15\" .. la dir ip target\n # hwdst=\"08:00:27:e7:53:c8\" target mac\n # psrc=\"10.0.2.1\" router ip\n if target_mac == \"\":\n target_mac = scan(target_ip)[0][\"mac\"]\n\n des_mac = scan(des_ip)[0][\"mac\"]\n\n catch = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=des_ip,\n hwsrc=des_mac)\n scapy.send(catch, count=4, verbose=False)",
"def ex_release_address(self, elastic_ip, domain=None):\r\n params = {'Action': 'ReleaseAddress'}\r\n\r\n if domain is not None and domain != 'vpc':\r\n raise AttributeError('Domain can only be set to vpc')\r\n\r\n if domain is None:\r\n params['PublicIp'] = elastic_ip.ip\r\n else:\r\n params['AllocationId'] = elastic_ip.extra['allocation_id']\r\n\r\n response = self.connection.request(self.path, params=params).object\r\n return self._get_boolean(response)",
"def release_elastic_ip(self, eip):\n\n eip_obj = None\n try:\n eip_obj = self.conn.get_all_addresses(addresses=[eip])[0]\n except IndexError:\n return True\n\n if eip_obj:\n retries=0\n done=False\n while not done and retries < 3:\n try:\n status=eip_obj.release()\n done=True\n except:\n retries+=1\n time.sleep(15)\n try:\n eip_obj = self.conn.get_all_addresses(addresses=[eip])[0]\n except IndexError:\n return True\n\n if not done:\n return False\n\n if status:\n del self.eip_obj_dict[eip]\n \n return status\n\n else:\n return False",
"def restore(target_ip, host_ip, verbose=True):\n # get the real MAC address of target\n target_mac = get_mac(target_ip)\n # get the real MAC address of spoofed (gateway, i.e router)\n host_mac = get_mac(host_ip)\n # crafting the restoring packet\n arp_response = ARP(pdst=target_ip, hwdst=target_mac, psrc=host_ip, hwsrc=host_mac, op=\"is-at\")\n # sending the restoring packet\n # to restore the network to its normal process\n # we send each reply seven times for a good measure (count=7)\n send(arp_response, verbose=0, count=7)\n if verbose:\n print(\"[+] Sent to {} : {} is-at {}\".format(target_ip, host_ip, host_mac))",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def restart() -> None:\n config = load_config_file()\n instance_ips = [i.public_ip_address for i in get_running_instances(config)]\n if not instance_ips:\n raise Exception('ERROR: No instances with public IPs found. Exiting.')\n try:\n execute_commands_on_linux_instances(\n config,\n [\n COMMAND_KILL,\n COMMAND_CLEAN,\n COMMAND_DOWNLOAD,\n COMMAND_START\n ],\n instance_ips\n )\n except Exception as e:\n logging.error(\"Something went wrong.\")\n raise\n logging.info('Done!')",
"def ReuseAddresses(self, zone = None):\n prev_address = None\n if zone is None:\n zone = self.zone\n ### Run the test 5 times in a row\n for i in xrange(5):\n self.reservation = self.tester.run_instance(keypair=self.keypair.name, group=self.group.name, zone=zone)\n for instance in self.reservation.instances:\n if prev_address is not None:\n self.assertTrue(re.search(str(prev_address) ,str(instance.public_dns_name)), str(prev_address) +\" Address did not get reused but rather \" + str(instance.public_dns_name))\n prev_address = instance.public_dns_name\n self.tester.terminate_instances(self.reservation)",
"def reverse_IP(self):\n pass",
"def set_cidr_ip(value, yaml_file):\n\n new_ports = [22, {4506: {\"cidr-ip\": value}}, {4505: {\"cidr-ip\": value}} ]\n\n print \"setting cidr_ip \" + value\n yaml_content = get_yaml(yaml_file)\n yaml_content[\"master-server\"][\"aws\"][\"ports\"] = new_ports\n write_yaml(yaml_content, yaml_file)",
"def set_subnet_cidr(value, yaml_file):\n yaml_content = get_yaml(elife_global_yaml)\n yaml_content[\"defaults\"][\"aws\"][\"subnet-cidr\"] = value\n write_yaml(yaml_content, yaml_file)",
"def associate_address(DryRun=None, InstanceId=None, PublicIp=None, AllocationId=None, NetworkInterfaceId=None, PrivateIpAddress=None, AllowReassociation=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[EC2VPC only] Removes one or more egress rules from a security group for EC2VPC. This action doesn't apply to security groups for use in EC2Classic. The values that you specify in the revoke request (for example, ports) must match the existing rule's values for the rule to be revoked. Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur.
|
def revoke_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):
pass
|
[
"def revoke_security_group_ingress(DryRun=None, GroupName=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def delete_security_groups():\n print('Deleting Security Groups')\n client = boto3.resource('ec2')\n for security_group in client.security_groups.all():\n print('Deleting Security Group rules for security group {}'.format(security_group.id))\n for perm in security_group.ip_permissions:\n security_group.revoke_ingress(\n IpPermissions=[perm]\n )\n for perm in security_group.ip_permissions_egress:\n security_group.revoke_egress(\n IpPermissions=[perm]\n )\n for security_group in client.security_groups.all():\n if security_group.group_name != 'default':\n print('Deleting Security Group {}'.format(security_group.id))\n security_group.delete()\n print('Security Groups deleted')",
"def authorize_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def revoke(rule, owner):\n conn = connect_to_region(rule['region'])\n if type(rule['port/type']) is tuple:\n from_port, to_port = rule['port/type']\n else:\n from_port = rule['port/type']\n to_port = from_port\n if '/' in rule['source']: ### source is a CIDR address\n return conn.revoke_security_group(rule['target'],\n ip_protocol=rule['protocol'],\n from_port=from_port,\n to_port=to_port,\n cidr_ip=rule['source'])\n return conn.revoke_security_group(rule['target'],\n src_security_group_name=rule['source'],\n src_security_group_owner_id=owner,\n ip_protocol=rule['protocol'],\n from_port=from_port,\n to_port=to_port)",
"def remove_sg_inbound_rule(self):\n try:\n vpc = self.ec2_client.Vpc(id=self.cluster_props['VpcId'])\n sg_list = list(vpc.security_groups.all())\n for sg in sg_list:\n if sg.group_id == self.security_group_id:\n sg.authorize_ingress(\n GroupName=sg.group_name,\n CidrIp='0.0.0.0/0',\n IpProtocol='TCP',\n FromPort=int(self.dwh_port),\n ToPort=int(self.dwh_port))\n continue\n except Exception as e:\n print(e)",
"def delete_egress_only_internet_gateways():\n client = boto3.client('ec2')\n print('Deleting Egress Only Internet Gateways')\n gw_resp = client.describe_egress_only_internet_gateways()\n while True:\n for gateway in gw_resp['EgressOnlyInternetGateways']:\n gw_id = gateway['EgressOnlyInternetGatewayId']\n client.delete_egress_only_internet_gateway(\n EgressOnlyInternetGatewayId=gw_id\n )\n if 'NextMarker' in gw_resp:\n gw_resp = client.describe_egress_only_internet_gateways(\n Marker=gw_resp['NextMarker'],\n )\n else:\n break\n while client.describe_egress_only_internet_gateways()['EgressOnlyInternetGateways']:\n time.sleep(5)\n print('Egress Only Internet Gateways deleted')",
"def revoke_ip_permission(\n self, group_name, ip_protocol, from_port, to_port, cidr_ip):\n d = self.revoke_security_group(\n group_name,\n ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,\n cidr_ip=cidr_ip)\n return d",
"def AddVpcNetworkGroupFlags(parser, resource_kind='service', is_update=False):\n group = parser.add_argument_group('Direct VPC egress setting flags group.')\n AddVpcNetworkFlags(group, resource_kind)\n AddVpcSubnetFlags(group, resource_kind)\n if not is_update:\n AddVpcNetworkTagsFlags(group, resource_kind)\n return\n tags_group = group.add_mutually_exclusive_group()\n AddVpcNetworkTagsFlags(tags_group, resource_kind)\n AddClearVpcNetworkTagsFlags(tags_group, resource_kind)",
"def delete_vpc_endpoint_resources():\n print('Deleting VPC endpoints')\n ec2 = boto3.client('ec2')\n endpoint_ids = []\n for endpoint in ec2.describe_vpc_endpoints()['VpcEndpoints']:\n print('Deleting VPC Endpoint - {}'.format(endpoint['ServiceName']))\n endpoint_ids.append(endpoint['VpcEndpointId'])\n\n if endpoint_ids:\n ec2.delete_vpc_endpoints(\n VpcEndpointIds=endpoint_ids\n )\n\n print('Waiting for VPC endpoints to get deleted')\n while ec2.describe_vpc_endpoints()['VpcEndpoints']:\n time.sleep(5)\n\n print('VPC endpoints deleted')\n\n # VPC endpoints connections\n print('Deleting VPC endpoint connections')\n service_ids = []\n for connection in ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n service_id = connection['ServiceId']\n state = connection['VpcEndpointState']\n\n if state in ['PendingAcceptance', 'Pending', 'Available', 'Rejected', 'Failed', 'Expired']:\n print('Deleting VPC Endpoint Service - {}'.format(service_id))\n service_ids.append(service_id)\n\n ec2.reject_vpc_endpoint_connections(\n ServiceId=service_id,\n VpcEndpointIds=[\n connection['VpcEndpointId'],\n ]\n )\n\n if service_ids:\n ec2.delete_vpc_endpoint_service_configurations(\n ServiceIds=service_ids\n )\n\n print('Waiting for VPC endpoint services to be destroyed')\n while ec2.describe_vpc_endpoint_connections()['VpcEndpointConnections']:\n time.sleep(5)\n\n print('VPC endpoint connections deleted')",
"def cli(env, securitygroup_id):\n mgr = SoftLayer.NetworkManager(env.client)\n if not mgr.delete_securitygroup(securitygroup_id):\n raise exceptions.CLIAbort(\"Failed to delete security group\")",
"def delete_security_group_rule(self, context, sgr_id):\n try:\n self.drv.delete_security_group_rule(context, sgr_id)\n except Exception:\n LOG.exception('Failed to delete Security Group rule %s' % sgr_id)",
"def test_050_create_security_groups(self):\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"WebServerSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.web_security_group = sg\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"NATSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.nat_security_group = sg\n sg = self.vpc_client.create_security_group(\n data_utils.rand_name(\"DBServerSG-\"),\n data_utils.rand_name(\"description \"),\n self.ctx.vpc.id)\n self.assertIsNotNone(sg)\n self.assertTrue(sg.id)\n self.addResourceCleanUp(self._destroy_security_group_wait, sg)\n self.ctx.db_security_group = sg\n\n sg = self.ctx.web_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 1433, 1433,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 3306, 3306,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 22, 22,\n src_group_id=self.ctx.db_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=80, to_port=80,\n cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=443, to_port=443,\n cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=22, to_port=22,\n cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=3389,\n to_port=3389, cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n\n sg = self.ctx.nat_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 443, 443, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"udp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=53,\n to_port=53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"udp\", from_port=53,\n to_port=53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=80, to_port=80,\n cidr_ip=str(self.db_subnet))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=443, to_port=443,\n cidr_ip=str(self.db_subnet))\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\", from_port=22, to_port=22,\n cidr_ip=str(self.test_client_cidr))\n self.assertTrue(status)\n\n sg = self.ctx.db_security_group\n status = self.vpc_client.revoke_security_group_egress(\n sg.id, \"-1\", cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 80, 80, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 443, 443, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"tcp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group_egress(\n sg.id, \"udp\", 53, 53, cidr_ip=\"0.0.0.0/0\")\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=1433,\n to_port=1433,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=3306,\n to_port=3306,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)\n # NOTE(ft): especially for connectivity test\n status = self.vpc_client.authorize_security_group(\n group_id=sg.id, ip_protocol=\"tcp\",\n from_port=22,\n to_port=22,\n src_security_group_group_id=self.ctx.web_security_group.id)\n self.assertTrue(status)",
"def ValidateClearVpcConnector(service, args):\n if (service is None or\n not flags.FlagIsExplicitlySet(args, 'clear_vpc_connector') or\n not args.clear_vpc_connector):\n return\n\n if flags.FlagIsExplicitlySet(args, 'vpc_egress'):\n egress = args.vpc_egress\n elif container_resource.EGRESS_SETTINGS_ANNOTATION in service.template_annotations:\n egress = service.template_annotations[\n container_resource.EGRESS_SETTINGS_ANNOTATION]\n else:\n # --vpc-egress flag not specified and egress settings not set on service.\n return\n\n if (egress != container_resource.EGRESS_SETTINGS_ALL and\n egress != container_resource.EGRESS_SETTINGS_ALL_TRAFFIC):\n return\n\n if console_io.CanPrompt():\n console_io.PromptContinue(\n message='Removing the VPC connector from this service will clear the '\n 'VPC egress setting and route outbound traffic to the public internet.',\n default=False,\n cancel_on_no=True)\n else:\n raise exceptions.ConfigurationError(\n 'Cannot remove VPC connector with VPC egress set to \"{}\". Set'\n ' `--vpc-egress=private-ranges-only` or run this command '\n 'interactively and provide confirmation to continue.'.format(egress))",
"def delete( # pylint: disable=inconsistent-return-statements\n self,\n resource_group_name: str,\n network_security_perimeter_name: str,\n profile_name: str,\n access_rule_name: str,\n **kwargs: Any\n ) -> None:\n error_map = {\n 401: ClientAuthenticationError,\n 404: ResourceNotFoundError,\n 409: ResourceExistsError,\n 304: ResourceNotModifiedError,\n }\n error_map.update(kwargs.pop(\"error_map\", {}) or {})\n\n _headers = kwargs.pop(\"headers\", {}) or {}\n _params = case_insensitive_dict(kwargs.pop(\"params\", {}) or {})\n\n api_version: str = kwargs.pop(\n \"api_version\", _params.pop(\"api-version\", self._api_version or \"2021-02-01-preview\")\n )\n cls: ClsType[None] = kwargs.pop(\"cls\", None)\n\n request = build_nsp_access_rules_delete_request(\n resource_group_name=resource_group_name,\n network_security_perimeter_name=network_security_perimeter_name,\n profile_name=profile_name,\n access_rule_name=access_rule_name,\n subscription_id=self._config.subscription_id,\n api_version=api_version,\n template_url=self.delete.metadata[\"url\"],\n headers=_headers,\n params=_params,\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n _stream = False\n pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access\n request, stream=_stream, **kwargs\n )\n\n response = pipeline_response.http_response\n\n if response.status_code not in [200, 204]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n if cls:\n return cls(pipeline_response, None, {})",
"def modify_vpc_endpoint(DryRun=None, VpcEndpointId=None, ResetPolicy=None, PolicyDocument=None, AddRouteTableIds=None, RemoveRouteTableIds=None):\n pass",
"def DeleteSecurityGroup(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DeleteSecurityGroup\", params, headers=headers)\n response = json.loads(body)\n model = models.DeleteSecurityGroupResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def remove_securitygroup_rules(self, group_id, rules):\n return self.security_group.removeRules(rules, id=group_id)",
"def delete(self, api_client):\n cmd = {'id': self.id}\n api_client.deleteEgressFirewallRule(**cmd)\n return",
"def create_egress_only_internet_gateway(DryRun=None, VpcId=None, ClientToken=None):\n pass"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Removes one or more ingress rules from a security group. The values that you specify in the revoke request (for example, ports) must match the existing rule's values for the rule to be removed. Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur.
|
def revoke_security_group_ingress(DryRun=None, GroupName=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):
pass
|
[
"def revoke_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def remove_securitygroup_rules(self, group_id, rules):\n return self.security_group.removeRules(rules, id=group_id)",
"def delete_security_groups():\n print('Deleting Security Groups')\n client = boto3.resource('ec2')\n for security_group in client.security_groups.all():\n print('Deleting Security Group rules for security group {}'.format(security_group.id))\n for perm in security_group.ip_permissions:\n security_group.revoke_ingress(\n IpPermissions=[perm]\n )\n for perm in security_group.ip_permissions_egress:\n security_group.revoke_egress(\n IpPermissions=[perm]\n )\n for security_group in client.security_groups.all():\n if security_group.group_name != 'default':\n print('Deleting Security Group {}'.format(security_group.id))\n security_group.delete()\n print('Security Groups deleted')",
"def remove_sg_inbound_rule(self):\n try:\n vpc = self.ec2_client.Vpc(id=self.cluster_props['VpcId'])\n sg_list = list(vpc.security_groups.all())\n for sg in sg_list:\n if sg.group_id == self.security_group_id:\n sg.authorize_ingress(\n GroupName=sg.group_name,\n CidrIp='0.0.0.0/0',\n IpProtocol='TCP',\n FromPort=int(self.dwh_port),\n ToPort=int(self.dwh_port))\n continue\n except Exception as e:\n print(e)",
"def revoke(rule, owner):\n conn = connect_to_region(rule['region'])\n if type(rule['port/type']) is tuple:\n from_port, to_port = rule['port/type']\n else:\n from_port = rule['port/type']\n to_port = from_port\n if '/' in rule['source']: ### source is a CIDR address\n return conn.revoke_security_group(rule['target'],\n ip_protocol=rule['protocol'],\n from_port=from_port,\n to_port=to_port,\n cidr_ip=rule['source'])\n return conn.revoke_security_group(rule['target'],\n src_security_group_name=rule['source'],\n src_security_group_owner_id=owner,\n ip_protocol=rule['protocol'],\n from_port=from_port,\n to_port=to_port)",
"def delete_security_group_rule(self, context, sgr_id):\n try:\n self.drv.delete_security_group_rule(context, sgr_id)\n except Exception:\n LOG.exception('Failed to delete Security Group rule %s' % sgr_id)",
"def delete( # pylint: disable=inconsistent-return-statements\n self,\n resource_group_name: str,\n network_security_perimeter_name: str,\n profile_name: str,\n access_rule_name: str,\n **kwargs: Any\n ) -> None:\n error_map = {\n 401: ClientAuthenticationError,\n 404: ResourceNotFoundError,\n 409: ResourceExistsError,\n 304: ResourceNotModifiedError,\n }\n error_map.update(kwargs.pop(\"error_map\", {}) or {})\n\n _headers = kwargs.pop(\"headers\", {}) or {}\n _params = case_insensitive_dict(kwargs.pop(\"params\", {}) or {})\n\n api_version: str = kwargs.pop(\n \"api_version\", _params.pop(\"api-version\", self._api_version or \"2021-02-01-preview\")\n )\n cls: ClsType[None] = kwargs.pop(\"cls\", None)\n\n request = build_nsp_access_rules_delete_request(\n resource_group_name=resource_group_name,\n network_security_perimeter_name=network_security_perimeter_name,\n profile_name=profile_name,\n access_rule_name=access_rule_name,\n subscription_id=self._config.subscription_id,\n api_version=api_version,\n template_url=self.delete.metadata[\"url\"],\n headers=_headers,\n params=_params,\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n _stream = False\n pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access\n request, stream=_stream, **kwargs\n )\n\n response = pipeline_response.http_response\n\n if response.status_code not in [200, 204]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response, error_format=ARMErrorFormat)\n\n if cls:\n return cls(pipeline_response, None, {})",
"def DeleteAlertRules(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DeleteAlertRules\", params, headers=headers)\n response = json.loads(body)\n model = models.DeleteAlertRulesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def refresh_security_group_rules(self, *args, **kwargs):\n raise NotImplementedError()",
"def revoke_ip_permission(\n self, group_name, ip_protocol, from_port, to_port, cidr_ip):\n d = self.revoke_security_group(\n group_name,\n ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,\n cidr_ip=cidr_ip)\n return d",
"def remove_all_acl_rules(self):\n AC.delete_all_l2_acl_policies(self)\n AC.delete_all_l3_acl_policies(self)\n AC.delete_all_l3_ipv6_acl_policies(self)",
"def clear_iptables():\n\n # WAT: This task wouldn't be necessary if cotton's firewall task reset the firewall before\n # applying its own rules. Ho hum.\n\n # 1 DROP tcp -- anywhere anywhere tcp dpt:http\n res = system.sudo(\"iptables -L INPUT --line-numbers |tail -n +3\")\n for l in res.split(\"\\n\"):\n try:\n (num, action, proto, opt, src, dest, foo, rule) = l.split()\n except ValueError:\n continue\n if action != 'DROP':\n continue\n system.sudo(\"iptables -D INPUT %s\" % num)",
"def delete_ipv6_acl_rule_bulk(self, **kwargs):\n # Validate required and accepted kwargs\n params_validator.validate_params_mlx_delete_ipv6_rule_acl(**kwargs)\n\n acl_name = self.mac.parse_acl_name(**kwargs)\n\n ret = self.get_acl_address_and_acl_type(acl_name)\n address_type = ret['protocol']\n\n if address_type != 'ipv6':\n raise ValueError(\"IPv6 Rule can not be deleted from non-ipv6 ACL.\"\n \"ACL {} is of type {}\"\n .format(acl_name, address_type))\n\n # Get already configured seq_ids\n configured_seq_ids = self.get_configured_seq_ids(acl_name,\n address_type)\n seq_range = self.mac.parse_seq_id_by_range(configured_seq_ids,\n **kwargs)\n\n cli_arr = ['ipv6 access-list ' + acl_name]\n\n for seq_id in seq_range:\n cli_arr.append('no sequence ' + str(seq_id))\n\n output = self._callback(cli_arr, handler='cli-set')\n return self._process_cli_output(inspect.stack()[0][3],\n str(cli_arr), output)",
"def delete_security_group_rule(rule):\n return IMPL.delete_security_group_rule(rule)",
"def delete(self, api_client):\n cmd = {'id': self.id}\n api_client.deleteEgressFirewallRule(**cmd)\n return",
"def authorize_security_group_egress(DryRun=None, GroupId=None, SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None, IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions=None):\n pass",
"def test_008(self):\n HEADING()\n command = \"cm secgroup rules-delete --cloud={cloud} test-group --all\"\n\n result = run(command.format(**self.data))\n assert \"Rule [443 | 443 | tcp | 0.0.0.0/0] deleted\" in result\n\n return",
"def delete_network_acl_entry(DryRun=None, NetworkAclId=None, RuleNumber=None, Egress=None):\n pass",
"def DisassociateNetworkInterfaceSecurityGroups(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"DisassociateNetworkInterfaceSecurityGroups\", params, headers=headers)\n response = json.loads(body)\n model = models.DisassociateNetworkInterfaceSecurityGroupsResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Launches the specified Scheduled Instances. Before you can launch a Scheduled Instance, you must purchase it and obtain an identifier using PurchaseScheduledInstances . You must launch a Scheduled Instance during its scheduled time period. You can't stop or reboot a Scheduled Instance, but you can terminate it as needed. If you terminate a Scheduled Instance before the current scheduled time period ends, you can launch it again after a few minutes. For more information, see Scheduled Instances in the Amazon Elastic Compute Cloud User Guide .
|
def run_scheduled_instances(DryRun=None, ClientToken=None, InstanceCount=None, ScheduledInstanceId=None, LaunchSpecification=None):
pass
|
[
"def run_instances(self):\n # create an entry in the s3 log for the start of this task \n self.log_to_s3('run-instances-start.log', 'start')\n\n session = botocore.session.get_session()\n client = session.create_client('ec2', region_name=self.aws_region)\n\n # convert user-data to base64\n user_data = ''\n # NOTE conversion of file to string, then string to bytes, the bytes encoded \n # base64 - then decode the base64 bytes into base64 string\n with open(self.ec2_user_data, 'r') as f:\n user_data = base64.b64encode(bytes(f.read(), \"utf-8\")).decode(\"utf-8\")\n\n if self.ec2_type in (CONST.VALID_EC2_INSTANCE_TYPES_EBS_ONLY).split('|'):\n # block device mapping for ebs backed instances\n # creates an ephemeral EBS volume (delete on terminate)\n # Note that gp2 instance type is EBS SSD\n custom_block_device_mapping = [{\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0',\n 'Ebs':{\n 'VolumeSize': self.ec2_ebs_only_volume_size,\n 'VolumeType': self.ec2_ebs_only_volume_type,\n },\n }]\n else:\n # block device mapping allows for 2 extra drives\n # - works for either single ssd or 2 ssd's\n custom_block_device_mapping = [ \n {\n 'DeviceName': '/dev/sdb',\n 'VirtualName': 'ephemeral0'\n },\n {\n 'DeviceName': '/dev/sdc',\n 'VirtualName': 'ephemeral1'\n }\n ]\n\n r = client.request_spot_instances(\n InstanceCount=self.ec2_count,\n SpotPrice=self.ec2_spot_price,\n LaunchSpecification= {\n 'SecurityGroupIds': [\n self.ec2_security_group_id,\n ],\n 'SecurityGroups': [\n self.ec2_security_groups,\n ],\n 'Placement': {\n 'AvailabilityZone': self.ec2_availability_zone,\n },\n 'BlockDeviceMappings': custom_block_device_mapping,\n 'IamInstanceProfile': {\n 'Arn': self.ec2_arn_id,\n },\n 'UserData': user_data,\n 'ImageId': self.ec2_image_id,\n 'InstanceType': self.ec2_type,\n 'KeyName': self.ec2_security_key,\n },\n )\n\n # get the spot instance request ids\n spot_ids = []\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Spot request ids:'))\n for i, spot_inst in enumerate(r['SpotInstanceRequests']):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, \n inst_str + '\\t' + spot_inst['SpotInstanceRequestId']))\n spot_ids.append(spot_inst['SpotInstanceRequestId'])\n utility.list_to_file(CONST.SPOT_REQUEST_IDS, spot_ids)\n\n # create a list of spot instance statuses - so we can print out\n # some updates to the user\n spot_status = ['']*len(spot_ids)\n # Expecting status codes of \"pending-evaluation\", \"pending-fulfillment\", or \n # fulfilled. Any other status-code should be printed out & the program \n # terminated.\n expected_status = ['fulfilled', 'pending-evaluation', 'pending-fulfillment']\n instance_ids = [None]*len(spot_ids)\n\n # check the status of the spot requests\n while True:\n fulfilled = 0\n for i, id in enumerate(spot_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_spot_instance_requests(SpotInstanceRequestIds=[id])\n status_code = r['SpotInstanceRequests'][0]['Status']['Code']\n if status_code not in expected_status:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, 'Unexpected status for spot request ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': ') +\n colour_msg(Colour.PURPLE, status_code))\n sys.exit(1)\n if status_code != spot_status[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Spot instance request: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tStatus: ') +\n colour_msg(Colour.PURPLE, status_code))\n spot_status[i] = status_code\n if status_code == 'fulfilled':\n fulfilled += 1\n # record the instance id\n instance_ids[i] = r['SpotInstanceRequests'][0]['InstanceId']\n if fulfilled == len(spot_ids):\n break\n time.sleep(1)\n\n utility.list_to_file(CONST.INSTANCE_IDS, instance_ids)\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ids:'))\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n tag_val = self.ec2_instance_tag + str(i)\n client.create_tags(Resources=[id], Tags=[{'Key':'Name', 'Value':tag_val}])\n\n # monitor the instances until all running\n instance_states = ['']*len(instance_ids)\n expected_states = ['running', 'pending']\n instance_ips = [None]*len(instance_ids)\n running = 0\n while True:\n running = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instances(InstanceIds=[id])\n state = r['Reservations'][0]['Instances'][0]['State']['Name']\n if state not in expected_states:\n lgr.error(CONST.ERROR + \n colour_msg(Colour.CYAN, \n 'Unexpected instance state for instance-id ') +\n colour_msg(Colour.PURPLE, id) +\n colour_msg(Colour.CYAN, ': \\t') +\n colour_msg(Colour.PURPLE, state))\n sys.exit(1)\n if state != instance_states[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tState: ') +\n colour_msg(Colour.PURPLE, state))\n instance_states[i] = state\n if state == 'running':\n running += 1\n # record the instance id\n instance_ips[i] = r['Reservations'][0]['Instances'][0]['PublicDnsName']\n if running == len(instance_ids):\n break\n time.sleep(10)\n\n lgr.debug(CONST.DEBUG + colour_msg(Colour.CYAN, 'Instance Ips:'))\n for i, id in enumerate(instance_ips):\n inst_str = '[' + str(i) + ']'\n lgr.debug(CONST.DEBUG + colour_msg(Colour.PURPLE, inst_str + '\\t' + id))\n \n utility.list_to_file(CONST.INSTANCE_IPS_FILE, instance_ips)\n # need to at least wait until all the instances are reachable\n # possible statuses: (passed | failed | initializing | insufficient-data )\n reachability = ['']*len(instance_ids)\n while True:\n passed = 0\n for i, id in enumerate(instance_ids):\n inst_str = '[' + str(i) + ']'\n r = client.describe_instance_status(InstanceIds=[id])\n state = r['InstanceStatuses'][0]['InstanceStatus']['Details'][0]['Status']\n if state != reachability[i]:\n lgr.debug(CONST.DEBUG + \n colour_msg(Colour.CYAN, 'Instance id: ') +\n colour_msg(Colour.PURPLE, inst_str) +\n colour_msg(Colour.CYAN, '\\tReachability: ') +\n colour_msg(Colour.PURPLE, state))\n reachability[i] = state\n if state == 'passed':\n passed += 1\n if passed == len(instance_ids):\n break\n time.sleep(10)\n \n lgr.info(CONST.INFO + colour_msg(Colour.GREEN, 'Instances are reachable'))\n \n # if user-data configuration file supplied - check that it has worked\n # Note that this checker is run once on each instance\n if self.ec2_user_data:\n lgr.info(CONST.INFO + colour_msg(Colour.CYAN, \n 'Starting job to monitor user-data configuration...'))\n # at the moment is calling a local script that does the checking\n result = subprocess.call('./' + self.ec2_user_data_check) \n if result:\n lgr.error(CONST.ERROR + colour_msg(Colour.CYAN, \n 'user data checker FAILED'))\n sys.exit(1)\n\n # create an entry in the s3 log for finish this task \n self.log_to_s3('run-instances-finish.log', 'finish')\n\n # return the list of ip's for the newly created instances\n return utility.file_to_list(CONST.INSTANCE_IPS_FILE)",
"def reboot_instances(DryRun=None, InstanceIds=None):\n pass",
"def start():\n local('aws ec2 start-instances --instance-ids %s'%(AWS_INSTANCE_ID))",
"def instances_start(cfg: Config):\n print(\"Starting version %s\", describe_current_release(cfg))\n exec_remote_all(pick_instances(cfg), [\"sudo\", \"systemctl\", \"start\", \"compiler-explorer\"])",
"def purchase_scheduled_instances(DryRun=None, ClientToken=None, PurchaseRequests=None):\n pass",
"def describe_scheduled_instances(DryRun=None, ScheduledInstanceIds=None, SlotStartTimeRange=None, NextToken=None, MaxResults=None, Filters=None):\n pass",
"def create_reserved_instances_listing(ReservedInstancesId=None, InstanceCount=None, PriceSchedules=None, ClientToken=None):\n pass",
"def restart() -> None:\n config = load_config_file()\n instance_ips = [i.public_ip_address for i in get_running_instances(config)]\n if not instance_ips:\n raise Exception('ERROR: No instances with public IPs found. Exiting.')\n try:\n execute_commands_on_linux_instances(\n config,\n [\n COMMAND_KILL,\n COMMAND_CLEAN,\n COMMAND_DOWNLOAD,\n COMMAND_START\n ],\n instance_ips\n )\n except Exception as e:\n logging.error(\"Something went wrong.\")\n raise\n logging.info('Done!')",
"def run_instances(region, boto3_config, run_instances_kwargs):\n try:\n from slurm_plugin.overrides import run_instances\n\n logger.info(\"Launching instances with run_instances override API. Parameters: %s\", run_instances_kwargs)\n return run_instances(region=region, boto3_config=boto3_config, **run_instances_kwargs)\n except ImportError:\n logger.info(\"Launching instances with run_instances API. Parameters: %s\", run_instances_kwargs)\n ec2_client = boto3.client(\"ec2\", region_name=region, config=boto3_config)\n return ec2_client.run_instances(**run_instances_kwargs)",
"def start_cluster(aws_instances: List[AWSInstance], region: str):\n\n instances_ids = [x.id for x in aws_instances]\n print(\"Found the following stopped instances to start: {}\".format(list(str(i) for i in instances)))\n ec2 = boto3.client(\"ec2\", region_name=region)\n return ec2.start_instances(InstanceIds=instances_ids)",
"def ec2_schedule(schedule_action, tag_key, tag_value):\n if schedule_action == \"stop\":\n ec2_stop_instances(tag_key, tag_value)\n elif schedule_action == \"start\":\n ec2_start_instances(tag_key, tag_value)\n else:\n logging.error(\"Bad scheduler action\")",
"def ec2_start_instances(tag_key, tag_value):\n ec2 = boto3.client(\"ec2\")\n\n for ec2_instance in ec2_list_instances(tag_key, tag_value):\n try:\n ec2.start_instances(InstanceIds=[ec2_instance])\n print(\"Start instances {0}\".format(ec2_instance))\n except ClientError as e:\n error_code = e.response[\"Error\"][\"Code\"]\n if error_code == \"UnsupportedOperation\":\n logging.warning(\"%s\", e)\n else:\n logging.error(\"Unexpected error: %s\", e)",
"def run(**kwargs):\n from apscheduler.scheduler import Scheduler\n\n sched = Scheduler(**kwargs)\n\n for task, kwargs in schedule.tasks.iteritems():\n sched.add_cron_job(task.run, name=task.__name__, **kwargs)\n\n sched.start() # main loop",
"def startinstance(imagename, instance_type='m1.large'):\n if not settings.get_image(imagename):\n raise SystemExit(\"Invalid imagename '%s'\" % imagename)\n\n username, conn = _getbotoconn(auth_user)\n\n print \"starting an instance from the %s image under the %s account of \" \\\n \"type %s\" % \\\n (imagename, username, instance_type)\n\n username, accesskey, secretkey, pkname = settings.get_user(username)\n imagename, imageid = settings.get_image(imagename)\n\n image = conn.get_image(imageid)\n reservation = None\n if pkname:\n reservation = image.run(instance_type=instance_type, key_name=pkname)\n else:\n reservation = image.run(instance_type=instance_type)\n\n instance = reservation.instances[0]\n\n # The image has been started in the pending state, wait for it to transition\n # into the running state\n while True:\n if instance.update() == u'running':\n # [AN] it would be nice if the user knew it was still working\n break\n time.sleep(1)\n\n print \"\"\n print \"Instance started\"\n print \"DNS name: %s\" % instance.dns_name",
"def create_spot_instance(config, job_id, sched_time, docker_image, env_vars):\n\n client = boto3.client('ec2')\n\n # Get my own public fqdn by quering metadata\n my_own_name = urllib2.urlopen(\n \"http://169.254.169.254/latest/meta-data/public-hostname\").read()\n\n user_data = (\n \"#!/bin/bash\\n\"\n \"touch /tmp/start.txt\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=started' -X PUT\\n\"\n \"yum -y update\\n\"\n \"yum install docker -y\\n\"\n \"sudo service docker start\\n\"\n \"sudo docker run %s %s\\n\"\n \"touch /tmp/executing.txt\\n\"\n \"sleep 180\\n\"\n \"curl -i -H 'Content-Type: application/json' \"\n \"'http://%s/v1/notifications/%s?status=finished' -X PUT\\n\" %\n (my_own_name, job_id, env_vars, docker_image, my_own_name, job_id))\n\n response = client.request_spot_instances(\n SpotPrice=\"%s\" % config[\"spot-price\"],\n InstanceCount=1,\n Type='one-time',\n ValidFrom=sched_time,\n LaunchSpecification={\n 'ImageId': config[\"ami-id\"],\n 'InstanceType': config[\"instance-type\"],\n 'KeyName': config[\"key-name\"],\n 'SecurityGroups': ['default', config[\"sg-name\"]],\n 'UserData': base64.b64encode(user_data)\n }\n )\n\n req_id = response['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n req_state = response['SpotInstanceRequests'][0][\n 'State'] # open/failed/active/cancelled/closed\n req_status_code = response['SpotInstanceRequests'][0][\n 'Status']['Code'] # pending-evaluation/price-too-low/etc\n\n return [req_id, req_state, req_status_code]",
"def test_jenkins_autoscaling_schedules_set(self) -> None:\n self.assertTrue(all([\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-morning',\n recurrence='0 11 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-morning',\n recurrence='0 12 * * *',\n max_size=0,\n min_size=0,\n desired_size=0),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-online-evening',\n recurrence='0 22 * * *',\n max_size=1,\n min_size=1,\n desired_size=1\n ),\n EC2.autoscaling_schedule_valid(\n asg_name='global-jenkins-server-asg',\n schedule_name='jenkins-server-offline-evening',\n recurrence='0 23 * * *',\n max_size=0,\n min_size=0,\n desired_size=0\n )\n ]))",
"def startInstances(self, api_client):\n\n cmd = {'group': self.id}\n return api_client.startVirtualMachine(**cmd)",
"def create_ec2_instances(count=1):\n conn = get_ec2_connection()\n user_data = get_user_data()\n reservation = conn.run_instances(image_id=settings.EC2_IMAGE_ID,\n min_count=count,\n max_count=count,\n instance_type=settings.EC2_INSTANCE_TYPE,\n user_data=user_data)\n return reservation.instances",
"def start_instance(conn, instance_id):\n\n conn.start_instances(instance_id, False)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Unassigns one or more IPv6 addresses from a network interface.
|
def unassign_ipv6_addresses(NetworkInterfaceId=None, Ipv6Addresses=None):
pass
|
[
"def UnassignIpv6Addresses(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6Addresses\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6AddressesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def streamingbypass_ipv6_rem(ipv6_addrs: str):\n return _run_speedify_cmd([\"streamingbypass\", \"ipv6\", \"rem\", ipv6_addrs])",
"def UnassignIpv6CidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6CidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6CidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def streaming_ipv6_rem(ipv6_addrs: str):\n return _run_speedify_cmd([\"streaming\", \"ipv6\", \"rem\", ipv6_addrs])",
"def assign_ipv6_addresses(NetworkInterfaceId=None, Ipv6Addresses=None, Ipv6AddressCount=None):\n pass",
"def ipv6(self, ipv6: SubUnnumberedTop):\n\n self._ipv6 = ipv6",
"def unset(cls, client, resource, args) :\n\t\ttry :\n\t\t\tif type(resource) is not list :\n\t\t\t\tunsetresource = onlinkipv6prefix()\n\t\t\t\tif type(resource) != type(unsetresource):\n\t\t\t\t\tunsetresource.ipv6prefix = resource\n\t\t\t\telse :\n\t\t\t\t\tunsetresource.ipv6prefix = resource.ipv6prefix\n\t\t\t\treturn unsetresource.unset_resource(client, args)\n\t\t\telse :\n\t\t\t\tif type(resource[0]) != cls :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ onlinkipv6prefix() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipv6prefix = resource[i]\n\t\t\t\telse :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ onlinkipv6prefix() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipv6prefix = resource[i].ipv6prefix\n\t\t\t\tresult = cls.unset_bulk_request(client, unsetresources, args)\n\t\t\treturn result\n\t\texcept Exception as e :\n\t\t\traise e",
"def UnassignIpv6SubnetCidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6SubnetCidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6SubnetCidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def test_ipv6interface_is_unspecified(self):\n n = 10**6\n addrs = ['1:2:3:4:5:6::', '::']\n for a in addrs:\n addr = ip.IPv6Interface(a)\n time1, result1 = timefn(n, lambda: addr.is_unspecified)\n eaddr = eip.IPv6Interface(a)\n time2, result2 = timefn(n, lambda: eaddr.is_unspecified)\n results = (time1, result1), (time2, result2)\n self.report_6i.report(fn_name(), n, results, a)",
"def delete_interfaces_interface_routed_vlan_ipv6_ipv6_by_id(name): # noqa: E501\n return 'do some magic!'",
"def delete_interfaces_interface_subinterfaces_subinterface_ipv6_ipv6_by_id(name, index): # noqa: E501\n return 'do some magic!'",
"def test_resolveOnlyIPv6(self):\n self._resolveOnlyTest([IPv6Address], AF_INET6)",
"def give_me_an_interface_ipv6():\n import netifaces\n for interface in netifaces.interfaces():\n if netifaces.AF_INET6 in netifaces.ifaddresses(interface):\n return interface\n return None",
"def reverse_ipv6(ipv6):\n reverse_chars = ipaddress_local.ip_address(ipv6).exploded[::-1].replace(':', '')\n return '.'.join(reverse_chars) + '.ip6.arpa'",
"def decode_ip6(pkt):\n ip6 = {}\n\n (ip6[\"ip6_label\"],\n ip6[\"ip6_length\"],\n ip6[\"ip6_nh\"],\n ip6[\"ip6_hop_limit\"],\n ip6[\"ip6_source_raw\"],\n ip6[\"ip6_destination_raw\"]) = struct.unpack(\n \">LHBB16s16s\", pkt[0:IP6_HDR_LEN])\n\n ip6[\"ip6_version\"] = ip6[\"ip6_label\"] >> 28\n ip6[\"ip6_class\"] = (ip6[\"ip6_label\"] >> 20) & 0xff\n ip6[\"ip6_label\"] = ip6[\"ip6_label\"] & 0xfffff\n ip6[\"ip6_source\"] = util.decode_inet_addr(ip6[\"ip6_source_raw\"])\n ip6[\"ip6_destination\"] = util.decode_inet_addr(ip6[\"ip6_destination_raw\"])\n\n offset = IP6_HDR_LEN\n\n # Skip over known extension headers.\n while True:\n if ip6[\"ip6_nh\"] in IP6_EXT_HEADER_TYPES:\n ip6[\"ip6_nh\"], ext_len = struct.unpack(\">BB\", pkt[offset:offset+2])\n offset += 8 + (ext_len * 8)\n else:\n break\n\n if ip6[\"ip6_nh\"] == IPPROTO_UDP:\n ip6.update(decode_udp(pkt[offset:]))\n elif ip6[\"ip6_nh\"] == IPPROTO_TCP:\n ip6.update(decode_tcp(pkt[offset:]))\n elif ip6[\"ip6_nh\"] == IPPROTO_ICMPV6:\n ip6.update(decode_icmp6(pkt[offset:]))\n\n return ip6",
"def mod_ip6(payload, **kw):\n _asciify_kw_for_scapy(kw)\n return ((inet6.IPv6(**kw) / p) for p in payload)",
"def tearDown(self):\n for i in reversed(self.interfaces):\n i.unconfig_ip6()\n i.admin_down()\n for i in self.sub_interfaces:\n i.remove_vpp_config()\n\n super(TestIPv6, self).tearDown()\n if not self.vpp_dead:\n self.logger.info(self.vapi.cli(\"show ip6 neighbors\"))\n # info(self.vapi.cli(\"show ip6 fib\")) # many entries",
"def streamingbypass_ipv6_set(ipv6_addrs: str):\n return _run_speedify_cmd([\"streamingbypass\", \"ipv6\", \"set\", ipv6_addrs])",
"def disable_IPV6_grub_level(self):\n for server in self.servers:\n shell = RemoteMachineShellConnection(server)\n shell.execute_command(\n '''sed -i 's/ipv6.disable=0 //; s/ipv6.disable=1 //; s/GRUB_CMDLINE_LINUX=\"/GRUB_CMDLINE_LINUX=\"ipv6.disable=1 /' /etc/default/grub''')\n shell.execute_command(\"grub2-mkconfig -o /boot/grub2/grub.cfg\")\n shell.reboot_node()\n time.sleep(10)\n shell = RemoteMachineShellConnection(server)\n output, error = shell.execute_command(\"ifconfig | grep inet6\")\n if output == [] and error == []:\n log.info(\"IPv6 Successfully Disabled for {0}\".format(server.ip))\n else:\n log.info(\"Cant disable IPv6\")\n log.info(\"Output message is {0} and error message is {1}\".format(output, error))\n output, error = shell.execute_command(\"iptables -F\")\n shell.disconnect()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Unassigns one or more secondary private IP addresses from a network interface.
|
def unassign_private_ip_addresses(NetworkInterfaceId=None, PrivateIpAddresses=None):
pass
|
[
"def unassign_ipv6_addresses(NetworkInterfaceId=None, Ipv6Addresses=None):\n pass",
"def assign_private_ip_addresses(NetworkInterfaceId=None, PrivateIpAddresses=None, SecondaryPrivateIpAddressCount=None, AllowReassignment=None):\n pass",
"def do_del_private_ip(vnic_utils, delete_options):\n # needs the OCI SDK installed and configured\n sess = get_oci_api_session()\n if sess is None:\n raise Exception(\"Failed to get API session.\")\n # find the private IP\n priv_ip = sess.this_instance().find_private_ip(\n delete_options.ip_address)\n if priv_ip is None:\n raise Exception(\n \"Secondary private IP not found: %s\" %\n delete_options.ip_address)\n\n if priv_ip.is_primary():\n raise Exception(\"Cannot delete IP %s, it is the primary private \"\n \"address of the VNIC.\" % delete_options.ip_address)\n\n vnic_id = priv_ip.get_vnic_ocid()\n\n if not priv_ip.delete():\n raise Exception('failed to delete secondary private IP %s' %\n delete_options.ip_address)\n\n _logger.info('deconfigure secondary private IP %s' %\n delete_options.ip_address)\n # delete from vnic_info and de-configure the interface\n return vnic_utils.del_private_ip(delete_options.ip_address, vnic_id)",
"def disassociate_address(DryRun=None, PublicIp=None, AssociationId=None):\n pass",
"def UnassignIpv6Addresses(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6Addresses\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6AddressesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def unplug_vifs(self, instance, network_info):\n for vif in network_info:\n self.vif_driver.unplug(instance, vif)\n self._stop_firewall(instance, network_info)",
"def HaVipDisassociateAddressIp(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"HaVipDisassociateAddressIp\", params, headers=headers)\n response = json.loads(body)\n model = models.HaVipDisassociateAddressIpResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def disassociate_floating_ip(server):\n return IMPL.disassociate_floating_ip(server)",
"def unset(cls, client, resource, args) :\n\t\ttry :\n\t\t\tif type(resource) is not list :\n\t\t\t\tunsetresource = nsrpcnode()\n\t\t\t\tif type(resource) != type(unsetresource):\n\t\t\t\t\tunsetresource.ipaddress = resource\n\t\t\t\telse :\n\t\t\t\t\tunsetresource.ipaddress = resource.ipaddress\n\t\t\t\treturn unsetresource.unset_resource(client, args)\n\t\t\telse :\n\t\t\t\tif type(resource[0]) != cls :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ nsrpcnode() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipaddress = resource[i]\n\t\t\t\telse :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ nsrpcnode() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipaddress = resource[i].ipaddress\n\t\t\t\tresult = cls.unset_bulk_request(client, unsetresources, args)\n\t\t\treturn result\n\t\texcept Exception as e :\n\t\t\traise e",
"def unplug_vifs(self, *args, **kwargs):\n # TODO: this is hardcoded\n pass",
"def unblock_ip():\r\n\t\r\n\tdata=temp_data.get()\r\n\tall_ips=data.split(\";\")\r\n\tfile_data=[]\r\n\twith open(\"fw_rules.txt\") as fw:\r\n\t\tfile_data=fw.read()\r\n\t\r\n\twith open(\"fw_rules.txt\",\"w+\") as fw:\r\n\t\tfor i in all_ips:\r\n\t\t\ti=socket.gethostbyname(i)\r\n\t\t\tprint (i)\r\n\t\t\tfile_data=file_data.replace('\\n'+i,'')\r\n\t\tfw.write(file_data)",
"def UnassignIpv6CidrBlock(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"UnassignIpv6CidrBlock\", params, headers=headers)\n response = json.loads(body)\n model = models.UnassignIpv6CidrBlockResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def del_vip_as_secondary_ip(vcns, edge_id, vip):\n if not vip_as_secondary_ip(vcns, edge_id, vip,\n del_address_from_address_groups):\n\n msg = _('Failed to delete VIP %(vip)s as secondary IP on '\n 'Edge %(edge_id)s') % {'vip': vip, 'edge_id': edge_id}\n raise n_exc.BadRequest(resource='edge-lbaas', msg=msg)",
"def ifDelIp(interface):\n logging.debugv(\"functions/linux.py->ifDelIp(interface)\", [interface])\n logging.info(\"Removing IP address from %s\" % interface)\n cmd = [locations.IFCONFIG, interface, \"0.0.0.0\", \"up\"]\n if runWrapper(cmd):\n return True\n else:\n return False",
"def _assign_secondary_ip_():\n interface_idx = 0\n node = env.nodes[0]\n cidr='%s/%s' % (env.secondary_ip,env.secondary_ip_cidr_prefix_size)\n\n if (_get_secondary_ip_node_().id == node.id):\n debug(\"VPC Secondary IP %s already assigned to %s\" % (cidr, pretty_instance(node)))\n else:\n info(\"Assigning VPC Secondary IP %s to %s\" % (cidr, pretty_instance(node)))\n connect().assign_private_ip_addresses(node.interfaces[interface_idx].id, env.secondary_ip, allow_reassignment=True)\n # Notify opsys that it has a new address (This seems to only happen automatically with Elastic IPs). Write to /etc to make persistent.\n has_address = run('ip addr | grep %s' % cidr, quiet=True)\n if not has_address:\n sudo('ip addr add %s dev eth0' % cidr)\n append('/etc/network/interfaces','up ip addr add %s dev eth%d' % (cidr,interface_idx),use_sudo=True)",
"def remove_floating_ip(server, address):\n return IMPL.remove_floating_ip(server, address)",
"def disassociate_address(self, address):\n query = self.query_factory(\n action=\"DisassociateAddress\", creds=self.creds,\n endpoint=self.endpoint, other_params={\"PublicIp\": address})\n d = query.submit()\n return d.addCallback(self.parser.truth_return)",
"def unset(cls, client, resource, args) :\n\t\ttry :\n\t\t\tif type(resource) is not list :\n\t\t\t\tunsetresource = onlinkipv6prefix()\n\t\t\t\tif type(resource) != type(unsetresource):\n\t\t\t\t\tunsetresource.ipv6prefix = resource\n\t\t\t\telse :\n\t\t\t\t\tunsetresource.ipv6prefix = resource.ipv6prefix\n\t\t\t\treturn unsetresource.unset_resource(client, args)\n\t\t\telse :\n\t\t\t\tif type(resource[0]) != cls :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ onlinkipv6prefix() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipv6prefix = resource[i]\n\t\t\t\telse :\n\t\t\t\t\tif (resource and len(resource) > 0) :\n\t\t\t\t\t\tunsetresources = [ onlinkipv6prefix() for _ in range(len(resource))]\n\t\t\t\t\t\tfor i in range(len(resource)) :\n\t\t\t\t\t\t\tunsetresources[i].ipv6prefix = resource[i].ipv6prefix\n\t\t\t\tresult = cls.unset_bulk_request(client, unsetresources, args)\n\t\t\treturn result\n\t\texcept Exception as e :\n\t\t\traise e",
"def _destroy_interface(name):\n\n links = _ipr.link_lookup(ifname=name)\n if len(links) == 0:\n logging.warning(\"Can't destroy %s interface. It doesn't exist.\", name)\n return\n index = links[0]\n\n # IP addresses assigned to interface\n ip_list = _ipr.get_addr(family=socket.AF_INET, label=name)\n for ipo in ip_list:\n ip = ipo.get_attr(\"IFA_ADDRESS\")\n\n # Deleting routes\n route_list = _ipr.get_routes(family=socket.AF_INET, gateway=ip)\n for route in route_list:\n rip = route.get_attr(\"RTA_DST\") # route[\"dst_len\"] <- mask\n if rip is not None:\n _del_route(\"%s/%d\" % (rip, route[\"dst_len\"]), ip)\n route_list = _ipr.get_routes(family=socket.AF_INET, scope=253)\n for route in route_list:\n if route.get_attr(\"RTA_OIF\") == index:\n rip = route.get_attr(\"RTA_DST\") # route[\"dst_len\"] <- mask\n if rip is not None:\n _del_route(\"%s/%d\" % (rip, route[\"dst_len\"]), name)\n\n # Deleting interface\n logging.debug(\"Destroying %s interface.\", name)\n _ipr.link(\"set\", index=index, state=\"down\")\n _ipr.link(\"del\", index=index)",
"def get_private_ip_address(instance_info):\n private_ip = instance_info[\"PrivateIpAddress\"]\n for network_interface in instance_info[\"NetworkInterfaces\"]:\n attachment = network_interface[\"Attachment\"]\n if attachment[\"DeviceIndex\"] == 0 and attachment[\"NetworkCardIndex\"] == 0:\n private_ip = network_interface[\"PrivateIpAddress\"]\n break\n return private_ip"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disables detailed monitoring for a running instance. For more information, see Monitoring Your Instances and Volumes in the Amazon Elastic Compute Cloud User Guide .
|
def unmonitor_instances(DryRun=None, InstanceIds=None):
pass
|
[
"def disable_performance_metrics(self) -> bool:\n return pulumi.get(self, \"disable_performance_metrics\")",
"def enable_instance_inspection(request):\n log('Enabling instance inspection')\n _assign_role(request, _get_role('vm-reader'))",
"def disable(self):\n hoomd.util.print_status_line()\n\n hoomd.util.quiet_status()\n _compute.disable(self)\n hoomd.util.unquiet_status()\n\n hoomd.context.current.thermos.remove(self)",
"def disabled_stp_on_management_ports(self):\n pass",
"def stop() -> None:\n config = load_config_file()\n instance_ips = [i.public_ip_address for i in get_running_instances(config)]\n if not instance_ips:\n raise Exception('ERROR: No instances with public IPs found. Exiting.')\n try:\n execute_commands_on_linux_instances(\n config,\n [\n COMMAND_KILL\n ],\n instance_ips\n )\n except Exception as e:\n logging.error(\"Something went wrong.\")\n raise\n logging.info('Done!')",
"def stop_monitoring():\n global toMonitor\n if toMonitor:\n logging.info(\"Halting monitoring on directory.\")\n toMonitor = False",
"def kdump_disable(db):\n kdump_table = db.cfgdb.get_table(\"KDUMP\")\n check_kdump_table_existence(kdump_table)\n\n db.cfgdb.mod_entry(\"KDUMP\", \"config\", {\"enabled\": \"false\"})\n click.echo(\"KDUMP configuration changes may require a reboot to take effect.\")\n click.echo(\"Save SONiC configuration using 'config save' before issuing the reboot command.\")",
"def performance_capacity_monitoring(n1, ip, x_api_session):\n os.system(\"cls\")\n SelectManagedSystem_obj = SelectManagedSystem.SelectManagedSystem()\n managedsystem_object = SelectManagedSystem_obj.\\\n get_managedsystem_uuid(ip, x_api_session)\n managedsystem_uuid = SelectManagedSystem_obj.managedsystem_uuid\n virtualioserver_object = ListVirtualIOServer.ListVirtualIOServer()\n object_list = virtualioserver_object.list_VirtualIOServer(ip,\n managedsystem_uuid,\n x_api_session)\n if managedsystem_uuid != \"\":\n st = 'y'\n n = n1\n if n == 1:\n ManagedSystemPcmPreference_object = ManagedSystemPcm.ManagedSystemPcmPreference(ip,\n managedsystem_uuid,\n x_api_session)\n while True:\n print((\"\\n\\n\",\"ManagedSystemPcmPreference\".center(50)))\n print_list = ['Get ManagedSystemPcmPreference','Set/Update ManagedSystemPcmPreference','Return to PCM Menu']\n #select any performance_capacity_monitoring operation\n x = int(print_obj.print_on_screen(print_list) )\n if x == 1:\n get_managedsystempcmpreference_object = ManagedSystemPcmPreference_object.get_managedsystempcmpreference()\n ManagedSystemPcmPreference_object.print_managedsystempcmpreference(get_managedsystempcmpreference_object)\n \n elif x == 2:\n set_managedsystempcmpreference_object = ManagedSystemPcmPreference_object.\\\n set_managedsystempcmpreference()\n \n elif x == 3:\n os.system(\"cls\")\n break\n else:\n print(\"\\nTry again using valid option\")\n back_to_menu()\n elif n == 2:\n #object creation and Method call to Longterm monitor\n LongTermMonitor_object = LongTermMonitor.LongTermMonitor(ip,\n managedsystem_uuid,\n x_api_session)\n LongTermMonitor_object.get_longtermmonitor(object_list)\n \n back_to_menu()\n \n elif n == 3:\n #object creation and Method call to Shortterm monitor\n ShortTermMonitor_object = ShortTermMonitor.ShortTermMonitor(ip,\n managedsystem_uuid,\n x_api_session)\n ShortTermMonitor_object.get_shorttermmonitor(object_list)\n \n back_to_menu()\n \n elif n == 4:\n #object creation and Method call to Processed Metrics\n process_metrics_object = ProcessedMetrics.ProcessedMetrics(ip,managedsystem_uuid ,x_api_session)\n process_metrics_object.get_processedmetrics()\n back_to_menu()\n \n else:\n print(\"\\nTry again using valid option\")\n back_to_menu()\n else:\n back_to_menu()",
"def DisableRSS(self):\n # First ensure that the driver supports interrupt moderation\n net_adapters, _ = self.RemoteCommand('Get-NetAdapter')\n if 'Red Hat VirtIO Ethernet Adapter' not in net_adapters:\n raise GceDriverDoesntSupportFeatureError(\n 'Driver not tested with RSS disabled in PKB.'\n )\n\n command = 'netsh int tcp set global rss=disabled'\n self.RemoteCommand(command)\n try:\n self.RemoteCommand('Restart-NetAdapter -Name \"Ethernet\"')\n except IOError:\n # Restarting the network adapter will always fail because\n # the winrm connection used to issue the command will be\n # broken.\n pass\n\n # Verify the setting went through\n stdout, _ = self.RemoteCommand('netsh int tcp show global')\n if 'Receive-Side Scaling State : enabled' in stdout:\n raise GceUnexpectedWindowsAdapterOutputError('RSS failed to disable.')",
"def disable_performance_metrics(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"disable_performance_metrics\")",
"def report_instance_status(DryRun=None, Instances=None, Status=None, StartTime=None, EndTime=None, ReasonCodes=None, Description=None):\n pass",
"def HideProgressMeter():\r\n pass",
"def lambda_handler(event, context):\n instance_id = event[\"instance_id\"]\n # Capture all the info about the instance so we can extract the ASG name later\n response = ec2_client.describe_instances(\n Filters=[\n {\"Name\": \"instance-id\", \"Values\": [instance_id]},\n ],\n )\n\n # Get the ASG name from the response JSON\n tags = response[\"Reservations\"][0][\"Instances\"][0][\"Tags\"]\n autoscaling_name = next(\n t[\"Value\"] for t in tags if t[\"Key\"] == \"aws:autoscaling:groupName\"\n )\n\n # Put the instance in standby\n response = asg_client.exit_standby(\n InstanceIds=[\n instance_id,\n ],\n AutoScalingGroupName=autoscaling_name,\n )\n\n response = asg_client.describe_auto_scaling_instances(\n InstanceIds=[\n instance_id,\n ]\n )\n while response[\"AutoScalingInstances\"][0][\"LifecycleState\"] != \"InService\":\n print(\" The node is not yet in service state, waiting for 5 more seconds\")\n time.sleep(5)\n response = asg_client.describe_auto_scaling_instances(\n InstanceIds=[\n instance_id,\n ]\n )\n if response[\"AutoScalingInstances\"][0][\"LifecycleState\"] == \"InService\":\n break\n # Detach the instance\n response = asg_client.detach_instances(\n InstanceIds=[\n instance_id,\n ],\n AutoScalingGroupName=autoscaling_name,\n ShouldDecrementDesiredCapacity=True,\n )\n\n response = ec2_client.describe_instances(\n Filters=[\n {\"Name\": \"instance-id\", \"Values\": [instance_id]},\n ],\n )\n\n while response[\"Reservations\"][0][\"Instances\"][0][\"Tags\"] == autoscaling_name:\n # sleep added to reduce the number of api calls for checking the status\n print(\" The node is not yet detached, waiting for 10 more seconds\")\n time.sleep(10)\n response = ec2_client.describe_instances(\n Filters=[\n {\"Name\": \"instance-id\", \"Values\": [instance_id]},\n ],\n )\n if response[\"Reservations\"][0][\"Instances\"][0][\"Tags\"] != autoscaling_name:\n break\n\n # if the node is detqched then stop the instance\n\n response = ec2_client.stop_instances(\n InstanceIds=[\n instance_id,\n ],\n )",
"def ex_disable_balancer_health_monitor_no_poll(self, balancer):\r\n uri = '/loadbalancers/%s/healthmonitor' % (balancer.id)\r\n\r\n resp = self.connection.request(uri,\r\n method='DELETE')\r\n\r\n return resp.status == httplib.ACCEPTED",
"def run_stopdisableyumcron():\n run(\"systemctl disable yum-cron\")\n run(\"systemctl stop yum-cron\")",
"def disable_disk_logging():\n app.set_option(_DISK_LOG_LEVEL_OPTION, LogOptions._LOG_LEVEL_NONE_KEY, force=True)",
"def stop():\n local('aws ec2 stop-instances --instance-ids %s'%(AWS_INSTANCE_ID))",
"def instances_status(cfg: Config):\n print_instances(Instance.elb_instances(target_group_arn_for(cfg)), number=False)",
"def PowerOff(self) -> None:"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Thread safe print function
|
def multithread_safe(self, *args, **kwargs) -> None:
with self.s_print_lock:
print(*args, **kwargs)
|
[
"def my_print(msg):\r\n with print_lock:\r\n print(msg)",
"def write():\n with LOCK:\n sys.stdout.write(\"%s writing..\" % threading.current_thread().name)\n time.sleep(random.random())\n sys.stdout.write(\"..done\\n\")",
"def _print(data):\n sys.stdout.buffer.write(data)",
"def acquire_print(timeout=None):\n\n if not timeout:\n success = PRINT_MUTEX.acquire()\n else:\n success = PRINT_MUTEX.acquire(timeout=timeout)\n\n return success",
"def release_print():\n\n PRINT_MUTEX.release()",
"def _mockable_print(arg):\n print(arg)",
"def _mllog_print(logger, *args, **kwargs):\n if kwargs.pop('sync', False):\n barrier()\n if 'value' not in kwargs:\n kwargs['value'] = None\n if get_rank() == 0:\n logger(*args, **kwargs, stack_offset=3)",
"def test_multi_threaded_interleaved_write(self):\n mock_io = expect.ExpectedInputOutput()\n sys.stdout = mock_io\n\n thread1_turn = queue.Queue()\n thread2_turn = queue.Queue()\n thread1_turn.put(True)\n with thread_safe_print.ThreadSafePrint():\n with thread_pool.ThreadPool(2) as pool:\n pool.add(self._thread1, thread1_turn, thread2_turn)\n pool.add(self._thread2, thread1_turn, thread2_turn)\n\n mock_io.assert_output_was([\n 'Thread 1 starts, thread 1 finishes.',\n 'Thread 2 starts, thread 2 finishes.'\n ])",
"def block_print():\n if NOPRINT:\n sys.stdout = open(os.devnull, \"w\")",
"def print_sink():\n while True:\n info = (yield)\n print info",
"def print(self):\n pass",
"def print_flush(s):\n print s\n sys.stdout.flush()",
"def prints(self, data, base=None):\r\n return self.write(self._process(data, base))",
"def test_fastprint_calls_puts():\n text = \"Some output\"\n fake_puts = Fake('puts', expect_call=True).with_args(\n text=text, show_prefix=False, end=\"\", flush=True\n )\n with patched_context(utils, 'puts', fake_puts):\n fastprint(text)",
"def print_queue(self):\n print self.queue",
"def enable_print():\n if NOPRINT:\n sys.stdout = sys.__stdout__",
"def job(self, msg, *args, **kwargs):\n self.print(50, msg, *args, **kwargs)",
"def timed_print():\n while True:\n print(\"hello\")\n yield TimedTask(3)",
"def threadDump():\n # type: () -> unicode\n return unicode(\"\"\"{0}\\n \"version\": \"{1}\"...{2}\"\"\").format(\n \"{\", getVersion().toParseableString(), \"}\"\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Pretty print of list, dicts, tuples `param object_` object to print `param indent` indent to new nested level `param quiet` suppress print to console `return` from pprint.pformat
|
def prettify(self, object_: Union[list, dict, tuple], indent: int = 4, quiet: bool = False) -> str:
import pprint
pretty_printer = pprint.PrettyPrinter(indent=indent)
pretty_string = pretty_printer.pformat(object=object_)
if not quiet:
self.multithread_safe(pretty_string)
return pretty_string
|
[
"def pp(object):\n return pprint.PrettyPrinter(indent=2, width=200).pprint(object)",
"def pprint(obj):\n print(json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')))",
"def dprint(object, stream=None, indent=1, width=80, depth=None):\n # Catch any singleton Django model object that might get passed in\n if getattr(object, '__metaclass__', None):\n if object.__metaclass__.__name__ == 'ModelBase':\n # Convert it to a dictionary\n object = object.__dict__\n # Catch any Django QuerySets that might get passed in\n elif isinstance(object, QuerySet):\n # Convert it to a list of dictionaries\n object = [i.__dict__ for i in object]\n # Pass everything through pprint in the typical way\n printer = PrettyPrinter(stream=stream, indent=indent, width=width, depth=depth)\n printer.pprint(object)",
"def prettify(topojson_object):\n return pprint.pprint(topojson_object)",
"def pretty_print(item):\n print(prettify(item))",
"def debugObject(level, msg, obj):\n if level > OPTIONS.verbose:\n return\n print(\"||\", ' ' * int(OPTIONS.indent), msg, end=\"\")\n pp(obj)",
"def _format_object(p_title, p_obj, suppressdoc = True, maxlen = 180, lindent = 24, maxspew = 2000):\r\n\r\n import types\r\n l_output = ''\r\n # Formatting parameters.\r\n ltab = 2 # initial tab in front of level 2 text\r\n # There seem to be a couple of other types; gather templates of them\r\n MethodWrapperType = type(object().__hash__)\r\n #\r\n # Gather all the attributes of the object\r\n objclass = None\r\n objdoc = None\r\n objmodule = '<None defined>'\r\n methods = []\r\n builtins = []\r\n classes = []\r\n attrs = []\r\n for slot in dir(p_obj):\r\n attr = getattr(p_obj, slot)\r\n if slot == '__class__':\r\n objclass = attr.__name__\r\n elif slot == '__doc__':\r\n objdoc = attr\r\n elif slot == '__module__':\r\n objmodule = attr\r\n elif (isinstance(attr, types.BuiltinMethodType) or isinstance(attr, MethodWrapperType)):\r\n builtins.append(slot)\r\n elif (isinstance(attr, types.MethodType) or isinstance(attr, types.FunctionType)):\r\n methods.append((slot, attr))\r\n elif isinstance(attr, types.TypeType):\r\n classes.append((slot, attr))\r\n else:\r\n attrs.append((slot, attr))\r\n # Organize them\r\n methods.sort()\r\n builtins.sort()\r\n classes.sort()\r\n attrs.sort()\r\n # Print a readable summary of those attributes\r\n normalwidths = [lindent, maxlen - lindent]\r\n tabbedwidths = [ltab, lindent - ltab, maxlen - lindent - ltab]\r\n\r\n # def truncstring(s, maxlen):\r\n # if len(s) > maxlen:\r\n # return s[0:maxlen] + ' ...(%d more chars)...' % (len(s) - maxlen)\r\n # else:\r\n # return s\r\n\r\n # Summary of introspection attributes\r\n if objclass == '':\r\n objclass = type(p_obj).__name__\r\n intro = \"\\nInstance of class '{}' as defined in module {} with id {}\".format(objclass, objmodule, id(p_obj))\r\n l_output += '\\nTitle: {} {}'.format(p_title, '\\n'.join(_format_line(intro, maxlen)))\r\n # l_output += '\\nTitle: ', p_title, '\\n'.join(_format_line(intro, maxlen))\r\n # Object's Docstring\r\n if not suppressdoc:\r\n if objdoc is None:\r\n objdoc = str(objdoc)\r\n else:\r\n objdoc = ('\"\"\"' + objdoc.strip() + '\"\"\"')\r\n l_output += '\\n'\r\n l_output += _format_cols(('Documentation string:', _trunc_string(objdoc, maxspew)), normalwidths, ' ')\r\n # Built-in methods\r\n if builtins:\r\n bi_str = _delchars(str(builtins), \"[']\") or str(None)\r\n l_output += '\\n'\r\n l_output += _format_cols(('Built-in Methods:', _trunc_string(bi_str, maxspew)), normalwidths, ', ')\r\n # Classes\r\n if classes:\r\n l_output += '\\nClasses'\r\n for (classname, classtype) in classes:\r\n classdoc = getattr(classtype, '__doc__', None) or '<No documentation>'\r\n if suppressdoc:\r\n classdoc = '<No documentation>'\r\n l_output += _format_cols(('', classname, _trunc_string(classdoc, maxspew)), tabbedwidths, ' ')\r\n # User methods\r\n if methods:\r\n l_output += '\\nMethods'\r\n for (methodname, method) in methods:\r\n methoddoc = getattr(method, '__doc__', None) or '<No documentation>'\r\n if suppressdoc:\r\n methoddoc = '<No documentation>'\r\n l_output += _format_cols(('', methodname, _trunc_string(methoddoc, maxspew)), tabbedwidths, ' ')\r\n # Attributes\r\n if attrs:\r\n l_output += '\\nAttributes'\r\n for (attr, val) in attrs:\r\n l_output += _format_cols(('', attr, _trunc_string(str(val), maxspew)), tabbedwidths, ' ')\r\n l_output += '\\n'\r\n l_output += '\\n====================\\n'\r\n return l_output",
"def debug(tag, *obj):\n\n global indent\n global tags\n\n indentChange = 0\n if tag.endswith(\"(\"):\n indentChange = 1\n tag = tag[0:-1]\n if tag.endswith(\")\"):\n indentChange = -1\n tag = tag[0:-1]\n if len(obj) > 0:\n if tag in tags or \"all\" in tags:\n # sys.stderr.write(\"(indent %04d)\" % indent)\n sys.stderr.write(\"%-7s \" %(tag+\":\"))\n sys.stderr.write(\". \" * indent)\n sys.stderr.write(\" \".join([my_repr(x) for x in obj]) + \"\\n\")\n indent += indentChange",
"def printr(obj: Any, *args, **kwargs) -> None:\n\n\tprint(repr(obj), *args, **kwargs)",
"def dumps(obj, width=80, indent=2, close_on_same_line=False,\n utf8_output=False, with_boring_lists=True, cls=None):\n # TODO use cls if not None\n buffer = tobuffer(obj, [], width, indent, close_on_same_line, utf8_output, with_boring_lists, cls)\n return \"\".join(buffer)",
"def pretty(ob, lexer=None):\r\n if lexer is None:\r\n if isinstance(ob, basestring):\r\n lexer = 'text'\r\n else:\r\n lexer = 'json'\r\n\r\n if lexer == 'json':\r\n ob = json.dumps(ob, indent=4, sort_keys=True)\r\n\r\n if got_pygments:\r\n lexerob = get_lexer_by_name(lexer)\r\n formatter = get_formatter_by_name(PRETTY_FORMATTER, style=PRETTY_STYLE)\r\n #from pygments.filters import *\r\n #lexerob.add_filter(VisibleWhitespaceFilter())\r\n ret = highlight(ob, lexerob, formatter)\r\n else:\r\n ret = ob\r\n\r\n return ret.rstrip()",
"def print_friendly_JSON_object(JSON_object):\n text = json.dumps(JSON_object, sort_keys=True, indent=4)\n print(text)",
"def pretty_printer(prettify, sudoku_row):\n if prettify is True:\n print(*sudoku_row)\n else:\n print(sudoku_row)",
"def as_indented_str(self, indent: int=0, multiple_entries: bool = False) -> str:\n modifiers = (\"M\" if multiple_entries else \"\") + (\"P\" if self.is_primitive else \"\") + \\\n (\"C\" if self.is_complex_type else \"\")\n return \"({})\".format(self.fns(self.node)) + (\"({})\".format(modifiers) if modifiers else \"\") + \\\n ((':\\n' + '\\n'.join([e.as_indented_str(indent+1) for e in sorted(self.edges)])) if self.edges else \"\")",
"def prettify(indent=0, width=80, compact=True):\n\n def decorate(func):\n @functools.wraps(func)\n def inner(*args, **kwargs):\n result = func(*args, **kwargs)\n\n print(t.format_function_header(func, args, kwargs))\n print(t.format_return_value(result, indent, width, compact))\n print(t.BLUE_LINES)\n\n return result\n\n return inner\n\n return decorate",
"def dumped (text, level, indent=2):\n return indented (\"{\\n%s\\n}\" % indented (text, level+1, indent) or \"None\", level, indent) + \"\\n\"",
"def html_format(obj, indent = 1):\n \n if isinstance(obj, list):\n htmls = []\n for k in obj:\n htmls.append(html_format(k))\n return '['+ \", \".join(htmls)+']'\n\n if isinstance(obj, dict):\n htmls = []\n for k,v in obj.items():\n htmls.append(\"<span style='font-style: italic; color: #888'>%s</span>: %s\" % (k,html_format(v,indent+1)))\n\n return '{<div style=\"margin-left: %dem\">%s</div>}' % (indent, ',<br>'.join(htmls))\n\n if type(obj) == str and obj.startswith(\"'<text\") and obj.endswith(\"/text>'\"):\n obj = obj[1:-1]\n \n return str(obj)",
"def log_output(self):\n\t\tpretty_output = json.dumps(self.nested_params, sort_keys=False, indent=4, separators=(',', ': '))\n\t\tprint(pretty_output)",
"def pprint(self):\n def pprintStr(node):\n s = \"(\" + str(node.value) \n for action in node.children:\n s = s + \", \" + pprintStr(node.children[action])\n s = s + \")\"\n return s\n\n print pprintStr(self)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns None for unparseable term names.
|
def test_unparseable_term_name(self):
assert berkeley.sis_term_id_for_name('Winter 2061') is None
assert berkeley.sis_term_id_for_name('Default Term') is None
|
[
"def test_missing_term_name(self):\n assert berkeley.sis_term_id_for_name(None) is None",
"def single_term(self):\n if self.terms.keys() == ['text'] and len(self.terms['text']) == 1:\n return self.terms['text'][0]['arg']",
"def try_parse_name(line):\n match = re.search(NAME_PATTERN, line)\n return list(match.groups())[0] if match else None",
"def term(self):\n if self.found(NAME):\n n = Node(Parser.VAR, value=self.token.string)\n self.next_token()\n return n\n elif self.found(NUMBER):\n n = Node(Parser.CONST, value=int(self.token.string))\n self.next_token()\n return n\n elif self.found('('):\n self.next_token()\n n = self.summa()\n if not self.found(')'):\n self.error('expected )')\n return n\n elif self.found('-'):\n self.next_token()\n n=Node(Parser.CONST, value=-int(self.token.string))\n self.next_token()\n return n",
"def get_random_term(parser, token):\n try:\n random_term = Term.objects.order_by('?')[0]\n return RandomTermNode(random_term)\n except IndexError:\n random_term = Term(title='Error', slug='error', description = 'No Term defined, please delete this Message or rename', source='http://trac.karrie.info/browser/repo/g2007/django_apps/nicetoknow/templatetags/nicetoknow_tags.py#L16')\n return RandomTermNode(random_term)",
"def _resolve_name(name):\n if not name or name.lower() == 'all':\n name = None\n return name",
"def qualname(short_term):\n\n return next(t for t in TERMS if t.endswith('/' + short_term))",
"def _parse_prefix(string: str) -> Tuple[Term, str]:\n # Task 7.3.1\n if is_variable(string[0]):\n return Term.variable_case(string)\n\n elif is_constant(string[0]):\n return Term.constant_case(string)\n\n elif is_function(string[0]):\n return Term.function_case(string)\n\n else: # string[0] is a char that doesnt correspond to any pattern\n return None, string",
"def find_term(self, question):\n\n term = None\n\n for regex in self.regexes:\n match = re.match(regex, question.lower())\n if match:\n term = stem(match.groups(1))\n break\n\n return term",
"def try_create(subterm):\n assert(isinstance(subterm, str))\n if subterm not in Tokens.__token_mapping:\n return None\n return Token(term=subterm, token_value=Tokens.__token_mapping[subterm])",
"def cut_reserved_word(self, line):\r\n word = self.read_identifier(line)\r\n if word in RESERVED_WORDS:\r\n return word, line[len(word):]\r\n else:\r\n return None",
"def __isanon(self, term):\n\t\treturn term == '_' or term == '?'",
"def term (self):\n return self.__term",
"def parse(name):\n\n pass",
"def _isTerminator(self, optionName):\n\n# sys.stderr.write(optionName + \"\\n\")\n# sys.stderr.write(repr(self.terminators))\n\n if optionName in self.terminators:\n self.terminator = optionName\n elif not self.allowAbbreviations:\n return None\n\n# regex thing in bogus\n# termExpr = regex.compile('^' + optionName)\n\n terms = filter(lambda x, on=optionName: string.find(x,on) == 0, self.terminators)\n\n if not len(terms):\n return None\n elif len(terms) > 1:\n raise TerminationError('Ambiguous terminator \\'' + optionName +\n '\\' matches ' + repr(terms))\n\n self.terminator = terms[0]\n return self.terminator",
"def isToken(symbol): \n key = symbols.get(symbol, \"NO\")\n if isinstance(key, str):\n return symbol\n else:\n return key",
"def lit_to_tok(lit: str) -> Token:\n return Token(lit) if lit in LIT_DICT else None",
"def search_term_or_none(\n prefix: str, pattern: str, exact: bool = False\n) -> Optional[\"ControlledTerm\"]:\n ret = None\n\n if prefix and pattern:\n try:\n ret = search_term(prefix, pattern, exact=exact)\n except ControlledVocabulary.DoesNotExist:\n pass\n\n return ret",
"def _parse_dot_name(self, pre_used_token=None):\r\n def append(el):\r\n names.append(el)\r\n self.module.temp_used_names.append(el[0])\r\n\r\n names = []\r\n if pre_used_token is None:\r\n token_type, tok = self.next()\r\n if token_type != tokenize.NAME and tok != '*':\r\n return [], token_type, tok\r\n else:\r\n token_type, tok = pre_used_token\r\n\r\n if token_type != tokenize.NAME and tok != '*':\r\n # token maybe a name or star\r\n return None, token_type, tok\r\n\r\n append((tok, self.start_pos))\r\n first_pos = self.start_pos\r\n while True:\r\n end_pos = self.end_pos\r\n token_type, tok = self.next()\r\n if tok != '.':\r\n break\r\n token_type, tok = self.next()\r\n if token_type != tokenize.NAME:\r\n break\r\n append((tok, self.start_pos))\r\n\r\n n = pr.Name(self.module, names, first_pos, end_pos) if names else None\r\n return n, token_type, tok"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns None for missing term names.
|
def test_missing_term_name(self):
assert berkeley.sis_term_id_for_name(None) is None
|
[
"def test_unparseable_term_name(self):\n assert berkeley.sis_term_id_for_name('Winter 2061') is None\n assert berkeley.sis_term_id_for_name('Default Term') is None",
"def single_term(self):\n if self.terms.keys() == ['text'] and len(self.terms['text']) == 1:\n return self.terms['text'][0]['arg']",
"def get_random_term(parser, token):\n try:\n random_term = Term.objects.order_by('?')[0]\n return RandomTermNode(random_term)\n except IndexError:\n random_term = Term(title='Error', slug='error', description = 'No Term defined, please delete this Message or rename', source='http://trac.karrie.info/browser/repo/g2007/django_apps/nicetoknow/templatetags/nicetoknow_tags.py#L16')\n return RandomTermNode(random_term)",
"def get_term(course_code):\n\n ans = DatabaseConnector.get_values(\"SELECT term FROM course WHERE course.course_code = \\\"\" + course_code + \"\\\"\")\n\n term = ans[0][0]\n\n if term == \"null\":\n return \"Term is not available.\"\n else:\n return term",
"def getAvailableTerms():\n # type: () -> List[String]\n return [\"term1\", \"term2\"]",
"def lookup_term(cls, snomed_id):\n\t\tif snomed_id is not None:\n\t\t\tsql = 'SELECT term FROM descriptions WHERE concept_id = ?'\n\t\t\tres = self.sqlite.executeOne(sql, (snomed_id,))\n\t\t\tif res:\n\t\t\t\treturn res[0]\n\t\t\n\t\treturn ''",
"def term (self):\n return self.__term",
"def search_term_or_none(\n prefix: str, pattern: str, exact: bool = False\n) -> Optional[\"ControlledTerm\"]:\n ret = None\n\n if prefix and pattern:\n try:\n ret = search_term(prefix, pattern, exact=exact)\n except ControlledVocabulary.DoesNotExist:\n pass\n\n return ret",
"def test_terms_undefined(self):\n with pytest.raises(qml.operation.TermsUndefinedError):\n MyOp.compute_terms(wires=[1])\n with pytest.raises(qml.operation.TermsUndefinedError):\n op.terms()",
"def find_term(self, question):\n\n term = None\n\n for regex in self.regexes:\n match = re.match(regex, question.lower())\n if match:\n term = stem(match.groups(1))\n break\n\n return term",
"def get_term_types():\n term_types = ['_Wq_', '_Wa_', '_Wd_']\n if common_flags.USE_DOCUMENT_TITLE.value == 1:\n term_types.append('_Wt_')\n return term_types",
"def unique_term(self):\n if self.satisfied is None and self.literals_values.count(None) == 1:\n # so there is only one Term that is None, all others are False\n i_unique = self.literals_values.index(None)\n u_term = self.terms[i_unique]\n tracer(f\"clause {self} must be satisfied with {u_term}\", TRACE_LVL, 5)\n if u_term.neg is True:\n return {'x': u_term.x, 'val': True}\n else:\n return {'x': u_term.x, 'val': False}\n return None",
"def x_are_none():\n list_x = []\n for k in Term.values.keys():\n if Term.values[k] is None:\n list_x.append(k)\n return list_x",
"def qualname(short_term):\n\n return next(t for t in TERMS if t.endswith('/' + short_term))",
"def optGetTermNum(self):\r\n content=openner.open('https://myinfo.cuny.edu/cfalternate/CFAltController?param_schedule=push')\r\n soup = BeautifulSoup(content.read(),'lxml')\r\n terms = soup.find_all(id = \"type_term\") #get the list of term code\r\n termDict = {}\r\n termCounter = 1 \r\n for i in range(0,len(terms[0])):\r\n try:\r\n print(str(i + 1) + \" - \" + str(terms[0].contents[termCounter].contents[0]))\r\n termDict[str(i + 1)] = str(terms[0].contents[termCounter].get(\"value\")) \r\n termCounter +=2\r\n except IndexError: #break from loop if there is no more term \r\n break\r\n \r\n userResp = input(\"Select the term that you want to check: \")\r\n return termDict[userResp]",
"def get(self, term: Term) -> Lesson:\n\n for lesson in self.lessons:\n if lesson.term == term:\n return lesson\n return None",
"def test_glossary_term_show(self):\n pass",
"def get_terms(self) -> set:\n return self.dictionary.words",
"def terms(self):\n return self._offr['terms'].keys()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
We must have unique dept codes and unique names.
|
def test_unique_department_names(self):
assert len(BERKELEY_DEPT_CODE_TO_NAME) == len(BERKELEY_DEPT_NAME_TO_CODE)
|
[
"def test_get_unique_fields(self):\n from nomnom.tests.models import Department\n self.assertListEqual(['id','code'], get_unique_field_names(Department))",
"def test_create_department_invalid_values_fails(self, client, dept_data):\n data = dept_data['test_dept']\n data.update({'name': \"$$$\"})\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 400\n assert response.data['message'] == VALIDATION['unsuccessful']\n assert 'name' in response.data['errors']",
"def test_create_department_succeeds(self, client, dept_data):\n\n data = dept_data['test_dept']\n response = client.post('/api/v1/department/', data)\n assert response.status_code == 201\n assert response.data['message'] == SUCCESS['create_entry'].format(\n data['name'])",
"def test_extract_valid_department_from_id():\n assert extract_valid_department_from_id(\"MITx+7.03.2x\") == [\"7\"]\n assert extract_valid_department_from_id(\"course-v1:MITxT+21A.819.2x\") == [\"21A\"]\n # Has a department not in the list and thus should not be entered\n assert extract_valid_department_from_id(\"course-v1:MITxT+123.658.2x\") is None\n # Has no discernible department\n assert extract_valid_department_from_id(\"MITx+CITE101x\") is None\n assert extract_valid_department_from_id(\"RanD0mStr1ng\") is None",
"def test_department_model(self, add_org, dept_data):\n\n data = dept_data['test_dept']\n data.update({'organization': add_org})\n department = Department(**data)\n department.save()\n assert Department.objects.get(name=data['name'])\n assert len(Department.objects.all()) >= 1",
"def test_create_valid(self):\n dp = baker.make(\"DegreeProgram\")\n rub = baker.make(\"Rubric\")\n f = CreateReportByDept({\n 'year':2017,\n 'degreeProgram':dp.pk,\n 'rubric': rub.pk\n },dept=dp.department.pk\n )\n self.assertTrue(f.is_valid())",
"def test_portals_id_designs_post(self):\n pass",
"def setup_db_department():\n # Initialize key variables\n idx_department = 1\n\n # Create a dict of all the expected values\n expected = {\n 'enabled': 1,\n 'name': general.hashstring(general.randomstring()),\n 'idx_department': idx_department,\n 'code': general.hashstring(general.randomstring()),\n }\n\n # Drop the database and create tables\n initialize_db()\n\n # Insert data into database\n data = Department(\n code=general.encode(expected['code']),\n name=general.encode(expected['name']))\n database = db.Database()\n database.add_all([data], 1048)\n\n # Return\n return expected",
"def test_portals_id_designs_get(self):\n pass",
"def test_duplicate_names(self):\n self.assertRaises(ds.DuplicateNames,\n ds.process_form,\n {'row_count': '2', 'debt_name_1': 'test_name', 'balance_1': '1',\n 'payment_1': '1', 'apr_1':'5.3', 'debt_name_2': 'test_name',\n 'balance_2': '1', 'payment_2': '1', 'apr_2': '5.3'})",
"def test_portals_id_designs_fk_put(self):\n pass",
"def get_dept_code(dept: str, resdept: str, user: str) -> str:\n if dept == \"Unspecified Department\" and resdept in depts:\n return depts[resdept]\n elif dept in depts:\n return depts[dept]\n else:\n print(f\"No entry for {dept} or {resdept} in dossier.py for {user}\")\n return \"NOT_FOUND_IN_DOSSIER_DEPTS\"",
"def getDeptCode (self):\n return self.deptCode",
"def department(cls):\r\n return cls.random_element(cls.departments)",
"def test_portals_id_head(self):\n pass",
"def test_get_department_list_succeeds(self, client, add_dept):\n response = client.get('/api/v1/department/')\n assert response.status_code == 200\n assert len(response.data['data']) >= 1",
"def test_portals_id_templates_fk_designs_generate_post(self):\n pass",
"def __init__(self, department):\r\n self.name = department",
"def test_legal_names(self):\n prod = generate_product()\n for word in prod:\n self.assertIn(word.name.split()[0], ADJECTIVES)\n self.assertIn(word.name.split()[1], NOUNS)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Checks that force flag overwrites page if the author is different
|
def test_post_force_overwrite_other_author(force_flag, tmp_path, setup_page):
config_file, (page_id, page_title) = setup_page(1)
original_username = Config(config_file).author
new_config = replace_new_author(config_file=config_file, tmp_path=tmp_path)
new_text = rewrite_page_file(Config(new_config).pages[0].page_file)
new_username = Config(new_config).author
result = run_with_config(
config_file=new_config,
pre_args=["--force"] * force_flag,
)
assert result.exit_code == 0
if force_flag:
assert (
"Updating page" in result.stdout
), "User should be notified an update is happening"
assert new_text in get_page_body(page_id), "Page should had been updated"
check_body_and_title(page_id, body_text=new_text, title_text=page_title)
else:
assert "Flag 'force' is not set and last author" in result.stdout, (
"User should be notified why the script " "is not updating anything"
)
assert (
original_username in result.stdout
), "The original username should be mentioned in the script output"
assert (
new_username in result.stdout
), "The author_to_check username should be mentioned in the script output"
assert new_text not in get_page_body(
page_id
), "Page should not had been updated"
|
[
"def test_bad_author(self):\n author_links = []\n page_url = \"hola\"\n author_links.append(page_url)\n self.assertEqual(author_scraper.scrape_author(author_links), False)",
"def test_func(self):\n article = self.get_object()\n if self.request.user == article.author:\n return True\n return False",
"def changed_author(self):\n return self.article.correspondence_author.pk == self.parent_article.coreespondece_author.pk",
"def _wikipedia_Page_botMayEdit(self):\n botsTemplate = wikipedia.Page(self.site(), 'template:bots')\n nobotsTemplate = wikipedia.Page(self.site(), 'template:nobots')\n if toolserver.Tests.isIncludedIn(botsTemplate, self):\n return _wikipedia_Page_botMayEdit(self, original=True)\n elif toolserver.Tests.isIncludedIn(nobotsTemplate, self):\n return False\n else:\n return True",
"def need_change(self, title, poster):\n pos = Poster.objects.get(title=title)\n if pos.poster.name == poster:\n return False\n else:\n return True",
"def test_create_and_overwrite_page(force_flag, setup_page):\n config_file, (page_id, page_title) = setup_page(1)\n new_text = rewrite_page_file(Config(config_file).pages[0].page_file)\n\n overwrite_result = run_with_config(\n config_file=config_file,\n pre_args=[\"--force\"] * force_flag,\n )\n assert overwrite_result.exit_code == 0\n assert \"Updating page\" in overwrite_result.stdout\n check_body_and_title(page_id, body_text=new_text, title_text=page_title)",
"def pdf_needs_regenerate(self):\n cachefile = self.pdf_get_cachefile()\n\n if not os.path.isfile(cachefile):\n return True\n\n # Check if cache file is older than last modification of wiki snip.\n modifytime = datetime.fromtimestamp(os.path.getmtime(cachefile))\n if modifytime < self.changed:\n return True\n return False",
"def did_authors_publish_before_in_venue(self):\n if self.total_number_of_times_authors_published_in_venue > 0:\n return True\n return False",
"def user_and_author(self, author):\n if self.logged_in() and self.account == author:\n return True\n else:\n return False",
"def should_override(self, flag: Flag, **kwargs) -> bool:\n return SiteFlagOverride.objects.filter(name=flag.name).exists()",
"def pre_save(self, obj):\n try:\n obj.author\n obj.owner\n except ObjectDoesNotExist:\n obj.author = self.request.user\n obj.owner = self.request.user.user.owner",
"def test_redirects_if_revision_not_awaiting_moderation(self):\n self.revision.submitted_for_moderation = False\n self.revision.save()\n\n url = self.get_url(revision_id=self.revision.id)\n response = self.client.get(url, follow=True)\n self.assertRedirects(response, reverse('wagtailadmin_home'))\n self.assertContains(response, 'is not currently awaiting moderation')",
"def addAuthor(self, author):\r\n authorPage=AuthorPage(self.site)\r\n if author in self.metadata['orcids']:\r\n existingauthor = self.authorAlreadyExists(self.metadata['orcids'][author])\r\n if existingauthor == False :\r\n authorPage.setName(author)\r\n authorPage.addOrcid(self.metadata['orcids'][author])\r\n authorPage.setItemType()\r\n else:\r\n authorPage=AuthorPage(self.site, existingauthor)\r\n else:\r\n authorPage.setName(author)\r\n authorPage.setItemType()\r\n #print(\"adding author:\" + author)\r\n self.addDelayedClaim('P2', authorPage)",
"def test_redirect_can_be_clobbered(self):\n client = LocalizingClient()\n client.login(username='admin', password='testpass')\n\n exist_title = \"Existing doc\"\n exist_slug = \"existing-doc\"\n\n changed_title = 'Changed title'\n changed_slug = 'changed-title'\n\n # Create a new doc.\n data = new_document_data()\n data.update({ \"title\": exist_title, \"slug\": exist_slug })\n resp = client.post(reverse('wiki.new_document'), data)\n eq_(302, resp.status_code)\n\n # Change title and slug\n data.update({'form': 'rev', \n 'title': changed_title, \n 'slug': changed_slug})\n resp = client.post(reverse('wiki.edit_document',\n args=['%s/%s' % (data['locale'],\n exist_slug)]), \n data)\n eq_(302, resp.status_code)\n\n # Change title and slug back to originals, clobbering the redirect\n data.update({'form': 'rev', \n 'title': exist_title, \n 'slug': exist_slug})\n resp = client.post(reverse('wiki.edit_document',\n args=[\"%s/%s\" % (data['locale'],\n changed_slug)]), \n data)\n eq_(302, resp.status_code)",
"def is_owner_check(message):\r\n return str(message.author.id) == \"188508216995348483\"",
"def test_should_render_for_owner_unpublished(self):\n review_request = self.create_review_request(public=False)\n\n request = RequestFactory().request()\n request.user = review_request.submitter\n\n self.assertTrue(self.action.should_render({\n 'review_request': review_request,\n 'request': request,\n 'perms': {\n 'reviews': {\n 'can_change_status': False,\n },\n },\n }))",
"def is_mutable_by(self, user):\n return ((self.submitter == user or\n user.has_perm('reviews.can_edit_reviewrequest',\n self.local_site)) and\n not is_site_read_only_for(user))",
"def _need_link (self, objects, output_file):\r\n if self.force:\r\n return 1\r\n else:\r\n if self.dry_run:\r\n newer = newer_group (objects, output_file, missing='newer')\r\n else:\r\n newer = newer_group (objects, output_file)\r\n return newer",
"def test_url_not_in_cache(self):\n authors_response = self.client.get(reverse('authors-list'))\n author1_name = authors_response.data[0]['first_name']\n self.assertEqual(len(authors_response.data), 1)\n self.assertEqual(author1_name, self.author.first_name)\n\n author2 = Author(first_name=\"Rowling\")\n author2.save()\n authors_response = self.client.get(reverse('authors-list'))\n author1_name = authors_response.data[0]['first_name']\n author2_name = authors_response.data[1]['first_name']\n\n self.assertEqual(len(authors_response.data), 2)\n self.assertEqual(author1_name, self.author.first_name)\n self.assertEqual(author2_name, author2.first_name)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a page and tries to overwrite it as the same user. Checks that the force_flag does not matter
|
def test_create_and_overwrite_page(force_flag, setup_page):
config_file, (page_id, page_title) = setup_page(1)
new_text = rewrite_page_file(Config(config_file).pages[0].page_file)
overwrite_result = run_with_config(
config_file=config_file,
pre_args=["--force"] * force_flag,
)
assert overwrite_result.exit_code == 0
assert "Updating page" in overwrite_result.stdout
check_body_and_title(page_id, body_text=new_text, title_text=page_title)
|
[
"def test_post_force_overwrite_other_author(force_flag, tmp_path, setup_page):\n config_file, (page_id, page_title) = setup_page(1)\n original_username = Config(config_file).author\n new_config = replace_new_author(config_file=config_file, tmp_path=tmp_path)\n new_text = rewrite_page_file(Config(new_config).pages[0].page_file)\n new_username = Config(new_config).author\n\n result = run_with_config(\n config_file=new_config,\n pre_args=[\"--force\"] * force_flag,\n )\n assert result.exit_code == 0\n\n if force_flag:\n assert (\n \"Updating page\" in result.stdout\n ), \"User should be notified an update is happening\"\n assert new_text in get_page_body(page_id), \"Page should had been updated\"\n check_body_and_title(page_id, body_text=new_text, title_text=page_title)\n else:\n assert \"Flag 'force' is not set and last author\" in result.stdout, (\n \"User should be notified why the script \" \"is not updating anything\"\n )\n assert (\n original_username in result.stdout\n ), \"The original username should be mentioned in the script output\"\n assert (\n new_username in result.stdout\n ), \"The author_to_check username should be mentioned in the script output\"\n assert new_text not in get_page_body(\n page_id\n ), \"Page should not had been updated\"",
"def page_create():\n return redirect(url_for('page_edit'))",
"def test_14_super_add_page_to_root(self):\n self.login_user(self.user_super)\n # create page under root\n page = self.create_page()\n \n # public must not exist\n self.assertEqual(not page.publisher_public, True)\n \n # moderator_state must be changed\n self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)",
"def test_create_inaccessible(self):\n response, page = self._create_page(Page.objects.get(pk=1))\n self.assertIsNone(page.url)\n self.assertFalse(any(\n 'View live' in message.message\n for message in response.context['messages']))",
"def createTestPage(self):\n import os\n path = self.dictPagePath()\n if os.path.exists(path):\n self.shouldDeleteTestPage = False\n raise TestSkiped(\"%s exists. Won't overwrite exiting page\" % \n self.dictPage)\n try:\n os.mkdir(path)\n revisionsDir = os.path.join(path, 'revisions')\n os.mkdir(revisionsDir)\n current = '00000001'\n file(os.path.join(path, 'current'), 'w').write('%s\\n' % current)\n text = u' ME:: %s\\n' % self.name\n file(os.path.join(revisionsDir, current), 'w').write(text)\n except Exception, err:\n raise TestSkiped(\"Can not be create test page: %s\" % err)",
"def test_create_page_without_promote_tab(self):\n response = self.client.get(\n reverse('wagtailadmin_pages:add', args=('tests', 'standardindex', self.root_page.id))\n )\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, '<a href=\"#tab-content\" class=\"active\">Content</a>')\n self.assertNotContains(response, '<a href=\"#tab-promote\" class=\"\">Promote</a>')",
"def save_core_model(self, form, user):\n c_data = form.get_core_data()\n c_data = dict(user, {'author': user, 'pagetype': self.pagetype})\n # DOES NOT IMPLEMENT UPDATE!\n landing_page = LandingPage(**c_data)\n landing_page.save()\n return landing_page",
"def post_creation(self):\n new_page = VersionedText(revision_number = self.revision_number,\n content = \"Empty page\",\n author = getActiveDatabaseUser().get_active_user(),\n comment = \"Initial revision\")\n new_page.put()\n self.add_entry(date.today(), \"Initial revision\", new_page.key())",
"def create_userpref(sender, **kwargs):\n user = kwargs[\"instance\"]\n if kwargs[\"created\"]:\n user_pref = UserPref(user=user)\n user_pref.save()",
"def assign_user_to_page(self, page, user, grant_on=ACCESS_PAGE_AND_DESCENDANTS,\n can_add=False, can_change=False, can_delete=False, \n can_change_advanced_settings=False, can_publish=False, \n can_change_permissions=False, can_move_page=False, can_moderate=False, \n grant_all=False):\n if grant_all:\n return self.assign_user_to_page(page, user, grant_on, \n True, True, True, True, True, True, True, True)\n \n # just check if the current logged in user even can change the page and \n # see the permission inline\n response = self.client.get(URL_CMS_PAGE_CHANGE % page.id)\n self.assertEqual(response.status_code, 200)\n \n data = {\n 'can_add': can_add,\n 'can_change': can_change,\n 'can_delete': can_delete, \n 'can_change_advanced_settings': can_change_advanced_settings,\n 'can_publish': can_publish, \n 'can_change_permissions': can_change_permissions, \n 'can_move_page': can_move_page, \n 'can_moderate': can_moderate, \n }\n \n page_permission = PagePermission(page=page, user=user, grant_on=grant_on, **data)\n page_permission.save()\n return page_permission",
"def create_default_page(case):\n p = Page(template='page.html', skin='', layout_json='{\"static_containers\": [], \"containers\": []}', id=settings.DEFAULT_PAGE_ID, layout_migrated=True)\n p.save()\n case.page = p",
"def test_create_accessible(self):\n response, page = self._create_page(Page.objects.get(pk=2))\n self.assertIsNotNone(page.url)\n self.assertTrue(any(\n 'View live' in message.message and page.url in message.message\n for message in response.context['messages']))",
"def create_page(sender, instance):\n raw_title = instance.title.split(\".\")[0]\n title = raw_title[0].upper()+raw_title[1:]\n title = title.replace(\"_\", \" \")\n\n page_creation = ImageSelector.objects.get(id=4)\n new_page_creation = page_creation.copy(\n update_attrs={'title': title, 'slug': instance.id})\n new_page_creation.main_image = instance\n new_page_creation.front = False\n new_page_creation.intro = \"\"\n new_page_creation.body = \"\"\n new_page_creation.save()\n\n page_object = ImageSelector.objects.get(slug=instance.id)\n slug = '%s-%s-%s' % (raw_title, page_object.id, instance.id)\n\n new_page_creation.slug = slugify(slug, allow_unicode=False)\n new_page_creation.set_url_path(new_page_creation.get_parent())\n new_page_creation.save()\n\n instance.has_page = True\n\n # predefinition of the thumb and resized image\n if not instance.thumb_url:\n filter_spec = \"fill-200x200\"\n rendition_file = instance.get_rendition(filter_spec).file\n # set url for the rest api\n instance.thumb_url = 'media/images/'+rendition_file.path.split(\"/\")[-1]\n\n filter_spec = \"max-1500x800\"\n rendition_file = instance.get_rendition(filter_spec).file\n # set url for the rest api\n instance.resize_url = 'media/images/'+rendition_file.path.split(\"/\")[-1]\n print 'thumb created'\n\n instance.save()",
"def test_page_permission_cache_invalidation(self):\n user = User(username='user', email='user@domain.com', password='user',\n is_staff=True)\n user.save()\n group = Group.objects.create(name='testgroup')\n group.user_set.add(user)\n page = create_page('A', 'nav_playground.html', 'en')\n page_permission = PagePermission.objects.create(\n can_change_permissions=True, group=group, page=page)\n request = self.get_request(user)\n self.assertTrue(page.has_change_permissions_permission(request))\n page_permission.can_change_permissions = False\n page_permission.save()\n request = self.get_request(user)\n # re-fetch the page from the db to so that the page doesn't have\n # the permission_user_cache attribute set\n page = Page.objects.get(pk=page.pk)\n self.assertFalse(page.has_change_permissions_permission(request))",
"def test_redirect_can_be_clobbered(self):\n client = LocalizingClient()\n client.login(username='admin', password='testpass')\n\n exist_title = \"Existing doc\"\n exist_slug = \"existing-doc\"\n\n changed_title = 'Changed title'\n changed_slug = 'changed-title'\n\n # Create a new doc.\n data = new_document_data()\n data.update({ \"title\": exist_title, \"slug\": exist_slug })\n resp = client.post(reverse('wiki.new_document'), data)\n eq_(302, resp.status_code)\n\n # Change title and slug\n data.update({'form': 'rev', \n 'title': changed_title, \n 'slug': changed_slug})\n resp = client.post(reverse('wiki.edit_document',\n args=['%s/%s' % (data['locale'],\n exist_slug)]), \n data)\n eq_(302, resp.status_code)\n\n # Change title and slug back to originals, clobbering the redirect\n data.update({'form': 'rev', \n 'title': exist_title, \n 'slug': exist_slug})\n resp = client.post(reverse('wiki.edit_document',\n args=[\"%s/%s\" % (data['locale'],\n changed_slug)]), \n data)\n eq_(302, resp.status_code)",
"def save_model(self, request, obj, form, change):\n landing_page = self.save_core_model(form, request.user)\n obj.landingpage = landing_page\n super(LandingPageAdmin, self).save_model(request, obj, form, change)",
"def add_user_perm(self, user, doc, write = False):\n\n try:\n perm = self.user_perms.get(doc = doc, user = user)\n perm.write = write\n perm.save()\n except ObjectDoesNotExist:\n self.user_perms.create(doc = doc, user = user, write = write)",
"def test_deposit_already_exists_overwrite(self):\n app = create_app()\n with app.app_context():\n token = generate_token('123', 'foo@user.com', 'foouser',\n scope=[auth.scopes.READ_PREVIEW,\n auth.scopes.CREATE_PREVIEW])\n\n client = app.test_client()\n content = io.BytesIO(b'foocontent')\n client.put('/1234/foohash1==/content', data=content,\n headers={'Authorization': token})\n new_content = io.BytesIO(b'barcontent')\n response = client.put('/1234/foohash1==/content', data=new_content,\n headers={'Overwrite': 'true',\n 'Authorization': token})\n self.assertEqual(response.status_code, status.CREATED,\n 'Returns 201 Created')\n response_data = response.get_json()\n try:\n jsonschema.validate(response_data, self.schema)\n except jsonschema.ValidationError as e:\n self.fail(f'Failed to validate: {e}')",
"def add_as_website_user(self):\n add_patient_as_a_website_user = frappe.db.get_single_value (\n 'Healthcare Settings', 'add_patient_as_a_website_user')\n if add_patient_as_a_website_user:\n original_add_as_website_user(self)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Copy a dinosaur. This returns a new alive dinosaur with score 0. It only copies DNA and behavior
|
def from_dinosaur(dinosaur):
newdino = AIDinosaur(dinosaur.surfaceheight)
newdino.dna = dinosaur.dna.copy()
newdino.score = 0
newdino.behavior = AIDinoBehavior(newdino.dna)
return newdino
|
[
"def copy(toCopy):\r\n copiedPkmn = copy.deepcopy(toCopy)\r\n copiedPkmn.battleDelegate.attacks = toCopy.battleDelegate.attacks\r\n return copiedPkmn",
"def copy(self, new_id=None):\n if not new_id:\n copy = ScriptedSprite(self.id+'_copy', self.rect.topleft, self.rect.size, self.resolution, self.fps, self.fps_modes, **self.params)\n else:\n copy = ScriptedSprite(new_id, self.rect.topleft, self.rect.size, self.resolution, self.fps, self.fps_modes, **self.params)\n copy.frames = dict(self.frames)\n copy.real_frames = dict(self.real_frames)\n return copy",
"def copy(self):\n copyDealerHand = deepcopy(self.dealerHand)\n copyPlayerHands = [deepcopy(hand) for hand in self.playerHands]\n \n return GameState(self.verbose, self.dealer, copyDealerHand, self.player, copyPlayerHands, self.deck, self.bets, self.playerHandIdx, self.turn)",
"def copy(self):\r\n U = CatMorphism(self.name,self.source,self.target)\r\n U.set_mapping_matrix(self.get_mapping_matrix())\r\n\r\n return U",
"def duplicate(prototype, coords = None, currentLevel = None):\n \n return Monster(prototype.name,\n coords,\n prototype.glyph,\n prototype.AICode,\n prototype.speed,\n prototype.max_HP,\n prototype.tags[:] if prototype.tags is not None else None,\n prototype.attack,\n prototype.defense,\n prototype.char_level,\n prototype.spec,\n prototype.specfreq,\n currentLevel,\n )",
"def get_copy(self):\n return Game(\n self.width,\n self.height,\n self.maxPlayers,\n self.currentPlayer,\n self.legalMoves.copy(),\n self.grid,\n self.boxes,\n self.movesMade.copy())",
"def copy(self):\n new = Shavtsak(self.soldiers)\n new.days = self.days.copy()\n new.watches = self.watches.copy()\n new.schedule = {day: {watch: self.schedule[day][watch].copy() for watch in self.watches} for day in self.days}\n new.reduced = self.reduced.copy()\n new.name = '' + self.name\n return new",
"def copy(self) -> Game:\n return _CONVERTER.structure(_CONVERTER.unstructure(self), Game)",
"def copy(self):\n \n return Move(self.x, self.y, self.z, self.dir)",
"def copy(self):\n new_piece = Bishop(self.pos, self.team)\n new_piece.moved = self.moved\n return new_piece",
"def __copy__(self):\n return BasicEffect(self._variable_label, self._variable_value, self._priority, self._exclusive, self._negated)",
"def copy(self):\n dbn = DynamicBayesianNetwork()\n dbn.add_nodes_from(self._nodes())\n edges = [(u.to_tuple(), v.to_tuple()) for (u, v) in self.edges()]\n dbn.add_edges_from(edges)\n cpd_copy = [cpd.copy() for cpd in self.get_cpds()]\n dbn.add_cpds(*cpd_copy)\n return dbn",
"def copy(self):\n cp = Entity()\n cp.genotype = self.genotype.copy()\n cp.fitness = self.fitness\n\n return cp",
"def copy_skeleton(self, newdomain=None):\n if not newdomain:\n newdomain = self.parent\n \n args = [Parameter(p.name, p.type) for p in self.args]\n adict = dict((a.name, a) for a in args)\n agents = [adict[a.name] for a in self.agents]\n params = [a for a in args if a not in agents]\n\n o = Observation(self.name, agents, params, None, None, None, newdomain)\n exe_cond = [ex.copy(newparent=o, newdomain=newdomain) for ex in self.execution]\n o.execution = exe_cond\n return o",
"def create_copy(self):\n print('WARNING: Implementation and testing still in progress!!!!')\n\n new_obj = self.__class__()\n new_obj.data = copy.deepcopy(self.data)\n new_obj.topography = copy.deepcopy(self.topography)\n new_obj.electrode_positions = copy.deepcopy(\n self.electrode_positions)\n\n # what about the log?\n print('WARNING: Journal and log is not copied!')\n\n return new_obj",
"def crossover(mom, dad):\n if len(mom) != len(dad):\n raise Exception(\"Length of DNA are not same between parents\")\n crossovers = int(random.betavariate(2, 5) * len(mom)) # gets a number that's more heavily weighted to only a couple of crossovers, not too many, not too few\n # print(crossovers, \"crossovers\")\n crossoverPoints = random.choices(list(range(0, len(mom))), k=crossovers)\n # print(crossoverPoints, \"points\")\n \n which = random.randint(0, 1)\n baby = []\n for i in range(0, len(mom)):\n if i in crossoverPoints:\n which = 1 - which # switch parent it's pulling from\n \n if which == 0:\n dna = mom\n else:\n dna = dad\n \n baby.append(dna[i])\n \n return baby",
"def unfilled_copy(self):\n copy = Region(self.image, target=self.target, seed_vox=self.pos_to_vox(self.seed_pos))\n copy.bias_against_merge = self.bias_against_merge\n copy.move_based_on_new_mask = self.move_based_on_new_mask\n\n return copy",
"def make_same(self, dist):\n return dist.make_hazard()",
"def copy(cls, script):\n scripts = copy.deepcopy(script.script)\n return cls(scripts)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QCoreApplication.notify(QObject, QEvent) > bool
|
def notify(self, QObject, QEvent): # real signature unknown; restored from __doc__
return False
|
[
"def sendEvent(self, QObject, QEvent): # real signature unknown; restored from __doc__\r\n return False",
"def sendEvent(self, QGraphicsItem, QEvent): # real signature unknown; restored from __doc__\r\n return False",
"def notify(self, observed, arg_bundle = None):\n\t\tpass",
"def monitor_cb(ud, msg):\r\n return False",
"def test_notify_run_status(self):\n pass",
"def notify (self, event):\n cblist = self._signals.get (event.signal, [])\n for callback in cblist:\n callback.run (event.data)",
"def handle_watch_event(self, event):",
"def isNotifying(self) -> \"SbBool\":\n return _coin.SoEngine_isNotifying(self)",
"def supports_function_notification(self):\n return # boolean",
"def try_notify(self):\n if self.last_notify_time == 0:\n notify_ready_time = 0\n else:\n notify_ready_time = self.last_notify_time + self.notify_pause\n\n if self.condition(self.arg) and notify_ready_time < time.time():\n self.notify()\n self.last_notify_time = time.time()",
"def reliable_event_notifications(self):\n pass",
"def haveSignal(signame):",
"def isNotifying(self) -> \"SbBool\":\n return _coin.SoNodeEngine_isNotifying(self)",
"def notify(info):\n __notifier.notify(info)",
"def JobWillPublishInBackground(self) -> bool:",
"def notify(self, *args, **kwargs):\n\t\tself.server.notify(self, *args, **kwargs)",
"def can_register_for_event_notifications(self):\n return # boolean",
"def supports_function_notification(self):\n return False # Change to True when implemented.",
"def quit_signal(self):\n\t\tprint 'Emitted a quit signal'",
"def signal_changed(self, message):\n self.view.signal_changed(self.model)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QCoreApplication.postEvent(QObject, QEvent) QCoreApplication.postEvent(QObject, QEvent, int)
|
def postEvent(self, QObject, QEvent, p_int=None): # real signature unknown; restored from __doc__ with multiple overloads
pass
|
[
"def sendEvent(self, QObject, QEvent): # real signature unknown; restored from __doc__\r\n return False",
"def sendEvent(self, QGraphicsItem, QEvent): # real signature unknown; restored from __doc__\r\n return False",
"def test_qeventloop_exec(qtbot):\n assert QtCore.QEventLoop.exec_ is not None\n assert QtCore.QEventLoop.exec is not None\n event_loop = QtCore.QEventLoop(None)\n QtCore.QTimer.singleShot(100, event_loop.quit)\n event_loop.exec_()\n QtCore.QTimer.singleShot(100, event_loop.quit)\n event_loop.exec()",
"def handle_watch_event(self, event):",
"def event(self, e):\n self.queue.put(e)",
"def __init__(self):\n QObject.__init__(self)",
"def quit_signal(self):\n\t\tprint 'Emitted a quit signal'",
"def ProcessUiEvent(self, event):\n self.board.ProcessUiEvent(event)\n self.wheel.ProcessUiEvent(event)\n self.scoreboard.ProcessUiEvent(event)",
"def on_ask_event(self, event):\n self.event_dispatcher.dispatch_event( \n MyEvent ( MyEvent.RESPOND, self ) \n )",
"def on_end(self, event):\n pass",
"def process_events(self):\n pass",
"def addEventCallback(*args, **kwargs):\n \n pass",
"def event_handler(self):\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.done = True\n elif event.type == pg.KEYDOWN:\n self.toggle_show_fps(event.key)\n\n self.ui.state_events(self.state, event)\n\n self.state.get_event(event)",
"def OnButton(self,e):\n self.queue.put('button!')",
"def send(self, event):\n pass",
"def postUserEvent(*args, **kwargs):\n \n pass",
"def mouseMoveEvent(self, moveEvent):\n if self.grabbedByWidget==True: \n QGraphicsItem.mouseMoveEvent(self, moveEvent) \n else:\n QGraphicsProxyWidget.mouseMoveEvent(self, moveEvent)",
"def on_idle(self, *args):",
"def publish(event):\n if event.signal in Framework._subscriber_table:\n for act in Framework._subscriber_table[event.signal]:\n act.postFIFO(event)\n # Run to completion\n Framework.get_event_loop().call_soon_threadsafe(Framework.run)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QCoreApplication.sendEvent(QObject, QEvent) > bool
|
def sendEvent(self, QObject, QEvent): # real signature unknown; restored from __doc__
return False
|
[
"def sendEvent(self, QGraphicsItem, QEvent): # real signature unknown; restored from __doc__\r\n return False",
"def can_handle(cls, event: dict) -> bool:",
"def check_event(self, event):\n # pylint: disable=R0201, W0613\n return True",
"def test_qeventloop_exec(qtbot):\n assert QtCore.QEventLoop.exec_ is not None\n assert QtCore.QEventLoop.exec is not None\n event_loop = QtCore.QEventLoop(None)\n QtCore.QTimer.singleShot(100, event_loop.quit)\n event_loop.exec_()\n QtCore.QTimer.singleShot(100, event_loop.quit)\n event_loop.exec()",
"def handle_watch_event(self, event):",
"def send(self, event):\n pass",
"def event(self,ev):\n if ev.type()==QtCore.QEvent.User:\n ErrorDialog.postError(ev.error)\n return True\n return QtWidgets.QWidget.event(self,ev)",
"def postEvent(self, QObject, QEvent, p_int=None): # real signature unknown; restored from __doc__ with multiple overloads\r\n pass",
"def processEventQueue(self) -> \"SbBool\":\n return _coin.ScXMLEventTarget_processEventQueue(self)",
"def processEvent(self, event: 'SoEvent') -> \"SbBool\":\n return _coin.SoEventManager_processEvent(self, event)",
"def check_for_event(self):\r\n a=self.read_chat(0)\r\n event=False\r\n finmes=\"\"\r\n next=False\r\n for m in a:\r\n if next==True:\r\n finmes=m\r\n break\r\n\r\n elif \"event\" in m:\r\n event=True\r\n next=True\r\n\r\n\r\n if event==True:\r\n finmes+=\" \"\r\n t1=finmes[finmes.find(\"Type\")+5:-1]\r\n\r\n self.write_to_chat(t1)\r\n\r\n t2=finmes[finmes.find(\"type\")+5:-1]\r\n self.write_to_chat(t2)\r\n\r\n for i in range(5):\r\n self.write_to_chat(t2)\r\n sleep(0.8)\r\n self.write_to_chat(t1)\r\n sleep(0.8)\r\n\r\n return True\r\n\r\n else:\r\n return False",
"def processEvent(self, event: 'SoEvent') -> \"SbBool\":\n return _coin.SoSceneManager_processEvent(self, event)",
"def check_events(self, event:Event):\n pass",
"def haveSignal(signame):",
"def accept(self, event: Event) -> bool:\n return isinstance(event, self.handled_event_class)",
"def ask(self):\n print(\">>> I'm instance {0}. Who are listening to me ?\".format( self ))\n\n self.event_dispatcher.dispatch_event( \n MyEvent( MyEvent.ASK, self ) \n )",
"def left_click(self):\n loop = QEventLoop()\n self.__parent._qt_invocation.async_js_finished.connect(loop.quit)\n self.__run_js(Utils.qt_js_prepare('Qt.click(\"{0}\")').format(self.node_id))\n loop.exec()\n print('after click')",
"def on_ask_event(self, event):\n self.event_dispatcher.dispatch_event( \n MyEvent ( MyEvent.RESPOND, self ) \n )",
"def test_qthread_exec():\n assert QtCore.QThread.exec_ is not None\n assert QtCore.QThread.exec is not None"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
QCoreApplication.translate(str, str, str disambiguation=None, QCoreApplication.Encoding encoding=QCoreApplication.CodecForTr) > QString QCoreApplication.translate(str, str, str, QCoreApplication.Encoding, int) > QString
|
def translate(p_str, p_str_1, *__args): # real signature unknown; restored from __doc__ with multiple overloads
return QString
|
[
"def translate(input_str, lang_source, lang_target):\n pass",
"def translation(text):\n\tinput_text = TextBlob(text)\n\tclick.secho(\"Text Translation\",fg='black',bg='white')\n\tclick.secho(\"Original Text: {}\".format(text),fg='yellow')\n\tclick.secho(\"Translated Text {}\".format(input_text.translate(to='en')),fg='green')",
"def _subs_latin_with_cyrillic(self, word: str):\n return word.translate(self.from_lat_translator)",
"def _translate(self, srcString: str, charsToReplace: str, replacementChars: str, deleteChars: str = None) -> str:\n if deleteChars is None:\n return srcString.translate(str.maketrans(charsToReplace, replacementChars, \"\"))\n return srcString.translate(str.maketrans(charsToReplace, replacementChars, deleteChars))",
"def translateStrings(language_code):\n from translate_admin import translateAdminStrings\n from translate_frontend import translateFrontendStrings\n from translate_help import translateHelpStrings\n from translate_login import translateLoginStrings\n\n translateAdminStrings(language_code)\n translateFrontendStrings(language_code)\n translateHelpStrings(language_code)\n translateLoginStrings(language_code)",
"def translate(text, f=\"en\", t=\"ja\"):\r\n # unicode -> string (utf8)\r\n # urlencode does not allow unicode.\r\n if isinstance(text, unicode):\r\n text = text.encode(\"utf8\")\r\n\r\n # Access to Translation API\r\n data = {\r\n \"q\": text,\r\n \"v\": \"1.0\",\r\n \"hl\": \"ja\",\r\n \"langpair\": \"%s|%s\" % (f, t),\r\n }\r\n f = urllib.urlopen(\"http://ajax.googleapis.com/ajax/services/language/translate\",\r\n urllib.urlencode(data))\r\n\r\n # Result\r\n ret = json.loads(f.read())\r\n\r\n if ret[\"responseStatus\"] != 200:\r\n raise IOError(ret.get(\"responseDetails\", \"\"))\r\n\r\n return ret[\"responseData\"][\"translatedText\"]",
"def translate(translate_from, translate_to, string_to_translate=\"\"):\n params = {'key': API_KEY,\n 'text': string_to_translate,\n 'lang': '%s-%s' % (translate_from, translate_to)}\n\n response = requests.get(API_URL, params)\n\n try:\n result = response.json()\n except ValueError:\n print(\"Yandex: service request error: failed to decode json\")\n return\n\n if str(result['code']) == '200':\n print(\"Yandex: \", result['text'])\n else:\n print(\"Yandex: request error, message: %s\" % result['message'])",
"def __init__(self, encoding):\n self.trans = {}\n for char in 'ÀÁÂẦẤẪẨẬÃĀĂẰẮẴẶẲȦǠẠḀȂĄǍẢ':\n self.trans[char] = 'A'\n for char in 'ȀǞ':\n self.trans[char] = 'Ä'\n self.trans['Ǻ'] = 'Å'\n self.trans['Ä'] = 'Ae'\n self.trans['Å'] = 'Aa'\n for char in 'àáâầấẫẩậãāăằắẵặẳȧǡạḁȃąǎảẚ':\n self.trans[char] = 'a'\n for char in 'ȁǟ':\n self.trans[char] = 'ä'\n self.trans['ǻ'] = 'å'\n self.trans['ä'] = 'ae'\n self.trans['å'] = 'aa'\n for char in 'ḂḄḆƁƂ':\n self.trans[char] = 'B'\n for char in 'ḃḅḇƀɓƃ':\n self.trans[char] = 'b'\n for char in 'ĆĈĊÇČƇ':\n self.trans[char] = 'C'\n for char in 'ćĉċçčƈȼ':\n self.trans[char] = 'c'\n self.trans['Ḉ'] = 'Ç'\n self.trans['ḉ'] = 'ç'\n self.trans['Ð'] = 'Dh'\n self.trans['ð'] = 'dh'\n for char in 'ĎḊḌḎḐḒĐƉƊƋ':\n self.trans[char] = 'D'\n for char in 'ďḋḍḏḑḓđɖɗƌ':\n self.trans[char] = 'd'\n for char in 'ÈȄÉÊḚËĒḔḖĔĖẸE̩ȆȨḜĘĚẼḘẺ':\n self.trans[char] = 'E'\n for char in 'ỀẾỄỆỂ':\n self.trans[char] = 'Ê'\n for char in 'èȅéêḛëēḕḗĕėẹe̩ȇȩḝęěẽḙẻ':\n self.trans[char] = 'e'\n for char in 'ềếễệể':\n self.trans[char] = 'ê'\n for char in 'ḞƑ':\n self.trans[char] = 'F'\n for char in 'ḟƒ':\n self.trans[char] = 'f'\n for char in 'ǴḠĞĠĢǦǤƓ':\n self.trans[char] = 'G'\n for char in 'ǵḡğġģǧǥɠ':\n self.trans[char] = 'g'\n self.trans['Ĝ'] = 'Gx'\n self.trans['ĝ'] = 'gx'\n for char in 'ḢḤḦȞḨḪH̱ĦǶ':\n self.trans[char] = 'H'\n for char in 'ḣḥḧȟḩḫ̱ẖħƕ':\n self.trans[char] = 'h'\n for char in 'IÌȈÍÎĨḬÏḮĪĬȊĮǏİỊỈƗ':\n self.trans[char] = 'I'\n for char in 'ıìȉíîĩḭïḯīĭȋįǐiịỉɨ':\n self.trans[char] = 'i'\n for char in 'ĴJ':\n self.trans[char] = 'J'\n for char in 'ɟĵ̌ǰ':\n self.trans[char] = 'j'\n for char in 'ḰǨĶḲḴƘ':\n self.trans[char] = 'K'\n for char in 'ḱǩķḳḵƙ':\n self.trans[char] = 'k'\n for char in 'ĹĻĽḶḸḺḼȽŁ':\n self.trans[char] = 'L'\n for char in 'ĺļľḷḹḻḽƚłɫ':\n self.trans[char] = 'l'\n for char in 'ḾṀṂ':\n self.trans[char] = 'M'\n for char in 'ḿṁṃɱ':\n self.trans[char] = 'm'\n for char in 'ǸŃÑŅŇṄṆṈṊŊƝɲȠ':\n self.trans[char] = 'N'\n for char in 'ǹńñņňṅṇṉṋŋɲƞ':\n self.trans[char] = 'n'\n for char in 'ÒÓÔÕṌṎȬÖŌṐṒŎǑȮȰỌǪǬƠỜỚỠỢỞỎƟØǾ':\n self.trans[char] = 'O'\n for char in 'òóôõṍṏȭöōṑṓŏǒȯȱọǫǭơờớỡợởỏɵøǿ':\n self.trans[char] = 'o'\n for char in 'ȌŐȪ':\n self.trans[char] = 'Ö'\n for char in 'ȍőȫ':\n self.trans[char] = 'ö'\n for char in 'ỒỐỖỘỔȎ':\n self.trans[char] = 'Ô'\n for char in 'ồốỗộổȏ':\n self.trans[char] = 'ô'\n for char in 'ṔṖƤ':\n self.trans[char] = 'P'\n for char in 'ṕṗƥ':\n self.trans[char] = 'p'\n self.trans['ᵽ'] = 'q'\n for char in 'ȐŔŖŘȒṘṚṜṞ':\n self.trans[char] = 'R'\n for char in 'ȑŕŗřȓṙṛṝṟɽ':\n self.trans[char] = 'r'\n for char in 'ŚṤŞȘŠṦṠṢṨ':\n self.trans[char] = 'S'\n for char in 'śṥşșšṧṡṣṩȿ':\n self.trans[char] = 's'\n self.trans['Ŝ'] = 'Sx'\n self.trans['ŝ'] = 'sx'\n for char in 'ŢȚŤṪṬṮṰŦƬƮ':\n self.trans[char] = 'T'\n for char in 'ţțťṫṭṯṱŧȾƭʈ':\n self.trans[char] = 't'\n for char in 'ÙÚŨṸṴÜṲŪṺŬỤŮŲǓṶỦƯỮỰỬ':\n self.trans[char] = 'U'\n for char in 'ùúũṹṵüṳūṻŭụůųǔṷủưữựửʉ':\n self.trans[char] = 'u'\n for char in 'ȔŰǛǗǕǙ':\n self.trans[char] = 'Ü'\n for char in 'ȕűǜǘǖǚ':\n self.trans[char] = 'ü'\n self.trans['Û'] = 'Ux'\n self.trans['û'] = 'ux'\n self.trans['Ȗ'] = 'Û'\n self.trans['ȗ'] = 'û'\n self.trans['Ừ'] = 'Ù'\n self.trans['ừ'] = 'ù'\n self.trans['Ứ'] = 'Ú'\n self.trans['ứ'] = 'ú'\n for char in 'ṼṾ':\n self.trans[char] = 'V'\n for char in 'ṽṿ':\n self.trans[char] = 'v'\n for char in 'ẀẂŴẄẆẈ':\n self.trans[char] = 'W'\n for char in 'ẁẃŵẅẇẉ':\n self.trans[char] = 'w'\n for char in 'ẊẌ':\n self.trans[char] = 'X'\n for char in 'ẋẍ':\n self.trans[char] = 'x'\n for char in 'ỲÝŶŸỸȲẎỴỶƳ':\n self.trans[char] = 'Y'\n for char in 'ỳýŷÿỹȳẏỵỷƴ':\n self.trans[char] = 'y'\n for char in 'ŹẐŻẒŽẔƵȤ':\n self.trans[char] = 'Z'\n for char in 'źẑżẓžẕƶȥ':\n self.trans[char] = 'z'\n self.trans['ɀ'] = 'zv'\n\n # Latin: extended Latin alphabet\n self.trans['ɑ'] = 'a'\n for char in 'ÆǼǢ':\n self.trans[char] = 'AE'\n for char in 'æǽǣ':\n self.trans[char] = 'ae'\n self.trans['Ð'] = 'Dh'\n self.trans['ð'] = 'dh'\n for char in 'ƎƏƐ':\n self.trans[char] = 'E'\n for char in 'ǝəɛ':\n self.trans[char] = 'e'\n for char in 'ƔƢ':\n self.trans[char] = 'G'\n for char in 'ᵷɣƣᵹ':\n self.trans[char] = 'g'\n self.trans['Ƅ'] = 'H'\n self.trans['ƅ'] = 'h'\n self.trans['Ƕ'] = 'Wh'\n self.trans['ƕ'] = 'wh'\n self.trans['Ɩ'] = 'I'\n self.trans['ɩ'] = 'i'\n self.trans['Ŋ'] = 'Ng'\n self.trans['ŋ'] = 'ng'\n self.trans['Œ'] = 'OE'\n self.trans['œ'] = 'oe'\n self.trans['Ɔ'] = 'O'\n self.trans['ɔ'] = 'o'\n self.trans['Ȣ'] = 'Ou'\n self.trans['ȣ'] = 'ou'\n self.trans['Ƽ'] = 'Q'\n for char in 'ĸƽ':\n self.trans[char] = 'q'\n self.trans['ȹ'] = 'qp'\n self.trans[''] = 'r'\n self.trans['ſ'] = 's'\n self.trans['ß'] = 'ss'\n self.trans['Ʃ'] = 'Sh'\n for char in 'ʃᶋ':\n self.trans[char] = 'sh'\n self.trans['Ʉ'] = 'U'\n self.trans['ʉ'] = 'u'\n self.trans['Ʌ'] = 'V'\n self.trans['ʌ'] = 'v'\n for char in 'ƜǷ':\n self.trans[char] = 'W'\n for char in 'ɯƿ':\n self.trans[char] = 'w'\n self.trans['Ȝ'] = 'Y'\n self.trans['ȝ'] = 'y'\n self.trans['IJ'] = 'IJ'\n self.trans['ij'] = 'ij'\n self.trans['Ƨ'] = 'Z'\n for char in 'ʮƨ':\n self.trans[char] = 'z'\n self.trans['Ʒ'] = 'Zh'\n self.trans['ʒ'] = 'zh'\n self.trans['Ǯ'] = 'Dzh'\n self.trans['ǯ'] = 'dzh'\n for char in 'ƸƹʔˀɁɂ':\n self.trans[char] = u\"'\"\n self.trans['Þ'] = 'Th'\n self.trans['þ'] = 'th'\n for char in 'Cʗǃ':\n self.trans[char] = '!'\n\n # Punctuation and typography\n for char in '«»“”„¨':\n self.trans[char] = u'\"'\n for char in '‘’′':\n self.trans[char] = u\"'\"\n self.trans['•'] = '*'\n self.trans['@'] = '(at)'\n self.trans['¤'] = '$'\n self.trans['¢'] = 'c'\n self.trans['€'] = 'E'\n self.trans['£'] = 'L'\n self.trans['¥'] = 'yen'\n self.trans['†'] = '+'\n self.trans['‡'] = '++'\n self.trans['°'] = ':'\n self.trans['¡'] = '!'\n self.trans['¿'] = '?'\n self.trans['‰'] = 'o/oo'\n self.trans['‱'] = 'o/ooo'\n for char in '¶§':\n self.trans[char] = '>'\n self.trans['…'] = '...'\n for char in '‒–—―':\n self.trans[char] = '-'\n self.trans['·'] = ' '\n self.trans['¦'] = '|'\n self.trans['⁂'] = '***'\n self.trans['◊'] = '<>'\n self.trans['‽'] = '?!'\n self.trans['؟'] = ';-)'\n self.trans['¹'] = '1'\n self.trans['²'] = '2'\n self.trans['³'] = '3'\n\n # Cyrillic\n self.trans.update({'А': 'A', 'а': 'a', 'Б': 'B', 'б': 'b',\n 'В': 'V', 'в': 'v', 'Г': 'G', 'г': 'g',\n 'Д': 'D', 'д': 'd', 'Е': 'E', 'е': 'e',\n 'Ж': 'Zh', 'ж': 'zh', 'З': 'Z', 'з': 'z',\n 'И': 'I', 'и': 'i', 'Й': 'J', 'й': 'j',\n 'К': 'K', 'к': 'k', 'Л': 'L', 'л': 'l',\n 'М': 'M', 'м': 'm', 'Н': 'N', 'н': 'n',\n 'О': 'O', 'о': 'o', 'П': 'P', 'п': 'p',\n 'Р': 'R', 'р': 'r', 'С': 'S', 'с': 's',\n 'Т': 'T', 'т': 't', 'У': 'U', 'у': 'u',\n 'Ф': 'F', 'ф': 'f', 'х': 'kh', 'Ц': 'C',\n 'ц': 'c', 'Ч': 'Ch', 'ч': 'ch', 'Ш': 'Sh',\n 'ш': 'sh', 'Щ': 'Shch', 'щ': 'shch', 'Ь': \"'\",\n 'ь': \"'\", 'Ъ': '\"', 'ъ': '\"', 'Ю': 'Yu',\n 'ю': 'yu', 'Я': 'Ya', 'я': 'ya', 'Х': 'Kh',\n 'Χ': 'Kh'})\n\n # Additional Cyrillic letters, most occuring in only a few languages\n self.trans.update({\n 'Ы': 'Y', 'ы': 'y', 'Ё': 'Ë', 'ё': 'ë',\n 'Э': 'È', 'Ѐ': 'È', 'э': 'è', 'ѐ': 'è',\n 'І': 'I', 'і': 'i', 'Ї': 'Ji', 'ї': 'ji',\n 'Є': 'Je', 'є': 'je', 'Ґ': 'G', 'Ҝ': 'G',\n 'ґ': 'g', 'ҝ': 'g', 'Ђ': 'Dj', 'ђ': 'dj',\n 'Љ': 'Lj', 'љ': 'lj',\n 'Њ': 'Nj', 'њ': 'nj', 'Ћ': 'Cj', 'ћ': 'cj',\n 'Җ': 'Zhj', 'Ѓ': 'Gj', 'ѓ': 'gj',\n 'Ќ': 'Kj', 'ќ': 'kj', 'Ӣ': 'Ii', 'ӣ': 'ii',\n 'Ҳ': 'H', 'ҳ': 'h',\n 'Ҷ': 'Dz', 'ҷ': 'dz', 'Ө': 'Ô', 'Ӫ': 'Ô',\n 'ө': 'ô', 'ӫ': 'ô', 'Ү': 'Y', 'ү': 'y', 'Һ': 'H',\n 'һ': 'h', 'Ә': 'AE', 'Ӕ': 'AE', 'ә': 'ae',\n 'Ӛ': 'Ë', 'Ӭ': 'Ë', 'ӛ': 'ë', 'ӭ': 'ë',\n 'җ': 'zhj', 'Ұ': 'U', 'ў': 'ù', 'Ў': 'Ù',\n 'ѝ': 'ì', 'Ѝ': 'Ì', 'Ӑ': 'A', 'ă': 'a', 'Ӓ': 'Ä',\n 'Ҽ': 'Ts', 'Ҿ': 'Ts', 'ҽ': 'ts', 'ҿ': 'ts',\n 'Ҙ': 'Dh', 'ҙ': 'dh', 'Ӏ': '', 'ӏ': '', 'Ӆ': 'L',\n 'ӆ': 'l', 'Ӎ': 'M', 'ӎ': 'm', 'Ӧ': 'Ö', 'ӧ': 'ö',\n 'Ҩ': 'u', 'ҩ': 'u', 'Ҧ': 'Ph', 'ҧ': 'ph', 'Ҏ': 'R',\n 'ҏ': 'r', 'Ҫ': 'Th', 'ҫ': 'th', 'Ҭ': 'T', 'ҭ': 't',\n 'Ӯ': 'Û', 'ӯ': 'û', 'Ӹ': 'U', 'ұ': 'u',\n 'ӹ': 'u', 'Ҵ': 'Tts', 'ҵ': 'tts', 'Ӵ': 'Ch', 'ӵ': 'ch'})\n\n for char in 'ЈӤҊ':\n self.trans[char] = 'J'\n for char in 'јӥҋ':\n self.trans[char] = 'j'\n for char in 'ЏӁӜҶ':\n self.trans[char] = 'Dzh'\n for char in 'џӂӝҷ':\n self.trans[char] = 'dzh'\n for char in 'ЅӞӠӋҸ':\n self.trans[char] = 'Dz'\n for char in 'ѕӟӡӌҹ':\n self.trans[char] = 'dz'\n for char in 'ҒӶҔ':\n self.trans[char] = 'G'\n for char in 'ғӷҕ':\n self.trans[char] = 'g'\n for char in 'ҚҞҠӃ':\n self.trans[char] = 'Q'\n for char in 'қҟҡӄ':\n self.trans[char] = 'q'\n for char in 'ҢҤӉӇ':\n self.trans[char] = 'Ng'\n for char in 'ңҥӊӈ':\n self.trans[char] = 'ng'\n for char in 'ӖѢҌ':\n self.trans[char] = 'E'\n for char in 'ӗѣҍ':\n self.trans[char] = 'e'\n for char in 'ӲӰҮ':\n self.trans[char] = 'Ü'\n for char in 'ӳӱү':\n self.trans[char] = 'ü'\n\n # Archaic Cyrillic letters\n self.trans.update({\n 'Ѹ': 'Ou', 'ѹ': 'ou', 'Ѡ': 'O', 'Ѻ': 'O', 'ѡ': 'o',\n 'ѻ': 'o', 'Ѿ': 'Ot', 'ѿ': 'ot', 'Ѣ': 'E', 'ѣ': 'e',\n 'Ѥ': 'Ei', 'Ѧ': 'Ei', 'ѥ': 'ei', 'ѧ': 'ei', 'Ѫ': 'Ai',\n 'ѫ': 'ai', 'Ѯ': 'X', 'ѯ': 'x', 'Ѱ': 'Ps', 'ѱ': 'ps',\n 'Ѳ': 'Th', 'ѳ': 'th', 'Ѵ': 'Ü', 'Ѷ': 'Ü', 'ѵ': 'ü'})\n\n # Hebrew alphabet\n for char in 'אע':\n self.trans[char] = u\"'\"\n self.trans['ב'] = 'b'\n self.trans['ג'] = 'g'\n self.trans['ד'] = 'd'\n self.trans['ה'] = 'h'\n self.trans['ו'] = 'v'\n self.trans['ז'] = 'z'\n self.trans['ח'] = 'kh'\n self.trans['ט'] = 't'\n self.trans['י'] = 'y'\n for char in 'ךכ':\n self.trans[char] = 'k'\n self.trans['ל'] = 'l'\n for char in 'םמ':\n self.trans[char] = 'm'\n for char in 'ןנ':\n self.trans[char] = 'n'\n self.trans['ס'] = 's'\n for char in 'ףפ':\n self.trans[char] = 'ph'\n for char in 'ץצ':\n self.trans[char] = 'ts'\n self.trans['ק'] = 'q'\n self.trans['ר'] = 'r'\n self.trans['ש'] = 'sh'\n self.trans['ת'] = 'th'\n\n # Arab alphabet\n for char in 'اﺍﺎ':\n self.trans[char] = 'a'\n for char in 'بﺏﺐﺒﺑ':\n self.trans[char] = 'b'\n for char in 'تﺕﺖﺘﺗ':\n self.trans[char] = 't'\n for char in 'ثﺙﺚﺜﺛ':\n self.trans[char] = 'th'\n for char in 'جﺝﺞﺠﺟ':\n self.trans[char] = 'g'\n for char in 'حﺡﺢﺤﺣ':\n self.trans[char] = 'h'\n for char in 'خﺥﺦﺨﺧ':\n self.trans[char] = 'kh'\n for char in 'دﺩﺪ':\n self.trans[char] = 'd'\n for char in 'ذﺫﺬ':\n self.trans[char] = 'dh'\n for char in 'رﺭﺮ':\n self.trans[char] = 'r'\n for char in 'زﺯﺰ':\n self.trans[char] = 'z'\n for char in 'سﺱﺲﺴﺳ':\n self.trans[char] = 's'\n for char in 'شﺵﺶﺸﺷ':\n self.trans[char] = 'sh'\n for char in 'صﺹﺺﺼﺻ':\n self.trans[char] = 's'\n for char in 'ضﺽﺾﻀﺿ':\n self.trans[char] = 'd'\n for char in 'طﻁﻂﻄﻃ':\n self.trans[char] = 't'\n for char in 'ظﻅﻆﻈﻇ':\n self.trans[char] = 'z'\n for char in 'عﻉﻊﻌﻋ':\n self.trans[char] = u\"'\"\n for char in 'غﻍﻎﻐﻏ':\n self.trans[char] = 'gh'\n for char in 'فﻑﻒﻔﻓ':\n self.trans[char] = 'f'\n for char in 'قﻕﻖﻘﻗ':\n self.trans[char] = 'q'\n for char in 'كﻙﻚﻜﻛک':\n self.trans[char] = 'k'\n for char in 'لﻝﻞﻠﻟ':\n self.trans[char] = 'l'\n for char in 'مﻡﻢﻤﻣ':\n self.trans[char] = 'm'\n for char in 'نﻥﻦﻨﻧ':\n self.trans[char] = 'n'\n for char in 'هﻩﻪﻬﻫ':\n self.trans[char] = 'h'\n for char in 'وﻭﻮ':\n self.trans[char] = 'w'\n for char in 'یيﻱﻲﻴﻳ':\n self.trans[char] = 'y'\n # Arabic - additional letters, modified letters and ligatures\n self.trans['ﺀ'] = \"'\"\n for char in 'آﺁﺂ':\n self.trans[char] = u\"'a\"\n for char in 'ةﺓﺔ':\n self.trans[char] = 'th'\n for char in 'ىﻯﻰ':\n self.trans[char] = 'á'\n for char in 'یﯼﯽﯿﯾ':\n self.trans[char] = 'y'\n self.trans['؟'] = '?'\n # Arabic - ligatures\n for char in 'ﻻﻼ':\n self.trans[char] = 'la'\n self.trans['ﷲ'] = 'llah'\n for char in 'إأ':\n self.trans[char] = u\"a'\"\n self.trans['ؤ'] = \"w'\"\n self.trans['ئ'] = \"y'\"\n for char in '◌◌':\n self.trans[char] = \"\" # indicates absence of vowels\n # Arabic vowels\n self.trans['◌'] = 'a'\n self.trans['◌'] = 'u'\n self.trans['◌'] = 'i'\n self.trans['◌'] = 'a'\n self.trans['◌'] = 'ay'\n self.trans['◌'] = 'ay'\n self.trans['◌'] = 'u'\n self.trans['◌'] = 'iy'\n # Arab numerals\n for char in '٠۰':\n self.trans[char] = '0'\n for char in '١۱':\n self.trans[char] = '1'\n for char in '٢۲':\n self.trans[char] = '2'\n for char in '٣۳':\n self.trans[char] = '3'\n for char in '٤۴':\n self.trans[char] = '4'\n for char in '٥۵':\n self.trans[char] = '5'\n for char in '٦۶':\n self.trans[char] = '6'\n for char in '٧۷':\n self.trans[char] = '7'\n for char in '٨۸':\n self.trans[char] = '8'\n for char in '٩۹':\n self.trans[char] = '9'\n # Perso-Arabic\n for char in 'پﭙﭙپ':\n self.trans[char] = 'p'\n for char in 'چچچچ':\n self.trans[char] = 'ch'\n for char in 'ژژ':\n self.trans[char] = 'zh'\n for char in 'گﮔﮕﮓ':\n self.trans[char] = 'g'\n\n # Greek\n self.trans.update({\n 'Α': 'A', 'α': 'a', 'Β': 'B', 'β': 'b', 'Γ': 'G',\n 'γ': 'g', 'Δ': 'D', 'δ': 'd', 'Ε': 'E', 'ε': 'e',\n 'Ζ': 'Z', 'ζ': 'z', 'Η': 'I', 'η': 'i', 'θ': 'th',\n 'Θ': 'Th', 'Ι': 'I', 'ι': 'i', 'Κ': 'K', 'κ': 'k',\n 'Λ': 'L', 'λ': 'l', 'Μ': 'M', 'μ': 'm', 'Ν': 'N',\n 'ν': 'n', 'Ξ': 'X', 'ξ': 'x', 'Ο': 'O', 'ο': 'o',\n 'Π': 'P', 'π': 'p', 'Ρ': 'R', 'ρ': 'r', 'Σ': 'S',\n 'σ': 's', 'ς': 's', 'Τ': 'T', 'τ': 't', 'Υ': 'Y',\n 'υ': 'y', 'Φ': 'F', 'φ': 'f', 'Ψ': 'Ps', 'ψ': 'ps',\n 'Ω': 'O', 'ω': 'o', 'ϗ': '&', 'Ϛ': 'St', 'ϛ': 'st',\n 'Ϙ': 'Q', 'Ϟ': 'Q', 'ϙ': 'q', 'ϟ': 'q', 'Ϻ': 'S',\n 'ϻ': 's', 'Ϡ': 'Ss', 'ϡ': 'ss', 'Ϸ': 'Sh', 'ϸ': 'sh',\n '·': ':', 'Ά': 'Á', 'ά': 'á', 'Έ': 'É', 'Ή': 'É',\n 'έ': 'é', 'ή': 'é', 'Ί': 'Í', 'ί': 'í', 'Ϊ': 'Ï',\n 'ϊ': 'ï', 'ΐ': 'ï', 'Ό': 'Ó', 'ό': 'ó', 'Ύ': 'Ý',\n 'ύ': 'ý', 'Ϋ': 'Y', 'ϋ': 'ÿ', 'ΰ': 'ÿ', 'Ώ': 'Ó',\n 'ώ': 'ó'})\n\n # Japanese (katakana and hiragana)\n for char in 'アァあ':\n self.trans[char] = 'a'\n for char in 'イィい':\n self.trans[char] = 'i'\n for char in 'ウう':\n self.trans[char] = 'u'\n for char in 'エェえ':\n self.trans[char] = 'e'\n for char in 'オォお':\n self.trans[char] = 'o'\n for char in 'ャや':\n self.trans[char] = 'ya'\n for char in 'ュゆ':\n self.trans[char] = 'yu'\n for char in 'ョよ':\n self.trans[char] = 'yo'\n for char in 'カか':\n self.trans[char] = 'ka'\n for char in 'キき':\n self.trans[char] = 'ki'\n for char in 'クく':\n self.trans[char] = 'ku'\n for char in 'ケけ':\n self.trans[char] = 'ke'\n for char in 'コこ':\n self.trans[char] = 'ko'\n for char in 'サさ':\n self.trans[char] = 'sa'\n for char in 'シし':\n self.trans[char] = 'shi'\n for char in 'スす':\n self.trans[char] = 'su'\n for char in 'セせ':\n self.trans[char] = 'se'\n for char in 'ソそ':\n self.trans[char] = 'so'\n for char in 'タた':\n self.trans[char] = 'ta'\n for char in 'チち':\n self.trans[char] = 'chi'\n for char in 'ツつ':\n self.trans[char] = 'tsu'\n for char in 'テて':\n self.trans[char] = 'te'\n for char in 'トと':\n self.trans[char] = 'to'\n for char in 'ナな':\n self.trans[char] = 'na'\n for char in 'ニに':\n self.trans[char] = 'ni'\n for char in 'ヌぬ':\n self.trans[char] = 'nu'\n for char in 'ネね':\n self.trans[char] = 'ne'\n for char in 'ノの':\n self.trans[char] = 'no'\n for char in 'ハは':\n self.trans[char] = 'ha'\n for char in 'ヒひ':\n self.trans[char] = 'hi'\n for char in 'フふ':\n self.trans[char] = 'fu'\n for char in 'ヘへ':\n self.trans[char] = 'he'\n for char in 'ホほ':\n self.trans[char] = 'ho'\n for char in 'マま':\n self.trans[char] = 'ma'\n for char in 'ミみ':\n self.trans[char] = 'mi'\n for char in 'ムむ':\n self.trans[char] = 'mu'\n for char in 'メめ':\n self.trans[char] = 'me'\n for char in 'モも':\n self.trans[char] = 'mo'\n for char in 'ラら':\n self.trans[char] = 'ra'\n for char in 'リり':\n self.trans[char] = 'ri'\n for char in 'ルる':\n self.trans[char] = 'ru'\n for char in 'レれ':\n self.trans[char] = 're'\n for char in 'ロろ':\n self.trans[char] = 'ro'\n for char in 'ワわ':\n self.trans[char] = 'wa'\n for char in 'ヰゐ':\n self.trans[char] = 'wi'\n for char in 'ヱゑ':\n self.trans[char] = 'we'\n for char in 'ヲを':\n self.trans[char] = 'wo'\n for char in 'ンん':\n self.trans[char] = 'n'\n for char in 'ガが':\n self.trans[char] = 'ga'\n for char in 'ギぎ':\n self.trans[char] = 'gi'\n for char in 'グぐ':\n self.trans[char] = 'gu'\n for char in 'ゲげ':\n self.trans[char] = 'ge'\n for char in 'ゴご':\n self.trans[char] = 'go'\n for char in 'ザざ':\n self.trans[char] = 'za'\n for char in 'ジじ':\n self.trans[char] = 'ji'\n for char in 'ズず':\n self.trans[char] = 'zu'\n for char in 'ゼぜ':\n self.trans[char] = 'ze'\n for char in 'ゾぞ':\n self.trans[char] = 'zo'\n for char in 'ダだ':\n self.trans[char] = 'da'\n for char in 'ヂぢ':\n self.trans[char] = 'dji'\n for char in 'ヅづ':\n self.trans[char] = 'dzu'\n for char in 'デで':\n self.trans[char] = 'de'\n for char in 'ドど':\n self.trans[char] = 'do'\n for char in 'バば':\n self.trans[char] = 'ba'\n for char in 'ビび':\n self.trans[char] = 'bi'\n for char in 'ブぶ':\n self.trans[char] = 'bu'\n for char in 'ベべ':\n self.trans[char] = 'be'\n for char in 'ボぼ':\n self.trans[char] = 'bo'\n for char in 'パぱ':\n self.trans[char] = 'pa'\n for char in 'ピぴ':\n self.trans[char] = 'pi'\n for char in 'プぷ':\n self.trans[char] = 'pu'\n for char in 'ペぺ':\n self.trans[char] = 'pe'\n for char in 'ポぽ':\n self.trans[char] = 'po'\n for char in 'ヴゔ':\n self.trans[char] = 'vu'\n self.trans['ヷ'] = 'va'\n self.trans['ヸ'] = 'vi'\n self.trans['ヹ'] = 've'\n self.trans['ヺ'] = 'vo'\n\n # Japanese and Chinese punctuation and typography\n for char in '・·':\n self.trans[char] = ' '\n for char in '〃『』《》':\n self.trans[char] = u'\"'\n for char in '「」〈〉〘〙〚〛':\n self.trans[char] = u\"'\"\n for char in '(〔':\n self.trans[char] = '('\n for char in ')〕':\n self.trans[char] = ')'\n for char in '[【〖':\n self.trans[char] = '['\n for char in ']】〗':\n self.trans[char] = ']'\n self.trans['{'] = '{'\n self.trans['}'] = '}'\n self.trans['っ'] = ':'\n self.trans['ー'] = 'h'\n self.trans['゛'] = \"'\"\n self.trans['゜'] = 'p'\n self.trans['。'] = '. '\n self.trans['、'] = ', '\n self.trans['・'] = ' '\n self.trans['〆'] = 'shime'\n self.trans['〜'] = '-'\n self.trans['…'] = '...'\n self.trans['‥'] = '..'\n self.trans['ヶ'] = 'months'\n for char in '•◦':\n self.trans[char] = '_'\n for char in '※*':\n self.trans[char] = '*'\n self.trans['Ⓧ'] = '(X)'\n self.trans['Ⓨ'] = '(Y)'\n self.trans['!'] = '!'\n self.trans['?'] = '?'\n self.trans[';'] = ';'\n self.trans[':'] = ':'\n self.trans['。'] = '.'\n for char in ',、':\n self.trans[char] = ','\n\n # Georgian\n self.trans['ა'] = 'a'\n self.trans['ბ'] = 'b'\n self.trans['გ'] = 'g'\n self.trans['დ'] = 'd'\n for char in 'ეჱ':\n self.trans[char] = 'e'\n self.trans['ვ'] = 'v'\n self.trans['ზ'] = 'z'\n self.trans['თ'] = 'th'\n self.trans['ი'] = 'i'\n self.trans['კ'] = 'k'\n self.trans['ლ'] = 'l'\n self.trans['მ'] = 'm'\n self.trans['ნ'] = 'n'\n self.trans['ო'] = 'o'\n self.trans['პ'] = 'p'\n self.trans['ჟ'] = 'zh'\n self.trans['რ'] = 'r'\n self.trans['ს'] = 's'\n self.trans['ტ'] = 't'\n self.trans['უ'] = 'u'\n self.trans['ფ'] = 'ph'\n self.trans['ქ'] = 'q'\n self.trans['ღ'] = 'gh'\n for char in 'ყ':\n self.trans[char] = u\"q'\"\n self.trans['შ'] = 'sh'\n self.trans['ჩ'] = 'ch'\n self.trans['ც'] = 'ts'\n self.trans['ძ'] = 'dz'\n for char in 'წ':\n self.trans[char] = u\"ts'\"\n for char in 'ჭ':\n self.trans[char] = u\"ch'\"\n self.trans['ხ'] = 'kh'\n self.trans['ჯ'] = 'j'\n self.trans['ჰ'] = 'h'\n self.trans['ჳ'] = 'w'\n self.trans['ჵ'] = 'o'\n self.trans['ჶ'] = 'f'\n\n # Devanagari\n for char in 'पप':\n self.trans[char] = 'p'\n self.trans['अ'] = 'a'\n for char in 'आा':\n self.trans[char] = 'aa'\n self.trans['प'] = 'pa'\n for char in 'इि':\n self.trans[char] = 'i'\n for char in 'ईी':\n self.trans[char] = 'ii'\n for char in 'उु':\n self.trans[char] = 'u'\n for char in 'ऊू':\n self.trans[char] = 'uu'\n for char in 'एे':\n self.trans[char] = 'e'\n for char in 'ऐै':\n self.trans[char] = 'ai'\n for char in 'ओो':\n self.trans[char] = 'o'\n for char in 'औौ':\n self.trans[char] = 'au'\n for char in 'ऋृर':\n self.trans[char] = 'r'\n for char in 'ॠॄ':\n self.trans[char] = 'rr'\n for char in 'ऌॢल':\n self.trans[char] = 'l'\n for char in 'ॡॣ':\n self.trans[char] = 'll'\n self.trans['क'] = 'k'\n self.trans['ख'] = 'kh'\n self.trans['ग'] = 'g'\n self.trans['घ'] = 'gh'\n self.trans['ङ'] = 'ng'\n self.trans['च'] = 'c'\n self.trans['छ'] = 'ch'\n self.trans['ज'] = 'j'\n self.trans['झ'] = 'jh'\n self.trans['ञ'] = 'ñ'\n for char in 'टत':\n self.trans[char] = 't'\n for char in 'ठथ':\n self.trans[char] = 'th'\n for char in 'डद':\n self.trans[char] = 'd'\n for char in 'ढध':\n self.trans[char] = 'dh'\n for char in 'णन':\n self.trans[char] = 'n'\n self.trans['फ'] = 'ph'\n self.trans['ब'] = 'b'\n self.trans['भ'] = 'bh'\n self.trans['म'] = 'm'\n self.trans['य'] = 'y'\n self.trans['व'] = 'v'\n self.trans['श'] = 'sh'\n for char in 'षस':\n self.trans[char] = 's'\n self.trans['ह'] = 'h'\n self.trans['क'] = 'x'\n self.trans['त'] = 'tr'\n self.trans['ज'] = 'gj'\n for char in 'क़':\n self.trans[char] = 'q'\n self.trans['फ'] = 'f'\n self.trans['ख'] = 'hh'\n self.trans['H'] = 'gh'\n self.trans['ज'] = 'z'\n for char in 'डढ':\n self.trans[char] = 'r'\n # Devanagari ligatures (possibly incomplete and/or incorrect)\n for char in 'ख्':\n self.trans[char] = 'khn'\n self.trans['त'] = 'tn'\n for char in 'द्':\n self.trans[char] = 'dn'\n self.trans['श'] = 'cn'\n for char in 'ह्':\n self.trans[char] = 'fn'\n for char in 'अँ':\n self.trans[char] = 'm'\n for char in '॒॑':\n self.trans[char] = u\"\"\n self.trans['०'] = '0'\n self.trans['१'] = '1'\n self.trans['२'] = '2'\n self.trans['३'] = '3'\n self.trans['४'] = '4'\n self.trans['५'] = '5'\n self.trans['६'] = '6'\n self.trans['७'] = '7'\n self.trans['८'] = '8'\n self.trans['९'] = '9'\n\n # Armenian\n self.trans['Ա'] = 'A'\n self.trans['ա'] = 'a'\n self.trans['Բ'] = 'B'\n self.trans['բ'] = 'b'\n self.trans['Գ'] = 'G'\n self.trans['գ'] = 'g'\n self.trans['Դ'] = 'D'\n self.trans['դ'] = 'd'\n self.trans['Ե'] = 'Je'\n self.trans['ե'] = 'e'\n self.trans['Զ'] = 'Z'\n self.trans['զ'] = 'z'\n self.trans['Է'] = 'É'\n self.trans['է'] = 'é'\n self.trans['Ը'] = 'Ë'\n self.trans['ը'] = 'ë'\n self.trans['Թ'] = 'Th'\n self.trans['թ'] = 'th'\n self.trans['Ժ'] = 'Zh'\n self.trans['ժ'] = 'zh'\n self.trans['Ի'] = 'I'\n self.trans['ի'] = 'i'\n self.trans['Լ'] = 'L'\n self.trans['լ'] = 'l'\n self.trans['Խ'] = 'Ch'\n self.trans['խ'] = 'ch'\n self.trans['Ծ'] = 'Ts'\n self.trans['ծ'] = 'ts'\n self.trans['Կ'] = 'K'\n self.trans['կ'] = 'k'\n self.trans['Հ'] = 'H'\n self.trans['հ'] = 'h'\n self.trans['Ձ'] = 'Dz'\n self.trans['ձ'] = 'dz'\n self.trans['Ղ'] = 'R'\n self.trans['ղ'] = 'r'\n self.trans['Ճ'] = 'Cz'\n self.trans['ճ'] = 'cz'\n self.trans['Մ'] = 'M'\n self.trans['մ'] = 'm'\n self.trans['Յ'] = 'J'\n self.trans['յ'] = 'j'\n self.trans['Ն'] = 'N'\n self.trans['ն'] = 'n'\n self.trans['Շ'] = 'S'\n self.trans['շ'] = 's'\n self.trans['Շ'] = 'Vo'\n self.trans['շ'] = 'o'\n self.trans['Չ'] = 'Tsh'\n self.trans['չ'] = 'tsh'\n self.trans['Պ'] = 'P'\n self.trans['պ'] = 'p'\n self.trans['Ջ'] = 'Dz'\n self.trans['ջ'] = 'dz'\n self.trans['Ռ'] = 'R'\n self.trans['ռ'] = 'r'\n self.trans['Ս'] = 'S'\n self.trans['ս'] = 's'\n self.trans['Վ'] = 'V'\n self.trans['վ'] = 'v'\n for char in 'Տ':\n self.trans[char] = u\"T'\"\n for char in 'տ':\n self.trans[char] = u\"t'\"\n self.trans['Ր'] = 'R'\n self.trans['ր'] = 'r'\n self.trans['Ց'] = 'Tsh'\n self.trans['ց'] = 'tsh'\n self.trans['Ւ'] = 'V'\n self.trans['ւ'] = 'v'\n self.trans['Փ'] = 'Ph'\n self.trans['փ'] = 'ph'\n self.trans['Ք'] = 'Kh'\n self.trans['ք'] = 'kh'\n self.trans['Օ'] = 'O'\n self.trans['օ'] = 'o'\n self.trans['Ֆ'] = 'F'\n self.trans['ֆ'] = 'f'\n self.trans['և'] = '&'\n self.trans['՟'] = '.'\n self.trans['՞'] = '?'\n self.trans['՝'] = ';'\n self.trans['՛'] = ''\n\n # Tamil\n for char in 'க்':\n self.trans[char] = 'k'\n for char in 'ஙண்ந்ன்':\n self.trans[char] = 'n'\n self.trans['ச'] = 'c'\n for char in 'ஞ்':\n self.trans[char] = 'ñ'\n for char in 'ட்':\n self.trans[char] = 'th'\n self.trans['த'] = 't'\n self.trans['ப'] = 'p'\n for char in 'ம்':\n self.trans[char] = 'm'\n for char in 'ய்':\n self.trans[char] = 'y'\n for char in 'ர்ழ்ற':\n self.trans[char] = 'r'\n for char in 'ல்ள':\n self.trans[char] = 'l'\n for char in 'வ்':\n self.trans[char] = 'v'\n self.trans['ஜ'] = 'j'\n self.trans['ஷ'] = 'sh'\n self.trans['ஸ'] = 's'\n self.trans['ஹ'] = 'h'\n for char in 'க்ஷ':\n self.trans[char] = 'x'\n self.trans['அ'] = 'a'\n self.trans['ஆ'] = 'aa'\n self.trans['இ'] = 'i'\n self.trans['ஈ'] = 'ii'\n self.trans['உ'] = 'u'\n self.trans['ஊ'] = 'uu'\n self.trans['எ'] = 'e'\n self.trans['ஏ'] = 'ee'\n self.trans['ஐ'] = 'ai'\n self.trans['ஒ'] = 'o'\n self.trans['ஓ'] = 'oo'\n self.trans['ஔ'] = 'au'\n self.trans['ஃ'] = ''\n\n # Bengali\n self.trans['অ'] = 'ô'\n for char in 'আা':\n self.trans[char] = 'a'\n for char in 'ইিঈী':\n self.trans[char] = 'i'\n for char in 'উুঊূ':\n self.trans[char] = 'u'\n for char in 'ঋৃ':\n self.trans[char] = 'ri'\n for char in 'এেয়':\n self.trans[char] = 'e'\n for char in 'ঐৈ':\n self.trans[char] = 'oi'\n for char in 'ওো':\n self.trans[char] = 'o'\n for char in 'ঔৌ':\n self.trans[char] = 'ou'\n self.trans['্'] = ''\n self.trans['ৎ'] = 't'\n self.trans['ং'] = 'n'\n self.trans['ঃ'] = 'h'\n self.trans['ঁ'] = 'ñ'\n self.trans['ক'] = 'k'\n self.trans['খ'] = 'kh'\n self.trans['গ'] = 'g'\n self.trans['ঘ'] = 'gh'\n self.trans['ঙ'] = 'ng'\n self.trans['চ'] = 'ch'\n self.trans['ছ'] = 'chh'\n self.trans['জ'] = 'j'\n self.trans['ঝ'] = 'jh'\n self.trans['ঞ'] = 'n'\n for char in 'টত':\n self.trans[char] = 't'\n for char in 'ঠথ':\n self.trans[char] = 'th'\n for char in 'ডদ':\n self.trans[char] = 'd'\n for char in 'ঢধ':\n self.trans[char] = 'dh'\n for char in 'ণন':\n self.trans[char] = 'n'\n self.trans['প'] = 'p'\n self.trans['ফ'] = 'ph'\n self.trans['ব'] = 'b'\n self.trans['ভ'] = 'bh'\n self.trans['ম'] = 'm'\n self.trans['য'] = 'dzh'\n self.trans['র'] = 'r'\n self.trans['ল'] = 'l'\n self.trans['শ'] = 's'\n self.trans['হ'] = 'h'\n for char in 'য়':\n self.trans[char] = '-'\n for char in 'ড়':\n self.trans[char] = 'r'\n self.trans['ঢ'] = 'rh'\n self.trans['০'] = '0'\n self.trans['১'] = '1'\n self.trans['২'] = '2'\n self.trans['৩'] = '3'\n self.trans['৪'] = '4'\n self.trans['৫'] = '5'\n self.trans['৬'] = '6'\n self.trans['৭'] = '7'\n self.trans['৮'] = '8'\n self.trans['৯'] = '9'\n\n # Thai (because of complications of the alphabet, self.transliterations\n # are very imprecise here)\n self.trans['ก'] = 'k'\n for char in 'ขฃคฅฆ':\n self.trans[char] = 'kh'\n self.trans['ง'] = 'ng'\n for char in 'จฉชฌ':\n self.trans[char] = 'ch'\n for char in 'ซศษส':\n self.trans[char] = 's'\n for char in 'ญย':\n self.trans[char] = 'y'\n for char in 'ฎด':\n self.trans[char] = 'd'\n for char in 'ฏต':\n self.trans[char] = 't'\n for char in 'ฐฑฒถทธ':\n self.trans[char] = 'th'\n for char in 'ณน':\n self.trans[char] = 'n'\n self.trans['บ'] = 'b'\n self.trans['ป'] = 'p'\n for char in 'ผพภ':\n self.trans[char] = 'ph'\n for char in 'ฝฟ':\n self.trans[char] = 'f'\n self.trans['ม'] = 'm'\n self.trans['ร'] = 'r'\n self.trans['ฤ'] = 'rue'\n self.trans['ๅ'] = ':'\n for char in 'ลฬ':\n self.trans[char] = 'l'\n self.trans['ฦ'] = 'lue'\n self.trans['ว'] = 'w'\n for char in 'หฮ':\n self.trans[char] = 'h'\n self.trans['อ'] = ''\n self.trans['ร'] = 'ü'\n self.trans['ว'] = 'ua'\n for char in 'อวโิ':\n self.trans[char] = 'o'\n for char in 'ะัา':\n self.trans[char] = 'a'\n self.trans['ว'] = 'u'\n self.trans['ำ'] = 'am'\n self.trans['ิ'] = 'i'\n self.trans['ี'] = 'i:'\n self.trans['ึ'] = 'ue'\n self.trans['ื'] = 'ue:'\n self.trans['ุ'] = 'u'\n self.trans['ู'] = 'u:'\n for char in 'เ็':\n self.trans[char] = 'e'\n self.trans['แ'] = 'ae'\n for char in 'ใไ':\n self.trans[char] = 'ai'\n for char in '่้๊๋็์':\n self.trans[char] = u\"\"\n self.trans['ฯ'] = '.'\n self.trans['ๆ'] = '(2)'\n\n # Korean (Revised Romanization system within possible, incomplete)\n self.trans['국'] = 'guk'\n self.trans['명'] = 'myeong'\n self.trans['검'] = 'geom'\n self.trans['타'] = 'ta'\n self.trans['분'] = 'bun'\n self.trans['사'] = 'sa'\n self.trans['류'] = 'ryu'\n self.trans['포'] = 'po'\n self.trans['르'] = 'reu'\n self.trans['투'] = 'tu'\n self.trans['갈'] = 'gal'\n self.trans['어'] = 'eo'\n self.trans['노'] = 'no'\n self.trans['웨'] = 'we'\n self.trans['이'] = 'i'\n self.trans['라'] = 'ra'\n self.trans['틴'] = 'tin'\n self.trans['루'] = 'ru'\n self.trans['마'] = 'ma'\n self.trans['니'] = 'ni'\n self.trans['아'] = 'a'\n self.trans['독'] = 'dok'\n self.trans['일'] = 'il'\n self.trans['모'] = 'mo'\n self.trans['크'] = 'keu'\n self.trans['샤'] = 'sya'\n self.trans['영'] = 'yeong'\n self.trans['불'] = 'bul'\n self.trans['가'] = 'ga'\n self.trans['리'] = 'ri'\n self.trans['그'] = 'geu'\n self.trans['지'] = 'ji'\n self.trans['야'] = 'ya'\n self.trans['바'] = 'ba'\n self.trans['슈'] = 'syu'\n self.trans['키'] = 'ki'\n self.trans['프'] = 'peu'\n self.trans['랑'] = 'rang'\n self.trans['스'] = 'seu'\n self.trans['로'] = 'ro'\n self.trans['메'] = 'me'\n self.trans['역'] = 'yeok'\n self.trans['도'] = 'do'\n\n # Kannada\n self.trans['ಅ'] = 'a'\n for char in 'ಆಾ':\n self.trans[char] = 'aa'\n for char in 'ಇಿ':\n self.trans[char] = 'i'\n for char in 'ಈೀ':\n self.trans[char] = 'ii'\n for char in 'ಉು':\n self.trans[char] = 'u'\n for char in 'ಊೂ':\n self.trans[char] = 'uu'\n for char in 'ಋೂ':\n self.trans[char] = u\"r'\"\n for char in 'ಎೆ':\n self.trans[char] = 'e'\n for char in 'ಏೇ':\n self.trans[char] = 'ee'\n for char in 'ಐೈ':\n self.trans[char] = 'ai'\n for char in 'ಒೊ':\n self.trans[char] = 'o'\n for char in 'ಓೋ':\n self.trans[char] = 'oo'\n for char in 'ಔೌ':\n self.trans[char] = 'au'\n self.trans['ಂ'] = \"m'\"\n self.trans['ಃ'] = \"h'\"\n self.trans['ಕ'] = 'k'\n self.trans['ಖ'] = 'kh'\n self.trans['ಗ'] = 'g'\n self.trans['ಘ'] = 'gh'\n self.trans['ಙ'] = 'ng'\n self.trans['ಚ'] = 'c'\n self.trans['ಛ'] = 'ch'\n self.trans['ಜ'] = 'j'\n self.trans['ಝ'] = 'ny'\n self.trans['ಟ'] = 'tt'\n self.trans['ಠ'] = 'tth'\n self.trans['ಡ'] = 'dd'\n self.trans['ಢ'] = 'ddh'\n self.trans['ಣ'] = 'nn'\n self.trans['ತ'] = 't'\n self.trans['ಥ'] = 'th'\n self.trans['ದ'] = 'd'\n self.trans['ಧ'] = 'dh'\n self.trans['ನ'] = 'n'\n self.trans['ಪ'] = 'p'\n self.trans['ಫ'] = 'ph'\n self.trans['ಬ'] = 'b'\n self.trans['ಭ'] = 'bh'\n self.trans['ಮ'] = 'm'\n self.trans['ಯ'] = 'y'\n self.trans['ರ'] = 'r'\n self.trans['ಲ'] = 'l'\n self.trans['ವ'] = 'v'\n self.trans['ಶ'] = 'sh'\n self.trans['ಷ'] = 'ss'\n self.trans['ಸ'] = 's'\n self.trans['ಹ'] = 'h'\n self.trans['ಳ'] = 'll'\n self.trans['೦'] = '0'\n self.trans['೧'] = '1'\n self.trans['೨'] = '2'\n self.trans['೩'] = '3'\n self.trans['೪'] = '4'\n self.trans['೫'] = '5'\n self.trans['೬'] = '6'\n self.trans['೭'] = '7'\n self.trans['೮'] = '8'\n self.trans['೯'] = '9'\n # Telugu\n self.trans['అ'] = 'a'\n for char in 'ఆా':\n self.trans[char] = 'aa'\n for char in 'ఇి':\n self.trans[char] = 'i'\n for char in 'ఈీ':\n self.trans[char] = 'ii'\n for char in 'ఉు':\n self.trans[char] = 'u'\n for char in 'ఊూ':\n self.trans[char] = 'uu'\n for char in 'ఋృ':\n self.trans[char] = \"r'\"\n for char in 'ౠౄ':\n self.trans[char] = 'r\"'\n self.trans['ఌ'] = \"l'\"\n self.trans['ౡ'] = 'l\"'\n for char in 'ఎె':\n self.trans[char] = 'e'\n for char in 'ఏే':\n self.trans[char] = 'ee'\n for char in 'ఐై':\n self.trans[char] = 'ai'\n for char in 'ఒొ':\n self.trans[char] = 'o'\n for char in 'ఓో':\n self.trans[char] = 'oo'\n for char in 'ఔౌ':\n self.trans[char] = 'au'\n self.trans['ం'] = \"'\"\n self.trans['ః'] = '\"'\n self.trans['క'] = 'k'\n self.trans['ఖ'] = 'kh'\n self.trans['గ'] = 'g'\n self.trans['ఘ'] = 'gh'\n self.trans['ఙ'] = 'ng'\n self.trans['చ'] = 'ts'\n self.trans['ఛ'] = 'tsh'\n self.trans['జ'] = 'j'\n self.trans['ఝ'] = 'jh'\n self.trans['ఞ'] = 'ñ'\n for char in 'టత':\n self.trans[char] = 't'\n for char in 'ఠథ':\n self.trans[char] = 'th'\n for char in 'డద':\n self.trans[char] = 'd'\n for char in 'ఢధ':\n self.trans[char] = 'dh'\n for char in 'ణన':\n self.trans[char] = 'n'\n self.trans['ప'] = 'p'\n self.trans['ఫ'] = 'ph'\n self.trans['బ'] = 'b'\n self.trans['భ'] = 'bh'\n self.trans['మ'] = 'm'\n self.trans['య'] = 'y'\n for char in 'రఱ':\n self.trans[char] = 'r'\n for char in 'లళ':\n self.trans[char] = 'l'\n self.trans['వ'] = 'v'\n self.trans['శ'] = 'sh'\n for char in 'షస':\n self.trans[char] = 's'\n self.trans['హ'] = 'h'\n self.trans['్'] = \"\"\n for char in 'ంఁ':\n self.trans[char] = '^'\n self.trans['ః'] = '-'\n self.trans['౦'] = '0'\n self.trans['౧'] = '1'\n self.trans['౨'] = '2'\n self.trans['౩'] = '3'\n self.trans['౪'] = '4'\n self.trans['౫'] = '5'\n self.trans['౬'] = '6'\n self.trans['౭'] = '7'\n self.trans['౮'] = '8'\n self.trans['౯'] = '9'\n self.trans['౹'] = '1/4'\n self.trans['౺'] = '1/2'\n self.trans['౻'] = '3/4'\n self.trans['౼'] = '1/16'\n self.trans['౽'] = '1/8'\n self.trans['౾'] = '3/16'\n # Lao - note: pronounciation in initial position is used;\n # different pronounciation in final position is ignored\n self.trans['ກ'] = 'k'\n for char in 'ຂຄ':\n self.trans[char] = 'kh'\n self.trans['ງ'] = 'ng'\n self.trans['ຈ'] = 'ch'\n for char in 'ສຊ':\n self.trans[char] = 's'\n self.trans['ຍ'] = 'ny'\n self.trans['ດ'] = 'd'\n self.trans['ຕ'] = 't'\n for char in 'ຖທ':\n self.trans[char] = 'th'\n self.trans['ນ'] = 'n'\n self.trans['ບ'] = 'b'\n self.trans['ປ'] = 'p'\n for char in 'ຜພ':\n self.trans[char] = 'ph'\n for char in 'ຝຟ':\n self.trans[char] = 'f'\n for char in 'ມໝ':\n self.trans[char] = 'm'\n self.trans['ຢ'] = 'y'\n for char in 'ຣຼ':\n self.trans[char] = 'r'\n for char in 'ລຼ':\n self.trans[char] = 'l'\n self.trans['ວ'] = 'v'\n self.trans['ຮ'] = 'h'\n self.trans['ອ'] = \"'\"\n for char in 'ະັ':\n self.trans[char] = 'a'\n self.trans['ິ'] = 'i'\n self.trans['ຶ'] = 'ue'\n self.trans['ຸ'] = 'u'\n self.trans['ເ'] = 'é'\n self.trans['ແ'] = 'è'\n for char in 'ໂົາໍ':\n self.trans[char] = 'o'\n self.trans['ຽ'] = 'ia'\n self.trans['ເຶ'] = 'uea'\n self.trans['ຍ'] = 'i'\n for char in 'ໄໃ':\n self.trans[char] = 'ai'\n self.trans['ຳ'] = 'am'\n self.trans['າ'] = 'aa'\n self.trans['ີ'] = 'ii'\n self.trans['ື'] = 'yy'\n self.trans['ູ'] = 'uu'\n self.trans['ເ'] = 'e'\n self.trans['ແ'] = 'ei'\n self.trans['໐'] = '0'\n self.trans['໑'] = '1'\n self.trans['໒'] = '2'\n self.trans['໓'] = '3'\n self.trans['໔'] = '4'\n self.trans['໕'] = '5'\n self.trans['໖'] = '6'\n self.trans['໗'] = '7'\n self.trans['໘'] = '8'\n self.trans['໙'] = '9'\n # Chinese -- note: incomplete\n for char in '埃挨哎唉哀皑癌蔼矮艾碍爱隘':\n self.trans[char] = 'ai'\n for char in '鞍氨安俺按暗岸胺案':\n self.trans[char] = 'an'\n for char in '肮昂盎':\n self.trans[char] = 'ang'\n for char in '凹敖熬翱袄傲奥懊澳':\n self.trans[char] = 'ao'\n for char in '芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸':\n self.trans[char] = 'ba'\n for char in '白柏百摆佰败拜稗':\n self.trans[char] = 'bai'\n for char in '斑班搬扳般颁板版扮拌伴瓣半办绊':\n self.trans[char] = 'ban'\n for char in '邦帮梆榜膀绑棒磅蚌镑傍谤':\n self.trans[char] = 'bang'\n for char in '苞胞包褒剥薄雹保堡饱宝抱报暴豹鲍爆':\n self.trans[char] = 'bao'\n for char in '杯碑悲卑北辈背贝钡倍狈备惫焙被':\n self.trans[char] = 'bei'\n for char in '奔苯本笨':\n self.trans[char] = 'ben'\n for char in '崩绷甭泵蹦迸':\n self.trans[char] = 'beng'\n for char in '逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛':\n self.trans[char] = 'bi'\n for char in '鞭边编贬扁便变卞辨辩辫遍':\n self.trans[char] = 'bian'\n for char in '标彪膘表':\n self.trans[char] = 'biao'\n for char in '鳖憋别瘪':\n self.trans[char] = 'bie'\n for char in '彬斌濒滨宾摈':\n self.trans[char] = 'bin'\n for char in '兵冰柄丙秉饼炳病并':\n self.trans[char] = 'bing'\n for char in '玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜亳':\n self.trans[char] = 'bo'\n for char in '哺补埠不布步簿部怖':\n self.trans[char] = 'bu'\n for char in '猜裁材才财睬踩采彩菜蔡':\n self.trans[char] = 'cai'\n for char in '餐参蚕残惭惨灿':\n self.trans[char] = 'can'\n for char in '苍舱仓沧藏':\n self.trans[char] = 'cang'\n for char in '操糙槽曹草':\n self.trans[char] = 'cao'\n for char in '厕策侧册测':\n self.trans[char] = 'ce'\n for char in '层蹭':\n self.trans[char] = 'ceng'\n for char in '插叉茬茶查碴搽察岔差诧':\n self.trans[char] = 'cha'\n for char in '拆柴豺':\n self.trans[char] = 'chai'\n for char in '搀掺蝉馋谗缠铲产阐颤':\n self.trans[char] = 'chan'\n for char in '昌猖场尝常长偿肠厂敞畅唱倡':\n self.trans[char] = 'chang'\n for char in '超抄钞朝嘲潮巢吵炒':\n self.trans[char] = 'chao'\n for char in '车扯撤掣彻澈':\n self.trans[char] = 'che'\n for char in '郴臣辰尘晨忱沉陈趁衬':\n self.trans[char] = 'chen'\n for char in '撑称城橙成呈乘程惩澄诚承逞骋秤':\n self.trans[char] = 'cheng'\n for char in '吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽':\n self.trans[char] = 'chi'\n for char in '充冲虫崇宠':\n self.trans[char] = 'chong'\n for char in '抽酬畴踌稠愁筹仇绸瞅丑臭':\n self.trans[char] = 'chou'\n for char in '初出橱厨躇锄雏滁除楚储矗搐触处':\n self.trans[char] = 'chu'\n self.trans['揣'] = 'chuai'\n for char in '川穿椽传船喘串':\n self.trans[char] = 'chuan'\n for char in '疮窗幢床闯创':\n self.trans[char] = 'chuang'\n for char in '吹炊捶锤垂':\n self.trans[char] = 'chui'\n for char in '春椿醇唇淳纯蠢':\n self.trans[char] = 'chun'\n for char in '戳绰':\n self.trans[char] = 'chuo'\n for char in '疵茨磁雌辞慈瓷词此刺赐次':\n self.trans[char] = 'ci'\n for char in '聪葱囱匆从丛':\n self.trans[char] = 'cong'\n self.trans['凑'] = 'cou'\n for char in '粗醋簇促':\n self.trans[char] = 'cu'\n for char in '蹿篡窜':\n self.trans[char] = 'cuan'\n for char in '摧崔催脆瘁粹淬翠':\n self.trans[char] = 'cui'\n for char in '村存寸':\n self.trans[char] = 'cun'\n for char in '磋撮搓措挫错':\n self.trans[char] = 'cuo'\n for char in '搭达答瘩打大':\n self.trans[char] = 'da'\n for char in '呆歹傣戴带殆代贷袋待逮怠':\n self.trans[char] = 'dai'\n for char in '耽担丹单郸掸胆旦氮但惮淡诞弹蛋儋':\n self.trans[char] = 'dan'\n for char in '当挡党荡档':\n self.trans[char] = 'dang'\n for char in '刀捣蹈倒岛祷导到稻悼道盗':\n self.trans[char] = 'dao'\n for char in '德得的':\n self.trans[char] = 'de'\n for char in '蹬灯登等瞪凳邓':\n self.trans[char] = 'deng'\n for char in '堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔':\n self.trans[char] = 'di'\n for char in '颠掂滇碘点典靛垫电佃甸店惦奠淀殿':\n self.trans[char] = 'dian'\n for char in '碉叼雕凋刁掉吊钓调':\n self.trans[char] = 'diao'\n for char in '跌爹碟蝶迭谍叠':\n self.trans[char] = 'die'\n for char in '丁盯叮钉顶鼎锭定订':\n self.trans[char] = 'ding'\n self.trans['丢'] = 'diu'\n for char in '东冬董懂动栋侗恫冻洞':\n self.trans[char] = 'dong'\n for char in '兜抖斗陡豆逗痘':\n self.trans[char] = 'dou'\n for char in '都督毒犊独读堵睹赌杜镀肚度渡妒':\n self.trans[char] = 'du'\n for char in '端短锻段断缎':\n self.trans[char] = 'duan'\n for char in '堆兑队对':\n self.trans[char] = 'dui'\n for char in '墩吨蹲敦顿囤钝盾遁':\n self.trans[char] = 'dun'\n for char in '掇哆多夺垛躲朵跺舵剁惰堕':\n self.trans[char] = 'duo'\n for char in '蛾峨鹅俄额讹娥恶厄扼遏鄂饿':\n self.trans[char] = 'e'\n for char in '恩嗯':\n self.trans[char] = 'en'\n for char in '而儿耳尔饵洱二贰':\n self.trans[char] = 'er'\n for char in '发罚筏伐乏阀法珐':\n self.trans[char] = 'fa'\n for char in '藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛':\n self.trans[char] = 'fan'\n for char in '坊芳方肪房防妨仿访纺放':\n self.trans[char] = 'fang'\n for char in '菲非啡飞肥匪诽吠肺废沸费':\n self.trans[char] = 'fei'\n for char in '芬酚吩氛分纷坟焚汾粉奋份忿愤粪':\n self.trans[char] = 'fen'\n for char in '丰封枫蜂峰锋风疯烽逢冯缝讽奉凤':\n self.trans[char] = 'feng'\n self.trans['佛'] = 'fo'\n self.trans['否'] = 'fou'\n for char in ('夫敷肤孵扶拂辐幅氟符伏俘服浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋'\n '复傅付阜父腹负富讣附妇缚咐'):\n self.trans[char] = 'fu'\n for char in '噶嘎':\n self.trans[char] = 'ga'\n for char in '该改概钙盖溉':\n self.trans[char] = 'gai'\n for char in '干甘杆柑竿肝赶感秆敢赣':\n self.trans[char] = 'gan'\n for char in '冈刚钢缸肛纲岗港杠':\n self.trans[char] = 'gang'\n for char in '篙皋高膏羔糕搞镐稿告':\n self.trans[char] = 'gao'\n for char in '哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各':\n self.trans[char] = 'ge'\n self.trans['给'] = 'gei'\n for char in '根跟':\n self.trans[char] = 'gen'\n for char in '耕更庚羹埂耿梗':\n self.trans[char] = 'geng'\n for char in '工攻功恭龚供躬公宫弓巩汞拱贡共':\n self.trans[char] = 'gong'\n for char in '钩勾沟苟狗垢构购够':\n self.trans[char] = 'gou'\n for char in '辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇':\n self.trans[char] = 'gu'\n for char in '刮瓜剐寡挂褂':\n self.trans[char] = 'gua'\n for char in '乖拐怪':\n self.trans[char] = 'guai'\n for char in '棺关官冠观管馆罐惯灌贯':\n self.trans[char] = 'guan'\n for char in '光广逛':\n self.trans[char] = 'guang'\n for char in '瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽':\n self.trans[char] = 'gui'\n for char in '辊滚棍':\n self.trans[char] = 'gun'\n for char in '锅郭国果裹过':\n self.trans[char] = 'guo'\n self.trans['哈'] = 'ha'\n for char in '骸孩海氦亥害骇':\n self.trans[char] = 'hai'\n for char in '酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉':\n self.trans[char] = 'han'\n for char in '夯杭航':\n self.trans[char] = 'hang'\n for char in '壕嚎豪毫郝好耗号浩':\n self.trans[char] = 'hao'\n for char in '呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺':\n self.trans[char] = 'he'\n for char in '嘿黑':\n self.trans[char] = 'hei'\n for char in '痕很狠恨':\n self.trans[char] = 'hen'\n for char in '哼亨横衡恒':\n self.trans[char] = 'heng'\n for char in '轰哄烘虹鸿洪宏弘红':\n self.trans[char] = 'hong'\n for char in '喉侯猴吼厚候后':\n self.trans[char] = 'hou'\n for char in '呼乎忽瑚壶葫胡蝴狐糊湖弧虎唬护互沪户':\n self.trans[char] = 'hu'\n for char in '花哗华猾滑画划化话':\n self.trans[char] = 'hua'\n for char in '槐徊怀淮坏':\n self.trans[char] = 'huai'\n for char in '欢环桓还缓换患唤痪豢焕涣宦幻':\n self.trans[char] = 'huan'\n for char in '荒慌黄磺蝗簧皇凰惶煌晃幌恍谎':\n self.trans[char] = 'huang'\n for char in '灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘':\n self.trans[char] = 'hui'\n for char in '荤昏婚魂浑混':\n self.trans[char] = 'hun'\n for char in '豁活伙火获或惑霍货祸':\n self.trans[char] = 'huo'\n for char in ('击圾基机畸稽积箕肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几'\n '脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪'):\n self.trans[char] = 'ji'\n for char in '嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁':\n self.trans[char] = 'jia'\n for char in ('歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件健'\n '舰剑饯渐溅涧建'):\n self.trans[char] = 'jian'\n for char in '僵姜将浆江疆蒋桨奖讲匠酱降':\n self.trans[char] = 'jiang'\n for char in '蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖':\n self.trans[char] = 'jiao'\n for char in '揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届':\n self.trans[char] = 'jie'\n for char in '巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸尽劲':\n self.trans[char] = 'jin'\n for char in '荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净':\n self.trans[char] = 'jing'\n for char in '囧炯窘':\n self.trans[char] = 'jiong'\n for char in '揪究纠玖韭久灸九酒厩救旧臼舅咎就疚':\n self.trans[char] = 'jiu'\n for char in '鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧':\n self.trans[char] = 'ju'\n for char in '捐鹃娟倦眷卷绢':\n self.trans[char] = 'juan'\n for char in '撅攫抉掘倔爵觉决诀绝':\n self.trans[char] = 'jue'\n for char in '均菌钧军君峻俊竣浚郡骏':\n self.trans[char] = 'jun'\n for char in '喀咖卡咯':\n self.trans[char] = 'ka'\n for char in '开揩楷凯慨':\n self.trans[char] = 'kai'\n for char in '刊堪勘坎砍看':\n self.trans[char] = 'kan'\n for char in '康慷糠扛抗亢炕':\n self.trans[char] = 'kang'\n for char in '考拷烤靠':\n self.trans[char] = 'kao'\n for char in '坷苛柯棵磕颗科壳咳可渴克刻客课':\n self.trans[char] = 'ke'\n for char in '肯啃垦恳':\n self.trans[char] = 'ken'\n for char in '坑吭':\n self.trans[char] = 'keng'\n for char in '空恐孔控':\n self.trans[char] = 'kong'\n for char in '抠口扣寇':\n self.trans[char] = 'kou'\n for char in '枯哭窟苦酷库裤':\n self.trans[char] = 'ku'\n for char in '夸垮挎跨胯':\n self.trans[char] = 'kua'\n for char in '块筷侩快':\n self.trans[char] = 'kuai'\n for char in '宽款':\n self.trans[char] = 'kuan'\n for char in '匡筐狂框矿眶旷况':\n self.trans[char] = 'kuang'\n for char in '亏盔岿窥葵奎魁傀馈愧溃':\n self.trans[char] = 'kui'\n for char in '坤昆捆困':\n self.trans[char] = 'kun'\n for char in '括扩廓阔':\n self.trans[char] = 'kuo'\n for char in '垃拉喇蜡腊辣啦':\n self.trans[char] = 'la'\n for char in '莱来赖':\n self.trans[char] = 'lai'\n for char in '蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥':\n self.trans[char] = 'lan'\n for char in '琅榔狼廊郎朗浪':\n self.trans[char] = 'lang'\n for char in '捞劳牢老佬姥酪烙涝':\n self.trans[char] = 'lao'\n for char in '勒乐':\n self.trans[char] = 'le'\n for char in '雷镭蕾磊累儡垒擂肋类泪':\n self.trans[char] = 'lei'\n for char in '棱楞冷':\n self.trans[char] = 'leng'\n for char in ('厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐痢立粒沥隶力'\n '璃哩'):\n self.trans[char] = 'li'\n self.trans['俩'] = 'lia'\n for char in '联莲连镰廉怜涟帘敛脸链恋炼练':\n self.trans[char] = 'lian'\n for char in '粮凉梁粱良两辆量晾亮谅':\n self.trans[char] = 'liang'\n for char in '撩聊僚疗燎寥辽潦了撂镣廖料':\n self.trans[char] = 'liao'\n for char in '列裂烈劣猎':\n self.trans[char] = 'lie'\n for char in '琳林磷霖临邻鳞淋凛赁吝拎':\n self.trans[char] = 'lin'\n for char in '玲菱零龄铃伶羚凌灵陵岭领另令':\n self.trans[char] = 'ling'\n for char in '溜琉榴硫馏留刘瘤流柳六':\n self.trans[char] = 'liu'\n for char in '龙聋咙笼窿隆垄拢陇':\n self.trans[char] = 'long'\n for char in '楼娄搂篓漏陋':\n self.trans[char] = 'lou'\n for char in '芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮泸':\n self.trans[char] = 'lu'\n for char in '峦挛孪滦卵乱':\n self.trans[char] = 'luan'\n for char in '掠略':\n self.trans[char] = 'lue'\n for char in '抡轮伦仑沦纶论':\n self.trans[char] = 'lun'\n for char in '萝螺罗逻锣箩骡裸落洛骆络漯':\n self.trans[char] = 'luo'\n for char in '驴吕铝侣旅履屡缕虑氯律率滤绿':\n self.trans[char] = 'lv'\n for char in '妈麻玛码蚂马骂嘛吗':\n self.trans[char] = 'ma'\n for char in '埋买麦卖迈脉':\n self.trans[char] = 'mai'\n for char in '瞒馒蛮满蔓曼慢漫谩':\n self.trans[char] = 'man'\n for char in '芒茫盲氓忙莽':\n self.trans[char] = 'mang'\n for char in '猫茅锚毛矛铆卯茂冒帽貌贸':\n self.trans[char] = 'mao'\n self.trans['么'] = 'me'\n for char in '玫枚梅酶霉煤没眉媒镁每美昧寐妹媚':\n self.trans[char] = 'mei'\n for char in '门闷们':\n self.trans[char] = 'men'\n for char in '萌蒙檬盟锰猛梦孟':\n self.trans[char] = 'meng'\n for char in '眯醚靡糜迷谜弥米秘觅泌蜜密幂':\n self.trans[char] = 'mi'\n for char in '棉眠绵冕免勉娩缅面':\n self.trans[char] = 'mian'\n for char in '苗描瞄藐秒渺庙妙':\n self.trans[char] = 'miao'\n for char in '蔑灭':\n self.trans[char] = 'mie'\n for char in '民抿皿敏悯闽':\n self.trans[char] = 'min'\n for char in '明螟鸣铭名命':\n self.trans[char] = 'ming'\n self.trans['谬'] = 'miu'\n for char in '摸摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌':\n self.trans[char] = 'mo'\n for char in '谋牟某':\n self.trans[char] = 'mou'\n for char in '拇牡亩姆母墓暮幕募慕木目睦牧穆':\n self.trans[char] = 'mu'\n for char in '拿哪呐钠那娜纳':\n self.trans[char] = 'na'\n for char in '氖乃奶耐奈':\n self.trans[char] = 'nai'\n for char in '南男难':\n self.trans[char] = 'nan'\n self.trans['囊'] = 'nang'\n for char in '挠脑恼闹淖':\n self.trans[char] = 'nao'\n self.trans['呢'] = 'ne'\n for char in '馁内':\n self.trans[char] = 'nei'\n self.trans['嫩'] = 'nen'\n self.trans['能'] = 'neng'\n for char in '妮霓倪泥尼拟你匿腻逆溺':\n self.trans[char] = 'ni'\n for char in '蔫拈年碾撵捻念':\n self.trans[char] = 'nian'\n for char in '娘酿':\n self.trans[char] = 'niang'\n for char in '鸟尿':\n self.trans[char] = 'niao'\n for char in '捏聂孽啮镊镍涅':\n self.trans[char] = 'nie'\n self.trans['您'] = 'nin'\n for char in '柠狞凝宁拧泞':\n self.trans[char] = 'ning'\n for char in '牛扭钮纽':\n self.trans[char] = 'niu'\n for char in '脓浓农弄':\n self.trans[char] = 'nong'\n for char in '奴努怒':\n self.trans[char] = 'nu'\n self.trans['暖'] = 'nuan'\n for char in '虐疟':\n self.trans[char] = 'nue'\n for char in '挪懦糯诺':\n self.trans[char] = 'nuo'\n self.trans['女'] = 'nv'\n self.trans['哦'] = 'o'\n for char in '欧鸥殴藕呕偶沤':\n self.trans[char] = 'ou'\n for char in '啪趴爬帕怕琶':\n self.trans[char] = 'pa'\n for char in '拍排牌徘湃派':\n self.trans[char] = 'pai'\n for char in '攀潘盘磐盼畔判叛':\n self.trans[char] = 'pan'\n for char in '乓庞旁耪胖':\n self.trans[char] = 'pang'\n for char in '抛咆刨炮袍跑泡':\n self.trans[char] = 'pao'\n for char in '呸胚培裴赔陪配佩沛':\n self.trans[char] = 'pei'\n for char in '喷盆':\n self.trans[char] = 'pen'\n for char in '砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰':\n self.trans[char] = 'peng'\n for char in '坯砒霹批披劈琵毗啤脾疲皮匹痞僻屁譬':\n self.trans[char] = 'pi'\n for char in '篇偏片骗':\n self.trans[char] = 'pian'\n for char in '飘漂瓢票':\n self.trans[char] = 'piao'\n for char in '撇瞥':\n self.trans[char] = 'pie'\n for char in '拼频贫品聘':\n self.trans[char] = 'pin'\n for char in '乒坪苹萍平凭瓶评屏':\n self.trans[char] = 'ping'\n for char in '坡泼颇婆破魄迫粕剖':\n self.trans[char] = 'po'\n for char in '扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑濮':\n self.trans[char] = 'pu'\n for char in ('期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄'\n '弃汽泣讫'):\n self.trans[char] = 'qi'\n for char in '掐恰洽':\n self.trans[char] = 'qia'\n for char in '牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉':\n self.trans[char] = 'qian'\n for char in '枪呛腔羌墙蔷强抢':\n self.trans[char] = 'qiang'\n for char in '橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍':\n self.trans[char] = 'qiao'\n for char in '切茄且怯窃':\n self.trans[char] = 'qie'\n for char in '钦侵亲秦琴勤芹擒禽寝沁':\n self.trans[char] = 'qin'\n for char in '青轻氢倾卿清擎晴氰情顷请庆':\n self.trans[char] = 'qing'\n for char in '琼穷':\n self.trans[char] = 'qiong'\n for char in '秋丘邱球求囚酋泅':\n self.trans[char] = 'qiu'\n for char in '趋区蛆曲躯屈驱渠取娶龋趣去':\n self.trans[char] = 'qu'\n for char in '圈颧权醛泉全痊拳犬券劝':\n self.trans[char] = 'quan'\n for char in '缺炔瘸却鹊榷确雀':\n self.trans[char] = 'que'\n for char in '裙群':\n self.trans[char] = 'qun'\n for char in '然燃冉染':\n self.trans[char] = 'ran'\n for char in '瓤壤攘嚷让':\n self.trans[char] = 'rang'\n for char in '饶扰绕':\n self.trans[char] = 'rao'\n for char in '惹热':\n self.trans[char] = 're'\n for char in '壬仁人忍韧任认刃妊纫':\n self.trans[char] = 'ren'\n for char in '扔仍':\n self.trans[char] = 'reng'\n self.trans['日'] = 'ri'\n for char in '戎茸蓉荣融熔溶容绒冗':\n self.trans[char] = 'rong'\n for char in '揉柔肉':\n self.trans[char] = 'rou'\n for char in '茹蠕儒孺如辱乳汝入褥':\n self.trans[char] = 'ru'\n for char in '软阮':\n self.trans[char] = 'ruan'\n for char in '蕊瑞锐':\n self.trans[char] = 'rui'\n for char in '闰润':\n self.trans[char] = 'run'\n for char in '若弱':\n self.trans[char] = 'ruo'\n for char in '撒洒萨':\n self.trans[char] = 'sa'\n for char in '腮鳃塞赛':\n self.trans[char] = 'sai'\n for char in '三叁伞散':\n self.trans[char] = 'san'\n for char in '桑嗓丧':\n self.trans[char] = 'sang'\n for char in '搔骚扫嫂':\n self.trans[char] = 'sao'\n for char in '瑟色涩':\n self.trans[char] = 'se'\n self.trans['森'] = 'sen'\n self.trans['僧'] = 'seng'\n for char in '莎砂杀刹沙纱傻啥煞':\n self.trans[char] = 'sha'\n for char in '筛晒':\n self.trans[char] = 'shai'\n for char in '珊苫杉山删煽衫闪陕擅赡膳善汕扇缮':\n self.trans[char] = 'shan'\n for char in '墒伤商赏晌上尚裳':\n self.trans[char] = 'shang'\n for char in '梢捎稍烧芍勺韶少哨邵绍':\n self.trans[char] = 'shao'\n for char in '奢赊蛇舌舍赦摄射慑涉社设':\n self.trans[char] = 'she'\n for char in '砷申呻伸身深娠绅神沈审婶甚肾慎渗':\n self.trans[char] = 'shen'\n for char in '声生甥牲升绳省盛剩胜圣':\n self.trans[char] = 'sheng'\n for char in ('师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝'\n '势是嗜噬适仕侍释饰氏市恃室视试'):\n self.trans[char] = 'shi'\n for char in '收手首守寿授售受瘦兽':\n self.trans[char] = 'shou'\n for char in (\n '蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱恕'):\n self.trans[char] = 'shu'\n for char in '刷耍':\n self.trans[char] = 'shua'\n for char in '摔衰甩帅':\n self.trans[char] = 'shuai'\n for char in '栓拴':\n self.trans[char] = 'shuan'\n for char in '霜双爽':\n self.trans[char] = 'shuang'\n for char in '谁水睡税':\n self.trans[char] = 'shui'\n for char in '吮瞬顺舜':\n self.trans[char] = 'shun'\n for char in '说硕朔烁':\n self.trans[char] = 'shuo'\n for char in '斯撕嘶思私司丝死肆寺嗣四伺似饲巳':\n self.trans[char] = 'si'\n for char in '松耸怂颂送宋讼诵':\n self.trans[char] = 'song'\n for char in '搜艘擞':\n self.trans[char] = 'sou'\n for char in '嗽苏酥俗素速粟僳塑溯宿诉肃':\n self.trans[char] = 'su'\n for char in '酸蒜算':\n self.trans[char] = 'suan'\n for char in '虽隋随绥髓碎岁穗遂隧祟':\n self.trans[char] = 'sui'\n for char in '孙损笋':\n self.trans[char] = 'sun'\n for char in '蓑梭唆缩琐索锁所':\n self.trans[char] = 'suo'\n for char in '塌他它她塔獭挞蹋踏':\n self.trans[char] = 'ta'\n for char in '胎苔抬台泰酞太态汰':\n self.trans[char] = 'tai'\n for char in '坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭':\n self.trans[char] = 'tan'\n for char in '汤塘搪堂棠膛唐糖倘躺淌趟烫':\n self.trans[char] = 'tang'\n for char in '掏涛滔绦萄桃逃淘陶讨套':\n self.trans[char] = 'tao'\n self.trans['特'] = 'te'\n for char in '藤腾疼誊':\n self.trans[char] = 'teng'\n for char in '梯剔踢锑提题蹄啼体替嚏惕涕剃屉':\n self.trans[char] = 'ti'\n for char in '兲天添填田甜恬舔腆':\n self.trans[char] = 'tian'\n for char in '挑条迢眺跳':\n self.trans[char] = 'tiao'\n for char in '贴铁帖':\n self.trans[char] = 'tie'\n for char in '厅听烃汀廷停亭庭挺艇':\n self.trans[char] = 'ting'\n for char in '通桐酮瞳同铜彤童桶捅筒统痛':\n self.trans[char] = 'tong'\n for char in '偷投头透':\n self.trans[char] = 'tou'\n for char in '凸秃突图徒途涂屠土吐兔':\n self.trans[char] = 'tu'\n for char in '湍团':\n self.trans[char] = 'tuan'\n for char in '推颓腿蜕褪退':\n self.trans[char] = 'tui'\n for char in '吞屯臀':\n self.trans[char] = 'tun'\n for char in '拖托脱鸵陀驮驼椭妥拓唾':\n self.trans[char] = 'tuo'\n for char in '挖哇蛙洼娃瓦袜':\n self.trans[char] = 'wa'\n for char in '歪外':\n self.trans[char] = 'wai'\n for char in '豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕莞':\n self.trans[char] = 'wan'\n for char in '汪王亡枉网往旺望忘妄':\n self.trans[char] = 'wang'\n for char in '威巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫':\n self.trans[char] = 'wei'\n for char in '瘟温蚊文闻纹吻稳紊问':\n self.trans[char] = 'wen'\n for char in '嗡翁瓮':\n self.trans[char] = 'weng'\n for char in '挝蜗涡窝我斡卧握沃':\n self.trans[char] = 'wo'\n for char in '巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误':\n self.trans[char] = 'wu'\n for char in ('昔熙析西硒矽晰嘻吸锡牺稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系'\n '隙戏细'):\n self.trans[char] = 'xi'\n for char in '瞎虾匣霞辖暇峡侠狭下厦夏吓':\n self.trans[char] = 'xia'\n for char in '掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线':\n self.trans[char] = 'xian'\n for char in '相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象':\n self.trans[char] = 'xiang'\n for char in '萧硝霄削哮嚣销消宵淆晓小孝校肖啸笑效':\n self.trans[char] = 'xiao'\n for char in '楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑':\n self.trans[char] = 'xie'\n for char in '薪芯锌欣辛新忻心信衅':\n self.trans[char] = 'xin'\n for char in '星腥猩惺兴刑型形邢行醒幸杏性姓':\n self.trans[char] = 'xing'\n for char in '兄凶胸匈汹雄熊':\n self.trans[char] = 'xiong'\n for char in '休修羞朽嗅锈秀袖绣':\n self.trans[char] = 'xiu'\n for char in '墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续':\n self.trans[char] = 'xu'\n for char in '轩喧宣悬旋玄选癣眩绚':\n self.trans[char] = 'xuan'\n for char in '靴薛学穴雪血':\n self.trans[char] = 'xue'\n for char in '勋熏循旬询寻驯巡殉汛训讯逊迅':\n self.trans[char] = 'xun'\n for char in '压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶':\n self.trans[char] = 'ya'\n for char in '焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验':\n self.trans[char] = 'yan'\n for char in '殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾':\n self.trans[char] = 'yang'\n for char in '邀腰妖瑶摇尧遥窑谣姚咬舀药要耀':\n self.trans[char] = 'yao'\n for char in '椰噎耶爷野冶也页掖业叶曳腋夜液':\n self.trans[char] = 'ye'\n for char in ('一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿'\n '役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎'):\n self.trans[char] = 'yi'\n for char in '茵荫因殷音阴姻吟银淫寅饮尹引隐印':\n self.trans[char] = 'yin'\n for char in '英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映':\n self.trans[char] = 'ying'\n self.trans['哟'] = 'yo'\n for char in '拥佣臃痈庸雍踊蛹咏泳涌永恿勇用':\n self.trans[char] = 'yong'\n for char in '幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂':\n self.trans[char] = 'you'\n for char in ('淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻'\n '峪御愈欲狱育誉浴寓裕预豫驭'):\n self.trans[char] = 'yu'\n for char in '鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院':\n self.trans[char] = 'yuan'\n for char in '曰约越跃钥岳粤月悦阅':\n self.trans[char] = 'yue'\n for char in '耘云郧匀陨允运蕴酝晕韵孕':\n self.trans[char] = 'yun'\n for char in '匝砸杂':\n self.trans[char] = 'za'\n for char in '栽哉灾宰载再在':\n self.trans[char] = 'zai'\n for char in '咱攒暂赞':\n self.trans[char] = 'zan'\n for char in '赃脏葬':\n self.trans[char] = 'zang'\n for char in '遭糟凿藻枣早澡蚤躁噪造皂灶燥':\n self.trans[char] = 'zao'\n for char in '责择则泽':\n self.trans[char] = 'ze'\n self.trans['贼'] = 'zei'\n self.trans['怎'] = 'zen'\n for char in '增憎曾赠':\n self.trans[char] = 'zeng'\n for char in '扎喳渣札轧铡闸眨栅榨咋乍炸诈':\n self.trans[char] = 'zha'\n for char in '摘斋宅窄债寨':\n self.trans[char] = 'zhai'\n for char in '瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽':\n self.trans[char] = 'zhan'\n for char in '樟章彰漳张掌涨杖丈帐账仗胀瘴障':\n self.trans[char] = 'zhang'\n for char in '招昭找沼赵照罩兆肇召':\n self.trans[char] = 'zhao'\n for char in '遮折哲蛰辙者锗蔗这浙':\n self.trans[char] = 'zhe'\n for char in '珍斟真甄砧臻贞针侦枕疹诊震振镇阵圳':\n self.trans[char] = 'zhen'\n for char in '蒸挣睁征狰争怔整拯正政帧症郑证':\n self.trans[char] = 'zheng'\n for char in ('芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置'\n '帜峙制智秩稚质炙痔滞治窒'):\n self.trans[char] = 'zhi'\n for char in '中盅忠钟衷终种肿重仲众':\n self.trans[char] = 'zhong'\n for char in '舟周州洲诌粥轴肘帚咒皱宙昼骤':\n self.trans[char] = 'zhou'\n for char in '珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑住注祝驻':\n self.trans[char] = 'zhu'\n for char in '抓爪':\n self.trans[char] = 'zhua'\n self.trans['拽'] = 'zhuai'\n for char in '专砖转撰赚篆':\n self.trans[char] = 'zhuan'\n for char in '桩庄装妆撞壮状':\n self.trans[char] = 'zhuang'\n for char in '椎锥追赘坠缀':\n self.trans[char] = 'zhui'\n for char in '谆准':\n self.trans[char] = 'zhun'\n for char in '捉拙卓桌琢茁酌啄着灼浊':\n self.trans[char] = 'zhuo'\n for char in '兹咨资姿滋淄孜紫仔籽滓子自渍字':\n self.trans[char] = 'zi'\n for char in '鬃棕踪宗综总纵':\n self.trans[char] = 'zong'\n for char in '邹走奏揍':\n self.trans[char] = 'zou'\n for char in '租足卒族祖诅阻组':\n self.trans[char] = 'zu'\n for char in '钻纂':\n self.trans[char] = 'zuan'\n for char in '嘴醉最罪':\n self.trans[char] = 'zui'\n for char in '尊遵':\n self.trans[char] = 'zun'\n for char in '昨左佐柞做作坐座':\n self.trans[char] = 'zuo'\n # from:\n # https://www.wikidata.org/wiki/MediaWiki:Gadget-SimpleTransliterate.js\n self.trans['ଂ'] = 'anusvara'\n self.trans['ઇ'] = 'i'\n self.trans['എ'] = 'e'\n self.trans['ગ'] = 'ga'\n self.trans['ਜ'] = 'ja'\n self.trans['ഞ'] = 'nya'\n self.trans['ଢ'] = 'ddha'\n self.trans['ધ'] = 'dha'\n self.trans['ਬ'] = 'ba'\n self.trans['മ'] = 'ma'\n self.trans['ଲ'] = 'la'\n self.trans['ષ'] = 'ssa'\n self.trans['਼'] = 'nukta'\n self.trans['ാ'] = 'aa'\n self.trans['ୂ'] = 'uu'\n self.trans['ે'] = 'e'\n self.trans['ੌ'] = 'au'\n self.trans['ൎ'] = 'reph'\n self.trans['ੜ'] = 'rra'\n self.trans['՞'] = '?'\n self.trans['ୢ'] = 'l'\n self.trans['૧'] = '1'\n self.trans['੬'] = '6'\n self.trans['൮'] = '8'\n self.trans['୲'] = 'quarter'\n self.trans['ൾ'] = 'll'\n self.trans['ਇ'] = 'i'\n self.trans['ഉ'] = 'u'\n self.trans['ઌ'] = 'l'\n self.trans['ਗ'] = 'ga'\n self.trans['ങ'] = 'nga'\n self.trans['ଝ'] = 'jha'\n self.trans['જ'] = 'ja'\n self.trans['؟'] = '?'\n self.trans['ਧ'] = 'dha'\n self.trans['ഩ'] = 'nnna'\n self.trans['ଭ'] = 'bha'\n self.trans['બ'] = 'ba'\n self.trans['ഹ'] = 'ha'\n self.trans['ଽ'] = 'avagraha'\n self.trans['઼'] = 'nukta'\n self.trans['ੇ'] = 'ee'\n self.trans['୍'] = 'virama'\n self.trans['ૌ'] = 'au'\n self.trans['੧'] = '1'\n self.trans['൩'] = '3'\n self.trans['୭'] = '7'\n self.trans['૬'] = '6'\n self.trans['൹'] = 'mark'\n self.trans['ਖ਼'] = 'khha'\n self.trans['ਂ'] = 'bindi'\n self.trans['ഈ'] = 'ii'\n self.trans['ઍ'] = 'e'\n self.trans['ଌ'] = 'l'\n self.trans['ഘ'] = 'gha'\n self.trans['ઝ'] = 'jha'\n self.trans['ଡ଼'] = 'rra'\n self.trans['ਢ'] = 'ddha'\n self.trans['ന'] = 'na'\n self.trans['ભ'] = 'bha'\n self.trans['ବ'] = 'ba'\n self.trans['ਲ'] = 'la'\n self.trans['സ'] = 'sa'\n self.trans['ઽ'] = 'avagraha'\n self.trans['଼'] = 'nukta'\n self.trans['ੂ'] = 'uu'\n self.trans['ൈ'] = 'ai'\n self.trans['્'] = 'virama'\n self.trans['ୌ'] = 'au'\n self.trans['൨'] = '2'\n self.trans['૭'] = '7'\n self.trans['୬'] = '6'\n self.trans['ੲ'] = 'iri'\n self.trans['ഃ'] = 'visarga'\n self.trans['ં'] = 'anusvara'\n self.trans['ଇ'] = 'i'\n self.trans['ഓ'] = 'oo'\n self.trans['ଗ'] = 'ga'\n self.trans['ਝ'] = 'jha'\n self.trans['?'] = '?'\n self.trans['ണ'] = 'nna'\n self.trans['ઢ'] = 'ddha'\n self.trans['ଧ'] = 'dha'\n self.trans['ਭ'] = 'bha'\n self.trans['ള'] = 'lla'\n self.trans['લ'] = 'la'\n self.trans['ଷ'] = 'ssa'\n self.trans['ൃ'] = 'r'\n self.trans['ૂ'] = 'uu'\n self.trans['େ'] = 'e'\n self.trans['੍'] = 'virama'\n self.trans['ୗ'] = 'mark'\n self.trans['ൣ'] = 'll'\n self.trans['ૢ'] = 'l'\n self.trans['୧'] = '1'\n self.trans['੭'] = '7'\n self.trans['൳'] = '1/4'\n self.trans['୷'] = 'sixteenths'\n self.trans['ଆ'] = 'aa'\n self.trans['ઋ'] = 'r'\n self.trans['ഊ'] = 'uu'\n self.trans['ਐ'] = 'ai'\n self.trans['ଖ'] = 'kha'\n self.trans['છ'] = 'cha'\n self.trans['ച'] = 'ca'\n self.trans['ਠ'] = 'ttha'\n self.trans['ଦ'] = 'da'\n self.trans['ફ'] = 'pha'\n self.trans['പ'] = 'pa'\n self.trans['ਰ'] = 'ra'\n self.trans['ଶ'] = 'sha'\n self.trans['ഺ'] = 'ttta'\n self.trans['ੀ'] = 'ii'\n self.trans['ો'] = 'o'\n self.trans['ൊ'] = 'o'\n self.trans['ୖ'] = 'mark'\n self.trans['୦'] = '0'\n self.trans['૫'] = '5'\n self.trans['൪'] = '4'\n self.trans['ੰ'] = 'tippi'\n self.trans['୶'] = 'eighth'\n self.trans['ൺ'] = 'nn'\n self.trans['ଁ'] = 'candrabindu'\n self.trans['അ'] = 'a'\n self.trans['ઐ'] = 'ai'\n self.trans['ക'] = 'ka'\n self.trans['ਸ਼'] = 'sha'\n self.trans['ਛ'] = 'cha'\n self.trans['ଡ'] = 'dda'\n self.trans['ઠ'] = 'ttha'\n self.trans['ഥ'] = 'tha'\n self.trans['ਫ'] = 'pha'\n self.trans['ર'] = 'ra'\n self.trans['വ'] = 'va'\n self.trans['ୁ'] = 'u'\n self.trans['ી'] = 'ii'\n self.trans['ੋ'] = 'oo'\n self.trans['ૐ'] = 'om'\n self.trans['ୡ'] = 'll'\n self.trans['ૠ'] = 'rr'\n self.trans['੫'] = '5'\n self.trans['ୱ'] = 'wa'\n self.trans['૰'] = 'sign'\n self.trans['൵'] = 'quarters'\n self.trans['ਫ਼'] = 'fa'\n self.trans['ઁ'] = 'candrabindu'\n self.trans['ਆ'] = 'aa'\n self.trans['ઑ'] = 'o'\n self.trans['ଐ'] = 'ai'\n self.trans['ഔ'] = 'au'\n self.trans['ਖ'] = 'kha'\n self.trans['ડ'] = 'dda'\n self.trans['ଠ'] = 'ttha'\n self.trans['ത'] = 'ta'\n self.trans['ਦ'] = 'da'\n self.trans['ର'] = 'ra'\n self.trans['ഴ'] = 'llla'\n self.trans['ુ'] = 'u'\n self.trans['ୀ'] = 'ii'\n self.trans['ൄ'] = 'rr'\n self.trans['ૡ'] = 'll'\n self.trans['ୠ'] = 'rr'\n self.trans['੦'] = '0'\n self.trans['૱'] = 'sign'\n self.trans['୰'] = 'isshar'\n self.trans['൴'] = '1/2'\n self.trans['ਁ'] = 'bindi'\n self.trans['આ'] = 'aa'\n self.trans['ଋ'] = 'r'\n self.trans['ഏ'] = 'ee'\n self.trans['ખ'] = 'kha'\n self.trans['ଛ'] = 'cha'\n self.trans['ട'] = 'tta'\n self.trans['ਡ'] = 'dda'\n self.trans['દ'] = 'da'\n self.trans['ଫ'] = 'pha'\n self.trans['യ'] = 'ya'\n self.trans['શ'] = 'sha'\n self.trans['ി'] = 'i'\n self.trans['ੁ'] = 'u'\n self.trans['ୋ'] = 'o'\n self.trans['ੑ'] = 'udaat'\n self.trans['૦'] = '0'\n self.trans['୫'] = '5'\n self.trans['൯'] = '9'\n self.trans['ੱ'] = 'addak'\n self.trans['ൿ'] = 'k'\n self.trans['ആ'] = 'aa'\n self.trans['ଊ'] = 'uu'\n self.trans['એ'] = 'e'\n self.trans['ਔ'] = 'au'\n self.trans['ഖ'] = 'kha'\n self.trans['ଚ'] = 'ca'\n self.trans['ટ'] = 'tta'\n self.trans['ਤ'] = 'ta'\n self.trans['ദ'] = 'da'\n self.trans['ପ'] = 'pa'\n self.trans['ય'] = 'ya'\n self.trans['ശ'] = 'sha'\n self.trans['િ'] = 'i'\n self.trans['െ'] = 'e'\n self.trans['൦'] = '0'\n self.trans['୪'] = '4'\n self.trans['૯'] = '9'\n self.trans['ੴ'] = 'onkar'\n self.trans['ଅ'] = 'a'\n self.trans['ਏ'] = 'ee'\n self.trans['କ'] = 'ka'\n self.trans['ઔ'] = 'au'\n self.trans['ਟ'] = 'tta'\n self.trans['ഡ'] = 'dda'\n self.trans['ଥ'] = 'tha'\n self.trans['ત'] = 'ta'\n self.trans['ਯ'] = 'ya'\n self.trans['റ'] = 'rra'\n self.trans['ଵ'] = 'va'\n self.trans['ਿ'] = 'i'\n self.trans['ു'] = 'u'\n self.trans['ૄ'] = 'rr'\n self.trans['ൡ'] = 'll'\n self.trans['੯'] = '9'\n self.trans['൱'] = '100'\n self.trans['୵'] = 'sixteenth'\n self.trans['અ'] = 'a'\n self.trans['ਊ'] = 'uu'\n self.trans['ഐ'] = 'ai'\n self.trans['ક'] = 'ka'\n self.trans['ଔ'] = 'au'\n self.trans['ਚ'] = 'ca'\n self.trans['ഠ'] = 'ttha'\n self.trans['થ'] = 'tha'\n self.trans['ତ'] = 'ta'\n self.trans['ਪ'] = 'pa'\n self.trans['ര'] = 'ra'\n self.trans['વ'] = 'va'\n self.trans['ീ'] = 'ii'\n self.trans['ૅ'] = 'e'\n self.trans['ୄ'] = 'rr'\n self.trans['ൠ'] = 'rr'\n self.trans['ਜ਼'] = 'za'\n self.trans['੪'] = '4'\n self.trans['൰'] = '10'\n self.trans['୴'] = 'quarters'\n self.trans['ਅ'] = 'a'\n self.trans['ഋ'] = 'r'\n self.trans['ઊ'] = 'uu'\n self.trans['ଏ'] = 'e'\n self.trans['ਕ'] = 'ka'\n self.trans['ഛ'] = 'cha'\n self.trans['ચ'] = 'ca'\n self.trans['ଟ'] = 'tta'\n self.trans['ਥ'] = 'tha'\n self.trans['ഫ'] = 'pha'\n self.trans['પ'] = 'pa'\n self.trans['ଯ'] = 'ya'\n self.trans['ਵ'] = 'va'\n self.trans['ି'] = 'i'\n self.trans['ോ'] = 'oo'\n self.trans['ୟ'] = 'yya'\n self.trans['൫'] = '5'\n self.trans['૪'] = '4'\n self.trans['୯'] = '9'\n self.trans['ੵ'] = 'yakash'\n self.trans['ൻ'] = 'n'\n self.trans['ઃ'] = 'visarga'\n self.trans['ം'] = 'anusvara'\n self.trans['ਈ'] = 'ii'\n self.trans['ઓ'] = 'o'\n self.trans['ഒ'] = 'o'\n self.trans['ਘ'] = 'gha'\n self.trans['ଞ'] = 'nya'\n self.trans['ણ'] = 'nna'\n self.trans['ഢ'] = 'ddha'\n self.trans['ਲ਼'] = 'lla'\n self.trans['ਨ'] = 'na'\n self.trans['ମ'] = 'ma'\n self.trans['ળ'] = 'lla'\n self.trans['ല'] = 'la'\n self.trans['ਸ'] = 'sa'\n self.trans['¿'] = '?'\n self.trans['ା'] = 'aa'\n self.trans['ૃ'] = 'r'\n self.trans['ൂ'] = 'uu'\n self.trans['ੈ'] = 'ai'\n self.trans['ૣ'] = 'll'\n self.trans['ൢ'] = 'l'\n self.trans['੨'] = '2'\n self.trans['୮'] = '8'\n self.trans['൲'] = '1000'\n self.trans['ਃ'] = 'visarga'\n self.trans['ଉ'] = 'u'\n self.trans['ઈ'] = 'ii'\n self.trans['ਓ'] = 'oo'\n self.trans['ଙ'] = 'nga'\n self.trans['ઘ'] = 'gha'\n self.trans['ഝ'] = 'jha'\n self.trans['ਣ'] = 'nna'\n self.trans['ન'] = 'na'\n self.trans['ഭ'] = 'bha'\n self.trans['ଜ'] = 'ja'\n self.trans['ହ'] = 'ha'\n self.trans['સ'] = 'sa'\n self.trans['ഽ'] = 'avagraha'\n self.trans['ૈ'] = 'ai'\n self.trans['്'] = 'virama'\n self.trans['୩'] = '3'\n self.trans['૨'] = '2'\n self.trans['൭'] = '7'\n self.trans['ੳ'] = 'ura'\n self.trans['ൽ'] = 'l'\n self.trans['ઉ'] = 'u'\n self.trans['ଈ'] = 'ii'\n self.trans['ഌ'] = 'l'\n self.trans['ઙ'] = 'nga'\n self.trans['ଘ'] = 'gha'\n self.trans['ജ'] = 'ja'\n self.trans['ਞ'] = 'nya'\n self.trans['ନ'] = 'na'\n self.trans['ബ'] = 'ba'\n self.trans['ਮ'] = 'ma'\n self.trans['હ'] = 'ha'\n self.trans['ସ'] = 'sa'\n self.trans['ਾ'] = 'aa'\n self.trans['ૉ'] = 'o'\n self.trans['ୈ'] = 'ai'\n self.trans['ൌ'] = 'au'\n self.trans['૩'] = '3'\n self.trans['୨'] = '2'\n self.trans['൬'] = '6'\n self.trans['੮'] = '8'\n self.trans['ർ'] = 'rr'\n self.trans['ଃ'] = 'visarga'\n self.trans['ഇ'] = 'i'\n self.trans['ਉ'] = 'u'\n self.trans['ଓ'] = 'o'\n self.trans['ഗ'] = 'ga'\n self.trans['ਙ'] = 'nga'\n self.trans['ઞ'] = 'nya'\n self.trans['ଣ'] = 'nna'\n self.trans['ധ'] = 'dha'\n self.trans['મ'] = 'ma'\n self.trans['ଳ'] = 'lla'\n self.trans['ഷ'] = 'ssa'\n self.trans['ਹ'] = 'ha'\n self.trans['ਗ਼'] = 'ghha'\n self.trans['ા'] = 'aa'\n self.trans['ୃ'] = 'r'\n self.trans['േ'] = 'ee'\n self.trans['ൗ'] = 'mark'\n self.trans['ଢ଼'] = 'rha'\n self.trans['ୣ'] = 'll'\n self.trans['൧'] = '1'\n self.trans['੩'] = '3'\n self.trans['૮'] = '8'\n self.trans['୳'] = 'half'\n for char in self.trans:\n value = self.trans[char]\n if value == '?':\n continue\n while (value.encode(encoding, 'replace').decode(encoding) == '?'\n and value in self.trans):\n assert value != self.trans[value], \\\n '{!r} == self.trans[{!r}]!'.format(value, value)\n value = self.trans[value]\n self.trans[char] = value",
"def replace_foreign_phrase(text, dic=load_dic()):\n # matches 15 words or quotation in front of the parantheses\n regex = re.compile(\"((?:(\\w+\\s+|\\w+')){1,15}\\(((d|D)eutsch:|zu (d|D)eutsch).*?\\)|\\\"([^\\\"]*)\\\" \\(((d|D)eutsch:|zu (d|D)eutsch):.*?\\))\")\n original_and_translation = regex.search(remove_nonlatin(text))\n \n if original_and_translation != None:\n original = re.search(\"^.*?\\(\", original_and_translation.group()).group()[:-1]\n \n if re.search(\"\\\"([^\\\"]*)\\\"\", original) == None:\n original = find_foreign_phrase(original, dic)\n \n paranthesis = re.search(\"\\(((d|D)eutsch:|zu (d|D)eutsch).*?\\)\", original_and_translation.group())\n if paranthesis != None:\n translation = re.sub(\"\\(((d|D)eutsch:|zu (d|D)eutsch). |\\)\", \"\", paranthesis.group())\n \n return text[:text.find(original)] + translation + text[text.find(paranthesis.group()) + len(paranthesis.group()):]\n else:\n return text",
"def _visit_translation(self, s):\r\n return s",
"def google_translate(params):\n global translator\n if translator is None:\n translator = Translator()\n translated = translator.translate(params['text'], src=params['src'], dest=params['dest'])\n return translated",
"def translate(text, conversion_dict, before=None):\n # if empty:\n if not text: return text\n # preliminary transformation:\n before = before or str\n t = before(text)\n for key, value in conversion_dict.items():\n t = t.replace(key, value)\n return t",
"def _single_google_translate(jp_str: str) -> str:\n\tif _DISABLE_INTERNET_TRANSLATE:\n\t\treturn jp_str\n\ttry:\n\t\t# acutally send a single string to Google for translation\n\t\tif GOOGLE_AUTODETECT_LANGUAGE:\n\t\t\tr = jp_to_en_google.translate(jp_str, dest=\"en\") # auto\n\t\telse:\n\t\t\tr = jp_to_en_google.translate(jp_str, dest=\"en\", src=\"ja\") # jap\n\t\treturn r.text\n\texcept ConnectionError as e:\n\t\tcore.MY_PRINT_FUNC(e.__class__.__name__, e)\n\t\tcore.MY_PRINT_FUNC(\"Check your internet connection?\")\n\t\traise RuntimeError()\n\texcept Exception as e:\n\t\tcore.MY_PRINT_FUNC(e.__class__.__name__, e)\n\t\tif hasattr(e, \"doc\"):\n\t\t\tcore.MY_PRINT_FUNC(\"Response from Google:\")\n\t\t\tcore.MY_PRINT_FUNC(e.doc.split(\"\\n\")[7])\n\t\t\tcore.MY_PRINT_FUNC(e.doc.split(\"\\n\")[9])\n\t\tcore.MY_PRINT_FUNC(\"Google API has rejected the translate request\")\n\t\tcore.MY_PRINT_FUNC(\"This is probably due to too many translate requests too quickly\")\n\t\tcore.MY_PRINT_FUNC(\"Strangely, this lockout does NOT prevent you from using Google Translate thru your web browser. So go use that instead.\")\n\t\tcore.MY_PRINT_FUNC(\"Get a VPN or try again in about 1 day (TODO: CONFIRM LOCKOUT TIME)\")\n\t\traise RuntimeError()",
"def load_fake_translation(func=None):\n StringProperty.set_translator(func or fake_translation)",
"def translate_text(source_text, lg_from, lg_to):\n # Instantiates a client\n translate_client = translate.Client()\n\n # The text to translate\n text = source_text\n # The target language\n target = lg_to\n\n # Translates some text into Russian\n translation = translate_client.translate(\n text,\n target_language=target)\n\n #print(u'Text: {}'.format(text))\n #print(u'Translation: {}'.format(translation['translatedText']))\n # [END translate_quickstart]\n return translation['translatedText']",
"def _hit_google_api(text: str, source_lang_code: str, destination_lang_code: str) -> str:\n translator = Translator()\n return translator.translate(text, src=source_lang_code, dest=destination_lang_code).text",
"def setupTranslator(app):\n try:\n locale.setlocale(locale.LC_ALL, '')\n except locale.Error:\n pass\n global lang\n lang = os.environ.get('LC_MESSAGES', '')\n if not lang:\n lang = os.environ.get('LANG', '')\n if not lang:\n try:\n lang = locale.getdefaultlocale()[0]\n except ValueError:\n pass\n if not lang:\n lang = ''\n numTranslators = 0\n if lang and lang[:2] not in ['C', 'en']:\n numTranslators += loadTranslator('qt_{0}'.format(lang), app)\n numTranslators += loadTranslator('convertall_{0}'.format(lang), app)\n\n def translate(text, comment=''):\n \"\"\"Translation function that sets context to calling module's\n filename.\n \"\"\"\n try:\n frame = sys._getframe(1)\n fileName = frame.f_code.co_filename\n finally:\n del frame\n context = os.path.basename(os.path.splitext(fileName)[0])\n return QCoreApplication.translate(context, text, comment)\n\n def markNoTranslate(text, comment=''):\n return text\n\n if numTranslators:\n builtins._ = translate\n else:\n builtins._ = markNoTranslate",
"def unicode_translate_error():\n try:\n # just throwing the exception...\n raise UnicodeTranslateError('\\x99', 1, 2, 'Unknown char')\n except UnicodeTranslateError:\n return \"can't translate unicode character\"",
"def get_translation(cls, destination_lang: str, text: str, source_lang: str = None):\n if destination_lang not in cls.abbreviation_list:\n raise cls.TranslatorIncorrectAbbreviation(destination_lang)\n try:\n if source_lang is None:\n source_lang = cls.detect_lang(text)\n elif source_lang not in cls.abbreviation_list:\n raise cls.TranslatorIncorrectAbbreviation(source_lang)\n return cls.TRANSLATOR.translate(text, lang_src=source_lang, lang_tgt=destination_lang)\n except json.decoder.JSONDecodeError:\n cls.TranslatorUntranslatableError(text)\n except Exception as e:\n if e.__str__() == 'Failed to connect. Probable cause: timeout':\n raise cls.TranslatorConnectionError()\n raise e"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.