Sends notification through AWS SES.

    Does not handle access keys.  Use either
      1/ configuration file
      2/ EC2 instance profile

    See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
559531
def send_email_ses(sender, subject, message, recipients, image_png):
    
    from boto3 import client as boto3_client

    client = boto3_client('ses')

    msg_root = generate_email(sender, subject, message, recipients, image_png)
    response = client.send_raw_email(Source=sender,
                                     Destinations=recipients,
                                     RawMessage={'Data': msg_root.as_string()})

    logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n"
                 "HTTPSStatusCode: {}").format(response['MessageId'],
                                               response['ResponseMetadata']['RequestId'],
                                               response['ResponseMetadata']['HTTPStatusCode']))
217925
def send_email_notification(self, notification_id=None, include_traceback=False, verbosity=1):
        
        # Load email notification settings if available
        if notification_id is not None:
            try:
                email_settings = settings.EMAIL_NOTIFICATIONS.get(notification_id, {})
            except AttributeError:
                email_settings = {}
        else:
            email_settings = {}

        # Exit if no traceback found and not in 'notify always' mode
        if not include_traceback and not email_settings.get('notification_level', 0):
            print(self.style.ERROR("Exiting, not in 'notify always' mode."))
            return

        # Set email fields.
        subject = email_settings.get('subject', "Django extensions email notification.")

        command_name = self.__module__.split('.')[-1]

        body = email_settings.get(
            'body',
            "Reporting execution of command: '%s'" % command_name
        )

        # Include traceback
        if include_traceback and not email_settings.get('no_traceback', False):
            try:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                trb = ''.join(traceback.format_tb(exc_traceback))
                body += "\n\nTraceback:\n\n%s\n" % trb
            finally:
                del exc_traceback

        # Set from address
        from_email = email_settings.get('from_email', settings.DEFAULT_FROM_EMAIL)

        # Calculate recipients
        recipients = list(email_settings.get('recipients', []))

        if not email_settings.get('no_admins', False):
            recipients.extend(settings.ADMINS)

        if not recipients:
            if verbosity > 0:
                print(self.style.ERROR("No email recipients available."))
            return

        # Send email...
        send_mail(subject, body, from_email, recipients,
                  fail_silently=email_settings.get('fail_silently', True))
600189
def run(self, check_interval=300):
        
        while True:
            # Read configuration from the config file if present, else fall
            # back to command line options
            if args.config:
                config = config_file_parser.get_configuration(args.config)
                access_key_id = config['access-key-id']
                secret_access_key = config['secret-access-key']
                region = config['region']
            else:
                access_key_id = args.access_key_id
                secret_access_key = args.secret_access_key
                region = args.region

            # Connect to AWS
            connection = connection_manager.connect_to_ec2(
                region, access_key_id, secret_access_key)

            snapshot_manager.run(connection)

            logger.info('Sleeping {} seconds until next check'.format(
                check_interval))
            time.sleep(check_interval)
1055972
def send_notification(self, method, params):
        
        msg = self._encoder.create_notification(method, params)
        self._send_message(msg)
275178
def enable_notifications(self):
        
        # todo: #783 create a dedicated brok for global parameters
        if not self.my_conf.enable_notifications:
            self.my_conf.modified_attributes |= \
                DICT_MODATTR["MODATTR_NOTIFICATIONS_ENABLED"].value
            self.my_conf.enable_notifications = True
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()
47330
def get_connection(service, module=None, region=None, key=None, keyid=None,
                   profile=None):
    '''
    
    '''

    module = module or service

    cxkey, region, key, keyid = _get_profile(service, region, key,
                                             keyid, profile)
    cxkey = cxkey + ':conn3'

    if cxkey in __context__:
        return __context__[cxkey]

    try:
        session = boto3.session.Session(aws_access_key_id=keyid,
                          aws_secret_access_key=key,
                          region_name=region)
        if session is None:
            raise SaltInvocationError('Region "{0}" is not '
                                      'valid.'.format(region))
        conn = session.client(module)
        if conn is None:
            raise SaltInvocationError('Region "{0}" is not '
                                      'valid.'.format(region))
    except boto.exception.NoAuthHandlerFound:
        raise SaltInvocationError('No authentication credentials found when '
                                  'attempting to make boto {0} connection to '
                                  'region "{1}".'.format(service, region))
    __context__[cxkey] = conn
    return conn
135155
def set_bucket_notification(self, bucket_name, notifications):
        
        is_valid_bucket_name(bucket_name)
        is_valid_bucket_notification_config(notifications)

        content = xml_marshal_bucket_notifications(notifications)
        headers = {
            'Content-Length': str(len(content)),
            'Content-Md5': get_md5_base64digest(content)
        }
        content_sha256_hex = get_sha256_hexdigest(content)
        self._url_open(
            'PUT',
            bucket_name=bucket_name,
            query={"notification": ""},
            headers=headers,
            body=content,
            content_sha256=content_sha256_hex
        )
1189731
def _send_notification(self, handle, payload):
        

        self.bable.notify(
            connection_handle=self._connection_handle,
            attribute_handle=handle,
            value=payload
        )
317995
def get_ec2_client(region_name=None, aws_access_key_id=None, aws_secret_access_key=None):
    
    log = logging.getLogger(mod_logger + '.get_ec2_client')
    # Connect to EC2 API
    try:
        client = boto3.client('ec2', region_name=region_name, aws_access_key_id=aws_access_key_id,
                              aws_secret_access_key=aws_secret_access_key)
    except ClientError:
        _, ex, trace = sys.exc_info()
        msg = 'There was a problem connecting to EC2, please check AWS CLI and boto configuration, ensure ' \
              'credentials and region are set appropriately.\n{e}'.format(e=str(ex))
        log.error(msg)
        raise AWSAPIError, msg, trace
    else:
        log.debug('Successfully created an EC2 client')
        return client
852206
def _notify(p, **data):
    """"""
    message = data.get("message")
    if not message and not sys.stdin.isatty():
        message = click.get_text_stream("stdin").read()
    data["message"] = message

    data = clean_data(data)

    ctx = click.get_current_context()
    if ctx.obj.get("env_prefix"):
        data["env_prefix"] = ctx.obj["env_prefix"]

    rsp = p.notify(**data)
    rsp.raise_on_errors()
    click.secho(f"Succesfully sent a notification to {p.name}!", fg="green")
1169486
def send_notification(self, method, args, kwargs):
        """"""
        msg = dumps([1, method, args, kwargs])
        self.send(msg)
320037
def handle(self, *args, **options):
        
        # AWS SES connection, which can be re-used for each query needed.
        conn = get_boto_ses_connection()
        self._print_quota(conn)
        self._print_daily_stats(conn)
578710
def send_notification(self, title, message, typ=1, url=None, sender=None):
        
        self.user.send_notification(title=title, message=message, typ=typ, url=url,
                                    sender=sender)
76719
def print_ec2_info(region,
                   instance_id,
                   access_key_id,
                   secret_access_key,
                   username):
    
    data = get_ec2_info(instance_id=instance_id,
                        region=region,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        username=username)

    log_green("region: %s" % data['region'])
    log_green("Instance_type: %s" % data['instance_type'])
    log_green("Instance state: %s" % data['state'])
    log_green("Public dns: %s" % data['public_dns_name'])
    log_green("Ip address: %s" % data['ip_address'])
    log_green("volume: %s" % data['volume'])
    log_green("user: %s" % data['username'])
    log_green("ssh -i %s %s@%s" % (env.key_filename,
                                   username,
                                   data['ip_address']))
996530
def _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output):
    

    config = dict(config_file=config_file, profile=profile, solver=solver_def)
    if request_timeout is not None:
        config.update(request_timeout=request_timeout)
    if polling_timeout is not None:
        config.update(polling_timeout=polling_timeout)
    try:
        client = Client.from_config(**config)
    except Exception as e:
        raise CLIError("Invalid configuration: {}".format(e), code=1)
    if config_file:
        output("Using configuration file: {config_file}", config_file=config_file)
    if profile:
        output("Using profile: {profile}", profile=profile)
    output("Using endpoint: {endpoint}", endpoint=client.endpoint)

    t0 = timer()
    try:
        solver = client.get_solver()
    except SolverAuthenticationError:
        raise CLIError("Authentication error. Check credentials in your configuration file.", 2)
    except SolverNotFoundError:
        raise CLIError("Solver not available.", 6)
    except (InvalidAPIResponseError, UnsupportedSolverError):
        raise CLIError("Invalid or unexpected API response.", 3)
    except RequestTimeout:
        raise CLIError("API connection timed out.", 4)
    except requests.exceptions.SSLError as e:
        # we need to handle `ssl.SSLError` wrapped in several exceptions,
        # with differences between py2/3; greping the message is the easiest way
        if 'CERTIFICATE_VERIFY_FAILED' in str(e):
            raise CLIError(
                "Certificate verification failed. Please check that your API endpoint "
                "is correct. If you are connecting to a private or third-party D-Wave "
                "system that uses self-signed certificate(s), please see "
                "https://support.dwavesys.com/hc/en-us/community/posts/360018930954.", 5)
        raise CLIError("Unexpected SSL error while fetching solver: {!r}".format(e), 5)
    except Exception as e:
        raise CLIError("Unexpected error while fetching solver: {!r}".format(e), 5)

    t1 = timer()
    output("Using solver: {solver_id}", solver_id=solver.id)

    try:
        future = solver.sample_ising({0: 1}, {})
        timing = future.timing
    except RequestTimeout:
        raise CLIError("API connection timed out.", 8)
    except PollingTimeout:
        raise CLIError("Polling timeout exceeded.", 9)
    except Exception as e:
        raise CLIError("Sampling error: {!r}".format(e), 10)
    finally:
        output("Submitted problem ID: {problem_id}", problem_id=future.id)

    t2 = timer()

    output("\nWall clock time:")
    output(" * Solver definition fetch: {wallclock_solver_definition:.3f} ms", wallclock_solver_definition=(t1-t0)*1000.0)
    output(" * Problem submit and results fetch: {wallclock_sampling:.3f} ms", wallclock_sampling=(t2-t1)*1000.0)
    output(" * Total: {wallclock_total:.3f} ms", wallclock_total=(t2-t0)*1000.0)
    if timing.items():
        output("\nQPU timing:")
        for component, duration in timing.items():
            output(" * %(name)s = {%(name)s} us" % {"name": component}, **{component: duration})
    else:
        output("\nQPU timing data not available.")
486089
def send(to, message, **kwargs):
    

    available_kwargs_keys = [
        'parse_mode',
        'disable_web_page_preview',
        'disable_notification',
        'reply_to_message_id',
        'reply_markup'
    ]

    available_kwargs = {
        k: v for k, v in kwargs.iteritems() if k in available_kwargs_keys
    }

    bot = telepot.Bot(settings.TELEGRAM_BOT_TOKEN)
    return bot.sendMessage(to, message, **available_kwargs)
939081
def down_ec2(instance_id, region, access_key_id, secret_access_key):
    
    conn = connect_to_ec2(region, access_key_id, secret_access_key)
    # get the instance_id from the state file, and stop the instance
    instance = conn.stop_instances(instance_ids=instance_id)[0]
    while instance.state != "stopped":
        log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    log_green('Instance state: %s' % instance.state)