Esempio n. 1
0
    def __init__(self,
                 home=None,
                 version=None,
                 server=None,
                 memory=None,
                 jmx=None,
                 prop=None,
                 option=None):
        # constraints
        assert home is not None and os.path.isabs(
            home), 'java.home is required and must be an absolute path'
        assert version is not None, 'java.version is required'

        # TODO: check value types and format
        assert prop is None or isinstance(prop,
                                          dict), 'java.prop must be a dict'
        assert option is None or isinstance(option,
                                            list), 'java.option must be a list'

        CaseClass.__init__(
            self,
            ('home', home),
            ('version', version),
            ('server', server),
            ('memory', JavaSetting.Memory(version, **oget(memory, {}))),
            ('jmx', JavaSetting.JMX(**oget(jmx, {}))),
            ('prop', oget(prop, {})),
            ('option', oget(option, [])),
        )
Esempio n. 2
0
 def __init__(self,
              config_path=None,
              extra_args=None,
              dry_run=False,
              debug=False,
              app_setting=None,
              java_setting=None,
              log_setting=None,
              os_setting=None,
              pre_commands=None,
              post_commands=None):
     """
     :param config_path:
     :param extra_args: arguments for Java application
     :param dry_run:
     :param debug: debug mode if true
     :param app_setting:
     :param java_setting:
     :param log_setting:
     :param os_setting:
     :param pre_commands:
     :param post_commands:
     :return:
     """
     CaseClass.__init__(self, ('config_path', config_path),
                        ('extra_args', oget(extra_args, [])),
                        ('dry_run', dry_run), ('debug', debug),
                        ('app_setting', app_setting),
                        ('java_setting', java_setting),
                        ('log_setting', log_setting),
                        ('os_setting', os_setting),
                        ('pre_commands', oget(pre_commands, [])),
                        ('post_commands', oget(post_commands, [])))
Esempio n. 3
0
    def __init__(self,
                 home=None,
                 version=None,
                 server=None,
                 memory=None,
                 jmx=None,
                 prop=None,
                 option=None):
        # constraints
        assert home is not None and os.path.isabs(home), 'java.home is required and must be an absolute path'
        assert version is not None, 'java.version is required'

        # TODO: check value types and format
        assert prop is None or isinstance(prop, dict), 'java.prop must be a dict'
        assert option is None or isinstance(option, list), 'java.option must be a list'

        CaseClass.__init__(
            self,
            ('home', home),
            ('version', version),
            ('server', server),
            ('memory', JavaSetting.Memory(version, **oget(memory, {}))),
            ('jmx', JavaSetting.JMX(**oget(jmx, {}))),
            ('prop', oget(prop, {})),
            ('option', oget(option, [])),
        )
Esempio n. 4
0
 def __init__(self, home, console=None, gc=None, dump=None, error=None):
     CaseClass.__init__(
         self,
         ('console', LogSetting.Console(home, **oget(console, {}))),
         ('gc', LogSetting.GC(home, **oget(gc, {}))),
         ('dump', LogSetting.Dump(home, **oget(dump, {}))),
         ('error', LogSetting.Error(home, **oget(error, {}))),
     )
Esempio n. 5
0
 def __init__(self, home, console=None, gc=None, dump=None, error=None):
     CaseClass.__init__(
         self,
         ('console', LogSetting.Console(home, **oget(console, {}))),
         ('gc', LogSetting.GC(home, **oget(gc, {}))),
         ('dump', LogSetting.Dump(home, **oget(dump, {}))),
         ('error', LogSetting.Error(home, **oget(error, {}))),
     )
Esempio n. 6
0
 def to_format(self, format_):
     return (
         format_
         .replace('%D', self.start_time.to_long_summary())
         .replace('%T', self.str_time_range())
         .replace('%S', self.summary)
         .replace('%C', oget(omap(lambda s: ' (%s)' % s, self.str_creator()), ''))
         .replace('%L', oget(omap(lambda s: ' @%s' % s, self.location), ''))
     )
Esempio n. 7
0
    def to_format(self, format_):

        return (
            format_
            .replace('%I', self.event_id if not None else "")
            .replace('%Ds', self.start_time.to_long_summary())
            .replace('%De', self.end_time.to_long_summary())
            .replace('%D', self.start_time.to_long_summary())
            .replace('%Ts', self.start_time.to_short_summary() if self.start_time.has_time else "00:00")
            .replace('%Te', self.end_time.to_short_summary() if self.end_time.has_time else "00:00")
            .replace('%T', self.str_time_range())
            .replace('%S', self.summary)
            .replace('%C', oget(omap(lambda s: '(%s)' % s, self.str_creator()), ''))
            .replace('%L', oget(omap(lambda s: '@%s' % s, self.location), ''))
        )
Esempio n. 8
0
 def to_dict(self):
     if self.has_time:
         d = {'dateTime': self.datetime_tz.isoformat()}
     else:
         d = {'date': self.datetime_tz.date().isoformat()}
     d.update(oget(omap(lambda tz: {'timeZone': str(tz)}, self.datetime_tz.tzinfo), {}))
     return d
Esempio n. 9
0
 def to_dict(self):
     if self.has_time:
         d = {'dateTime': self.datetime_tz.isoformat()}
     else:
         d = {'date': self.datetime_tz.date().isoformat()}
     d.update(oget(omap(lambda tz: {'timeZone': str(tz)}, self.datetime_tz.tzinfo), {}))
     return d
Esempio n. 10
0
    def __init__(self, user=None, env=None):
        # constraints
        assert user is not None, 'os.user is required'
        assert isinstance(user, six.string_types), 'os.user must be a string'
        assert env is None or isinstance(env, dict), 'os.env must be a dict'

        d = dict((k, str(v)) for k, v in oget(env, {}).items())
        CaseClass.__init__(self, ('user', user), ('env', d))
Esempio n. 11
0
    def _execute_application(self, now):
        if self.failed:
            return self

        failed = False
        self.logger.info(
            '%s started: config=%s, args=%s' % (
                self.setting.app_setting.name, self.setting.config_path, self.setting.extra_args))

        time_start = time.time()
        if self.setting.dry_run:
            print('Would execute: cwd=%s, cmd=[\n%s\n], env={\n%s\n}, output=%s' % (
                self.setting.app_setting.home,
                '\n'.join('  %s' % s for s in self.setting.get_args(now)),
                '\n'.join('  %s: %s' % kv for kv in self.setting.get_environ(now).items()),
                oget(self.setting.log_setting.console.get_path(now), 'stdout')
            ))
            ret = 0
        else:
            out_path = self.setting.log_setting.console.get_path(now)
            if out_path is None:
                stdout = sys.stdout
                stderr = sys.stderr
            else:
                stdout = get_console_logger(
                    out_path,
                    self.setting.log_setting.console.max_size.bytes(),
                    self.setting.log_setting.console.backup)
                stderr = stdout
            ret = execute_command_with_pid(
                self.setting.get_args(now),
                self.setting.app_setting.pid_file,
                shell=False,
                cwd=self.setting.app_setting.home,
                env=dict(os.environ, **(oget(self.setting.get_environ(now), {}))),
                stdin=sys.stdin, stdout=stdout, stderr=stderr)

        elapsed = time.time() - time_start

        if ret == 0:
            self.logger.info('%s ended successfully: elapsed=%ds' % (self.setting.app_setting.name, elapsed))
        else:
            self.logger.error(
                '%s ended with error: return_code=%d, elapsed=%ds' % (self.setting.app_setting.name, ret, elapsed))
            failed = True
        return self.copy(failed=failed)
Esempio n. 12
0
    def __init__(self, user=None, env=None):
        # constraints
        assert user is not None, "os.user is required"
        assert isinstance(user, six.string_types), "os.user must be a string"
        assert env is None or isinstance(env, dict), "os.env must be a dict"

        d = dict((k, str(v)) for k, v in oget(env, {}).items())
        CaseClass.__init__(self, ("user", user), ("env", d))
Esempio n. 13
0
    def parse_args(self, argv):
        assert self.now is not None

        # decode all args as utf-8
        option, args = arg_parser.parser.parse_args(
            [to_unicode(a, errors='ignore') for a in argv[1:]])

        try:
            if not args:
                # summary
                dt = oget(self._parse_date(option.date, self.now),
                          self.now.date())
                start_time = get_localzone().localize(
                    datetime(dt.year, dt.month, dt.day))

                fmt = (option.format
                       or (arg_parser.DEFAULT_FORMAT if option.days == 0 else
                           arg_parser.DEFAULT_FORMAT_DAYS))

                if option.days == 0:
                    # show events on one day
                    duration = timedelta(days=1)
                elif option.days < 0:
                    # show events from past several days
                    duration = timedelta(days=-option.days + 1)
                    start_time -= timedelta(days=-option.days)
                else:
                    # show events from several days from today
                    duration = timedelta(days=option.days + 1)

                operation = SummaryOperation(option.calendar, start_time,
                                             duration, option.credential, fmt,
                                             option.separator)
            elif args[0] == 'setup' and len(args) == 2:
                # setup
                operation = SetupOperation(args[1], option.credential,
                                           option.read_only, option.no_browser)
            elif args[0] == 'create' and len(args) >= 2:
                # create
                summary = ' '.join(args[1:])
                start, end = self._parse_time_range(option.date,
                                                    option.start_time,
                                                    option.end_time, self.now)
                ev = Event(start, end, summary, location=option.location)
                operation = CreateOperation(option.calendar, ev,
                                            option.credential)
            else:
                # help
                operation = HelpOperation()
        except Exception as e:
            # parse error
            operation = HelpOperation(e)
            if option.debug:
                import traceback
                traceback.print_exc()
                print()

        return self.copy(operation=operation, debug=option.debug)
Esempio n. 14
0
    def __init__(self,
                 timer_sec=None,
                 say_enabled=None,
                 say_cmd=None,
                 say_countdown_sec=None,
                 say_periodic_min=None,
                 say_specific_min=None,
                 lang=None,
                 i18n=None,
                 stdin=None,
                 stdout=None,
                 stderr=None):
        lang_setting = oget(lang, self._find_lang())

        CaseClass.__init__(
            self, ('timer_sec', timer_sec), ('say_enabled', say_enabled),
            ('say_cmd', say_cmd),
            ('say_countdown_sec',
             oget(say_countdown_sec, DEFAULT_SAY_COUNTDOWN_SEC)),
            ('say_periodic_min',
             oget(say_periodic_min, DEFAULT_SAY_PERIODIC_MIN)),
            ('say_specific_min',
             oget(say_specific_min, DEFAULT_SAY_SPECIFIC_MIN)),
            ('lang', lang_setting), ('i18n', self._find_i18n(lang_setting)),
            ('stdin', oget(stdin, sys.stdin)),
            ('stdout', oget(stdout, sys.stdout)),
            ('stderr', oget(stderr, sys.stderr)))
Esempio n. 15
0
def __convert_env(env, encoding):
    """Environment variables should be bytes not unicode on Windows."""
    d = dict(os.environ, **(oget(env, {})))

    # workaround for Windows+Python3 environment
    if not SHOULD_NOT_ENCODE_ARGS:
        return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())
    else:
        return d
Esempio n. 16
0
 def formatted(self):
     buf = [
         '- cmd: %s' % self.cmd,
         '  cwd: %s' % oget(self.meta.work_dir, os.path.abspath(os.path.curdir)),
     ]
     if self.meta.env:
         buf.append('  env: {%s}' % ', '.join('%s: %s' % (k, v) for k, v in sorted(self.meta.env.items())))
     if self.meta.lock:
         buf.append('  lock: True')
     return '\n'.join(buf)
Esempio n. 17
0
def __convert_env(env, encoding):
    """Environment variables should be bytes not unicode on Windows."""
    d = dict(os.environ, **(oget(env, {})))

    # workaround for Windows+Python3 environment
    if not SHOULD_NOT_ENCODE_ARGS:
        return dict(
            (k.encode(encoding), v.encode(encoding)) for k, v in d.items())
    else:
        return d
Esempio n. 18
0
 def formatted(self):
     buf = [
         '- cmd: %s' % self.cmd,
         '  cwd: %s' %
         oget(self.meta.work_dir, os.path.abspath(os.path.curdir)),
     ]
     if self.meta.env:
         buf.append('  env: {%s}' %
                    ', '.join('%s: %s' % (k, v)
                              for k, v in sorted(self.meta.env.items())))
     if self.meta.lock:
         buf.append('  lock: True')
     return '\n'.join(buf)
Esempio n. 19
0
    def __init__(self, config_path=None, work_dir=None, root_menu=None, encoding=None, lang=None, width=None,
                 clear_cache=False, cache_dir=EVAL_CACHE_DIR, pid_dir=COMMAND_PID_DIR,
                 stdin=None, stdout=None, stderr=None, getch_enabled=True, source_enabled=True):
        is_url = Loader.is_url(config_path)
        work_dir = omap(lambda s: to_unicode(s, encoding), self._search_work_dir(work_dir, config_path, is_url))

        CaseClass.__init__(self,
                           ('config_path', config_path),
                           ('work_dir', work_dir),
                           ('root_menu', oget(root_menu, {})),
                           ('encoding', encoding),
                           ('lang', self._find_lang(lang)),
                           ('width', width),
                           ('clear_cache', clear_cache),
                           ('cache_dir', cache_dir),
                           ('pid_dir', pid_dir),
                           ('stdin', oget(stdin, sys.stdin)),
                           ('stdout', oget(stdout, sys.stdout)),
                           ('stderr', oget(stderr, sys.stderr)),
                           ('getch_enabled', getch_enabled),
                           ('source_enabled', source_enabled)
                           )
Esempio n. 20
0
 def __init__(self,
              config_path=None,
              extra_args=None,
              dry_run=False,
              debug=False,
              app_setting=None,
              java_setting=None,
              log_setting=None,
              os_setting=None,
              pre_commands=None,
              post_commands=None):
     """
     :param config_path:
     :param extra_args: arguments for Java application
     :param dry_run:
     :param debug: debug mode if true
     :param app_setting:
     :param java_setting:
     :param log_setting:
     :param os_setting:
     :param pre_commands:
     :param post_commands:
     :return:
     """
     CaseClass.__init__(
         self,
         ('config_path', config_path),
         ('extra_args', oget(extra_args, [])),
         ('dry_run', dry_run),
         ('debug', debug),
         ('app_setting', app_setting),
         ('java_setting', java_setting),
         ('log_setting', log_setting),
         ('os_setting', os_setting),
         ('pre_commands', oget(pre_commands, [])),
         ('post_commands', oget(post_commands, []))
     )
Esempio n. 21
0
    def parse_args(self, argv):
        assert self.now is not None

        # decode all args as utf-8
        option, args = arg_parser.parser.parse_args([to_unicode(a, errors='ignore') for a in argv[1:]])

        try:
            if not args:
                # summary
                dt = oget(self._parse_date(option.date, self.now), self.now.date())
                start_time = get_localzone().localize(datetime(dt.year, dt.month, dt.day))

                fmt = (option.format or
                       (arg_parser.DEFAULT_FORMAT if option.days == 0 else arg_parser.DEFAULT_FORMAT_DAYS))

                if option.days == 0:
                    # show events on one day
                    duration = timedelta(days=1)
                elif option.days < 0:
                    # show events from past several days
                    duration = timedelta(days=-option.days + 1)
                    start_time -= timedelta(days=-option.days)
                else:
                    # show events from several days from today
                    duration = timedelta(days=option.days + 1)

                operation = SummaryOperation(option.calendar, start_time, duration,
                                             option.credential, fmt, option.separator)
            elif args[0] == 'setup' and len(args) == 2:
                # setup
                operation = SetupOperation(args[1], option.credential, option.read_only, option.no_browser)
            elif args[0] == 'create' and len(args) >= 2:
                # create
                summary = ' '.join(args[1:])
                start, end = self._parse_time_range(option.date, option.start_time, option.end_time, self.now)
                ev = Event(start, end, summary, location=option.location)
                operation = CreateOperation(option.calendar, ev, option.credential)
            else:
                # help
                operation = HelpOperation()
        except Exception as e:
            # parse error
            operation = HelpOperation(e)
            if option.debug:
                import traceback
                traceback.print_exc()
                print()

        return self.copy(operation=operation, debug=option.debug)
Esempio n. 22
0
 def str_creator(self):
     return omap(lambda s: '%s' % s, oget(self.creator_name, self.creator_email))
Esempio n. 23
0
 def str_time_range(self):
     s = ozip(self.start_time.to_short_summary(), self.end_time.to_short_summary())
     return oget(omap('-'.join, s), MSG_ALL_DAY)
Esempio n. 24
0
 def test_oget(self):
     self.assertEqual(oget(123), 123)
     self.assertEqual(oget(None), None)
     self.assertEqual(oget(123, 45), 123)
     self.assertEqual(oget(None, 45), 45)
Esempio n. 25
0
 def str_creator(self):
     return omap(lambda s: '%s' % s, oget(self.creator_name, self.creator_email))
Esempio n. 26
0
 def str_time_range(self):
     s = ozip(self.start_time.to_short_summary(), self.end_time.to_short_summary())
     return oget(omap('-'.join, s), MSG_ALL_DAY)