Example #1
0
 def __init__(self):
     try:
         logging.info('Init quota setting config')
         with open("config.yml", 'r') as ymlfile:
             cfg = yaml.load(ymlfile)
         self.router_body = {
             'network_id': cfg['openstack']['public_network_id'],
             'enable_snat': True
         }
         self.domain_id = cfg["openstack"]["domain_id"]
         self.public_network_id = cfg["openstack"]["public_network_id"]
         self.admin_users = cfg["openstack"]["admin_users"]
         self.quota_instance = QUOTA_DEFAULT_INSTANCE
         self.quota_cores = QUOTA_DEFAULT_CORES
         self.quota_floatingip = QUOTA_DEFAULT_FLOATING_IP
         self.quota_gigabytes = QUOTA_DEFAULT_GIGABYTES
         self.quota_volumes = QUOTA_DEFAULT_VOLUMES
         self.quota_key_pairs = QUOTA_DEFAULT_KEY_PAIRS
         self.quota_ram = QUOTA_DEFAULT_RAM
         self.quota_secgroup_rule = QUOTA_DEFAULT_SECGROUP_RULE
         self.quota_sercgroups = QUOTA_DEFAULT_SECGROUPS
         ss = init_auth(3)
         self.conn = init_openstack()
         self.nova = init_session(ss, 'nova')
         self.cinder = init_session(ss, "cinder")
         self.neutron = init_session(ss, "neutron")
         self.keystone = init_session(ss, "keystone")
     except Exception, e:
         logging.error('Init quota config failed' + str(e))
Example #2
0
def main():
    with open("config.yml", 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

    ss = init_auth(3)
    heat = init_session(ss, 'heat')
    nova = init_session(ss, 'nova')
    neutron = init_session(ss, 'neutron')
    conn = init_openstack()
    embed(globals(), locals())

    host_info=listing_host(nova)
    server_list = create_server(nova, conn, host_info, cfg)
    port_list = attach_floatingip(conn, server_list, cfg)
    ping(port_list)
    delete_floatingip_port(conn, port_list)
    delete_server(conn=conn, server_list=server_list)
Example #3
0
def lambda_handler(event, context):
    """ Main lambda function triggered by S3 Notification """

    # Get the endpoint from lambda environment variable
    if 'my_endpoint_url' not in os.environ or 'lambda_action_on_process' not in os.environ:
        raise ValueError('Missing variables')

    # Init aws4auth and elasticsearch
    es_client = auth.init_elasticsearch(auth.init_auth(),
                                        os.environ['my_endpoint_url'])

    # Create a index if it does not exist
    init_index(es_client)

    # Read all records in the event (Notification send an array)
    # Probably S3 groups the records in large input event (Need to check)
    if event is None or 'Records' not in event:
        raise ValueError('Invalid event')

    for r in event['Records']:
        try:
            obj_name = r['s3']['bucket']['name']
            obj_key = r['s3']['object']['key']
        except Exception as e:
            raise ValueError('Invalid event record')

        obj = s3.Object(obj_name, obj_key)
        obj_str = read_bucket_file(obj)

        if validate_json(obj_str):
            # Indexing the file
            if es_index_file(es_client, obj_str):
                #print("Indexed.")
                change_processed_file(obj, True)
        else:
            change_processed_file(obj, False)
            raise ValueError('Invalid json file input')

    return "end"
Example #4
0

dbo = SQLAlchemy(app)

# Init Database
db = db_base.Database(dbo, config)
db.init()
#db.commit()


print("hello and welcome to flaskyphoto")


# JWT authentication
if config['auth']['enable']:
    auth.init_auth(config)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SECRET_KEY'] = config['auth']['secret']
    app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(
        seconds=int(config['auth']['token_valid_for'])
    )
    jwt = JWT(app, auth.authenticate, auth.identity)
else:
    # override jwt_required if auth is disabled
    # sorry for uglyness
    def jwt_required(realm=None):
        def wrapper(fn):
            @functools.wraps(fn)
            def decorator(*args, **kwargs):
                return fn(*args, **kwargs)
            return decorator
Example #5
0
#========================================= UPLOADS
from flaskext.uploads import UploadSet, configure_uploads, IMAGES, UploadNotAllowed

uploaded_files = UploadSet('postfile', IMAGES, default_dest=lambda app: 'post-images')
uploaded_media = UploadSet('media', default_dest=lambda app: 'uploaded-media')
configure_uploads(app, (uploaded_files, uploaded_media))

#========================================= BLUEPRINTS APPS
app.register_blueprint(auth, url_prefix='/user')
app.register_blueprint(blog, url_prefix='/blog')
blog.register_uploader(uploaded_files)
app.register_blueprint(media, url_prefix='/media')
app.register_blueprint(pages, url_prefix='/pages')

init_auth(app)

#========================================= ERROR TEMPLATES

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def page_not_found(e):
    return render_template('500.html'), 500

@app.errorhandler(401)
def page_not_found(e):
    return render_template('401.html'), 401
Example #6
0
        return render_template('login.j2', error_message=error, show_menu=False, show_refresh=False)

@app.route('/settings', methods=['GET', 'POST'])
@app.route('/settings/<error>', methods=['GET', 'POST'])
def settings(error=None):
    """Loads the settings page or saves settings.."""
    if request.method == 'POST':
        username = session['username']
        current_password = request.form.get('current_password')
        new_password = request.form.get('new_password')
        confirm_password = request.form.get('confirm_password')
        try_result = auth.try_change_password(username, current_password, new_password, confirm_password)
        if try_result is not None:
            return render_template('settings.j2', error_message=try_result, show_menu=True, show_refresh=False)    
        return redirect(url_for('home'))
    else:
        return render_template('settings.j2', error_message=error, show_menu=True, show_refresh=False)

@app.route('/logout')
def logout():
    """Nullifies the session."""
    session.pop('username', None)
    return redirect(url_for('home'))

if __name__ == '__main__':
    scheduling.init_scheduler()
    auth.init_auth()
    init_visibility()
    app.secret_key = 'a3ddad8e-2288-414e-9d7d-c5dd9018fef0'
    app.run(debug=True, host='0.0.0.0', port=80, use_reloader=False)
    
Example #7
0
import time
import os
import yaml
import collections
from ptpython.repl import embed
from auth import init_auth
from auth import init_session
from pprint import pprint as pp

ss = init_auth(3)

nova = init_session(ss, 'nova')
cinder = init_session(ss, 'cinder')
glance = init_session(ss, 'glance')
neutron = init_session(ss, 'neutron')


def find_image(name):
    images = []
    for i in glance.images.list():
        images.append(i)

    for i in images:
        if i['name'] == name:
            return i['id']


def find_flavor(name):
    return nova.flavors.find(name=name).id

Example #8
0
# -*- coding:utf-8 -*-
__author__ = 'liming'

import os
import time

from daemond import be_daemon
from auth import get as get_auth
from auth import init_auth
from utils.parse import get_options

cfg_path = os.path.abspath(os.path.pardir) + '/config.yml'

init_auth(cfg_path)

import status

# be_daemon()

def handler():
    status.main()

def main():
    while True:
        handler()
        time.sleep(get_auth('monitor_interval'))


if __name__ == '__main__':
    parser, opts = get_options()
Example #9
0
def create_app():
    app = Flask(__name__)
    if os.environ.get('LOGIN_DISABLED') is None or os.environ.get(
            'LOGIN_DISABLED') != 'True':
        app.config['LOGIN_DISABLED'] = False
    else:
        app.config['LOGIN_DISABLED'] = True
    init_auth(app)

    mongo_manager = MongoConnectionManager()

    @app.route('/')
    @login_required
    def index():
        print('getting all cards!!!')
        full_list = get_all_cards()
        v_model = TodoListViewModel(
            board_utils.mapCardsToLocalRepresentation(full_list),
            current_user_role_if_login_enabled())
        return render_template('index.html', v_model=v_model)

    @app.route('/add-list-item', methods=['POST'])
    @login_required
    def addListItem():
        if current_user_role_if_login_enabled() == "writer":
            print("Adding Item!")
            card_title = request.form.get('new_card_textbox')
            card = {
                'name': card_title,
                'dateLastActivity': datetime.datetime.now().isoformat()
            }
            devops_database = mongo_manager.get_database()
            inserted_id = devops_database[
                board_utils.MONGO_LIST_TODO].insert_one(card).inserted_id
            print('Created card with ID: ' + str(inserted_id))
        else:
            print('User with role: ' + current_user_role_if_login_enabled() +
                  ' does not have permission to add items')
        return redirect("/")

    @app.route('/completeditem', methods=['POST'])
    @login_required
    def updateListItem():
        if current_user_role_if_login_enabled() == "writer":
            print('Updating Item!')
            print(request.form.get('id'))
            card_id = request.form.get('id')
            card_old_list = board_utils.MONGO_LIST_TODO

            devops_database = mongo_manager.get_database()

            completed_card = devops_database[
                board_utils.MONGO_LIST_TODO].find_one(
                    {'_id': ObjectId(card_id)})
            if completed_card is None:
                card_old_list = board_utils.MONGO_LIST_DOING
                completed_card = devops_database[
                    board_utils.MONGO_LIST_DOING].find_one(
                        {'_id': ObjectId(card_id)})
                if completed_card is None:
                    print('No card to update with ID: ' + card_id)
                    return redirect("/")
            devops_database[card_old_list].delete_one(
                {'_id': completed_card['_id']})
            devops_database[board_utils.MONGO_LIST_DONE].insert_one(
                completed_card)
        else:
            print('User with role: ' + current_user_role_if_login_enabled() +
                  ' does not have permission to update items')
        return redirect("/")

    @app.route('/login/callback', methods=['GET'])
    def login_callback():
        auth_code = request.args.get('code')
        auth_state = request.args.get('state')
        github_login(auth_code, auth_state)
        return redirect("/")

    def get_all_cards():
        devops_database = mongo_manager.get_database()
        to_do_items = devops_database['to_do'].find()
        doing_items = devops_database['doing'].find()
        done_items = devops_database['done_items'].find()
        return {
            board_utils.MONGO_LIST_TODO: to_do_items,
            board_utils.MONGO_LIST_DOING: doing_items,
            board_utils.MONGO_LIST_DONE: done_items
        }

    def current_user_role_if_login_enabled():
        print(app.config['LOGIN_DISABLED'])
        if app.config['LOGIN_DISABLED']:
            return "writer"
        else:
            return current_user.role

    return app