summaryrefslogtreecommitdiff
path: root/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractVirtualHostNode.java
blob: f4c0576d79799d593c3b07a8a93f555f0ea2c3ed (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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
 *
 * 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.qpid.server.virtualhostnode;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;

import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.logging.EventLogger;
import org.apache.qpid.server.logging.messages.ConfigStoreMessages;
import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject;
import org.apache.qpid.server.model.AbstractConfiguredObject;
import org.apache.qpid.server.model.Broker;
import org.apache.qpid.server.model.ConfiguredObject;
import org.apache.qpid.server.model.Exchange;
import org.apache.qpid.server.model.LifetimePolicy;
import org.apache.qpid.server.model.ManagedAttributeField;
import org.apache.qpid.server.model.State;
import org.apache.qpid.server.model.StateTransition;
import org.apache.qpid.server.model.SystemConfig;
import org.apache.qpid.server.model.VirtualHost;
import org.apache.qpid.server.model.VirtualHostNode;
import org.apache.qpid.server.security.access.Operation;
import org.apache.qpid.server.security.auth.AuthenticatedPrincipal;
import org.apache.qpid.server.store.ConfiguredObjectRecord;
import org.apache.qpid.server.store.ConfiguredObjectRecordConverter;
import org.apache.qpid.server.store.ConfiguredObjectRecordImpl;
import org.apache.qpid.server.store.DurableConfigurationStore;
import org.apache.qpid.server.util.urlstreamhandler.data.Handler;

public abstract class AbstractVirtualHostNode<X extends AbstractVirtualHostNode<X>> extends AbstractConfiguredObject<X> implements VirtualHostNode<X>
{

    private static final Logger LOGGER = Logger.getLogger(AbstractVirtualHostNode.class);


    static
    {
        Handler.register();
    }

    private final Broker<?> _broker;
    private final EventLogger _eventLogger;

    private DurableConfigurationStore _durableConfigurationStore;

    private MessageStoreLogSubject _configurationStoreLogSubject;

    @ManagedAttributeField
    private String _virtualHostInitialConfiguration;

    public AbstractVirtualHostNode(Broker<?> parent, Map<String, Object> attributes)
    {
        super(Collections.<Class<? extends ConfiguredObject>,ConfiguredObject<?>>singletonMap(Broker.class, parent),
              attributes);
        _broker = parent;
        SystemConfig<?> systemConfig = _broker.getParent(SystemConfig.class);
        _eventLogger = systemConfig.getEventLogger();
    }


    @Override
    public void onOpen()
    {
        super.onOpen();
        _durableConfigurationStore = createConfigurationStore();
    }

    @Override
    public LifetimePolicy getLifetimePolicy()
    {
        return LifetimePolicy.PERMANENT;
    }

    @Override
    protected void onCreate()
    {
        super.onCreate();
    }

    @StateTransition( currentState = {State.UNINITIALIZED, State.STOPPED, State.ERRORED }, desiredState = State.ACTIVE )
    protected void doActivate()
    {
        try
        {
            activate();
            setState(State.ACTIVE);
        }
        catch(RuntimeException e)
        {
            setState(State.ERRORED);
            if (_broker.isManagementMode())
            {
                LOGGER.warn("Failed to make " + this + " active.", e);
            }
            else
            {
                throw e;
            }
        }
    }

    @Override
    public VirtualHost<?,?,?> getVirtualHost()
    {
        Collection<VirtualHost> children = getChildren(VirtualHost.class);
        if (children.size() == 0)
        {
            return null;
        }
        else if (children.size() == 1)
        {
            return children.iterator().next();
        }
        else
        {
            throw new IllegalStateException(this + " has an unexpected number of virtualhost children, size " + children.size());
        }
    }

    @Override
    public DurableConfigurationStore getConfigurationStore()
    {
        return _durableConfigurationStore;
    }

    protected Broker<?> getBroker()
    {
        return _broker;
    }

    protected EventLogger getEventLogger()
    {
        return _eventLogger;
    }

    protected MessageStoreLogSubject getConfigurationStoreLogSubject()
    {
        return _configurationStoreLogSubject;
    }

    @StateTransition( currentState = { State.ACTIVE, State.STOPPED, State.ERRORED}, desiredState = State.DELETED )
    protected void doDelete()
    {
        setState(State.DELETED);
        deleteVirtualHostIfExists();
        close();
        deleted();
        DurableConfigurationStore configurationStore = getConfigurationStore();
        if (configurationStore != null)
        {
            configurationStore.onDelete(this);
        }
    }

    protected void deleteVirtualHostIfExists()
    {
        VirtualHost<?, ?, ?> virtualHost = getVirtualHost();
        if (virtualHost != null)
        {
            virtualHost.delete();
        }
    }

    @StateTransition( currentState = { State.ACTIVE, State.ERRORED, State.UNINITIALIZED }, desiredState = State.STOPPED )
    protected void doStop()
    {
        stopAndSetStateTo(State.STOPPED);
    }

    protected void stopAndSetStateTo(State stoppedState)
    {
        closeChildren();
        closeConfigurationStoreSafely();
        setState(stoppedState);
    }

    @Override
    protected void onExceptionInOpen(RuntimeException e)
    {
        super.onExceptionInOpen(e);
        closeConfigurationStoreSafely();
    }

    @Override
    protected void postResolve()
    {
        super.postResolve();
        DurableConfigurationStore store = getConfigurationStore();
        if (store == null)
        {
            store = createConfigurationStore();
        }
        _configurationStoreLogSubject = new MessageStoreLogSubject(getName(), store.getClass().getSimpleName());
    }

    @Override
    protected void onClose()
    {
        closeConfigurationStore();
    }

    @Override
    protected void authoriseSetDesiredState(State desiredState) throws AccessControlException
    {
        if(desiredState == State.DELETED)
        {
            _broker.getSecurityManager().authoriseVirtualHostNode(getName(), Operation.DELETE);
        }
        else
        {
            _broker.getSecurityManager().authoriseVirtualHostNode(getName(), Operation.UPDATE);
        }
    }

    @Override
    protected <C extends ConfiguredObject> void authoriseCreateChild(final Class<C> childClass,
                                                                     final Map<String, Object> attributes,
                                                                     final ConfiguredObject... otherParents)
            throws AccessControlException
    {
        if (childClass == VirtualHost.class)
        {
            _broker.getSecurityManager().authoriseVirtualHost(String.valueOf(attributes.get(VirtualHost.NAME)),
                                                              Operation.CREATE);

        }
        else
        {
            super.authoriseCreateChild(childClass, attributes, otherParents);
        }
    }

    @Override
    protected void authoriseSetAttributes(ConfiguredObject<?> modified, Set<String> attributes) throws AccessControlException
    {
        _broker.getSecurityManager().authoriseVirtualHostNode(getName(), Operation.UPDATE);
    }

    private void closeConfigurationStore()
    {
        DurableConfigurationStore configurationStore = getConfigurationStore();
        if (configurationStore != null)
        {
            configurationStore.closeConfigurationStore();
            getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.CLOSE());
        }
    }

    private void closeConfigurationStoreSafely()
    {
        try
        {
            closeConfigurationStore();
        }
        catch(Exception e)
        {
            LOGGER.warn("Unexpected exception on close of configuration store", e);
        }
    }

    @Override
    public String getVirtualHostInitialConfiguration()
    {
        return _virtualHostInitialConfiguration;
    }

    protected abstract DurableConfigurationStore createConfigurationStore();

    protected abstract void activate();



    protected abstract ConfiguredObjectRecord enrichInitialVirtualHostRootRecord(final ConfiguredObjectRecord vhostRecord);

    protected final ConfiguredObjectRecord[] getInitialRecords() throws IOException
    {
        ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(getModel());

        Collection<ConfiguredObjectRecord> records =
                new ArrayList<>(converter.readFromJson(VirtualHost.class,this,getInitialConfigReader()));

        if(!records.isEmpty())
        {
            ConfiguredObjectRecord vhostRecord = null;
            for(ConfiguredObjectRecord record : records)
            {
                if(record.getType().equals(VirtualHost.class.getSimpleName()))
                {
                    vhostRecord = record;
                    break;
                }
            }
            if(vhostRecord != null)
            {
                records.remove(vhostRecord);
                vhostRecord = enrichInitialVirtualHostRootRecord(vhostRecord);
                records.add(vhostRecord);
            }
            else
            {
                // this should be impossible as the converter should always generate a parent record
                throw new IllegalConfigurationException("Somehow the initial configuration has records but "
                                                        + "not a VirtualHost. This must be a coding error in Qpid");
            }
            addStandardExchangesIfNecessary(records, vhostRecord);
            enrichWithAuditInformation(records);
        }


        return records.toArray(new ConfiguredObjectRecord[records.size()]);
    }

    private void enrichWithAuditInformation(final Collection<ConfiguredObjectRecord> records)
    {
        List<ConfiguredObjectRecord> replacements = new ArrayList<>(records.size());

        for(ConfiguredObjectRecord record : records)
        {
            replacements.add(new ConfiguredObjectRecordImpl(record.getId(), record.getType(),
                                                            enrichAttributesWithAuditInformation(record.getAttributes()),
                                                            record.getParents()));
        }
        records.clear();
        records.addAll(replacements);
    }

    private Map<String, Object> enrichAttributesWithAuditInformation(final Map<String, Object> attributes)
    {
        LinkedHashMap<String,Object> enriched = new LinkedHashMap<>(attributes);
        final AuthenticatedPrincipal currentUser = org.apache.qpid.server.security.SecurityManager.getCurrentUser();

        if(currentUser != null)
        {
            enriched.put(ConfiguredObject.LAST_UPDATED_BY, currentUser.getName());
            enriched.put(ConfiguredObject.CREATED_BY, currentUser.getName());
        }
        long currentTime = System.currentTimeMillis();
        enriched.put(ConfiguredObject.LAST_UPDATED_TIME, currentTime);
        enriched.put(ConfiguredObject.CREATED_TIME, currentTime);

        return enriched;
    }

    private void addStandardExchangesIfNecessary(final Collection<ConfiguredObjectRecord> records,
                                                 final ConfiguredObjectRecord vhostRecord)
    {
        addExchangeIfNecessary(ExchangeDefaults.FANOUT_EXCHANGE_CLASS, ExchangeDefaults.FANOUT_EXCHANGE_NAME, records, vhostRecord);
        addExchangeIfNecessary(ExchangeDefaults.HEADERS_EXCHANGE_CLASS, ExchangeDefaults.HEADERS_EXCHANGE_NAME, records, vhostRecord);
        addExchangeIfNecessary(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, ExchangeDefaults.TOPIC_EXCHANGE_NAME, records, vhostRecord);
        addExchangeIfNecessary(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, ExchangeDefaults.DIRECT_EXCHANGE_NAME, records, vhostRecord);
    }

    private void addExchangeIfNecessary(final String exchangeClass,
                                        final String exchangeName,
                                        final Collection<ConfiguredObjectRecord> records,
                                        final ConfiguredObjectRecord vhostRecord)
    {
        boolean found = false;

        for(ConfiguredObjectRecord record : records)
        {
            if(Exchange.class.getSimpleName().equals(record.getType())
               && exchangeName.equals(record.getAttributes().get(ConfiguredObject.NAME)))
            {
                found = true;
                break;
            }
        }

        if(!found)
        {
            final Map<String, Object> exchangeAttributes = new HashMap<>();
            exchangeAttributes.put(ConfiguredObject.NAME, exchangeName);
            exchangeAttributes.put(ConfiguredObject.TYPE, exchangeClass);

            records.add(new ConfiguredObjectRecordImpl(UUID.randomUUID(), Exchange.class.getSimpleName(),
                                                       exchangeAttributes, Collections.singletonMap(VirtualHost.class.getSimpleName(), vhostRecord.getId())));
        }
    }

    protected final Reader getInitialConfigReader() throws IOException
    {
        Reader initialConfigReader;
        if(getVirtualHostInitialConfiguration() != null)
        {
            String initialContextString = getVirtualHostInitialConfiguration();


            try
            {
                URL url = new URL(initialContextString);

                initialConfigReader =new InputStreamReader(url.openStream());
            }
            catch (MalformedURLException e)
            {
                initialConfigReader = new StringReader(initialContextString);
            }

        }
        else
        {
            LOGGER.warn("No initial configuration found for the virtual host");
            initialConfigReader = new StringReader("{}");
        }
        return initialConfigReader;
    }

}