def cleanup():
    # Iterate over all resources with label from this deployer
    # Remove all which are not needed anymore
    needed_apps = unitdata.kv().get('used_apps', [])
    all_apps = get_label_values_per_deployer(
        config.get('namespace').rstrip(),
        unitdata.kv().get('juju_app_selector'),
        unitdata.kv().get('deployer_selector') + '=' +
        os.environ['JUJU_UNIT_NAME'].split('/')[0])
    for app in all_apps:
        if app not in needed_apps:
            # Remove resource via label
            delete_resources_by_label(
                config.get('namespace').rstrip(), ['all,cm,secrets'],
                unitdata.kv().get('juju_app_selector') + '=' + app)
    unitdata.kv().set('used_apps', [])

    if config.changed('namespace') and config.previous('namespace').rstrip():
        log('Checking if previous namespace still has resources, if not delete namespace ('
            + config.previous('namespace').rstrip() + ')')
        namespace = ResourceFactory.create_resource(
            'namespace', {'name': config.previous('namespace').rstrip()})
        namespace.delete_resource()
    clear_flag('resources.created')
    clear_flag('endpoint.kubernetes-deployer.cleanup')
Example #2
0
def send_requests(requests):
    error_states = {}
    for uuid in requests:
        resource_id = 0
        for resource in requests[uuid]['requests']:
            # Check if there is a naming conflict in the namespace
            if resource_name_duplicate(resource, uuid):
                error_states[uuid] = {
                    'error':
                    'Duplicate name for resource: ' +
                    resource['metadata']['name']
                }
                log('Duplicate name for resource: ' +
                    resource['metadata']['name'])
                continue
            prepared_request = {
                'uuid': uuid,
                'resource': resource,
                'namespace': unitdata.kv().get('namespace').rstrip(),
                'unique_id': resource_id,
                'model_uuid': requests[uuid]['model_uuid'],
                'juju_unit': requests[uuid]['juju_unit'],
            }
            resource_id += 1
            pre_resource = ResourceFactory.create_resource(
                'preparedresource', prepared_request)
            pre_resource.write_resource_file()
            if not pre_resource.create_resource():
                error_states[uuid] = {
                    'error': 'Could not create requested resources.'
                }
    # Save the error states so update_status_info handler can report them
    unitdata.kv().set('error-states', error_states)
def configure_headless_services(requests):
    """Create requested headless services.
    
    Args:
        requests (list): list with requests
    Return:
        running services (dict)
    """
    application_names = {}
    service_names = {}
    for request in requests:
        application_names[request['unit'].split('/')[0]] = request
    for app, hs_req in application_names.items():
        request = {
            'name': app,
            'namespace': config.get('namespace').rstrip(),
            'port': hs_req['port'],
            'ips': hs_req['ips']
        }
        headless_service = ResourceFactory.create_resource(
            'headless-service', request)
        headless_service.write_resource_file()
        service_names[headless_service.name()] = app
    headless_service.create_resource(
    )  # One call to create resources will create all new / modified services
    used_apps = unitdata.kv().get('used_apps', [])
    unitdata.kv().set('used_apps',
                      list(set(used_apps) | application_names.keys()))
    return get_running_info(service_names)
def configure_deployment(app, request, application_units, secret):
    deployment_request = {
        'name': app,
        'replicas': len(application_units),
        'image': request['image'],
        'namespace': config.get('namespace').rstrip(),
        'rolling': config.get('rolling-updates'),
        'env_vars': {
            'units': ' '.join(application_units)
        }
    }
    if 'env' in request:
        deployment_request['env_vars'] = {
            **deployment_request['env_vars'],
            **request['env']
        }
        sorted_env_keys = sorted(deployment_request['env_vars'].keys()
                                 )  # Sort for the same pod hash
        deployment_request['env_order'] = sorted_env_keys
    if secret:
        deployment_request['secret'] = secret.name()
    deployment = ResourceFactory.create_resource('deployment',
                                                 deployment_request)
    deployment.write_resource_file()
    return deployment
Example #5
0
def configure_namespace():
    namespace = ResourceFactory.create_resource(
        'namespace', {
            'name': unitdata.kv().get('namespace').rstrip(),
            'deployer': deployer
        })
    namespace.write_resource_file()
    namespace.create_resource()
def configure_namespace():
    namespace = ResourceFactory.create_resource(
        'namespace', {
            'name': config.get('namespace', 'default').rstrip(),
            'deployer': deployer
        })
    namespace.write_resource_file()
    namespace.create_resource()
    # Check if config.namespace changed
    if config.changed('namespace') and config.previous('namespace'):
        # Remove all resources from previous namespace created by this deployer
        prev_namespace = ResourceFactory.create_resource(
            'namespace', {
                'name': config.previous('namespace').rstrip(),
                'deployer': deployer
            })
        prev_namespace.delete_namespace_resources()
def configure_service(app, request):
    service = None
    if 'ports' in request:
        service_request = {
            'name': app,
            'ports': get_ports_context(request),
            'namespace': config.get('namespace', 'default').rstrip()
        }
        service = ResourceFactory.create_resource('service', service_request)
        service.write_resource_file()
    return service
def new_resource_request(dep, kube):
    status_set('active', 'Processing resource requests')
    configure_namespace()
    requests = dep.get_resource_requests()
    # Remove all config files since we are recreating them from the new requests
    clean_deployer_config(['resources'])
    # Store all uuids in the kv store so we can check later in the cleanup handler
    # which are still in use (= still have a relation with the deployer)
    unitdata.kv().set('used_apps', list(requests.keys()))
    error_states = {}
    for uuid in requests:
        resource_id = 0
        for resource in requests[uuid]['requests']:
            # Check if there is a naming conflict in the namespace
            if resource_name_duplicate(resource, uuid):
                error_states[uuid] = {
                    'error':
                    'Duplicate name for resource: ' +
                    resource['metadata']['name']
                }
                log('Duplicate name for resource: ' +
                    resource['metadata']['name'])
                continue
            prepared_request = {
                'uuid': uuid,
                'resource': resource,
                'namespace': config.get('namespace').rstrip(),
                'unique_id': resource_id,
                'model_uuid': requests[uuid]['model_uuid'],
                'juju_unit': requests[uuid]['juju_unit'],
            }
            resource_id += 1
            pre_resource = ResourceFactory.create_resource(
                'preparedresource', prepared_request)
            pre_resource.write_resource_file()
            if not pre_resource.create_resource():
                error_states[uuid] = {
                    'error': 'Could not create requested resources.'
                }
    # Save the error states so update_status_info handler can report them
    unitdata.kv().set('error-states', error_states)
    if error_states:
        status_set(
            'active',
            'Could not create requested resources, check the deployer log for more details.'
        )
    else:
        status_set('active', 'Ready')
    set_flag('resources.created')
    clear_flag('endpoint.kubernetes-deployer.resources-changed')
def create_policies():
    configure_namespace()
    request = {
        'namespace': config['namespace'].rstrip(''),
        'name': os.environ['JUJU_UNIT_NAME'].replace('/', '-')
    }
    policy = ResourceFactory.create_resource('network-policy', request)
    if not config['isolated']:
        policy.delete_resource()
        return
    if config.changed('namespace') and config.previous('namespace').rstrip():
        policy.delete_resource()
    policy.write_resource_file()
    policy.create_resource()
def configure_secret(app, request, application_names):
    secret = None
    # Check if request has secret info
    if is_secret_image(application_names[app]):
        secret = ResourceFactory.create_resource(
            'secret', {
                'username': request['username'],
                'password': request['password'],
                'docker-registry': request['docker-registry'],
                'deployer': deployer,
                'app': app,
                'namespace': config.get('namespace', 'default').rstrip()
            })
        secret.create_resource()
    return secret