Exemplo n.º 1
0
    def run(self, args):
        parser = argparse.ArgumentParser(
            prog="%s cloc" % sys.argv[0].split(os.path.sep)[-1],
            description=textwrap.dedent(self.__doc__),
            formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument('--database',
                            '-d',
                            dest="database",
                            help="Database name")
        parser.add_argument('--path',
                            '-p',
                            action='append',
                            help="File or directory path")
        parser.add_argument('--verbose', '-v', action='count', default=0)
        opt, unknown = parser.parse_known_args(args)
        if not opt.database and not opt.path:
            parser.print_help()
            sys.exit()

        c = cloc.Cloc()
        if opt.database:
            config.parse_config(['-d', opt.database] + unknown)
            c.count_database(opt.database)
        if opt.path:
            for i in opt.path:
                c.count_path(i)
        c.report(opt.verbose)
Exemplo n.º 2
0
Arquivo: ci.py Projeto: initOS/dob-lib
    def test(self, args=None):
        """ Run tests """
        if not args:
            args = []

        if not self._init_odoo():
            return False

        # pylint: disable=C0415,E0401
        import odoo
        from odoo.tools import config

        # Append needed parameter
        if self.get(base.SECTION, "coverage"):
            for path in self.get("odoo", "addons_path", default=[]):
                args.extend([f"--cov={path}", path])

            args += ["--cov-report=html", "--cov-report=term"]

        # Load the odoo configuration
        with self._manage():
            config.parse_config(["-c", base.ODOO_CONFIG])
            odoo.cli.server.report_configuration()
            # Pass the arguments to pytest
            sys.argv = sys.argv[:1] + args
            result = pytest.main()
            if result and result != pytest.ExitCode.NO_TESTS_COLLECTED:
                return result

            return 0
Exemplo n.º 3
0
def main(starter, conf, version=None, just_test=False,
         server_wide_modules=None,
         gevent_script_path=None):
    """Call the `starter` script, dispatching configuration.

    All arguments are set in the standalone script produced by buildout through
    entry point options.

    :param starter: path to the main script source file (currently
      ``openerp-server``)
    :param conf: path to the Odoo configuration file (managed by the recipe)
    :param version: Odoo major version
    :param server_wide_modules: additional server wide modules, to pass with
       the ``--load`` command-line option (ignored if the option is actually
       there on the command line)
    :type version: tuple of integers
    :param just_test: if True, only run unit tests
    """
    arguments = ['-c', conf]

    if just_test:
        arguments.extend(('--log-level',
                          'test' if version >= (6, 0) else 'info',
                          '--stop-after-init'))

        if version >= (7, 0):
            arguments.append('--test-enable')

    if server_wide_modules:
        for opt in sys.argv[1:]:
            if opt.startswith('--load'):
                break
        else:
            arguments.append('--load=' + ','.join(server_wide_modules))

    if '--install-all' in sys.argv:
        sys.argv.remove('--install-all')
        from odoo.tools import config
        # Maybe we should preparse config in all cases and therefore avoid
        # adding the '-c' on the fly ?
        # Still, cautious about pre-6.1 versions
        config.parse_config(['-c', conf])
        from odoo.modules import get_modules
        arguments.extend(('-i', ','.join(get_modules())))

    insert_args(arguments)

    if version >= (8, 0):  # always true in a.r.odoo, but keeping for now
        assert gevent_script_path is not None
        patch_odoo.do_patch(gevent_script_path)

    os.chdir(os.path.split(starter)[0])
    glob = globals()
    glob['__name__'] = '__main__'
    glob['__file__'] = starter
    sys.argv[0] = starter
    try:
        execfile(starter, globals())
    except SystemExit as exc:
        return exc.code
Exemplo n.º 4
0
    def __init__(self, conffile, buildout_dir, parse_config=True):
        self.buildout_dir = buildout_dir
        self.openerp_config_file = conffile

        self._registry = self.cr = None
        if parse_config:
            config.parse_config(['-c', conffile])
Exemplo n.º 5
0
    def apply_action(self, args=None):
        """ Apply in the configuration defined actions on the database """
        actions = self.get("actions", default={})
        args, _ = load_action_arguments(args or [], list(actions))

        if not self._init_odoo():
            return

        # pylint: disable=C0415,E0401
        import odoo
        from odoo.tools import config

        # Load the Odoo configuration
        config.parse_config(["-c", base.ODOO_CONFIG])
        odoo.cli.server.report_configuration()

        db_name = config["db_name"]

        utils.info(f"Running {args.action}")
        with self._manage():
            with self.env(db_name) as env:
                for name, item in actions[args.action].items():
                    utils.info(f"{args.action.capitalize()} {name}")
                    model = item.get("model")
                    if not isinstance(model, str):
                        utils.error("Model must be string")
                        continue

                    domain = item.get("domain", [])
                    if not isinstance(domain, list):
                        utils.error("Domain must be list")
                        continue

                    ctx = env.context.copy()
                    ctx.update(item.get("context") or {})
                    action_env = odoo.api.Environment(env.cr, env.uid, ctx)

                    act = item.get("action", "update")
                    if act == "update":
                        self._action_update(action_env, model, domain, item)
                    elif act == "delete":
                        self._action_delete(action_env, model, domain, item)
                    elif act == "insert":
                        self._action_insert(action_env, model, domain, item)
                    else:
                        utils.error(f"Undefined action {act}")
Exemplo n.º 6
0
 def init(self, args):
     config.parse_config(args)
     odoo.cli.server.report_configuration()
     odoo.service.server.start(preload=[], stop=True)
     signal.signal(signal.SIGINT, raise_keyboard_interrupt)
Exemplo n.º 7
0
def main(ctx, database_url, database_maxconn, redis_url, redis_maxconn,
         aws_access_key_id, aws_secret_access_key, aws_region, s3_bucket,
         s3_endpoint_url, s3_custom_domain, s3_addressing_style, addons,
         tmp_dir, debug, ptvsd_url, statsd_host):

    # Setup logger first, then import further modules
    import odooku.logger
    odooku.logger.setup(debug=debug, statsd_host=statsd_host)

    logger = logging.getLogger(__name__)

    from odooku.backends import register_backend
    from odooku.backends.s3 import S3Backend
    from odooku.backends.redis import RedisBackend

    # Setup S3
    if s3_bucket:
        register_backend(
            's3',
            S3Backend(
                bucket=s3_bucket,
                aws_access_key_id=aws_access_key_id,
                aws_secret_access_key=aws_secret_access_key,
                aws_region=aws_region,
                endpoint_url=s3_endpoint_url,
                custom_domain=s3_custom_domain,
                addressing_style=s3_addressing_style,
            ))

    # Setup Redis
    if redis_url:
        redis_url = urlparse.urlparse(redis_url)
        register_backend(
            'redis',
            RedisBackend(
                host=redis_url.hostname,
                port=redis_url.port,
                password=redis_url.password,
                db_number=redis_url.path[1:] if redis_url.path else None,
                maxconn=redis_maxconn))

    # Setup PTVSD
    if ptvsd_url:
        if ptvsd:
            ptvsd_url = urlparse.urlparse(ptvsd_url)
            ptvsd.enable_attach(ptvsd_url.password,
                                address=(ptvsd_url.hostname, ptvsd_url.port))
            logger.warning("PTVSD Enabled")
        else:
            logger.warning("PTVSD_URL configured but PTVSD not found.")

    # Setup Odoo
    import odoo
    from odoo.tools import config

    # Always account for multiple processes:
    # - we can run multiple dyno's consisting of:
    #    - web
    #    - worker
    odoo.multi_process = True

    # Patch odoo config
    config.parse_config()
    config['data_dir'] = tmp_dir
    config['addons_path'] = addons
    config['demo'] = {}
    config['without_demo'] = 'all'
    config['debug_mode'] = debug

    if database_url:
        database_url = urlparse.urlparse(database_url)
        db_name = database_url.path[1:] if database_url.path else False
        config['db_name'] = db_name
        config['db_user'] = database_url.username
        config['db_password'] = database_url.password
        config['db_host'] = database_url.hostname
        config['db_port'] = database_url.port
        config['db_maxconn'] = database_maxconn
        config['list_db'] = not bool(db_name)
    else:
        params.no_db = True

    ctx.obj.update({
        'debug': debug,
        'config': config,
        'params': params,
        'logger': logger
    })
Exemplo n.º 8
0
    def update(self, args=None):
        """ Install/update Odoo modules """
        args, _ = load_update_arguments(args or [])

        self.generate_config()

        if not self._init_odoo():
            return

        # pylint: disable=C0415,E0401
        import odoo
        from odoo.tools import config

        # Load the Odoo configuration
        config.parse_config(["-c", base.ODOO_CONFIG])
        odoo.cli.server.report_configuration()

        db_name = config["db_name"]
        with self._manage():
            # Ensure that the database is initialized
            db = odoo.sql_db.db_connect(db_name)
            initialized = False
            with closing(db.cursor()) as cr:
                if not odoo.modules.db.is_initialized(cr):
                    utils.info("Initializing the database")
                    odoo.modules.db.initialize(cr)
                    cr.commit()
                    initialized = True

            # Execute the pre install script
            self._run_migration(db_name, "pre_install")

            # Get the modules to install
            if initialized:
                uninstalled = self.get_modules()
            else:
                installed = self.get_installed_modules(db_name)
                modules = self.get_modules()
                uninstalled = modules.difference(installed)

            # Install all modules
            utils.info("Installing all modules")
            if uninstalled:
                self.install_all(db_name, uninstalled)

            # Execute the pre update script
            self._run_migration(db_name, "pre_update")

            # Update all modules which aren't installed before
            if args.modules:
                self.update_all(db_name, args.modules)
            elif args.listed:
                self.update_listed(db_name, uninstalled)
            elif args.all:
                self.update_all(db_name, uninstalled)
            else:
                self.update_changed(db_name, uninstalled)

            # Execute the post update script
            self._run_migration(db_name, "post_update")

            # Finish everything
            with self.env(db_name) as env:
                # Set the user passwords if previously initialized
                users = self.get("odoo", "users", default={})
                if (initialized or args.passwords) and users:
                    utils.info("Setting user passwords")
                    model = env["res.users"]
                    for user, password in users.items():
                        domain = [("login", "=", user)]
                        model.search(domain).write({"password": password})

                # Write the version into the database
                utils.info("Setting database version")
                version = self.get(base.SECTION, "version", default="0.0")
                env["ir.config_parameter"].set_param("db_version", version)
Exemplo n.º 9
0
import odoo
from odoo.tools import config
from odoo.models import DEFAULT_SERVER_DATE_FORMAT
from datetime import datetime
import time
import os
import random

path = os.path.abspath(os.path.dirname(__file__))
args = [
    '-c', './local.conf', '-d', 'mdias2', '--addons-path',
    '%s,%s' %
    (os.path.abspath(os.path.join(path, '../../', './%s' % 'mdias_addons')),
     os.path.abspath(os.path.join(path, '../../', './%s' % 'addons')))
]
config.parse_config(args)
config.parse_config(args)

db_name = config['db_name']

date_range = ['2019-08-01', '2019-09-05']

DATA_MAX = 10000

DAY_SECOND = 24 * 60 * 60
DISPATCH_STATE = [
    'draft', 'wait_accept', 'accepted', 'wait_executing', 'executing',
    'rebacked', 'canceled', 'finished'
]