summaryrefslogtreecommitdiff
path: root/cpp/src/qpid/client/ClientChannel.cpp
blob: ab6b9a41c3899f58ae2088e9e64711a879dadd62 (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
/*
 *
 * 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.
 *
 */
#include "qpid/log/Statement.h"
#include <iostream>
#include "ClientChannel.h"
#include "qpid/sys/Monitor.h"
#include "ClientMessage.h"
#include "qpid/QpidError.h"
#include "MethodBodyInstances.h"
#include "Connection.h"
#include "BasicMessageChannel.h"
#include "MessageMessageChannel.h"

// FIXME aconway 2007-01-26: Evaluate all throws, ensure consistent
// handling of errors that should close the connection or the channel.
// Make sure the user thread receives a connection in each case.
//
using namespace std;
using namespace boost;
using namespace qpid::client;
using namespace qpid::framing;
using namespace qpid::sys;

Channel::Channel(bool _transactional, u_int16_t _prefetch, InteropMode mode) :
    connection(0), prefetch(_prefetch), transactional(_transactional), errorCode(200), errorText("Ok"), running(false)
{
    switch (mode) {
      case AMQP_08: messaging.reset(new BasicMessageChannel(*this)); break;
      case AMQP_09: messaging.reset(new MessageMessageChannel(*this)); break;
      default: assert(0); QPID_ERROR(INTERNAL_ERROR, "Invalid interop-mode.");
    }
}

Channel::~Channel(){
    closeInternal();
    stop();
}

void Channel::open(ChannelId id, Connection& con)
{
    if (isOpen())
        THROW_QPID_ERROR(INTERNAL_ERROR, "Attempt to re-open channel "+id);
    connection = &con;
    init(id, con, con.getVersion()); // ChannelAdapter initialization.
    string oob;
    if (id != 0) 
        sendAndReceive<ChannelOpenOkBody>(make_shared_ptr(new ChannelOpenBody(version, oob)));
}

void Channel::protocolInit(
    const std::string& uid, const std::string& pwd, const std::string& vhost) {
    assert(connection);
    responses.expect();
    connection->connector->init(); // Send ProtocolInit block.
    ConnectionStartBody::shared_ptr connectionStart =
        responses.receive<ConnectionStartBody>();
    
    FieldTable props;
    string mechanism("PLAIN");
    string response = ((char)0) + uid + ((char)0) + pwd;
    string locale("en_US");
    ConnectionTuneBody::shared_ptr proposal =
        sendAndReceive<ConnectionTuneBody>(
            make_shared_ptr(new ConnectionStartOkBody(
                version, connectionStart->getRequestId(),
                props, mechanism,
                response, locale)));

    /**
     * Assume for now that further challenges will not be required
     //receive connection.secure
     responses.receive(connection_secure));
     //send connection.secure-ok
     connection->send(new AMQFrame(0, new ConnectionSecureOkBody(response)));
    **/

    send(new ConnectionTuneOkBody(
             version, proposal->getRequestId(),
             proposal->getChannelMax(), connection->getMaxFrameSize(),
             proposal->getHeartbeat()));
    
    uint16_t heartbeat = proposal->getHeartbeat();
    connection->connector->setReadTimeout(heartbeat * 2);
    connection->connector->setWriteTimeout(heartbeat);

    // Send connection open.
    std::string capabilities;
    responses.expect();
    send(new ConnectionOpenBody(version, vhost, capabilities, true));
    //receive connection.open-ok (or redirect, but ignore that for now
    //esp. as using force=true).
    AMQMethodBody::shared_ptr openResponse = responses.receive();
    if(openResponse->isA<ConnectionOpenOkBody>()) {
        //ok
    }else if(openResponse->isA<ConnectionRedirectBody>()){
        //ignore for now
        ConnectionRedirectBody::shared_ptr redirect(
            shared_polymorphic_downcast<ConnectionRedirectBody>(openResponse));
        QPID_LOG(error, "Ignoring redirect to " << redirect->getHost());
    } else {
        THROW_QPID_ERROR(PROTOCOL_ERROR, "Bad response to Connection.open");
    }
}
    
bool Channel::isOpen() const { 
    Mutex::ScopedLock l(lock);
    return connection; 
}

void Channel::setQos() {
    messaging->setQos();
}

void Channel::setPrefetch(uint16_t _prefetch){
    prefetch = _prefetch;
    setQos();
}

void Channel::declareExchange(Exchange& exchange, bool synch){
    string name = exchange.getName();
    string type = exchange.getType();
    FieldTable args;
    sendAndReceiveSync<ExchangeDeclareOkBody>(
        synch,
        make_shared_ptr(new ExchangeDeclareBody(
                            version, 0, name, type, false, false, false, false, !synch, args)));
}

void Channel::deleteExchange(Exchange& exchange, bool synch){
    string name = exchange.getName();
    sendAndReceiveSync<ExchangeDeleteOkBody>(
        synch,
        make_shared_ptr(new ExchangeDeleteBody(version, 0, name, false, !synch)));
}

void Channel::declareQueue(Queue& queue, bool synch){
    string name = queue.getName();
    FieldTable args;
    QueueDeclareOkBody::shared_ptr response =
        sendAndReceiveSync<QueueDeclareOkBody>(
            synch,
            make_shared_ptr(new QueueDeclareBody(
                version, 0, name, false/*passive*/, queue.isDurable(),
                queue.isExclusive(), queue.isAutoDelete(), !synch, args)));
    if(synch) {
        if(queue.getName().length() == 0)
            queue.setName(response->getQueue());
    }
}

void Channel::deleteQueue(Queue& queue, bool ifunused, bool ifempty, bool synch){
    //ticket, queue, ifunused, ifempty, nowait
    string name = queue.getName();
    sendAndReceiveSync<QueueDeleteOkBody>(
        synch,
        make_shared_ptr(new QueueDeleteBody(version, 0, name, ifunused, ifempty, !synch)));
}

void Channel::bind(const Exchange& exchange, const Queue& queue, const std::string& key, const FieldTable& args, bool synch){
    string e = exchange.getName();
    string q = queue.getName();
    sendAndReceiveSync<QueueBindOkBody>(
        synch,
        make_shared_ptr(new QueueBindBody(version, 0, q, e, key,!synch, args)));
}

void Channel::commit(){
    sendAndReceive<TxCommitOkBody>(make_shared_ptr(new TxCommitBody(version)));
}

void Channel::rollback(){
    sendAndReceive<TxRollbackOkBody>(make_shared_ptr(new TxRollbackBody(version)));
}

void Channel::handleMethodInContext(
AMQMethodBody::shared_ptr method, const MethodContext& ctxt)
{
    // Special case for consume OK as it is both an expected response
    // and needs handling in this thread.
    if (method->isA<BasicConsumeOkBody>()) {
        messaging->handle(method);
        responses.signalResponse(method);
        return;
    }
    if(responses.isWaiting()) {
        responses.signalResponse(method);
        return;
    }
    try {
        switch (method->amqpClassId()) {
          case MessageOkBody::CLASS_ID: 
          case BasicGetOkBody::CLASS_ID: messaging->handle(method); break;
          case ChannelCloseBody::CLASS_ID: handleChannel(method, ctxt); break;
          case ConnectionCloseBody::CLASS_ID: handleConnection(method); break;
          default: throw UnknownMethod();
        }
    }
    catch (const UnknownMethod&) {
                connection->close(
                    504, "Unknown method",
                    method->amqpClassId(), method->amqpMethodId());
            }
        }

void Channel::handleChannel(AMQMethodBody::shared_ptr method, const MethodContext& ctxt) {
    switch (method->amqpMethodId()) {
      case ChannelCloseBody::METHOD_ID:
          send(new ChannelCloseOkBody(version, ctxt.getRequestId()));
        peerClose(shared_polymorphic_downcast<ChannelCloseBody>(method));
        return;
      case ChannelFlowBody::METHOD_ID:
        // FIXME aconway 2007-02-22: Not yet implemented.
        return;
    }
    throw UnknownMethod();
}

void Channel::handleConnection(AMQMethodBody::shared_ptr method) {
    if (method->amqpMethodId() == ConnectionCloseBody::METHOD_ID) {
        connection->close();
        return;
    } 
    throw UnknownMethod();
}

void Channel::handleHeader(AMQHeaderBody::shared_ptr body){
    messaging->handle(body);
}
    
void Channel::handleContent(AMQContentBody::shared_ptr body){
    messaging->handle(body);
}

void Channel::handleHeartbeat(AMQHeartbeatBody::shared_ptr /*body*/){
    THROW_QPID_ERROR(PROTOCOL_ERROR + 504, "Channel received heartbeat");
}

void Channel::start(){
    running = true;
    dispatcher = Thread(*messaging);
}

// Close called by local application.
void Channel::close(
    uint16_t code, const std::string& text,
    ClassId classId, MethodId methodId)
{
    if (isOpen()) {
        try {
            if (getId() != 0) {
                if (code == 200) messaging->cancelAll();

                sendAndReceive<ChannelCloseOkBody>(
                    make_shared_ptr(new ChannelCloseBody(
                                        version, code, text, classId, methodId)));
            }
            static_cast<ConnectionForChannel*>(connection)->erase(getId()); 
            closeInternal();
        } catch (...) {
            static_cast<ConnectionForChannel*>(connection)->erase(getId()); 
            closeInternal();
            throw;
        }
    }
    stop();
}

// Channel closed by peer.
void Channel::peerClose(ChannelCloseBody::shared_ptr reason) {
    assert(isOpen());
    //record reason:
    errorCode = reason->getReplyCode();
    errorText = reason->getReplyText();
    closeInternal();
}

void Channel::closeInternal() {
    Mutex::ScopedLock l(lock);
    if (connection);
    {
        connection = 0;
        messaging->close();
        // A 0 response means we are closed.
        responses.signalResponse(AMQMethodBody::shared_ptr());
    }
}

void Channel::stop() {
    Mutex::ScopedLock l(stopLock);
    if(running) {
        dispatcher.join();
        running = false;
    }
}

AMQMethodBody::shared_ptr Channel::sendAndReceive(
    AMQMethodBody::shared_ptr toSend, ClassId c, MethodId m)
{
    responses.expect();
    send(toSend);
    return responses.receive(c, m);
}

AMQMethodBody::shared_ptr Channel::sendAndReceiveSync(
    bool sync, AMQMethodBody::shared_ptr body, ClassId c, MethodId m)
{
    if(sync)
        return sendAndReceive(body, c, m);
    else {
        send(body);
        return AMQMethodBody::shared_ptr();
    }
}

void Channel::consume(
    Queue& queue, std::string& tag, MessageListener* listener, 
    AckMode ackMode, bool noLocal, bool synch, const FieldTable* fields) {
    messaging->consume(queue, tag, listener, ackMode, noLocal, synch, fields);
}
        
void Channel::cancel(const std::string& tag, bool synch) {
    messaging->cancel(tag, synch);
}

bool Channel::get(Message& msg, const Queue& queue, AckMode ackMode) {
    bool result = messaging->get(msg, queue, ackMode);
    if (!isOpen()) {
        throw ChannelException(errorCode, errorText);
    }
    return result;
}

void Channel::publish(const Message& msg, const Exchange& exchange,
                      const std::string& routingKey, 
                      bool mandatory, bool immediate) {
    messaging->publish(msg, exchange, routingKey, mandatory, immediate);
}

void Channel::setReturnedMessageHandler(ReturnedMessageHandler* handler) {
    messaging->setReturnedMessageHandler(handler);
}

void Channel::run() {
    messaging->run();
}