summaryrefslogtreecommitdiff
path: root/ambari-server/src/test/java/org/apache/ambari/server/notifications/dispatchers/AlertScriptDispatcherTest.java
blob: 12141c9992eb4eab5a3b909cecc100b5fc4e73a9 (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
278
279
280
281
282
283
284
285
286
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.apache.ambari.server.notifications.dispatchers;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.Executor;

import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.notifications.DispatchCallback;
import org.apache.ambari.server.notifications.DispatchFactory;
import org.apache.ambari.server.notifications.Notification;
import org.apache.ambari.server.notifications.NotificationDispatcher;
import org.apache.ambari.server.state.alert.AlertNotification;
import org.apache.ambari.server.state.alert.TargetType;
import org.apache.ambari.server.state.stack.OsFamily;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 * Tests {@link AlertScriptDispatcher}.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ProcessBuilder.class, AlertScriptDispatcher.class })
public class AlertScriptDispatcherTest {

  private static final String SCRIPT_CONFIG_VALUE = "/foo/script.py";

  private Injector m_injector;

  @Inject
  private DispatchFactory m_dispatchFactory;

  @Inject
  private Configuration m_configuration;

  @Before
  public void before() throws Exception {
    m_injector = Guice.createInjector(new MockModule());
    m_injector.injectMembers(this);
  }

  /**
   * Tests that a callback error happens when the notification is not an
   * {@link AlertNotification}.
   */
  @Test
  public void testNonAlertNotification() throws Exception {
    DispatchCallback callback = EasyMock.createNiceMock(DispatchCallback.class);
    Notification notification = EasyMock.createNiceMock(Notification.class);
    notification.Callback = callback;
    notification.CallbackIds = Collections.singletonList(UUID.randomUUID().toString());

    callback.onFailure(notification.CallbackIds);
    EasyMock.expectLastCall().once();

    EasyMock.replay(callback, notification);

    NotificationDispatcher dispatcher = m_dispatchFactory.getDispatcher(TargetType.ALERT_SCRIPT.name());
    dispatcher.dispatch(notification);

    EasyMock.verify(callback, notification);
  }

  /**
   * Tests that a missing script property results in a callback failure.
   */
  @Test
  public void testMissingScriptConfiguration() throws Exception {
    m_configuration.setProperty(AlertScriptDispatcher.SCRIPT_CONFIG_DEFAULT_KEY, null);

    DispatchCallback callback = EasyMock.createNiceMock(DispatchCallback.class);
    AlertNotification notification = new AlertNotification();
    notification.Callback = callback;
    notification.CallbackIds = Collections.singletonList(UUID.randomUUID().toString());

    callback.onFailure(notification.CallbackIds);
    EasyMock.expectLastCall().once();

    EasyMock.replay(callback);

    NotificationDispatcher dispatcher = m_dispatchFactory.getDispatcher(TargetType.ALERT_SCRIPT.name());
    dispatcher.dispatch(notification);

    EasyMock.verify(callback);
  }

  /**
   * Tests a successfull invocation of the script.
   *
   * @throws Exception
   */
  @Test
  public void testProcessBuilderInvocation() throws Exception {
    DispatchCallback callback = EasyMock.createNiceMock(DispatchCallback.class);
    AlertNotification notification = new AlertNotification();
    notification.Callback = callback;
    notification.CallbackIds = Collections.singletonList(UUID.randomUUID().toString());

    callback.onSuccess(notification.CallbackIds);
    EasyMock.expectLastCall().once();

    AlertScriptDispatcher dispatcher = (AlertScriptDispatcher) m_dispatchFactory.getDispatcher(TargetType.ALERT_SCRIPT.name());
    m_injector.injectMembers(dispatcher);

    ProcessBuilder powerMockProcessBuilder = m_injector.getInstance(ProcessBuilder.class);
    EasyMock.expect(dispatcher.getProcessBuilder(SCRIPT_CONFIG_VALUE, notification)).andReturn(
        powerMockProcessBuilder).once();

    EasyMock.replay(callback, dispatcher);

    dispatcher.dispatch(notification);

    EasyMock.verify(callback, dispatcher);
    PowerMock.verifyAll();
  }

  /**
   * Tests that we will pickup the correct script when its specified on the
   * notification.
   */
  @Test
  public void testCustomScriptConfiguration() throws Exception {
    // remove the default value from configuration and put the customized value
    final String customScriptKey = "foo.bar.key";
    final String customScriptValue = "/foo/bar/foobar.py";
    m_configuration.setProperty(AlertScriptDispatcher.SCRIPT_CONFIG_DEFAULT_KEY, null);
    m_configuration.setProperty(customScriptKey, customScriptValue);

    DispatchCallback callback = EasyMock.createNiceMock(DispatchCallback.class);
    AlertNotification notification = new AlertNotification();
    notification.Callback = callback;
    notification.CallbackIds = Collections.singletonList(UUID.randomUUID().toString());

    // put the custom config value
    notification.DispatchProperties = new HashMap<String, String>();
    notification.DispatchProperties.put(AlertScriptDispatcher.DISPATCH_PROPERTY_SCRIPT_CONFIG_KEY,
        customScriptKey);

    callback.onSuccess(notification.CallbackIds);
    EasyMock.expectLastCall().once();

    AlertScriptDispatcher dispatcher = (AlertScriptDispatcher) m_dispatchFactory.getDispatcher(TargetType.ALERT_SCRIPT.name());
    m_injector.injectMembers(dispatcher);

    ProcessBuilder powerMockProcessBuilder = m_injector.getInstance(ProcessBuilder.class);
    EasyMock.expect(dispatcher.getProcessBuilder(customScriptValue, notification)).andReturn(
        powerMockProcessBuilder).once();

    EasyMock.replay(callback, dispatcher);

    dispatcher.dispatch(notification);

    EasyMock.verify(callback, dispatcher);
    PowerMock.verifyAll();
  }

  /**
   * Tests that a process with an error code of 255 causes the failure callback
   * to be invoked.
   *
   * @throws Exception
   */
  @Test
  public void testFailedProcess() throws Exception {
    DispatchCallback callback = EasyMock.createNiceMock(DispatchCallback.class);
    AlertNotification notification = new AlertNotification();
    notification.Callback = callback;
    notification.CallbackIds = Collections.singletonList(UUID.randomUUID().toString());

    callback.onFailure(notification.CallbackIds);
    EasyMock.expectLastCall().once();

    AlertScriptDispatcher dispatcher = (AlertScriptDispatcher) m_dispatchFactory.getDispatcher(TargetType.ALERT_SCRIPT.name());
    m_injector.injectMembers(dispatcher);

    ProcessBuilder powerMockProcessBuilder = m_injector.getInstance(ProcessBuilder.class);
    EasyMock.expect(dispatcher.getProcessBuilder(SCRIPT_CONFIG_VALUE, notification)).andReturn(
        powerMockProcessBuilder).once();

    Process mockProcess = powerMockProcessBuilder.start();
    EasyMock.expect(mockProcess.exitValue()).andReturn(255).anyTimes();

    EasyMock.replay(callback, dispatcher, mockProcess);

    dispatcher.dispatch(notification);

    EasyMock.verify(callback, dispatcher);
    PowerMock.verifyAll();
  }

  /**
   *
   */
  private class MockModule extends AbstractModule {

    /**
     * {@inheritDoc}
     */
    @Override
    protected void configure() {
      try {
        // populate configuration with the 1 config we need
        Configuration configuration = new Configuration();
        configuration.setProperty(AlertScriptDispatcher.SCRIPT_CONFIG_DEFAULT_KEY, SCRIPT_CONFIG_VALUE);

        // do some basic bindings
        DispatchFactory dispatchFactory = DispatchFactory.getInstance();
        bind(DispatchFactory.class).toInstance(dispatchFactory);
        bind(Configuration.class).toInstance(configuration);
        bind(OsFamily.class).toInstance(EasyMock.createNiceMock(OsFamily.class));

        // mock the dispatcher to return our doctored ProcessBuilder
        AlertScriptDispatcher dispatcher = EasyMock.createMockBuilder(AlertScriptDispatcher.class).addMockedMethods(
            "getProcessBuilder").createNiceMock();

        // make the executor synchronized for testing
        SynchronizedExecutor synchronizedExecutor = new SynchronizedExecutor();
        Field field = AlertScriptDispatcher.class.getDeclaredField("m_executor");
        field.setAccessible(true);
        field.set(dispatcher, synchronizedExecutor);

        // since we're bypassing normal bootstrapping, register the dispatcher
        // manually
        dispatchFactory.register(dispatcher.getType(), dispatcher);

        // bind the dispatcher to force member injection
        bind(AlertScriptDispatcher.class).toInstance(dispatcher);

        Process processMock = EasyMock.createNiceMock(Process.class);

        // use powermock since EasyMock can't mock final classes
        ProcessBuilder powerMockProcessBuilder = PowerMock.createNiceMock(ProcessBuilder.class);
        EasyMock.expect(powerMockProcessBuilder.start()).andReturn(processMock).atLeastOnce();
        PowerMock.replay(powerMockProcessBuilder);

        // bind the doctored ProcessBuilder so we can use it from anywhere
        bind(ProcessBuilder.class).toInstance(powerMockProcessBuilder);
      } catch (Exception exception) {
        throw new RuntimeException(exception);
      }
    }
  }

  /**
   * The {@link SynchronizedExecutor} is used to execute {@link Runnable}s
   * serially.
   */
  private static final class SynchronizedExecutor implements Executor {

    /**
     * @param command
     */
    @Override
    public void execute(Runnable command) {
      command.run();
    }
  }
}