Exemplo n.º 1
0
def api_list_actions():
    """
    Define a route.

    This is a main routing method
    """
    #
    # Basic authentication module requirement
    # If the auth module is installed and the user is not authenticated, so go to login
    #
    session = {}
    if hasattr(app, 'auth'):
        try:
            session = get_session_data(
                transaction=transaction,
                session_id=request.cookies.get('session_id'))
        except Exception as e:
            print(e)
            return redirect(url_for('auth_blueprint.login'))
    else:
        session['kubeconfig'] = None
    # not current_user.is_authenticated:
    if hasattr(app, 'auth') and session['email'] is None:
        return redirect(url_for('auth_blueprint.login'))
    #
    # End basic authentication requirement
    #

    return jsonify(list_actions())
Exemplo n.º 2
0
Arquivo: cli.py Projeto: pystol/pystol
def main():
    """
    Application's entry point.

    Here, application's settings are read from the command line,
    environment variables and CRD. Then, retrieving and processing
    of Kubernetes events are initiated.
    """
    parser = ArgumentParser(description='Pystol - CLI', prog='pystol')

    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + pystol_version)

    parser.add_argument('-b',
                        '--banner',
                        action='store_true',
                        help='Print Pystol.org banner')

    subparsers = parser.add_subparsers(title="Pystol subcommands",
                                       dest="command",
                                       help=("These are the options "
                                             "supported: \n"
                                             "The listen option will "
                                             "watch for CRD events. "
                                             "The run option will "
                                             "execute the Pystol "
                                             "actions against the cluster."))

    parser_purge = subparsers.add_parser('purge',
                                         help=("Purge any Pystol "
                                               "deployed resource."))

    parser_purge.add_argument('-y',
                              '--yes',
                              action='store_true',
                              help=("Run this to avoid having to write 'yes'"))

    parser_run = subparsers.add_parser('run',
                                       help=("CLI options to run the "
                                             "Pystol actions."))

    parser_run.add_argument('-n',
                            '--namespace',
                            required=True,
                            type=str,
                            help=("Name of the namespace to be referenced, "
                                  "this will be the Galaxy handler, like: "
                                  "pystol (from galaxy), "
                                  "which will be referenced as "
                                  "https://galaxy.ansible.com/pystol"))

    parser_run.add_argument(
        '-c',
        '--collection',
        required=True,
        type=str,
        help=("Name of the collection to be installed/executed, "
              "this can be the name of the galaxy collection like: "
              "actions (from galaxy), "
              "which will be referenced as "
              "https://galaxy.ansible.com/pystol/actions"))

    parser_run.add_argument(
        '-r',
        '--role',
        required=True,
        type=str,
        help=("Name of the role to be executed part of the "
              "namespace and collection value, "
              "for example, if the name is: "
              "kill-pods "
              "It will execute: "
              "pystol.actions.kill-pods "))

    parser_run.add_argument(
        '-s',
        '--source',
        default="galaxy.ansible.com",
        type=str,
        help=("The source URL where we will fetch the collection "
              "with the Pystol actions.\n"
              "It can be i.e. git+http://github.com/pystol/pystol-galaxy.git\n"
              "Defaults to: galaxy.ansible.com"))

    parser_run.add_argument(
        '-e',
        '--extra-vars',
        default="{}",
        type=str,
        help=("The extra vars for example:"
              "--extra-vars '{\"a\":\"b\",\"c\":[\",\"d\",\"e\"]}'\n"
              "Defaults to: ''"))

    subparsers.add_parser('listen', help=("CLI options to " "watch for CRs"))

    subparsers.add_parser('list', help=("CLI options to " "list CRs"))

    parser_get = subparsers.add_parser('get', help=("Get Pystol resource."))

    parser_get.add_argument("action",
                            type=str,
                            help=("Specify the action to fetch details"))

    parser_show = subparsers.add_parser('show',
                                        help=("Get available Pystol actions."))

    parser_show.add_argument("action",
                             nargs='?',
                             default='',
                             type=str,
                             help=("Specify the action to fetch details"))

    parser_get.add_argument(
        '-d',
        '--debug',
        action='store_true',
        help=("Add the debug flag to show extra information"))

    subparsers.add_parser('deploy',
                          help=("Install the Pystol operator "
                                "includes, deployment, "
                                "RBAC rules, and CRD"))

    args = parser.parse_args()

    # print("Pystol called with the folowing parameters")
    # print(parser.parse_args())

    if args.banner:
        print(get_banner())
        exit()

    try:
        if (args.command == 'run'):
            print(u"\U0001F52B" + " Starting a Pystol action")
            print("  " + u"\U0001F4BE" + " Inserting the custom resource"
                  " in the cluster")
            ins = insert_pystol_object(args.namespace, args.collection,
                                       args.role, args.source, args.extra_vars)

            if ins:
                print("  " + u"\U0001F4A8" + " The action was deployed OK")
                print("  " + u"\U0001F916" + " Check its status for details")
                print("  " + u"\U0001F92B" + " Try using the CLI list and get"
                      " options, 'pystol -h' helps")
            else:
                print("  " + u"\U0001F914" + " We can not add the resource,"
                      " did you deploy Pystol?")
                print("  " + u"\U0001F440" + " Logs are stored in"
                      " /tmp/pystol.org")

            exit()
        elif (args.command == 'listen'):
            print("We will watch for objects to process")
            try:
                t1 = threading.Thread(target=watch_for_pystol_objects,
                                      args=(t1_stop, ))
                t1.start()
                t2 = threading.Thread(target=watch_for_pystol_timeouts,
                                      args=(t2_stop, ))
                t2.start()
            except Exception as err:
                print("Error: unable to start thread: " + err)
        elif (args.command == 'purge'):
            if not args.yes:
                yes = {'yes', 'y'}
                msg = ("*********This action can not be undone**********\n"
                       "*  You are about to purge any Pystol resource  *\n"
                       "* part of the pystol namespace in the cluster. *\n"
                       "* This includes any deployment, previous runs, *\n"
                       "*  RBAC rules, and any other Pystol resource.  *\n"
                       "*********This action can not be undone**********\n")
                print(msg)
                choice = input("Write 'yes' and press 'enter' to proceed: \n")
                if choice in yes:
                    print(u"\U0001F480" + " Purging Pystol from the cluster.")
                    print("  " + u"\U0001F4A3" + " Removing resources...")
                    purge_pystol()
                    print(u"\u2728" + " Pystol was removed completely.")
                else:
                    print("Cancelling...")
            else:
                print(u"\U0001F480" + " Purging Pystol from the cluster.")
                print("  " + u"\U0001F4A3" + " Removing resources...")
                purge_pystol()
                print(u"\u2728" + " Pystol was removed completely.")
            exit()
        elif (args.command == 'list'):
            print(u"\U0001F4DA" + " Listing the deployed actions"
                  " from the cluster.")
            list_actions()
            print(u"\U0001F4A1" + " For further information use:"
                  " pystol get <action_name> [--debug]")
            exit()
        elif (args.command == 'show'):
            if args.action:
                show_action(args.action)
            else:
                show_actions()
            exit()
        elif (args.command == 'get'):
            print(u"\U0001F4E4" + " Getting the details from"
                  " an specific action.")
            get_action(args.action, args.debug)
            exit()
        elif (args.command == 'deploy'):
            print(u"\U0001F680" + " Deploying Pystol in the cluster.")
            deploy_pystol()
            print(u"\U0001F3C4" + " Done! Pystol is now deployed.")
            print(u"\U0001F550" + " Wait a few seconds to have the"
                  " deployments up and running.")
            exit()

    except KeyboardInterrupt:
        pass
    except Exception as err:
        raise RuntimeError('There is something wrong...' + err)

    while not t2_stop.is_set() or not t1_stop.is_set():
        pass
Exemplo n.º 3
0
def executed():
    """
    Render all the templates not from base.

    This is a main method
    """
    #
    # Basic authentication module requirement
    # If the auth module is installed and the user is not authenticated, so go to login
    #
    session = {}
    if hasattr(app, 'auth'):
        try:
            session = get_session_data(transaction=transaction, session_id=request.cookies.get('session_id'))
        except Exception as e:
            print(e)
            return redirect(url_for('auth_blueprint.login'))
    else:
        session['kubeconfig'] = None
    # not current_user.is_authenticated:
    if hasattr(app, 'auth') and session['email'] is None:
        return redirect(url_for('auth_blueprint.login'))
    #
    # End basic authentication requirement
    #

    if 'kubeconfig' not in session or session['kubeconfig'] is None or session['kubeconfig'] == '':
        kubeconfig = None
        api_client = None
    else:
        kubeconfig = session['kubeconfig']
        api_client = remote_cluster(kubeconfig=kubeconfig)

    if ('username' not in session or
        session['username'] is None or
        session['username'] == '' or
        'email' not in session or
        session['email'] is None or
            session['email'] == ''):

        username = None
        email = None
    else:
        username = session['username']
        email = session['email']

    try:
        return render_template('executed.html',
                               username=username, email=email,
                               list_actions=list_actions(api_client=api_client, debug=True),
                               compute_allocated_resources=compute_allocated_resources(
                                   api_client=api_client),
                               cluster_name_configured=cluster_name_configured(
                                   api_client=api_client),
                               kubeinit_version=KUBEINIT_VERSION,)

    except TemplateNotFound:
        return render_template('page-404.html'), 404
    except Exception as e:
        print("Exception found in %s: %s" % (blueprint.name, e))
        if current_app.config['DEBUG']:
            raise e
        return render_template('page-500.html'), 500