コード例 #1
0
ファイル: daemon.py プロジェクト: cyhatgithub/tcollector
def main(argv):
    options, args = parse_cmdline(argv)
    common_utils.setup_logging(LOG, options.logfile, 64 * 1024 * 1024, 1)
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, shutdown_signal)

    while True:
        LOG.info("uagnt daemon starting...")
        try:
            agent = uagent.UAgent(LOG)
            exit_code = agent.run()
            LOG.info(
                "uagnt daemon finished. exit code %d. sleep for 1 hour and recheck.",
                exit_code)
            time.sleep(3600)
            # in case the update agent itself was upgraded
            LOG.info("reloading uagent package...")
            reload(uagent)
            LOG.info("reloaded uagent package.")
        except SystemExit:
            LOG.info("shutting down, exit")
            exit(0)
        except:
            LOG.exception(
                "failed to run one iteration of uagent. ignore error and retry after 5 minutes"
            )
            time.sleep(300)
コード例 #2
0
ファイル: daemon.py プロジェクト: wangy1931/tcollector
def main(argv):
    options, args = parse_cmdline(argv)
    common_utils.setup_logging(LOG, options.logfile, 64 * 1024 * 1024, 1)
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, shutdown_signal)

    while True:
        LOG.info("uagnt daemon starting...")
        try:
            agent = uagent.UAgent(LOG)
            exit_code = agent.run()
            LOG.info("uagnt daemon finished. exit code %d. sleep for 1 hour and recheck.", exit_code)
            time.sleep(3600)
            # in case the update agent itself was upgraded
            LOG.info("reloading uagent package...")
            reload(uagent)
            LOG.info("reloaded uagent package.")
        except SystemExit:
            LOG.info("shutting down, exit")
            exit(0)
        except:
            LOG.exception("failed to run one iteration of uagent. ignore error and retry after 5 minutes")
            time.sleep(300)
コード例 #3
0
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.#

# TicTacToe code derived from https://inventwithpython.com

import common_utils
from player import Player
from game_env import GameBoard, is_winner, who_goes_first

logging = common_utils.setup_logging()
logger = logging.getLogger(__name__)

if __name__ == "__main__":

    debug = False

    # Reset the board
    game_board = GameBoard()
    roundNo = 1

    player1 = Player("Player 1")
    player2 = Player("Player 2")

    player1_letter, player2_letter = 'X', 'O'
    turn = who_goes_first(player1, player2)
コード例 #4
0
            shutil.copy( sourcefile, environment.ogreterrain.generated_dir )
            print "Updated ", filename, "as it was missing or out of date"

#     common_utils.copyTree ( sourcePath = environment.Config.PATH_INCLUDE_ogreterrain, 
#                             destPath = environment.ogreterrain.generated_dir, 
#                             recursive=False )
    if environment.ogre.version.startswith("1.7"):
        ## have a code generation issue that needs resolving...
        filesToFix=['TerrainGroup.pypp.cpp', 'stdVectorOgreTerrain.pypp.cpp']
        for filename in filesToFix:
            fname = os.path.join( environment.ogreterrain.generated_dir, filename)
            try:
                f = open(fname, 'r')
                buf = f.read()
                f.close()
                if (" MEMCATEGORY_GENERAL" in buf) or ("<MEMCATEGORY_GENERAL" in buf):
                    buf = buf.replace ( " MEMCATEGORY_GENERAL", " Ogre::MEMCATEGORY_GENERAL")
                    buf = buf.replace ( "<MEMCATEGORY_GENERAL", "<Ogre::MEMCATEGORY_GENERAL")
                    f = open ( fname, 'w+')
                    f.write ( buf )
                    f.close()
                    print "UGLY FIX OK:", fname
            except:
                print "ERROR: Unable to fix:", fname
        
if __name__ == '__main__':
    start_time = time.clock()
    common_utils.setup_logging ("log.out")
    generate_code()
    print 'Source code was updated( %f minutes ).' % (  ( time.clock() - start_time )/60 )
コード例 #5
0
ファイル: runner.py プロジェクト: cyhatgithub/tcollector
def main(argv):
    try:
        options, args = parse_cmdline(argv)
    except:
        sys.stderr.write("Unexpected error: %s" % sys.exc_info()[0])
        return 1

    if options.daemonize:
        daemonize()

    common_utils.setup_logging(LOG, options.logfile, options.max_bytes or None, options.backup_count or None)

    if options.verbose:
        LOG.setLevel(logging.DEBUG)  # up our level

    LOG.info('agent starting..., %s', argv)

    if options.pidfile:
        write_pid(options.pidfile)

    # validate everything
    tags = {}
    for tag in options.tags:
        if re.match('^[-_.a-z0-9]+=\S+$', tag, re.IGNORECASE) is None:
            assert False, 'Tag string "%s" is invalid.' % tag
        k, v = tag.split('=', 1)
        if k in tags:
            assert False, 'Tag "%s" already declared.' % k
        tags[k] = v

    if 'host' not in tags and not options.stdin:
        tags['host'] = socket.gethostname()
        LOG.warning('Tag "host" not specified, defaulting to %s.', tags['host'])

    options.cdir = os.path.realpath(options.cdir)
    if not os.path.isdir(options.cdir):
        LOG.fatal('No such directory: %s', options.cdir)
        return 1

    setup_python_path(options.cdir)

    # gracefully handle death for normal termination paths and abnormal
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, shutdown_signal)

    # prepare list of (host, port) of TSDs given on CLI
    if not options.hosts:
        options.hosts = [(options.host, options.port)]
    else:
        def splithost(hostport):
            if ":" in hostport:
                # Check if we have an IPv6 address.
                if hostport[0] == "[" and "]:" in hostport:
                    host, port = hostport.split("]:")
                    host = host[1:]
                else:
                    host, port = hostport.split(":")
                return host, int(port)
            return hostport, DEFAULT_PORT

        options.hosts = [splithost(host_str) for host_str in options.hosts.split(",")]
        if options.host != "localhost" or options.port != DEFAULT_PORT:
            options.hosts.append((options.host, options.port))

    runner_config = load_runner_conf()
    token = runner_config.get('base', 'token')

    readq = NonBlockingQueue(MAX_READQ_SIZE)
    global SENDER
    SENDER = Sender(token, readq, options, tags)
    SENDER.start()

    LOG.info('agent finish initializing, enter main loop.')
    main_loop(readq, options, {}, COLLECTORS)
コード例 #6
0
def main(argv):

    global MYSQL_PASSWORD

    options, args = parse_cmdline(argv)
    common_utils.setup_logging(LOG, options.logfile, 64 * 1024 * 1024, 1)
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, shutdown_signal)

    # Trying to become master in order to proceed
    zk = KazooClient(hosts=ZOOKEEPER)
    zk.start()
    lock = zk.Lock('/umanager')
    subprocess.call(GET_TOKENS_SH)

    MYSQL_PASSWORD = base64.b64decode(MYSQL_PASSWORD)

    with lock:
        LOG.info("I am the master of the universe!")
        count = 0
        lastHourDateTime = datetime.strptime(
            get_current_time(), "%Y-%m-%d %H:%M:%S") - timedelta(days=1)
        while not shutdown_requested:
            LOG.info("update manager daemon starting...")
            try:
                if (count % 100) == 0:
                    LOG.info("reloading tokens")
                    try:
                        subprocess.call(GET_TOKENS_SH)
                    except:
                        LOG.info("Failed to update tokens")
                count += 1

                manager = update_manager.UpdateManager(LOG)
                fromTime = datetime.strptime(
                    str(lastHourDateTime),
                    "%Y-%m-%d %H:%M:%S") - timedelta(seconds=128)
                toTime = get_current_time()
                LOG.info("from %s to %s", fromTime, toTime)
                exit_code = manager.run(fromTime, toTime)
                LOG.info(
                    "update manager daemon finished. exit code %d. sleep for %d seconds.",
                    exit_code, INTERVAL)
                if exit_code == 0:
                    lastHourDateTime = datetime.strptime(
                        toTime, "%Y-%m-%d %H:%M:%S") - timedelta(seconds=1)
                sleep_for(INTERVAL)
                # in case the update agent itself was upgraded
                LOG.info("reloading update manager package...")
                reload(update_manager)
                LOG.info("reloaded update_manager package.")
            except SystemExit:
                LOG.info("shutting down, exit")
                exit(0)
            except:
                LOG.exception(
                    "failed to run one iteration of update_manager. ignore error and retry after 2 seconds"
                )
                sleep_for(2)

    zk.stop()
    return 0
コード例 #7
0
ファイル: runner.py プロジェクト: wangy1931/tcollector
def main(argv):
    try:
        options, args = parse_cmdline(argv)
    except:
        sys.stderr.write("Unexpected error: %s" % sys.exc_info()[0])
        return 1

    if options.daemonize:
        daemonize()

    common_utils.setup_logging(LOG, options.logfile, options.max_bytes or None, options.backup_count or None)

    if options.verbose:
        LOG.setLevel(logging.DEBUG)  # up our level

    LOG.info('agent starting..., %s', argv)

    if options.pidfile:
        write_pid(options.pidfile)

    # validate everything
    tags = {}
    for tag in options.tags:
        if re.match('^[-_.a-z0-9]+=\S+$', tag, re.IGNORECASE) is None:
            assert False, 'Tag string "%s" is invalid.' % tag
        k, v = tag.split('=', 1)
        if k in tags:
            assert False, 'Tag "%s" already declared.' % k
        tags[k] = v

    if 'host' not in tags and not options.stdin:
        tags['host'] = socket.gethostname()
        LOG.warning('Tag "host" not specified, defaulting to %s.', tags['host'])

    options.cdir = os.path.realpath(options.cdir)
    if not os.path.isdir(options.cdir):
        LOG.fatal('No such directory: %s', options.cdir)
        return 1

    setup_python_path(options.cdir)

    # gracefully handle death for normal termination paths and abnormal
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, shutdown_signal)

    # prepare list of (host, port) of TSDs given on CLI
    if not options.hosts:
        options.hosts = [(options.host, options.port)]
    else:
        def splithost(hostport):
            if ":" in hostport:
                # Check if we have an IPv6 address.
                if hostport[0] == "[" and "]:" in hostport:
                    host, port = hostport.split("]:")
                    host = host[1:]
                else:
                    host, port = hostport.split(":")
                return host, int(port)
            return hostport, DEFAULT_PORT

        options.hosts = [splithost(host_str) for host_str in options.hosts.split(",")]
        if options.host != "localhost" or options.port != DEFAULT_PORT:
            options.hosts.append((options.host, options.port))

    runner_config = load_runner_conf()
    token = runner_config.get('base', 'token')

    readq = NonBlockingQueue(MAX_READQ_SIZE)
    global SENDER
    SENDER = Sender(token, readq, options, tags)
    SENDER.start()

    LOG.info('agent finish initializing, enter main loop.')
    main_loop(readq, options, {}, COLLECTORS)