Configuration Service

Fit in NEANIAS Ecosystem

The NEANIAS Configuration Management Service provides a key value storage for storing configurations that will be used by NEANIAS services. Configurations are created or updated using the respective API available allowing for consistnet integration at bootstrap and runtime.

The NEANIAS Configuration Management Service is backed by a distributed, highly available system. The storage can be replicated across multiple nodes of the service to guarantee data redundancy.

NEANIAS Configuration Management Service operates as a key / value store. Data will is stored using a unique hierarchical key that allows nesting and can be accessed using the same key.

Restricted access is offered (ACLs) in order to restrict the actions (read/write) clients can perform.

The main interface to NEANIAS Configuration Management Service is offred through a set of low level binding clients. All requests will require authentication and client service will be able to perform updates to specific keys.

Technology

The Configuration Management Service is backed by Apache Zookeer (https://zookeeper.apache.org/).

ZooKeeper is a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services.

Distributed System

The service itself is distributed and highly reliable. It handles internally aspects pertinent to its distributed nature such as

  • Consensus
  • Group management
  • Presence protocols

ZooKeeper allows distributed processes to coordinate with each other through a shared hierarchical name space of data registers (znodes), much like a file system. Unlike normal file systems ZooKeeper provides its clients with high throughput, low latency, highly available, strictly ordered access to the znodes.

  • The performance aspects of ZooKeeper allow it to be used in large distributed systems.
  • The reliability aspects prevent it from becoming the single point of failure in big systems.
  • Its strict ordering allows sophisticated synchronization primitives to be implemented at the client.

The service itself is replicated over a set of machines that comprise the service. These machines maintain an in-memory image of the data tree along with a transaction logs and snapshots in a persistent store.

Hierarchical Model

The namespace provided by ZooKeeper is much like that of a standard file system. A name is a sequence of path elements separated by a slash (“/”). Every znode in ZooKeeper’s name space is identified by a path. And every znode has a parent whose path is a prefix of the znode with one less element; the exception to this rule is root (“/”) which has no parent. Also, exactly like standard file systems, a znode cannot be deleted if it has any children.

The main differences between ZooKeeper and standard file systems are that every znode can have data associated with it (every file can also be a directory and vice-versa) and znodes are limited to the amount of data that they can have. ZooKeeper was designed to store coordination data: status information, configuration, location information, etc. This kind of meta-information is usually measured in kilobytes, if not bytes. ZooKeeper has a built-in sanity check of 1M, to prevent it from being used as a large data store, but in general it is used to store much smaller pieces of data.

The configured path that a service can store it’s configuration follows the concept : /configuration/application_name/configuration where :

  1. application_name is the configured name of the service.
  2. configuration is the configuration data of the service.

So for example the below configuration of service with name service-1 :

{
	"host": "db.neanias.eu",
	"port": "5432",
	"name":	"db"
}

will be found under the path /configuration/service-1

Bindings

The servers that make up the ZooKeeper service must all know about each other. As long as a majority of the servers are available, the ZooKeeper service will be available. Clients must also know the list of servers. The clients create a handle to the ZooKeeper service using this list of servers.

Clients only connect to a single ZooKeeper server. The client maintains a TCP connection through which it sends requests, gets responses, gets watch events, and sends heartbeats. If the TCP connection to the server breaks, the client will connect to a different server. When a client first connects to the ZooKeeper service, the first ZooKeeper server will setup a session for the client. If the client needs to connect to another server, this session will get reestablished with the new server.

Available client bindings exist and are available for the following languages:

  • Java
  • Python
  • C#
  • Node.js
  • C
  • Go
  • Perl
  • Scala
  • Twisted/Python
  • Erlang
  • Haskell
  • Ruby
  • Lua

Examples

The following example showcases a simple integration of the Service Instance Registry to a Spring Boot Java application retrieving available instances. For a ready-to-go sample navigate under the spring-boot-client folder at the https://gitlab.neanias.eu/configuration-service/docs repository.

These example aim to provide an overview of the integration and do not reflect the final hierarchy model or security considerations. ZooKeeper resources provide a lot of information on most of the common and exotic topics that may need to be considered.

Configuring the dependencies :

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/>
	</parent>


	<properties>
		<java.version>11</java.version>

		<curator.version>5.1.0</curator.version>
		<zookeeper.version>3.6.2</zookeeper.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>${curator.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-x-discovery</artifactId>
			<version>${curator.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-framework</artifactId>
			<version>${curator.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>${zookeeper.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

Configuring the application properties :

spring.application.name=service-1
zookeeper.connect-string=localhost:2281

server.port=8091
server.ssl.enabled=true
server.ssl.protocol=TLSv1.2
server.ssl.key-store=classpath:ssl/client.jks
server.ssl.key-store-password=password
server.ssl.key-store-type=JKS
server.ssl.trust-store=classpath:ssl/client-trustore.jks
server.ssl.trust-store-password=password
server.ssl.trust-store-type=JKS

zookeeper.ssl.client.certificate.alias=client

The configuration object that we want to be retrieving :

package eu.neanias.example.configuration;

import java.util.Map;

public class DbProperties {
	private final String host;
	private final String port;
	private final String name;

	public DbProperties(String host, String port, String name) {
		this.host = host;
		this.port = port;
		this.name = name;
	}

	public DbProperties(Map<String, String> config) {
		this.host = config.get("host");
		this.port = config.get("port");
		this.name = config.get("name");
	}

	public String getHost() {
		return host;
	}

	public String getPort() {
		return port;
	}

	public String getName() {
		return name;
	}
}

Retrieving and managing the configuration values :

package eu.neanias.configuration.demo.service;

public interface NeaniasConfigurationService {
	void createConfiguration(Object configuration) throws Exception;

	void updateConfiguration(Object configuration) throws Exception;

	void removeConfiguration() throws Exception;

	<T> T getConfiguration(Class<T> configType) throws Exception;
}
package eu.neanias.configuration.demo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DefaultNeaniasNeaniasConfigurationService implements NeaniasConfigurationService {
    private static final String CONFIG_ROOT = "configuration";

    private static final ObjectMapper mapper = new ObjectMapper();

    private final CuratorFramework curator;

    private final String serviceConfigRoot;

    public DefaultNeaniasNeaniasConfigurationService(CuratorFramework curator, @Value("${spring.application.name}") String serviceName) {
        this.curator = curator;
        this.serviceConfigRoot = "/" + CONFIG_ROOT + "/" + serviceName;
    }

    @Override
    public void createConfiguration(Object configuration) throws Exception {
        if (curator.checkExists().forPath(serviceConfigRoot) != null) {
            return;
        }

        byte[] data = configuration != null ? mapper.writeValueAsBytes(configuration) : new byte[0];
        curator.create().creatingParentContainersIfNeeded().forPath(serviceConfigRoot, data);
    }

    @Override
    public void updateConfiguration(Object configuration) throws Exception {
        if (curator.checkExists().forPath(serviceConfigRoot) == null) {
            throw new IllegalArgumentException("Configuration does not exist");
        }

        byte[] data = configuration != null ? mapper.writeValueAsBytes(configuration) : new byte[0];
        curator.setData().forPath(serviceConfigRoot, data);
    }

    @Override
    public void removeConfiguration() throws Exception {
        if (curator.checkExists().forPath(serviceConfigRoot) == null) {
            return;
        }

        curator.delete().forPath(serviceConfigRoot);
    }

    @Override
    public <T> T getConfiguration(Class<T> configType) throws Exception {
        if (curator.checkExists().forPath(serviceConfigRoot) == null) {
            return null;
        }

        byte[] pathData = curator.getData().forPath(serviceConfigRoot);
        return mapper.readValue(pathData, configType);
    }
}

Configuring Curator client and establishing a connection :

package eu.neanias.configuration.demo.configuration;

import eu.neanias.configuration.demo.certificate.CertificateLoader;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.KeyStoreException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class CuratorConfiguration {
	private static final String ALIAS_PROPERTY_NAME = "zookeeper.ssl.client.certificate.alias";

	@Bean
	public CuratorFramework curatorFramework(
		CertificateLoader certificateLoader,
		@Value("${zookeeper.ssl.client.certificate.alias}") String alias,
		@Value("${zookeeper.connect-string}") String connectString
	) throws KeyStoreException, CertificateEncodingException {
		X509Certificate certificate = (X509Certificate) certificateLoader.loadCertificate(alias);
		byte[] certificateData = certificate.getEncoded();

		CuratorFramework curator =
			CuratorFrameworkFactory.builder()
				.connectString(connectString)
				.retryPolicy(new ExponentialBackoffRetry(2000, 5))
				.authorization("x509", certificateData)
				.aclProvider(aclProvider())
				.build();

		curator.start();

		return curator;
	}

	private ACLProvider aclProvider() {
		return new ACLProvider() {
			@Override
			public List<ACL> getDefaultAcl() {
				List<ACL> acls = new ArrayList<>();
				ACL defaultPermission = new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE);
				acls.add(defaultPermission);
				return acls;
			}

			@Override
			public List<ACL> getAclForPath(String path) {
				List<ACL> acls = new ArrayList<>();
				ACL defaultPermission = new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE);
				acls.add(defaultPermission);
				return acls;
			}
		};
	}
}

Configuring a loader for the client’s certificate :

package eu.neanias.configuration.demo.certificate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

@Component
public class CertificateLoader {
    private static final String DEFAULT_KEY_STORE_TYPE = "JKS";

    private final KeyStore keyStore;

    @Autowired
    public CertificateLoader(Environment environment, ResourceLoader resourceLoader) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
        String keyStoreFile = environment.getProperty("server.ssl.key-store");
        String keyStorePassword = environment.getProperty("server.ssl.key-store-password");
        String keyStoreType = environment.getProperty("server.ssl.key-store-type");

        if (keyStoreFile == null || keyStoreFile.isBlank()) {
            throw new IllegalArgumentException("Property server.ssl.key-store must be defined");
        }
        if (keyStorePassword == null || keyStorePassword.isBlank()) {
            throw new IllegalArgumentException("Property server.ssl.key-store-password must be defined");
        }
        if (keyStoreType == null || keyStoreType.isBlank()) {
            keyStoreType = DEFAULT_KEY_STORE_TYPE;
        }

        keyStore = KeyStore.getInstance(keyStoreType);

        FileInputStream keyStoreFileInput = new FileInputStream(resourceLoader.getResource(keyStoreFile).getFile());
        keyStore.load(keyStoreFileInput, keyStorePassword.toCharArray());
    }

    public Certificate loadCertificate(String alias) throws KeyStoreException {
        return keyStore.getCertificate(alias);
    }
}

Configuring a test suite for the above implementation :

package eu.neanias.configuration.demo;

public class DbProperties {
    private String host;
    private String port;
    private String name;

    public DbProperties() {
    }

    public DbProperties(String host, String port, String name) {
        this.host = host;
        this.port = port;
        this.name = name;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package eu.neanias.configuration.demo;

import eu.neanias.configuration.demo.service.NeaniasConfigurationService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class ConfigurationRetrievalTests {
	static {
		System.setProperty("zookeeper.clientCnxnSocket", "org.apache.zookeeper.ClientCnxnSocketNetty");
		System.setProperty("zookeeper.client.secure", "true");
		System.setProperty("zookeeper.ssl.client.enable", "true");
		System.setProperty("zookeeper.ssl.keyStore.location", "{{your_path}}\\src\\main\\resources\\ssl\\client1.keystore");
		System.setProperty("zookeeper.ssl.keyStore.password", "password");
		System.setProperty("zookeeper.ssl.keyStore.type", "JKS");
		System.setProperty("zookeeper.ssl.trustStore.location", "{{your_path}}\\src\\main\\resources\\ssl\\client1.truststore");
		System.setProperty("zookeeper.ssl.trustStore.password", "password");
		System.setProperty("zookeeper.ssl.trustStore.type", "JKS");
		System.setProperty("zookeeper.ssl.protocol", "TLSv1.2");
	}

	private static final DbProperties configuration = new DbProperties("db.neanias.eu", "5432", "db");

	@Autowired
	protected NeaniasConfigurationService neaniasConfigurationService;

	@Value("${spring.application.name}")
	protected String serviceName;

	@Test
	void testGetConfiguration() throws Exception {
		neaniasConfigurationService.createConfiguration(configuration);

		DbProperties dbProperties = neaniasConfigurationService.getConfiguration(DbProperties.class);

		neaniasConfigurationService.removeConfiguration();

		assertThat(dbProperties.getHost()).isEqualTo(configuration.getHost());
		assertThat(dbProperties.getPort()).isEqualTo(configuration.getPort());
		assertThat(dbProperties.getName()).isEqualTo(configuration.getName());
	}

	@Test
	void testRemoveConfiguration() throws Exception {
		neaniasConfigurationService.createConfiguration(configuration);

		neaniasConfigurationService.removeConfiguration();

		DbProperties dbProperties = neaniasConfigurationService.getConfiguration(DbProperties.class);

		assertThat(dbProperties).isNull();
	}

	@Test
	void testUpdateConfiguration() throws Exception {
		neaniasConfigurationService.createConfiguration(configuration);
		DbProperties currentDbProperties = neaniasConfigurationService.getConfiguration(DbProperties.class);

		currentDbProperties.setPort("9876");

		neaniasConfigurationService.updateConfiguration(currentDbProperties);

		DbProperties updatedDbProperties = neaniasConfigurationService.getConfiguration(DbProperties.class);

		neaniasConfigurationService.removeConfiguration();


		assertThat(updatedDbProperties.getHost()).isEqualTo(currentDbProperties.getHost());
		assertThat(updatedDbProperties.getPort()).isEqualTo(currentDbProperties.getPort());
		assertThat(updatedDbProperties.getName()).isEqualTo(currentDbProperties.getName());
	}
}

Permissions and access control configuration

The current implementation grants all access permissions to every authenticated service that needs to set a configuration. This behaviour can be overriden by changing the getDefaultAcl and getAclForPath methods of the aclProvider in the CuratorConfiguration class.

Client configuration

To establish an ssl connection, the client must create a keystore file containing an entry with the client’s private/public key pair, and a truststore file containing a public trusted certificate.

Keystore configuration

In order to create a keystore using a private key (ex. client.pem) and a public certificate (ex. client.cert), create a keystore in pkcs12 format and then transform it into a jks format :

1. openssl pkcs12 -export -in client.cert -inkey client.pem -out clientkeystore.p12
2. keytool -importkeystore -srckeystore clientkeystore.p12 -srcstoretype pkcs12 -destkeystore client.jks -deststoretype JKS

The created client.jks keystore contains an entry combining the information from both private and public keys but has the default alias, so in order to change it into the correct alias name (ex. client-name) :

1. keytool -changealias -alias default-alias -destalias client-name -keystore client.jks

Truststore configuration

In order to create a truststore using a trusted public certificate from a server (ex. server.cert) with an alias (ex. server-name) :

1. keytool -import -alias server-name -file server.cert -storetype JKS -keystore client-truststore.jks

Java VM options

-Dzookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
-Dzookeeper.client.secure=true
-Dzookeeper.ssl.keyStore.location=path\client.jks
-Dzookeeper.ssl.keyStore.password=password
-Dzookeeper.ssl.keyStore.type=JKS
-Dzookeeper.ssl.trustStore.location=path\client-truststore.jks
-Dzookeeper.ssl.trustStore.password=password
-Dzookeeper.ssl.trustStore.type=JKS