summaryrefslogtreecommitdiff
path: root/cpp/src/qpid/cluster/Cluster.cpp
blob: e691ad357dd4f6e6bb25d55360248aa71d65e4b7 (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
/*
 *
 * Copyright (c) 2006 The Apache Software Foundation
 *
 * Licensed 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 "Cluster.h"
#include "qpid/framing/AMQFrame.h"
#include "qpid/framing/ClusterNotifyBody.h"
#include "qpid/log/Statement.h"
#include <boost/bind.hpp>
#include <algorithm>
#include <iterator>
#include <map>

namespace qpid {
namespace cluster {
using namespace qpid::framing;
using namespace qpid::sys;
using namespace std;

ostream& operator <<(ostream& out, const Cluster& cluster) {
    return out << "cluster[" << cluster.name.str() << " " << cluster.self << "]";
}

ostream& operator<<(ostream& out, const Cluster::MemberMap::value_type& m) {
    return out << m.first << "=" << m.second->url;
}

ostream& operator <<(ostream& out, const Cluster::MemberMap& members) {
    ostream_iterator<Cluster::MemberMap::value_type> o(out, " ");
    copy(members.begin(), members.end(), o);
    return out;
}

namespace {

/** We mark the high bit of a frame's channel number to know if it's
 * an incoming or outgoing frame when frames arrive via multicast.
 */ 
bool isOutgoing(AMQFrame& frame) { return frame.channel&CHANNEL_HIGH_BIT; }
bool isIncoming(AMQFrame& frame) { return !isOutgoing(frame); }
void markOutgoing(AMQFrame& frame) { frame.channel |= CHANNEL_HIGH_BIT; }
void markIncoming(AMQFrame&) { /*noop*/ }
void unMark(AMQFrame& frame) { frame.channel &= ~CHANNEL_HIGH_BIT; }

}

struct Cluster::IncomingHandler : public FrameHandler {
    IncomingHandler(Cluster& c) : cluster(c) {}
    void handle(AMQFrame& frame) {
        markIncoming(frame);
        cluster.mcast(frame);
    }
    Cluster& cluster;
};

struct Cluster::OutgoingHandler : public FrameHandler {
    OutgoingHandler(Cluster& c) : cluster(c) {}
    void handle(AMQFrame& frame) {
        markOutgoing(frame);
        cluster.mcast(frame);
    }
    Cluster& cluster;
};


// TODO aconway 2007-06-28: Right now everything is backed up via
// multicast.  When we have point-to-point backups the
// Incoming/Outgoing handlers must determine where each frame should
// be sent: to multicast or only to specific backup(s) via AMQP.

Cluster::Cluster(const std::string& name_, const std::string& url_) :
    cpg(new Cpg(*this)),
    name(name_),
    url(url_), 
    self(cpg->getLocalNoideId(), getpid()),
    toChains(new IncomingHandler(*this), new OutgoingHandler(*this))
{
    QPID_LOG(trace, *this << " Joining cluster.");
    cpg->join(name);
    notify();
    dispatcher=Thread(*this);
    // Wait till we show up in the cluster map.
    {
        Mutex::ScopedLock l(lock);
        while (empty())
            lock.wait();
    }
}

Cluster::~Cluster() {
    QPID_LOG(trace, *this << " Leaving cluster.");
    try {
        cpg->leave(name);
        cpg.reset();
        dispatcher.join();
    }
    catch (const std::exception& e) {
        QPID_LOG(error, "Exception leaving cluster " << *this << ": "
                 << e.what());
    }
}

void Cluster::mcast(AMQFrame& frame) {
    QPID_LOG(trace, *this << " SEND: " << frame);
    Buffer buf(frame.size());
    frame.encode(buf);
    buf.flip();
    iovec iov = { buf.start(), frame.size() };
    cpg->mcast(name, &iov, 1);
}

void Cluster::notify() {
    // TODO aconway 2007-06-25: Use proxy here.
    ProtocolVersion version;
    AMQFrame frame(version, 0,
                   make_shared_ptr(new ClusterNotifyBody(version, url)));
    mcast(frame);
}

size_t Cluster::size() const {
    Mutex::ScopedLock l(lock);
    return members.size();
}

void Cluster::setFromChains(const framing::FrameHandler::Chains& chains) {
    Mutex::ScopedLock l(lock);
    fromChains = chains;
}

Cluster::MemberList Cluster::getMembers() const {
    Mutex::ScopedLock l(lock);
    MemberList result(members.size());
    std::transform(members.begin(), members.end(), result.begin(),
                   boost::bind(&MemberMap::value_type::second, _1));
    return result;        
}

void Cluster::deliver(
        cpg_handle_t /*handle*/,
        struct cpg_name* /* group */,
        uint32_t nodeid,
        uint32_t pid,
        void* msg,
        int msg_len)
{
    Id from(nodeid, pid);
    Buffer buf(static_cast<char*>(msg), msg_len);
    AMQFrame frame;
    frame.decode(buf);
    QPID_LOG(trace, *this << " RECV: " << frame << " from: " << from);
    if (!handleClusterFrame(from, frame)) {
        FrameHandler::Chain chain = isIncoming(frame) ? fromChains.in : fromChains.out;
        unMark(frame);
        if (chain)
            chain->handle(frame);
    }
}

bool Cluster::wait(boost::function<bool(const Cluster&)> predicate,
                   Duration timeout) const
{
    AbsTime deadline(now(), timeout);
    Mutex::ScopedLock l(lock);
    while (!predicate(*this) && lock.wait(deadline))
        ;
    return (predicate(*this));
}
        
bool Cluster::handleClusterFrame(Id from, AMQFrame& frame) {
    // TODO aconway 2007-06-20: use visitor pattern here.
    ClusterNotifyBody* notifyIn=
        dynamic_cast<ClusterNotifyBody*>(frame.getBody().get());
    if (notifyIn) {
        MemberList list;
        {
            Mutex::ScopedLock l(lock);
            if (!members[from]) 
                members[from].reset(new Member(url));
            else 
                members[from]->url = notifyIn->getUrl();
            QPID_LOG(trace, *this << ": member update: " << members);
            lock.notifyAll();
        }
        return true;
    }
    return false;
}

void Cluster::configChange(
    cpg_handle_t /*handle*/,
    struct cpg_name */*group*/,
    struct cpg_address */*current*/, int /*nCurrent*/,
    struct cpg_address *left, int nLeft,
    struct cpg_address *joined, int nJoined)
{
    bool newMembers=false;
    MemberList updated;
    {
        Mutex::ScopedLock l(lock);
        if (nLeft) {
            for (int i = 0; i < nLeft; ++i) 
                members.erase(Id(left[i]));
            QPID_LOG(trace, *this << ": members left: " << members);
            lock.notifyAll();
        }
        newMembers = nJoined > 1 || (nJoined==1 && Id(joined[0]) != self);
        // We don't record members joining here, we record them when
        // we get their ClusterNotify message.
    }
    if (newMembers)
        notify();
}

void Cluster::run() {
    cpg->dispatchBlocking();
}

}} // namespace qpid::cluster