Beispiel #1
0
def load_article(link):
    print 'Loading...', link
    if 'getpocket' not in link:
        print 'External Link cannot be downloaded'
        return
    try:
        if not driver:
            login()
        driver.get(link)
        WebDriverWait(driver, 60).until(readystate_complete)
        prev_length = 0
        while True:
            driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(1)
            curr_length = len(driver.page_source)
            if prev_length == curr_length:
                break
            prev_length = curr_length
            print 'loading...'
        time.sleep(2)

        article = download_html(driver.page_source)
        print 'Downloaded at', article
        np = '%s%s' % (KINDLE_FOLDER, article)
        if os.path.exists(np):
            os.remove(np)
        os.rename(article, np)
        choice = raw_input('Would you like to send to kindle (y/N)').strip()
        if choice in ['y', 'Y']:
            mail(KINDLE_MAIL, '', article, np)
    except Exception, e:
        print '[*] Error: Something went wrong'
        print str(e)
Beispiel #2
0
 def remind(self):
     for lease in ResourceLease.objects.filter(expires <= datetime.date.today()):
         #TODO : set reminder count and adjust expires
         lease.reminder += 1;
         lease.expires = self.updateExpires(lease)
         lease.save()
         users = []
         for key in ResourceSubscribers.filter(resource_id == lease.resource.id):
             if key.subscriber.email not in users:
                users.append(key.subscriber.email)
         for user in users:
             mailer.mail(owner=user, resource=lease.resource)
         if lease.resource.callbackurl:
             import httplib2
             import urllib
             import base64
             import json
             try:
                url = lease.resource.callbackurl
                auth = lease.resource.callbackauth
                logger.info('url='+url)
                params = urllib.urlencode({'id':lease.resource.id, 'msg': 'lease expiration reminder',
                      'subscribers': users, 'count':lease.reminder, 'next':repr(lease.expires)})
                response, content = http.request(url, 'POST',
                    headers={"Content-Type": "application/json", 'Authorization' : 'Basic ' + auth})
                if response.status != 200:
                    logger.error('status='+str(response.status))
                logger.info(repr(content))
                msg = 'callback invoked'
                logger.info(msg)
             except:
                pass 
     pass
def takeFive():
	#counter, list of file names, date stamp
	#turn off green LED, turn on red LED
	#activate camera
	i = 0
	pics =[]
	date = time.strftime("%d-%m-%y")
	GPIO.output(GREEN, GPIO.LOW)
	GPIO.output(RED, GPIO.HIGH)
	camera = picamera.PiCamera()
	while i < 5:
		#when we reach the third picture, play an audio clip!
		#mine is a voice that says "What are you doing in here!?"
		#the idea is the perpetrator will turn around and look right at the camera
		if i == 3:
			os.system("aplay " +AUDIO +"WhatDoing.wav")
		#sleep 1 second, make a timestamp, snap a picture, add it to the list, increment counter
		time.sleep(1)
		timestamp = time.strftime("%X")
		camera.capture(PATH+date+"-"+timestamp+".jpg")
		pics.append(PATH+date+"-"+timestamp+".jpg")
		i+=1
	#mail our pictures then sleep five minutes (so this doesn't continually take pictures and bomb our inbox
	mailer.mail("from account", "password", "to account", "subject", "body text", pics)
	time.sleep(300)
	#switch LEDs back to green on / red off
	GPIO.output(RED, GPIO.LOW)
	GPIO.output(GREEN, GPIO.HIGH)
Beispiel #4
0
        def sendmail():
            if config['use_gmail'] == 'yes':
                password = config['feedback_password']
            else:
                password = None

            mail(config['smtp_server'], config['smtp_port'],
                config['feedback_email'], password,
                '*****@*****.**', 'Uploader exception', stack_trace)
Beispiel #5
0
def menu():
    articles = load_articles()
    print 'Select what you wanna do'
    print '1. Reload Articles'
    print '1f. Force Reload Articles'
    print '2. List Articles'
    print '3. Download Article'
    print '4. Send Article To Kindle'
    print '5. Exit'
    choice = raw_input().strip()
    if choice is '1':
        articles = reload_articles()
        list_articles(articles)
    elif choice is '1f':
        articles = reload_articles(force=True)
        list_articles(articles)
    elif choice is '2':
        list_articles(articles)
    elif choice is '3':
        art = raw_input('Select article number to download:').strip()
        try:
            art = int(art)
            if art not in id_stuff:
                print 'Invalid Article Selected'
                return
            article_id = id_stuff[art]
            print '[*] Downloading'
            print articles[article_id]['title']
            load_article(articles[article_id]['link'])
        except:
            print 'Invalid article choice'
    elif choice is '4':
        files = os.listdir(KINDLE_FOLDER)
        file_dict = {}
        for i, f in enumerate(files):
            file_dict[str(i)] = f
            print '[%d] %s' % (i, f)
        ch = raw_input('select the file to send:')
        ch = str(ch.strip())
        if ch not in file_dict:
            print 'Invalid choice'
            return
        file_to_send = file_dict[ch]
        mail(KINDLE_MAIL, '', file_to_send, '%s%s' % (KINDLE_FOLDER,
                                                      file_to_send))
    elif choice is '5':
        print 'Exiting'
        if driver:
            try:
                driver.close()
            except:
                pass
        exit()
    else:
        print 'Invalid choice'
Beispiel #6
0
def alert(subject, message):
	configp = SafeConfigParser()
	configp.read(config_paths)

	smtp_addr = configp.defaults()['smtp_server']
	smtp_port = configp.defaults()['smtp_port']
	alert_email = configp.defaults()['alert_email']
	alert_password = configp.defaults()['alert_password']

	mailer.mail(smtp_addr, smtp_port, alert_email, alert_password, 
				'*****@*****.**', subject, message)
Beispiel #7
0
 def sendmail():
     cc = user_email
     if config['use_gmail'] == 'yes' or not user_email:
         frm = config['feedback_email']
         pword = config['feedback_password']
     else:
         frm = user_email
         pword = None
     mail(config['smtp_server'], config['smtp_port'],
         frm, pword,
         '*****@*****.**', subject, message, cc=cc)
Beispiel #8
0
def notify():
    phone_email = csh_email = username = None

    # checks for valid input in the GET request
    uid_number = request.args.get("uid_number", "")
    if uid_number == "":
        username = request.args.get("username", "")
        if username == "":
            return "no uid number or username given"
    notification = request.args.get("notification", "")
    if notification == "":
        return "no notification"
    api_key = request.args.get("apiKey", "")
    if api_key == "":
        return "no api key"

    service = Service.query.filter_by(api_key=api_key).first()
    if not service:
        return "invalid API key"
    user = User.query.filter_by(uid_number=uid_number).first()
    if user == None:  # make a user entry for the new user
        if check_uid_number(uid_number):
            user = User(uid_number)
            db.session.add(user)
        else:
            return "invalid uid number"
    subscription = Subscription.query.filter(
        db.and_(Subscription.uid_number == user.uid_number,
                Subscription.service_id == service.id)).first()
    if not subscription:
        return "user not subscribed to service"

    # sends the text message
    if subscription.state == 1 or subscription.state == 2:
        carrier = Carrier.query.filter_by(id=user.carrier).first()
        print user, carrier
        phone_email = str(user.phone_number) + "@" + carrier.domain
        mail(phone_email, "CSH Notification - " + service.service_name,
             notification)
        db.session.add(Log(service.id, user.uid_number, phone_email))
    # sends the email to the csh account
    if subscription.state == 0 or subscription.state == 2:
        if username != None:
            csh_email = username + "@csh.rit.edu"
        else:
            csh_email = get_username(user.uid_number) + "@csh.rit.edu"
        mail(csh_email, "CSH Notification - " + service.service_name,
             notification)
        db.session.add(Log(service.id, user.uid_number, csh_email))
    db.session.commit()
    return "good"
Beispiel #9
0
def notify():
    phone_email = csh_email = username = None

    # checks for valid input in the GET request
    uid_number = request.args.get("uid_number", "")
    if uid_number == "":
        username = request.args.get("username", "")
        if username == "":
            return "no uid number or username given"
    notification = request.args.get("notification", "")
    if notification == "":
        return "no notification"
    api_key = request.args.get("apiKey", "")
    if api_key == "":
        return "no api key"

    service = Service.query.filter_by(api_key = api_key).first()
    if not service:
        return "invalid API key"
    user = User.query.filter_by(uid_number = uid_number).first()
    if user == None: # make a user entry for the new user
        if check_uid_number(uid_number):
            user = User(uid_number)
            db.session.add(user)
        else:
            return "invalid uid number"
    subscription = Subscription.query.filter(
            db.and_(Subscription.uid_number == user.uid_number,
                Subscription.service_id == service.id)).first()
    if not subscription:
        return "user not subscribed to service"

    # sends the text message
    if subscription.state == 1 or subscription.state == 2:
        carrier = Carrier.query.filter_by(id = user.carrier).first()
        print user, carrier
        phone_email = str(user.phone_number) + "@" + carrier.domain
        mail(phone_email, "CSH Notification - " + service.service_name, notification)
        db.session.add(Log(service.id, user.uid_number, phone_email))
    # sends the email to the csh account
    if subscription.state == 0 or subscription.state == 2:
        if username != None:
            csh_email = username + "@csh.rit.edu"
        else:
            csh_email = get_username(user.uid_number) + "@csh.rit.edu"
        mail(csh_email, "CSH Notification - " + service.service_name, notification)
        db.session.add(Log(service.id, user.uid_number, csh_email))
    db.session.commit()
    return "good"
Beispiel #10
0
def main():

    # Obtain weather data
    data = acquire.acquire()

    # Organize data
    output = parse.parse(data)
    print(output)

    # Obtain mailing list
    csv_file = 'emails.txt'
    mailing_list = read_file.read_file(csv_file)

    # Sending the emails
    mailer.mail(mailing_list, output)
Beispiel #11
0
def alert_for_payment():
    invoices = Invoice.objects.all()
    current_date = datetime.datetime.now().date()

    # Send email alert
    """
    Change mail 
    """
    recipient_list = ['mail']
    subject = "Reminder for Collection of Payment from Hotels"
    text = "Hello,<br><br>Kindly collect the payment from below hotels on the respective dates.<br><br>"
    text += '<!DOCTYPE html><html><head><title>HTML Tables</title></head><body><table border="1">' \
            '<tr><th>Hotel Name</th><th>Amount</th>' \
            '<th>Pay Date</th></tr>'

    html = ""
    for invoice in invoices:
        if invoice.pay_date:
            date_object = datetime.datetime.strptime(str(
                invoice.pay_date), "%d-%m-%Y").strftime("%Y-%m-%d")
            alert_date = datetime.datetime.strptime(str(date_object),
                                                    "%Y-%m-%d")
            current_date_formatted = datetime.datetime.strptime(
                str(current_date), "%Y-%m-%d")

            time_diff = (alert_date - current_date_formatted).days
            if time_diff <= 2:
                invoice_name = str(invoice.invoice_name).split("_")
                hotel_name = invoice_name[0]

                amount = 0
                for data in invoice.invoice_data:
                    amount += (float(data["rate_per_unit"]) *
                               float(data["quantity"]))

                html += '<tr><th>{}</th><th>{}</th><th>{}</th></tr>'.format(
                    hotel_name, amount, invoice.pay_date)

    if html:
        text += html
        text += "</table></body></html><br><br>Regards,<br>Technology Team"
        mail(recipient_list, subject, text, "")
        print "Mail sent"
    else:
        print "No due payment coming soon."
Beispiel #12
0
def DirectoryTraversal(path):
    a_dict = {}
    #print("Contents of the Directory are: ")
    for folder, subfolder, filename in os.walk(path):
        for _ in subfolder:
            ...
        for file in filename:
            actualpath = os.path.join(folder, file)
            hashval = checksum.calculateCheckSum(actualpath)
            if hashval in a_dict:
                a_dict[hashval].append(actualpath)
            else:
                a_dict[hashval] = [file]
    current_date_time = datetime.now().strftime("%d_%m_%Y-%I_%M") + ".txt"
    logger.Writer(a_dict, current_date_time)
    ans = DisplayDuplicate(a_dict)
    mailer.mail(current_date_time, ans)
    twiliooo.tw(current_date_time, ans)
Beispiel #13
0
    def encrypt_file(self):
        if self.img_path:
            with open(self.img_path, "rb") as image_file:

                encoded_string = base64.b64encode(image_file.read())

                self.init_curve()

                encryptedMsg = SafeEC.encrypt_ECC(self.curve, encoded_string,
                                                  self.pubKey)

                enc_file = open('encrypted.dat', 'wb')
                pickle.dump(encryptedMsg, enc_file)
                self.show_message("Encrypted")

                file_name = os.path.basename(self.img_path)
                s_mail = self.ui.lineEditUsername.text()
                s_pwd = self.ui.lineEditPassword.text()
                r_mail = self.ui.lineEditMail.text()
                mail(r_mail, file_name, s_mail, s_pwd)

        else:
            self.show_error("No file selected!")
Beispiel #14
0
    def build(self, deps=None, nesting_count=0):

        build_error = False

        nesting_count += 1

        log.trace('_bset: %s: make' % (self.bset))
        log.notice('Build Set: %s' % (self.bset))

        if self.opts.get_arg('--mail'):
            mail_report_subject = '%s %s' % (self.bset,
                                             self.macros.expand('%{_host}'))

        current_path = os.environ['PATH']

        start = datetime.datetime.now()

        mail_report = False
        have_errors = False

        try:
            configs = self.load()

            log.trace('_bset: %s: configs: %s' %
                      (self.bset, ','.join(configs)))

            builds = []
            for s in range(0, len(configs)):
                b = None
                try:
                    #
                    # Each section of the build set gets a separate set of
                    # macros so we do not contaminate one configuration with
                    # another.
                    #
                    opts = copy.copy(self.opts)
                    macros = copy.copy(self.macros)
                    if configs[s].endswith('.bset'):
                        log.trace('_bset: == %2d %s' %
                                  (nesting_count + 1, '=' * 75))
                        bs = buildset(configs[s], self.configs, opts, macros)
                        bs.build(deps, nesting_count)
                        del bs
                    elif configs[s].endswith('.cfg'):
                        mail_report = self.opts.get_arg('--mail')
                        log.trace('_bset: -- %2d %s' %
                                  (nesting_count + 1, '-' * 75))
                        try:
                            b = build.build(
                                configs[s],
                                self.opts.get_arg('--pkg-tar-files'), opts,
                                macros)
                        except:
                            build_error = True
                            raise
                        if b.macros.get('%{_disable_reporting}'):
                            mail_report = False
                        if deps is None:
                            self.build_package(configs[s], b)
                            self.report(configs[s], b, copy.copy(self.opts),
                                        copy.copy(self.macros))
                            # Always product an XML report.
                            self.report(configs[s],
                                        b,
                                        copy.copy(self.opts),
                                        copy.copy(self.macros),
                                        format='xml')
                            if s == len(configs) - 1 and not have_errors:
                                self.bset_tar(b)
                        else:
                            deps += b.config.includes()
                        builds += [b]
                        #
                        # Dump post build macros.
                        #
                        log.trace('_bset: macros post-build')
                        log.trace(str(macros))
                    else:
                        raise error.general('invalid config type: %s' %
                                            (configs[s]))
                except error.general as gerr:
                    have_errors = True
                    if b is not None:
                        if self.build_failure is None:
                            self.build_failure = b.name()
                        self.write_mail_header('')
                        self.write_mail_header('= ' * 40)
                        self.write_mail_header('Build FAILED: %s' % (b.name()))
                        self.write_mail_header('- ' * 40)
                        self.write_mail_header(str(log.default))
                        self.write_mail_header('- ' * 40)
                        if self.opts.keep_going():
                            log.notice(str(gerr))
                            if self.opts.always_clean():
                                builds += [b]
                        else:
                            raise
                    else:
                        raise
            #
            # Installing ...
            #
            log.trace('_bset: installing: deps:%r no-install:%r' % \
                      (deps is None, self.opts.no_install()))
            if deps is None \
               and not self.opts.no_install() \
               and not have_errors:
                for b in builds:
                    log.trace('_bset: installing: %r' % b.installable())
                    if b.installable():
                        self.install(b.name(), b.config.expand('%{buildroot}'),
                                     b.config.expand('%{_prefix}'))

            if deps is None and \
                    (not self.opts.no_clean() or self.opts.always_clean()):
                for b in builds:
                    if not b.disabled():
                        log.notice('cleaning: %s' % (b.name()))
                        b.cleanup()
            for b in builds:
                del b
        except error.general as gerr:
            if not build_error:
                log.stderr(str(gerr))
            raise
        except KeyboardInterrupt:
            mail_report = False
            raise
        except:
            self.build_failure = 'RSB general failure'
            raise
        finally:
            end = datetime.datetime.now()
            os.environ['PATH'] = current_path
            build_time = str(end - start)
            if mail_report:
                to_addr = self.opts.get_arg('--mail-to')
                if to_addr is not None:
                    to_addr = to_addr[1]
                else:
                    to_addr = self.macros.expand('%{_mail_tools_to}')
                log.notice('Mailing report: %s' % (to_addr))
                self.write_mail_header('Build Time %s' % (build_time), True)
                self.write_mail_header('')
                m = mailer.mail(self.opts)
                if self.build_failure is not None:
                    mail_report_subject = 'Build: FAILED %s (%s)' %\
                        (mail_report_subject, self.build_failure)
                    pass_fail = 'FAILED'
                else:
                    mail_report_subject = 'Build: PASSED %s' % (
                        mail_report_subject)
                if not self.opts.dry_run():
                    m.send(to_addr, mail_report_subject,
                           self.mail_header + self.mail_report)
            log.notice('Build Set: Time %s' % (build_time))
            self.build_failure = 'RSB general failure'
            raise
        finally:
            end = datetime.datetime.now()
            os.environ['PATH'] = current_path
            build_time = str(end - start)
            if mail_report:
                to_addr = self.opts.get_arg('--mail-to')
                if to_addr is not None:
                    to_addr = to_addr[1]
                else:
                    to_addr = self.macros.expand('%{_mail_tools_to}')
                log.notice('Mailing report: %s' % (to_addr))
                self.write_mail_header('Build Time %s' % (build_time), True)
                self.write_mail_header('')
                m = mailer.mail(self.opts)
                if self.build_failure is not None:
                    mail_report_subject = 'Build: FAILED %s (%s)' %\
                        (mail_report_subject, self.build_failure)
                    pass_fail = 'FAILED'
                else:
                    mail_report_subject = 'Build: PASSED %s' % (
                        mail_report_subject)
                if not self.opts.dry_run():
                    m.send(to_addr, mail_report_subject,
                           self.mail_header + self.mail_report)
            log.notice('Build Set: Time %s' % (build_time))


def list_bset_cfg_files(opts, configs):
    if opts.get_arg('--list-configs') or opts.get_arg('--list-bsets'):
            master_host = master["host"]
            connection = master["connection"]
            logging.info("Cluster [%s] has a valid master [%s] in the config",
                         cluster, master_host)
        except Exception as e:
            logging.error(
                "Cluster [%s] does not have a valid master in the config",
                cluster)
            logging.info("End processing Cluster [%s]", cluster)
            result.append({
                "title":
                "No valid elasticsearch instance in the configuration",
                "severity": "FATAL",
                "body": "<br />".join(config["eshosts"].split(","))
            })
            mail(cluster, result)
            continue

        cluster_health = health(connection, config)
        result.append(cluster_health)

        # These metrics are not alarming if the cluster health is good
        result.append(indices(connection, config, cluster_health["severity"]))
        result.append(shards(connection, config, cluster_health["severity"]))

        # These metrics are alarming irrespective of the cluster health
        result.append(allocations(connection, config))
        result.append(nodes(cluster, connection, config))

        mail(cluster, result)
Beispiel #17
0
def run():
    import sys
    ec = 0
    setbuilder_error = False
    mail = None
    try:
        optargs = {
            '--list-configs': 'List available configurations',
            '--list-bsets': 'List available build sets',
            '--list-configs': 'List available configuration files.',
            '--list-deps': 'List the dependent files.',
            '--bset-tar-file': 'Create a build set tar file',
            '--pkg-tar-files': 'Create package tar files',
            '--no-report': 'Do not create a package report.',
            '--report-format': 'The report format (text, html, asciidoc).'
        }
        mailer.append_options(optargs)
        opts = options.load(sys.argv, optargs)
        if opts.get_arg('--mail'):
            mail = {'mail': mailer.mail(opts), 'output': log_capture()}
            to_addr = opts.get_arg('--mail-to')
            if to_addr is not None:
                mail['to'] = to_addr[1]
            else:
                mail['to'] = opts.defaults.expand('%{_mail_tools_to}')
            mail['from'] = mail['mail'].from_address()
        log.notice('RTEMS Source Builder - Set Builder, %s' % (version.str()))
        opts.log_info()
        if not check.host_setup(opts):
            raise error.general(
                'host build environment is not set up correctly')
        if mail:
            mail['header'] = os.linesep.join(mail['output'].get()) + os.linesep
            mail['header'] += os.linesep
            mail['header'] += 'Host: ' + reports.platform(
                'compact') + os.linesep
            indent = '       '
            for l in textwrap.wrap(reports.platform('extended'),
                                   width=80 - len(indent)):
                mail['header'] += indent + l + os.linesep
        configs = build.get_configs(opts)
        if opts.get_arg('--list-deps'):
            deps = []
        else:
            deps = None
        if not list_bset_cfg_files(opts, configs):
            prefix = opts.defaults.expand('%{_prefix}')
            if opts.canadian_cross():
                opts.disable_install()

            if not opts.dry_run() and \
               not opts.canadian_cross() and \
               not opts.no_install() and \
               not path.ispathwritable(prefix):
                raise error.general('prefix is not writable: %s' %
                                    (path.host(prefix)))

            for bset in opts.params():
                setbuilder_error = True
                b = buildset(bset, configs, opts)
                b.build(deps, mail=mail)
                b = None
                setbuilder_error = False

        if deps is not None:
            c = 0
            for d in sorted(set(deps)):
                c += 1
                print('dep[%d]: %s' % (c, d))
    except error.general as gerr:
        if not setbuilder_error:
            log.stderr(str(gerr))
        log.stderr('Build FAILED')
        ec = 1
    except error.internal as ierr:
        if not setbuilder_error:
            log.stderr(str(ierr))
        log.stderr('Internal Build FAILED')
        ec = 1
    except error.exit as eerr:
        pass
    except KeyboardInterrupt:
        log.notice('abort: user terminated')
        ec = 1
    except:
        raise
        log.notice('abort: unknown error')
        ec = 1
    sys.exit(ec)
            self.build_failure = 'RSB general failure'
            raise
        finally:
            end = datetime.datetime.now()
            os.environ['PATH'] = current_path
            build_time = str(end - start)
            if mail_report:
                to_addr = self.opts.get_arg('--mail-to')
                if to_addr is not None:
                    to_addr = to_addr[1]
                else:
                    to_addr = self.macros.expand('%{_mail_tools_to}')
                log.notice('Mailing report: %s' % (to_addr))
                self.write_mail_header('Build Time %s' % (build_time), True)
                self.write_mail_header('')
                m = mailer.mail(self.opts)
                if self.build_failure is not None:
                    mail_report_subject = 'Build: FAILED %s (%s)' %\
                        (mail_report_subject, self.build_failure)
                    pass_fail = 'FAILED'
                else:
                    mail_report_subject = 'Build: PASSED %s' % (mail_report_subject)
                if not self.opts.dry_run():
                    m.send(to_addr, mail_report_subject,
                           self.mail_header + self.mail_report)
            log.notice('Build Set: Time %s' % (build_time))

def list_bset_cfg_files(opts, configs):
    if opts.get_arg('--list-configs') or opts.get_arg('--list-bsets'):
        if opts.get_arg('--list-configs'):
            ext = '.cfg'
    def build(self, deps = None, nesting_count = 0):

        build_error = False

        nesting_count += 1

        log.trace('_bset: %s: make' % (self.bset))
        log.notice('Build Set: %s' % (self.bset))

        if self.opts.get_arg('--mail'):
            mail_report_subject = '%s %s' % (self.bset, self.macros.expand('%{_host}'))

        current_path = os.environ['PATH']

        start = datetime.datetime.now()

        mail_report = False
        have_errors = False

        try:
            configs = self.load()

            log.trace('_bset: %s: configs: %s'  % (self.bset, ','.join(configs)))

            builds = []
            for s in range(0, len(configs)):
                b = None
                try:
                    #
                    # Each section of the build set gets a separate set of
                    # macros so we do not contaminate one configuration with
                    # another.
                    #
                    opts = copy.copy(self.opts)
                    macros = copy.copy(self.macros)
                    if configs[s].endswith('.bset'):
                        log.trace('_bset: == %2d %s' % (nesting_count + 1, '=' * 75))
                        bs = buildset(configs[s], self.configs, opts, macros)
                        bs.build(deps, nesting_count)
                        del bs
                    elif configs[s].endswith('.cfg'):
                        mail_report = self.opts.get_arg('--mail')
                        log.trace('_bset: -- %2d %s' % (nesting_count + 1, '-' * 75))
                        try:
                            b = build.build(configs[s], self.opts.get_arg('--pkg-tar-files'),
                                            opts, macros)
                        except:
                            build_error = True
                            raise
                        if b.macros.get('%{_disable_reporting}'):
                            mail_report = False
                        if deps is None:
                            self.build_package(configs[s], b)
                            self.report(configs[s], b,
                                        copy.copy(self.opts),
                                        copy.copy(self.macros))
                            # Always product an XML report.
                            self.report(configs[s], b,
                                        copy.copy(self.opts),
                                        copy.copy(self.macros),
                                        format = 'xml')
                            if s == len(configs) - 1 and not have_errors:
                                self.bset_tar(b)
                        else:
                            deps += b.config.includes()
                        builds += [b]
                        #
                        # Dump post build macros.
                        #
                        log.trace('_bset: macros post-build')
                        log.trace(str(macros))
                    else:
                        raise error.general('invalid config type: %s' % (configs[s]))
                except error.general as gerr:
                    have_errors = True
                    if b is not None:
                        if self.build_failure is None:
                            self.build_failure = b.name()
                        self.write_mail_header('')
                        self.write_mail_header('= ' * 40)
                        self.write_mail_header('Build FAILED: %s' % (b.name()))
                        self.write_mail_header('- ' * 40)
                        self.write_mail_header(str(log.default))
                        self.write_mail_header('- ' * 40)
                        if self.opts.keep_going():
                            log.notice(str(gerr))
                            if self.opts.always_clean():
                                builds += [b]
                        else:
                            raise
                    else:
                        raise
            #
            # Installing ...
            #
            log.trace('_bset: installing: deps:%r no-install:%r' % \
                      (deps is None, self.opts.no_install()))
            if deps is None \
               and not self.opts.no_install() \
               and not have_errors:
                for b in builds:
                    log.trace('_bset: installing: %r' % b.installable())
                    if b.installable():
                        self.install(b.name(),
                                     b.config.expand('%{buildroot}'),
                                     b.config.expand('%{_prefix}'))

            if deps is None and \
                    (not self.opts.no_clean() or self.opts.always_clean()):
                for b in builds:
                    if not b.disabled():
                        log.notice('cleaning: %s' % (b.name()))
                        b.cleanup()
            for b in builds:
                del b
        except error.general as gerr:
            if not build_error:
                log.stderr(str(gerr))
            raise
        except KeyboardInterrupt:
            mail_report = False
            raise
        except:
            self.build_failure = 'RSB general failure'
            raise
        finally:
            end = datetime.datetime.now()
            os.environ['PATH'] = current_path
            build_time = str(end - start)
            if mail_report:
                to_addr = self.opts.get_arg('--mail-to')
                if to_addr is not None:
                    to_addr = to_addr[1]
                else:
                    to_addr = self.macros.expand('%{_mail_tools_to}')
                log.notice('Mailing report: %s' % (to_addr))
                self.write_mail_header('Build Time %s' % (build_time), True)
                self.write_mail_header('')
                m = mailer.mail(self.opts)
                if self.build_failure is not None:
                    mail_report_subject = 'Build: FAILED %s (%s)' %\
                        (mail_report_subject, self.build_failure)
                    pass_fail = 'FAILED'
                else:
                    mail_report_subject = 'Build: PASSED %s' % (mail_report_subject)
                if not self.opts.dry_run():
                    m.send(to_addr, mail_report_subject,
                           self.mail_header + self.mail_report)
            log.notice('Build Set: Time %s' % (build_time))
Beispiel #20
0
def handle_success(req):
    message = "An item on the ITR order sheet has been changed or added:\n\n"
    message += "Item Name: %s\n Vendor: %s\n Total Price: %s\n Requestor:%s\n Approver:%s" % (req[0],req[3],req[6],req[9],req[10])
    message += '\n\nRegards,\nThe ITR order list robot'
    mailer.mail(cf.success_rcpts,'ITR Order list Change/Request',message)
def run():
    import sys
    ec = 0
    setbuilder_error = False
    mail = None
    try:
        optargs = { '--list-configs':  'List available configurations',
                    '--list-bsets':    'List available build sets',
                    '--list-configs':  'List available configuration files.',
                    '--list-deps':     'List the dependent files.',
                    '--bset-tar-file': 'Create a build set tar file',
                    '--pkg-tar-files': 'Create package tar files',
                    '--no-report':     'Do not create a package report.',
                    '--report-format': 'The report format (text, html, asciidoc).' }
        mailer.append_options(optargs)
        opts = options.load(sys.argv, optargs)
        if opts.get_arg('--mail'):
            mail = { 'mail'  : mailer.mail(opts),
                     'output': log_capture() }
            to_addr = opts.get_arg('--mail-to')
            if to_addr is not None:
                mail['to'] = to_addr[1]
            else:
                mail['to'] = opts.defaults.expand('%{_mail_tools_to}')
            mail['from'] = mail['mail'].from_address()
        log.notice('RTEMS Source Builder - Set Builder, %s' % (version.str()))
        opts.log_info()
        if not check.host_setup(opts):
            raise error.general('host build environment is not set up correctly')
        if mail:
            mail['header'] = os.linesep.join(mail['output'].get()) + os.linesep
            mail['header'] += os.linesep
            mail['header'] += 'Host: '  + reports.platform('compact') + os.linesep
            indent = '       '
            for l in textwrap.wrap(reports.platform('extended'),
                                   width = 80 - len(indent)):
                mail['header'] += indent + l + os.linesep
        configs = build.get_configs(opts)
        if opts.get_arg('--list-deps'):
            deps = []
        else:
            deps = None
        if not list_bset_cfg_files(opts, configs):
            prefix = opts.defaults.expand('%{_prefix}')
            if opts.canadian_cross():
                opts.disable_install()

            if not opts.dry_run() and \
               not opts.canadian_cross() and \
               not opts.no_install() and \
               not path.ispathwritable(prefix):
                raise error.general('prefix is not writable: %s' % (path.host(prefix)))

            for bset in opts.params():
                setbuilder_error = True
                b = buildset(bset, configs, opts)
                b.build(deps, mail = mail)
                b = None
                setbuilder_error = False

        if deps is not None:
            c = 0
            for d in sorted(set(deps)):
                c += 1
                print('dep[%d]: %s' % (c, d))
    except error.general as gerr:
        if not setbuilder_error:
            log.stderr(str(gerr))
        log.stderr('Build FAILED')
        ec = 1
    except error.internal as ierr:
        if not setbuilder_error:
            log.stderr(str(ierr))
        log.stderr('Internal Build FAILED')
        ec = 1
    except error.exit as eerr:
        pass
    except KeyboardInterrupt:
        log.notice('abort: user terminated')
        ec = 1
    except:
        raise
        log.notice('abort: unknown error')
        ec = 1
    sys.exit(ec)