示例#1
0
def daemonize_for_windows(profile, role, expires):
    pidfile = profile.pidfile
    with Daemonizer() as (is_setup, daemonizer):
        is_parent, profile, role, expires = daemonizer(
            pidfile, profile, role, expires
        )
        if not is_parent:
            logger = configFileLogger(profile.logfile, logging.INFO)
            logger.info('Starting refresh process for role %s' % role[1])
            # TODO add retries!
            while (True):
                retries = 0
                nap(expires, 0.9)

                while (True):
                    try:
                        saml, _ = refresh(
                            profile.ecp_endpoint_url,
                            profile.cookies,
                        )
                    except Exception as e:
                        retries += 1

                        if (retries < 4):
                            logger.info('Refresh failed: %s' % str(e))
                            nap(expires, 0.2)
                        else:
                            raise
                    else:
                        break

                profile_name = profile.name if profile.name else 'default'
                session = boto3.Session(profile=profile_name)
                client = boto3.client('sts')
                expires = save_sts_token(session, client, saml, role)
示例#2
0
def start(namespace=None):
    ''' Starts a Hypergolix daemon.
    '''
    with Daemonizer() as (is_setup, daemonizer):
        # Need these so that the second time around doesn't NameError
        user_id = None
        password = None
        pid_file = None
        parent_port = 7771
        homedir = None

        if is_setup:
            with Config() as config:
                user_id = config.user_id
                password = config.password
                # Convert the path to a str
                pid_file = str(config.pid_file)
                homedir = str(config.home_dir)

            if password is None:
                password = _request_password(user_id)

            print('Starting Hypergolix...')

        # Daemonize. Don't strip cmd-line arguments, or we won't know to
        # continue with startup
        is_parent, user_id, password = daemonizer(pid_file,
                                                  user_id,
                                                  password,
                                                  chdir=homedir)

        if is_parent:
            # Set up a logging server that we can print() to the terminal
            _startup_listener(port=parent_port, timeout=60)
            #####################
            # PARENT EXITS HERE #
            #####################

    # Daemonized child only from here on out.
    with _StartupReporter(parent_port) as startup_logger:
        # We need to set up a signal handler ASAP
        with Config() as config:
            pid_file = str(config.pid_file)
        sighandler = SignalHandler1(pid_file)
        sighandler.start()

        core = app_core(user_id, password, startup_logger)

        startup_logger.info('Hypergolix startup complete.')

    # Wait indefinitely until signal caught.
    # TODO: literally anything smarter than this.
    try:
        while True:
            time.sleep(.5)
    except SIGTERM:
        logger.info('Caught SIGTERM. Exiting.')

    del core
示例#3
0
文件: UIP.py 项目: vartika-arora/UIP
def main():
    """Main method of the UIP."""
    wallpaper = Wallpaper()
    settingsParser = ParseSettings()
    settings = settingsParser.settings
    pid_file = os.path.join(HOME_DIR, 'daemon-uip.pid')
    auto_flush(settings)
    if settings['error']:
        print("\nWRONG USAGE OF FLAGS, see --help")
        settingsParser.show_help()
        exit_UIP()
    if settings['service']:
        if 'start' == str(settings['service']):
            with Daemonizer() as (is_setup, daemonizer):
                if is_setup:
                    print("UIP will now run as a serice.")
                try:
                    daemonizer(pid_file)
                except SystemExit:
                    print("UIP service already, running "
                          "Close previous app by running UIP --service stop")
                    sys.exit(0)

        elif 'stop' == str(settings['service']):
            exit_UIP()
        else:
            print('Wrong option for service flag see --help')

    print("Hey this is UIP! you can use it to download"
          " images from reddit and also to schedule the setting of these"
          " images as your desktop wallpaper."
          " \nPress ctrl-c to exit")
    if settings['offline']:
        print("You have choosen to run UIP in offline mode.")
    if settings['flush']:
        flush_wallpapers(settings['pics-folder'])
    if not settings['offline']:
        print("UIP will now connect to internet and download images"
              " from reddit and unsplash.")
    if settings['ui']:
        from uiplib.gui.mainGui import MainWindow
        app = MainWindow(settings, wallpaper)
        app.run()
        exit_UIP()

    else:
        try:
            scheduler_object = Scheduler(
                settings['offline'], settings['pics-folder'],
                settings['timeout'], settings['website'],
                settings['no-of-images'],
                not (settings['service'] or settings['ui']), wallpaper)
            while True:  # To keep the program from closing.
                time.sleep(15)
        except KeyboardInterrupt:
            exit_UIP()
示例#4
0
def main():
    settingsParser = ParseSettings()
    settings = settingsParser.settings
    pid_file = os.path.join(HOME_DIR, 'daemon-uip.pid')
    if settings['service']:
        if 'start' == str(settings['service']):
            with Daemonizer() as (is_setup, daemonizer):
                if is_setup:
                    print("UIP will now run as a serice.")
                try:
                    is_parent = daemonizer(pid_file)
                except SystemExit:
                    print("UIP service already, running "
                          "Close previous app by running UIP --service stop")

        elif 'stop' == str(settings['service']):
            try:
                send(pid_file, SIGTERM)
                os.remove(pid_file)
                sys.exit(0)
            except Exception as e:
                print("you need to start a service first", str(e))
                sys.exit(0)
        else:
            print('Wrong option for service flag see --help')

    print("Hey this is UIP! you can use it to download"
          " images from reddit and also to schedule the setting of these"
          " images as your desktop wallpaper."
          " \nPress ctrl-c to exit")
    try:
        if settings['error']:
            print("\nWRONG USAGE OF FLAGS --no-of-images AND --offline")
            settingsParser.show_help()
            sys.exit(0)
        if settings['offline']:
            print("You have choosen to run UIP in offline mode.")
        if settings['flush']:
            print("Deleting all downloaded wallpapers...")
            try:
                shutil.rmtree(settings['pics-folder'])
                os.mkdir(settings['pics-folder'])
            except FileNotFoundError:
                pass
        if not settings['offline']:
            print("UIP will now connect to internet and download images"
                  " from reddit and unsplash.")
        scheduler(settings['offline'], settings['pics-folder'],
                  settings['timeout'], settings['website'],
                  settings['no-of-images'])
    except KeyboardInterrupt:
        print("Exiting UIP hope you had a nice time :)")
        sys.exit(0)
示例#5
0
文件: UIP.py 项目: DarkSouL11/UIP
def main():
    """Main method of the UIP."""
    settingsParser = ParseSettings()
    settings = settingsParser.settings
    pid_file = os.path.join(HOME_DIR, 'daemon-uip.pid')
    if settings['error']:
        print("\nWRONG USAGE OF FLAGS, see --help")
        settingsParser.show_help()
        exit_UIP()
    if settings['service']:
        if 'start' == str(settings['service']):
            with Daemonizer() as (is_setup, daemonizer):
                if is_setup:
                    print("UIP will now run as a serice.")
                try:
                    is_parent = daemonizer(pid_file)
                except SystemExit:
                    print("UIP service already, running "
                          "Close previous app by running UIP --service stop")
                    sys.exit(0)

        elif 'stop' == str(settings['service']):
            exit_UIP()
        else:
            print('Wrong option for service flag see --help')

    print("Hey this is UIP! you can use it to download"
          " images from reddit and also to schedule the setting of these"
          " images as your desktop wallpaper."
          " \nPress ctrl-c to exit")
    try:
        if settings['offline']:
            print("You have choosen to run UIP in offline mode.")
        if settings['flush']:
            print("Deleting all downloaded wallpapers...")
            try:
                shutil.rmtree(settings['pics-folder'])
                make_dir(settings['pics-folder'])
            except FileNotFoundError:
                pass
        if not settings['offline']:
            print("UIP will now connect to internet and download images"
                  " from reddit and unsplash.")
        if settings['ui']:
            from uiplib.gui.mainGui import MainWindow
            app = MainWindow(settings)
            app.run()
            exit_UIP()
        scheduler(settings['offline'], settings['pics-folder'],
                  settings['timeout'], settings['website'],
                  settings['no-of-images'], settings['service'])
    except KeyboardInterrupt:
        exit_UIP()
示例#6
0
def watch(daemon):
    """
    Watches for figures.
    """
    if daemon:
        with Daemonizer() as (is_setup, daemonizer):
            is_parent = daemonizer(str(pid_file))
            if is_parent:
                log.info("parent will done")
        log.info("Watching figures.")
        watch_daemon()
    else:
        log.info("Watching figures.")
        watch_daemon()
def daemonize(profile: Profile, session: Session, client: Client, role: Role,
              expires: datetime) -> bool:
    with Daemonizer() as (is_setup, daemonizer):
        is_parent, profile, session, client, role, expires = daemonizer(
            profile.pidfile,
            profile,
            session,
            client,
            role,
            expires,
        )

        if not is_parent:
            sighandler = SignalHandler1(profile.pidfile)
            sighandler.start()

            logger = configFileLogger(profile.logfile, logging.INFO)
            logger.info('Startig refresh process for role %s' % role[1])

            while (True):
                try:
                    retries = 0
                    nap(expires, 0.9, profile.refresh)

                    while (True):
                        try:
                            saml, _ = refresh(
                                profile.ecp_endpoint_url,
                                profile.cookies,
                            )
                        except Exception as e:
                            retries += 1

                            if (retries < 4):
                                logger.info('Refresh failed: %s' % str(e))
                                nap(expires, 0.2, profile.refresh * 0.2)
                            else:
                                raise
                        else:
                            break

                    expires = save_sts_token(session, client, saml, role)
                except SIGINT:
                    pass

        return is_parent
示例#8
0
def main():
    pid_file = 'Communicator.pid'
    number = 1

    with Daemonizer() as (is_setup, daemonizer):
        if is_setup:
            pass

        is_parent, *args = daemonizer(pid_file, 1000)

        if is_parent:
            pass

    with open('test.txt', 'w') as file:
        while number <= args[0]:
            print(number)
            file.write(f'{number}\n')

            number += 1
示例#9
0
    def run(cls, role, console, **kwargs):
        sys.stderr = open(os.devnull, "w")
        cls.logger = logging.getLogger("gfl")
        with Daemonizer() as (is_setup, daemonizer):
            main_pid = None
            if is_setup:
                main_pid = os.getpid()
            pid_file = PathUtils.join(GflConf.home_dir, "proc.lock")
            stdout_file = PathUtils.join(GflConf.logs_dir, "console_out")
            stderr_file = PathUtils.join(GflConf.logs_dir, "console_err")
            is_parent = daemonizer(pid_file,
                                   stdout_goto=stdout_file,
                                   stderr_goto=stderr_file)
            if is_parent:
                if console and main_pid == os.getpid():
                    Shell.startup()

        GflNode.load_node()

        if GflConf.get_property("net.mode") == "standalone":
            client_number = GflConf.get_property(
                "net.standalone.client_number")
            for _ in range(len(GflNode.standalone_nodes), client_number):
                GflNode.add_standalone_node()

            ManagerHolder.default_manager = NodeManager(
                node=GflNode.default_node, role="server")

            for i in range(client_number):
                client_manager = NodeManager(node=GflNode.standalone_nodes[i],
                                             role="client")
                ManagerHolder.standalone_managers.append(client_manager)
        else:
            ManagerHolder.default_manager = NodeManager(
                node=GflNode.default_node, role=role)

        # cls.__startup_node_managers()
        HttpListener.start()

        while HttpListener.is_alive():
            time.sleep(2)
示例#10
0
    def run(cls, console=True, **kwargs):
        sys.stderr = open(os.devnull, "w")
        cls.logger = logging.getLogger("gfl")
        with Daemonizer() as (is_setup, daemonizer):
            main_pid = None
            if is_setup:
                main_pid = os.getpid()
            pid_file = PathUtils.join(GflConf.home_dir, "proc.lock")
            stdout_file = PathUtils.join(GflConf.logs_dir, "console_out")
            stderr_file = PathUtils.join(GflConf.logs_dir, "console_err")
            is_parent = daemonizer(pid_file,
                                   stdout_goto=stdout_file,
                                   stderr_goto=stderr_file)
            if is_parent:
                if console and main_pid == os.getpid():
                    Shell.startup()

        GflNode.load_node()

        HttpListener.start()

        NodeManager.get_instance().run()
示例#11
0
    def run(cls, **kwargs):
        daemon = kwargs.pop("daemon", False)
        if daemon:
            print("DAEMON")
            with Daemonizer() as (is_setup, daemonizer):
                if is_setup:
                    pass
                pid_file = "proc.lock"
                stdout_file = PathUtils.join(GflConf.logs_dir, "console_out")
                stderr_file = PathUtils.join(GflConf.logs_dir, "console_err")
                is_parent = daemonizer(pid_file,
                                       stdout_goto=stdout_file,
                                       stderr_goto=stderr_file)
                if is_parent:
                    pass

        GflConf.reload()
        GflNode.load_node()

        if GflConf.get_property("standalone.enabled"):
            server_number = GflConf.get_property("standalone.server_number")
            client_number = GflConf.get_property("standalone.client_number")
            for _ in range(len(GflNode.standalone_nodes),
                           server_number + client_number):
                GflNode.add_standalone_node()
            for i in range(0, server_number):
                node_manager = NodeManager(node=GflNode.standalone_nodes[i],
                                           role="server")
                cls.node_managers.append(node_manager)
            for i in range(server_number, server_number + client_number):
                node_manager = NodeManager(node=GflNode.standalone_nodes[i],
                                           role="client")
                cls.node_managers.append(node_manager)
        else:
            role = kwargs.pop("role")
            print(role)
            node_manager = NodeManager(node=GflNode.default_node, role=role)
            cls.node_managers.append(node_manager)
        cls.__startup_node_managers()
示例#12
0
from daemoniker import Daemonizer

with Daemonizer() as (is_setup, daemonizer):
    pid_file = './awrtest_messages_daemon.pid'
    daemonizer(pid_file)

# In daemon
from persistqueue import Queue
import requests
from requests.exceptions import HTTPError
import random
import json
import time
from datetime import datetime, timedelta

q = Queue("messages")


def send_message(message):
    sent = False
    try:
        response = requests.post(
            'https://213.219.214.58/api/message/create/',
            verify='server.crt',
            cert='client.crt',
            data={
                'data': json.dumps({
                    'id': 'FG3f4h7t973h4g5b3498h',
                    'time': message['time'],
                    'value': message['value'],
                })
示例#13
0
def start(namespace=None):
    ''' Starts a Hypergolix daemon.
    '''
    # Command args coming in.
    if namespace is not None:
        host = namespace.host
        port = namespace.port
        debug = namespace.debug
        traceur = namespace.traceur
        chdir = namespace.chdir
        # Convert log dir to absolute if defined
        if namespace.logdir is not None:
            log_dir = str(pathlib.Path(namespace.logdir).absolute())
        else:
            log_dir = namespace.log_dir
        # Convert cache dir to absolute if defined
        if namespace.cachedir is not None:
            cache_dir = str(pathlib.Path(namespace.cachedir).absolute())
        else:
            cache_dir = namespace.cache_dir
        verbosity = namespace.verbosity
        # Convert pid path to absolute (must be defined)
        pid_path = str(pathlib.Path(namespace.pidfile).absolute())

    # Daemonizing, we still need these to be defined to avoid NameErrors
    else:
        host = None
        port = None
        debug = None
        traceur = None
        chdir = None
        log_dir = None
        cache_dir = None
        verbosity = None
        pid_path = None

    with Daemonizer() as (is_setup, daemonizer):
        # Daemonize. Don't strip cmd-line arguments, or we won't know to
        # continue with startup
        (
            is_parent, host, port, debug, traceur, log_dir, cache_dir,
            verbosity, pid_path
        ) = daemonizer(
            pid_path,
            host,
            port,
            debug,
            traceur,
            log_dir,
            cache_dir,
            verbosity,
            pid_path,
            chdir=chdir,
            # Don't strip these, because otherwise we won't know to resume
            # daemonization
            strip_cmd_args=False)

        if not is_parent:
            # Do signal handling within the Daemonizer so that the parent knows
            # it was correctly init'd
            sighandler = SignalHandler1(pid_path)
            sighandler.start()

        #####################
        # PARENT EXITS HERE #
        #####################

    verbosity = _cast_verbosity(verbosity, debug, traceur)

    if log_dir is not None:
        logutils.autoconfig(tofile=True,
                            logdirname=log_dir,
                            logname='hgxremote',
                            loglevel=verbosity)

    logger.debug('Starting remote persistence server...')
    host = _cast_host(host)
    remote, server = _hgx_server(host, port, cache_dir, debug, traceur)
    logger.info('Remote persistence server successfully started.')

    # Wait indefinitely until signal caught.
    # TODO: literally anything smarter than this.
    try:
        while True:
            time.sleep(.5)
    except SIGTERM:
        logger.info('Caught SIGTERM. Exiting.')

    del remote
    del server