示例#1
0
def run_server():
    # parse arguments
    import optparse
    parser = optparse.OptionParser(usage='usage: %prog [options]')
    parser.add_option('-c', '--conf',
        dest='conf', default='yastatsd.cfg',
        help='Path to configuration file')
    (opt, args) = parser.parse_args()

    # read config file
    import ConfigParser
    conf = ConfigParser.ConfigParser()
    conf.readfp(open(opt.conf))

    # setup logger
    if conf.has_option('files', 'logging'):
        import os
        os.environ['TZ'] = 'Etc/UTC'
        time.tzset()
        import logging.config
        logging.config.fileConfig(open(conf.get('files', 'logging')))
        logging.Formatter.converter = time.localtime

    # start server
    server = Server(
        carbon_host=conf.get('carbon', 'host'),
        carbon_port=conf.getint('carbon', 'port'),
        send_interval=conf.getint('carbon', 'interval'),
        pct_threshold=conf.getint('metrics', 'percentile'),
        prefix=conf.get('metrics', 'prefix')
    )

    server.serve(conf.get('listen', 'host'), conf.getint('listen', 'port'))
示例#2
0
 def teardown(self):
     if self.old_tz:
         os.environ['TZ'] = self.old_tz
     else:
         del os.environ['TZ']
     if 'tzset' in dir(time):
         time.tzset()
示例#3
0
文件: helpers.py 项目: wbbim/collipa
def format_date(timestamp):
    FORY = '%Y-%m-%d @ %H:%M'
    FORM = '%m-%d @ %H:%M'
    FORH = '%H:%M'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    r_time = time.strftime(FORM, time.localtime(timestamp))
    h_time = time.strftime(FORH, time.localtime(timestamp))
    now = int(time.time())
    t = now - timestamp
    if t < 60:
        format_str = '刚刚'
    elif t < 60 * 60:
        min = t / 60
        format_str = '%d 分钟前' % min
    elif t < 60 * 60 * 24:
        h = t / (60 * 60)
        format_str = '%d 小时前 %s' % (h, h_time)
    elif t < 60 * 60 * 24 * 3:
        d = t / (60 * 60 * 24)
        if d == 1:
            format_str = '昨天 ' + r_time
        else:
            format_str = '前天 ' + r_time
    else:
        format_str = time.strftime(FORY, time.localtime(timestamp))
    return format_str
示例#4
0
def get_messages():
    os.environ['TZ'] = 'Asia/Shanghai'
    time.tzset()
    db = MySQLdb.connect("localhost","root","dhdj513758","iems5722")
    chatroom_id = request.args.get("chatroom_id",0,type = int)
    page = request.args.get("page",0,type = int)
    query = "SELECT * FROM messages WHERE chatroom_id = %s"
    params = (chatroom_id,)
    cursor = db.cursor()
    cursor.execute(query,params)
    messages =cursor.fetchall()
    string_t = []
    if messages is None:
      db.close()
      return jsonify(message="<error message>",status="ERROR")
    else:
       for row in messages:
        roww = {}
        roww["message"]=row[4]
        roww["user_id"]=row[2]
        roww["name"]=row[3]
        roww["timestamp"]=str(row[5])
        string_t.append(roww)
       messages_num = cursor.execute(query,params)
       total_pages = messages_num / 5 + 1
       string_u = string_t[::-1]
       string = string_u[page * 5 - 5:page * 5]
       data = {
           "current_page":page,
           "messages":string,
           "total_pages":total_pages,
       }
       db.close()
       return jsonify(data=data,status="OK")
def apply_django_settings(siteconfig, settings_map=None):
    """
    Applies all settings from the site configuration to the Django settings
    object.
    """
    if settings_map is None:
        settings_map = get_django_settings_map()

    for key, setting_data in settings_map.iteritems():
        if key in siteconfig.settings:
            value = siteconfig.get(key)

            if isinstance(setting_data, dict):
                setting_key = setting_data['key']

                if ('deserialize_func' in setting_data and
                    callable(setting_data['deserialize_func'])):
                    value = setting_data['deserialize_func'](value)
            else:
                setting_key = setting_data

            setattr(settings, setting_key, value)

    if hasattr(time, 'tzset'):
        os.environ['TZ'] = settings.TIME_ZONE
        time.tzset()
示例#6
0
    def setup_new_conf(self):
        conf = self.new_conf
        self.new_conf = None
        self.cur_conf = conf
        # Got our name from the globals
        if 'receiver_name' in conf['global']:
            name = conf['global']['receiver_name']
        else:
            name = 'Unnamed receiver'
        self.name = name
        self.log.load_obj(self, name)

        print "[%s] Sending us configuration %s" % (self.name, conf)

        if not self.have_modules:
            self.modules = mods = conf['global']['modules']
            self.have_modules = True
            logger.log("[%s] We received modules %s " % (self.name,  mods))

        # Set our giving timezone from arbiter
        use_timezone = conf['global']['use_timezone']
        if use_timezone != 'NOTSET':
            logger.log("[%s] Setting our timezone to" % (self.name, use_timezone))
            os.environ['TZ'] = use_timezone
            time.tzset()
示例#7
0
文件: helpers.py 项目: wbbim/collipa
def get_month():
    timestamp = int(time.time())
    FORY = '%m'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    format_str = time.strftime(FORY, time.localtime(timestamp))
    return format_str
示例#8
0
文件: signals.py 项目: 007lva/mmddpp
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone._localtime = None

    # Reset the database connections' time zone
    if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz])
示例#9
0
def setUpMyTime():
	# Set the time to a fixed, known value
	# Sun Aug 14 12:00:00 CEST 2005
	# yoh: we need to adjust TZ to match the one used by Cyril so all the timestamps match
	os.environ['TZ'] = 'Europe/Zurich'
	time.tzset()
	MyTime.setTime(1124013600)
示例#10
0
def update_connections_time_zone(**kwargs):
    if kwargs["setting"] == "TIME_ZONE":
        # Reset process time zone
        if hasattr(time, "tzset"):
            if kwargs["value"]:
                os.environ["TZ"] = kwargs["value"]
            else:
                os.environ.pop("TZ", None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs["setting"] == "USE_TZ" and settings.TIME_ZONE != "UTC":
        USE_TZ, TIME_ZONE = kwargs["value"], settings.TIME_ZONE
    elif kwargs["setting"] == "TIME_ZONE" and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs["value"]
    else:
        # no need to change the database connnections' time zones
        return
    tz = "UTC" if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict["TIME_ZONE"] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz])
示例#11
0
文件: Url.py 项目: sq9mev/TileCache
    def read(self, configs, reload=False):
        # sys.stderr.write("url.read\n")
        self.cache = None
        self.metadata = {}

        config = None
        try:
            config = ConfigParser.ConfigParser()
            fp = urllib2.urlopen(self.resource)
            headers = dict(fp.info())
            config.readfp(fp)
            fp.close()
            self.layers = {}

            self._loadSections(config, configs, reload, cache=self.cache)

            ##### set last_mtime #####
            os.environ["TZ"] = "UTC"
            time.tzset()
            # FIXME fixed format is probably wrong
            mytime = time.strptime(headers["last-modified"], "%a, %d %b %Y %H:%M:%S %Z")
            self.last_mtime = time.mktime(mytime)

        except Exception, E:
            self.metadata["exception"] = E
            self.metadata["traceback"] = "".join(traceback.format_tb(sys.exc_traceback))
示例#12
0
 def test_TimeRE_recreation_timezone(self):
     # The TimeRE instance should be recreated upon changing the timezone.
     oldtzname = time.tzname
     tm = _strptime._strptime_time(time.tzname[0], '%Z')
     self.assertEqual(tm.tm_isdst, 0)
     tm = _strptime._strptime_time(time.tzname[1], '%Z')
     self.assertEqual(tm.tm_isdst, 1)
     # Get id of current cache object.
     first_time_re = _strptime._TimeRE_cache
     # Change the timezone and force a recreation of the cache.
     os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
     time.tzset()
     tm = _strptime._strptime_time(time.tzname[0], '%Z')
     self.assertEqual(tm.tm_isdst, 0)
     tm = _strptime._strptime_time(time.tzname[1], '%Z')
     self.assertEqual(tm.tm_isdst, 1)
     # Get the new cache object's id.
     second_time_re = _strptime._TimeRE_cache
     # They should not be equal.
     self.assertIsNot(first_time_re, second_time_re)
     # Make sure old names no longer accepted.
     with self.assertRaises(ValueError):
         _strptime._strptime_time(oldtzname[0], '%Z')
     with self.assertRaises(ValueError):
         _strptime._strptime_time(oldtzname[1], '%Z')
示例#13
0
    def testApprovedTZFromEnvironmentWithFloating(self):

        def _restoreTZEnv(result, oldTZ):
            if oldTZ is None:
                del os.environ['TZ']
            else:
                os.environ['TZ'] = oldTZ
            time.tzset()
            eventcalendar.tz.LOCAL = tz.LocalTimezone()
            return result

        new_end_naive = self.half_an_hour_ago.replace(tzinfo=None)

        oldTZ = os.environ.get('TZ', None)
        os.environ['TZ'] = 'US/Pacific'
        time.tzset()
        eventcalendar.tz.LOCAL = tz.LocalTimezone()

        data = self.ical_from_specs('', self.half_an_hour_ago,
                                    '', new_end_naive)
        self.bouncer = self.bouncer_from_ical(data)

        keycard = keycards.KeycardGeneric()
        d = defer.maybeDeferred(self.bouncer.authenticate, keycard)
        d.addCallback(self._approved_callback)
        d.addBoth(_restoreTZEnv, oldTZ)
        return d
示例#14
0
	def __init__(self):
		# Will only work on UNIX
		if (hasattr(time, 'tzset')):
			os.environ['TZ'] = 'Europe/London'
			time.tzset()
			
		# DB connection string
		try:
			with open('plugins/LogsToDB/config.json') as data:
				config = json.load(data)

			conn_string = "host='%s' dbname='%s' user='******' password='******'" % (config['db']['host'], config['db']['dbname'], config['db']['user'], config['db']['password'])
		except IOError as e:
			print(os.getcwd())
			sys.exit("Error! No config file supplied, please create a config.json file in the root")
		
		# Print connection string
		print("Connecting to database\n -> %s" % (conn_string))
		
		# get a connection
		conn = psycopg2.connect(conn_string)
		
		# conn.curser will return a cursor object, you can use this to perform queries
		self.cursor = conn.cursor()
		self.conn = conn
		print("connected!\n")
示例#15
0
def setup(bot):
    time.tzset()

    ctime = time.time()
    bot.memory['kd_queue']=[]
    
    try:
        bot.memory['kd_evnctr']=int(bot.config.kdown.ev_ctr)
    except:
        bot.memory['kd_evnctr']=0
    
    print(bot.config.kdown.events)    
    events=unpack_events(bot, bot.config.kdown.events)
    bot.memory['kd_events']=events
    print(bot.memory['kd_events'])
    print()
    print(bot.memory['kd_queue'])
    
    try:
        subscrl=bot.config.kdown.get_list('subscribers')
        bot.memory['kd_subscribers']=set()
        for sub in subscrl:
            bot.memory['kd_subscribers'].add(sub)
        print(subscrl,bot.memory['kd_subscribers'])
    except Exception as e:
        bot.memory['kd_subscribers']=set()
    bot.memory.setdefault('ctmutex', threading.BoundedSemaphore(1)) #CheckTime Mutex
    
    lstr = lambda o: str(o).lower()
    admins=set(map(lstr, bot.config.core.get_list('admins')))
    admins.update(set(map(lstr, bot.config.kdown.get_list('admins'))))
    admins.add(bot.config.core.owner)
    bot.memory['kd_admins'] = admins
示例#16
0
 def cleanup():
     # os.environ.pop is broken!  Don't use it!  Ever!  Or die!
     try:
         del os.environ['TZ']
     except KeyError:
         pass
     time.tzset()
示例#17
0
def main():
  logging.warning(
      'devappserver2.py is currently experimental but will eventually replace '
      'dev_appserver.py in the App Engine Python SDK. For more information and '
      'to report bugs, please see: '
      'http://code.google.com/p/appengine-devappserver2-experiment/')

  _install_signal_handler()
  # The timezone must be set in the devappserver2 process rather than just in
  # the runtime so printed log timestamps are consistent and the taskqueue stub
  # expects the timezone to be UTC. The runtime inherits the environment.
  os.environ['TZ'] = 'UTC'
  if hasattr(time, 'tzset'):
    # time.tzet() should be called on Unix, but doesn't exist on Windows.
    time.tzset()
  options = parse_command_arguments(sys.argv[1:])
  dev_server = DevelopmentServer()
  try:
    dev_server.start(options)
    while True:
      time.sleep(1)
  except KeyboardInterrupt:
    pass
  finally:
    dev_server.stop()
示例#18
0
    def set_current_tz(self, tzval):
        if tzval is UnsetTz and 'TZ' in os.environ:
            del os.environ['TZ']
        else:
            os.environ['TZ'] = tzval

        time.tzset()
示例#19
0
文件: tz.py 项目: Astalaseven/Cnchi
 def _restore_tz(self, tzbackup):
     if tzbackup is None:
         if 'TZ' in os.environ:
             del os.environ['TZ']
     else:
         os.environ['TZ'] = tzbackup
     time.tzset()
示例#20
0
文件: feed.py 项目: nanamii/gylfeed
    def __init__(self, init_data, raw_feed=None, has_icon=None,
                 icon=None, feedhandler=None, feedtype='usual'):

        GObject.GObject.__init__(self)

        tzset()

        self.url = init_data["url"]
        self.name = init_data["feed_name"]
        self.automatic_update = init_data["update_switch"]
        self.notifications = init_data["notify_switch"]
        self.update_interval = init_data["update_spin"]
        self.delete_interval = init_data["delete_spin"]
        self.new_entries = []
        self.has_icon = has_icon
        self.icon = icon
        self.feedtype = feedtype
        self.is_clicked = False
        self.count_new_entries = 0
        self.raw_feed = raw_feed
        if raw_feed is None:
            self._download_data()

        self.update_id = None
        self.add_updater(self.update_interval)
示例#21
0
def test_timezones():
    pofile = po.pofile()

    # The following will only work on Unix because of tzset() and %z
    if 'tzset' in time.__dict__:
        os.environ['TZ'] = 'Asia/Kabul'
        time.tzset()
        assert time.timezone == -16200
        # Typically "+0430"
        assert poheader.tzstring() == time.strftime("%z")

        os.environ['TZ'] = 'Asia/Seoul'
        time.tzset()
        assert time.timezone == -32400
        # Typically "+0900"
        assert poheader.tzstring() == time.strftime("%z")

        os.environ['TZ'] = 'Africa/Johannesburg'
        time.tzset()
        assert time.timezone == -7200
        # Typically "+0200"
        assert poheader.tzstring() == time.strftime("%z")

        os.environ['TZ'] = 'Africa/Windhoek'
        time.tzset()
        assert time.timezone == -3600
        # Typically "+0100"
        # For some reason python's %z doesn't know about Windhoek DST
        #assert poheader.tzstring() == time.strftime("%z")

        os.environ['TZ'] = 'UTC'
        time.tzset()
        assert time.timezone == 0
        # Typically "+0000"
        assert poheader.tzstring() == time.strftime("%z")
示例#22
0
 def getTodayDate(self):
     import os, time
     os.environ['TZ'] = "Europe/London"
     time.tzset()
     localtime = time.localtime()
     timeString = time.strftime('%Y%m%d')
     return(timeString)
示例#23
0
文件: model.py 项目: treylitefm/medio
    def __init__(self):
        with open('config.json', 'r') as f:
            self.config = json.load(f)

        self.conn = Redis(self.config['redis']['host']) 
        os.environ['TZ'] = 'EST'
        time.tzset()
示例#24
0
def reload_django_settings():
        mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE'])

        # reload module
        reload(mod)

        # reload settings.
        # USe code from django.settings.Settings module.

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and type(setting_value) == str:
                    setting_value = (setting_value,) # In case the user forgot the comma.
                setattr(settings, setting, setting_value)

        # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
        # of all those apps.
        new_installed_apps = []
        for app in settings.INSTALLED_APPS:
            if app.endswith('.*'):
                app_mod = util.import_module(app[:-2])
                appdir = os.path.dirname(app_mod.__file__)
                app_subdirs = os.listdir(appdir)
                name_pattern = re.compile(r'[a-zA-Z]\w*')
                for d in sorted(app_subdirs):
                    if (name_pattern.match(d) and
                            os.path.isdir(os.path.join(appdir, d))):
                        new_installed_apps.append('%s.%s' % (app[:-2], d))
            else:
                new_installed_apps.append(app)
        setattr(settings, "INSTALLED_APPS", new_installed_apps)

        if hasattr(time, 'tzset') and settings.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root,
                        *(settings.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                        settings.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = settings.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if getattr(settings, 'LOGGING_CONFIG', False):
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1)
            logging_config_module = util.import_module(logging_config_path)
            logging_config_func = getattr(logging_config_module, logging_config_func_name)

            # ... then invoke it with the logging settings
            logging_config_func(settings.LOGGING)
    def setUp(self):
        # Ensure we're in UTC.
        os.environ['TZ'] = 'UTC'
        time.tzset()

        # Start with a fresh api proxy.
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()

        # Use a fresh stub datastore.
        self.__datastore_stub = datastore_file_stub.DatastoreFileStub(
            APP_ID, '/dev/null', '/dev/null')
        apiproxy_stub_map.apiproxy.RegisterStub(
            'datastore_v3', self.__datastore_stub)
        os.environ['APPLICATION_ID'] = APP_ID

        # Use a fresh stub UserService.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'user', user_service_stub.UserServiceStub())
        os.environ['AUTH_DOMAIN'] = AUTH_DOMAIN
        os.environ['USER_EMAIL'] = LOGGED_IN_USER

        # Use a fresh urlfetch stub.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'urlfetch', urlfetch_stub.URLFetchServiceStub())

        # Use a fresh mail stub.
        apiproxy_stub_map.apiproxy.RegisterStub(
            'mail', mail_stub.MailServiceStub())
示例#26
0
 def updateTime(self, event = None):
     """When this is called, update all the text boxes with the correct time"""
     boxWidth = 80 #used to force the window to be the correct width
     for [tz, title, format, wxtextbox] in self.config:
         os.environ['TZ'] = tz #set the TZ to that given in the config
         time.tzset() #set the time zone in the time module
         dateStr = time.strftime(format) + " " + title
         boxWidth = max(boxWidth, len(dateStr)*self.pixlesPerCharX)
         wxtextbox.SetValue(dateStr)
         if self.paintFormat == self.__PAINT_DIURNAL__ and \
                 int(time.strftime("%H")) >= 7 and int(time.strftime("%H")) <= 19:  #rudimentary check for daylight
             wxtextbox.SetBackgroundColour(wx.Colour(self.bgA[0], self.bgA[1], self.bgA[2]))
         if self.paintFormat == self.__PAINT_DIURNAL__ and \
                 int(time.strftime("%H")) < 7 or int(time.strftime("%H")) > 19:  #checking for daylight
             wxtextbox.SetBackgroundColour(wx.Colour(self.bgB[0], self.bgB[1], self.bgB[2]))
     for i in range(len(self.config)): #set smallest size and colorize
         self.config[i][3].SetMinSize([boxWidth, 27]) #set smallest size
         if (i % 2) == 0 and self.paintFormat == self.__PAINT_ALTERNATING__:
             self.config[i][3].SetBackgroundColour(wx.Colour(self.bgA[0], self.bgA[1], self.bgA[2]))
         if (i % 2) == 1 and self.paintFormat == self.__PAINT_ALTERNATING__:
             self.config[i][3].SetBackgroundColour(wx.Colour(self.bgB[0], self.bgB[1], self.bgB[2]))
     self.SetMinSize([boxWidth, -1])      
     self.SetMaxSize([boxWidth, 27*len(self.config)])
     try:
         event.Skip
     except:
         pass
示例#27
0
  def __init__(self):

    Cmd.__init__(self)
    os.environ["TZ"] = "UTC"
    time.tzset()

    # Try parsing just the arguments that make sense if we're
    # going to be running an interactive command loop.  If that
    # parses everything, we're interactive, otherwise, it's either
    # a non-interactive command or a parse error, so we let the full
    # parser sort that out for us.

    args, argv = self.top_argparser.parse_known_args()
    self.interactive = not argv
    if not self.interactive:
      args = self.full_argparser.parse_args()

    self.cfg_file = args.config
    self.handle = args.identity

    if args.profile:
      import cProfile
      prof = cProfile.Profile()
      try:
        prof.runcall(self.main, args)
      finally:
        prof.dump_stats(args.profile)
        print "Dumped profile data to %s" % args.profile
    else:
      self.main(args)
示例#28
0
def get_year():
    timestamp = int(time.time())
    FORY = '%Y'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    str = time.strftime(FORY, time.localtime(timestamp))
    return str
示例#29
0
	def activateTimezone(self, tz, tzarea):
		if path.exists("/usr/lib/enigma2/python/Plugins/Extensions/AutoTimer/plugin.pyo") and config.plugins.autotimer.autopoll.value:
			print "[Timezones] trying to stop main AutoTimer poller"
			self.autopoller.stop()
			self.ATupdate = True

		if tzarea == Timezones.gen_label:
			fulltz = tz
		else:
			fulltz = "%s/%s" % (tzarea, tz)

		tzneed = "%s/%s" % (Timezones.tzbase, fulltz)
		if not path.isfile(tzneed):
			print "[Timezones] Attempt to set timezone", fulltz, "ignored. UTC used"
			fulltz = "UTC"
			tzneed = "%s/%s" % (Timezones.tzbase, fulltz)

		print "[Timezones] setting timezone to", fulltz
		environ['TZ'] = fulltz
		try:
			unlink("/etc/localtime")
		except OSError:
			pass
		try:
			symlink(tzneed, "/etc/localtime")
		except OSError:
			pass
		try:
			time.tzset()
		except:
			from enigma import e_tzset
			e_tzset()
		if path.exists("/usr/lib/enigma2/python/Plugins/Extensions/AutoTimer/plugin.pyo") and config.plugins.autotimer.autopoll.value:
			self.startATupdate()
示例#30
0
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}:
        for conn in connections.all():
            try:
                del conn.timezone
            except AttributeError:
                pass
            try:
                del conn.timezone_name
            except AttributeError:
                pass
            conn.ensure_timezone()
示例#31
0
    def test_tzset(self):
        if not hasattr(time, "tzset"):
            return  # Can't test this; don't want the test suite to fail

        from os import environ

        # Epoch time of midnight Dec 25th 2002. Never DST in northern
        # hemisphere.
        xmas2002 = 1040774400.0

        # These formats are correct for 2002, and possibly future years
        # This format is the 'standard' as documented at:
        # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
        # They are also documented in the tzset(3) man page on most Unix
        # systems.
        eastern = 'EST+05EDT,M4.1.0,M10.5.0'
        victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
        utc = 'UTC+0'

        org_TZ = environ.get('TZ', None)
        try:
            # Make sure we can switch to UTC time and results are correct
            # Note that unknown timezones default to UTC.
            # Note that altzone is undefined in UTC, as there is no DST
            environ['TZ'] = eastern
            time.tzset()
            environ['TZ'] = utc
            time.tzset()
            self.failUnlessEqual(time.gmtime(xmas2002),
                                 time.localtime(xmas2002))
            self.failUnlessEqual(time.daylight, 0)
            self.failUnlessEqual(time.timezone, 0)
            self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0)

            # Make sure we can switch to US/Eastern
            environ['TZ'] = eastern
            time.tzset()
            self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.failUnlessEqual(time.tzname, ('EST', 'EDT'))
            self.failUnlessEqual(len(time.tzname), 2)
            self.failUnlessEqual(time.daylight, 1)
            self.failUnlessEqual(time.timezone, 18000)
            self.failUnlessEqual(time.altzone, 14400)
            self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0)
            self.failUnlessEqual(len(time.tzname), 2)

            # Now go to the southern hemisphere.
            environ['TZ'] = victoria
            time.tzset()
            self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.failUnless(time.tzname[0] == 'AEST', str(time.tzname[0]))
            self.failUnless(time.tzname[1] == 'AEDT', str(time.tzname[1]))
            self.failUnlessEqual(len(time.tzname), 2)
            self.failUnlessEqual(time.daylight, 1)
            self.failUnlessEqual(time.timezone, -36000)
            self.failUnlessEqual(time.altzone, -39600)
            self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 1)

        finally:
            # Repair TZ environment variable in case any other tests
            # rely on it.
            if org_TZ is not None:
                environ['TZ'] = org_TZ
            elif environ.has_key('TZ'):
                del environ['TZ']
            time.tzset()
示例#32
0
import shutil
import tempfile
import time

import py7zr
import py7zr.archiveinfo
import py7zr.cli
import py7zr.compression
import pytest

from . import check_output, decode_all

testdata_path = os.path.join(os.path.dirname(__file__), 'data')
os.environ['TZ'] = 'UTC'
if os.name == 'posix':
    time.tzset()
os.umask(0o022)


@pytest.mark.basic
def test_basic_initinfo():
    archive = py7zr.SevenZipFile(
        open(os.path.join(testdata_path, 'test_1.7z'), 'rb'))
    assert archive is not None


@pytest.mark.basic
def test_basic_list_1():
    archive = py7zr.SevenZipFile(
        open(os.path.join(testdata_path, 'test_1.7z'), 'rb'))
    output = io.StringIO()
示例#33
0
 def getString(self):
     time.tzset()
     timeString = time.strftime(self.timeFormat)
     output = [Icons.get('clock1')]
     output.append(timeString)
     return " ".join(output)
示例#34
0
 async def _reload_timeservices(self, **kwargs):
     await self._service("ix-localtime", "start", quiet=True, **kwargs)
     await self._service("ix-ntpd", "start", quiet=True, **kwargs)
     await self._service("ntpd", "restart", **kwargs)
     os.environ['TZ'] = await self.middleware.call('datastore.query', 'system.settings', [], {'order_by': ['-id'], 'get': True})['stg_timezone']
     time.tzset()
示例#35
0
def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: str
    """
    filename = None
    pagename = None
    namespace = None
    salt = ''
    force = False
    calc = None
    templates = []

    local_args = pywikibot.handle_args(args)
    for arg in local_args:
        option, _, value = arg.partition(':')
        if not option.startswith('-'):
            templates.append(arg)
            continue
        option = option[1:]
        if option in ('file', 'filename'):
            filename = value
        elif option == 'locale':
            # Required for english month names
            locale.setlocale(locale.LC_TIME, value.encode('utf8'))
        elif option == 'timezone':
            os.environ['TZ'] = value.timezone
            # Or use the preset value
            if hasattr(time, 'tzset'):
                time.tzset()
        elif option == 'calc':
            calc = value
        elif option == 'salt':
            salt = value
        elif option == 'force':
            force = True
        elif option == 'page':
            pagename = value
        elif option == 'namespace':
            namespace = value

    site = pywikibot.Site()

    if calc:
        if not salt:
            pywikibot.bot.suggest_help(missing_parameters=['-salt'])
            return False
        page = pywikibot.Page(site, calc)
        if page.exists():
            calc = page.title()
        else:
            pywikibot.output(
                'NOTE: the specified page "{0}" does not (yet) exist.'.format(
                    calc))
        pywikibot.output('key = {}'.format(calc_md5_hexdigest(calc, salt)))
        return

    if not templates:
        pywikibot.bot.suggest_help(
            additional_text='No template was specified.')
        return False

    for template_name in templates:
        pagelist = []
        tmpl = pywikibot.Page(site, template_name, ns=10)
        if not filename and not pagename:
            if namespace is not None:
                ns = [str(namespace)]
            else:
                ns = []
            pywikibot.output('Fetching template transclusions...')
            for pg in tmpl.getReferences(only_template_inclusion=True,
                                         follow_redirects=False,
                                         namespaces=ns):
                pagelist.append(pg)
        if filename:
            for pg in open(filename, 'r').readlines():
                pagelist.append(pywikibot.Page(site, pg, ns=10))
        if pagename:
            pagelist.append(pywikibot.Page(site, pagename, ns=3))
        pagelist = sorted(pagelist)
        for pg in iter(pagelist):
            pywikibot.output('Processing {}'.format(pg))
            # Catching exceptions, so that errors in one page do not bail out
            # the entire process
            try:
                archiver = PageArchiver(pg, tmpl, salt, force)
                archiver.run()
            except ArchiveBotSiteConfigError as e:
                # no stack trace for errors originated by pages on-site
                pywikibot.error(
                    'Missing or malformed template in page {}: {}'.format(
                        pg, e))
            except Exception:
                pywikibot.error(
                    'Error occurred while processing page {}'.format(pg))
                pywikibot.exception(tb=True)
示例#36
0
def makeService(options):
    """
    Makes a new swftp-sftp service. The only option is the config file
    location. See CONFIG_DEFAULTS for list of configuration options.
    """
    from twisted.cred.portal import Portal

    from swftp.realm import SwftpRealm
    from swftp.auth import SwiftBasedAuthDB
    from swftp.utils import (log_runtime_info, GLOBAL_METRICS,
                             parse_key_value_config)

    c = get_config(options['config_file'], options)

    smtp_service = service.MultiService()

    # ensure timezone is GMT
    os.environ['TZ'] = 'GMT'
    time.tzset()

    print('Starting SwFTP-smtp %s' % VERSION)

    authdb = SwiftBasedAuthDB(
        c.get('smtp', 'auth_url'),
        global_max_concurrency=c.getint('smtp', 'num_persistent_connections'),
        max_concurrency=c.getint('smtp', 'num_connections_per_session'),
        timeout=c.getint('smtp', 'connection_timeout'),
        extra_headers=parse_key_value_config(c.get('smtp', 'extra_headers')),
        verbose=c.getboolean('smtp', 'verbose'),
        rewrite_scheme=c.get('smtp', 'rewrite_storage_scheme'),
        rewrite_netloc=c.get('smtp', 'rewrite_storage_netloc'),
    )

    rabbitmq_hosts = c.get('rabbitmq', 'rabbitmq_hosts')
    rabbitmq_cluster = RabbitClusterClient([RabbitReplica(host, port) \
                        for host, port in [(h,int(p)) for h,p in [r.split(':') \
                        for r in rabbitmq_hosts.split(',')]]], \
                        c.get('rabbitmq', 'username'), \
                        c.get('rabbitmq', 'password')) \
                        if rabbitmq_hosts else None
    queue_name = c.get('smtp', 'queue_name')
    swift_username = c.get('smtp', 'swift_username')
    swift_password = c.get('smtp', 'swift_password')

    def swift_connect():
        d = authdb.requestAvatarId(
            UsernamePassword(swift_username, swift_password))

        def cb(connection):
            return connection

        def errback(failure):
            log.err("Swift connection failed: %s" % failure.type)
            raise SMTPServerError(451, "Internal server error")

        d.addCallbacks(cb, errback)
        return d

    @defer.inlineCallbacks
    def prepare_path():
        swift_conn = yield swift_connect()
        swift_filesystem = SwiftFileSystem(swift_conn)
        try:
            yield swift_filesystem.get_container_listing('smtp', '/')
        except swift.NotFound:
            yield swift_filesystem.makeDirectory('/smtp/')
        defer.returnValue(None)

    prepare_path()

    smtp_factory = SwftpSMTPFactory(swift_connect, rabbitmq_cluster,\
                                queue_name)

    signal.signal(signal.SIGUSR1, log_runtime_info)
    signal.signal(signal.SIGUSR2, log_runtime_info)

    internet.TCPServer(c.getint('smtp', 'port'),
                       smtp_factory,
                       interface=c.get('smtp',
                                       'host')).setServiceParent(smtp_service)

    return smtp_service
示例#37
0
def initTimeZone():
    os.environ['TZ'] = 'America/New_York'
    time.tzset()
示例#38
0
 def handle_api_tz_get(self, http_context):
     time.tzset()
     return {
         'tz': self.manager.get_tz(),
         'offset': self.manager.get_offset(),
     }
示例#39
0
    def test_tzset(self):

        from os import environ

        # Epoch time of midnight Dec 25th 2002. Never DST in northern
        # hemisphere.
        xmas2002 = 1040774400.0

        # These formats are correct for 2002, and possibly future years
        # This format is the 'standard' as documented at:
        # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
        # They are also documented in the tzset(3) man page on most Unix
        # systems.
        eastern = 'EST+05EDT,M4.1.0,M10.5.0'
        victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
        utc = 'UTC+0'

        org_TZ = environ.get('TZ', None)
        try:
            # Make sure we can switch to UTC time and results are correct
            # Note that unknown timezones default to UTC.
            # Note that altzone is undefined in UTC, as there is no DST
            environ['TZ'] = eastern
            time.tzset()
            environ['TZ'] = utc
            time.tzset()
            self.assertEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.assertEqual(time.daylight, 0)
            self.assertEqual(time.timezone, 0)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)

            # Make sure we can switch to US/Eastern
            environ['TZ'] = eastern
            time.tzset()
            self.assertNotEqual(time.gmtime(xmas2002),
                                time.localtime(xmas2002))
            self.assertEqual(time.tzname, ('EST', 'EDT'))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, 18000)
            self.assertEqual(time.altzone, 14400)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
            self.assertEqual(len(time.tzname), 2)

            # Now go to the southern hemisphere.
            environ['TZ'] = victoria
            time.tzset()
            self.assertNotEqual(time.gmtime(xmas2002),
                                time.localtime(xmas2002))

            # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
            # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
            # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
            # on some operating systems (e.g. FreeBSD), which is wrong. See for
            # example this bug:
            # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
            self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
            self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'),
                            str(time.tzname[1]))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, -36000)
            self.assertEqual(time.altzone, -39600)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)

        finally:
            # Repair TZ environment variable in case any other tests
            # rely on it.
            if org_TZ is not None:
                environ['TZ'] = org_TZ
            elif 'TZ' in environ:
                del environ['TZ']
            time.tzset()
示例#40
0
    def reload_django_settings(self, settings_modname):
        from django.conf import settings
        from django.utils import importlib

        mod = importlib.import_module(settings_modname)

        # reload module
        reload(mod)

        # reload settings.
        # USe code from django.settings.Settings module.

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and type(setting_value) == str:
                    setting_value = (setting_value,
                                     )  # In case the user forgot the comma.
                setattr(settings, setting, setting_value)

        # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
        # of all those apps.
        new_installed_apps = []
        for app in settings.INSTALLED_APPS:
            if app.endswith('.*'):
                app_mod = importlib.import_module(app[:-2])
                appdir = os.path.dirname(app_mod.__file__)
                app_subdirs = os.listdir(appdir)
                app_subdirs.sort()
                name_pattern = re.compile(r'[a-zA-Z]\w*')
                for d in app_subdirs:
                    if name_pattern.match(d) and os.path.isdir(
                            os.path.join(appdir, d)):
                        new_installed_apps.append('%s.%s' % (app[:-2], d))
            else:
                new_installed_apps.append(app)
        setattr(settings, "INSTALLED_APPS", new_installed_apps)

        if hasattr(time, 'tzset') and settings.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not os.path.exists(
                    os.path.join(zoneinfo_root,
                                 *(settings.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                                 settings.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = settings.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if getattr(settings, 'LOGGING_CONFIG', False):
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit(
                '.', 1)
            logging_config_module = importlib.import_module(
                logging_config_path)
            logging_config_func = getattr(logging_config_module,
                                          logging_config_func_name)

            # ... then invoke it with the logging settings
            logging_config_func(settings.LOGGING)
示例#41
0
        while True:
            sys.stdout.write("-----\n")
            sys.stdout.flush()
            # TODO 1: write check_file_change & add settings.

            #self.check_file_change()
            #sleep(settings.LOOP_INTERVAL)

            # This will restart on very short downtime, but if it's longer,
            # the MM will crash entirely as it is unable to connect to the WS on boot.
            if not self.check_connection():
                print('No connection detected! Restarting...')
                logging.error(
                    "Realtime data connection unexpectedly closed, restarting."
                )
                self.restart()

            # TODO 2: sanity_check, print_status

            self.run()

            #self.sanity_check()  # Ensures health of mm - several cut-out points here
            #self.print_status()  # Print skew, delta, etc
            #self.place_orders()  # Creates desired orders and converges to existing orders


if __name__ == "__main__":
    current_hour = datetime.datetime.now().hour
    os.environ['TZ'] = 'Asia/Saigon'
    time.tzset()  # only available in Unix
    Market_maker('ETHUSD').run()
示例#42
0
 def setUp(self):
     os.environ['TZ'] = 'GMT'
     time.tzset()
示例#43
0
def format_date2(timestamp):
    FORY = '%Y-%m-%d @ %H:%M'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    format_str = time.strftime(FORY, time.localtime(timestamp))
    return format_str
示例#44
0
 def tearDownClass(cls):
     del os.environ["TZ"]
     if cls.tz_prev is not None:
         os.environ["TZ"] = cls.tz_prev
     time.tzset()
     super(ArrowTests, cls).tearDownClass()
示例#45
0
 def tearDownClass(cls):
     del os.environ["TZ"]
     if cls.tz_prev is not None:
         os.environ["TZ"] = cls.tz_prev
     time.tzset()
     ReusedSQLTestCase.tearDownClass()
示例#46
0
def settimezone(timezone):
    os.environ['TZ'] = timezone
    time.tzset()
    return ""
示例#47
0
# -*- coding: utf-8 -*-
import telebot
import io, re, os, time
from telebot import types
from SQLighter import SQLighter
import botan, requests, json, logging

os.environ['TZ'] = 'Europe/Moscow'
time.tzset()  # Настройка времени на сервере

# Настройка соединения с Telegram и Botan
BOTAN_TOKEN = ''
API_TOKEN = ''

# Создание клавиатуры по-умолчанию
key_default = types.ReplyKeyboardMarkup(resize_keyboard=True)
key_default.row(types.KeyboardButton('Добавить страницу ВК 📠'))
key_default.row(types.KeyboardButton('Настройки моих страниц 🚀'))
key_default.row(types.KeyboardButton('О боте VK Poster 🤖'))

key_hide = types.ReplyKeyboardHide(selective=False)
key_force = types.ForceReply(selective=False)

# Настройка логгера, сохраняющего все входящие сообщения
logging.getLogger('requests').setLevel(logging.CRITICAL)
logging.basicConfig(format='[%(asctime)s]%(message)s',
                    level=logging.INFO,
                    filename='app.log',
                    datefmt='%d.%m.%Y %H:%M:%S')

logger = telebot.logger
示例#48
0
def get_day(timestamp):
    FORY = '%d'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    str = time.strftime(FORY, time.localtime(timestamp))
    return str
示例#49
0
def main(args=None):
    args = parser.parse_args(args)
    if args.hardening:
        if platform.system() == 'Windows':  # pragma: no cover
            raise NotImplementedError('require --no-hardening under Windows')
        if args.setuid is None or isinstance(args.setuid, str):
            parser.error(f'unknown --setuid user: {args.setuid}')
        if (args.chroot is None or isinstance(args.chroot, str)
                or not args.chroot.is_dir()):
            parser.error(f'not a present --chroot directory: {args.chroot}')

    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
                        format='%(asctime)s %(message)s',
                        datefmt='%b %d %H:%M:%S')

    logging.info('start asciimation server on %s port %s', args.host,
                 args.port)

    @register_signal_handler(signal.SIGINT, signal.SIGTERM)
    def handle_with_exit(signum, _):
        sys.exit(f'received signal.{signal.Signals(signum).name}')

    next(iterframes())  # pre-load FRAMES

    logging.debug('socket.create_server(%r)', (args.host, args.port))
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((args.host, args.port))
    logging.debug('%r', s)

    if args.hardening:
        with pathlib.Path('/etc/timezone').open(encoding='utf-8') as f:
            tz = f.readline().strip()
        logging.debug('TZ=%r; time.tzset()', tz)
        os.environ['TZ'] = tz
        time.tzset()

        logging.debug('os.chroot(%r)', args.chroot)
        os.chroot(args.chroot)

        logging.debug('os.setuid(%r)', uid)
        os.setgid(args.setuid.pw_gid)
        os.setgroups([])
        os.setuid(args.setuid.pw_uid)

    logging.debug('asyncio.run(serve_forever(sock=%r))', s)
    try:
        asyncio.run(serve_forever(sock=s, fps=args.fps))
    except socket.error:  # pragma: no cover
        logging.exception('socket.error')
        return 'socket error'
    except SystemExit as e:
        logging.info('%r exiting', e)
    finally:
        try:
            s.shutdown(socket.SHUT_WR)
        except (socket.error, OSError):
            pass
        s.close()
        logging.info('asciimation server stopped')

    return None
示例#50
0
 def setup(self):
     self.old_tz = os.environ.get('TZ')
     os.environ['TZ'] = 'UTC'
     # time.tzset() is not implemented on some platforms (notably, Windows).
     if hasattr(time, 'tzset'):
         time.tzset()
示例#51
0
def get_timestamp():
    os.environ['TZ'] = 'Singapore'
    time.tzset()
    timestamp = time.strftime("%Y%m%d-%H.%M.%S")
    return timestamp
示例#52
0
def main():
    """Main() for gatherer.
    """

    global LOGGER
    global PUB

    opts = arg_parse()
    CONFIG.read(opts.config)

    print("Setting timezone to UTC")
    os.environ["TZ"] = "UTC"
    time.tzset()

    handlers = []
    if opts.log:
        handlers.append(
            logging.handlers.TimedRotatingFileHandler(opts.log,
                                                      "midnight",
                                                      backupCount=7))

    handlers.append(logging.StreamHandler())

    if opts.verbose:
        loglevel = logging.DEBUG
    else:
        loglevel = logging.INFO
    for handler in handlers:
        handler.setFormatter(
            logging.Formatter(
                "[%(levelname)s: %(asctime)s :"
                " %(name)s] %(message)s", '%Y-%m-%d %H:%M:%S'))
        handler.setLevel(loglevel)
        logging.getLogger('').setLevel(loglevel)
        logging.getLogger('').addHandler(handler)

    logging.getLogger("posttroll").setLevel(logging.INFO)
    LOGGER = logging.getLogger("gatherer")

    if opts.config_item:
        for section in opts.config_item:
            if section not in CONFIG.sections():
                LOGGER.warning(
                    "No config item called %s found in config file.", section)
        for section in CONFIG.sections():
            if section not in opts.config_item:
                CONFIG.remove_section(section)
        if len(CONFIG.sections()) == 0:
            LOGGER.error("No valid config item provided")
            return

    nameservers = []
    for section in CONFIG.sections():
        try:
            nameserver = CONFIG.get(section, "nameserver")
        except NoOptionError:
            nameserver = "localhost"
        if nameserver not in nameservers:
            nameservers.append(nameserver)

    decoder = get_metadata

    PUB = publisher.NoisyPublisher("gatherer", nameservers=nameservers)

    granule_triggers = setup(decoder)

    PUB.start()

    for granule_trigger in granule_triggers:
        granule_trigger.start()
    try:
        while True:
            time.sleep(1)
            for granule_trigger in granule_triggers:
                if not granule_trigger.is_alive():
                    raise RuntimeError
    except KeyboardInterrupt:
        LOGGER.info("Shutting down...")
    except RuntimeError:
        LOGGER.critical('Something went wrong!')
    except OSError:
        LOGGER.critical('Something went wrong!')
    finally:
        LOGGER.warning('Ending publication the gathering of granules...')
        for granule_trigger in granule_triggers:
            granule_trigger.stop()
        PUB.stop()
示例#53
0
# Load Twilio secrets from twilio_secrets.json
twilio_secrets = None

with open('twilio_secrets.json') as twilio_secrets_file:
    twilio_secrets = load(twilio_secrets_file)

# Load config from config.json
config = None

with open('config.json') as config_file:
    config = load(config_file)

# Set timezone
os.environ['TZ'] = config['timezone']
tzset()

# Set transparent pixel information data
# We do this with a base64 string to avoid being dependent on a 1x1 png
base64_pixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII="
pixel_data = b64decode(base64_pixel)

# Set up Twilio
client = Client(twilio_secrets['account_sid'], twilio_secrets['auth_token'])

# Read GeoIP2 database
geoip2_reader = geoip2.database.Reader('geolite2/GeoLite2-City.mmdb')


def ip_location_summary(ip_addr):
    try:
示例#54
0
def set_timezone(tz_name: str = 'Asia/Calcutta'):
    os.environ['TZ'] = tz_name
    time.tzset()
    print(f"Time-zone: {time.tzname}")
示例#55
0
    def __init__(self, arguments):
        '''
            initialize local variables
        '''
        if 'TZ' not in environ:
            os.environ['TZ'] = 'America/Los_Angeles'
        time.tzset()

        if 'FrameworkPath' not in environ:
            self.FrameworkPath = path.join(environ['HOME'], 'Projects',
                                           'AutoBDD')
        else:
            self.FrameworkPath = environ['FrameworkPath']

        self.reportonly = arguments.REPORTONLY
        self.rumtime_stamp = arguments.TIMESTAMP if arguments.TIMESTAMP else time.strftime(
            "%Y%m%d_%H%M%S%Z", time.gmtime())
        self.parallel = arguments.PARALLEL
        self.screenshot = arguments.SCREENSHOT
        self.movie = arguments.MOVIE
        self.runlevel = arguments.RUNLEVEL
        self.platform = arguments.PLATFORM
        self.browser = arguments.BROWSER
        self.debugmode = arguments.DEBUGMODE
        self.projectbase = arguments.PROJECTBASE
        self.project = arguments.PROJECT
        self.reportbase = arguments.REPORTBASE if arguments.REPORTBASE else path.join(
            self.FrameworkPath, 'test-reports')
        self.reportpath = arguments.REPORTPATH if arguments.REPORTPATH else '_'.join(
            (self.project, self.rumtime_stamp))

        self.modulelist = arguments.MODULELIST
        if arguments.TAGLIST is not None:
            self.args = '_'.join((arguments.MODULELIST + arguments.TAGLIST))
            self.tags = ' --tags ' + ','.join(arguments.TAGLIST)
        else:
            self.args = '_'.join(arguments.MODULELIST)
            self.tags = ''
        self.tagarray = arguments.TAGLIST
        self.display = ':99'
        self.display_size = '1920x1200'

        # self.test_projects_path = path.join(self.FrameworkPath,
        #                                     'test-projects')
        self.project_full_path = path.join(self.FrameworkPath,
                                           self.projectbase, self.project)
        # Each runable module should have a chimp.js
        self.chimp_profile = path.join('chimp.js')
        # Create report directory
        if not path.exists(path.join(self.FrameworkPath, self.reportbase)):
            os.makedirs(path.join(self.FrameworkPath, self.reportbase))
        self.report_dir = path.join(self.reportbase, self.reportpath)
        try:
            os.makedirs(self.report_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        print('\n*** Report Directory: ***\n {}'.format(self.report_dir))

        self.rerun = None
        if arguments.RERUN is not None:
            self.rerun = path.join(
                path.abspath(path.join(self.report_dir, '..')),
                arguments.RERUN)
            assert path.exists(self.rerun), '{} is not exits'.format(
                self.rerun)
            self.runlevel = 'Scenario'

        # remove /tmp/*.lock file
        for item in os.listdir('/tmp/'):
            if item.endswith(".lock"):
                os.remove('/tmp/' + item)

        self.marray = {}
        self.sarray = {}
        self.features_count = 0
        self.scenarios_count = 0
        self.runarray = []
        self.host = []
        self.thread_count = 0
        self.end_time = time.strftime("%Y%m%d_%H%M%S%Z", time.gmtime())
        self.get_available_host()
示例#56
0
    def __init__(self, arguments):
        '''
            initialize local variables
        '''
        if 'TZ' not in environ:
            os.environ['TZ'] = 'UTC'
        time.tzset()

        if 'FrameworkPath' not in environ:
            self.FrameworkPath = path.join(environ['HOME'], 'Projects',
                                           'AutoBDD')
        else:
            self.FrameworkPath = environ['FrameworkPath']
        os.chdir(self.FrameworkPath)
        self.reportonly = arguments.REPORTONLY
        self.runtime_stamp = arguments.TIMESTAMP if arguments.TIMESTAMP else time.strftime("%Y%m%d_%H%M%S%Z", time.gmtime())
        self.parallel = arguments.PARALLEL
        self.screenshot = arguments.SCREENSHOT
        self.screenremark = arguments.SCREENREMARK
        self.movie = arguments.MOVIE
        self.platform = arguments.PLATFORM
        self.browser = arguments.BROWSER
        self.debugmode = arguments.DEBUGMODE
        self.projectbase = arguments.PROJECTBASE if arguments.PROJECTBASE else 'test-projects'
        self.project = arguments.PROJECT
        self.projecttype = arguments.PROJECTTYPE
        self.reportbase = arguments.REPORTBASE if arguments.REPORTBASE else path.join(
            self.FrameworkPath, self.projectbase, self.project, 'bdd_reports')
        self.reportpath = arguments.REPORTPATH if arguments.REPORTPATH else '_'.join(
            (self.project, self.runtime_stamp))

        self.modulelist = arguments.MODULELIST
        self.argstring = arguments.ARGSTRING
        self.display_size = '1920x1200'

        self.project_full_path = path.join(self.FrameworkPath, self.projectbase, self.project)
        self.report_full_path = path.join(self.reportbase, self.reportpath)
        self.isMaven = self.isMavenProject (arguments.PROJECTTYPE)

        # Each runable module should have a chimp.js
        self.chimp_profile = path.join('chimp.js')
        # Create report directory
        if not path.exists(path.join(self.FrameworkPath, self.reportbase)):
            os.makedirs(path.join(self.FrameworkPath, self.reportbase))
        self.report_dir_base = path.join(self.reportbase, self.reportpath)
        try:
            os.makedirs(self.report_dir_base)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        print('\n*** Report Directory: ***\n {}'.format(self.report_dir_base))

        # remove /tmp/*.lock file
        for item in os.listdir('/tmp/'):
            if item.endswith(".lock"):
                os.remove('/tmp/' + item)

        self.host = []
        self.available_pool_number = 0
        self.end_time = time.strftime("%Y%m%d_%H%M%S%Z", time.gmtime())
        self.get_available_host()

        pprint(vars(self))
示例#57
0
def lambda_handler(event, context):
    os.environ['TZ'] = 'America/New_York'
    time.tzset()
    return dispatch(event)
示例#58
0
def main():  # pragma: no cover
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--broker', dest='broker', default=DEFAULT_BROKER,
        help="URL to the Celery broker. Defaults to {}".format(DEFAULT_BROKER))
    parser.add_argument(
        '--transport-options', dest='transport_options',
        help=("JSON object with additional options passed to the underlying "
              "transport."))
    parser.add_argument(
        '--addr', dest='addr', default=DEFAULT_ADDR,
        help="Address the HTTPD should listen on. Defaults to {}".format(
            DEFAULT_ADDR))
    parser.add_argument(
        '--enable-events', action='store_true',
        help="Periodically enable Celery events")
    parser.add_argument(
        '--tz', dest='tz',
        help="Timezone used by the celery app.")
    parser.add_argument(
        '--verbose', action='store_true', default=False,
        help="Enable verbose logging")
    parser.add_argument(
        '--max_tasks_in_memory', dest='max_tasks_in_memory',
        default=DEFAULT_MAX_TASKS_IN_MEMORY, type=int,
        help="Tasks cache size. Defaults to {}".format(
            DEFAULT_MAX_TASKS_IN_MEMORY))
    parser.add_argument(
        '--version', action='version',
        version='.'.join([str(x) for x in __VERSION__]))
    opts = parser.parse_args()

    if opts.verbose:
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
    else:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

    signal.signal(signal.SIGINT, shutdown)
    signal.signal(signal.SIGTERM, shutdown)

    if opts.tz:
        os.environ['TZ'] = opts.tz
        time.tzset()

    app = celery.Celery(broker=opts.broker)

    if opts.transport_options:
        try:
            transport_options = json.loads(opts.transport_options)
        except ValueError:
            print("Error parsing broker transport options from JSON '{}'"
                  .format(opts.transport_options), file=sys.stderr)
            sys.exit(1)
        else:
            app.conf.broker_transport_options = transport_options

    setup_metrics(app)

    t = MonitorThread(app=app, max_tasks_in_memory=opts.max_tasks_in_memory)
    t.daemon = True
    t.start()
    w = WorkerMonitoringThread(app=app)
    w.daemon = True
    w.start()
    e = None
    if opts.enable_events:
        e = EnableEventsThread(app=app)
        e.daemon = True
        e.start()
    start_httpd(opts.addr)
    t.join()
    w.join()
    if e is not None:
        e.join()
示例#59
0
def lambda_handler(event, context):
    # TODO implement
    os.environ['TZ'] = 'America/New_York'
    time.tzset()
    logger.debug('event.bot.name={}'.format(event['bot']['name']))
    return dispatch(event)
示例#60
0
    def __init__(self, settings_module):
        # update this dict from global settings (but only for ALL_CAPS settings)
        for setting in dir(global_settings):
            if setting == setting.upper():
                setattr(self, setting, getattr(global_settings, setting))

        # store the settings module in case someone later cares
        self.SETTINGS_MODULE = settings_module

        try:
            mod = importlib.import_module(self.SETTINGS_MODULE)
        except ImportError as e:
            raise ImportError(
                "Could not import settings '%s' (Is it on sys.path?): %s" %
                (self.SETTINGS_MODULE, e))

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and \
                        isinstance(setting_value, basestring):
                    warnings.warn(
                        "The %s setting must be a tuple. Please fix your "
                        "settings, as auto-correction is now deprecated." %
                        setting, PendingDeprecationWarning)
                    setting_value = (setting_value,
                                     )  # In case the user forgot the comma.
                setattr(self, setting, setting_value)

        if not self.SECRET_KEY:
            raise ImproperlyConfigured(
                "The SECRET_KEY setting must not be empty.")

        if hasattr(time, 'tzset') and self.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not os.path.exists(
                    os.path.join(zoneinfo_root,
                                 *(self.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                                 self.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = self.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if self.LOGGING_CONFIG:
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit(
                '.', 1)
            logging_config_module = importlib.import_module(
                logging_config_path)
            logging_config_func = getattr(logging_config_module,
                                          logging_config_func_name)

            # Backwards-compatibility shim for #16288 fix
            compat_patch_logging_config(self.LOGGING)

            # ... then invoke it with the logging settings
            logging_config_func(self.LOGGING)