Python settings 模块,Settings() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用settings.Settings()

项目:sublime-commandbox    作者:Ortus-Solutions    | 项目源码 | 文件源码
def run(self, task_name=None, task_flag=None, silent=False, paths=[]):
        self.searchable_folders = [os.path.dirname(path) for path in paths] if len(paths) > 0 else self.window.folders()
        self._working_dir = ""
        self._working_dir = self.projectPath()
        print( "Working Directory: " + self._working_dir )
        self.settings = Settings()
        self.setup_data_from_settings()

        self.process = CrossPlatformProcess( self )
        self.non_blocking=False
        self.results_in_new_tab=False
        self.task_name = task_name
        self.task_flag = task_flag if task_name is not None and task_flag is not None else self.get_flag_from_task_name()
        self.silent = silent
        self.output_view = self.window.get_output_panel("commandbox_output")

        self.work()
项目:TrezorSymmetricFileEncryption    作者:8go    | 项目源码 | 文件源码
def showGui(trezor, dialog, settings):
    """
    Initialize, ask for encrypt/decrypt options,
    ask for files to be decrypted/encrypted,
    ask for master passphrase = trezor passphrase.

    Makes sure a session is created on Trezor so that the passphrase
    will be cached until disconnect.

    @param trezor: Trezor client
    @param settings: Settings object to store command line arguments or
        items selected in GUI
    """
    settings.settings2Gui(dialog)
    if not dialog.exec_():
        # Esc or exception or Quit/Close/Done
        settings.mlogger.log("Shutting down due to user request "
            "(Done/Quit was called).", logging.DEBUG, "GUI IO")
        # sys.exit(4)
    settings.gui2Settings(dialog)
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Set the background color.
    bg_color = (230, 230, 230)

    # Make a ship.
    ship = Ship(ai_settings, screen)
    # Make a group to store bullets in.
    bullets = Group()

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullets(bullets)
        gf.update_screen(ai_settings, screen, ship, bullets)
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Set the background color.
    bg_color = (230, 230, 230)

    # Make a ship.
    ship = Ship(ai_settings, screen)

    # Start the main loop for the game.
    while True:
        gf.check_events(ship)
        ship.update()
        gf.update_screen(ai_settings, screen, ship)
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Set the background color.
    bg_color = (230, 230, 230)

    # Make a ship.
    ship = Ship(ai_settings, screen)
    # Make a group to store bullets in.
    bullets = Group()

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        bullets.update()
        gf.update_screen(ai_settings, screen, ship, bullets)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.region = 'canada-1a'
        self.settings.pcf_pcfcustomresourcesqsqueueurl = 'https://queue.example.com'

        self.response = {'Messages':
            [
                {
                    'Body': '{\n  "Type" : "Notification",\n  "MessageId" : "3c71d3a0-7d25-59b1-93bc-8213196855a7",\n  "TopicArn" : "arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ",\n  "Subject" : "AWS CloudFormation custom resource request",\n  "Message" : "{\\"RequestType\\":\\"Create\\",\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ\\",\\"ResponseURL\\":\\"https://cloudformation-custom-resource-response-uswest2.s3-us-west-2.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-west-2%3A530420658117%3Astack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2%7CMyCustomResource%7C4dd2c9a0-04cb-4218-908c-e3cdfad3c634?AWSAccessKeyId=AKIAI4KYMPPRGQACET5Q&Expires=1496940077&Signature=uLbeSl3rtkuDa2xf0y9oMFc1zBI%3D\\",\\"StackId\\":\\"arn:aws:cloudformation:us-west-2:540420658117:stack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2\\",\\"RequestId\\":\\"4dd2c9a0-04cb-4218-908c-e2cdfad3c634\\",\\"LogicalResourceId\\":\\"MyCustomResource\\",\\"ResourceType\\":\\"Custom::CloudFoundryPhase1\\",\\"ResourceProperties\\":{\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540410658117:custom-resource-maybe-4-SNSTopic-11NVZUIXWZTXZ\\",\\"ExampleProperty2\\":\\"ExampleValue2\\",\\"ExampleProperty1\\":\\"ExampleValue1\\"}}",\n  "Timestamp" : "2017-06-08T14:41:17.469Z",\n  "SignatureVersion" : "1",\n  "Signature" : "eNbpNJ+mzhH4qRP89tIWj96cK0nCirmNkwjQe/3DAgWnuhKKYKvtkffZu04uTynb/Tjt/5O7y/dfUy5cTmauhAx9g8gFkwH4vQVGhJOgEI6hFEHqRgY+8FwfeKowDiZTJyixwuqY9O1wqXxOb9q0rsLpApZCVwHsIhXio3ATdmJVNuJZhpC+0Dae1jnAg7nRyLAOrjEI8yaGLLoA1s/KdrZakclwGIgNj+/as4Vscbd1+VH59cpzryoHpOIjQrESTsCqCSSHh9H4j10wjDAeFxDY3lAZOZu+SlWOsCshv+4xRiJMmWY+WCgJ2UuAXnj7N6QPKwXwnPV1UmdkXGaGWQ==",\n  "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-b95095beb82e8q6a046b3aafc7f4149a.pem",\n  "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:540420258117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ:dc93952d-b252-4da3-a726-7df99631df02"\n}',
                    'MD5OfBody': '46e9054484367800fbd6bb8e13aaea36',
                    'MessageId': '6eef8c02-9874-41f8-8883-9788b911b773',
                    'ReceiptHandle': 'AQEBCLcjvnWL65ILiE9/L6WzthEatj3punqXWcxK/VGSfOhkjbfaMoy6GHtxPr/giOjO2gIW7buTv9Mkhk7/tpgbgJEm338nzoLOxqiW4s3fzoQWrjDu0HHpcD1KrMJBeVstxnLglEOOny2KRozfsLjbeH5HoXuo+8mrb0nwVUglIK2vBkAPHLOGu64/BPOR6dt2qgYK4hzytgXQprcLlS5rYrrpYkqBKjWt9PCuwSG244LuN3brNyRIgxPR9SQ/ja9CWocx7sS3Ri6tAVU8zP4OxjRmfdMj/EEdL3Wm5m4v7+hnGDnj0LSV/3UX6C1/ozIOtHY6bqN6HQ6nM48Dk6UTEm78ApFuYmOFnh5xfcAEJHHN9meqnMsYMe0l8hTEBRHDYII/W4K5APbUNNsuoU/R3uYgqWlNMFWDvxSORKPwy/2O0Kk51+ZE/fyGEaVncoof'
                }
            ],
            'ResponseMetadata': {
                'HTTPStatusCode': 200, 'HTTPHeaders': {
                    'connection': 'keep-alive', 'server': 'Server',
                    'content-length': '3342',
                    'content-type': 'text/xml',
                    'date': 'Thu, 08 Jun 2017 15:20:07 GMT',
                    'x-amzn-requestid': '116092e7-fee7-5580-b276-c3549380b837'
                },
                'RequestId': '116092e7-fee7-5580-b276-c3549380b837', 'RetryAttempts': 0
            }
        }
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def generate_ssh_keypair(my_settings: Settings):
    client = boto3.client(service_name='ec2', region_name=my_settings.region)

    keyname = my_settings.get_pcf_keypair_name()
    response = client.create_key_pair(
        DryRun=False,
        KeyName=keyname
    )

    home = expanduser("~/.ssh")
    pem_file = '{}/{}.pem'.format(home, keyname)

    with open(pem_file, 'w') as keyfile:
        keyfile.write(response.get('KeyMaterial'))
    os.chmod(pem_file, 0o400)

    return keyname, response.get('KeyMaterial')
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def check(my_settings: settings.Settings):
    raw_message = sqs.get_messages(my_settings)

    if len(raw_message) < 1:
        print("No message on queue; doing nothing since delete not triggered")
        return
    messages = [sqs.parse_message(m) for m in raw_message]
    delete_messages = [
        m for m in messages if
        m.get('RequestType') == "Delete"
    ]
    if len(delete_messages) < 1:
        print("No message of type Delete")
        return

    out, err, return_code = delete_everything.delete_everything(my_settings)
    for delete_message in delete_messages:
        if return_code != 0:
            sqs.report_cr_deletion_failure(my_settings, delete_message.get('LogicalResourceId'))
        else:
            sqs.report_cr_deletion_success(my_settings, delete_message.get('LogicalResourceId'))
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.zones = ["zone1"]
        self.settings.pcf_iam_access_key_id = "access_id"
        self.settings.pcf_iam_secret_access_key = "secret_key"
        self.settings.vpc_id = "vpc-123"
        self.settings.stack_name = "my-pcf-stack"
        self.settings.security_group = "sec-123"
        self.settings.key_pair_name = "mytestkeypair"
        self.settings.region = "region-123"
        self.settings.vpc_private_subnet_id = "subnet1"
        self.settings.vpc_private_subnet_az = "east1"
        self.settings.vpc_private_subnet_id2 = "subnet2"
        self.settings.vpc_private_subnet_az2 = "east2"
        self.settings.opsman_url = "https://example123.com"
        self.settings.pcf_input_opsmanageradminpassword = "monkey123"
        self.settings.opsman_user = "testuser"
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def post_eula(my_settings: settings.Settings, slug: str, release_id: int):
    response = requests.post(
        url='https://network.pivotal.io/api/v2/products/{}/releases/{}/eula_acceptance'.format(slug, release_id),
        headers={
            'Authorization': 'Token {}'.format(my_settings.pcf_input_pivnettoken),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'User-Agent': 'PCF-Ecosystem-AWS-client'
        }
    )
    print(response)
    if response.status_code < 300:
        return response, EULAResult.SUCCESS
    elif response.status_code >= 500:
        return response, EULAResult.RETRY
    return response, EULAResult.FAILURE
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def stage_product(product_name: str, my_settings: settings.Settings):
    cmd = "{om_with_auth} curl --path /api/v0/available_products".format(
        om_with_auth=get_om_with_auth(my_settings)
    )
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = p.communicate()
    if p.returncode != 0:
        print("Failed to query api")
        return out, err, p.returncode

    products = json.loads(out.decode())
    cf_version = [x['product_version'] for x in products if x['name'] == product_name][0]

    # ok to call multiple times, no-op when already staged
    cmd = "{om_with_auth} stage-product -p {product_name} -v {version}".format(
        om_with_auth=get_om_with_auth(my_settings),
        product_name=product_name,
        version=cf_version
    )
    return util.exponential_backoff_cmd(cmd)
项目:funing    作者:langzi1949    | 项目源码 | 文件源码
def run_game():
    # ?????,?????????
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    # ????
    ship = Ship(ai_settings, screen)
    # ??????????????
    aliens = Group()
    # ??????
    gf.create_fleet(ai_settings, screen, aliens)
    # ?????????????
    bullets = Group()

    # ????????
    while True:
        # ?????????
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullet(bullets)
        # ????
        gf.update_screen(ai_settings, screen, ship, bullets,aliens)
项目:filaswitch    作者:spegelius    | 项目源码 | 文件源码
def __init__(self, logger, settings: Settings):
        super().__init__(logger, settings)
        self.extruder_name = []
        self.extruder_tool = []
        self.extruder_diameter = []
        self.extruder_multiplier = []
        self.extruder_use_retract = []
        self.extruder_retract_dist = []
        self.extruder_retract_speed = []
        self.extruder_zhop = []
        self.extruder_use_coasting = []
        self.extruder_coasting = []
        self.extruder_use_wipe = []
        self.extruder_wipe = []
        self.relative_e = False
        self.retract_while_wiping = False
        self.version = None

        self.temperature_names = []
        self.temperature_numbers = []
        self.temperature_setpoints = []
        self.temperature_setpoint_layers = []
        self.temperature_setpoint_temps = []
        self.temperature_heated_bed = []
项目:alien_invasion    作者:samnew    | 项目源码 | 文件源码
def run_game():
    #??????????????
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #??Play??
    play_button = Button(ai_settings, screen, "Play")


    #????????????????? ??????
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #??????
    ship = Ship(ai_settings, screen)
    #?????????????
    bullets = Group()
    #??????????
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #????????
    while True:

        #?????????
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            # bullets.update()

            # #????????
            # for bullet in bullets.copy():
            #     if bullet.rect.bottom <= 0:
            #         bullets.remove(bullet)
            # #print(len(bullets))
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
项目:labelImage    作者:tsuzukit    | 项目源码 | 文件源码
def test_basic(self):
        wSetting = Settings()
        wSetting['test0'] = 'hello'
        wSetting['test1'] = 10
        wSetting['test2'] = [0, 2, 3]
        self.assertEqual(wSetting.get('test3', 3), 3)
        self.assertEqual(wSetting.save(), True)
项目:ceph-backup    作者:teralytics    | 项目源码 | 文件源码
def main():
    parser = argparse.ArgumentParser(description='Backup tool for ceph')
    default_cephbackup_cfg = '/etc/cephbackup/cephbackup.conf'
    parser.add_argument('-c', '--conf', help="path to the configuration file (default: {})".format(default_cephbackup_cfg), type=str, default=default_cephbackup_cfg)
    args = parser.parse_args()
    settings = Settings(args.conf)
    settings.start_backup()
项目:ticketnak    作者:MartijnDevNull    | 项目源码 | 文件源码
def __init__(self, debug):
        self.debug = debug
        self.settings = Settings()
        try:
            self.graph = facebook.GraphAPI(access_token=self._get_acces_token(), version='2.9')
            self.logger = logging.basicConfig(level=logging.DEBUG) if self.debug else logging.basicConfig(
                level=logging.INFO)
        except KeyError:
            exit("Check if configuration is set right")

        try:
            self.scoop = Reserve()
        except:
            pass
项目:ticketnak    作者:MartijnDevNull    | 项目源码 | 文件源码
def __init__(self):
        settings = Settings()
        self.access_token = settings.TICKETSWAP_SESSION
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)

    # Set the background color.
    bg_color = (230, 230, 230)

    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)

        gf.update_screen(ai_settings, screen, ship, aliens, bullets)
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
# ??????????????
    pygame.init()
    #???init ?????

    ai_settings = Settings()
    screen = pygame.display.set_mode(
     (ai_settings.screen_width,
     ai_settings.screen_height)                                   
                                   )


    #screen = pygame.display.set_mode((1200, 800))
    #???????Settings ???
    #screen = pygame.display.set_mode((1200, 800))

    pygame.display.set_caption("?????")

    # ?????
    #bg_color = (230, 230, 230)
    #??? ?? ??? ????surface,????????surface

# ????????
    #???????,??????? ?? ???? ?????? ?????
    while True:
# ?????????
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                #event.type == pygame.QUIT: ?????????
                sys.exit()
    # ??????????
        screen.fill(ai_settings.bg_color)
        #?? ??? ??? 230 ?? ???????? ????
        #?? ??? ????

    #???????????? ????????? ???? ??

        pygame.display.flip()
项目:Pythonlearn    作者:godzoco    | 项目源码 | 文件源码
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics, and a scoreboard.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Set the background color.
    bg_color = (230, 230, 230)

    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
            aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
            bullets, play_button)
项目:events-organizer    作者:ccanonguy    | 项目源码 | 文件源码
def __init__(self, document):
        """Tokenize the text of the body."""
        self.settings = settings.Settings()
        self.tokeniser = RegexpTokenizer(self.settings.pattern)
        self.text = document['body']
        self.sentences = nltk.sent_tokenize(self.text)
        self.event = document['head']
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.meta_json = """
{
  "StackName": "pcf-stack",
  "StackId": "arn:aws:cloudformation:us-east-1:429148957415:stack/pcf-stack/1cb9cd21-2c4e-11e7-8e25-50fae98a10fe",
  "Region": "canada-west-1"
}
"""
        self.version_config_json = """
{
  "stemcell": {
    "releaseDate": "2017-04-26",
    "sha256": "ece6b9aaa4af20c180c446582bfa8e7d29681e2aac06c5d3d978a92c84432237",
    "version": "3363.20",
    "id": 5200
  },
  "ert": {
    "releaseDate": "2017-05-04",
    "sha256": "70070bf22231d9971c97b8deb8c4cd5ba990d24101e5398d0ccc70778060dbea",
    "version": "1.10.8",
    "id": 5334
  }
}
"""

        mock_client_contructor = Mock()

        with patch('boto3.client', mock_client_contructor):
            with patch('settings.read_meta') as mock_read_meta:
                mock_read_meta.return_value = json.loads(self.meta_json)
                with patch('settings.read_version_config') as mock_read_version_config:
                    mock_read_version_config.return_value = json.loads(self.version_config_json)

                    mock_client = Mock()
                    mock_client_contructor.return_value = mock_client
                    mock_client.describe_stacks.return_value = input_params
                    mock_client.get_parameter.return_value = params_store_output

                    self.settings = settings.Settings()
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_success(my_settings: settings.Settings, reason: str):
    return report_status(my_settings, reason, "SUCCESS")
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_failure(my_settings: settings.Settings, reason: str):
    return report_status(my_settings, reason, "FAILURE")
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_status(my_settings: settings.Settings, reason: str, status: str):
    response_url_full = my_settings.pcf_pcfwaithandle
    response_url, response_params = response_url_full.split('?')
    response_for_waitcondition = build_payload(reason, status)

    print("Writing to wait handle {}".format(response_url_full))
    response = requests.put(
        url=response_url, params=response_params,
        data=str.encode(json.dumps(response_for_waitcondition))
    )
    print(response)

    return 0
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_cr_creation_failure(my_settings: settings.Settings, reason: str, logical_res_id: str = ""):
    return report_status_backoff(my_settings, 'Create', reason, logical_res_id, 'FAILED')
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_cr_deletion_success(my_settings: settings.Settings, reason: str, logical_res_id: str = ""):
    return report_status_backoff(my_settings, 'Delete', reason, logical_res_id, 'SUCCESS')
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_cr_deletion_failure(my_settings: settings.Settings, reason: str, logical_res_id: str = ""):
    return report_status_backoff(my_settings, 'Delete', reason, logical_res_id, 'FAILED')
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_status_backoff(my_settings: settings.Settings, req_type: str, reason: str, logical_res_id: str, status: str):
    return util.exponential_backoff(
        functools.partial(report_status, my_settings, req_type, reason, logical_res_id, status),
        check_report_status
    )
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def report_status(my_settings: settings.Settings, req_type: str, reason: str, logical_res_id: str, status: str):
    raw_message = get_messages(my_settings)
    if len(raw_message) < 1:
        print("No message on queue... so we can't report back")
        return 1
    messages = [parse_message(m) for m in raw_message]
    filtered_messages = [m for m in messages if m.get('RequestType') == req_type]
    if logical_res_id != "":
        filtered_messages = [m for m in messages if m.get('LogicalResourceId') == logical_res_id]

    if len(filtered_messages) < 1:
        print("No message of type '{}', so unable to report back to CloudFormation".format(req_type))
        return 1

    for message in filtered_messages:
        response_for_cloud_formation = build_payload(message, status, reason)
        response_url_full = message.get('ResponseURL')
        response_url, response_params = response_url_full.split('?')
        json_response = json.dumps(response_for_cloud_formation)
        print("Posting SQS response\n{}".format(json_response))
        response = requests.put(
            url=response_url, params=response_params,
            data=str.encode(json_response)
        )
        if response.status_code != 200:
            print("Failed posting message {}".format(response))
            print("{}\n".format(response.text))

            return 1

        print("Deleting message", message.get('ReceiptHandle'))
        delete_messages(my_settings, message)

    return 0
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def get_messages(my_settings: settings.Settings):
    sqs = boto3.client(service_name='sqs', region_name=my_settings.region)
    response = sqs.receive_message(
        QueueUrl=my_settings.pcf_pcfcustomresourcesqsqueueurl,
        MaxNumberOfMessages=10,
        VisibilityTimeout=1
    )
    print("SQS Messages")
    print(json.dumps(response, indent="  "))

    return response.get('Messages', [])
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def configure_ert(my_settings: Settings):
    out, err, exit_code = om_manager.stage_product("cf", my_settings)
    if exit_code != 0:
        print("Failed to stage ERT")
        return out, err, exit_code

    out, err, exit_code = configure_tile_az(my_settings, 'cf')
    if exit_code != 0:
        print("Failed to configure az ERT")
        return out, err, exit_code

    out, err, exit_code = configure_ert_config(my_settings)
    if exit_code != 0:
        print("Failed to configure ERT")
        return out, err, exit_code

    out, err, exit_code = modify_vm_types(my_settings)
    if exit_code != 0:
        print("Failed to modify VM types for ERT")
        return out, err, exit_code

    out, err, exit_code = configure_ert_resources(my_settings)
    if exit_code != 0:
        print("Failed to configure ERT")
        return out, err, exit_code

    out, err, exit_code = configure_ert_multiaz_resources(my_settings)
    if exit_code != 0:
        print("Failed to configure Multi AZ ERT")
        return out, err, exit_code

    return create_required_databases(my_settings)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def configure_ert_resources(my_settings: Settings):
    prefix = my_settings.stack_name
    if my_settings.pcf_input_elbprefix != "":
        prefix = my_settings.pcf_input_elbprefix
    ert_resource_ctx = {
        "router_lb_name": "{prefix}".format(prefix=prefix)
    }
    with open("templates/ert_resources_config.j2.json", 'r') as f:
        ert_resource_template = Template(f.read())
    ert_resource_config = om_manager.format_om_json_str(ert_resource_template.render(ert_resource_ctx))
    cmd = "{om_with_auth} configure-product -n cf -pr '{ert_resources}'".format(
        om_with_auth=om_manager.get_om_with_auth(my_settings),
        ert_resources=ert_resource_config
    )
    return util.exponential_backoff_cmd(cmd)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def configure_ert_multiaz_resources(my_settings: Settings):
    if my_settings.pcf_pcfdeploymentsize == "Multi-AZ":
        with open("templates/ert_multiaz_resources_config.j2.json", 'r') as f:
            template = f.read()
    else:
        with open("templates/ert_singleaz_resources_config.j2.json", 'r') as f:
            template = f.read()

    ert_resource_config = om_manager.format_om_json_str(template)
    cmd = "{om_with_auth} configure-product -n cf -pr '{ert_resources}'".format(
        om_with_auth=om_manager.get_om_with_auth(my_settings),
        ert_resources=ert_resource_config
    )
    return util.exponential_backoff_cmd(cmd)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def configure_ert_config(my_settings: Settings):
    cert, key = generate_ssl_cert(my_settings)
    ert_config_template_ctx = {
        "pcf_rds_address": my_settings.pcf_rdsaddress,
        "pcf_rds_username": my_settings.pcf_rdsusername,
        "dns_suffix": my_settings.pcf_input_domain,
        "pcf_rds_password": my_settings.pcf_rdspassword,
        "admin_email": my_settings.pcf_input_adminemail,
        "pcf_elastic_runtime_s3_buildpacks_bucket": my_settings.pcf_elasticruntimes3buildpacksbucket,
        "pcf_elastic_runtime_s3_droplets_bucket": my_settings.pcf_elasticruntimes3dropletsbucket,
        "pcf_elastic_runtime_s3_packages_bucket": my_settings.pcf_elasticruntimes3packagesbucket,
        "pcf_elastic_runtime_s3_resources_bucket": my_settings.pcf_elasticruntimes3resourcesbucket,
        "pcf_iam_access_key_id": my_settings.pcf_iamuseraccesskey,
        "pcf_iam_secret_access_key": my_settings.pcf_iamusersecretaccesskey,
        "pcf_companyname": my_settings.pcf_pcfcompanyname,
        "s3_endpoint": my_settings.get_s3_endpoint(),
        "s3_region": my_settings.region,
        "pcf_skipsslvalidation": my_settings.pcf_input_skipsslvalidation,
        "cert": cert.replace("\n", "\\n"),
        "key": key.replace("\n", "\\n")
    }
    with open("templates/ert_config.j2.json", 'r') as f:
        ert_template = Template(f.read())
    ert_config = om_manager.format_om_json_str(ert_template.render(ert_config_template_ctx))
    cmd = "{om_with_auth} configure-product -n cf -p '{ert_config}'".format(
        om_with_auth=om_manager.get_om_with_auth(my_settings),
        ert_config=ert_config
    )
    return util.exponential_backoff_cmd(cmd)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def create_required_databases(my_settings: Settings):
    cmd = "mysql -h {hostname} --user={username} --port={port} --password={password} < templates/required_dbs.sql".format(
        hostname=my_settings.pcf_rdsaddress,
        username=my_settings.pcf_rdsusername,
        port=my_settings.pcf_rdsport,
        password=my_settings.pcf_rdspassword
    )

    return util.exponential_backoff_cmd(cmd)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def modify_vm_types(my_settings: Settings):
    path = '/api/v0/vm_types'
    out, err, return_code = om_manager.curl_get(my_settings, path)
    if return_code != 0:
        if out != "":
            print(out)
        if err != "":
            print(err)
        return out, err, return_code

    response_json = json.loads(out)
    m4_exists = False

    for vm_type in response_json["vm_types"]:
        if vm_type["name"].startswith("m3"):
            response_json["vm_types"].remove(vm_type)
        elif vm_type["name"].startswith("m4"):
            m4_exists = True

    if not m4_exists:
        with open("templates/ert_vm_types.json") as template:
            additional_types = json.load(template)
            for a in additional_types:
                response_json["vm_types"].append(a)

    out, err, return_code = om_manager.curl_payload(my_settings, path, json.dumps(response_json), 'PUT')
    if return_code != 0:
        if out != "":
            print(out)
        if err != "":
            print(err)

    return out, err, return_code
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def generate_ssl_cert(my_settings: Settings):
    call("scripts/gen_ssl_certs.sh {}".format(my_settings.pcf_input_domain), shell=True)
    with open("{}.crt".format(my_settings.pcf_input_domain), 'r') as cert_file:
        cert = cert_file.read()

    with open("{}.key".format(my_settings.pcf_input_domain), 'r') as key_file:
        key = key_file.read()

    return cert, key
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(settings.Settings)
        self.settings.ert_release_version = "1.9.0"
        self.settings.ert_release_sha256 = "xyz123"
        self.settings.stemcell_release_version = "123"
        self.settings.stemcell_release_sha256 = "123"
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def upload_stemcell(my_settings: settings.Settings, path: str):
    for stemcell in os.listdir(path):
        if stemcell.endswith(".tgz"):
            print("uploading stemcell {0}".format(stemcell))
            cmd = "{om_with_auth} upload-stemcell -s '{path}'".format(
                om_with_auth=om_manager.get_om_with_auth(my_settings), path=os.path.join(path, stemcell)
            )
            out, err, exit_code = util.exponential_backoff_cmd(cmd)
            if exit_code != 0:
                return out, err, exit_code

    return "", "", 0
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def upload_assets(my_settings: settings.Settings, path: str):
    for tile in os.listdir(path):
        if tile.endswith(".pivotal"):
            print("uploading product {0}".format(tile))

            cmd = "{om_with_auth} -r 3600 upload-product -p '{path}'".format(
                om_with_auth=om_manager.get_om_with_auth(my_settings), path=os.path.join(path, tile))

            out, err, exit_code = util.exponential_backoff_cmd(cmd)
            if exit_code != 0:
                return out, err, exit_code

    return "", "", 0
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.region = 'canada-1a'
        self.settings.pcf_pcfwaithandle = 'https://wait.example.com?signature=foo'
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.opsman_url = 'https://cf.example.com'
        self.settings.opsman_user = 'admin'
        self.settings.pcf_opsmanageradminpassword = 'monkey-123'
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.region = 'canada-1a'
        self.settings.pcf_elasticruntimes3buildpacksbucket = 'bucket-bp'
        self.settings.pcf_elasticruntimes3dropletsbucket = 'bucket-dp'
        self.settings.pcf_elasticruntimes3packagesbucket = 'bucket-pkg'
        self.settings.pcf_elasticruntimes3resourcesbucket = 'bucket-rsc'
        self.settings.pcf_iam_access_key_id = 'key-vale'
        self.settings.pcf_iam_secret_access_key = 'key-secret'
        self.settings.resources_created = True
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def setUp(self):
        self.settings = Mock(Settings)
        self.settings.region = 'canada-1a'
        self.settings.pcf_pcfcustomresourcesqsqueueurl = 'https://queue.example.com'

        self.response = {'Messages':
            [
                {
                    'Body': '{\n  "Type" : "Notification",\n  "MessageId" : "3c71d3a0-7d25-59b1-93bc-8213196855a7",\n  "TopicArn" : "arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ",\n  "Subject" : "AWS CloudFormation custom resource request",\n  "Message" : "{\\"RequestType\\":\\"Delete\\",\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ\\",\\"ResponseURL\\":\\"https://cloudformation-custom-resource-response-uswest2.s3-us-west-2.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-west-2%3A530420658117%3Astack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2%7CMyCustomResource%7C4dd2c9a0-04cb-4218-908c-e3cdfad3c634?AWSAccessKeyId=AKIAI4KYMPPRGQACET5Q&Expires=1496940077&Signature=uLbeSl3rtkuDa2xf0y9oMFc1zBI%3D\\",\\"StackId\\":\\"arn:aws:cloudformation:us-west-2:540420658117:stack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2\\",\\"RequestId\\":\\"4dd2c9a0-04cb-4218-908c-e2cdfad3c634\\",\\"LogicalResourceId\\":\\"MyCustomResource\\",\\"ResourceType\\":\\"Custom::CloudFoundryPhase1\\",\\"ResourceProperties\\":{\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540410658117:custom-resource-maybe-4-SNSTopic-11NVZUIXWZTXZ\\",\\"ExampleProperty2\\":\\"ExampleValue2\\",\\"ExampleProperty1\\":\\"ExampleValue1\\"}}",\n  "Timestamp" : "2017-06-08T14:41:17.469Z",\n  "SignatureVersion" : "1",\n  "Signature" : "eNbpNJ+mzhH4qRP89tIWj96cK0nCirmNkwjQe/3DAgWnuhKKYKvtkffZu04uTynb/Tjt/5O7y/dfUy5cTmauhAx9g8gFkwH4vQVGhJOgEI6hFEHqRgY+8FwfeKowDiZTJyixwuqY9O1wqXxOb9q0rsLpApZCVwHsIhXio3ATdmJVNuJZhpC+0Dae1jnAg7nRyLAOrjEI8yaGLLoA1s/KdrZakclwGIgNj+/as4Vscbd1+VH59cpzryoHpOIjQrESTsCqCSSHh9H4j10wjDAeFxDY3lAZOZu+SlWOsCshv+4xRiJMmWY+WCgJ2UuAXnj7N6QPKwXwnPV1UmdkXGaGWQ==",\n  "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-b95095beb82e8q6a046b3aafc7f4149a.pem",\n  "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:540420258117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ:dc93952d-b252-4da3-a726-7df99631df02"\n}',
                    'MD5OfBody': '46e9054484367800fbd6bb8e13aaea36',
                    'MessageId': '6eef8c02-9874-41f8-8883-9788b911b773',
                    'ReceiptHandle': 'AQEBCLcjvnWL65ILiE9/L6WzthEatj3punqXWcxK/VGSfOhkjbfaMoy6GHtxPr/giOjO2gIW7buTv9Mkhk7/tpgbgJEm338nzoLOxqiW4s3fzoQWrjDu0HHpcD1KrMJBeVstxnLglEOOny2KRozfsLjbeH5HoXuo+8mrb0nwVUglIK2vBkAPHLOGu64/BPOR6dt2qgYK4hzytgXQprcLlS5rYrrpYkqBKjWt9PCuwSG244LuN3brNyRIgxPR9SQ/ja9CWocx7sS3Ri6tAVU8zP4OxjRmfdMj/EEdL3Wm5m4v7+hnGDnj0LSV/3UX6C1/ozIOtHY6bqN6HQ6nM48Dk6UTEm78ApFuYmOFnh5xfcAEJHHN9meqnMsYMe0l8hTEBRHDYII/W4K5APbUNNsuoU/R3uYgqWlNMFWDvxSORKPwy/2O0Kk51+ZE/fyGEaVncoof'
                },
                {
                    'Body': '{\n  "Type" : "Notification",\n  "MessageId" : "3c71d3a0-7d25-59b1-93bc-8213196855a7",\n  "TopicArn" : "arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ",\n  "Subject" : "AWS CloudFormation custom resource request",\n  "Message" : "{\\"RequestType\\":\\"Create\\",\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540420658117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ\\",\\"ResponseURL\\":\\"https://cloudformation-custom-resource-response-uswest2.s3-us-west-2.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-west-2%3A530420658117%3Astack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2%7CMyCustomResource%7C4dd2c9a0-04cb-4218-908c-e3cdfad3c634?AWSAccessKeyId=AKIAI4KYMPPRGQACET5Q&Expires=1496940077&Signature=uLbeSl3rtkuDa2xf0y9oMFc1zBI%3D\\",\\"StackId\\":\\"arn:aws:cloudformation:us-west-2:540420658117:stack/pcf-stack/1e820540-4c58-11e7-a965-50d5ca0184f2\\",\\"RequestId\\":\\"4dd2c9a0-04cb-4218-908c-e2cdfad3c634\\",\\"LogicalResourceId\\":\\"MyCustomResource\\",\\"ResourceType\\":\\"Custom::CloudFoundryPhase1\\",\\"ResourceProperties\\":{\\"ServiceToken\\":\\"arn:aws:sns:us-west-2:540410658117:custom-resource-maybe-4-SNSTopic-11NVZUIXWZTXZ\\",\\"ExampleProperty2\\":\\"ExampleValue2\\",\\"ExampleProperty1\\":\\"ExampleValue1\\"}}",\n  "Timestamp" : "2017-06-08T14:41:17.469Z",\n  "SignatureVersion" : "1",\n  "Signature" : "eNbpNJ+mzhH4qRP89tIWj96cK0nCirmNkwjQe/3DAgWnuhKKYKvtkffZu04uTynb/Tjt/5O7y/dfUy5cTmauhAx9g8gFkwH4vQVGhJOgEI6hFEHqRgY+8FwfeKowDiZTJyixwuqY9O1wqXxOb9q0rsLpApZCVwHsIhXio3ATdmJVNuJZhpC+0Dae1jnAg7nRyLAOrjEI8yaGLLoA1s/KdrZakclwGIgNj+/as4Vscbd1+VH59cpzryoHpOIjQrESTsCqCSSHh9H4j10wjDAeFxDY3lAZOZu+SlWOsCshv+4xRiJMmWY+WCgJ2UuAXnj7N6QPKwXwnPV1UmdkXGaGWQ==",\n  "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-b95095beb82e8q6a046b3aafc7f4149a.pem",\n  "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:540420258117:custom-resource-maybe-4-SNSTopic-11NVYUIXWZTXZ:dc93952d-b252-4da3-a726-7df99631df02"\n}',
                    'MD5OfBody': '46e9054484367800fbd6bb8e13aaea36',
                    'MessageId': '6eef8c02-9874-41f8-8883-9788b911b773',
                    'ReceiptHandle': 'AQEBCLcjvnWL65ILiE9/L6WzthEatj3punqXWcxK/VGSfOhkjbfaMoy6GHtxPr/giOjO2gIW7buTv9Mkhk7/tpgbgJEm338nzoLOxqiW4s3fzoQWrjDu0HHpcD1KrMJBeVstxnLglEOOny2KRozfsLjbeH5HoXuo+8mrb0nwVUglIK2vBkAPHLOGu64/BPOR6dt2qgYK4hzytgXQprcLlS5rYrrpYkqBKjWt9PCuwSG244LuN3brNyRIgxPR9SQ/ja9CWocx7sS3Ri6tAVU8zP4OxjRmfdMj/EEdL3Wm5m4v7+hnGDnj0LSV/3UX6C1/ozIOtHY6bqN6HQ6nM48Dk6UTEm78ApFuYmOFnh5xfcAEJHHN9meqnMsYMe0l8hTEBRHDYII/W4K5APbUNNsuoU/R3uYgqWlNMFWDvxSORKPwy/2O0Kk51+ZE/fyGEaVncoof'
                }
            ],
            'ResponseMetadata': {
                'HTTPStatusCode': 200, 'HTTPHeaders': {
                    'connection': 'keep-alive', 'server': 'Server',
                    'content-length': '3342',
                    'content-type': 'text/xml',
                    'date': 'Thu, 08 Jun 2017 15:20:07 GMT',
                    'x-amzn-requestid': '116092e7-fee7-5580-b276-c3549380b837'
                },
                'RequestId': '116092e7-fee7-5580-b276-c3549380b837', 'RetryAttempts': 0
            }
        }
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def accept_eulas(my_settings: settings.Settings):
    out, err, exit_code = accept_ert_eula(my_settings)
    if exit_code != 0:
        return out, err, exit_code
    return accept_stemcell_eula(my_settings)
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def accept_stemcell_eula(my_settings: settings.Settings):
    response, result = util.exponential_backoff(
        functools.partial(post_eula, my_settings, "stemcells", my_settings.stemcell_release_id),
        check_eula_succeeded
    )
    if result == EULAResult.SUCCESS:
        return "Success", "", 0
    else:
        return "Failed to accept stemcell EULA; status code from Pivotal Network {}".format(response.status_code), "", 1
项目:aws-pcf-quickstart    作者:cf-platform-eng    | 项目源码 | 文件源码
def config_opsman_auth(my_settings: settings.Settings):
    cmd = "om -k --target {url} configure-authentication --username '{user}' --password '{password}' --decryption-passphrase '{password}'".format(
        url=my_settings.opsman_url,
        user=my_settings.opsman_user,
        password=my_settings.pcf_opsmanageradminpassword
    )
    return util.exponential_backoff_cmd(cmd)