Exemplo n.º 1
0
def remove_devices(args):
    """ Removes the device(s) from the ring(s).

    Removes the device(s) from the ring(s) based on the search pattern.

    :raises SwiftProxyCharmException: if pattern action_get('search-value')
        doesn't match any device in the ring.
    """
    rings_valid = ['account', 'container', 'object', 'all']
    rings_to_update = []
    ring = action_get('ring')
    if ring not in rings_valid:
        action_fail("Invalid ring name '{}'. Should be one of: {}".format(
            ring, ', '.join(rings_valid)))
        return
    if ring == 'all':
        rings_to_update.extend(['account', 'container', 'object'])
    else:
        rings_to_update.append(ring)
    for ring_to_update in rings_to_update:
        ring_to_update_builder = ring_to_update + '.builder'
        ring_to_update_path = os.path.join(SWIFT_CONF_DIR,
                                           ring_to_update_builder)
        remove_from_ring(ring_to_update_path, action_get('search-value'))
    balance_rings()
def make_cache_tier():
    backer_pool = action_get("backer-pool")
    cache_pool = action_get("cache-pool")
    cache_mode = action_get("cache-mode")

    # Pre flight checks
    if not pool_exists('admin', backer_pool):
        log("Please create {} pool before calling create-cache-tier".format(
            backer_pool))
        action_fail("create-cache-tier failed. Backer pool {} must exist "
                    "before calling this".format(backer_pool))

    if not pool_exists('admin', cache_pool):
        log("Please create {} pool before calling create-cache-tier".format(
            cache_pool))
        action_fail("create-cache-tier failed. Cache pool {} must exist "
                    "before calling this".format(cache_pool))

    pool = Pool(service='admin', name=backer_pool)
    try:
        pool.add_cache_tier(cache_pool=cache_pool, mode=cache_mode)
    except CalledProcessError as err:
        log("Add cache tier failed with message: {}".format(
            err.message))
        action_fail("create-cache-tier failed.  Add cache tier failed with "
                    "message: {}".format(err.message))
Exemplo n.º 3
0
def add_peer():
    err = ''
    try:
        peer_public_key = action_get('peer-publickey')
        gateway_ip = action_get('gateway-ip')
        subnet_behind_tunnel = action_get('subnet-behind-tunnel')
        public_endpoint = action_get('public-endpoint')
        cmd = [
            'sudo wg set wg0 peer {} allowed-ips {},{} endpoint {}:51820 persistent-keepalive 25'
            .format(peer_public_key, gateway_ip, subnet_behind_tunnel,
                    public_endpoint)
        ]
        result, err = charms.sshproxy._run(cmd)
        cmd = ['sudo ip -4 route add {} dev wg0'.format(gateway_ip)]
        result, err = charms.sshproxy._run(cmd)
        cmd = ['sudo ip -4 route add {} dev wg0'.format(subnet_behind_tunnel)]
        result, err = charms.sshproxy._run(cmd)
        cmd = ['sudo wg-quick save wg0']
        result, err = charms.sshproxy._run(cmd)
    except:
        action_fail('command failed:' + err)
    else:
        action_set({'outout': result})
    finally:
        clear_flag('actions.add-peer')
Exemplo n.º 4
0
def set_weight(args):
    """ Sets the device's weight.

    Sets the device's weight based on the search pattern.

    :raises SwiftProxyCharmException: if pattern action_get('search-value')
        doesn't match any device in the ring.
    """
    if not is_elected_leader(SWIFT_HA_RES):
        action_fail('Must run action on leader unit')
        return

    rings_valid = ['account', 'container', 'object', 'all']
    ring = action_get('ring')
    if ring not in rings_valid:
        action_fail('Invalid ring name.')
        return
    if ring == 'all':
        rings_to_update = ['account', 'container', 'object']
    else:
        rings_to_update = [ring]
    for ring_to_update in rings_to_update:
        ring_to_update_builder = ring_to_update + '.builder'
        ring_to_update_path = os.path.join(SWIFT_CONF_DIR,
                                           ring_to_update_builder)
        set_weight_in_ring(ring_to_update_path, action_get('search-value'),
                           str(action_get('weight')))
    balance_rings()
Exemplo n.º 5
0
def user_create():
    user = action_get('name')
    groups = action_get('groups') or ''
    protect_resources(user)

    users = user_list()
    if user in list(users):
        action_fail('User "{}" already exists.'.format(user))
        return

    # Create the secret
    # TODO: make the token format less magical so it doesn't get out of
    # sync with the function that creates secrets in k8s-master.py.
    token = '{}::{}'.format(user, layer.kubernetes_master.token_generator())
    layer.kubernetes_master.create_secret(token, user, user, groups)

    # Create a kubeconfig
    ca_crt = layer.kubernetes_common.ca_crt_path
    kubeconfig_path = '/home/ubuntu/{}-kubeconfig'.format(user)
    public_address, public_port = layer.kubernetes_master.get_api_endpoint()
    public_server = 'https://{0}:{1}'.format(public_address, public_port)

    layer.kubernetes_common.create_kubeconfig(kubeconfig_path,
                                              public_server,
                                              ca_crt,
                                              token=token,
                                              user=user)
    os.chmod(kubeconfig_path, 0o644)

    # Tell the people what they've won
    fetch_cmd = 'juju scp {}:{} .'.format(hookenv.local_unit(),
                                          kubeconfig_path)
    action_set({'msg': 'User "{}" created.'.format(user)})
    action_set({'users': ', '.join(list(users) + [user])})
    action_set({'kubeconfig': fetch_cmd})
Exemplo n.º 6
0
def restore_backup():
    backend = Backend()
    backup_name = action_get("backup-name")
    restore_path = action_get("restore-path")

    if not os.path.exists(restore_path):
        log("Creating restore path: {}".format(restore_path))
        os.mkdir(restore_path)
    try:
        log("Restoring backup {} to {}".format(backup_name, restore_path),
            level=DEBUG)
        check_output(
            ["/snap/bin/preserve",
             "--configdir",
             os.path.join(os.path.expanduser("~"), ".config"),
             "--loglevel", "error",
             "restore",
             "--backend", backend.get_backend(),
             "--vault",
             backup_name, restore_path])

    except OSError as err:
        log("Restore backup failed with error: {}".format(err.message),
            level=ERROR)
        action_fail("Restore backup failed with error: {}".format(err.message))
Exemplo n.º 7
0
def add_user():
    """Add a swauth user to swift."""
    if config('auth-type') == 'swauth':
        try_initialize_swauth()
        account = action_get('account')
        username = action_get('username')
        password = action_get('password')
        bind_port = config('bind-port')
        bind_port = determine_api_port(bind_port, singlenode_mode=True)
        success = True
        try:
            check_call([
                "swauth-add-user",
                "-A", "http://localhost:{}/auth/".format(bind_port),
                "-K", leader_get('swauth-admin-key'),
                "-a", account, username, password])
        except CalledProcessError as e:
            success = False
            log("Has a problem adding user: {}".format(e.output))
            action_fail(
                "Adding user {} failed with: \"{}\""
                .format(username, str(e)))
        if success:
            message = "Successfully added the user {}".format(username)
            action_set({
                'add-user.result': 'Success',
                'add-user.message': message,
            })
Exemplo n.º 8
0
def action_add_user():
    """Run the touch command.

    Runs touch on vnf-a and vnf-b and returns the success or failure for each.
    """
    err = ''
    user_id = 0
    try:
        username = action_get('username')
        tariff = action_get('tariff')

        # If this were a functional VNF, it would add the username to its
        # database. For the purposes of demonstrating actions, this will return
        # a random number.
        user_id = random.randint(1, 100)

    except Exception as err:
        # This marks the action as having failed, so the ns charm knows not to
        # continue with the add_user operation.
        action_fail(str(err))
    else:
        # This will put the user_id in the action output, which will be read
        # by the ns charm. Multiple values could be returned here.
        action_set({'user-id': user_id})
    finally:
        clear_flag('actions.add-user')
Exemplo n.º 9
0
def copy_pool():
    try:
        source = hookenv.action_get("source")
        target = hookenv.action_get("target")
        subprocess.check_call(['rados', 'cppool', source, target])
    except subprocess.CalledProcessError as e:
        hookenv.action_fail("Error copying pool: {}".format(str(e)))
Exemplo n.º 10
0
def compact():
    '''Call `etcdctl compact`.

    '''
    def get_latest_revision():
        try:
            output = CTL.run('endpoint status --write-out json')
        except subprocess.CalledProcessError as e:
            action_fail_now(
                'Failed to determine latest revision for '
                'compaction: {}'.format(e))

        m = re.search(r'"revision":(\d*)', output)
        if not m:
            action_fail_now(
                "Failed to get revision from 'endpoint status' "
                "output: {}".format(output))
        return m.group(1)

    revision = action_get('revision') or get_latest_revision()
    physical = 'true' if action_get('physical') else 'false'
    command = 'compact {} --physical={}'.format(revision, physical)
    try:
        output = CTL.run(command)
        action_set(dict(output=output))
    except subprocess.CalledProcessError as e:
        action_fail_now(e.output)
Exemplo n.º 11
0
def make_cache_tier():
    backer_pool = action_get("backer-pool")
    cache_pool = action_get("cache-pool")
    cache_mode = action_get("cache-mode")

    # Pre flight checks
    if not pool_exists('admin', backer_pool):
        log("Please create {} pool before calling create-cache-tier".format(
            backer_pool))
        action_fail("create-cache-tier failed. Backer pool {} must exist "
                    "before calling this".format(backer_pool))

    if not pool_exists('admin', cache_pool):
        log("Please create {} pool before calling create-cache-tier".format(
            cache_pool))
        action_fail("create-cache-tier failed. Cache pool {} must exist "
                    "before calling this".format(cache_pool))

    pool = Pool(service='admin', name=backer_pool)
    try:
        pool.add_cache_tier(cache_pool=cache_pool, mode=cache_mode)
    except CalledProcessError as err:
        log("Add cache tier failed with message: {}".format(err.message))
        action_fail("create-cache-tier failed.  Add cache tier failed with "
                    "message: {}".format(err.message))
Exemplo n.º 12
0
def configure_interface():
    """
    Configure an ethernet interface
    """
    iface_name = action_get('iface-name')
    cidr = action_get('cidr')

    # cidr is optional
    if cidr:
        try:
            # Add may fail, but change seems to add or update
            router.ip('address', 'change', cidr, 'dev', iface_name)
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))
            return
        finally:
            remove_state('vpe.configure-interface')
            status_set('active', 'ready!')

    try:
        router.ip('link', 'set', 'dev', iface_name, 'up')
    except subprocess.CalledProcessError as e:
        action_fail('Command failed: %s (%s)' %
                    (' '.join(e.cmd), str(e.output)))
    finally:
        remove_state('vpe.configure-interface')
        status_set('active', 'ready!')
Exemplo n.º 13
0
def configure_interface():
    """
    Configure an ethernet interface
    """
    iface_name = action_get('iface-name')
    cidr = action_get('cidr')

    # cidr is optional
    if cidr:
        try:
            # Add may fail, but change seems to add or update
            router.ip('address', 'change', cidr, 'dev', iface_name)
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))
            return
        finally:
            remove_state('vpe.configure-interface')
            status_set('active', 'ready!')

    try:
        router.ip('link', 'set', 'dev', iface_name, 'up')
    except subprocess.CalledProcessError as e:
        action_fail('Command failed: %s (%s)' %
                    (' '.join(e.cmd), str(e.output)))
    finally:
        remove_state('vpe.configure-interface')
        status_set('active', 'ready!')
Exemplo n.º 14
0
def delete_domain_connection():
    ''' Remove the tunnel to another router where the domain is present '''
    domain = action_get('domain-name')
    tunnel_name = action_get('tunnel-name')

    status_set('maintenance', 'deleting domain connection: {}'.format(domain))

    try:

        try:
            """
            $ ip netns exec domain_name ip link set tunnel_name down
            """
            router.ip('netns', 'exec', domain, 'ip', 'link', 'set',
                      tunnel_name, 'down')
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))

        try:
            """
            $ ip netns exec domain_name ip tunnel del tunnel_name
            """
            router.ip('netns', 'exec', domain, 'ip', 'tunnel', 'del',
                      tunnel_name)
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))
    except:
        pass
    finally:
        remove_state('vpe.delete-domain-connection')
        status_set('active', 'ready!')
Exemplo n.º 15
0
def create_ogr_zone(args):
    aggr_name = action_get('aggregate-name')
    avail_zone = action_get('avail-zone')
    ogr_compute = action_get('ogr-compute')

    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-create {} {}'"\
          .format(aggr_name, avail_zone)
    commands.getoutput(cmd)
    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-add-host {} {}'"\
          .format(aggr_name, ogr_compute)
    commands.getoutput(cmd)
    if config("openstack-version") == "liberty" or \
       config("openstack-version") == "mitaka":
        cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-details {}'"\
              .format(aggr_name)
    else:
        cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-show {}'"\
              .format(aggr_name)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
    relation_info = {
        'aggr-name': aggr_name
    }
    if config("openstack-version") == "pike" or \
       config("openstack-version") == "ocata":
        for rid in relation_ids('neutron-api-cplane'):
            for unit in related_units(rid):
                relation_set(relation_id=rid, relation_settings=relation_info)
def backup():
    basedir = (action_get("basedir")).lower()
    compress = (action_get("compress"))
    incremental = (action_get("incremental"))
    sstpw = config("sst-password")
    optionlist = []

    # innobackupex will not create recursive dirs that do not already exist,
    # so help it along
    if not os.path.exists(basedir):
        os.makedirs(basedir)

    # Build a list of options to pass to innobackupex
    if compress is "true":
        optionlist.append("--compress")

    if incremental is "true":
        optionlist.append("--incremental")

    try:
        subprocess.check_call(
            ['innobackupex', '--compact', '--galera-info', '--rsync',
             basedir, '--user=sstuser', '--password='******'time-completed': (strftime("%Y-%m-%d %H:%M:%S", gmtime())),
            'outcome': 'Success'}
        )
    except subprocess.CalledProcessError as e:
        action_set({
            'time-completed': (strftime("%Y-%m-%d %H:%M:%S", gmtime())),
            'output': e.output,
            'return-code': e.returncode,
            'traceback': traceback.format_exc()})
        action_fail("innobackupex failed, you should log on to the unit"
                    "and check the status of the database")
Exemplo n.º 17
0
def apiset():
    """
    Configure an ethernet interface
    """
    name = action_get('name')
    path = action_get('path')
    params = action_get('parameters')

    status_set('maintenance', 'running cmd on fortios')
    log("in apiset call")
    # multi line is accepted with \n to separate then converted because juju does not allow advanced types like list or json :(
    try:
        mydata = {}
        for line in params.split("\\n"):
            log("line is:" + line)
            key = line.split(":")[0].strip()
            value = line.split(":")[1].strip()
            mydata[key] = value
        res, resp = fortios.set(name, path, data=mydata)
        if res:
            action_set({'output': resp})
        else:
            action_fail('API call on fortios failed reason:' + repr(resp))
        remove_state('actions.apiset')
        status_set('active', 'alive')
    except Exception as e:
        action_fail('API call on fortios failed reason:' + repr(e))
        remove_state('actions.apiset')
        status_set('active', 'alive')
Exemplo n.º 18
0
def create_pool():
    pool_name = action_get("name")
    pool_type = action_get("pool-type")
    try:
        if pool_type == "replicated":
            replicas = action_get("replicas")
            replicated_pool = ReplicatedPool(name=pool_name,
                                             service='admin',
                                             replicas=replicas)
            replicated_pool.create()

        elif pool_type == "erasure":
            crush_profile_name = action_get("erasure-profile-name")
            erasure_pool = ErasurePool(name=pool_name,
                                       erasure_code_profile=crush_profile_name,
                                       service='admin')
            erasure_pool.create()
        else:
            log("Unknown pool type of {}. Only erasure or replicated is "
                "allowed".format(pool_type))
            action_fail("Unknown pool type of {}. Only erasure or replicated "
                        "is allowed".format(pool_type))
    except CalledProcessError as e:
        action_fail("Pool creation failed because of a failed process. "
                    "Ret Code: {} Message: {}".format(e.returncode, str(e)))
Exemplo n.º 19
0
def prepare_spgwc_build():

    # ====== Install SPGW-C ==================================================
    # For a documentation of the installation procedure, see:
    # https://github.com/OPENAIRINTERFACE/openair-cn-cups/wiki/OpenAirSoftwareSupport#install-spgw-c

    gitRepository = action_get('spgwc-git-repository')
    gitCommit = action_get('spgwc-git-commit')
    gitDirectory = 'openair-cn-cups'

    # Prepare network configurations:
    spgwcS11_IfName = 'ens5'
    spgwcSXab_IfName = 'ens4'
    configurationS11 = configureInterface(spgwcS11_IfName,
                                          IPv4Interface('0.0.0.0/0'))
    configurationSXab = configureInterface(spgwcSXab_IfName,
                                           IPv4Interface('0.0.0.0/0'))

    # S5S8 dummy interfaces:
    spgwcS5S8_SGW_IfName = 'dummy0:s5c'
    configurationS5S8_SGW = configureInterface(
        spgwcS5S8_SGW_IfName, IPv4Interface('172.58.58.102/24'))
    spgwcS5S8_PGW_IfName = 'dummy0:p5c'
    configurationS5S8_PGW = configureInterface(
        spgwcS5S8_PGW_IfName, IPv4Interface('172.58.58.101/24'))

    # NOTE:
    # Double escaping is required for \ and " in "command" string!
    # 1. Python
    # 2. bash -c "<command>"
    # That is: $ => \$ ; \ => \\ ; " => \\\"

    commands = """\
echo \\\"###### Preparing system ###############################################\\\" && \\
echo -e \\\"{configurationS11}\\\" | sudo tee /etc/network/interfaces.d/61-{spgwcS11_IfName} && sudo ifup {spgwcS11_IfName} || true && \\
echo -e \\\"{configurationSXab}\\\" | sudo tee /etc/network/interfaces.d/62-{spgwcSXab_IfName} && sudo ifup {spgwcSXab_IfName} || true && \\
sudo ip link add dummy0 type dummy || true && \\
echo -e \\\"{configurationS5S8_SGW}\\\" | sudo tee /etc/network/interfaces.d/63-{spgwcS5S8_SGW_IfName} && sudo ifup {spgwcS5S8_SGW_IfName} || true && \\
echo -e \\\"{configurationS5S8_PGW}\\\" | sudo tee /etc/network/interfaces.d/64-{spgwcS5S8_PGW_IfName} && sudo ifup {spgwcS5S8_PGW_IfName} || true && \\
echo \\\"###### Preparing sources ##############################################\\\" && \\
cd /home/nornetpp/src && \\
if [ ! -d \\\"{gitDirectory}\\\" ] ; then git clone --quiet {gitRepository} {gitDirectory} && cd {gitDirectory} ; else cd {gitDirectory} && git pull ; fi && \\
git checkout {gitCommit} && \\
cd build/scripts && \\
echo \\\"###### Done! ##########################################################\\\"""".format(
        gitRepository=gitRepository,
        gitDirectory=gitDirectory,
        gitCommit=gitCommit,
        spgwcS11_IfName=spgwcS11_IfName,
        spgwcSXab_IfName=spgwcSXab_IfName,
        spgwcS5S8_SGW_IfName=spgwcS5S8_SGW_IfName,
        spgwcS5S8_PGW_IfName=spgwcS5S8_PGW_IfName,
        configurationS11=configurationS11,
        configurationSXab=configurationSXab,
        configurationS5S8_SGW=configurationS5S8_SGW,
        configurationS5S8_PGW=configurationS5S8_PGW)

    runShellCommands(commands, 'prepare_spgwc_build: preparing SPGW-C build',
                     'actions.prepare-spgwc-build',
                     'spgwccharm.prepared-spgwc-build')
Exemplo n.º 20
0
def mysqldump(args):
    """Execute a mysqldump backup.

    Execute mysqldump of the database(s).  The mysqldump action will take
    in the databases action parameter. If the databases parameter is unset all
    databases will be dumped, otherwise only the named databases will be
    dumped. The action will use the basedir action parameter to dump the
    database into the base directory.

    A successful mysqldump backup will set the action results key,
    mysqldump-file, with the full path to the dump file.

    :param args: sys.argv
    :type args: sys.argv
    :side effect: Calls instance.mysqldump
    :returns: This function is called for its side effect
    :rtype: None
    :action param basedir: Base directory to dump the db(s)
    :action param databases: Comma separated string of databases
    :action return:
    """
    basedir = action_get("basedir")
    databases = action_get("databases")

    try:
        filename = percona_utils.mysqldump(basedir, databases=databases)
        action_set({"mysqldump-file": filename, "outcome": "Success"})
    except subprocess.CalledProcessError as e:
        action_set({
            "output": e.output,
            "return-code": e.returncode,
            "traceback": traceback.format_exc()
        })
        action_fail("mysqldump failed")
Exemplo n.º 21
0
def add_user():
    """Add a swauth user to swift."""
    if config('auth-type') == 'swauth':
        try_initialize_swauth()
        account = action_get('account')
        username = action_get('username')
        password = action_get('password')
        bind_port = config('bind-port')
        bind_port = determine_api_port(bind_port, singlenode_mode=True)
        success = True
        try:
            check_call([
                "swauth-add-user", "-A",
                "http://localhost:{}/auth/".format(bind_port), "-K",
                leader_get('swauth-admin-key'), "-a", account, username,
                password
            ])
        except CalledProcessError as e:
            success = False
            log("Has a problem adding user: {}".format(e.output))
            action_fail("Adding user {} failed with: \"{}\"".format(
                username, str(e)))
        if success:
            message = "Successfully added the user {}".format(username)
            action_set({
                'add-user.result': 'Success',
                'add-user.message': message,
            })
def create_pool():
    pool_name = action_get("name")
    pool_type = action_get("pool-type")
    try:
        if pool_type == "replicated":
            replicas = action_get("replicas")
            replicated_pool = ReplicatedPool(name=pool_name,
                                             service='admin',
                                             replicas=replicas)
            replicated_pool.create()

        elif pool_type == "erasure":
            crush_profile_name = action_get("erasure-profile-name")
            erasure_pool = ErasurePool(name=pool_name,
                                       erasure_code_profile=crush_profile_name,
                                       service='admin')
            erasure_pool.create()
        else:
            log("Unknown pool type of {}. Only erasure or replicated is "
                "allowed".format(pool_type))
            action_fail("Unknown pool type of {}. Only erasure or replicated "
                        "is allowed".format(pool_type))
    except CalledProcessError as e:
        action_fail("Pool creation failed because of a failed process. "
                    "Ret Code: {} Message: {}".format(e.returncode, e.message))
def delete_cache_tier():
    backer_pool = action_get("backer-pool")
    cache_pool = action_get("cache-pool")

    # Pre flight checks
    if not pool_exists('admin', backer_pool):
        log("Backer pool {} must exist before calling this".format(
            backer_pool))
        action_fail("remove-cache-tier failed. Backer pool {} must exist "
                    "before calling this".format(backer_pool))

    if not pool_exists('admin', cache_pool):
        log("Cache pool {} must exist before calling this".format(
            cache_pool))
        action_fail("remove-cache-tier failed. Cache pool {} must exist "
                    "before calling this".format(cache_pool))

    pool = Pool(service='admin', name=backer_pool)
    try:
        pool.remove_cache_tier(cache_pool=cache_pool)
    except CalledProcessError as err:
        log("Removing the cache tier failed with message: {}".format(
            err.message))
        action_fail("remove-cache-tier failed. Removing the cache tier failed "
                    "with message: {}".format(err.message))
Exemplo n.º 24
0
def create_ogr_zone(args):
    aggr_name = action_get('aggregate-name')
    avail_zone = action_get('avail-zone')
    ogr_compute = action_get('ogr-compute')

    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-create {} {}'"\
          .format(aggr_name, avail_zone)
    commands.getoutput(cmd)
    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-add-host {} {}'"\
          .format(aggr_name, ogr_compute)
    commands.getoutput(cmd)
    if config("openstack-version") == "liberty" or \
       config("openstack-version") == "mitaka":
        cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-details {}'"\
              .format(aggr_name)
    else:
        cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-show {}'"\
              .format(aggr_name)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
    relation_info = {'aggr-name': aggr_name}
    if config("openstack-version") == "pike" or \
       config("openstack-version") == "ocata":
        for rid in relation_ids('neutron-api-cplane'):
            for unit in related_units(rid):
                relation_set(relation_id=rid, relation_settings=relation_info)
Exemplo n.º 25
0
def start_transcoder():
    try:
        stream_ip = action_get('stream-ip')
        output_port = action_get('output-port')

        cmd = "sudo rm /etc/systemd/system/opencv.service >/dev/null 2>&1; "
        cmd += "sudo systemctl stop opencv.service >/dev/null 2>&1; "
        cmd += "sudo systemctl daemon-reload"
        charms.sshproxy._run(cmd)

        cmd = "echo '[Unit]' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'Description=OpenCV' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo '' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo '[Service]' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'Type=simple' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'User=ubuntu' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'WorkingDirectory=/home/ubuntu' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'ExecStart=/usr/bin/python live_server.py {0} {1}' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && ".format(
            stream_ip, output_port)
        cmd += "echo 'Restart=always' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'RestartSec=5' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo '' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo '[Install]' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "echo 'WantedBy=multi-user.target' | sudo tee -a /etc/systemd/system/opencv.service > /dev/null && "
        cmd += "sudo systemctl daemon-reload && "
        cmd += "sudo systemctl start opencv.service"
        result, _ = charms.sshproxy._run(cmd)
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        err = traceback.format_exception(exc_type, exc_value, exc_traceback)
        action_fail('Starting transcoder failed: ' + str(err))
    else:
        action_set({'output': result})
    finally:
        remove_flag('actions.start-transcoder')
Exemplo n.º 26
0
def delete_domain_connection():
    ''' Remove the tunnel to another router where the domain is present '''
    domain = action_get('domain-name')
    tunnel_name = action_get('tunnel-name')

    status_set('maintenance', 'deleting domain connection: {}'.format(domain))

    """
    $ ip netns exec domain_name ip link set tunnel_name down
    """
    router.ip('netns',
              'exec',
              domain,
              'ip',
              'link',
              'set',
              tunnel_name,
              'down')

    """
    $ ip netns exec domain_name ip tunnel del tunnel_name
    """
    router.ip('netns',
              'exec',
              domain,
              'ip',
              'tunnel',
              'del',
              tunnel_name)

    status_set('active', 'ready!')
def pool_get():
    key = action_get("key")
    pool_name = action_get("pool_name")
    try:
        value = check_output(['ceph', 'osd', 'pool', 'get', pool_name, key])
        return value
    except CalledProcessError as e:
        action_fail(e.message)
Exemplo n.º 28
0
def pool_get():
    key = action_get("key")
    pool_name = action_get("pool_name")
    try:
        value = check_output(['ceph', 'osd', 'pool', 'get', pool_name, key])
        return value
    except CalledProcessError as e:
        action_fail(e.message)
Exemplo n.º 29
0
def pool_get():
    key = action_get("key")
    pool_name = action_get("pool_name")
    try:
        value = (check_output(['ceph', 'osd', 'pool', 'get', pool_name, key])
                 .decode('UTF-8'))
        return value
    except CalledProcessError as e:
        action_fail(str(e))
Exemplo n.º 30
0
def create_network(args):
    net_name = action_get('net-name')
    net_type = action_get('net-type')
    phys_net = action_get('phys-net')

    cmd = "su - ubuntu -c 'source nova.rc && neutron net-create {} --provider:network_type={} \
--provider:physical_network={}'".format(net_name, net_type, phys_net)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 31
0
def add_ogr_vm(args):
    name = action_get('name')
    image_path = action_get('image-path')

    cmd = "su - ubuntu -c 'source nova.rc && glance image-create --name {} \
--visibility public --container-format bare --disk-format qcow2 < {}'".format(
        name, image_path)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 32
0
def traceroute():
    try:
        result, err = _run('traceroute -m {} {}'.format(action_get('hops'), action_get('destination')))
    except:
        action_fail('traceroute command failed')
    else:
        # Here you can send results back from ping, if you had time to parse it
        action_set({'output': result})
    finally:
        remove_flag('actions.traceroute')
Exemplo n.º 33
0
def pingme_forreal():
    try:
        result, err = run('ping -qc {} {}'.format(action_get('count'), action_get('destination')))
    except:
        action_fail('ping command failed')
    finally:
        remove_flag('actions.ping')

    # Here you can send results back from ping, if you had time to parse it
    action_set({'output': result})
Exemplo n.º 34
0
def create_network(args):
    net_name = action_get('net-name')
    net_type = action_get('net-type')
    phys_net = action_get('phys-net')

    cmd = "su - ubuntu -c 'source nova.rc && neutron net-create {} \
--provider:network_type={} --provider:physical_network={}'"\
          .format(net_name, net_type, phys_net)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 35
0
def copy_pool():
    try:
        source = hookenv.action_get("source")
        target = hookenv.action_get("target")
        subprocess.check_call([
            'rados', 'cppool',
            source, target
        ])
    except subprocess.CalledProcessError as e:
        hookenv.action_fail("Error copying pool: {}".format(str(e)))
Exemplo n.º 36
0
def delete_ogr_zone(args):
    aggr_name = action_get('aggregate-name')
    ogr_compute = action_get('ogr-compute')

    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-remove-host {} {}'".format(
        aggr_name, ogr_compute)
    res = commands.getoutput(cmd)
    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-delete {}'".format(
        aggr_name)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 37
0
def set_bitrot_scan_frequency():
    """
    Set the bitrot scan frequency
    """
    vol = action_get("volume")
    frequency = action_get("frequency")
    option = ScrubSchedule.from_str(frequency)
    output = volume_set_bitrot_option(vol, BitrotOption.ScrubFrequency(option))
    if output.is_err():
        action_fail("set bitrot scan frequency failed with error: {}".format(
            output.value))
Exemplo n.º 38
0
def delete_ogr_zone(args):
    aggr_name = action_get('aggregate-name')
    ogr_compute = action_get('ogr-compute')

    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-remove-host {} {}\
'".format(aggr_name, ogr_compute)
    res = commands.getoutput(cmd)
    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-delete {}'"\
          .format(aggr_name)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 39
0
def pingme_forreal():
    try:
        result, err = run('ping -qc {} {}'.format(action_get('count'),
                                                  action_get('destination')))
    except:
        action_fail('ping command failed')
    finally:
        remove_flag('actions.ping')

    # Here you can send results back from ping, if you had time to parse it
    action_set({'output': result})
Exemplo n.º 40
0
def set_bitrot_throttle():
    """
    Set how aggressive bitrot scanning should be
    """
    vol = action_get("volume")
    throttle = action_get("throttle")
    option = ScrubAggression.from_str(throttle)
    output = volume_set_bitrot_option(vol, BitrotOption.ScrubThrottle(option))
    if output.is_err():
        action_fail("set bitrot throttle failed with error: {}".format(
            output.value))
Exemplo n.º 41
0
def set_pool_max_bytes():
    """
    Sets the max bytes quota for a pool.

    Sets the pool quota maximum bytes for the pool specified by
    the action parameter 'name' to the value specified by
    the action parameter 'max'
    """
    pool_name = action_get("name")
    max_bytes = action_get("max")
    set_pool_quota(service='ceph', pool_name=pool_name, max_bytes=max_bytes)
Exemplo n.º 42
0
def configure_hss():
    spgw_ip = action_get('spgw-ip')
    hss_ip = action_get('hss-ip')
    cmd1 = "sudo ip link set ens4 up && sudo dhclient ens4"
    charms.sshproxy._run(cmd1)
    cmd2 = 'sudo sed -i "\'s/$hss_ip/{}/g\'" /etc/nextepc/freeDiameter/hss.conf'.format(
        hss_ip)
    charms.sshproxy._run(cmd2)
    cmd3 = 'sudo sed -i "\'s/$spgw_ip/{}/g\'" /etc/nextepc/freeDiameter/hss.conf'.format(
        spgw_ip)
    charms.sshproxy._run(cmd3)
    remove_flag('actions.configure-hss')
Exemplo n.º 43
0
def create_subnet(args):
    sub_name = action_get('sub-name')
    net_name = action_get('net-name')
    cidr = action_get('cidr')
    pool_start = action_get('pool-start')
    pool_end = action_get('pool-end')

    cmd = "su - ubuntu -c 'source nova.rc && neutron subnet-create --name {} \
{} {} --no-gateway --allocation-pool start={},end={}'"\
          .format(sub_name, net_name, cidr, pool_start, pool_end)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 44
0
def create_subnet(args):
    sub_name = action_get('sub-name')
    net_name = action_get('net-name')
    cidr = action_get('cidr')
    pool_start = action_get('pool-start')
    pool_end = action_get('pool-end')

    cmd = "su - ubuntu -c 'source nova.rc && neutron subnet-create --name {} {} {} \
--no-gateway --allocation-pool start={},end={}'".format(
        sub_name, net_name, cidr, pool_start, pool_end)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 45
0
def set_pool():
    """
    Sets an arbitrary key key in a Ceph pool.

    Sets the key specified by the action parameter 'key' to the value
    specified in the action parameter 'value' for the pool specified
    by the action parameter 'pool_name' using the charmhelpers
    'pool_set' function.
    """
    key = action_get("key")
    value = action_get("value")
    pool_name = action_get("pool_name")
    pool_set(service='ceph', pool_name=pool_name, key=key, value=value)
Exemplo n.º 46
0
def set_pool_max_bytes():
    """
    Sets the max bytes quota for a pool.

    Sets the pool quota maximum bytes for the pool specified by
    the action parameter 'name' to the value specified by
    the action parameter 'max'
    """
    pool_name = action_get("name")
    max_bytes = action_get("max")
    set_pool_quota(service='ceph',
                   pool_name=pool_name,
                   max_bytes=max_bytes)
Exemplo n.º 47
0
def delete_pool_snapshot():
    """
    Delete a pool snapshot.

    Deletes a snapshot from the pool provided by the action
    parameter 'name', with the snapshot name provided by
    action parameter 'snapshot-name'
    """
    pool_name = action_get("name")
    snapshot_name = action_get("snapshot-name")
    remove_pool_snapshot(service='ceph',
                         pool_name=pool_name,
                         snapshot_name=snapshot_name)
Exemplo n.º 48
0
def import_cluster():
    juju_params = {}
    juju_params["juju_controller"] = action_get("juju-controller")
    juju_params["juju_cacert_path"] = _decode_cert(action_get("juju-ca-cert"))
    juju_params["juju_model_id"] = action_get("juju-model-id")
    juju_params["juju_controller_password"] = action_get(
        "juju-controller-password")
    juju_params["juju_controller_user"] = action_get("juju-controller-user")

    res, message = utils.import_cluster(juju_params)
    if not res:
        action_fail(message)
    action_set({'result': message})
Exemplo n.º 49
0
def snapshot_ceph_pool():
    """
    Snapshots a Ceph pool.

    Snapshots the pool provided in action parameter 'name' and
    uses the parameter provided in the action parameter 'snapshot-name'
    as the name for the snapshot.
    """
    pool_name = action_get("name")
    snapshot_name = action_get("snapshot-name")
    snapshot_pool(service='ceph',
                  pool_name=pool_name,
                  snapshot_name=snapshot_name)
Exemplo n.º 50
0
def ogr_zone_detail(args):
    aggr_name = action_get('aggregate-name')

    cmd = "su - ubuntu -c 'source nova.rc && nova aggregate-details {}'"\
          .format(aggr_name)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 51
0
def remove_services(args):
    host = action_get(key="host")
    services = cinder_manage_service_list()

    if host not in ("unused", "",):
        services = [s for s in services if s.host == host]
    else:
        services = [s for s in services if s.host not in DEFAULT_SERVICES]

    removed_services = []

    for service in services:
        log("Removing binary:{}, hostname:{}"
            .format(service.binary, service.host))
        try:
            if CompareOpenStackReleases(os_release("cinder")) >= "liberty":
                cinder_manage_remove(service.binary, service.host)
            else:
                action_fail("Cannot remove service: {}".format(service.host))
        except:
            action_set({'traceback': traceback.format_exc()})
            action_fail("Cannot remove service: {}".format(service.host))
        else:
            removed_services.append(service.host)

    action_set({'removed': ",".join(removed_services)})
Exemplo n.º 52
0
def remove_services():
    load_config_file(os.path.join(os.path.sep, "etc", "cinder", "cinder.conf"))

    host = action_get(key="host")
    services = model_query({}, models.Service, read_deleted="no",
                           session=get_session())

    if host not in ("unused", "",):
        services = services.filter(models.Service.host == host)
    else:
        ands = []
        for service in DEFAULT_SERVICES:
            ands.append(and_(models.Service.host != service))
        services = services.filter(*ands)

    removed_services = []
    ctxt = context.get_admin_context()

    for service in services.all():
        log("Removing service:%d, hostname:%s" % (service.id, service.host))
        try:
            if os_release("cinder") >= "liberty":
                cinder_manage_remove(service.binary, service.host)
            else:
                db.service_destroy(ctxt, service.id)
        except:
            action_set({'traceback': traceback.format_exc()})
            action_fail("Cannot remove service: %s" % service.host)
        else:
            removed_services.append(service.host)

    action_set({'removed': ",".join(removed_services)})
Exemplo n.º 53
0
def manual_backup():
    backend = Backend()
    # keyfile is in vault
    directories_to_backup = action_get('directory-list')
    timestamp = "{:%Y-%m-%d-%H-%M-%S}".format(datetime.datetime.now())
    try:
        log("Running a manual backup on {}".format(directories_to_backup),
            level=DEBUG)
        for directory in directories_to_backup:
            check_output(
                ["/snap/bin/preserve",
                 "--configdir",
                 os.path.join(os.path.expanduser("~"), ".config"),
                 "--loglevel", "error",
                 "create",
                 "{name}-{timestamp}".format(name=directory,
                                             timestamp=timestamp),
                 str(directory),
                 "--backend", backend.get_backend(),
                 "--vault"
                 ])
    except OSError as err:
        log("Create backup failed with error: {}".format(err.message),
            level=ERROR)
        action_fail("List backup failed with error: {}".format(err.message))
Exemplo n.º 54
0
    def service_info(self):
        """Assemble a list of services tempest should tests

        Compare the list of keystone registered services with the services the
        user has requested be tested. If in 'auto' mode test all services
        registered in keystone.

        @returns [svc1, svc2, ...]: List of services to test
        """
        service_info = {}
        tempest_candidates = ['ceilometer', 'cinder', 'glance', 'heat',
                              'horizon', 'ironic', 'neutron', 'nova',
                              'sahara', 'swift', 'trove', 'zaqar', 'neutron']
        present_svcs = self.get_present_services()
        # If not running in an action context asssume auto mode
        try:
            action_args = hookenv.action_get()
        except Exception:
            action_args = {'service-whitelist': 'auto'}
        if action_args['service-whitelist'] == 'auto':
            white_list = []
            for svc in present_svcs:
                if svc in tempest_candidates:
                    white_list.append(svc)
        else:
            white_list = action_args['service-whitelist']
        for svc in tempest_candidates:
            if svc in white_list:
                service_info[svc] = 'true'
            else:
                service_info[svc] = 'false'
        return service_info
Exemplo n.º 55
0
def get_devices():
    devices = []
    for path in hookenv.action_get('osd-devices').split(' '):
        path = path.strip()
        if os.path.isabs(path):
            devices.append(path)

    return devices
Exemplo n.º 56
0
def remove_quota():
    max_files = action_get('max-files')
    max_bytes = action_get('max-bytes')
    directory = action_get('directory')

    if not os.path.exists(directory):
        action_fail("Directory must exist before setting quota")
    attr = "ceph.quota.{}"
    if max_files:
        attr.format("max_files")
    elif max_bytes:
        attr.format("max_bytes")

    try:
        xattr.setxattr(directory, attr, str(0))
    except IOError as err:
        action_fail(
            "Unable to set xattr on {}.  Error: {}".format(directory, err))
Exemplo n.º 57
0
def create_crush_rule():
    """Create a new CRUSH rule."""
    rule_name = hookenv.action_get('name')
    failure_domain = hookenv.action_get('failure-domain')
    device_class = hookenv.action_get('device-class')
    cmd = [
        'ceph', 'osd', 'crush', 'rule',
        'create-replicated',
        rule_name,
        'default',
        failure_domain
    ]
    if device_class:
        cmd.append(device_class)
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError as e:
        hookenv.action_fail(str(e))
Exemplo n.º 58
0
def add_ogr_vm(args):
    name = action_get('name')
    image_path = download_ogr_image()

    cmd = "su - ubuntu -c 'source nova.rc && glance image-create --name {} \
--visibility public --container-format bare --disk-format qcow2 < {}'"\
          .format(name, image_path)
    res = commands.getoutput(cmd)
    action_set({'result-map.message': res})
Exemplo n.º 59
0
def delete_domain_connection():
    ''' Remove the tunnel to another router where the domain is present '''
    domain = action_get('domain-name')
    tunnel_name = action_get('tunnel-name')

    status_set('maintenance', 'deleting domain connection: {}'.format(domain))

    try:

        try:
            """
            $ ip netns exec domain_name ip link set tunnel_name down
            """
            router.ip('netns',
                      'exec',
                      domain,
                      'ip',
                      'link',
                      'set',
                      tunnel_name,
                      'down')
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))

        try:
            """
            $ ip netns exec domain_name ip tunnel del tunnel_name
            """
            router.ip('netns',
                      'exec',
                      domain,
                      'ip',
                      'tunnel',
                      'del',
                      tunnel_name)
        except subprocess.CalledProcessError as e:
            action_fail('Command failed: %s (%s)' %
                        (' '.join(e.cmd), str(e.output)))
    except:
        pass
    finally:
        remove_state('vpe.delete-domain-connection')
        status_set('active', 'ready!')