summaryrefslogtreecommitdiff
path: root/plugins/discovery-ec2/src/test/java/org/elasticsearch/discovery/ec2/Ec2DiscoveryTests.java
blob: bea0df9e8d8c244f1b66482bf49334a040d80e09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.discovery.ec2;

import com.amazonaws.services.ec2.model.Tag;
import org.elasticsearch.Version;
import org.elasticsearch.cloud.aws.AwsEc2Service;
import org.elasticsearch.cloud.aws.AwsEc2Service.DISCOVERY_EC2;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.local.LocalTransport;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

/**
 *
 */
public class Ec2DiscoveryTests extends ESTestCase {

    protected static ThreadPool threadPool;
    protected MockTransportService transportService;

    @BeforeClass
    public static void createThreadPool() {
        threadPool = new ThreadPool(Ec2DiscoveryTests.class.getName());
    }

    @AfterClass
    public static void stopThreadPool() throws InterruptedException {
        if (threadPool !=null) {
            terminate(threadPool);
            threadPool = null;
        }
    }

    @Before
    public void createTransportService() {
        transportService = new MockTransportService(
                Settings.EMPTY,
                new LocalTransport(Settings.EMPTY, threadPool, Version.CURRENT, new NamedWriteableRegistry()), threadPool);
    }

    protected List<DiscoveryNode> buildDynamicNodes(Settings nodeSettings, int nodes) {
        return buildDynamicNodes(nodeSettings, nodes, null);
    }

    protected List<DiscoveryNode> buildDynamicNodes(Settings nodeSettings, int nodes, List<List<Tag>> tagsList) {
        AwsEc2Service awsEc2Service = new AwsEc2ServiceMock(nodeSettings, nodes, tagsList);

        AwsEc2UnicastHostsProvider provider = new AwsEc2UnicastHostsProvider(nodeSettings, transportService,
                awsEc2Service, Version.CURRENT);

        List<DiscoveryNode> discoveryNodes = provider.buildDynamicNodes();
        logger.debug("--> nodes found: {}", discoveryNodes);
        return discoveryNodes;
    }

    public void testDefaultSettings() throws InterruptedException {
        int nodes = randomInt(10);
        Settings nodeSettings = Settings.builder()
                .build();
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes);
        assertThat(discoveryNodes, hasSize(nodes));
    }

    public void testPrivateIp() throws InterruptedException {
        int nodes = randomInt(10);
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.HOST_TYPE, "private_ip")
                .build();
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes);
        assertThat(discoveryNodes, hasSize(nodes));
        // We check that we are using here expected address
        int node = 1;
        for (DiscoveryNode discoveryNode : discoveryNodes) {
            TransportAddress address = discoveryNode.getAddress();
            TransportAddress expected = new LocalTransportAddress(AmazonEC2Mock.PREFIX_PRIVATE_IP + node++);
            assertThat(address.sameHost(expected), is(true));
        }
    }

    public void testPublicIp() throws InterruptedException {
        int nodes = randomInt(10);
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.HOST_TYPE, "public_ip")
                .build();
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes);
        assertThat(discoveryNodes, hasSize(nodes));
        // We check that we are using here expected address
        int node = 1;
        for (DiscoveryNode discoveryNode : discoveryNodes) {
            TransportAddress address = discoveryNode.getAddress();
            TransportAddress expected = new LocalTransportAddress(AmazonEC2Mock.PREFIX_PUBLIC_IP + node++);
            assertThat(address.sameHost(expected), is(true));
        }
    }

    public void testPrivateDns() throws InterruptedException {
        int nodes = randomInt(10);
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.HOST_TYPE, "private_dns")
                .build();
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes);
        assertThat(discoveryNodes, hasSize(nodes));
        // We check that we are using here expected address
        int node = 1;
        for (DiscoveryNode discoveryNode : discoveryNodes) {
            String instanceId = "node" + node++;
            TransportAddress address = discoveryNode.getAddress();
            TransportAddress expected = new LocalTransportAddress(
                    AmazonEC2Mock.PREFIX_PRIVATE_DNS + instanceId + AmazonEC2Mock.SUFFIX_PRIVATE_DNS);
            assertThat(address.sameHost(expected), is(true));
        }
    }

    public void testPublicDns() throws InterruptedException {
        int nodes = randomInt(10);
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.HOST_TYPE, "public_dns")
                .build();
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes);
        assertThat(discoveryNodes, hasSize(nodes));
        // We check that we are using here expected address
        int node = 1;
        for (DiscoveryNode discoveryNode : discoveryNodes) {
            String instanceId = "node" + node++;
            TransportAddress address = discoveryNode.getAddress();
            TransportAddress expected = new LocalTransportAddress(
                    AmazonEC2Mock.PREFIX_PUBLIC_DNS + instanceId + AmazonEC2Mock.SUFFIX_PUBLIC_DNS);
            assertThat(address.sameHost(expected), is(true));
        }
    }

    public void testInvalidHostType() throws InterruptedException {
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.HOST_TYPE, "does_not_exist")
                .build();
        try {
            buildDynamicNodes(nodeSettings, 1);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage(), containsString("No enum constant"));
        }
    }

    public void testFilterByTags() throws InterruptedException {
        int nodes = randomIntBetween(5, 10);
        Settings nodeSettings = Settings.builder()
                .put(DISCOVERY_EC2.TAG_PREFIX + "stage", "prod")
                .build();

        int prodInstances = 0;
        List<List<Tag>> tagsList = new ArrayList<>();

        for (int node = 0; node < nodes; node++) {
            List<Tag> tags = new ArrayList<>();
            if (randomBoolean()) {
                tags.add(new Tag("stage", "prod"));
                prodInstances++;
            } else {
                tags.add(new Tag("stage", "dev"));
            }
            tagsList.add(tags);
        }

        logger.info("started [{}] instances with [{}] stage=prod tag");
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes, tagsList);
        assertThat(discoveryNodes, hasSize(prodInstances));
    }

    public void testFilterByMultipleTags() throws InterruptedException {
        int nodes = randomIntBetween(5, 10);
        Settings nodeSettings = Settings.builder()
                .putArray(DISCOVERY_EC2.TAG_PREFIX + "stage", "prod", "preprod")
                .build();

        int prodInstances = 0;
        List<List<Tag>> tagsList = new ArrayList<>();

        for (int node = 0; node < nodes; node++) {
            List<Tag> tags = new ArrayList<>();
            if (randomBoolean()) {
                tags.add(new Tag("stage", "prod"));
                if (randomBoolean()) {
                    tags.add(new Tag("stage", "preprod"));
                    prodInstances++;
                }
            } else {
                tags.add(new Tag("stage", "dev"));
                if (randomBoolean()) {
                    tags.add(new Tag("stage", "preprod"));
                }
            }
            tagsList.add(tags);
        }

        logger.info("started [{}] instances with [{}] stage=prod tag");
        List<DiscoveryNode> discoveryNodes = buildDynamicNodes(nodeSettings, nodes, tagsList);
        assertThat(discoveryNodes, hasSize(prodInstances));
    }

    abstract class DummyEc2HostProvider extends AwsEc2UnicastHostsProvider {
        public int fetchCount = 0;
        public DummyEc2HostProvider(Settings settings, TransportService transportService, AwsEc2Service service, Version version) {
            super(settings, transportService, service, version);
        }
    }

    public void testGetNodeListEmptyCache() throws Exception {
        AwsEc2Service awsEc2Service = new AwsEc2ServiceMock(Settings.EMPTY, 1, null);
        DummyEc2HostProvider provider = new DummyEc2HostProvider(Settings.EMPTY, transportService, awsEc2Service, Version.CURRENT) {
            @Override
            protected List<DiscoveryNode> fetchDynamicNodes() {
                fetchCount++;
                return new ArrayList<>();
            }
        };
        for (int i=0; i<3; i++) {
            provider.buildDynamicNodes();
        }
        assertThat(provider.fetchCount, is(3));
    }

    public void testGetNodeListCached() throws Exception {
        Settings.Builder builder = Settings.settingsBuilder()
                .put(DISCOVERY_EC2.NODE_CACHE_TIME, "500ms");
        AwsEc2Service awsEc2Service = new AwsEc2ServiceMock(Settings.EMPTY, 1, null);
        DummyEc2HostProvider provider = new DummyEc2HostProvider(builder.build(), transportService, awsEc2Service, Version.CURRENT) {
            @Override
            protected List<DiscoveryNode> fetchDynamicNodes() {
                fetchCount++;
                return Ec2DiscoveryTests.this.buildDynamicNodes(Settings.EMPTY, 1);
            }
        };
        for (int i=0; i<3; i++) {
            provider.buildDynamicNodes();
        }
        assertThat(provider.fetchCount, is(1));
        Thread.sleep(1_000L); // wait for cache to expire
        for (int i=0; i<3; i++) {
            provider.buildDynamicNodes();
        }
        assertThat(provider.fetchCount, is(2));
    }
}