Ejemplo n.º 1
0
def main(argv=sys.argv):

    expandall = lambda string: os.path.expanduser(os.path.expandvars(string))
    home = expandall(os.environ.get('VOLTTRON_HOME', '~/.volttron'))

    os.environ['VOLTTRON_HOME'] = home
    default_wheelhouse = os.environ['VOLTTRON_HOME'] + '/packaged'

    # Setup option parser
    progname = os.path.basename(argv[0])
    parser = config.ArgumentParser(
        prog=progname,
        description='VOLTTRON packaging and signing utility',
    )
    parser.set_defaults(log_config=None)

    parser.add_argument('-l',
                        '--log',
                        metavar='FILE',
                        default=None,
                        help='send log output to FILE instead of stderr')
    parser.add_argument('-L',
                        '--log-config',
                        metavar='FILE',
                        help='read logging configuration from FILE')
    parser.add_argument(
        '-q',
        '--quiet',
        action='add_const',
        const=10,
        dest='verboseness',
        help='decrease logger verboseness; may be used multiple times')
    parser.add_argument(
        '-v',
        '--verbose',
        action='add_const',
        const=-10,
        dest='verboseness',
        help='increase logger verboseness; may be used multiple times')
    parser.add_argument('--verboseness',
                        type=int,
                        metavar='LEVEL',
                        default=logging.WARNING,
                        help='set logger verboseness')

    subparsers = parser.add_subparsers(title='subcommands',
                                       description='valid subcommands',
                                       help='additional help',
                                       dest='subparser_name')
    package_parser = subparsers.add_parser(
        'package',
        help=
        "Create agent package (whl) from a directory or installed agent name.")

    package_parser.add_argument(
        'agent_directory',
        help=
        'Directory for packaging an agent for the first time (requires setup.py file).'
    )
    package_parser.add_argument('--dest',
                                help='Directory to place the wheel file')
    package_parser.set_defaults(dest=default_wheelhouse)

    repackage_parser = subparsers.add_parser(
        'repackage',
        help="Creates agent package from a currently installed agent.")
    repackage_parser.add_argument('directory',
                                  help='Directory where agent is installed')
    repackage_parser.add_argument('--dest',
                                  help='Directory to place the wheel file')
    repackage_parser.set_defaults(dest=default_wheelhouse)

    config_parser = subparsers.add_parser(
        'configure', help='add a configuration file to an agent package')
    config_parser.add_argument('package',
                               metavar='PACKAGE',
                               help='agent package to configure')
    config_parser.add_argument('config_file',
                               metavar='CONFIG',
                               help='configuration file to add to wheel.')

    if auth is not None:
        cert_dir = os.path.expanduser(DEFAULT_CERTS_DIR)
        if not os.path.exists(cert_dir):
            os.makedirs('/'.join((cert_dir, 'certs')))
            os.makedirs('/'.join((cert_dir, 'private')))
        create_ca_cmd = subparsers.add_parser('create_ca')
        create_cert_cmd = subparsers.add_parser('create_cert')
        create_cert_opts = create_cert_cmd.add_mutually_exclusive_group(
            required=True)
        create_cert_opts.add_argument('--creator',
                                      action='store_true',
                                      help='create a creator cert')
        create_cert_opts.add_argument(
            '--admin',
            action='store_true',
            help='create an admin administrator cert')
        create_cert_opts.add_argument('--initiator',
                                      action='store_true',
                                      help='create an initiator cert')
        create_cert_opts.add_argument('--platform',
                                      action='store_true',
                                      help='create a platform cert')
        create_cert_cmd.add_argument(
            '--name', help='file name to store the cert under (no extension)')

        sign_cmd = subparsers.add_parser('sign', help='sign a package')

        sign_opts = sign_cmd.add_mutually_exclusive_group(required=True)
        sign_opts.add_argument('--creator',
                               action='store_true',
                               help='sign as the creator of the package')
        sign_opts.add_argument('--admin',
                               action='store_true',
                               help='sign as the soi administrator')
        sign_opts.add_argument('--initiator',
                               action='store_true',
                               help='sign as the initiator of the package')
        sign_opts.add_argument(
            '--platform',
            action='store_true',
            help='sign the mutable luggage of the package as the platform')
        sign_cmd.add_argument('--cert',
                              metavar='CERT',
                              help='certificate to use to sign the package')
        sign_cmd.add_argument('--config-file',
                              metavar='CONFIG',
                              help='agent configuration file')
        sign_cmd.add_argument('--contract',
                              metavar='CONTRACT',
                              help='agent resource contract file')
        sign_cmd.add_argument('--certs_dir',
                              metavar='CERTS_DIR',
                              help='certificates directory')
        sign_cmd.add_argument('package',
                              metavar='PACKAGE',
                              help='agent package to sign')

        #restricted = subparsers.add_parser('sign')
        #         restricted.add_argument('package',
        #             help='The agent package to sign (whl).')

        verify_cmd = subparsers.add_parser('verify',
                                           help='verify an agent package')
        verify_cmd.add_argument('package',
                                metavar='PACKAGE',
                                help='agent package to verify')

#         enable_restricted_parser = subparsers.add_parser('enable-restricted',
#             help='Enable the restricted features of VOLTTRON')
#
#         creator_key_parser = subparsers.add_parser('set-creator-key',
#             help='Set the key for the creator of the agent code')
#
#         soi_admin_key_parser = subparsers.add_parser('set-SOI-admin-key',
#             help='Set the key for administrator of this Scope of Influence')
#
#         initiator_key_parser = subparsers.add_parser('set-initiator-key',
#             help='Set the key for the initator of this agent')
#
#         source_key_parser = subparsers.add_parser('set-source-key',
#             help='Set the key for the most recent host of this agent')

    opts = parser.parse_args(argv[1:])

    # Configure logging
    level = max(1, opts.verboseness)
    if opts.log is None:
        log_to_file(sys.stderr, level)
    elif opts.log == '-':
        log_to_file(sys.stdout, level)
    elif opts.log:
        log_to_file(opts.log, level, handler_class=handlers.WatchedFileHandler)
    else:
        log_to_file(None, 100, handler_class=lambda x: logging.NullHandler())
    if opts.log_config:
        logging.config.fileConfig(opts.log_config)

    # whl_path will be specified if there is a package or repackage command
    # is specified and it was successful.
    whl_path = None
    user_type = None

    try:

        if opts.subparser_name == 'package':
            whl_path = create_package(opts.agent_directory,
                                      wheelhouse=opts.dest)
        elif opts.subparser_name == 'repackage':
            whl_path = repackage(opts.directory, dest=opts.dest)
        elif opts.subparser_name == 'configure':
            add_files_to_package(opts.package,
                                 {'config_file': opts.config_file})
        else:
            if auth is not None:
                try:
                    if opts.subparser_name == 'create_ca':
                        _create_ca()
                    elif opts.subparser_name == 'verify':
                        if not os.path.exists(opts.package):
                            print('Invalid package name {}'.format(
                                opts.package))
                        verifier = auth.SignedZipPackageVerifier(opts.package)
                        verifier.verify()
                        print "Package is verified"
                    else:
                        user_type = {
                            'admin': opts.admin,
                            'creator': opts.creator,
                            'initiator': opts.initiator,
                            'platform': opts.platform
                        }
                        if opts.subparser_name == 'sign':
                            in_args = {
                                'config_file': opts.config_file,
                                'user_type': user_type,
                                'contract': opts.contract,
                                'certs_dir': opts.certs_dir
                            }
                            _sign_agent_package(opts.package, **in_args)

                        elif opts.subparser_name == 'create_cert':
                            _create_cert(name=opts.name, **user_type)
                except auth.AuthError as e:
                    _log.error(e.message)
                    #print(e.message)


#         elif opts.subparser_name == 'create_cert':
#             _create_cert(name=opts.name, **)
    except AgentPackageError as e:
        _log.error(e.message)
        #print(e.message)
    except Exception as e:
        _log.error(str(e))
        #print e

    if whl_path:
        print("Package created at: {}".format(whl_path))
Ejemplo n.º 2
0
def main(argv=sys.argv):

    expandall = lambda string: os.path.expanduser(os.path.expandvars(string))
    home = expandall(os.environ.get('VOLTTRON_HOME', '~/.volttron'))

    os.environ['VOLTTRON_HOME'] = home
    default_wheelhouse = os.environ['VOLTTRON_HOME']+'/packaged'

    # Setup option parser
    progname = os.path.basename(argv[0])
    parser = config.ArgumentParser(
        prog=progname,
        description='VOLTTRON packaging and signing utility',
    )
    parser.set_defaults(log_config=None, verboseness=logging.INFO)

    parser.add_argument('-l', '--log', metavar='FILE', default=None,
                        help='send log output to FILE instead of stderr')
    parser.add_argument('-L', '--log-config', metavar='FILE',
                        help='read logging configuration from FILE')
    parser.add_argument('-q', '--quiet', action='add_const', const=10, dest='verboseness',
                        help='decrease logger verboseness; may be used multiple times')
    parser.add_argument('-v', '--verbose', action='add_const', const=-10, dest='verboseness',
                        help='increase logger verboseness; may be used multiple times')
    parser.add_argument('--verboseness', type=int, metavar='LEVEL',
                        default=logging.WARNING,
                        help='set logger verboseness')

    subparsers = parser.add_subparsers(title = 'subcommands',
                                       description = 'valid subcommands',
                                       help = 'additional help',
                                       dest='subparser_name')
    package_parser = subparsers.add_parser('package',
                                           help="Create agent package (whl) from a directory")

    package_parser.add_argument('agent_directory',
                                help='Directory for packaging an agent for the first time (requires setup.py file).')
    package_parser.add_argument('--dest',
                                help='Directory to place the wheel file')
    package_parser.set_defaults(dest=default_wheelhouse)
    package_parser.add_argument('--vip-identity',
                                help='Override the Agents desired VIP IDENTITY (if any). '
                                     'Takes precedent over default VIP IDENTITY generated by '
                                     'the platform and the preferred identity of the agent (if any).')
    package_parser.set_defaults(identity=None)

    init_parser = subparsers.add_parser('init',
                                        help="Create new agent code package from a template."
                                             " Will prompt for additional metadata.")

    init_parser.add_argument('directory',
                             help='Directory to create the new agent in (must not exist).')
    init_parser.add_argument('module_name',
                             help='Module name for agent. Class name is derived from this name.')
    init_parser.add_argument('--template', choices=_get_agent_template_list(),
                             help='Name of the template to use. Defaults to "common".')
    init_parser.add_argument('--identity',
                             help='Set agent to have a fixed VIP identity. Useful for new service agents.')
    init_parser.add_argument('--silent', action="store_true",
                             help='Use defaults for meta data and do not prompt.')
    init_parser.set_defaults(identity=None, template="common")

    repackage_parser = subparsers.add_parser('repackage',
                                             help="Creates agent package from a currently installed agent.")
    repackage_parser.add_argument('directory',
                                  help='Directory where agent is installed')
    repackage_parser.add_argument('--dest',
                                  help='Directory to place the wheel file')
    repackage_parser.set_defaults(dest=default_wheelhouse)

    config_parser = subparsers.add_parser('configure',
                                          help='add a configuration file to an agent package')
    config_parser.add_argument('package', metavar='PACKAGE',
                               help='agent package to configure')
    config_parser.add_argument('config_file', metavar='CONFIG',
                               help='configuration file to add to wheel.')

    create_ca_cmd = subparsers.add_parser('create_ca')

    if auth is not None:
        create_cert_cmd = subparsers.add_parser('create_cert')
        create_cert_opts = create_cert_cmd.add_mutually_exclusive_group(required=True)
        create_cert_opts.add_argument('--creator', action='store_true',
                                      help='create a creator cert')
        create_cert_opts.add_argument('--admin', action='store_true',
                                      help='create an admin administrator cert')
        create_cert_opts.add_argument('--initiator', action='store_true',
                                      help='create an initiator cert')
        create_cert_opts.add_argument('--platform', action='store_true',
                                      help='create a platform cert')
        create_cert_cmd.add_argument('--name',
                                     help='file name to store the cert under (no extension)')

        sign_cmd = subparsers.add_parser('sign',
                                         help='sign a package')

        sign_opts = sign_cmd.add_mutually_exclusive_group(required=True)
        sign_opts.add_argument('--creator', action='store_true',
                               help='sign as the creator of the package')
        sign_opts.add_argument('--admin', action='store_true',
                               help='sign as the soi administrator')
        sign_opts.add_argument('--initiator', action='store_true',
                               help='sign as the initiator of the package')
        sign_opts.add_argument('--platform', action='store_true',
                               help='sign the mutable luggage of the package as the platform')
        sign_cmd.add_argument('--cert', metavar='CERT',
                              help='certificate to use to sign the package')
        sign_cmd.add_argument('--config-file', metavar='CONFIG',
                              help='agent configuration file')
        sign_cmd.add_argument('--contract', metavar='CONTRACT',
                              help='agent resource contract file')
        sign_cmd.add_argument('--certs_dir', metavar='CERTS_DIR',
                              help='certificates directory')
        sign_cmd.add_argument('package', metavar='PACKAGE',
                              help='agent package to sign')

        verify_cmd = subparsers.add_parser('verify',
                                           help='verify an agent package')
        verify_cmd.add_argument('package', metavar='PACKAGE',
                                help='agent package to verify')

    opts = parser.parse_args(argv[1:])

    # Configure logging
    level = max(1, opts.verboseness)
    if opts.log is None:
        log_to_file(sys.stderr, level)
    elif opts.log == '-':
        log_to_file(sys.stdout, level)
    elif opts.log:
        log_to_file(opts.log, level, handler_class=handlers.WatchedFileHandler)
    else:
        log_to_file(None, 100, handler_class=lambda x: logging.NullHandler())
    if opts.log_config:
        logging.config.fileConfig(opts.log_config)

    # whl_path will be specified if there is a package or repackage command
    # is specified and it was successful.
    whl_path = None
    user_type = None

    try:

        if opts.subparser_name == 'package':
            whl_path = create_package(opts.agent_directory, wheelhouse=opts.dest, identity=opts.vip_identity)
        elif opts.subparser_name == 'repackage':
            whl_path = repackage(opts.directory, dest=opts.dest)
        elif opts.subparser_name == 'configure' :
            add_files_to_package(opts.package, {'config_file': opts.config_file})
        elif opts.subparser_name == 'init' :
            init_agent(opts.directory, opts.module_name, opts.template, opts.silent, opts.identity)
        elif opts.subparser_name == 'create_ca':
            _create_ca()
        else:
            if auth is not None:
                try:
                    if opts.subparser_name == 'verify':
                        if not os.path.exists(opts.package):
                            print(f'Invalid package name {opts.package}')
                        verifier = auth.SignedZipPackageVerifier(opts.package)
                        verifier.verify()
                        print("Package is verified")
                    else:
                        user_type = {'admin': opts.admin,
                                     'creator': opts.creator,
                                     'initiator': opts.initiator,
                                     'platform': opts.platform}
                        if opts.subparser_name == 'sign':
                            in_args = {
                                'config_file': opts.config_file,
                                'user_type': user_type,
                                'contract': opts.contract,
                                'certs_dir': opts.certs_dir
                            }
                            _sign_agent_package(opts.package, **in_args)

                        elif opts.subparser_name == 'create_cert':
                            _create_cert(name=opts.name, **user_type)
                except auth.AuthError as e:
                    _log.error(e.message)

    except AgentPackageError as e:
        print(e)

    except Exception as e:
        _log.exception(e)

    if whl_path:
        print(f"Package created at: {whl_path}")