Example #1
0
 def try_mail(self, subject, body, attachment=None):
     try:
         if gv.sd['master']:
             email(subject, gv.sd['name'] + ': ' + body, attachment)
             self.start_status('Email was sent: ' + body)
             gv.logger.debug('email sent.  body: ' + body)
             self.log_email(subject, body, 'Sent')
         else:
             parameters = {'subject':subject, 'body':gv.sd['name'] + ': ' + body}
             data = message_base('tereq', parameters)
             if data['status'] == 0:
                 self.start_status('Email was sent: ' + body)
                 gv.logger.debug('email sent.  body: ' + body)
                 self.log_email(subject, body, 'Sent')
             else:
                 self.start_status('Email was not sent! ')
                 gv.logger.debug('email not sent.  status: ' + str(data['status']) + ' body: ' + body)
                 self.log_email(subject, body, 'Unsent')
     except Exception as err:
         self.start_status('Email was not sent! ' + str(err))
         gv.logger.exception('email not sent.  body: ' + body)
         self.log_email(subject, body, 'Unsent')
Example #2
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        last_day = gv.now//86400 # wait at least a day before removing stale log files so startup does not delete them
        while True:
            try:
                cur_day = gv.now//86400
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

                    if cur_day != last_day:
                        last_day = cur_day
                        # delete any imported log files from substations that are no longer active
                        files = glob.glob('./data/imported_logs/*')
                        for full_name in files:
                            sub_name = full_name[full_name.rfind('/')+1:]
                            found_slave = 0
                            for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                                if sub_name == gv.plugin_data['su']['subinfo'][subid]['name']:
                                    found_slave = subid
                                    break
                            if found_slave == 0:
                                try:
                                    shutil.rmtree(full_name)
                                    gv.logger.info('removed substree: ' + full_name)
                                except Exception as ex:
                                    gv.logger.warning('failed to remove substree: ' + full_name + ' ex: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)
Example #3
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        while True:
            try:
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)