proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/CTrieSubscriptionDirectory.java
CTrieSubscriptionDirectory
init
class CTrieSubscriptionDirectory implements ISubscriptionsDirectory { private static final Logger LOG = LoggerFactory.getLogger(CTrieSubscriptionDirectory.class); private CTrie ctrie; private volatile ISubscriptionsRepository subscriptionsRepository; private final ConcurrentMap<String, List<SharedSubscription>> clientSharedSubscriptions = new ConcurrentHashMap<>(); @Override public void init(ISubscriptionsRepository subscriptionsRepository) {<FILL_FUNCTION_BODY>} /** * Given a topic string return the clients subscriptions that matches it. Topic string can't * contain character # and + because they are reserved to listeners subscriptions, and not topic * publishing. * * @param topicName * to use for search matching subscriptions. * @return the list of matching subscriptions, or empty if not matching. */ @Override public List<Subscription> matchWithoutQosSharpening(Topic topicName) { return ctrie.recursiveMatch(topicName); } @Override public List<Subscription> matchQosSharpening(Topic topicName) { final List<Subscription> subscriptions = matchWithoutQosSharpening(topicName); // for each session select the subscription with higher QoS return selectSubscriptionsWithHigherQoSForEachSession(subscriptions); } private static List<Subscription> selectSubscriptionsWithHigherQoSForEachSession(List<Subscription> subscriptions) { // for each session select the subscription with higher QoS Map<String, Subscription> subsGroupedByClient = new HashMap<>(); for (Subscription sub : subscriptions) { // If same client is subscribed to two different shared subscription that overlaps // then it has to return both subscriptions, because the share name made them independent. final String key = sub.clientAndShareName(); Subscription existingSub = subsGroupedByClient.get(key); // update the selected subscriptions if not present or if it has a greater qos if (existingSub == null || existingSub.qosLessThan(sub)) { subsGroupedByClient.put(key, sub); } } return new ArrayList<>(subsGroupedByClient.values()); } @Override public boolean add(String clientId, Topic filter, MqttSubscriptionOption option) { SubscriptionRequest subRequest = SubscriptionRequest.buildNonShared(clientId, filter, option); return addNonSharedSubscriptionRequest(subRequest); } @Override public boolean add(String clientId, Topic filter, MqttSubscriptionOption option, SubscriptionIdentifier subscriptionId) { SubscriptionRequest subRequest = SubscriptionRequest.buildNonShared(clientId, filter, option, subscriptionId); return addNonSharedSubscriptionRequest(subRequest); } private boolean addNonSharedSubscriptionRequest(SubscriptionRequest subRequest) { boolean notExistingSubscription = ctrie.addToTree(subRequest); subscriptionsRepository.addNewSubscription(subRequest.subscription()); return notExistingSubscription; } @Override public void addShared(String clientId, ShareName name, Topic topicFilter, MqttSubscriptionOption option) { SubscriptionRequest shareSubRequest = SubscriptionRequest.buildShared(name, topicFilter, clientId, option); addSharedSubscriptionRequest(shareSubRequest); } private void addSharedSubscriptionRequest(SubscriptionRequest shareSubRequest) { ctrie.addToTree(shareSubRequest); if (shareSubRequest.hasSubscriptionIdentifier()) { subscriptionsRepository.addNewSharedSubscription(shareSubRequest.getClientId(), shareSubRequest.getSharedName(), shareSubRequest.getTopicFilter(), shareSubRequest.getOption(), shareSubRequest.getSubscriptionIdentifier()); } else { subscriptionsRepository.addNewSharedSubscription(shareSubRequest.getClientId(), shareSubRequest.getSharedName(), shareSubRequest.getTopicFilter(), shareSubRequest.getOption()); } List<SharedSubscription> sharedSubscriptions = clientSharedSubscriptions.computeIfAbsent(shareSubRequest.getClientId(), unused -> new ArrayList<>()); sharedSubscriptions.add(shareSubRequest.sharedSubscription()); } @Override public void addShared(String clientId, ShareName name, Topic topicFilter, MqttSubscriptionOption option, SubscriptionIdentifier subscriptionId) { SubscriptionRequest shareSubRequest = SubscriptionRequest.buildShared(name, topicFilter, clientId, option, subscriptionId); addSharedSubscriptionRequest(shareSubRequest); } /** * Removes subscription from CTrie, adds TNode when the last client unsubscribes, then calls for cleanTomb in a * separate atomic CAS operation. * * @param topic the subscription's topic to remove. * @param clientID the Id of client owning the subscription. */ @Override public void removeSubscription(Topic topic, String clientID) { UnsubscribeRequest request = UnsubscribeRequest.buildNonShared(clientID, topic); ctrie.removeFromTree(request); this.subscriptionsRepository.removeSubscription(topic.toString(), clientID); } @Override public void removeSharedSubscription(ShareName name, Topic topicFilter, String clientId) { UnsubscribeRequest request = UnsubscribeRequest.buildShared(name, topicFilter, clientId); ctrie.removeFromTree(request); subscriptionsRepository.removeSharedSubscription(clientId, name, topicFilter); SharedSubscription sharedSubscription = new SharedSubscription(name, topicFilter, clientId, MqttSubscriptionOption.onlyFromQos(MqttQoS.AT_MOST_ONCE) /* UNUSED in compare */); List<SharedSubscription> sharedSubscriptions = clientSharedSubscriptions.get(clientId); if (sharedSubscriptions != null && !sharedSubscriptions.isEmpty()) { sharedSubscriptions.remove(sharedSubscription); clientSharedSubscriptions.replace(clientId, sharedSubscriptions); } } @Override public int size() { return ctrie.size(); } @Override public String dumpTree() { return ctrie.dumpTree(); } @Override public void removeSharedSubscriptionsForClient(String clientId) { List<SharedSubscription> sessionSharedSubscriptions = clientSharedSubscriptions .computeIfAbsent(clientId, s -> Collections.emptyList()); // remove the client from all shared subscriptions for (SharedSubscription subscription : sessionSharedSubscriptions) { UnsubscribeRequest request = UnsubscribeRequest.buildShared(subscription.getShareName(), subscription.topicFilter(), clientId); ctrie.removeFromTree(request); } subscriptionsRepository.removeAllSharedSubscriptions(clientId); } }
LOG.info("Initializing CTrie"); ctrie = new CTrie(); LOG.info("Initializing subscriptions store..."); this.subscriptionsRepository = subscriptionsRepository; // reload any subscriptions persisted if (LOG.isTraceEnabled()) { LOG.trace("Reloading all stored subscriptions. SubscriptionTree = {}", dumpTree()); } for (Subscription subscription : this.subscriptionsRepository.listAllSubscriptions()) { LOG.debug("Re-subscribing {}", subscription); ctrie.addToTree(SubscriptionRequest.buildNonShared(subscription)); } for (SharedSubscription shared : subscriptionsRepository.listAllSharedSubscription()) { LOG.debug("Re-subscribing shared {}", shared); ctrie.addToTree(SubscriptionRequest.buildShared(shared.getShareName(), shared.topicFilter(), shared.clientId(), MqttSubscriptionOption.onlyFromQos(shared.requestedQoS()))); } if (LOG.isTraceEnabled()) { LOG.trace("Stored subscriptions have been reloaded. SubscriptionTree = {}", dumpTree()); }
1,732
294
2,026
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/DumpTreeVisitor.java
DumpTreeVisitor
prettySubscriptions
class DumpTreeVisitor implements CTrie.IVisitor<String> { String s = ""; @Override public void visit(CNode node, int deep) { String indentTabs = indentTabs(deep); s += indentTabs + (node.getToken() == null ? "''" : node.getToken().toString()) + prettySubscriptions(node) + "\n"; } private String prettySubscriptions(CNode node) {<FILL_FUNCTION_BODY>} private String indentTabs(int deep) { StringBuilder s = new StringBuilder(); if (deep > 0) { s.append(" "); for (int i = 0; i < deep - 1; i++) { s.append("| "); } s.append("|-"); } return s.toString(); } @Override public String getResult() { return s; } }
if (node instanceof TNode) { return "TNode"; } if (node.subscriptions().isEmpty()) { return StringUtil.EMPTY_STRING; } StringBuilder subScriptionsStr = new StringBuilder(" ~~["); int counter = 0; for (Subscription couple : node.subscriptions()) { subScriptionsStr .append("{filter=").append(couple.topicFilter).append(", ") .append("option=").append(couple.option()).append(", ") .append("client='").append(couple.clientId).append("'}"); counter++; if (counter < node.subscriptions().size()) { subScriptionsStr.append(";"); } } return subScriptionsStr.append("]").toString();
245
205
450
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/ShareName.java
ShareName
equals
class ShareName { private final String shareName; public ShareName(String shareName) { this.shareName = shareName; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} public String getShareName() { return shareName; } @Override public int hashCode() { return Objects.hash(shareName); } @Override public String toString() { return "ShareName{" + "shareName='" + shareName + '\'' + '}'; } }
if (this == o) return true; if (o == null) return false; if (o instanceof String) { return Objects.equals(shareName, (String) o); } if (getClass() != o.getClass()) return false; ShareName shareName1 = (ShareName) o; return Objects.equals(shareName, shareName1.shareName);
156
102
258
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/SharedSubscription.java
SharedSubscription
equals
class SharedSubscription implements Comparable<SharedSubscription> { private final ShareName shareName; private final Topic topicFilter; private final String clientId; private final MqttSubscriptionOption option; private final Optional<SubscriptionIdentifier> subscriptionId; public SharedSubscription(ShareName shareName, Topic topicFilter, String clientId, MqttSubscriptionOption option) { Objects.requireNonNull(option, "option parameter can't be null"); this.shareName = shareName; this.topicFilter = topicFilter; this.clientId = clientId; this.option = option; this.subscriptionId = Optional.empty(); } public SharedSubscription(ShareName shareName, Topic topicFilter, String clientId, MqttSubscriptionOption option, SubscriptionIdentifier subscriptionId) { Objects.requireNonNull(option, "option parameter can't be null"); this.shareName = shareName; this.topicFilter = topicFilter; this.clientId = clientId; this.option = option; this.subscriptionId = Optional.of(subscriptionId); } public String clientId() { return clientId; } public Topic topicFilter() { return topicFilter; } public MqttQoS requestedQoS() { return option.qos(); } public MqttSubscriptionOption getOption() { return option; } public ShareName getShareName() { return shareName; } /** * Create a new Subscription instance from the data present in SharedSubscription * */ Subscription createSubscription() { if (subscriptionId.isPresent()) { return new Subscription(clientId, topicFilter, option, shareName.getShareName(), subscriptionId.get()); } else { return new Subscription(clientId, topicFilter, option, shareName.getShareName()); } } public boolean hasSubscriptionIdentifier() { return subscriptionId.isPresent(); } public SubscriptionIdentifier getSubscriptionIdentifier() { return subscriptionId.get(); } @Override public int compareTo(SharedSubscription o) { return this.clientId.compareTo(o.clientId); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(shareName, topicFilter, clientId, option); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SharedSubscription that = (SharedSubscription) o; return Objects.equals(shareName, that.shareName) && Objects.equals(topicFilter, that.topicFilter) && Objects.equals(clientId, that.clientId) && Objects.equals(option, that.option);
650
112
762
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/Subscription.java
Subscription
equals
class Subscription implements Serializable, Comparable<Subscription>{ private static final long serialVersionUID = -3383457629635732794L; private final MqttSubscriptionOption option; final String clientId; final Topic topicFilter; final String shareName; private final Optional<SubscriptionIdentifier> subscriptionId; public Subscription(String clientId, Topic topicFilter, MqttSubscriptionOption options) { this(clientId, topicFilter, options, ""); } public Subscription(String clientId, Topic topicFilter, MqttSubscriptionOption options, SubscriptionIdentifier subscriptionId) { this(clientId, topicFilter, options, "", subscriptionId); } public Subscription(String clientId, Topic topicFilter, MqttSubscriptionOption options, String shareName) { this(clientId, topicFilter, options, shareName, null); } public Subscription(String clientId, Topic topicFilter, MqttSubscriptionOption options, String shareName, SubscriptionIdentifier subscriptionId) { this.clientId = clientId; this.topicFilter = topicFilter; this.shareName = shareName; this.subscriptionId = Optional.ofNullable(subscriptionId); this.option = options; } public Subscription(Subscription orig) { this.clientId = orig.clientId; this.topicFilter = orig.topicFilter; this.shareName = orig.shareName; this.subscriptionId = orig.subscriptionId; this.option = orig.option; } public String getClientId() { return clientId; } public Topic getTopicFilter() { return topicFilter; } public boolean qosLessThan(Subscription sub) { return option.qos().value() < sub.option.qos().value(); } public boolean hasSubscriptionIdentifier() { return subscriptionId.isPresent(); } public SubscriptionIdentifier getSubscriptionIdentifier() { return subscriptionId.get(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(clientId, shareName, topicFilter); } @Override public String toString() { return String.format("[filter:%s, clientID: %s, options: %s - shareName: %s]", topicFilter, clientId, option, shareName); } @Override public Subscription clone() { try { return (Subscription) super.clone(); } catch (CloneNotSupportedException e) { return null; } } // The identity is important because used in CTries CNodes to check when a subscription is a duplicate or not. @Override public int compareTo(Subscription o) { int compare = this.clientId.compareTo(o.clientId); if (compare != 0) { return compare; } compare = this.shareName.compareTo(o.shareName); if (compare != 0) { return compare; } return this.topicFilter.compareTo(o.topicFilter); } public String clientAndShareName() { return clientId + (shareName.isEmpty() ? "" : "-" + shareName); } public boolean hasShareName() { return shareName != null; } public String getShareName() { return shareName; } public MqttSubscriptionOption option() { return option; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Subscription that = (Subscription) o; return Objects.equals(clientId, that.clientId) && Objects.equals(shareName, that.shareName) && Objects.equals(topicFilter, that.topicFilter);
937
95
1,032
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/SubscriptionIdentifier.java
SubscriptionIdentifier
equals
class SubscriptionIdentifier { private final int subscriptionId; public SubscriptionIdentifier(int value) { if (value <= 0 || value > 268435455) { throw new IllegalArgumentException("Value MUST be > 0 and <= 268435455"); } subscriptionId = value; } public int value() { return subscriptionId; } @Override public String toString() { return "SubscriptionIdentifier: " + subscriptionId; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(subscriptionId); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SubscriptionIdentifier that = (SubscriptionIdentifier) o; return subscriptionId == that.subscriptionId;
188
61
249
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/Token.java
Token
equals
class Token implements Comparable<Token> { static final Token EMPTY = new Token(""); static final Token MULTI = new Token("#"); static final Token SINGLE = new Token("+"); final String name; protected Token(String s) { name = s; } protected String name() { return name; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return name; } @Override public int compareTo(Token other) { if (name == null) { if (other.name == null) { return 0; } return 1; } if (other.name == null) { return -1; } return name.compareTo(other.name); } /** * Token which starts with $ is reserved * */ public boolean isReserved() { return name.startsWith("$"); } }
if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Token other = (Token) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true;
338
100
438
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/Topic.java
Topic
isEmpty
class Topic implements Serializable, Comparable<Topic> { private static final Logger LOG = LoggerFactory.getLogger(Topic.class); private static final long serialVersionUID = 2438799283749822L; private final String topic; private transient List<Token> tokens; private transient boolean valid; /** * Factory method * * @param s the topic string (es "/a/b"). * @return the created Topic instance. * */ public static Topic asTopic(String s) { return new Topic(s); } public Topic(String topic) { this.topic = topic; } Topic(List<Token> tokens) { this.tokens = tokens; List<String> strTokens = tokens.stream().map(Token::toString).collect(Collectors.toList()); this.topic = String.join("/", strTokens); this.valid = true; } public List<Token> getTokens() { if (tokens == null) { try { tokens = parseTopic(topic); valid = true; } catch (ParseException e) { valid = false; LOG.error("Error parsing the topic: {}, message: {}", topic, e.getMessage()); } } return tokens; } private List<Token> parseTopic(String topic) throws ParseException { if (topic.length() == 0) { throw new ParseException("Bad format of topic, topic MUST be at least 1 character [MQTT-4.7.3-1] and " + "this was empty", 0); } List<Token> res = new ArrayList<>(); String[] splitted = topic.split("/"); if (splitted.length == 0) { res.add(Token.EMPTY); } if (topic.endsWith("/")) { // Add a fictious space String[] newSplitted = new String[splitted.length + 1]; System.arraycopy(splitted, 0, newSplitted, 0, splitted.length); newSplitted[splitted.length] = ""; splitted = newSplitted; } for (int i = 0; i < splitted.length; i++) { String s = splitted[i]; if (s.isEmpty()) { // if (i != 0) { // throw new ParseException("Bad format of topic, expetec topic name between // separators", i); // } res.add(Token.EMPTY); } else if (s.equals("#")) { // check that multi is the last symbol if (i != splitted.length - 1) { throw new ParseException( "Bad format of topic, the multi symbol (#) has to be the last one after a separator", i); } res.add(Token.MULTI); } else if (s.contains("#")) { throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i); } else if (s.equals("+")) { res.add(Token.SINGLE); } else if (s.contains("+")) { throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i); } else { res.add(new Token(s)); } } return res; } public Token headToken() { final List<Token> tokens = getTokens(); if (tokens.isEmpty()) { //TODO UGLY use Optional return null; } return tokens.get(0); } public boolean isEmpty() {<FILL_FUNCTION_BODY>} /** * @return a new Topic corresponding to this less than the head token * */ public Topic exceptHeadToken() { List<Token> tokens = getTokens(); if (tokens.isEmpty()) { return new Topic(Collections.emptyList()); } List<Token> tokensCopy = new ArrayList<>(tokens); tokensCopy.remove(0); return new Topic(tokensCopy); } public boolean isValid() { if (tokens == null) getTokens(); return valid; } /** * Verify if the 2 topics matching respecting the rules of MQTT Appendix A * * @param subscriptionTopic * the topic filter of the subscription * @return true if the two topics match. */ // TODO reimplement with iterators or with queues public boolean match(Topic subscriptionTopic) { List<Token> msgTokens = getTokens(); List<Token> subscriptionTokens = subscriptionTopic.getTokens(); int i = 0; for (; i < subscriptionTokens.size(); i++) { Token subToken = subscriptionTokens.get(i); if (!Token.MULTI.equals(subToken) && !Token.SINGLE.equals(subToken)) { if (i >= msgTokens.size()) { return false; } Token msgToken = msgTokens.get(i); if (!msgToken.equals(subToken)) { return false; } } else { if (Token.MULTI.equals(subToken)) { return true; } // if (Token.SINGLE.equals(subToken)) { // // skip a step forward // } } } return i == msgTokens.size(); } @Override public String toString() { return topic; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Topic other = (Topic) obj; return Objects.equals(this.topic, other.topic); } @Override public int hashCode() { return topic.hashCode(); } @Override public int compareTo(Topic o) { return topic.compareTo(o.topic); } }
final List<Token> tokens = getTokens(); return tokens == null || tokens.isEmpty();
1,616
27
1,643
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/unsafequeues/PagedFilesAllocator.java
PagedFilesAllocator
openRWPageFile
class PagedFilesAllocator implements SegmentAllocator { interface AllocationListener { void segmentedCreated(String name, Segment segment); } private final Path pagesFolder; private final int pageSize; private final int segmentSize; private int lastSegmentAllocated; private int lastPage; private MappedByteBuffer currentPage; private FileChannel currentPageFile; PagedFilesAllocator(Path pagesFolder, int pageSize, int segmentSize, int lastPage, int lastSegmentAllocated) throws QueueException { if (pageSize % segmentSize != 0) { throw new IllegalArgumentException("The pageSize must be an exact multiple of the segmentSize"); } this.pagesFolder = pagesFolder; this.pageSize = pageSize; this.segmentSize = segmentSize; this.lastPage = lastPage; this.lastSegmentAllocated = lastSegmentAllocated; this.currentPage = openRWPageFile(this.pagesFolder, this.lastPage); } private MappedByteBuffer openRWPageFile(Path pagesFolder, int pageId) throws QueueException {<FILL_FUNCTION_BODY>} @Override public Segment nextFreeSegment() throws QueueException { if (currentPageIsExhausted()) { lastPage++; currentPage = openRWPageFile(pagesFolder, lastPage); lastSegmentAllocated = 0; } final int beginOffset = lastSegmentAllocated * segmentSize; final int endOffset = ((lastSegmentAllocated + 1) * segmentSize) - 1; lastSegmentAllocated += 1; return new Segment(currentPage, new SegmentPointer(lastPage, beginOffset), new SegmentPointer(lastPage, endOffset)); } @Override public Segment reopenSegment(int pageId, int beginOffset) throws QueueException { final MappedByteBuffer page = openRWPageFile(pagesFolder, pageId); final SegmentPointer begin = new SegmentPointer(pageId, beginOffset); final SegmentPointer end = new SegmentPointer(pageId, beginOffset + segmentSize - 1); return new Segment(page, begin, end); } @Override public void close() throws QueueException { if (currentPageFile != null) { try { currentPageFile.close(); } catch (IOException ex) { throw new QueueException("Problem closing current page file", ex); } } } @Override public void dumpState(Properties checkpoint) { checkpoint.setProperty("segments.last_page", String.valueOf(this.lastPage)); checkpoint.setProperty("segments.last_segment", String.valueOf(this.lastSegmentAllocated)); } @Override public int getPageSize() { return pageSize; } @Override public int getSegmentSize() { return segmentSize; } private boolean currentPageIsExhausted() { return lastSegmentAllocated * segmentSize == pageSize; } }
final Path pageFile = pagesFolder.resolve(String.format("%d.page", pageId)); boolean createNew = false; if (!Files.exists(pageFile)) { try { pageFile.toFile().createNewFile(); createNew = true; } catch (IOException ex) { throw new QueueException("Reached an IO error during the bootstrapping of empty 'checkpoint.properties'", ex); } } try (FileChannel fileChannel = FileChannel.open(pageFile, StandardOpenOption.READ, StandardOpenOption.WRITE)) { this.currentPageFile = fileChannel; final MappedByteBuffer mappedPage = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, pageSize); // DBG if (createNew && QueuePool.queueDebug) { for (int i = 0; i < pageSize; i++) { mappedPage.put(i, (byte) 'C'); } } // DBG return mappedPage; } catch (IOException e) { throw new QueueException("Can't open page file " + pageFile, e); }
775
291
1,066
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/unsafequeues/Segment.java
Segment
checkContentStartWith
class Segment { private static final Logger LOG = LoggerFactory.getLogger(Segment.class); final int segmentSize; final SegmentPointer begin; final SegmentPointer end; private final MappedByteBuffer mappedBuffer; Segment(MappedByteBuffer page, SegmentPointer begin, SegmentPointer end) { assert begin.samePage(end); this.segmentSize = end.offset() - begin.offset() + 1; this.begin = begin; this.end = end; this.mappedBuffer = page; } boolean hasSpace(VirtualPointer mark, long length) { return bytesAfter(mark) >= length; } /** * @return number of bytes in segment after the pointer. * The pointer slot is not counted. * */ public long bytesAfter(SegmentPointer mark) { assert mark.samePage(this.end); return end.distance(mark); } public long bytesAfter(VirtualPointer mark) { final int pageOffset = rebasedOffset(mark); final SegmentPointer physicalMark = new SegmentPointer(this.end.pageId(), pageOffset); return end.distance(physicalMark); } void write(SegmentPointer offset, ByteBuffer content) { checkContentStartWith(content); final int startPos = offset.offset(); final int endPos = startPos + content.remaining(); for (int i = startPos; i < endPos; i++) { mappedBuffer.put(i, content.get()); } } // fill the segment with value bytes void fillWith(byte value) { LOG.debug("Wipe segment {}", this); final int target = begin.offset() + (int)size(); for (int i = begin.offset(); i < target; i++) { mappedBuffer.put(i, value); } } // debug method private void checkContentStartWith(ByteBuffer content) {<FILL_FUNCTION_BODY>} void write(VirtualPointer offset, ByteBuffer content) { final int startPos = rebasedOffset(offset); final int endPos = startPos + content.remaining(); for (int i = startPos; i < endPos; i++) { mappedBuffer.put(i, content.get()); } } /** * Force flush of memory mapper buffer to disk * */ void force() { mappedBuffer.force(); } /** * return the int value contained in the 4 bytes after the pointer. * * @param pointer virtual pointer to start read from. * */ int readHeader(VirtualPointer pointer) { final int rebasedIndex = rebasedOffset(pointer); LOG.debug(" {} {} {} {} at {}", Integer.toHexString(mappedBuffer.get(rebasedIndex)), Integer.toHexString(mappedBuffer.get(rebasedIndex + 1)), Integer.toHexString(mappedBuffer.get(rebasedIndex + 2)), Integer.toHexString(mappedBuffer.get(rebasedIndex + 3)), pointer ); return mappedBuffer.getInt(rebasedIndex); } /*private*/ int rebasedOffset(VirtualPointer virtualPtr) { final int pointerOffset = (int) virtualPtr.segmentOffset(segmentSize); return this.begin.plus(pointerOffset).offset(); } public ByteBuffer read(VirtualPointer start, int length) { final int pageOffset = rebasedOffset(start); byte[] dst = new byte[length]; int sourceIdx = pageOffset; for (int dstIndex = 0; dstIndex < length; dstIndex++, sourceIdx++) { dst[dstIndex] = mappedBuffer.get(sourceIdx); } return ByteBuffer.wrap(dst); } public ByteBuffer read(SegmentPointer start, int length) { byte[] dst = new byte[length]; if (length > mappedBuffer.remaining() - start.offset()) throw new BufferUnderflowException(); int sourceIdx = start.offset(); for (int dstIndex = 0; dstIndex < length; dstIndex++, sourceIdx++) { dst[dstIndex] = mappedBuffer.get(sourceIdx); } return ByteBuffer.wrap(dst); } private long size() { return end.distance(begin) + 1; } @Override public String toString() { return "Segment{page=" + begin.pageId() + ", begin=" + begin.offset() + ", end=" + end.offset() + ", size=" + size() + "}"; } ByteBuffer readAllBytesAfter(SegmentPointer start) { // WARN, dataStart points to a byte position to read // if currentSegment.end is at offset 1023, and data start is 1020, the bytes after are 4 and // not 1023 - 1020. final long availableDataLength = bytesAfter(start) + 1; final ByteBuffer buffer = read(start, (int) availableDataLength); buffer.rewind(); return buffer; } ByteBuffer readAllBytesAfter(VirtualPointer start) { // WARN, dataStart points to a byte position to read // if currentSegment.end is at offset 1023, and data start is 1020, the bytes after are 4 and // not 1023 - 1020. final long availableDataLength = bytesAfter(start) + 1; final ByteBuffer buffer = read(start, (int) availableDataLength); buffer.rewind(); return buffer; } }
if (content.get(0) == 0 && content.get(1) == 0 && content.get(2) == 0 && content.get(3) == 0) { System.out.println("DNADBG content starts with 4 zero"); }
1,457
67
1,524
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/unsafequeues/SegmentPointer.java
SegmentPointer
equals
class SegmentPointer implements Comparable<SegmentPointer> { private final int idPage; private final long offset; public SegmentPointer(int idPage, long offset) { this.idPage = idPage; this.offset = offset; } /** * Construct using the segment, but changing the offset. * */ public SegmentPointer(Segment segment, long offset) { this.idPage = segment.begin.idPage; this.offset = offset; } /** * Copy constructor * */ public SegmentPointer copy() { return new SegmentPointer(idPage, offset); } @Override public int compareTo(SegmentPointer other) { if (idPage == other.idPage) { return Long.compare(offset, other.offset); } else { return Integer.compare(idPage, other.idPage); } } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(idPage, offset); } boolean samePage(SegmentPointer other) { return idPage == other.idPage; } SegmentPointer moveForward(long length) { return new SegmentPointer(idPage, offset + length); } @Override public String toString() { return "SegmentPointer{idPage=" + idPage + ", offset=" + offset + '}'; } /** * Calculate the distance in bytes inside the same segment * */ public long distance(SegmentPointer other) { assert idPage == other.idPage; return offset - other.offset; } int offset() { return (int) offset; } public SegmentPointer plus(int delta) { return moveForward(delta); } int pageId() { return this.idPage; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SegmentPointer that = (SegmentPointer) o; return idPage == that.idPage && offset == that.offset;
507
65
572
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/interception/messages/InterceptAcknowledgedMessage.java
StoredMessage
toString
class StoredMessage implements Serializable { private static final long serialVersionUID = 1755296138639817304L; private MqttQoS m_qos; final byte[] m_payload; final String m_topic; private boolean m_retained; private String m_clientID; public StoredMessage(byte[] message, MqttQoS qos, String topic) { m_qos = qos; m_payload = message; m_topic = topic; } public void setQos(MqttQoS qos) { this.m_qos = qos; } public MqttQoS getQos() { return m_qos; } public String getTopic() { return m_topic; } public String getClientID() { return m_clientID; } public void setClientID(String m_clientID) { this.m_clientID = m_clientID; } public ByteBuf getPayload() { return Unpooled.copiedBuffer(m_payload); } public void setRetained(boolean retained) { this.m_retained = retained; } public boolean isRetained() { return m_retained; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "PublishEvent{clientID='" + m_clientID + '\'' + ", m_retain=" + m_retained + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}';
386
69
455
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/logging/LoggingUtils.java
LoggingUtils
getInterceptorIds
class LoggingUtils { public static <T extends InterceptHandler> Collection<String> getInterceptorIds(Collection<T> handlers) {<FILL_FUNCTION_BODY>} private LoggingUtils() { } }
Collection<String> result = new ArrayList<>(handlers.size()); for (T handler : handlers) { result.add(handler.getID()); } return result;
62
50
112
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/ByteBufDataType.java
ByteBufDataType
read
class ByteBufDataType extends BasicDataType<ByteBuf> { @Override public int compare(ByteBuf a, ByteBuf b) { throw DataUtils.newUnsupportedOperationException("Can not compare"); } @Override public int getMemory(ByteBuf obj) { if (!(obj instanceof ByteBuf)) { throw new IllegalArgumentException("Expected instance of ByteBuf but found " + obj.getClass()); } final int payloadSize = ((ByteBuf) obj).readableBytes(); return 4 + payloadSize; } @Override public ByteBuf read(ByteBuffer buff) {<FILL_FUNCTION_BODY>} @Override public void write(WriteBuffer buff, ByteBuf obj) { final int payloadSize = obj.readableBytes(); byte[] rawBytes = new byte[payloadSize]; obj.copy().readBytes(rawBytes).release(); buff.putInt(payloadSize); buff.put(rawBytes); } @Override public ByteBuf[] createStorage(int i) { return new ByteBuf[i]; } }
final int payloadSize = buff.getInt(); byte[] payload = new byte[payloadSize]; buff.get(payload); return Unpooled.wrappedBuffer(payload);
281
51
332
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/EnqueuedMessageValueType.java
EnqueuedMessageValueType
write
class EnqueuedMessageValueType extends BasicDataType<EnqueuedMessage> { private enum MessageType {PUB_REL_MARKER, PUBLISHED_MESSAGE} private final StringDataType topicDataType = new StringDataType(); private final ByteBufDataType payloadDataType = new ByteBufDataType(); private final PropertiesDataType propertiesDataType = new PropertiesDataType(); @Override public int compare(EnqueuedMessage a, EnqueuedMessage b) { throw DataUtils.newUnsupportedOperationException("Can not compare"); } @Override public int getMemory(EnqueuedMessage obj) { if (obj instanceof SessionRegistry.PubRelMarker) { return 1; } final SessionRegistry.PublishedMessage casted = (SessionRegistry.PublishedMessage) obj; int propertiesSize = hasProperties(casted) ? propertiesDataType.getMemory(casted.getMqttProperties()) : 0; return 1 + // message type 1 + // qos topicDataType.getMemory(casted.getTopic().toString()) + payloadDataType.getMemory(casted.getPayload()) + 1 + // flag to indicate if there are MQttProperties or not propertiesSize; } static boolean hasProperties(SessionRegistry.PublishedMessage casted) { return casted.getMqttProperties().length > 0; } @Override public void write(WriteBuffer buff, EnqueuedMessage obj) {<FILL_FUNCTION_BODY>} @Override public EnqueuedMessage read(ByteBuffer buff) { final byte messageType = buff.get(); if (messageType == MessageType.PUB_REL_MARKER.ordinal()) { return new SessionRegistry.PubRelMarker(); } else if (messageType == MessageType.PUBLISHED_MESSAGE.ordinal()) { final MqttQoS qos = MqttQoS.valueOf(buff.get()); final String topicStr = topicDataType.read(buff); final ByteBuf payload = payloadDataType.read(buff); if (SerdesUtils.containsProperties(buff)) { MqttProperties.MqttProperty[] mqttProperties = propertiesDataType.read(buff); return new SessionRegistry.PublishedMessage(Topic.asTopic(topicStr), qos, payload, false, Instant.MAX, mqttProperties); } else { return new SessionRegistry.PublishedMessage(Topic.asTopic(topicStr), qos, payload, false, Instant.MAX); } } else { throw new IllegalArgumentException("Can't recognize record of type: " + messageType); } } @Override public EnqueuedMessage[] createStorage(int i) { return new EnqueuedMessage[i]; } }
if (obj instanceof SessionRegistry.PublishedMessage) { buff.put((byte) MessageType.PUBLISHED_MESSAGE.ordinal()); final SessionRegistry.PublishedMessage casted = (SessionRegistry.PublishedMessage) obj; buff.put((byte) casted.getPublishingQos().value()); final String token = casted.getTopic().toString(); topicDataType.write(buff, token); payloadDataType.write(buff, casted.getPayload()); if (hasProperties(casted)) { buff.put((byte) 1); // there are properties propertiesDataType.write(buff, casted.getMqttProperties()); } else { buff.put((byte) 0); // there aren't properties } } else if (obj instanceof SessionRegistry.PubRelMarker) { buff.put((byte) MessageType.PUB_REL_MARKER.ordinal()); } else { throw new IllegalArgumentException("Unrecognized message class " + obj.getClass()); }
716
261
977
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2Builder.java
H2Builder
initStore
class H2Builder { private static final Logger LOG = LoggerFactory.getLogger(H2Builder.class); private final String storePath; private final int autosaveInterval; // in seconds private final ScheduledExecutorService scheduler; private final Clock clock; private MVStore mvStore; public H2Builder(ScheduledExecutorService scheduler, Path storePath, int autosaveInterval, Clock clock) { this.storePath = storePath.resolve("moquette_store.h2").toAbsolutePath().toString(); this.autosaveInterval = autosaveInterval; this.scheduler = scheduler; this.clock = clock; } @SuppressWarnings("FutureReturnValueIgnored") public H2Builder initStore() {<FILL_FUNCTION_BODY>} public ISubscriptionsRepository subscriptionsRepository() { return new H2SubscriptionsRepository(mvStore); } public void closeStore() { mvStore.close(); } public IQueueRepository queueRepository() { return new H2QueueRepository(mvStore); } public IRetainedRepository retainedRepository() { return new H2RetainedRepository(mvStore); } public ISessionsRepository sessionsRepository() { return new H2SessionsRepository(mvStore, clock); } }
LOG.info("Initializing H2 store to {}", storePath); if (storePath == null || storePath.isEmpty()) { throw new IllegalArgumentException("H2 store path can't be null or empty"); } if (!Files.exists(Paths.get(storePath))) { try { Files.createFile(Paths.get(storePath)); } catch (IOException ex) { throw new IllegalArgumentException("Error creating " + storePath + " file", ex); } } mvStore = new MVStore.Builder() .fileName(storePath) .autoCommitDisabled() .open(); LOG.trace("Scheduling H2 commit task"); scheduler.scheduleWithFixedDelay(() -> { LOG.trace("Committing to H2"); mvStore.commit(); }, autosaveInterval, autosaveInterval, TimeUnit.SECONDS); return this;
346
238
584
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2PersistentQueue.java
H2PersistentQueue
dequeue
class H2PersistentQueue extends AbstractSessionMessageQueue<SessionRegistry.EnqueuedMessage> { private final MVMap<Long, SessionRegistry.EnqueuedMessage> queueMap; private final MVMap<String, Long> metadataMap; private final AtomicLong head; private final AtomicLong tail; private final MVStore store; private final String queueName; H2PersistentQueue(MVStore store, String queueName) { if (queueName == null || queueName.isEmpty()) { throw new IllegalArgumentException("queueName parameter can't be empty or null"); } final MVMap.Builder<Long, SessionRegistry.EnqueuedMessage> messageTypeBuilder = new MVMap.Builder<Long, SessionRegistry.EnqueuedMessage>() .valueType(new EnqueuedMessageValueType()); this.store = store; this.queueName = queueName; this.queueMap = this.store.openMap("queue_" + this.queueName, messageTypeBuilder); this.metadataMap = store.openMap("queue_" + queueName + "_meta"); //setup head index long headIdx = 0L; if (this.metadataMap.containsKey("head")) { headIdx = this.metadataMap.get("head"); } else { this.metadataMap.put("head", headIdx); } this.head = new AtomicLong(headIdx); //setup tail index long tailIdx = 0L; if (this.metadataMap.containsKey("tail")) { tailIdx = this.metadataMap.get("tail"); } else { this.metadataMap.put("tail", tailIdx); } this.tail = new AtomicLong(tailIdx); } @Override public void enqueue(SessionRegistry.EnqueuedMessage t) { checkEnqueuePreconditions(t); final long nextHead = head.getAndIncrement(); this.queueMap.put(nextHead, t); this.metadataMap.put("head", nextHead + 1); } @Override public SessionRegistry.EnqueuedMessage dequeue() {<FILL_FUNCTION_BODY>} @Override public boolean isEmpty() { checkIsEmptyPreconditions(); return (this.head.intValue() - this.tail.intValue()) == 0; } @Override public void closeAndPurge() { this.closed = true; dropQueue(this.queueName); } private void dropQueue(String queueName) { store.removeMap(store.openMap("queue_" + queueName)); store.removeMap(store.openMap("queue_" + queueName + "_meta")); } }
checkDequeuePreconditions(); if (head.equals(tail)) { return null; } final long nextTail = tail.getAndIncrement(); final SessionRegistry.EnqueuedMessage tail = this.queueMap.get(nextTail); queueMap.remove(nextTail); this.metadataMap.put("tail", nextTail + 1); return tail;
697
104
801
<methods>public non-sealed void <init>() <variables>protected boolean closed
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2QueueRepository.java
H2QueueRepository
listQueueNames
class H2QueueRepository implements IQueueRepository { private MVStore mvStore; public H2QueueRepository(MVStore mvStore) { this.mvStore = mvStore; } @Override public Set<String> listQueueNames() {<FILL_FUNCTION_BODY>} @Override public boolean containsQueue(String queueName) { return mvStore.hasMap("queue_" + queueName); } @Override public SessionMessageQueue<EnqueuedMessage> getOrCreateQueue(String clientId) { return new H2PersistentQueue(mvStore, clientId); } @Override public void close() { // No-op } }
return mvStore.getMapNames().stream() .filter(name -> name.startsWith("queue_") && !name.endsWith("_meta")) .map(name -> name.substring("queue_".length())) .collect(Collectors.toSet());
187
72
259
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2RetainedRepository.java
RetainedMessageValueType
read
class RetainedMessageValueType extends BasicDataType<RetainedMessage> { // Layout for RetainedMessage: // - topic String // - qos int // - payload byte[] // - flag map to say if contains properties, expiry time (MSB, LSB) // - (opt) expiry time in epoch millis long // - (opt) properties private final PropertiesDataType propertiesDataType = new PropertiesDataType(); private static final byte MESSAGE_EXPIRY_FLAG = 0x01; private static final byte PROPERTIES_FLAG = MESSAGE_EXPIRY_FLAG << 1; @Override public int getMemory(RetainedMessage retainedMsg) { int bytesSize = StringDataType.INSTANCE.getMemory(retainedMsg.getTopic().toString()) + 1 + // qos, 1 byte 4 + retainedMsg.getPayload().length + // length + bytes 1; // flags if (retainedMsg.getExpiryTime() != null) { bytesSize += 8; // long } int propertiesSize = retainedMsg.getMqttProperties().length > 0 ? propertiesDataType.getMemory(retainedMsg.getMqttProperties()) : 0; return bytesSize + propertiesSize; } @Override public void write(WriteBuffer buff, RetainedMessage retainedMsg) { StringDataType.INSTANCE.write(buff, retainedMsg.getTopic().toString()); buff.put((byte) retainedMsg.qosLevel().value()); buff.putInt(retainedMsg.getPayload().length); buff.put(retainedMsg.getPayload()); byte flagsBitmask = 0x00; if (retainedMsg.getExpiryTime() != null) { flagsBitmask = (byte) (flagsBitmask | MESSAGE_EXPIRY_FLAG); } if (retainedMsg.getMqttProperties().length > 0) { flagsBitmask = (byte) (flagsBitmask | PROPERTIES_FLAG); } buff.put(flagsBitmask); if (retainedMsg.getExpiryTime() != null) { buff.putLong(retainedMsg.getExpiryTime().toEpochMilli()); } if (retainedMsg.getMqttProperties().length > 0) { propertiesDataType.write(buff, retainedMsg.getMqttProperties()); } } @Override public RetainedMessage read(ByteBuffer buff) {<FILL_FUNCTION_BODY>} @Override public RetainedMessage[] createStorage(int size) { return new RetainedMessage[size]; } }
final String topicStr = StringDataType.INSTANCE.read(buff); final MqttQoS qos = MqttQoS.valueOf(buff.get()); final int payloadSize = buff.getInt(); byte[] payload = new byte[payloadSize]; buff.get(payload); final byte flags = buff.get(); final Instant expiry; if ((flags & MESSAGE_EXPIRY_FLAG) > 0) { long millis = buff.getLong(); expiry = Instant.ofEpochMilli(millis); } else { expiry = null; } final MqttProperties.MqttProperty[] mqttProperties; if ((flags & PROPERTIES_FLAG) > 0) { mqttProperties = propertiesDataType.read(buff); } else { mqttProperties = new MqttProperties.MqttProperty[0]; } if ((flags & MESSAGE_EXPIRY_FLAG) > 0) { return new RetainedMessage(new Topic(topicStr), qos, payload, mqttProperties, expiry); } else { return new RetainedMessage(new Topic(topicStr), qos, payload, mqttProperties); }
683
328
1,011
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2SessionsRepository.java
WillDataValueType
getMemory
class WillDataValueType extends BasicDataType<Will> { private final StringDataType stringDataType = new StringDataType(); private final WillOptionsDataValueType willOptionsDataType = new WillOptionsDataValueType(); @Override public int getMemory(Will will) {<FILL_FUNCTION_BODY>} @Override public void write(WriteBuffer buff, Will will) { stringDataType.write(buff, will.topic); buff.putInt(will.payload.length); buff.put(will.payload); // MSB retained, LSB QoS byte retained = will.retained ? (byte) 0x10 : 0x00; byte qos = (byte) (will.qos.value() & 0x0F); buff.put((byte) (retained & qos)); buff.putInt(will.delayInterval); buff.putLong(will.expireAt().map(Instant::toEpochMilli).orElse(UNDEFINED_INSTANT)); if (will.properties.notEmpty()) { willOptionsDataType.write(buff, will.properties); } } @Override public Will read(ByteBuffer buff) { final String topic = stringDataType.read(buff); final int payloadLength = buff.getInt(); final byte[] payload = new byte[payloadLength]; buff.get(payload); final byte rawFlags = buff.get(); // MSB retained, LSB QoS final byte qos = (byte) (rawFlags & 0x0F); final boolean retained = ((rawFlags >> 4) & 0x0F) > 0; final int willDelayInterval = buff.getInt(); Will will = new Will(topic, payload, MqttQoS.valueOf(qos), retained, willDelayInterval); final long expiresAt = buff.getLong(); if (expiresAt != UNDEFINED_INSTANT) { will = new Will(will, Instant.ofEpochMilli(expiresAt)); } final WillOptions options = willOptionsDataType.read(buff); if (options != null && options.notEmpty()) { will = new Will(will, options); } return will; } @Override public Will[] createStorage(int i) { return new Will[i]; } }
return stringDataType.getMemory(will.topic) + 4 + /* payload length */ will.payload.length + 1 /* retained + qos */;
614
45
659
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/H2SubscriptionsRepository.java
SubscriptionOptionAndIdValueType
read
class SubscriptionOptionAndIdValueType extends BasicDataType<SubscriptionOptionAndId> { @Override public int getMemory(SubscriptionOptionAndId obj) { return 4 + // integer, subscription identifier SubscriptionOptionValueType.INSTANCE.getMemory(obj.option); } @Override public void write(WriteBuffer buff, SubscriptionOptionAndId obj) { if (obj.subscriptionIdentifier != null) { buff.putInt(obj.subscriptionIdentifier.intValue()); } else { buff.putInt(-1); } SubscriptionOptionValueType.INSTANCE.write(buff, obj.option); } @Override public SubscriptionOptionAndId read(ByteBuffer buff) {<FILL_FUNCTION_BODY>} @Override public SubscriptionOptionAndId[] createStorage(int size) { return new SubscriptionOptionAndId[size]; } }
int subId = buff.getInt(); MqttSubscriptionOption option = SubscriptionOptionValueType.INSTANCE.read(buff); if (subId != -1) { return new SubscriptionOptionAndId(option, subId); } else { return new SubscriptionOptionAndId(option); }
236
84
320
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/MemorySubscriptionsRepository.java
MemorySubscriptionsRepository
removeSharedSubscription
class MemorySubscriptionsRepository implements ISubscriptionsRepository { private static final Logger LOG = LoggerFactory.getLogger(MemorySubscriptionsRepository.class); private final Set<Subscription> subscriptions = new ConcurrentSkipListSet<>(); private final Map<String, Map<Utils.Couple<ShareName, Topic>, SharedSubscription>> sharedSubscriptions = new HashMap<>(); @Override public Set<Subscription> listAllSubscriptions() { return Collections.unmodifiableSet(subscriptions); } @Override public void addNewSubscription(Subscription subscription) { subscriptions.add(subscription); } @Override public void removeSubscription(String topic, String clientID) { subscriptions.stream() .filter(s -> s.getTopicFilter().toString().equals(topic) && s.getClientId().equals(clientID)) .findFirst() .ifPresent(subscriptions::remove); } @Override public void removeAllSharedSubscriptions(String clientId) { sharedSubscriptions.remove(clientId); } @Override public void removeSharedSubscription(String clientId, ShareName share, Topic topicFilter) {<FILL_FUNCTION_BODY>} @Override public void addNewSharedSubscription(String clientId, ShareName share, Topic topicFilter, MqttSubscriptionOption option) { SharedSubscription sharedSub = new SharedSubscription(share, topicFilter, clientId, option); storeNewSharedSubscription(clientId, share, topicFilter, sharedSub); } private void storeNewSharedSubscription(String clientId, ShareName share, Topic topicFilter, SharedSubscription sharedSub) { Map<Utils.Couple<ShareName, Topic>, SharedSubscription> subsMap = sharedSubscriptions.computeIfAbsent(clientId, unused -> new HashMap<>()); subsMap.put(Utils.Couple.of(share, topicFilter), sharedSub); } @Override public void addNewSharedSubscription(String clientId, ShareName share, Topic topicFilter, MqttSubscriptionOption option, SubscriptionIdentifier subscriptionIdentifier) { SharedSubscription sharedSub = new SharedSubscription(share, topicFilter, clientId, option, subscriptionIdentifier); storeNewSharedSubscription(clientId, share, topicFilter, sharedSub); } @Override public Collection<SharedSubscription> listAllSharedSubscription() { final List<SharedSubscription> result = new ArrayList<>(); for (Map.Entry<String, Map<Utils.Couple<ShareName, Topic>, SharedSubscription>> entry : sharedSubscriptions.entrySet()) { for (Map.Entry<Utils.Couple<ShareName, Topic>, SharedSubscription> nestedEntry : entry.getValue().entrySet()) { result.add(nestedEntry.getValue()); } } return result; } }
Map<Utils.Couple<ShareName, Topic>, SharedSubscription> subsMap = sharedSubscriptions.get(clientId); if (subsMap == null) { LOG.info("Removing a non existing shared subscription for client: {}", clientId); return; } subsMap.remove(Utils.Couple.of(share, topicFilter)); if (subsMap.isEmpty()) { // clean up an empty sub map sharedSubscriptions.remove(clientId); }
739
130
869
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/PropertiesDataType.java
PropertiesDataType
write
class PropertiesDataType extends BasicDataType<MqttProperties.MqttProperty[]> { private final PropertyDataType propertyDataType = new PropertyDataType(); @Override public int getMemory(MqttProperties.MqttProperty[] obj) { return 4 + // integer containing the number of properties Arrays.stream(obj).mapToInt(propertyDataType::getMemory).sum(); } @Override public void write(WriteBuffer buff, MqttProperties.MqttProperty[] obj) {<FILL_FUNCTION_BODY>} @Override public MqttProperties.MqttProperty[] read(ByteBuffer buff) { return SerdesUtils.readProperties(buff, buffer -> propertyDataType.read(buff)); } @Override public MqttProperties.MqttProperty[][] createStorage(int size) { return new MqttProperties.MqttProperty[size][]; } }
// store property list size buff.putInt(obj.length); for (MqttProperties.MqttProperty property : obj) { propertyDataType.write(buff, property); }
241
54
295
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/PropertyDataType.java
PropertyDataType
read
class PropertyDataType extends BasicDataType<MqttProperties.MqttProperty> { enum MqttPropertyEnum {STRING, INTEGER, BINARY} private final ByteBufDataType binaryDataType = new ByteBufDataType(); @Override public int getMemory(MqttProperties.MqttProperty property) { int propSize = 4; // propertyId if (property instanceof MqttProperties.StringProperty) { MqttProperties.StringProperty stringProp = (MqttProperties.StringProperty) property; propSize += StringDataType.INSTANCE.getMemory(stringProp.value()); } else if (property instanceof MqttProperties.IntegerProperty) { propSize += 4; // integer is 4 bytes } else if (property instanceof MqttProperties.BinaryProperty) { MqttProperties.BinaryProperty byteArrayProp = (MqttProperties.BinaryProperty) property; propSize += binaryDataType.getMemory(Unpooled.wrappedBuffer(byteArrayProp.value())); } return 1 + // property type propSize; } @Override public void write(WriteBuffer buff, MqttProperties.MqttProperty property) { if (property instanceof MqttProperties.StringProperty) { MqttProperties.StringProperty stringProp = (MqttProperties.StringProperty) property; writePropertyType(buff, MqttPropertyEnum.STRING); buff.putInt(stringProp.propertyId()); StringDataType.INSTANCE.write(buff, stringProp.value()); } else if (property instanceof MqttProperties.IntegerProperty) { MqttProperties.IntegerProperty intProp = (MqttProperties.IntegerProperty) property; writePropertyType(buff, MqttPropertyEnum.INTEGER); buff.putInt(intProp.propertyId()); buff.putInt(intProp.value()); } else if (property instanceof MqttProperties.BinaryProperty) { MqttProperties.BinaryProperty byteArrayProp = (MqttProperties.BinaryProperty) property; writePropertyType(buff, MqttPropertyEnum.BINARY); binaryDataType.write(buff, Unpooled.wrappedBuffer(byteArrayProp.value())); } // TODO UserProperties and UserProperty? } private static void writePropertyType(WriteBuffer buff, MqttPropertyEnum mqttPropertyEnum) { buff.put((byte) mqttPropertyEnum.ordinal()); } @Override public MqttProperties.MqttProperty read(ByteBuffer buff) {<FILL_FUNCTION_BODY>} @Override public MqttProperties.MqttProperty[] createStorage(int size) { return new MqttProperties.MqttProperty[size]; } }
return SerdesUtils.readSingleProperty(buff, buffer -> { ByteBuf byteArray = binaryDataType.read(buffer); return byteArray.array(); });
691
46
737
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/SegmentPersistentQueue.java
SegmentPersistentQueue
dequeue
class SegmentPersistentQueue extends AbstractSessionMessageQueue<SessionRegistry.EnqueuedMessage> { private static final Logger LOG = LoggerFactory.getLogger(SegmentPersistentQueue.class); private final Queue segmentedQueue; private final SegmentedPersistentQueueSerDes serdes = new SegmentedPersistentQueueSerDes(); public SegmentPersistentQueue(Queue segmentedQueue) { this.segmentedQueue = segmentedQueue; } @Override public void enqueue(SessionRegistry.EnqueuedMessage message) { LOG.debug("Adding message {}", message); checkEnqueuePreconditions(message); final ByteBuffer payload = serdes.toBytes(message); try { segmentedQueue.enqueue(payload); } catch (QueueException e) { throw new RuntimeException(e); } } @Override public SessionRegistry.EnqueuedMessage dequeue() {<FILL_FUNCTION_BODY>} @Override public boolean isEmpty() { return segmentedQueue.isEmpty(); } @Override public void closeAndPurge() { closed = true; } }
checkDequeuePreconditions(); final Optional<ByteBuffer> dequeue; try { dequeue = segmentedQueue.dequeue(); } catch (QueueException e) { throw new RuntimeException(e); } if (!dequeue.isPresent()) { LOG.debug("No data pulled out from the queue"); return null; } final ByteBuffer content = dequeue.get(); SessionRegistry.EnqueuedMessage message = serdes.fromBytes(content); LOG.debug("Retrieved message {}", message); return message;
299
146
445
<methods>public non-sealed void <init>() <variables>protected boolean closed
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/SegmentQueueRepository.java
SegmentQueueRepository
close
class SegmentQueueRepository implements IQueueRepository { private static final Logger LOG = LoggerFactory.getLogger(SegmentQueueRepository.class); private final QueuePool queuePool; public SegmentQueueRepository(String path, int pageSize, int segmentSize) throws QueueException { queuePool = QueuePool.loadQueues(Paths.get(path), pageSize, segmentSize); } public SegmentQueueRepository(Path path, int pageSize, int segmentSize) throws QueueException { queuePool = QueuePool.loadQueues(path, pageSize, segmentSize); } @Override public Set<String> listQueueNames() { return queuePool.queueNames(); } @Override public boolean containsQueue(String clientId) { return listQueueNames().contains(clientId); } @Override public SessionMessageQueue<SessionRegistry.EnqueuedMessage> getOrCreateQueue(String clientId) { final Queue segmentedQueue; try { segmentedQueue = queuePool.getOrCreate(clientId); } catch (QueueException e) { throw new RuntimeException(e); } return new SegmentPersistentQueue(segmentedQueue); } @Override public void close() {<FILL_FUNCTION_BODY>} }
try { queuePool.close(); } catch (QueueException e) { LOG.error("Error saving state of the queue pool", e); }
334
43
377
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/persistence/SerdesUtils.java
SerdesUtils
readSingleProperty
class SerdesUtils { static boolean containsProperties(ByteBuffer buff) { return buff.get() == 1; } /** * Deserialize the array of MqttProperties. * * @param propertyDecoder function that read bytes from buffer and create a single MQTT property instance. * */ public static MqttProperties.MqttProperty[] readProperties(ByteBuffer buff, Function<ByteBuffer, MqttProperties.MqttProperty> propertyDecoder) { final int numProperties = buff.getInt(); final List<MqttProperties.MqttProperty> properties = new ArrayList<>(numProperties); for (int i = 0; i < numProperties; i++) { MqttProperties.MqttProperty property = propertyDecoder.apply(buff); properties.add(property); } return properties.toArray(new MqttProperties.MqttProperty[0]); } static MqttProperties.MqttProperty<? extends Serializable> readSingleProperty(ByteBuffer buff, Function<ByteBuffer, byte[]> bytearrayDecoder) {<FILL_FUNCTION_BODY>} }
byte propTypeValue = buff.get(); if (propTypeValue >= PropertyDataType.MqttPropertyEnum.values().length) { throw new IllegalStateException("Unrecognized property type value: " + propTypeValue); } PropertyDataType.MqttPropertyEnum type = PropertyDataType.MqttPropertyEnum.values()[propTypeValue]; int propertyId = buff.getInt(); switch (type) { case STRING: String value = StringDataType.INSTANCE.read(buff); return new MqttProperties.StringProperty(propertyId, value); case INTEGER: return new MqttProperties.IntegerProperty(propertyId, buff.getInt()); case BINARY: return new MqttProperties.BinaryProperty(propertyId, bytearrayDecoder.apply(buff)); default: throw new IllegalStateException("Unrecognized property type value: " + propTypeValue); }
292
235
527
<no_super_class>
weibocom_motan
motan/motan-benchmark/motan-benchmark-client/src/main/java/com/weibo/motan/benchmark/AbstractBenchmarkClient.java
AbstractBenchmarkClient
start
class AbstractBenchmarkClient { private static final int WARMUPTIME = 30; private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private int concurrents; private int runTime; private String classname; private String params; private ClientStatistics statistics; /** * * @param concurrents 并发线程数 * @param runtime benchmark实际运行时间 * @param classname 测试的类名 * @param params 测试String时,指String的size,单位为k */ public void start(int concurrents, int runtime, String classname, String params) {<FILL_FUNCTION_BODY>} private void printStartInfo() { Date currentDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentDate); calendar.add(Calendar.SECOND, runTime); Date finishDate = calendar.getTime(); StringBuilder startInfo = new StringBuilder(dateFormat.format(currentDate)); startInfo.append(" ready to start client benchmark"); startInfo.append(", concurrent num is ").append(concurrents); startInfo.append(", the benchmark will end at ").append(dateFormat.format(finishDate)); System.out.println(startInfo.toString()); } private void printStatistics() { System.out.println("----------Benchmark Statistics--------------"); System.out.println("Concurrents: " + concurrents); System.out.println("Runtime: " + runTime + " seconds"); System.out.println("ClassName: " + classname); System.out.println("Params: " + params); statistics.printStatistics(); } public abstract ClientRunnable getClientRunnable(String classname, String params, CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime); }
this.concurrents = concurrents; this.runTime = runtime; this.classname = classname; this.params = params; printStartInfo(); // prepare runnables long currentTime = System.nanoTime() / 1000L; long startTime = currentTime + WARMUPTIME * 1000 * 1000L; long endTime = currentTime + runTime * 1000 * 1000L; List<ClientRunnable> runnables = new ArrayList<>(); CyclicBarrier cyclicBarrier = new CyclicBarrier(this.concurrents); CountDownLatch countDownLatch = new CountDownLatch(this.concurrents); for (int i = 0; i < this.concurrents; i++) { ClientRunnable runnable = getClientRunnable(classname, params, cyclicBarrier, countDownLatch, startTime, endTime); runnables.add(runnable); Thread thread = new Thread(runnable, "benchmarkclient-" + i); thread.start(); } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } List<RunnableStatistics> runnableStatisticses = new ArrayList<>(); for (ClientRunnable runnable : runnables) { runnableStatisticses.add(runnable.getStatistics()); } statistics = new ClientStatistics(runnableStatisticses); statistics.collectStatistics(); printStatistics(); System.exit(0);
495
433
928
<no_super_class>
weibocom_motan
motan/motan-benchmark/motan-benchmark-client/src/main/java/com/weibo/motan/benchmark/AbstractClientRunnable.java
AbstractClientRunnable
callService
class AbstractClientRunnable implements ClientRunnable { RunnableStatistics statistics; private CyclicBarrier cyclicBarrier; private CountDownLatch countDownLatch; private long startTime; private long endTime; private int statisticTime; private BenchmarkService benchmarkService; public AbstractClientRunnable(BenchmarkService benchmarkService, CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime) { this.cyclicBarrier = barrier; this.countDownLatch = latch; this.startTime = startTime; this.endTime = endTime; this.benchmarkService = benchmarkService; statisticTime = (int) ((endTime - startTime) / 1000000); statistics = new RunnableStatistics(statisticTime); } @Override public RunnableStatistics getStatistics() { return statistics; } @Override public void run() { try { cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } callService(); countDownLatch.countDown(); } private void callService() {<FILL_FUNCTION_BODY>} private void collectResponseTimeDistribution(long time) { double responseTime = (double) (time / 1000L); if (responseTime >= 0 && responseTime <= 1) { statistics.above0sum++; } else if (responseTime > 1 && responseTime <= 5) { statistics.above1sum++; } else if (responseTime > 5 && responseTime <= 10) { statistics.above5sum++; } else if (responseTime > 10 && responseTime <= 50) { statistics.above10sum++; } else if (responseTime > 50 && responseTime <= 100) { statistics.above50sum++; } else if (responseTime > 100 && responseTime <= 500) { statistics.above100sum++; } else if (responseTime > 500 && responseTime <= 1000) { statistics.above500sum++; } else if (responseTime > 1000) { statistics.above1000sum++; } } protected abstract Object call(BenchmarkService benchmarkService); }
long beginTime = System.nanoTime() / 1000L; while (beginTime <= startTime) { // warm up beginTime = System.nanoTime() / 1000L; Object result = call(benchmarkService); } while (beginTime <= endTime) { beginTime = System.nanoTime() / 1000L; Object result = call(benchmarkService); long responseTime = System.nanoTime() / 1000L - beginTime; collectResponseTimeDistribution(responseTime); int currTime = (int) ((beginTime - startTime) / 1000000L); if (currTime >= statisticTime) { continue; } if (result != null) { statistics.TPS[currTime]++; statistics.RT[currTime] += responseTime; } else { statistics.errTPS[currTime]++; statistics.errRT[currTime] += responseTime; } }
625
272
897
<no_super_class>
weibocom_motan
motan/motan-benchmark/motan-benchmark-client/src/main/java/com/weibo/motan/benchmark/ClientStatistics.java
ClientStatistics
printStatistics
class ClientStatistics { public int statisticTime; public long above0sum; // [0,1] public long above1sum; // (1,5] public long above5sum; // (5,10] public long above10sum; // (10,50] public long above50sum; // (50,100] public long above100sum; // (100,500] public long above500sum; // (500,1000] public long above1000sum; // > 1000 public long maxTPS = 0; public long minTPS = 0; public long succTPS = 0; public long succRT = 0; public long errTPS = 0; public long errRT = 0; public long allTPS = 0; public long allRT = 0; public List<RunnableStatistics> statistics; public ClientStatistics(List<RunnableStatistics> statistics) { this.statistics = statistics; statisticTime = statistics.get(0).statisticTime; } public void collectStatistics() { for (RunnableStatistics statistic : statistics) { above0sum += statistic.above0sum; above1sum += statistic.above1sum; above5sum += statistic.above5sum; above10sum += statistic.above10sum; above50sum += statistic.above50sum; above100sum += statistic.above100sum; above500sum += statistic.above500sum; above1000sum += statistic.above1000sum; } for(int i=0; i < statistics.get(0).statisticTime;i++) { long runnableTPS = 0; for (RunnableStatistics statistic : statistics) { runnableTPS += (statistic.TPS[i]+statistic.errTPS[i]); succTPS += statistic.TPS[i]; succRT += statistic.RT[i]; errTPS += statistic.errTPS[i]; errRT += statistic.errRT[i]; } if (runnableTPS > maxTPS) { maxTPS = runnableTPS; } if (runnableTPS < minTPS || minTPS == 0) { minTPS = runnableTPS; } } allTPS = succTPS + errTPS; allRT = succRT + errRT; } public void printStatistics() {<FILL_FUNCTION_BODY>} }
System.out.println("Benchmark Run Time: " + statisticTime); System.out.println(MessageFormat.format("Requests: {0}, Success: {1}%({2}), Error: {3}%({4})", allTPS, succTPS * 100 / allTPS, succTPS, errTPS * 100 / allTPS, errTPS)); System.out.println(MessageFormat.format("Avg TPS: {0}, Max TPS: {1}, Min TPS: {2}", (allTPS / statisticTime), maxTPS, minTPS)); System.out.println(MessageFormat.format("Avg ResponseTime: {0}ms", allRT / allTPS / 1000f)); System.out.println(MessageFormat.format("RT [0,1]: {0}% {1}/{2}", above0sum * 100 / allTPS, above0sum, allTPS)); System.out.println(MessageFormat.format("RT (1,5]: {0}% {1}/{2}", above1sum * 100 / allTPS, above1sum, allTPS)); System.out.println(MessageFormat.format("RT (5,10]: {0}% {1}/{2}", above5sum * 100 / allTPS, above5sum, allTPS)); System.out.println(MessageFormat.format("RT (10,50]: {0}% {1}/{2}", above10sum * 100 / allTPS, above10sum, allTPS)); System.out.println(MessageFormat.format("RT (50,100]: {0}% {1}/{2}", above50sum * 100 / allTPS, above50sum, allTPS)); System.out.println(MessageFormat.format("RT (100,500]: {0}% {1}/{2}", above100sum * 100 / allTPS, above100sum, allTPS)); System.out.println(MessageFormat.format("RT (500,1000]: {0}% {1}/{2}", above500sum * 100 / allTPS, above500sum, allTPS)); System.out.println(MessageFormat.format("RT >1000: {0}% {1}/{2}", above1000sum * 100 / allTPS, above1000sum, allTPS));
703
622
1,325
<no_super_class>
weibocom_motan
motan/motan-benchmark/motan-benchmark-client/src/main/java/com/weibo/motan/benchmark/MotanBenchmarkClient.java
MotanBenchmarkClient
main
class MotanBenchmarkClient extends AbstractBenchmarkClient { static Properties properties = new Properties(); /** * 并发的Runable线程,是否使用相同的client进行调用。 * true:并发线程只使用一个client(bean实例)调用服务。 * false: 每个并发线程使用不同的Client调用服务 */ private static BenchmarkService benchmarkService; private static boolean isMultiClient; public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void loadProperties() { try { properties.load(ClassLoader.getSystemResourceAsStream("benchmark.properties")); } catch (IOException e) { e.printStackTrace(); } } @Override public ClientRunnable getClientRunnable(String classname, String params, CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime) { BenchmarkService service; if (isMultiClient) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath*:motan-benchmark-client.xml"}); service = (BenchmarkService) applicationContext.getBean("motanBenchmarkReferer"); } else { service = benchmarkService; } Class[] parameterTypes = new Class[]{BenchmarkService.class, String.class, CyclicBarrier.class, CountDownLatch.class, long.class, long.class}; Object[] parameters = new Object[]{service, params, barrier, latch, startTime, endTime}; ClientRunnable clientRunnable = null; try { clientRunnable = (ClientRunnable) Class.forName(classname).getConstructor(parameterTypes).newInstance(parameters); } catch (InstantiationException | NoSuchMethodException | ClassNotFoundException | IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException(); } return clientRunnable; } }
loadProperties(); int concurrents = Integer.parseInt(properties.getProperty("concurrents")); int runtime = Integer.parseInt(properties.getProperty("runtime")); String classname = properties.getProperty("classname"); String params = properties.getProperty("params"); isMultiClient = Boolean.parseBoolean(properties.getProperty("isMultiClient")); if (args.length == 5) { concurrents = Integer.parseInt(args[0]); runtime = Integer.parseInt(args[1]); classname = args[2]; params = args[3]; isMultiClient = Boolean.parseBoolean(args[4]); } ApplicationContext applicationContext = new ClassPathXmlApplicationContext( new String[]{"classpath*:motan-benchmark-client.xml"}); benchmarkService = (BenchmarkService) applicationContext.getBean("motanBenchmarkReferer"); new MotanBenchmarkClient().start(concurrents, runtime, classname, params);
526
251
777
<methods>public non-sealed void <init>() ,public abstract com.weibo.motan.benchmark.ClientRunnable getClientRunnable(java.lang.String, java.lang.String, java.util.concurrent.CyclicBarrier, java.util.concurrent.CountDownLatch, long, long) ,public void start(int, int, java.lang.String, java.lang.String) <variables>private static final int WARMUPTIME,private java.lang.String classname,private int concurrents,private java.text.SimpleDateFormat dateFormat,private java.lang.String params,private int runTime,private com.weibo.motan.benchmark.ClientStatistics statistics
weibocom_motan
motan/motan-benchmark/motan-benchmark-server/src/main/java/com/weibo/motan/benchmark/MotanBenchmarkServer.java
MotanBenchmarkServer
main
class MotanBenchmarkServer { public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>} }
ApplicationContext applicationContext = new ClassPathXmlApplicationContext( new String[]{"classpath*:motan-benchmark-server.xml"}); System.out.println("server running---"); Thread.sleep(Long.MAX_VALUE);
41
63
104
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/AbstractAdminCommandHandler.java
AbstractAdminCommandHandler
handle
class AbstractAdminCommandHandler implements AdminCommandHandler { @Override public Response handle(Request request) {<FILL_FUNCTION_BODY>} /** * Process admin command. * If the processing fails, an exception can be thrown safely and the upper layer will handle it uniformly. * * @param command admin command * @param params request params, i.e. http parameters or rpc arguments * @param attachments http headers or rpc attachments * @param result json result. it will be the response value */ protected abstract void process(String command, Map<String, String> params, Map<String, String> attachments, JSONObject result); }
JSONObject result = new JSONObject(); result.put("result", "ok"); // default result. process(request.getMethodName(), AdminUtil.getParams(request), request.getAttachments(), result); return AdminUtil.buildResponse(request, result.toJSONString());
171
74
245
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/AbstractAdminServer.java
RpcServerHandler
processLazyDeserialize
class RpcServerHandler implements MessageHandler { private final Class<?>[] paramClass = new Class[]{Map.class}; private final AdminHandler adminHandler; public RpcServerHandler(AdminHandler adminHandler) { this.adminHandler = adminHandler; } @Override public Object handle(Channel channel, Object message) { if (channel == null || message == null) { throw new MotanFrameworkException("AdminRpcServer handler(channel, message) params is null"); } if (!(message instanceof Request)) { throw new MotanFrameworkException("AdminRpcServer message type not support: " + message.getClass()); } Request request = (Request) message; // process parameter, the parameter type is unified as Map<String, String> processLazyDeserialize(request); Response response = adminHandler.handle(request); response.setSerializeNumber(request.getSerializeNumber()); response.setRpcProtocolVersion(request.getRpcProtocolVersion()); return response; } protected void processLazyDeserialize(Request request) {<FILL_FUNCTION_BODY>} }
if (request.getArguments() != null && request.getArguments().length == 1 && request.getArguments()[0] instanceof DeserializableObject && request instanceof DefaultRequest) { try { Object[] args = ((DeserializableObject) request.getArguments()[0]).deserializeMulti(paramClass); ((DefaultRequest) request).setArguments(args); } catch (IOException e) { throw new MotanFrameworkException("deserialize parameters fail: " + request + ", error:" + e.getMessage()); } }
289
137
426
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/AdminInitialization.java
AdminInitialization
parsePort
class AdminInitialization implements Initializable { // default values private static final String DEFAULT_ADMIN_SERVER = "netty4"; private static final String SECOND_DEFAULT_ADMIN_SERVER = "netty3"; private static final String DEFAULT_ADMIN_PROTOCOL = "http"; @Override public void init() { try { int port = getAdminPort(); if (port >= 0) { // create admin server String adminServerString = MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_SERVER); AdminServerFactory adminServerFactory; // an exception will be thrown if AdminServerFactory is not found if (StringUtils.isNotBlank(adminServerString)) { adminServerFactory = ExtensionLoader.getExtensionLoader(AdminServerFactory.class).getExtension(adminServerString); } else { // use default admin server adminServerFactory = ExtensionLoader.getExtensionLoader(AdminServerFactory.class).getExtension(DEFAULT_ADMIN_SERVER, false); if (adminServerFactory == null) { adminServerFactory = ExtensionLoader.getExtensionLoader(AdminServerFactory.class).getExtension(SECOND_DEFAULT_ADMIN_SERVER); } } // build admin server url URL adminUrl = new URL(MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_PROTOCOL, DEFAULT_ADMIN_PROTOCOL), "127.0.0.1", port, "/", MotanGlobalConfigUtil.getConfigs().entrySet().stream().filter((entry) -> entry.getKey().startsWith("admin.")).collect(Collectors.toMap((entry) -> entry.getKey().substring("admin.".length()), Map.Entry::getValue))); // add default command handlers; addDefaultHandlers(); // add command handler extensions from config addExtHandlers(MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_EXT_HANDLERS)); // add command handler extensions from ENV addExtHandlers(System.getenv(MotanConstants.ENV_MOTAN_ADMIN_EXT_HANDLERS)); // create admin server AdminServer adminServer = adminServerFactory.createServer(adminUrl, AdminUtil.getDefaultAdminHandler()); adminServer.open(); LoggerUtil.info("admin server is open. url:" + adminUrl.toFullStr()); } } catch (Exception e) { LoggerUtil.error("admin server open fail.", e); } } private int getAdminPort() { int port = -1; // 'admin.disable' has the highest priority if ("true".equals(MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_DISABLE))) { return port; } // get from env port = parsePort(System.getenv(MotanConstants.ENV_MOTAN_ADMIN_PORT)); if (port < 0) { // get from global configs port = parsePort(MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_PORT)); } // default admin port if (port < 0) { port = MotanConstants.DEFAULT_ADMIN_PORT; } return port; } private int parsePort(String portStr) {<FILL_FUNCTION_BODY>} private void addDefaultHandlers() { AdminUtil.addCommandHandler(new CommandListHandler()); AdminUtil.addCommandHandler(new RuntimeInfoHandler()); AdminUtil.addCommandHandler(new MetaInfoHandler()); } private void addExtHandlers(String handlerString) { if (handlerString != null) { String[] handlers = handlerString.split(","); for (String h : handlers) { if (StringUtils.isNotBlank(h)) { try { AdminCommandHandler handler = ExtensionLoader.getExtensionLoader(AdminCommandHandler.class).getExtension(h.trim()); AdminUtil.addCommandHandler(handler, true); LoggerUtil.info("admin server add handler " + handler.getClass().getName()); } catch (Exception e) { LoggerUtil.warn("can not find admin command handler :" + h); } } } } } }
int port = -1; if (StringUtils.isNotBlank(portStr)) { try { port = Integer.parseInt(portStr); } catch (NumberFormatException e) { LoggerUtil.warn("AdminInitialization parse admin port from env fail. value:" + portStr); } } return port;
1,067
89
1,156
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/AdminUtil.java
AdminUtil
buildResponse
class AdminUtil { private static final DefaultPermissionChecker DEFAULT_PERMISSION_CHECKER = new DefaultPermissionChecker(); private static final AdminHandler DEFAULT_ADMIN_HANDLER = new DefaultAdminHandler(); public static AdminHandler getDefaultAdminHandler() { return DEFAULT_ADMIN_HANDLER; } public static PermissionChecker getDefaultPermissionChecker() { return DEFAULT_PERMISSION_CHECKER; } public static void addCommandHandler(AdminCommandHandler adminCommandHandler) { addCommandHandler(adminCommandHandler, false); } public static void addCommandHandler(AdminCommandHandler adminCommandHandler, boolean override) { DEFAULT_ADMIN_HANDLER.addCommandHandler(adminCommandHandler, override); } public static void updatePermissionChecker(PermissionChecker permissionChecker) { DEFAULT_ADMIN_HANDLER.updatePermissionChecker(permissionChecker); } /** * build response for admin server * * @param request admin request * @param returnValue return value for the request * @return admin response */ public static DefaultResponse buildResponse(Request request, String returnValue) {<FILL_FUNCTION_BODY>} /** * build error response for admin server * * @param request admin request * @param errMessage error message for the request * @return error admin response */ public static DefaultResponse buildErrorResponse(Request request, String errMessage) { DefaultResponse response = new DefaultResponse(); response.setRequestId(request.getRequestId()); response.setRpcProtocolVersion(request.getRpcProtocolVersion()); response.setException(new MotanServiceException(toJsonErrorMessage(errMessage))); return response; } public static String toJsonErrorMessage(String errMessage) { JSONObject errJson = new JSONObject(); errJson.put("result", "fail"); errJson.put("error", errMessage == null ? "null" : errMessage); return errJson.toJSONString(); } public static DefaultResponse unknownCommand(Request request) { return buildErrorResponse(request, "unknown command " + request.getMethodName()); } public static DefaultResponse notAllowed(Request request) { return buildErrorResponse(request, "not allowed"); } @SuppressWarnings("unchecked") public static Map<String, String> getParams(Request request) { if (request.getArguments() == null || request.getArguments().length < 1 || !(request.getArguments()[0] instanceof Map)) { return Collections.emptyMap(); } return (Map<String, String>) request.getArguments()[0]; } }
DefaultResponse response = new DefaultResponse(); response.setRequestId(request.getRequestId()); response.setRpcProtocolVersion(request.getRpcProtocolVersion()); response.setValue(returnValue); return response;
693
60
753
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/DefaultAdminHandler.java
DefaultAdminHandler
addCommandHandler
class DefaultAdminHandler implements AdminHandler { protected PermissionChecker permissionChecker; protected ConcurrentHashMap<String, AdminCommandHandler> routeHandlers = new ConcurrentHashMap<>(); public DefaultAdminHandler(){ this(AdminUtil.getDefaultPermissionChecker()); } public DefaultAdminHandler(PermissionChecker permissionChecker) { if (permissionChecker == null) { throw new MotanFrameworkException("permissionChecker can not be null"); } this.permissionChecker = permissionChecker; } @Override public Response handle(Request request) { boolean pass = permissionChecker.check(request); if (!pass) { return AdminUtil.notAllowed(request); } AdminCommandHandler handler = routeHandlers.get(request.getMethodName()); if (handler == null) { return AdminUtil.unknownCommand(request); } try { return handler.handle(request); } catch (MotanAbstractException mae){ return AdminUtil.buildErrorResponse(request, mae.getOriginMessage()); } catch (Throwable e) { return AdminUtil.buildErrorResponse(request, e.getMessage()); } } @Override public void addCommandHandler(AdminCommandHandler adminCommandHandler, boolean override) {<FILL_FUNCTION_BODY>} @Override public PermissionChecker updatePermissionChecker(PermissionChecker permissionChecker) { if (permissionChecker == null) { throw new MotanFrameworkException("admin permission checker is null"); } PermissionChecker old = this.permissionChecker; this.permissionChecker = permissionChecker; return old; } public Set<String> getCommandSet(){ return routeHandlers.keySet(); } }
String[] commands = adminCommandHandler.getCommandName(); for (String c : commands) { if (StringUtils.isNotBlank(c)) { c = c.trim(); if (override) { routeHandlers.put(c, adminCommandHandler); } else { routeHandlers.putIfAbsent(c, adminCommandHandler); } } }
458
103
561
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/DefaultPermissionChecker.java
DefaultPermissionChecker
check
class DefaultPermissionChecker implements PermissionChecker { public static final String ADMIN_DISABLE_SWITCHER = "feature.motan.admin.disable"; protected String token; public DefaultPermissionChecker() { init(); } @Override public boolean check(Request request) {<FILL_FUNCTION_BODY>} protected boolean extendValidate(Request request) { // Override this method for extended validation return false; } protected String getToken(Request request){ String requestToken = request.getAttachments().get("Token"); if (requestToken == null){ requestToken = request.getAttachments().get("token"); } return requestToken; } private void init() { // set token String token = System.getenv(MotanConstants.ENV_MOTAN_ADMIN_TOKEN); if (StringUtils.isBlank(token)) { token = MotanGlobalConfigUtil.getConfig(MotanConstants.ADMIN_TOKEN); } if (token != null) { this.token = token.trim(); } MotanSwitcherUtil.switcherIsOpenWithDefault(ADMIN_DISABLE_SWITCHER, false); } }
// check ip String ip = request.getAttachments().get(URLParamType.host.getName()); if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) { return true; } if (MotanSwitcherUtil.isOpen(ADMIN_DISABLE_SWITCHER)) { // disable token validation and extended validation return false; } // check token if (token != null && token.equals(getToken(request))) { return true; } // for custom extension return extendValidate(request);
324
166
490
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/handler/CommandListHandler.java
CommandListHandler
process
class CommandListHandler extends AbstractAdminCommandHandler { @Override protected void process(String command, Map<String, String> params, Map<String, String> attachments, JSONObject result) {<FILL_FUNCTION_BODY>} @Override public String[] getCommandName() { return new String[]{"/command/list"}; } }
JSONArray jsonArray = new JSONArray(); if (AdminUtil.getDefaultAdminHandler() instanceof DefaultAdminHandler) { jsonArray.addAll(((DefaultAdminHandler) AdminUtil.getDefaultAdminHandler()).getCommandSet()); } result.put("commandList", jsonArray);
91
73
164
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.rpc.Response handle(com.weibo.api.motan.rpc.Request) <variables>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/handler/FaultInjectCommandHandler.java
FaultInjectCommandHandler
process
class FaultInjectCommandHandler extends AbstractAdminCommandHandler { private static final String[] commands = new String[]{ "/faultInjection/config/update", "/faultInjection/config/clear", "/faultInjection/config/get"}; static { String filters = MotanGlobalConfigUtil.getConfig(ENV_GLOBAL_FILTERS); filters = StringUtils.isBlank(filters) ? "faultInjection" : filters + MotanConstants.COMMA_SEPARATOR + "faultInjection"; MotanGlobalConfigUtil.putConfig(ENV_GLOBAL_FILTERS, filters); } @Override public String[] getCommandName() { return commands; } @Override protected void process(String command, Map<String, String> params, Map<String, String> attachments, JSONObject result) {<FILL_FUNCTION_BODY>} }
if (commands[0].equals(command)) { String configs = params.get("configs"); List<FaultInjectionFilter.FaultInjectionConfig> configList = JSONArray.parseArray(configs, FaultInjectionFilter.FaultInjectionConfig.class); if (configList == null) { throw new MotanServiceException("param configs not correct"); } FaultInjectionFilter.FaultInjectionUtil.updateConfigs(configList); } else if (commands[1].equals(command)) { FaultInjectionFilter.FaultInjectionUtil.clearConfigs(); }else if (commands[2].equals(command)){ List<FaultInjectionFilter.FaultInjectionConfig> conf = FaultInjectionFilter.FaultInjectionUtil.getConfigs(); result.put("data", JSON.parseArray(JSON.toJSONString(conf))); }
234
228
462
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.rpc.Response handle(com.weibo.api.motan.rpc.Request) <variables>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/handler/MetaInfoHandler.java
MetaInfoHandler
process
class MetaInfoHandler extends AbstractAdminCommandHandler { private static final String[] commands = new String[]{ "/meta/update", "/meta/delete", "/meta/get", "/meta/getAll" }; @Override protected void process(String command, Map<String, String> params, Map<String, String> attachments, JSONObject result) {<FILL_FUNCTION_BODY>} @Override public String[] getCommandName() { return commands; } }
if (commands[0].equals(command)) { params.forEach(GlobalRuntime::putDynamicMeta); } else if (commands[1].equals(command)) { GlobalRuntime.removeDynamicMeta(params.get("key")); } else if (commands[2].equals(command)) { result.put(params.get("key"), GlobalRuntime.getDynamicMeta().get(params.get("key"))); } else if (commands[3].equals(command)) { result.put("meta", GlobalRuntime.getDynamicMeta()); }
129
139
268
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.rpc.Response handle(com.weibo.api.motan.rpc.Request) <variables>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/admin/handler/RuntimeInfoHandler.java
RuntimeInfoHandler
process
class RuntimeInfoHandler extends AbstractAdminCommandHandler { @Override protected void process(String command, Map<String, String> params, Map<String, String> attachments, JSONObject result) {<FILL_FUNCTION_BODY>} private void addInfos(Map<String, ? extends RuntimeInfo> infos, String key, JSONObject result) { if (!infos.isEmpty()) { JSONObject infoObject = new JSONObject(); infos.forEach((k, v) -> infoObject.put(k, v.getRuntimeInfo())); result.put(key, infoObject); } } @Override public String[] getCommandName() { return new String[]{"/runtime/info"}; } }
result.put(RuntimeInfoKeys.INSTANCE_TYPE_KEY, "motan-java"); result.put(RuntimeInfoKeys.GLOBAL_CONFIG_KEY, MotanGlobalConfigUtil.getConfigs()); // add registry infos addInfos(GlobalRuntime.getRuntimeRegistries(), RuntimeInfoKeys.REGISTRIES_KEY, result); // add cluster infos addInfos(GlobalRuntime.getRuntimeClusters(), RuntimeInfoKeys.CLUSTERS_KEY, result); // add exporter infos addInfos(GlobalRuntime.getRuntimeExporters(), RuntimeInfoKeys.EXPORTERS_KEY, result); // add mesh client infos addInfos(GlobalRuntime.getRuntimeMeshClients(), RuntimeInfoKeys.MESH_CLIENTS_KEY, result); // add server infos addInfos(GlobalRuntime.getRuntimeServers(), RuntimeInfoKeys.SERVERS_KEY, result);
184
237
421
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.rpc.Response handle(com.weibo.api.motan.rpc.Request) <variables>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/closable/ShutDownHook.java
ShutDownHook
runHook
class ShutDownHook extends Thread { //Smaller the priority is,earlier the resource is to be closed,default Priority is 20 private static final int DEFAULT_PRIORITY = 20; //only global resource should be register to ShutDownHook,don't register connections to it. private static ShutDownHook instance; private ArrayList<closableObject> resourceList = new ArrayList<closableObject>(); private ShutDownHook() { } private static void init() { if (instance == null) { instance = new ShutDownHook(); LoggerUtil.info("ShutdownHook is initialized"); } } public static void runHook(boolean sync) {<FILL_FUNCTION_BODY>} public static void registerShutdownHook(Closable closable) { registerShutdownHook(closable, DEFAULT_PRIORITY); } public static synchronized void registerShutdownHook(Closable closable, int priority) { if (instance == null) { init(); } instance.resourceList.add(new closableObject(closable, priority)); LoggerUtil.info("add resource " + closable.getClass() + " to list"); } @Override public void run() { closeAll(); } //synchronized method to close all the resources in the list private synchronized void closeAll() { Collections.sort(resourceList); LoggerUtil.info("Start to close global resource due to priority"); for (closableObject resource : resourceList) { try { resource.closable.close(); } catch (Exception e) { LoggerUtil.error("Failed to close " + resource.closable.getClass(), e); } LoggerUtil.info("Success to close " + resource.closable.getClass()); } LoggerUtil.info("Success to close all the resource!"); resourceList.clear(); } private static class closableObject implements Comparable<closableObject> { Closable closable; int priority; public closableObject(Closable closable, int priority) { this.closable = closable; this.priority = priority; } @Override public int compareTo(closableObject o) { if (this.priority > o.priority) { return -1; } else if (this.priority == o.priority) { return 0; } else { return 1; } } } }
if (instance != null) { if (sync) { instance.run(); } else { instance.start(); } }
652
43
695
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/ha/FailfastHaStrategy.java
FailfastHaStrategy
call
class FailfastHaStrategy<T> extends AbstractHaStrategy<T> { @Override public Response call(Request request, LoadBalance<T> loadBalance) {<FILL_FUNCTION_BODY>} }
Referer<T> refer = loadBalance.select(request); if (refer == null) { throw new MotanServiceException(String.format("FailfastHaStrategy No referers for request:%s, load balance:%s", request, loadBalance)); } return refer.call(request);
57
82
139
<methods>public non-sealed void <init>() ,public void setUrl(com.weibo.api.motan.rpc.URL) <variables>protected com.weibo.api.motan.rpc.URL url
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/ha/FailoverHaStrategy.java
FailoverHaStrategy
getTryCount
class FailoverHaStrategy<T> extends AbstractHaStrategy<T> { protected ThreadLocal<List<Referer<T>>> referersHolder = ThreadLocal.withInitial(ArrayList::new); @Override public Response call(Request request, LoadBalance<T> loadBalance) { if (loadBalance.canSelectMulti()) { return callWithMultiReferer(request, loadBalance); } else { return callWithSingleReferer(request, loadBalance); } } protected Response callWithSingleReferer(Request request, LoadBalance<T> loadBalance) { int tryCount = getTryCount(request); for (int i = 0; i <= tryCount; i++) { Referer<T> referer = loadBalance.select(request); if (referer == null) { throw new MotanServiceException(String.format("FailoverHaStrategy No referers for request:%s, load balance:%s", request, loadBalance)); } try { request.setRetries(i); return referer.call(request); } catch (RuntimeException e) { // For business exceptions, throw them directly if (ExceptionUtil.isBizException(e)) { throw e; } else if (i >= tryCount) { throw e; } LoggerUtil.warn(String.format("FailoverHaStrategy Call false for request:%s error=%s", request, e.getMessage())); } } throw new MotanFrameworkException("FailoverHaStrategy.call should not come here!"); } // select multi referers at one time protected Response callWithMultiReferer(Request request, LoadBalance<T> loadBalance) { List<Referer<T>> referers = selectReferers(request, loadBalance); if (referers.isEmpty()) { throw new MotanServiceException(String.format("FailoverHaStrategy No referers for request:%s, loadbalance:%s", request, loadBalance)); } int tryCount = getTryCount(request); for (int i = 0; i <= tryCount; i++) { Referer<T> refer = referers.get(i % referers.size()); try { request.setRetries(i); return refer.call(request); } catch (RuntimeException e) { // For business exceptions, throw them directly if (ExceptionUtil.isBizException(e)) { throw e; } else if (i >= tryCount) { throw e; } LoggerUtil.warn(String.format("FailoverHaStrategy Call false for request:%s error=%s", request, e.getMessage())); } } throw new MotanFrameworkException("FailoverHaStrategy.call should not come here!"); } protected int getTryCount(Request request) {<FILL_FUNCTION_BODY>} protected List<Referer<T>> selectReferers(Request request, LoadBalance<T> loadBalance) { List<Referer<T>> referers = referersHolder.get(); referers.clear(); loadBalance.selectToHolder(request, referers); return referers; } }
int tryCount = url.getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.retries.getName(), URLParamType.retries.getIntValue()); // If it is a negative number, not retry if (tryCount < 0) { tryCount = 0; } return tryCount;
816
91
907
<methods>public non-sealed void <init>() ,public void setUrl(com.weibo.api.motan.rpc.URL) <variables>protected com.weibo.api.motan.rpc.URL url
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/AbstractLoadBalance.java
AbstractLoadBalance
selectFromRandomStart
class AbstractLoadBalance<T> implements LoadBalance<T> { public static final int MAX_REFERER_COUNT = 10; protected URL clusterUrl; private List<Referer<T>> referers; @Override public void init(URL clusterUrl) { this.clusterUrl = clusterUrl; } @Override public void onRefresh(List<Referer<T>> referers) { onRefresh(referers, true); } protected void onRefresh(List<Referer<T>> referers, boolean shuffle) { if (shuffle) { Collections.shuffle(referers); } // replaced only this.referers = referers; } @Override public Referer<T> select(Request request) { List<Referer<T>> referers = this.referers; if (referers == null) { throw new MotanServiceException(this.getClass().getSimpleName() + " No available referers for call request:" + request); } Referer<T> ref = null; if (referers.size() > 1) { ref = doSelect(request); } else if (referers.size() == 1) { ref = referers.get(0).isAvailable() ? referers.get(0) : null; } if (ref != null) { return ref; } throw new MotanServiceException(this.getClass().getSimpleName() + " No available referers for call request:" + request); } @Override public void selectToHolder(Request request, List<Referer<T>> refersHolder) { List<Referer<T>> referers = this.referers; if (referers == null) { throw new MotanServiceException(this.getClass().getSimpleName() + " No available referers for call : referers_size= 0 " + MotanFrameworkUtil.toString(request)); } if (referers.size() > 1) { doSelectToHolder(request, refersHolder); } else if (referers.size() == 1 && referers.get(0).isAvailable()) { refersHolder.add(referers.get(0)); } if (refersHolder.isEmpty()) { throw new MotanServiceException(this.getClass().getSimpleName() + " No available referers for call : referers_size=" + referers.size() + " " + MotanFrameworkUtil.toString(request)); } } protected List<Referer<T>> getReferers() { return referers; } protected Referer<T> selectFromRandomStart(List<Referer<T>> referers) {<FILL_FUNCTION_BODY>} protected void addToSelectHolderFromStart(List<Referer<T>> referers, List<Referer<T>> refersHolder, int start) { for (int i = 0, count = 0; i < referers.size() && count < MAX_REFERER_COUNT; i++) { Referer<T> referer = referers.get((i + start) % referers.size()); if (referer.isAvailable()) { refersHolder.add(referer); count++; } } } @Override public void setWeightString(String weightString) { LoggerUtil.info("ignore weightString:" + weightString); } protected abstract Referer<T> doSelect(Request request); protected abstract void doSelectToHolder(Request request, List<Referer<T>> refersHolder); }
int index = ThreadLocalRandom.current().nextInt(referers.size()); Referer<T> ref; for (int i = 0; i < referers.size(); i++) { ref = referers.get((i + index) % referers.size()); if (ref.isAvailable()) { return ref; } } return null;
926
97
1,023
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/ActiveWeightLoadBalance.java
ActiveWeightLoadBalance
doSelect
class ActiveWeightLoadBalance<T> extends AbstractLoadBalance<T> { @Override protected Referer<T> doSelect(Request request) {<FILL_FUNCTION_BODY>} @Override protected void doSelectToHolder(Request request, List<Referer<T>> refersHolder) { List<Referer<T>> referers = getReferers(); int refererSize = referers.size(); int startIndex = ThreadLocalRandom.current().nextInt(refererSize); int currentCursor = 0; int currentAvailableCursor = 0; while (currentAvailableCursor < MAX_REFERER_COUNT && currentCursor < refererSize) { Referer<T> temp = referers.get((startIndex + currentCursor) % refererSize); currentCursor++; if (!temp.isAvailable()) { continue; } currentAvailableCursor++; refersHolder.add(temp); } Collections.sort(refersHolder, new LowActivePriorityComparator<T>()); } private int compare(Referer<T> referer1, Referer<T> referer2) { return referer1.activeRefererCount() - referer2.activeRefererCount(); } static class LowActivePriorityComparator<T> implements Comparator<Referer<T>> { @Override public int compare(Referer<T> referer1, Referer<T> referer2) { return referer1.activeRefererCount() - referer2.activeRefererCount(); } } }
List<Referer<T>> referers = getReferers(); int refererSize = referers.size(); int startIndex = ThreadLocalRandom.current().nextInt(refererSize); int currentCursor = 0; int currentAvailableCursor = 0; Referer<T> referer = null; while (currentAvailableCursor < MAX_REFERER_COUNT && currentCursor < refererSize) { Referer<T> temp = referers.get((startIndex + currentCursor) % refererSize); currentCursor++; if (!temp.isAvailable()) { continue; } currentAvailableCursor++; if (referer == null) { referer = temp; } else { if (compare(referer, temp) > 0) { referer = temp; } } } return referer;
402
225
627
<methods>public non-sealed void <init>() ,public void init(com.weibo.api.motan.rpc.URL) ,public void onRefresh(List<Referer<T>>) ,public Referer<T> select(com.weibo.api.motan.rpc.Request) ,public void selectToHolder(com.weibo.api.motan.rpc.Request, List<Referer<T>>) ,public void setWeightString(java.lang.String) <variables>public static final int MAX_REFERER_COUNT,protected com.weibo.api.motan.rpc.URL clusterUrl,private List<Referer<T>> referers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/ConsistentHashLoadBalance.java
ConsistentHashLoadBalance
doSelect
class ConsistentHashLoadBalance<T> extends AbstractLoadBalance<T> { private List<Referer<T>> consistentHashReferers; @Override public void onRefresh(List<Referer<T>> referers) { super.onRefresh(referers); List<Referer<T>> copyReferers = new ArrayList<Referer<T>>(referers); List<Referer<T>> tempRefers = new ArrayList<Referer<T>>(); for (int i = 0; i < MotanConstants.DEFAULT_CONSISTENT_HASH_BASE_LOOP; i++) { Collections.shuffle(copyReferers); for (Referer<T> ref : copyReferers) { tempRefers.add(ref); } } consistentHashReferers = tempRefers; } @Override protected Referer<T> doSelect(Request request) {<FILL_FUNCTION_BODY>} @Override protected void doSelectToHolder(Request request, List<Referer<T>> refersHolder) { List<Referer<T>> referers = getReferers(); int hash = getHash(request); for (int i = 0; i < referers.size(); i++) { Referer<T> ref = consistentHashReferers.get((hash + i) % consistentHashReferers.size()); if (ref.isAvailable()) { refersHolder.add(ref); } } } private int getHash(Request request) { int hashcode; if (request.getArguments() == null || request.getArguments().length == 0) { hashcode = request.hashCode(); } else { hashcode = Arrays.hashCode(request.getArguments()); } return MathUtil.getNonNegative(hashcode); } }
int hash = getHash(request); Referer<T> ref; for (int i = 0; i < getReferers().size(); i++) { ref = consistentHashReferers.get((hash + i) % consistentHashReferers.size()); if (ref.isAvailable()) { return ref; } } return null;
480
96
576
<methods>public non-sealed void <init>() ,public void init(com.weibo.api.motan.rpc.URL) ,public void onRefresh(List<Referer<T>>) ,public Referer<T> select(com.weibo.api.motan.rpc.Request) ,public void selectToHolder(com.weibo.api.motan.rpc.Request, List<Referer<T>>) ,public void setWeightString(java.lang.String) <variables>public static final int MAX_REFERER_COUNT,protected com.weibo.api.motan.rpc.URL clusterUrl,private List<Referer<T>> referers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/GroupWeightLoadBalanceWrapper.java
MultiGroupSelector
reBuildInnerSelector
class MultiGroupSelector<T> implements Selector<T> { private final URL clusterUrl; private final String loadBalanceName; private List<Referer<T>> referers; private String weightString; private volatile InnerSelector<T> innerSelector; public MultiGroupSelector(URL clusterUrl, List<Referer<T>> referers, String loadBalanceName, String weightString) { this.referers = referers; this.clusterUrl = clusterUrl; this.loadBalanceName = loadBalanceName; this.weightString = weightString; reBuildInnerSelector(); } @Override public Referer<T> select(Request request) { if (innerSelector == null) { return null; } return innerSelector.select(request); } public synchronized void refresh(List<Referer<T>> referers, String weightString) { this.referers = referers; if (this.weightString.equals(weightString)) { // When weightString does not change, refresh each LB in innerSelector. Map<String, List<Referer<T>>> groupReferers = getGroupReferers(referers); for (String groupName : groupReferers.keySet()) { LoadBalance<T> loadBalance = innerSelector.lbMap.get(groupName); if (loadBalance != null) { loadBalance.onRefresh(groupReferers.get(groupName)); } else { LoggerUtil.warn("GroupWeightLoadBalance groupName:{} not exist in innerSelector.lbMap", groupName); } } } else { this.weightString = weightString; reBuildInnerSelector(); } } // depend on referers and weightString private void reBuildInnerSelector() {<FILL_FUNCTION_BODY>} private LoadBalance<T> reuseOrCreateLB(String group, List<Referer<T>> groupReferers) { LoadBalance<T> loadBalance = null; if (innerSelector != null) { // Reuse LB by group name loadBalance = innerSelector.lbMap.remove(group); } if (loadBalance == null) { // create new LB loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadBalanceName); loadBalance.init(clusterUrl); } loadBalance.onRefresh(groupReferers); // Referers in the same group can refresh first return loadBalance; } private Map<String, List<Referer<T>>> getGroupReferers(List<Referer<T>> referers) { Map<String, List<Referer<T>>> result = new HashMap<>(); for (Referer<T> referer : referers) { result.computeIfAbsent(referer.getUrl().getGroup(), k -> new ArrayList<>()).add(referer); } return result; } @Override public void destroy() { referers = null; if (innerSelector != null) { innerSelector.destroy(); innerSelector = null; } } }
Map<String, List<Referer<T>>> groupReferers = getGroupReferers(referers); // CommandServiceManager ensures that there will be no duplicate groups in the weightString // and no abnormal weight value. // If it occurs, just throw an exception String[] groupsAndWeights = weightString.split(","); if (groupsAndWeights.length > 256) { throw new MotanFrameworkException("the group in weightString is greater than 256"); } int[] weightsArr = new int[groupsAndWeights.length]; LoadBalance<T>[] lbArray = new LoadBalance[groupsAndWeights.length]; ConcurrentHashMap<String, LoadBalance<T>> lbMap = new ConcurrentHashMap<>(); int totalWeight = 0; for (int i = 0; i < groupsAndWeights.length; i++) { String[] gw = groupsAndWeights[i].split(":"); weightsArr[i] = Integer.parseInt(gw[1]); totalWeight += weightsArr[i]; lbArray[i] = reuseOrCreateLB(gw[0], groupReferers.get(gw[0])); lbMap.put(gw[0], lbArray[i]); } // divide the weight by the gcd of all weights int weightGcd = MathUtil.findGCD(weightsArr); if (weightGcd > 1) { totalWeight = 0; for (int i = 0; i < weightsArr.length; i++) { weightsArr[i] = weightsArr[i] / weightGcd; totalWeight += weightsArr[i]; } } // build weight ring byte[] groupWeightRing = new byte[totalWeight]; int index = 0; for (int i = 0; i < weightsArr.length; i++) { for (int j = 0; j < weightsArr[i]; j++) { groupWeightRing[index++] = (byte) i; } } CollectionUtil.shuffleByteArray(groupWeightRing); ConcurrentHashMap<String, LoadBalance<T>> remain = innerSelector == null ? null : innerSelector.lbMap; innerSelector = new InnerSelector<>(lbMap, groupWeightRing, lbArray); // Destroy the remaining LB if (remain != null) { for (LoadBalance<T> lb : remain.values()) { try { lb.destroy(); } catch (Exception e) { LoggerUtil.warn("GroupWeightLoadBalance destroy lb fail. url:" + clusterUrl.toSimpleString() + " error: " + e.getMessage()); } } }
813
707
1,520
<methods>public non-sealed void <init>() ,public void init(com.weibo.api.motan.rpc.URL) ,public void onRefresh(List<Referer<T>>) ,public Referer<T> select(com.weibo.api.motan.rpc.Request) ,public void selectToHolder(com.weibo.api.motan.rpc.Request, List<Referer<T>>) ,public void setWeightString(java.lang.String) <variables>public static final int MAX_REFERER_COUNT,protected com.weibo.api.motan.rpc.URL clusterUrl,private List<Referer<T>> referers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/LocalFirstLoadBalance.java
LocalFirstLoadBalance
doSelectToHolder
class LocalFirstLoadBalance<T> extends AbstractLoadBalance<T> { public static final int MAX_REFERER_COUNT = 10; public static long ipToLong(final String addr) { final String[] addressBytes = addr.split("\\."); int length = addressBytes.length; if (length < 3) { return 0; } long ip = 0; try { for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } } catch (Exception e) { LoggerUtil.warn("Warn ipToInt addr is wrong: addr=" + addr); } return ip; } @Override protected Referer<T> doSelect(Request request) { List<Referer<T>> referers = getReferers(); List<Referer<T>> localReferers = searchLocalReferer(referers, NetUtils.getLocalAddress().getHostAddress()); if (!localReferers.isEmpty()) { referers = localReferers; } int refererSize = referers.size(); Referer<T> referer = null; for (int i = 0; i < refererSize; i++) { Referer<T> temp = referers.get(i % refererSize); if (!temp.isAvailable()) { continue; } if (referer == null) { referer = temp; } else { if (compare(referer, temp) > 0) { referer = temp; } } } return referer; } @Override protected void doSelectToHolder(Request request, List<Referer<T>> refersHolder) {<FILL_FUNCTION_BODY>} private List<Referer<T>> searchLocalReferer(List<Referer<T>> referers, String localhost) { List<Referer<T>> localReferers = new ArrayList<Referer<T>>(); long local = ipToLong(localhost); for (Referer<T> referer : referers) { long tmp = ipToLong(referer.getUrl().getHost()); if (local != 0 && local == tmp) { if (referer.isAvailable()) { localReferers.add(referer); } } } return localReferers; } private int compare(Referer<T> referer1, Referer<T> referer2) { return referer1.activeRefererCount() - referer2.activeRefererCount(); } static class LowActivePriorityComparator<T> implements Comparator<Referer<T>> { @Override public int compare(Referer<T> referer1, Referer<T> referer2) { return referer1.activeRefererCount() - referer2.activeRefererCount(); } } }
List<Referer<T>> referers = getReferers(); List<Referer<T>> localReferers = searchLocalReferer(referers, NetUtils.getLocalAddress().getHostAddress()); if (!localReferers.isEmpty()) { Collections.sort(localReferers, new LowActivePriorityComparator<T>()); refersHolder.addAll(localReferers); } int refererSize = referers.size(); int startIndex = ThreadLocalRandom.current().nextInt(refererSize); int currentCursor = 0; int currentAvailableCursor = 0; List<Referer<T>> remoteReferers = new ArrayList<Referer<T>>(); while (currentAvailableCursor < MAX_REFERER_COUNT && currentCursor < refererSize) { Referer<T> temp = referers.get((startIndex + currentCursor) % refererSize); currentCursor++; if (!temp.isAvailable() || localReferers.contains(temp)) { continue; } currentAvailableCursor++; remoteReferers.add(temp); } Collections.sort(remoteReferers, new LowActivePriorityComparator<T>()); refersHolder.addAll(remoteReferers);
765
323
1,088
<methods>public non-sealed void <init>() ,public void init(com.weibo.api.motan.rpc.URL) ,public void onRefresh(List<Referer<T>>) ,public Referer<T> select(com.weibo.api.motan.rpc.Request) ,public void selectToHolder(com.weibo.api.motan.rpc.Request, List<Referer<T>>) ,public void setWeightString(java.lang.String) <variables>public static final int MAX_REFERER_COUNT,protected com.weibo.api.motan.rpc.URL clusterUrl,private List<Referer<T>> referers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/loadbalance/RoundRobinLoadBalance.java
RoundRobinLoadBalance
doSelect
class RoundRobinLoadBalance<T> extends AbstractLoadBalance<T> { private final AtomicInteger idx = new AtomicInteger(0); @Override protected Referer<T> doSelect(Request request) {<FILL_FUNCTION_BODY>} @Override protected void doSelectToHolder(Request request, List<Referer<T>> refersHolder) { addToSelectHolderFromStart(getReferers(), refersHolder, getNextNonNegative()); } // get non-negative int private int getNextNonNegative() { return MathUtil.getNonNegative(idx.incrementAndGet()); } @Override public boolean canSelectMulti() { return false; //Obtaining multiple referers may cause uneven requests } }
List<Referer<T>> referers = getReferers(); Referer<T> ref = referers.get(getNextNonNegative() % referers.size()); if (ref.isAvailable()) { return ref; } return selectFromRandomStart(referers);
198
76
274
<methods>public non-sealed void <init>() ,public void init(com.weibo.api.motan.rpc.URL) ,public void onRefresh(List<Referer<T>>) ,public Referer<T> select(com.weibo.api.motan.rpc.Request) ,public void selectToHolder(com.weibo.api.motan.rpc.Request, List<Referer<T>>) ,public void setWeightString(java.lang.String) <variables>public static final int MAX_REFERER_COUNT,protected com.weibo.api.motan.rpc.URL clusterUrl,private List<Referer<T>> referers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/cluster/support/ClusterSpi.java
ClusterSpi
removeCommonInfos
class ClusterSpi<T> implements Cluster<T> { private HaStrategy<T> haStrategy; private LoadBalance<T> loadBalance; private List<Referer<T>> referers; private AtomicBoolean available = new AtomicBoolean(false); private URL url; @Override public void init() { available.set(true); } @Override public Class<T> getInterface() { if (referers == null || referers.isEmpty()) { return null; } return referers.get(0).getInterface(); } @Override public Response call(Request request) { if (available.get()) { try { return haStrategy.call(request, loadBalance); } catch (Exception e) { return callFalse(request, e); } } throw new MotanServiceException(String.format("ClusterSpi Call false for request: %s, ClusterSpi not created or destroyed", request), MotanErrorMsgConstant.SERVICE_UNFOUND, false); } @Override public String desc() { return toString(); } @Override public void destroy() { available.set(false); loadBalance.destroy(); for (Referer<T> referer : this.referers) { referer.destroy(); } } @Override public URL getUrl() { return url; } @Override public void setUrl(URL url) { this.url = url; } @Override public boolean isAvailable() { return available.get(); } @Override public String toString() { return "cluster: {" + "ha=" + haStrategy + ",loadBalance=" + loadBalance + "referers=" + referers + "}"; } @Override public synchronized void onRefresh(List<Referer<T>> referers) { if (CollectionUtil.isEmpty(referers)) { return; } loadBalance.onRefresh(referers); List<Referer<T>> oldReferers = this.referers; this.referers = referers; haStrategy.setUrl(getUrl()); if (oldReferers == null || oldReferers.isEmpty()) { return; } List<Referer<T>> delayDestroyReferers = new ArrayList<>(); for (Referer<T> referer : oldReferers) { if (referers.contains(referer)) { continue; } delayDestroyReferers.add(referer); } if (!delayDestroyReferers.isEmpty()) { RefererSupports.delayDestroy(delayDestroyReferers); } } public AtomicBoolean getAvailable() { return available; } public void setAvailable(AtomicBoolean available) { this.available = available; } public HaStrategy<T> getHaStrategy() { return haStrategy; } @Override public void setHaStrategy(HaStrategy<T> haStrategy) { this.haStrategy = haStrategy; } @Override public LoadBalance<T> getLoadBalance() { return loadBalance; } @Override public void setLoadBalance(LoadBalance<T> loadBalance) { this.loadBalance = loadBalance; } @Override public List<Referer<T>> getReferers() { return referers; } protected Response callFalse(Request request, Exception cause) { // biz exception 无论如何都要抛出去 if (ExceptionUtil.isBizException(cause)) { throw (RuntimeException) cause; } // 其他异常根据配置决定是否抛,如果抛异常,需要统一为MotanException if (Boolean.parseBoolean(getUrl().getParameter(URLParamType.throwException.getName(), URLParamType.throwException.getValue()))) { if (cause instanceof MotanAbstractException) { throw (MotanAbstractException) cause; } else { throw new MotanServiceException(String.format("ClusterSpi Call false for request: %s", request), cause); } } return MotanFrameworkUtil.buildErrorResponse(request, cause); } @Override public Map<String, Object> getRuntimeInfo() { Map<String, Object> infos = new HashMap<>(); infos.put(RuntimeInfoKeys.URL_KEY, url.toFullStr()); infos.put(RuntimeInfoKeys.REFERER_SIZE_KEY, referers == null ? 0 : referers.size()); if (!CollectionUtil.isEmpty(referers)) { // common infos addCommonInfos(referers.get(0), infos, RuntimeInfoKeys.CODEC_KEY, RuntimeInfoKeys.FUSING_THRESHOLD_KEY); // available referers Map<String, Object> availableInfos = new HashMap<>(); Map<String, Object> unavailableInfos = new HashMap<>(); int i = 0; for (Referer<?> referer : referers) { if (referer.isAvailable()) { availableInfos.put(i + "-" + referer.getUrl().toTinyString(), removeCommonInfos(referer, RuntimeInfoKeys.CODEC_KEY, RuntimeInfoKeys.FUSING_THRESHOLD_KEY)); } else { unavailableInfos.put(i + "-" + referer.getUrl().toTinyString(), removeCommonInfos(referer, RuntimeInfoKeys.CODEC_KEY, RuntimeInfoKeys.FUSING_THRESHOLD_KEY)); } i++; } Map<String, Object> refererInfos = new HashMap<>(); refererInfos.put(RuntimeInfoKeys.AVAILABLE_KEY, availableInfos); refererInfos.put(RuntimeInfoKeys.UNAVAILABLE_KEY, unavailableInfos); infos.put(RuntimeInfoKeys.REFERERS_KEY, refererInfos); } return infos; } private Map<String, Object> removeCommonInfos(Referer<?> referer, String... keys) {<FILL_FUNCTION_BODY>} private void addCommonInfos(Referer<?> referer, Map<String, Object> infos, String... keys) { Map<String, Object> refererInfos = referer.getRuntimeInfo(); if (!CollectionUtil.isEmpty(refererInfos)) { for (String key : keys) { if (refererInfos.get(key) != null) { infos.put(key, refererInfos.get(key)); } } } } }
Map<String, Object> refererInfos = referer.getRuntimeInfo(); if (!CollectionUtil.isEmpty(refererInfos)) { for (String key : keys) { refererInfos.remove(key); } } return refererInfos;
1,761
73
1,834
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/codec/AbstractCodec.java
AbstractCodec
initAllSerialization
class AbstractCodec implements Codec { protected static ConcurrentHashMap<Integer, String> serializations; protected void serialize(ObjectOutput output, Object message, Serialization serialize) throws IOException { if (message == null) { output.writeObject(null); return; } output.writeObject(serialize.serialize(message)); } protected Object deserialize(byte[] value, Class<?> type, Serialization serialize) throws IOException { if (value == null) { return null; } return serialize.deserialize(value, type); } public ObjectOutput createOutput(OutputStream outputStream) { try { return new ObjectOutputStream(outputStream); } catch (Exception e) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " createOutput error", e, MotanErrorMsgConstant.FRAMEWORK_ENCODE_ERROR); } } public ObjectInput createInput(InputStream in) { try { return new ObjectInputStream(in); } catch (Exception e) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " createInput error", e, MotanErrorMsgConstant.FRAMEWORK_DECODE_ERROR); } } protected static synchronized void initAllSerialization() {<FILL_FUNCTION_BODY>} protected Serialization getSerializationByNum(int serializationNum) { if (serializations == null) { initAllSerialization(); } String name = serializations.get(serializationNum); Serialization s = null; if (StringUtils.isNotBlank(name)) { s = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name, false); } if (s == null) { throw new MotanServiceException("can not found serialization by number " + serializationNum + ", name: " + name); } return s; } }
if (serializations == null) { serializations = new ConcurrentHashMap<Integer, String>(); try { ExtensionLoader<Serialization> loader = ExtensionLoader.getExtensionLoader(Serialization.class); List<Serialization> exts = loader.getExtensions(null); for (Serialization s : exts) { String old = serializations.put(s.getSerializationNumber(), loader.getSpiName(s.getClass())); if (old != null) { LoggerUtil.warn("conflict serialization spi! serialization num :" + s.getSerializationNumber() + ", old spi :" + old + ", new spi :" + serializations.get(s.getSerializationNumber())); } } } catch (Exception e) { LoggerUtil.warn("init all serialzaion fail!", e); } }
506
222
728
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/AbstractConfig.java
AbstractConfig
isPrimitive
class AbstractConfig implements Serializable { private static final long serialVersionUID = 5736580957909744603L; protected String id; public String getId() { return id; } public void setId(String id) { this.id = id; } /** * 按顺序进行config 参数append and override,按照configs出现的顺序,后面的会覆盖前面的相同名称的参数 * * @param parameters * @param configs */ protected static void collectConfigParams(Map<String, String> parameters, AbstractConfig... configs) { for (AbstractConfig config : configs) { if (config != null) { config.appendConfigParams(parameters); } } } protected static void collectMethodConfigParams(Map<String, String> parameters, List<MethodConfig> methods) { if (methods == null || methods.isEmpty()) { return; } for (MethodConfig mc : methods) { if (mc != null) { mc.appendConfigParams(parameters, MotanConstants.METHOD_CONFIG_PREFIX + mc.getName() + "(" + mc.getArgumentTypes() + ")"); } } } protected void appendConfigParams(Map<String, String> parameters) { appendConfigParams(parameters, null); } /** * 将config 参数录入Map中 * * @param parameters */ @SuppressWarnings("unchecked") protected void appendConfigParams(Map<String, String> parameters, String prefix) { Method[] methods = this.getClass().getMethods(); for (Method method : methods) { try { String name = method.getName(); if (isConfigMethod(method)) { int idx = name.startsWith("get") ? 3 : 2; String key = name.substring(idx, idx + 1).toLowerCase() + name.substring(idx + 1); ConfigDesc configDesc = method.getAnnotation(ConfigDesc.class); if (configDesc != null && !StringUtils.isBlank(configDesc.key())) { key = configDesc.key(); } Object value = method.invoke(this); if (value == null || StringUtils.isBlank(String.valueOf(value))) { if (configDesc != null && configDesc.required()) { throw new MotanFrameworkException(String.format("%s.%s should not be null or empty", this.getClass() .getSimpleName(), key), MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } continue; } if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; } parameters.put(key, String.valueOf(value).trim()); } else if ("getParameters".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getReturnType() == Map.class) { Map<String, String> map = (Map<String, String>) method.invoke(this); if (map != null && map.size() > 0) { String pre = prefix != null && prefix.length() > 0 ? prefix + "." : ""; for (Map.Entry<String, String> entry : map.entrySet()) { parameters.put(pre + entry.getKey(), entry.getValue()); } } } } catch (Exception e) { throw new MotanFrameworkException(String.format("Error when append params for config: %s.%s", this.getClass() .getSimpleName(), method.getName()), e, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } } } private boolean isConfigMethod(Method method) { boolean checkMethod = (method.getName().startsWith("get") || method.getName().startsWith("is")) && !"isDefault".equals(method.getName()) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType()); if (checkMethod) { ConfigDesc configDesc = method.getAnnotation(ConfigDesc.class); if (configDesc != null && configDesc.excluded()) { return false; } } return checkMethod; } private boolean isPrimitive(Class<?> type) {<FILL_FUNCTION_BODY>} @Override public String toString() { try { StringBuilder buf = new StringBuilder(); buf.append("<motan:"); buf.append(getTagName(getClass())); Method[] methods = getClass().getMethods(); for (Method method : methods) { try { String name = method.getName(); if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name) && !"get".equals(name) && !"is".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { int i = name.startsWith("get") ? 3 : 2; String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); Object value = method.invoke(this); if (value != null) { buf.append(" "); buf.append(key); buf.append("=\""); buf.append(value); buf.append("\""); } } } catch (Exception e) { LoggerUtil.warn(e.getMessage(), e); } } buf.append(" />"); return buf.toString(); } catch (Throwable t) { // 防御性容错 LoggerUtil.warn(t.getMessage(), t); return super.toString(); } } private static final String[] SUFFIXS = new String[] {"Config", "Bean"}; private static String getTagName(Class<?> cls) { String tag = cls.getSimpleName(); for (String suffix : SUFFIXS) { if (tag.endsWith(suffix)) { tag = tag.substring(0, tag.length() - suffix.length()); break; } } tag = tag.toLowerCase(); return tag; } }
return type.isPrimitive() || type == String.class || type == Character.class || type == Boolean.class || type == Byte.class || type == Short.class || type == Integer.class || type == Long.class || type == Float.class || type == Double.class;
1,667
70
1,737
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/ConfigUtil.java
ConfigUtil
parseExport
class ConfigUtil { /** * export fomart: protocol1:port1,protocol2:port2 * * @param export * @return */ @SuppressWarnings("unchecked") public static Map<String, Integer> parseExport(String export) {<FILL_FUNCTION_BODY>} public static String extractProtocols(String export) { Map<String, Integer> protocols = parseExport(export); StringBuilder sb = new StringBuilder(16); for (String p : protocols.keySet()) { sb.append(p).append(MotanConstants.COMMA_SEPARATOR); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } }
if (StringUtils.isBlank(export)) { return Collections.emptyMap(); } Map<String, Integer> pps = new HashMap<String, Integer>(); String[] protocolAndPorts = MotanConstants.COMMA_SPLIT_PATTERN.split(export); for (String pp : protocolAndPorts) { if (StringUtils.isBlank(pp)) { continue; } String[] ppDetail = pp.split(":"); if (ppDetail.length == 2) { pps.put(ppDetail[0], Integer.parseInt(ppDetail[1])); } else if (ppDetail.length == 1) { if (MotanConstants.PROTOCOL_INJVM.equals(ppDetail[0])) { pps.put(ppDetail[0], MotanConstants.DEFAULT_INT_VALUE); } else { int port = MathUtil.parseInt(ppDetail[0], 0); if (port <= 0) { throw new MotanServiceException("Export is malformed :" + export); } else { pps.put(MotanConstants.PROTOCOL_MOTAN, port); } } } else { throw new MotanServiceException("Export is malformed :" + export); } } return pps;
211
338
549
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/DefaultGlobalConfig.java
DefaultGlobalConfig
putConfigs
class DefaultGlobalConfig implements GlobalConfig { private final ConcurrentHashMap<String, String> configs = new ConcurrentHashMap<>(); public DefaultGlobalConfig() { Map<String, String> defaultConfigs = MotanGlobalConfigUtil.getDefaultConfigCopy(); if (!defaultConfigs.isEmpty()) { putConfigs(defaultConfigs, false); } } @Override public String getConfig(String key) { return configs.get(key); } @Override public String getConfig(String key, String defaultValue) { String value = configs.get(key); return value == null ? defaultValue : value; } @Override public void putConfig(String key, String value) { configs.put(key, value); } @Override public String remove(String key) { return configs.remove(key); } @Override public void putConfigs(Map<String, String> configs, boolean override) {<FILL_FUNCTION_BODY>} @Override public ConcurrentHashMap<String, String> getConfigs() { return configs; } }
if (configs != null && !configs.isEmpty()) { for (Map.Entry<String, String> entry : configs.entrySet()) { if (override) { this.configs.put(entry.getKey(), entry.getValue()); } else { this.configs.putIfAbsent(entry.getKey(), entry.getValue()); } } }
301
102
403
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/MeshClientConfig.java
MeshClientConfig
initMeshClient
class MeshClientConfig extends AbstractConfig { // ---------- configuration items ------------ // mesh proxy port protected Integer port; // mesh management port protected Integer mport; // mesh host ip protected String host; // default application for all services protected String application; protected Integer minClientConnection; protected Integer maxClientConnection; protected String serialization; protected Integer connectTimeout; protected Integer requestTimeout; // the maximum length limit of the request or response packet protected Integer maxContentLength; // the filters decorated on the mesh client protected String filter; protected String accessLog; // min gzip size protected Integer mingzSize; // specify the endpoint used, such as using unix socket protected String endpointFactory; // specify motan protocol codec (such as 'motan' using the motan1 protocol) protected String codec; protected String check; protected Boolean asyncInitConnection; protected Integer fusingThreshold; // ---------- internal variable ------------ protected MeshClient meshClient; protected URL url; protected AtomicBoolean initialized = new AtomicBoolean(false); public MeshClient getMeshClient() { if (meshClient == null) { initMeshClient(); } return meshClient; } protected synchronized void initMeshClient() {<FILL_FUNCTION_BODY>} protected synchronized void destroy() throws Exception { if (meshClient != null) { GlobalRuntime.removeMeshClient(meshClient.getUrl().getIdentity()); meshClient.destroy(); meshClient = null; } initialized.set(false); } private void buildMeshClientUrl() { Map<String, String> params = DefaultMeshClient.getDefaultParams(); appendConfigParams(params); url = new URL(params.get(URLParamType.protocol.getName()), host == null ? MotanConstants.MESH_DEFAULT_HOST : host, port == null ? MotanConstants.MESH_DEFAULT_PORT : port, MeshClient.class.getName(), params); } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public Integer getMport() { return mport; } public void setMport(Integer mport) { this.mport = mport; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } public Integer getMinClientConnection() { return minClientConnection; } public void setMinClientConnection(Integer minClientConnection) { this.minClientConnection = minClientConnection; } public Integer getMaxClientConnection() { return maxClientConnection; } public void setMaxClientConnection(Integer maxClientConnection) { this.maxClientConnection = maxClientConnection; } public String getSerialization() { return serialization; } public void setSerialization(String serialization) { this.serialization = serialization; } public Integer getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public Integer getRequestTimeout() { return requestTimeout; } public void setRequestTimeout(Integer requestTimeout) { this.requestTimeout = requestTimeout; } public Integer getMaxContentLength() { return maxContentLength; } public void setMaxContentLength(Integer maxContentLength) { this.maxContentLength = maxContentLength; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public String getAccessLog() { return accessLog; } public void setAccessLog(String accessLog) { this.accessLog = accessLog; } public Integer getMingzSize() { return mingzSize; } public void setMingzSize(Integer mingzSize) { this.mingzSize = mingzSize; } public String getEndpointFactory() { return endpointFactory; } public void setEndpointFactory(String endpointFactory) { this.endpointFactory = endpointFactory; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } public String getCheck() { return check; } public void setCheck(String check) { this.check = check; } public Boolean getAsyncInitConnection() { return asyncInitConnection; } public void setAsyncInitConnection(Boolean asyncInitConnection) { this.asyncInitConnection = asyncInitConnection; } public Integer getFusingThreshold() { return fusingThreshold; } public void setFusingThreshold(Integer fusingThreshold) { this.fusingThreshold = fusingThreshold; } }
if (initialized.get()) { return; } buildMeshClientUrl(); DefaultMeshClient defaultMeshClient = new DefaultMeshClient(url); try { defaultMeshClient.init(); } catch (Exception e) { LoggerUtil.error("mesh client init fail. url:" + url.toFullStr(), e); boolean check = Boolean.parseBoolean(url.getParameter(URLParamType.check.getName(), URLParamType.check.getValue())); if (check) { throw e; } } meshClient = defaultMeshClient; GlobalRuntime.addMeshClient(meshClient.getUrl().getIdentity(), meshClient); initialized.set(true);
1,378
184
1,562
<methods>public non-sealed void <init>() ,public java.lang.String getId() ,public void setId(java.lang.String) ,public java.lang.String toString() <variables>private static final java.lang.String[] SUFFIXS,protected java.lang.String id,private static final long serialVersionUID
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/RegistryConfig.java
RegistryConfig
toURLs
class RegistryConfig extends AbstractConfig { private static final long serialVersionUID = 3236055928361714933L; // 注册配置名称 private String name; // 注册协议 private String regProtocol; // 注册中心地址,支持多个ip+port,格式:ip1:port1,ip2:port2,ip3,如果没有port,则使用默认的port private String address; // 注册中心缺省端口 private Integer port; // 注册中心请求超时时间(毫秒) private Integer requestTimeout; // 注册中心连接超时时间(毫秒) private Integer connectTimeout; // 注册中心会话超时时间(毫秒) private Integer registrySessionTimeout; // 失败后重试的时间间隔 private Integer registryRetryPeriod; // 启动时检查注册中心是否存在 private String check; // 在该注册中心上服务是否暴露 private Boolean register; // 在该注册中心上服务是否引用 private Boolean subscribe; private Boolean isDefault; // vintage的配置移除策略,@see #RegistryConfig#Excise private String excise; // 被代理的registry。 private RegistryConfig proxyRegistry; // 在mesh中要使用的registry。用来和mesh 配置中的registry进行关联 private String meshRegistryName; private Boolean dynamic; //是否支持动态注册、订阅能力。例如通过mesh代理的注册中心,是否支持动态注册、订阅服务。 @ConfigDesc(key = "protocol") public String getRegProtocol() { return regProtocol; } public void setRegProtocol(String regProtocol) { this.regProtocol = regProtocol; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getCheck() { return check; } public void setCheck(String check) { this.check = check; } @Deprecated public void setCheck(Boolean check) { this.check = String.valueOf(check); } public Boolean getRegister() { return register; } public void setRegister(Boolean register) { this.register = register; } public Boolean getSubscribe() { return subscribe; } public void setSubscribe(Boolean subscribe) { this.subscribe = subscribe; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRequestTimeout() { return requestTimeout; } public void setRequestTimeout(Integer requestTimeout) { this.requestTimeout = requestTimeout; } public Integer getRegistrySessionTimeout() { return registrySessionTimeout; } public void setRegistrySessionTimeout(Integer registrySessionTimeout) { this.registrySessionTimeout = registrySessionTimeout; } public Integer getRegistryRetryPeriod() { return registryRetryPeriod; } public void setRegistryRetryPeriod(Integer registryRetryPeriod) { this.registryRetryPeriod = registryRetryPeriod; } public String getExcise() { return excise; } public void setExcise(String excise) { this.excise = excise; } public void setDefault(boolean isDefault) { this.isDefault = isDefault; } public Boolean isDefault() { return isDefault; } public Integer getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public RegistryConfig getProxyRegistry() { return proxyRegistry; } public void setProxyRegistry(RegistryConfig proxyRegistry) { this.proxyRegistry = proxyRegistry; } public String getMeshRegistryName() { return meshRegistryName; } public void setMeshRegistryName(String meshRegistryName) { this.meshRegistryName = meshRegistryName; } public Boolean getDynamic() { return dynamic; } public void setDynamic(Boolean dynamic) { this.dynamic = dynamic; } /** * <pre> * vintage 的 excise 方式,static、dynamic、ratio; * static表示使用静态列表,不剔除unreachable的node;dynamic完全剔除;ratio按比例提出。 * 配置方式,ratio直接使用数字,其他使用数字0-100. * </pre> * * @author fishermen */ public enum Excise { excise_static("static"), excise_dynamic("dynamic"), excise_ratio("ratio"); private String name; Excise(String n) { this.name = n; } public String getName() { return name; } } public List<URL> toURLs() {<FILL_FUNCTION_BODY>} public Map<String, String> getAddressParams() { if (StringUtils.isNotBlank(address)) { int index = address.indexOf("?"); if (index > -1) { int end = address.length(); if (address.contains(MotanConstants.COMMA_SEPARATOR)) { end = address.indexOf(MotanConstants.COMMA_SEPARATOR); } return UrlUtils.parseQueryParams(address.substring(index + 1, end)); } } return Collections.emptyMap(); } }
String address = getAddress(); if (StringUtils.isBlank(address)) { address = NetUtils.LOCALHOST + ":" + MotanConstants.DEFAULT_INT_VALUE; } Map<String, String> map = new HashMap<>(); map.putAll(getAddressParams()); appendConfigParams(map); map.put(URLParamType.path.getName(), RegistryService.class.getName()); map.put(URLParamType.refreshTimestamp.getName(), String.valueOf(System.currentTimeMillis())); // 设置默认的registry protocol,parse完protocol后,需要去掉该参数 if (!map.containsKey(URLParamType.protocol.getName())) { if (address.contains("://")) { map.put(URLParamType.protocol.getName(), address.substring(0, address.indexOf("://"))); } else { map.put(URLParamType.protocol.getName(), MotanConstants.REGISTRY_PROTOCOL_LOCAL); } } if (proxyRegistry != null) { String proxyRegistryString = UrlUtils.urlsToString(proxyRegistry.toURLs()); if (StringUtils.isNotBlank(proxyRegistryString)) { map.put(URLParamType.proxyRegistryUrlString.getName(), proxyRegistryString); } else { LoggerUtil.warn("parse proxyRegistryString is empty, proxy registry:" + proxyRegistry.getName()); } } // address内部可能包含多个注册中心地址 return UrlUtils.parseURLs(address, map);
1,525
391
1,916
<methods>public non-sealed void <init>() ,public java.lang.String getId() ,public void setId(java.lang.String) ,public java.lang.String toString() <variables>private static final java.lang.String[] SUFFIXS,protected java.lang.String id,private static final long serialVersionUID
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/config/handler/SimpleConfigHandler.java
SimpleConfigHandler
buildClusterSupport
class SimpleConfigHandler implements ConfigHandler { @Override public <T> ClusterSupport<T> buildClusterSupport(Class<T> interfaceClass, List<URL> registryUrls, URL refUrl) {<FILL_FUNCTION_BODY>} @Override public <T> T refer(Class<T> interfaceClass, List<Cluster<T>> clusters, String proxyType) { ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension(proxyType); return proxyFactory.getProxy(interfaceClass, clusters); } @Override public <T> Exporter<T> export(Class<T> interfaceClass, T ref, List<URL> registryUrls, URL serviceUrl) { // export service // 利用protocol decorator来增加filter特性 String protocolName = serviceUrl.getParameter(URLParamType.protocol.getName(), URLParamType.protocol.getValue()); Protocol orgProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocolName); Provider<T> provider = getProvider(orgProtocol, ref, serviceUrl, interfaceClass); Protocol protocol = new ProtocolFilterDecorator(orgProtocol); Exporter<T> exporter = protocol.export(provider, serviceUrl); // register service register(MeshProxyUtil.processMeshProxy(registryUrls, serviceUrl, true), serviceUrl); return exporter; } protected <T> Provider<T> getProvider(Protocol protocol, T proxyImpl, URL url, Class<T> clz) { if (protocol instanceof ProviderFactory) { return ((ProviderFactory) protocol).newProvider(proxyImpl, url, clz); } else { return new DefaultProvider<T>(proxyImpl, url, clz); } } @Override public <T> void unexport(List<Exporter<T>> exporters, Collection<URL> registryUrls) { for (Exporter<T> exporter : exporters) { try { unRegister(registryUrls, exporter.getUrl()); exporter.unexport(); } catch (Exception e) { LoggerUtil.warn("Exception when unexport exporters:" + exporters); } } } private void register(List<URL> registryUrls, URL serviceUrl) { for (URL url : registryUrls) { // 根据check参数的设置,register失败可能会抛异常,上层应该知晓 RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url.getProtocol(), false); if (registryFactory == null) { throw new MotanFrameworkException(new MotanErrorMsg(500, MotanErrorMsgConstant.FRAMEWORK_REGISTER_ERROR_CODE, "register error! Could not find extension for registry protocol:" + url.getProtocol() + ", make sure registry module for " + url.getProtocol() + " is in classpath!")); } Registry registry = registryFactory.getRegistry(url); registry.register(serviceUrl); } } private void unRegister(Collection<URL> registryUrls, URL serviceUrl) { for (URL url : registryUrls) { // 不管check的设置如何,做完所有unregistry,做好清理工作 try { RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url.getProtocol()); Registry registry = registryFactory.getRegistry(url); registry.unregister(serviceUrl); } catch (Exception e) { LoggerUtil.warn(String.format("unregister url false:%s", url), e); } } } }
ClusterSupport<T> clusterSupport = new ClusterSupport<T>(interfaceClass, MeshProxyUtil.processMeshProxy(registryUrls, refUrl, false), refUrl); clusterSupport.init(); return clusterSupport;
925
62
987
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/core/DefaultThreadFactory.java
DefaultThreadFactory
newThread
class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup threadGroup; private final AtomicInteger currentThreadNumber = new AtomicInteger(1); private final String namePrefix; private int priority = Thread.NORM_PRIORITY; private boolean isDaemon = false; public DefaultThreadFactory() { this(MotanConstants.FRAMEWORK_NAME); } public DefaultThreadFactory(String prefix) { this(prefix, false); } public DefaultThreadFactory(String prefix, boolean isDaemon) { this(prefix, isDaemon, Thread.NORM_PRIORITY); } public DefaultThreadFactory(String prefix, boolean isDaemon, int priority) { SecurityManager s = System.getSecurityManager(); this.threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); this.namePrefix = prefix + "-" + poolNumber.getAndIncrement() + "-thread-"; this.isDaemon = isDaemon; this.priority = priority; } @Override public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>} }
Thread thread = new Thread(threadGroup, r, namePrefix + currentThreadNumber.getAndIncrement(), 0); thread.setDaemon(isDaemon); thread.setPriority(priority); return thread;
322
59
381
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/core/StandardThreadExecutor.java
StandardThreadExecutor
execute
class StandardThreadExecutor extends ThreadPoolExecutor { public static final int DEFAULT_MIN_THREADS = 20; public static final int DEFAULT_MAX_THREADS = 200; public static final int DEFAULT_MAX_IDLE_TIME = 60 * 1000; // 1 minutes protected AtomicInteger submittedTasksCount; // 正在处理的任务数 private int maxSubmittedTaskCount; // 最大允许同时处理的任务数 public StandardThreadExecutor() { this(DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS); } public StandardThreadExecutor(int coreThread, int maxThreads) { this(coreThread, maxThreads, maxThreads); } public StandardThreadExecutor(int coreThread, int maxThreads, long keepAliveTime, TimeUnit unit) { this(coreThread, maxThreads, keepAliveTime, unit, maxThreads); } public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity) { this(coreThreads, maxThreads, queueCapacity, Executors.defaultThreadFactory()); } public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity, ThreadFactory threadFactory) { this(coreThreads, maxThreads, DEFAULT_MAX_IDLE_TIME, TimeUnit.MILLISECONDS, queueCapacity, threadFactory); } public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit, int queueCapacity) { this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, Executors.defaultThreadFactory()); } public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit, int queueCapacity, ThreadFactory threadFactory) { this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, threadFactory, new AbortPolicy()); } public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit, int queueCapacity, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(coreThreads, maxThreads, keepAliveTime, unit, new ExecutorQueue(), threadFactory, handler); ((ExecutorQueue) getQueue()).setStandardThreadExecutor(this); submittedTasksCount = new AtomicInteger(0); // 最大并发任务限制: 队列buffer数 + 最大线程数 maxSubmittedTaskCount = queueCapacity + maxThreads; } public void execute(Runnable command) {<FILL_FUNCTION_BODY>} public int getSubmittedTasksCount() { return this.submittedTasksCount.get(); } public int getMaxSubmittedTaskCount() { return maxSubmittedTaskCount; } protected void afterExecute(Runnable r, Throwable t) { submittedTasksCount.decrementAndGet(); } }
int count = submittedTasksCount.incrementAndGet(); // 超过最大的并发任务限制,进行 reject // 依赖的LinkedTransferQueue没有长度限制,因此这里进行控制 if (count > maxSubmittedTaskCount) { submittedTasksCount.decrementAndGet(); getRejectedExecutionHandler().rejectedExecution(command, this); return; } try { super.execute(command); } catch (RejectedExecutionException rx) { // there could have been contention around the queue if (!((ExecutorQueue) getQueue()).force(command)) { submittedTasksCount.decrementAndGet(); getRejectedExecutionHandler().rejectedExecution(command, this); } }
741
198
939
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void allowCoreThreadTimeOut(boolean) ,public boolean allowsCoreThreadTimeOut() ,public boolean awaitTermination(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public void execute(java.lang.Runnable) ,public int getActiveCount() ,public long getCompletedTaskCount() ,public int getCorePoolSize() ,public long getKeepAliveTime(java.util.concurrent.TimeUnit) ,public int getLargestPoolSize() ,public int getMaximumPoolSize() ,public int getPoolSize() ,public BlockingQueue<java.lang.Runnable> getQueue() ,public java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler() ,public long getTaskCount() ,public java.util.concurrent.ThreadFactory getThreadFactory() ,public boolean isShutdown() ,public boolean isTerminated() ,public boolean isTerminating() ,public int prestartAllCoreThreads() ,public boolean prestartCoreThread() ,public void purge() ,public boolean remove(java.lang.Runnable) ,public void setCorePoolSize(int) ,public void setKeepAliveTime(long, java.util.concurrent.TimeUnit) ,public void setMaximumPoolSize(int) ,public void setRejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setThreadFactory(java.util.concurrent.ThreadFactory) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() ,public java.lang.String toString() <variables>private static final int COUNT_BITS,private static final int COUNT_MASK,private static final boolean ONLY_ONE,private static final int RUNNING,private static final int SHUTDOWN,private static final int STOP,private static final int TERMINATED,private static final int TIDYING,private volatile boolean allowCoreThreadTimeOut,private long completedTaskCount,private volatile int corePoolSize,private final java.util.concurrent.atomic.AtomicInteger ctl,private static final java.util.concurrent.RejectedExecutionHandler defaultHandler,private volatile java.util.concurrent.RejectedExecutionHandler handler,private volatile long keepAliveTime,private int largestPoolSize,private final java.util.concurrent.locks.ReentrantLock mainLock,private volatile int maximumPoolSize,private static final java.lang.RuntimePermission shutdownPerm,private final java.util.concurrent.locks.Condition termination,private volatile java.util.concurrent.ThreadFactory threadFactory,private final BlockingQueue<java.lang.Runnable> workQueue,private final HashSet<java.util.concurrent.ThreadPoolExecutor.Worker> workers
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/core/extension/ActivationComparator.java
ActivationComparator
compare
class ActivationComparator<T> implements Comparator<T> { /** * sequence 大的排在后面,如果没有设置sequence的排到最后面 */ @Override public int compare(T o1, T o2) {<FILL_FUNCTION_BODY>} }
Activation p1 = o1.getClass().getAnnotation(Activation.class); Activation p2 = o2.getClass().getAnnotation(Activation.class); if (p1 == null) { return 1; } else if (p2 == null) { return -1; } else { return p1.sequence() - p2.sequence(); }
79
101
180
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/exception/MotanAbstractException.java
MotanAbstractException
getMessage
class MotanAbstractException extends RuntimeException { private static final long serialVersionUID = -8742311167276890503L; protected MotanErrorMsg motanErrorMsg = MotanErrorMsgConstant.FRAMEWORK_DEFAULT_ERROR; protected String errorMsg = null; public MotanAbstractException() { super(); } public MotanAbstractException(MotanErrorMsg motanErrorMsg) { super(); this.motanErrorMsg = motanErrorMsg; } public MotanAbstractException(String message) { this(message, (MotanErrorMsg) null); } public MotanAbstractException(String message, MotanErrorMsg motanErrorMsg) { super(message); this.motanErrorMsg = motanErrorMsg; this.errorMsg = message; } public MotanAbstractException(String message, MotanErrorMsg motanErrorMsg, boolean writableStackTrace) { this(message, null, motanErrorMsg, writableStackTrace); } public MotanAbstractException(String message, Throwable cause, MotanErrorMsg motanErrorMsg, boolean writableStackTrace) { super(message, cause, false, writableStackTrace); this.motanErrorMsg = motanErrorMsg; this.errorMsg = message; } public MotanAbstractException(String message, Throwable cause) { this(message, cause, null); } public MotanAbstractException(String message, Throwable cause, MotanErrorMsg motanErrorMsg) { super(message, cause); this.motanErrorMsg = motanErrorMsg; this.errorMsg = message; } public MotanAbstractException(Throwable cause) { super(cause); } public MotanAbstractException(Throwable cause, MotanErrorMsg motanErrorMsg) { super(cause); this.motanErrorMsg = motanErrorMsg; } @Override public String getMessage() {<FILL_FUNCTION_BODY>} public String getOriginMessage(){ if (motanErrorMsg == null) { return super.getMessage(); } String message; if (errorMsg != null && !"".equals(errorMsg)) { message = errorMsg; } else { message = motanErrorMsg.getMessage(); } return message; } public int getStatus() { return motanErrorMsg != null ? motanErrorMsg.getStatus() : 0; } public int getErrorCode() { return motanErrorMsg != null ? motanErrorMsg.getErrorCode() : 0; } public MotanErrorMsg getMotanErrorMsg() { return motanErrorMsg; } }
String message = getOriginMessage(); return "error_message: " + message + ", status: " + motanErrorMsg.getStatus() + ", error_code: " + motanErrorMsg.getErrorCode() + ",r=" + RpcContext.getContext().getRequestId();
720
74
794
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/AccessLogFilter.java
AccessLogFilter
logAccess
class AccessLogFilter implements Filter { public static final String ACCESS_LOG_SWITCHER_NAME = "feature.motan.filter.accessLog"; public static final String PRINT_TRACE_LOG_SWITCHER_NAME = "feature.motan.printTraceLog.enable"; private String side; private Boolean accessLog; static { // init global switcher MotanSwitcherUtil.initSwitcher(ACCESS_LOG_SWITCHER_NAME, false); MotanSwitcherUtil.initSwitcher(PRINT_TRACE_LOG_SWITCHER_NAME, true); } @Override public Response filter(Caller<?> caller, Request request) { if (accessLog == null) { accessLog = caller.getUrl().getBooleanParameter(URLParamType.accessLog.getName(), URLParamType.accessLog.getBooleanValue()); } if (accessLog || needLog(request)) { long start = System.currentTimeMillis(); boolean success = false; Response response = null; try { response = caller.call(request); if (response != null && response.getException() == null) { success = true; } return response; } finally { processFinalLog(caller, request, response, start, success); } } else { return caller.call(request); } } private void processFinalLog(final Caller<?> caller, final Request request, final Response response, final long start, final boolean success) { long wholeTime = System.currentTimeMillis() - start; long segmentTime = wholeTime; // 分段耗时。server侧是内部业务耗时,client侧时server整体耗时+网络接收耗时 if (request instanceof Traceable && response instanceof Traceable) { // 可以取得细分时间点 if (caller instanceof Provider) { // server end if (response instanceof Callbackable) {// 因server侧完整耗时包括response发送时间,需要通过callback机制异步记录日志。 long finalSegmentTime = segmentTime; ((Callbackable) response).addFinishCallback(() -> { long responseSend = ((Traceable) response).getTraceableContext().getSendTime(); long requestReceive = ((Traceable) request).getTraceableContext().getReceiveTime(); long finalWholeTime = responseSend - requestReceive; logAccess(caller, request, response, finalSegmentTime, finalWholeTime, success); }, null); return; } } else { // client end long requestSend = ((Traceable) request).getTraceableContext().getSendTime(); long responseReceive = ((Traceable) response).getTraceableContext().getReceiveTime(); segmentTime = responseReceive - requestSend; } } logAccess(caller, request, response, segmentTime, wholeTime, success); // 同步记录access日志 } // 除了access log配置外,其他需要动态打印access的情况 private boolean needLog(Request request) { if (MotanSwitcherUtil.isOpen(ACCESS_LOG_SWITCHER_NAME)) { return true; } // check trace log if (!MotanSwitcherUtil.isOpen(PRINT_TRACE_LOG_SWITCHER_NAME)) { return false; } return "true".equalsIgnoreCase(request.getAttachments().get(MotanConstants.ATT_PRINT_TRACE_LOG)); } private void logAccess(Caller<?> caller, Request request, Response response, long segmentTime, long wholeTime, boolean success) {<FILL_FUNCTION_BODY>} private void append(StringBuilder builder, Object field) { if (field != null) { builder.append(StringTools.urlEncode(field.toString())); } builder.append(MotanConstants.SEPERATOR_ACCESS_LOG); } public String getSide() { return side; } public void setSide(String side) { this.side = side; } }
if (getSide() == null) { String side = caller instanceof Provider ? MotanConstants.NODE_TYPE_SERVICE : MotanConstants.NODE_TYPE_REFERER; setSide(side); } StringBuilder builder = new StringBuilder(128); append(builder, side); // application and module from local url append(builder, caller.getUrl().getParameter(URLParamType.application.getName())); append(builder, MotanFrameworkUtil.getModuleOrGroup(caller.getUrl().getParameters(), null)); append(builder, NetUtils.getLocalAddress().getHostAddress()); append(builder, request.getInterfaceName()); append(builder, request.getMethodName()); append(builder, request.getParamtersDesc()); // 对于client,url中的remote ip 和 service获取的地方不同 if (MotanConstants.NODE_TYPE_REFERER.equals(side)) { append(builder, caller.getUrl().getHost()); // direct append(builder, response == null ? null : response.getAttachments().get(MotanConstants.X_FORWARDED_FOR));// proxy } else { append(builder, request.getAttachments().get(URLParamType.host.getName())); // direct append(builder, request.getAttachments().get(MotanConstants.X_FORWARDED_FOR)); // proxy } // application and module from request append(builder, request.getAttachments().get(URLParamType.application.getName())); append(builder, MotanFrameworkUtil.getModuleOrGroup(request.getAttachments(), null)); append(builder, success); String requestId = request.getAttachments().get(URLParamType.requestIdFromClient.getName()); if (StringUtils.isBlank(requestId)) { requestId = String.valueOf(request.getRequestId()); } append(builder, requestId); append(builder, request.getAttachments().get(MotanConstants.CONTENT_LENGTH)); append(builder, response == null ? "0" : response.getAttachments().get(MotanConstants.CONTENT_LENGTH)); append(builder, segmentTime); append(builder, wholeTime); LoggerUtil.accessLog(builder.substring(0, builder.length() - 1));
1,042
583
1,625
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/AccessStatisticFilter.java
AccessStatisticFilter
filter
class AccessStatisticFilter implements Filter { private static final String RPC_SERVICE = "rpc_service"; @Override public Response filter(final Caller<?> caller, final Request request) {<FILL_FUNCTION_BODY>} }
long start = System.currentTimeMillis(); AccessStatus accessStatus = AccessStatus.NORMAL; final long bizProcessTime; Response response = null; try { response = caller.call(request); if (response != null && response.getException() != null) { if (ExceptionUtil.isBizException(response.getException())) { accessStatus = AccessStatus.BIZ_EXCEPTION; } else { accessStatus = AccessStatus.OTHER_EXCEPTION; } } return response; } finally { long end = System.currentTimeMillis(); if (response == null) { accessStatus = AccessStatus.OTHER_EXCEPTION; bizProcessTime = end - start; } else { bizProcessTime = response.getProcessTime(); } final String application, module; if (caller instanceof Referer) { application = request.getAttachments().get(URLParamType.application.getName()); module = MotanFrameworkUtil.getModuleOrGroup(request.getAttachments(), null); } else { application = caller.getUrl().getApplication(); module = MotanFrameworkUtil.getModuleOrGroup(caller.getUrl().getParameters(), null); } final String statName = caller.getUrl().getProtocol() + MotanConstants.PROTOCOL_SEPARATOR + MotanFrameworkUtil.getGroupMethodString(request); final int slowCost = caller.getUrl().getIntParameter(URLParamType.slowThreshold.getName(), URLParamType.slowThreshold.getIntValue()); final Response finalResponse = response; if (caller instanceof Provider) { StatsUtil.accessStatistic(statName, APPLICATION_STATISTIC, RPC_SERVICE, end, end - start, bizProcessTime, slowCost, accessStatus); if (response instanceof Callbackable) { final AccessStatus finalAccessStatus = accessStatus; ((Callbackable) response).addFinishCallback(() -> { if (request instanceof Traceable && finalResponse instanceof Traceable) { long responseSend = ((Traceable) finalResponse).getTraceableContext().getSendTime(); long requestReceive = ((Traceable) request).getTraceableContext().getReceiveTime(); StatsUtil.accessStatistic(statName + "_WHOLE", application, module, responseSend, responseSend - requestReceive, bizProcessTime, slowCost, finalAccessStatus); } }, null); } } StatsUtil.accessStatistic(statName, application, module, end, end - start, bizProcessTime, slowCost, accessStatus); }
66
670
736
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/ActiveLimitFilter.java
ActiveLimitFilter
filter
class ActiveLimitFilter implements Filter { @Override public Response filter(Caller<?> caller, Request request) {<FILL_FUNCTION_BODY>} }
int maxAcvitivyCount = caller.getUrl().getIntParameter(URLParamType.actives.getName(), URLParamType.actives.getIntValue()); if (maxAcvitivyCount > 0) { int activeCount = RpcStats.getServiceStat(caller.getUrl()).getActiveCount(); if (activeCount >= maxAcvitivyCount) { throw new MotanServiceException(String.format("Request(%s) active count exceed the limit (%s), referer:%s", request, maxAcvitivyCount, caller.getUrl()), MotanErrorMsgConstant.SERVICE_REJECT, false); } } long startTime = System.currentTimeMillis(); RpcStats.beforeCall(caller.getUrl(), request); try { Response rs = caller.call(request); RpcStats.afterCall(caller.getUrl(), request, true, System.currentTimeMillis() - startTime); return rs; } catch (RuntimeException re) { RpcStats.afterCall(caller.getUrl(), request, false, System.currentTimeMillis() - startTime); throw re; }
46
303
349
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/FaultInjectionFilter.java
FaultInjectionFilter
filter
class FaultInjectionFilter implements Filter { @Override public Response filter(Caller<?> caller, Request request) {<FILL_FUNCTION_BODY>} public static class FaultInjectionConfig { public String id; //rule id. public String servicePattern; public String methodPattern; public float delayRatio; // Delay ratio. For example, 0.25 means that the time-consuming delay is 0.25 times the actual time-consuming time. public long delayTime; // Specify the delay time(ms), for example, 1000 means a delay of 1 second based on the actual time taken. The delay includes remote exceptions. public int exceptionPercent; // Inject exception percentage. For example, setting it to 25 means that 25% of requests will return active exceptions. Percentages are used to facilitate calculations. public long exceptionTime; // Expected execution time when injecting an exception public String exceptionType; // Specifies the exception type when injecting exceptions. private Class<? extends Exception> exceptionClass; public boolean isMatch(String service, String method) { // check service boolean match = isMatch0(servicePattern, service); if (match && StringUtils.isNotBlank(methodPattern)) { // check method return isMatch0(methodPattern, method); } return match; } private boolean isMatch0(String pattern, String str) { if (StringUtils.isNotBlank(pattern)) { return Pattern.matches(pattern, str); } return false; } public Exception getException() { if (shouldException()) { if (exceptionClass != null) { try { Exception exception = exceptionClass.newInstance(); if (exception instanceof MotanAbstractException) { // return directly if it is motan exception return exception; } return new MotanBizException(exception); } catch (Exception ignore) { } } return new MotanServiceException("exception from FaultInjectionFilter"); } return null; } private boolean shouldException() { if (exceptionPercent > 0) { if (exceptionPercent >= 100) { return true; } return exceptionPercent > ThreadLocalRandom.current().nextInt(100); } return false; } public long getDelayTime(long responseTime) { if (delayTime > 0) { return delayTime; } else if (delayRatio > 0) { return (long) (responseTime * (delayRatio)); } return 0; } public long getExceptionTime() { return exceptionTime; } @SuppressWarnings("unchecked") public void init() { if (exceptionType != null) { try { exceptionClass = (Class<? extends Exception>) Class.forName(exceptionType); } catch (Exception ignore) { } } } } public static class FaultInjectionUtil { private static final String SEPARATOR = "-"; private static final FaultInjectionConfig NOT_MATCH = new FaultInjectionConfig(); // Fault injection configuration matching cache private static final ConcurrentHashMap<String, FaultInjectionConfig> matchCache = new ConcurrentHashMap<>(); private static List<FaultInjectionConfig> configList; // The configs to be updated must be complete configs,incremental updates are not supported. // Configs are regular expressions, multiple configs need to ensure matching order. // The fuzzy matching rules should after exact matching rules, the service rules should after the method matching rules. public static void updateConfigs(List<FaultInjectionConfig> configList) { configList.forEach(FaultInjectionConfig::init); FaultInjectionUtil.configList = configList; matchCache.clear(); } public static void clearConfigs() { configList = null; matchCache.clear(); } // get all configs public static List<FaultInjectionConfig> getConfigs() { return configList; } public static FaultInjectionConfig getGlobalFaultInjectionConfig(String service, String method) { if (configList == null) { return null; } FaultInjectionConfig config = matchCache.get(service + SEPARATOR + method); if (config == null) { // Not matched yet List<FaultInjectionConfig> configs = configList; for (FaultInjectionConfig temp : configs) { if (temp.isMatch(service, method)) { config = temp; break; } } if (config == null) { // Unmatched cache config = NOT_MATCH; } matchCache.put(service + SEPARATOR + method, config); } if (config == NOT_MATCH) { // Mismatch return null; } return config; } } }
FaultInjectionConfig config = FaultInjectionUtil.getGlobalFaultInjectionConfig(request.getInterfaceName(), request.getMethodName()); if (config == null) { return caller.call(request); } Response response; long delay; Exception exception = config.getException(); if (exception != null) { response = MotanFrameworkUtil.buildErrorResponse(request, exception); delay = config.getExceptionTime(); } else { response = caller.call(request); delay = config.getDelayTime(response.getProcessTime()); } if (delay > 0) { // process injected delay ignore sync/async calls try { Thread.sleep(delay); } catch (InterruptedException ignore) { } response.setProcessTime(response.getProcessTime() + delay); } return response;
1,268
225
1,493
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/ServiceMockFilter.java
ServiceMockFilter
filter
class ServiceMockFilter implements Filter { private static String RETURN_PREFIX = "return"; private static ConcurrentHashMap<String, MockInfo> mockServices = new ConcurrentHashMap<String, MockInfo>(); public static boolean isDefault(String value) { return "true".equalsIgnoreCase(value) || "default".equalsIgnoreCase(value); } private static MockInfo getServiceStat(URL url) { MockInfo info = mockServices.get(url.getIdentity()); if (info == null) { info = new MockInfo(url); mockServices.putIfAbsent(url.getIdentity(), info); info = mockServices.get(url.getIdentity()); } return info; } @Override public Response filter(Caller<?> caller, Request request) {<FILL_FUNCTION_BODY>} private Object invoke(Object clz, Method method, Object[] args, MockInfo info) throws InterruptedException, InvocationTargetException, IllegalAccessException { info.callNum.addAndGet(1); long sleepTime = caclSleepTime(info); Thread.sleep(sleepTime); return method.invoke(clz, args); } // Sleep invoke based on SLA private long caclSleepTime(MockInfo info) { double rMean = info.totalSleepTime.doubleValue() / info.callNum.get(); long sleepTime; int n = ThreadLocalRandom.current().nextInt(1000); long delta = (long) (rMean - info.mean + 1); if (n < 900) { sleepTime = info.p90; } else if (900 <= n && n < 990) { sleepTime = info.p99; } else if (990 <= n && n < 999) { sleepTime = info.p999; } else { sleepTime = info.p999 + 1; } // Use 0ms to offset the mean time. sleepTime = delta > 0 ? 0 : sleepTime; info.totalSleepTime.addAndGet(sleepTime); // Throw runtimeException when errorRate is defined. if (info.errorRate != 0) { int rate = 1; while (info.errorRate * rate < 1) { rate *= 10; } if (ThreadLocalRandom.current().nextInt(rate) == 1) { throw new RuntimeException(); } } return sleepTime; } public Object parseMockValue(String mock) throws Exception { return parseMockValue(mock, null); } public Object parseMockValue(String mock, Type[] returnTypes) { Object value; if ("empty".equals(mock)) { value = ReflectUtil.getEmptyObject(returnTypes != null && returnTypes.length > 0 ? (Class<?>) returnTypes[0] : null); } else if ("null".equals(mock)) { value = null; } else if ("true".equals(mock)) { value = true; } else if ("false".equals(mock)) { value = false; } else if (mock.length() >= 2 && (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) { value = mock.subSequence(1, mock.length() - 1); } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) { value = mock; } else { value = mock; } return value; } public static class MockInfo { private long mean; private long p90; private long p99; private long p999; private double errorRate; private AtomicLong callNum = new AtomicLong(0); private AtomicLong totalSleepTime = new AtomicLong(0); public MockInfo(URL url) { mean = Long.valueOf(url.getParameter(URLParamType.mean.getName(), URLParamType.mean.getValue())); p90 = Long.valueOf(url.getParameter(URLParamType.p90.getName(), URLParamType.p90.getValue())); p99 = Long.valueOf(url.getParameter(URLParamType.p99.getName(), URLParamType.p99.getValue())); p999 = Long.valueOf(url.getParameter(URLParamType.p999.getName(), URLParamType.p999.getValue())); errorRate = Double.valueOf(url.getParameter(URLParamType.errorRate.getName(), URLParamType.errorRate.getValue())); } } }
// Do nothing when mock is empty. String mockServiceName = caller.getUrl().getParameter(URLParamType.mock.getName()); if (StringUtils.isEmpty(mockServiceName) || "false".equals(mockServiceName)) { return caller.call(request); } MockInfo info = getServiceStat(caller.getUrl()); DefaultResponse response = new DefaultResponse(); if (mockServiceName.startsWith(RETURN_PREFIX)) { String value = mockServiceName.substring(RETURN_PREFIX.length()); try { info.callNum.addAndGet(1); long sleepTime = caclSleepTime(info); Thread.sleep(sleepTime); response.setValue(parseMockValue(value)); } catch (RuntimeException e) { if (e.getCause() != null) { response.setException(new MotanBizException("mock service call process error", e.getCause())); } else { response.setException(new MotanBizException("mock service call process error", e)); } } catch (Exception e) { throw new IllegalStateException("Illegal mock json value in <motan:service ... mock=\"" + mockServiceName + "\" />"); } } else { try { Class<?> mockClass = isDefault(mockServiceName) ? ReflectUtil.forName(caller.getInterface().getName() + "Mock") : ReflectUtil .forName(mockServiceName); if (!caller.getInterface().isAssignableFrom(mockClass)) { throw new MotanFrameworkException("The mock implemention class " + mockClass.getName() + " not implement interface " + caller.getInterface().getName()); } try { mockClass.getConstructor(); } catch (NoSuchMethodException e) { throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implemention class " + mockClass.getName()); } String methodDesc = ReflectUtil.getMethodDesc(request.getMethodName(), request.getParamtersDesc()); Method[] methods = mockClass.getMethods(); boolean invoke = false; for (Method method : methods) { if (methodDesc.equals(ReflectUtil.getMethodDesc(method))) { Object value = invoke(mockClass.newInstance(), method, request.getArguments(), info); response.setValue(value); invoke = true; break; } } if (!invoke) { throw new MotanFrameworkException("Mock method is not found." + methodDesc); } } catch (ClassNotFoundException e) { throw new MotanFrameworkException("Mock service is not found." + (isDefault(mockServiceName) ? caller.getInterface().getName() + "Mock" : mockServiceName)); } catch (Exception e) { if (e.getCause() != null) { response.setException(new MotanBizException("mock service call process error", e.getCause())); } else { response.setException(new MotanBizException("mock service call process error", e)); } } } return response;
1,224
818
2,042
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/SwitcherFilter.java
SwitcherFilter
mockDefaultResponse
class SwitcherFilter implements Filter { @Override public Response filter(Caller<?> caller, Request request) { // 检查接口或方法降级开关状态 if (MotanSwitcherUtil.isOpen(request.getInterfaceName()) || MotanSwitcherUtil.isOpen(MotanFrameworkUtil.getFullMethodString(request))) { // 返回的reponse需要设置exception,这样invocationhandler会在throwException为false时,构建默认值返回 return mockDefaultResponse(request); } return caller.call(request); } /** * 返回的reponse需要设置exception,这样invocationhandler会在throwException为false时,构建默认值返回 * * @param request * @return */ private Response mockDefaultResponse(Request request) {<FILL_FUNCTION_BODY>} }
DefaultResponse response = new DefaultResponse(null, request.getRequestId()); response.setException(new MotanServiceException("Request false for switcher is on")); return response;
222
47
269
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/filter/ThreadProtectedFilter.java
ThreadProtectedFilter
reject
class ThreadProtectedFilter implements InitializableFilter { protected static ConcurrentHashMap<String, AtomicInteger> portTotalMap = new ConcurrentHashMap<String, AtomicInteger>(); protected ConcurrentHashMap<String, AtomicInteger> methodMap = new ConcurrentHashMap<String, AtomicInteger>(); protected AtomicInteger totalCount; protected int maxThread; protected int totalLimit; protected int methodLimit; protected boolean isProvider = false; @Override public Response filter(Caller<?> caller, Request request) { if (isProvider) { String requestKey = MotanFrameworkUtil.getFullMethodString(request); AtomicInteger methodCount = methodMap.get(requestKey); if (methodCount == null) { methodMap.putIfAbsent(requestKey, new AtomicInteger()); methodCount = methodMap.get(requestKey); } try { int tCount = totalCount.incrementAndGet(); int mCount = methodCount.incrementAndGet(); if (tCount > totalLimit && mCount > methodLimit) { return reject(request.getInterfaceName() + "." + request.getMethodName(), mCount, tCount); } return caller.call(request); } finally { totalCount.decrementAndGet(); methodCount.decrementAndGet(); } } else { return caller.call(request); } } private Response reject(String method, int requestCounter, int totalCounter) {<FILL_FUNCTION_BODY>} /** * 默认策略当接口线程池占用达到3/4或者空闲小于150时,限制单个方法请求不能超过总线程数的1/2 需要自定义方法并发限制可以通过actives参数配置 */ @Override public void init(Caller<?> caller) { if (caller instanceof Provider) { String port = String.valueOf(caller.getUrl().getPort()); totalCount = portTotalMap.get(port); if (totalCount == null) { portTotalMap.putIfAbsent(port, new AtomicInteger()); totalCount = portTotalMap.get(port); } maxThread = caller.getUrl().getIntParameter(URLParamType.maxWorkerThread.getName(), URLParamType.maxWorkerThread.getIntValue()); totalLimit = maxThread > 600 ? maxThread - 150 : maxThread * 3 / 4; int active = caller.getUrl().getIntParameter(URLParamType.actives.getName(), URLParamType.actives.getIntValue()); if (active > 0) { methodLimit = active; } else { methodLimit = maxThread / 2; } isProvider = true; } } }
DefaultResponse response = new DefaultResponse(); MotanServiceException exception = new MotanServiceException("ThreadProtectedFilter reject request: request_counter=" + requestCounter + " total_counter=" + totalCounter + " max_thread=" + maxThread, MotanErrorMsgConstant.SERVICE_REJECT, false); response.setException(exception); LoggerUtil.error("ThreadProtectedFilter reject request: request_method=" + method + " request_counter=" + requestCounter + " =" + totalCounter + " max_thread=" + maxThread); return response;
721
149
870
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/AbstractProtocol.java
AbstractProtocol
refer
class AbstractProtocol implements Protocol { protected ConcurrentHashMap<String, Exporter<?>> exporterMap = new ConcurrentHashMap<String, Exporter<?>>(); public Map<String, Exporter<?>> getExporterMap() { return Collections.unmodifiableMap(exporterMap); } @SuppressWarnings("unchecked") @Override public <T> Exporter<T> export(Provider<T> provider, URL url) { if (url == null) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " export Error: url is null", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } if (provider == null) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " export Error: provider is null, url=" + url, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } String protocolKey = MotanFrameworkUtil.getProtocolKey(url); synchronized (exporterMap) { Exporter<T> exporter = (Exporter<T>) exporterMap.get(protocolKey); if (exporter != null) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " export Error: service already exist, url=" + url, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } exporter = createExporter(provider, url); exporter.init(); protocolKey = MotanFrameworkUtil.getProtocolKey(url);// rebuild protocolKey,maybe port change when using random port exporterMap.put(protocolKey, exporter); LoggerUtil.info(this.getClass().getSimpleName() + " export Success: url=" + url); return exporter; } } public <T> Referer<T> refer(Class<T> clz, URL url) { return refer(clz, url, url); } @Override public <T> Referer<T> refer(Class<T> clz, URL url, URL serviceUrl) {<FILL_FUNCTION_BODY>} protected abstract <T> Exporter<T> createExporter(Provider<T> provider, URL url); protected abstract <T> Referer<T> createReferer(Class<T> clz, URL url, URL serviceUrl); @Override public void destroy() { for (String key : exporterMap.keySet()) { Node node = exporterMap.remove(key); if (node != null) { try { node.destroy(); LoggerUtil.info(this.getClass().getSimpleName() + " destroy node Success: " + node); } catch (Throwable t) { LoggerUtil.error(this.getClass().getSimpleName() + " destroy Error", t); } } } } }
if (url == null) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " refer Error: url is null", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } if (clz == null) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " refer Error: class is null, url=" + url, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } long start = System.currentTimeMillis(); Referer<T> referer = createReferer(clz, url, serviceUrl); referer.init(); LoggerUtil.info(this.getClass().getSimpleName() + " refer Success: url=" + url + ", cost:" + (System.currentTimeMillis() - start)); return referer;
747
217
964
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/injvm/InjvmProtocol.java
InjvmReferer
doCall
class InjvmReferer<T> extends AbstractReferer<T> { private Exporter<T> exporter; public InjvmReferer(Class<T> clz, URL url, URL serviceUrl) { super(clz, url, serviceUrl); } @Override protected Response doCall(Request request) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") @Override protected boolean doInit() { String protocolKey = MotanFrameworkUtil.getProtocolKey(url); exporter = (Exporter<T>) exporterMap.get(protocolKey); if (exporter == null) { LoggerUtil.error("InjvmReferer init Error: provider not exist, url=" + url); return false; } return true; } @Override public void destroy() {} }
if (exporter == null) { throw new MotanServiceException("InjvmReferer call Error: provider not exist, url=" + url.getUri(), MotanErrorMsgConstant.SERVICE_UNFOUND); } return exporter.getProvider().call(request);
230
75
305
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/mock/AbstractMockRpcProtocol.java
AbstractMockRpcProtocol
createReferer
class AbstractMockRpcProtocol extends AbstractProtocol { private static ProviderMessageRouter mockProviderMessageRouter; @Override protected <T> Exporter<T> createExporter(Provider<T> provider, URL url) { Exporter<T> exporter = new MockRpcExporter<T>(provider, url); LoggerUtil.info("create MockRpcExporter: url={}", url); return exporter; } @Override protected <T> Referer<T> createReferer(Class<T> clz, URL url, URL serviceUrl) {<FILL_FUNCTION_BODY>} class MockRpcExporter<T> extends AbstractExporter<T> { private Server server; private EndpointFactory endpointFactory; public MockRpcExporter(Provider<T> provider, URL url) { super(provider, url); ProviderMessageRouter requestRouter = getMockProviderMessageRouter(url); endpointFactory = ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension( url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue())); server = endpointFactory.createServer(url, requestRouter); } @Override public void unexport() { String protocolKey = MotanFrameworkUtil.getProtocolKey(url); Exporter<T> exporter = (Exporter<T>) exporterMap.remove(protocolKey); if (exporter != null) { exporter.destroy(); } } @Override public void destroy() { endpointFactory.safeReleaseResource(server, url); LoggerUtil.info("MockRpcExporter destory Success: url={}", url); } @Override protected boolean doInit() { return server.open(); } @Override public boolean isAvailable() { return server.isAvailable(); } } class MockRpcReferer<T> extends AbstractReferer<T> { public MockRpcReferer(Class<T> clz, URL url, URL serviceUrl) { super(clz, url, serviceUrl); } @Override public void destroy() { LoggerUtil.info("MockRpcReferer destroy Success: url={}", url); } @Override protected Response doCall(Request request) { return processRequest(request); } @Override protected boolean doInit() { LoggerUtil.info("MockRpcReferer init Success: url={}", url); return true; } } // process all urls。 public ProviderMessageRouter getMockProviderMessageRouter(URL url) { if (mockProviderMessageRouter == null) { //default mockProviderMessageRouter = new MockProviderMessageRouter(); } return mockProviderMessageRouter; } class MockProviderMessageRouter extends ProviderMessageRouter { @Override public Object handle(Channel channel, Object message) { if (channel == null || message == null) { throw new MotanFrameworkException("RequestRouter handler(channel, message) params is null"); } if (!(message instanceof Request)) { throw new MotanFrameworkException("RequestRouter message type not support: " + message.getClass()); } return processRequest((Request) message); } } /** * process request. request is mock processed by client or server * * @param request * @return */ protected abstract Response processRequest(Request request); }
Referer<T> referer = new MockRpcReferer<T>(clz, url, serviceUrl); LoggerUtil.info("create MockRpcReferer: url={}", url); return referer;
918
58
976
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/rpc/DefaultRpcExporter.java
DefaultRpcExporter
unexport
class DefaultRpcExporter<T> extends AbstractExporter<T> { protected final ConcurrentHashMap<String, ProviderMessageRouter> ipPort2RequestRouter; protected final ConcurrentHashMap<String, Exporter<?>> exporterMap; protected Server server; protected EndpointFactory endpointFactory; public DefaultRpcExporter(Provider<T> provider, URL url, ConcurrentHashMap<String, ProviderMessageRouter> ipPort2RequestRouter, ConcurrentHashMap<String, Exporter<?>> exporterMap) { super(provider, url); this.exporterMap = exporterMap; this.ipPort2RequestRouter = ipPort2RequestRouter; ProviderMessageRouter requestRouter = initRequestRouter(url); endpointFactory = ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension( url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue())); server = endpointFactory.createServer(url, requestRouter); } @SuppressWarnings("unchecked") @Override public void unexport() {<FILL_FUNCTION_BODY>} @Override protected boolean doInit() { boolean result = server.open(); if (result && getUrl().getPort() == 0) { // use random port ProviderMessageRouter requestRouter = this.ipPort2RequestRouter.remove(getUrl().getServerPortStr()); if (requestRouter == null) { throw new MotanFrameworkException("can not find message router. url:" + getUrl().getIdentity()); } updateRealServerPort(server.getLocalAddress().getPort()); ProviderMessageRouter oldRouter = this.ipPort2RequestRouter.get(getUrl().getServerPortStr()); if (oldRouter != null) { oldRouter.addProvider(provider); } else { this.ipPort2RequestRouter.put(getUrl().getServerPortStr(), requestRouter); } } return result; } @Override public boolean isAvailable() { return server.isAvailable(); } @Override public void destroy() { endpointFactory.safeReleaseResource(server, url); LoggerUtil.info("DefaultRpcExporter destroy Success: url={}", url); } protected ProviderMessageRouter initRequestRouter(URL url) { String ipPort = url.getServerPortStr(); ProviderMessageRouter requestRouter = ipPort2RequestRouter.get(ipPort); if (requestRouter == null) { ProviderMessageRouter router = new ProviderMessageRouter(url); ipPort2RequestRouter.putIfAbsent(ipPort, router); requestRouter = ipPort2RequestRouter.get(ipPort); } requestRouter.addProvider(provider); return requestRouter; } }
String protocolKey = MotanFrameworkUtil.getProtocolKey(url); String ipPort = url.getServerPortStr(); Exporter<T> exporter = (Exporter<T>) exporterMap.remove(protocolKey); if (exporter != null) { exporter.destroy(); } ProviderMessageRouter requestRouter = ipPort2RequestRouter.get(ipPort); if (requestRouter != null) { requestRouter.removeProvider(provider); } LoggerUtil.info("DefaultRpcExporter unexport Success: url={}", url);
743
155
898
<methods>public void <init>(Provider<T>, com.weibo.api.motan.rpc.URL) ,public java.lang.String desc() ,public Provider<T> getProvider() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() <variables>protected Provider<T> provider
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/rpc/DefaultRpcReferer.java
DefaultRpcReferer
decrActiveCount
class DefaultRpcReferer<T> extends AbstractReferer<T> { protected Client client; protected EndpointFactory endpointFactory; public DefaultRpcReferer(Class<T> clz, URL url, URL serviceUrl) { super(clz, url, serviceUrl); endpointFactory = ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension( url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue())); client = endpointFactory.createClient(url); } @Override protected Response doCall(Request request) { try { // 为了能够实现跨group请求,需要使用server端的group。 request.setAttachment(URLParamType.group.getName(), serviceUrl.getGroup()); return client.request(request); } catch (TransportException exception) { throw new MotanServiceException("DefaultRpcReferer call Error: url=" + url.getUri(), exception); } } @Override protected void decrActiveCount(Request request, Response response) {<FILL_FUNCTION_BODY>} @Override protected boolean doInit() { return client.open(); } @Override public boolean isAvailable() { return client.isAvailable(); } @Override public void destroy() { endpointFactory.safeReleaseResource(client, url); LoggerUtil.info("DefaultRpcReferer destroy client: url={}" + url); } @Override public Map<String, Object> getRuntimeInfo() { Map<String, Object> infos = super.getRuntimeInfo(); infos.putAll(client.getRuntimeInfo()); return infos; } }
if (!(response instanceof Future)) { activeRefererCount.decrementAndGet(); return; } Future future = (Future) response; future.addListener(future1 -> activeRefererCount.decrementAndGet());
441
67
508
<methods>public void <init>(Class<T>, com.weibo.api.motan.rpc.URL) ,public void <init>(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) ,public int activeRefererCount() ,public com.weibo.api.motan.rpc.Response call(com.weibo.api.motan.rpc.Request) ,public java.lang.String desc() ,public Class<T> getInterface() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public com.weibo.api.motan.rpc.URL getServiceUrl() <variables>protected java.util.concurrent.atomic.AtomicInteger activeRefererCount,protected Class<T> clz,protected com.weibo.api.motan.rpc.URL serviceUrl
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/v2motan/CompatibleCodec.java
CompatibleCodec
decode
class CompatibleCodec implements Codec { private Codec v1 = new DefaultRpcCodec(); private Codec v1Compress = new CompressRpcCodec(); private Codec v2 = new MotanV2Codec(); @Override public byte[] encode(Channel channel, Object message) throws IOException { if (message instanceof Response) {// depends on the request protocol in server end. byte version = ((Response) message).getRpcProtocolVersion(); if (version == RpcProtocolVersion.VERSION_1.getVersion()) { return v1.encode(channel, message); } else if (version == RpcProtocolVersion.VERSION_1_Compress.getVersion()) { return v1Compress.encode(channel, message); } } return v2.encode(channel, message);// v2 codec as default. } @Override public Object decode(Channel channel, String remoteIp, byte[] buffer) throws IOException {<FILL_FUNCTION_BODY>} }
if (buffer.length < 2) { throw new MotanServiceException("not enough bytes for decode. length:" + buffer.length); } short type = ByteUtil.bytes2short(buffer, 0); if (type == DefaultRpcCodec.MAGIC) { return v1Compress.decode(channel, remoteIp, buffer); } else if (type == MotanV2Header.MAGIC) { return v2.decode(channel, remoteIp, buffer); } throw new MotanFrameworkException("decode error: magic error. magic:" + type);
255
150
405
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/v2motan/GrowableByteBuffer.java
GrowableByteBuffer
getVarint
class GrowableByteBuffer { public static int encodeZigZag32(int value) { return (value << 1) ^ (value >> 31); } public static long encodeZigZag64(long value) { return (value << 1) ^ (value >> 63); } public static int decodeZigZag32(int n) { return (n >>> 1) ^ -(n & 1); } public static long decodeZigZag64(long n) { return (n >>> 1) ^ -(n & 1); } private ByteBuffer buf; public GrowableByteBuffer(int initSize) { this.buf = ByteBuffer.allocate(initSize); } public GrowableByteBuffer(ByteBuffer buf) { this.buf = buf; } public void put(byte b) { ensureBufferEnough(1); buf.put(b); } public void put(int index, byte b) { buf.put(index, b); } public void put(byte[] b) { ensureBufferEnough(b.length); buf.put(b); } public void putShort(short value) { ensureBufferEnough(2); buf.putShort(value); } public void putShort(int index, short value) { buf.putShort(index, value); } public void putInt(int value) { ensureBufferEnough(4); buf.putInt(value); } public void putInt(int index, int value) { buf.putInt(index, value); } public void putLong(long value) { ensureBufferEnough(8); buf.putLong(value); } public void putLong(int index, long value) { buf.putLong(index, value); } public void putFloat(float value) { ensureBufferEnough(4); buf.putFloat(value); } public void putFloat(int index, float value) { buf.putFloat(index, value); } public void putDouble(double value) { ensureBufferEnough(8); buf.putDouble(value); } public void putDouble(int index, double value) { buf.putDouble(index, value); } public int putZigzag32(int value) { return putVarint(encodeZigZag32(value)); } public int putZigzag64(long value) { return putVarint(encodeZigZag64(value)); } public int putVarint(long value) { int count = 0; while (true) { count++; if ((value & ~0x7fL) == 0) { put((byte) value); break; } else { put((byte) ((value & 0x7f) | 0x80)); value >>>= 7; } } return count; } public byte get() { return buf.get(); } public byte get(int index) { return buf.get(index); } public void get(byte[] dst) { buf.get(dst); } public short getShort() { return buf.getShort(); } public short getShort(int index) { return buf.getShort(index); } public int getInt() { return buf.getInt(); } public int getInt(int index) { return buf.getInt(index); } public long getLong() { return buf.getLong(); } public long getLong(int index) { return buf.getLong(index); } public float getFloat() { return buf.getFloat(); } public float getFloat(int index) { return buf.getFloat(index); } public double getDouble() { return buf.getDouble(); } public double getDouble(int index) { return buf.getDouble(index); } public int getZigZag32() { return decodeZigZag32((int) getVarint()); } public long getZigZag64() { return decodeZigZag64(getVarint()); } public long getVarint() {<FILL_FUNCTION_BODY>} public void flip() { buf.flip(); } public int position() { return buf.position(); } public void position(int newPosition) { ensureBufferEnough(newPosition - buf.position()); buf.position(newPosition); } public int limit() { return buf.limit(); } public void limit(int newLimit) { buf.limit(newLimit); } public int capacity() { return buf.capacity(); } public int remaining() { return buf.remaining(); } public void clear() { buf.clear(); } private ByteBuffer grow(int size) { ByteBuffer newbuf = ByteBuffer.allocate(size); newbuf.put(buf.array()); newbuf.position(buf.position()); return newbuf; } private void ensureBufferEnough(int need) { int expandSize = buf.position() + need; if (buf.capacity() < expandSize) { int size = buf.capacity() * 2; while (size < expandSize) { size = size * 2; } buf = grow(size); } } }
long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = buf.get(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw new MotanServiceException("Integer overflow");
1,514
97
1,611
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/v2motan/MotanV2Header.java
MotanV2Header
toBytes
class MotanV2Header { public static final short MAGIC = (short) 0xF1F1; private int version = 1;//rpc协议版本号。motan1对应 0, motan2对应1 private boolean heartbeat = false;//是否心跳消息。 private boolean gzip = false; //是否gzip压缩消息 private boolean oneway = false;//是否单向消息。单向消息不需要response private boolean proxy = false;// 是否需要代理请求。motan agent使用。 private boolean request = true; //消息类型是否是request private int status = 0; //消息状态。最大能表示8种状态,最大值为7。 0表示正常消息,1表示异常消息。其他待扩展 private int serialize = 1;// 消息body序列化方式,最大支持32种方式,最大值31。0 hessian、1 grpc-pb、2 json、3 msgpack、4 hprose、5 pb、6 simple、7 grpc-pb-json private long requestId; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isHeartbeat() { return heartbeat; } public void setHeartbeat(boolean heartbeat) { this.heartbeat = heartbeat; } public boolean isGzip() { return gzip; } public void setGzip(boolean gzip) { this.gzip = gzip; } public boolean isOneway() { return oneway; } public void setOneway(boolean oneway) { this.oneway = oneway; } public boolean isProxy() { return proxy; } public void setProxy(boolean proxy) { this.proxy = proxy; } public boolean isRequest() { return request; } public void setRequest(boolean request) { this.request = request; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getSerialize() { return serialize; } public void setSerialize(int serialize) { this.serialize = serialize; } public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } public byte[] toBytes() {<FILL_FUNCTION_BODY>} public static MotanV2Header buildHeader(byte[] headerBytes) { ByteBuffer buf = ByteBuffer.wrap(headerBytes); short mg = buf.getShort(); if (mg != MAGIC) { throw new MotanServiceException("decode motan v2 header fail. magicnum not correct. magic:" + mg); } MotanV2Header header = new MotanV2Header(); byte b = buf.get(); if ((b & 0x10) == 0x10) { header.setHeartbeat(true); } if ((b & 0x08) == 0x08) { header.setGzip(true); } if ((b & 0x04) == 0x04) { header.setOneway(true); } if ((b & 0x02) == 0x02) { header.setProxy(true); } if ((b & 0x01) == 0x01) { header.setRequest(false); } b = buf.get(); header.setVersion((b >>> 3) & 0x1f); header.setStatus(b & 0x07); b = buf.get(); header.setSerialize((b >>> 3) & 0x1f); header.setRequestId(buf.getLong()); return header; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MotanV2Header that = (MotanV2Header) o; if (version != that.version) return false; if (heartbeat != that.heartbeat) return false; if (gzip != that.gzip) return false; if (oneway != that.oneway) return false; if (proxy != that.proxy) return false; if (request != that.request) return false; if (status != that.status) return false; if (serialize != that.serialize) return false; return requestId == that.requestId; } @Override public int hashCode() { int result = version; result = 31 * result + (heartbeat ? 1 : 0); result = 31 * result + (gzip ? 1 : 0); result = 31 * result + (oneway ? 1 : 0); result = 31 * result + (proxy ? 1 : 0); result = 31 * result + (request ? 1 : 0); result = 31 * result + status; result = 31 * result + serialize; result = 31 * result + (int) (requestId ^ (requestId >>> 32)); return result; } public static enum MessageStatus { NORMAL(0), EXCEPTION(1); private final int status; private MessageStatus(int status) { this.status = status; } public int getStatus() { return status; } } }
ByteBuffer buf = ByteBuffer.allocate(13); buf.putShort(MAGIC); byte msgType = (byte) 0x00; if (heartbeat) { msgType = (byte) (msgType | 0x10); } if (gzip) { msgType = (byte) (msgType | 0x08); } if (oneway) { msgType = (byte) (msgType | 0x04); } if (proxy) { msgType = (byte) (msgType | 0x02); } if (!request) { msgType = (byte) (msgType | 0x01); } buf.put(msgType); byte vs = 0x08; if (version != 1) { vs = (byte) ((version << 3) & 0xf8); } if (status != 0) { vs = (byte) (vs | (status & 0x07)); } buf.put(vs); byte se = 0x08; if (serialize != 1) { se = (byte) ((serialize << 3) & 0xf8); } buf.put(se); buf.putLong(requestId); buf.flip(); return buf.array();
1,483
349
1,832
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/protocol/v2motan/MotanV2Protocol.java
V2RpcReferer
doCall
class V2RpcReferer<T> extends DefaultRpcReferer<T> { public V2RpcReferer(Class<T> clz, URL url, URL serviceUrl) { super(clz, url, serviceUrl); } @Override protected Response doCall(Request request) {<FILL_FUNCTION_BODY>} }
try { // use server end group request.setAttachment(URLParamType.group.getName(), serviceUrl.getGroup()); request.setAttachment(M2_PROXY_PROTOCOL, this.url.getProtocol()); // add proxy protocol for request agent return client.request(request); } catch (TransportException exception) { throw new MotanServiceException("DefaultRpcReferer call Error: url=" + url.getUri(), exception); }
94
118
212
<methods>public non-sealed void <init>() ,public void destroy() ,public Exporter<T> export(Provider<T>, com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,Exporter<?>> getExporterMap() ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL) ,public Referer<T> refer(Class<T>, com.weibo.api.motan.rpc.URL, com.weibo.api.motan.rpc.URL) <variables>protected ConcurrentHashMap<java.lang.String,Exporter<?>> exporterMap
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/proxy/MeshClientRefererInvocationHandler.java
MeshClientRefererInvocationHandler
invoke
class MeshClientRefererInvocationHandler<T> extends AbstractRefererHandler<T> implements InvocationHandler, CommonClient { protected MeshClient meshClient; protected URL refUrl; /** * only for InvocationHandler */ public MeshClientRefererInvocationHandler(Class<T> clz, URL refUrl, MeshClient meshClient) { this.clz = clz; this.refUrl = refUrl; this.interfaceName = MotanFrameworkUtil.removeAsyncSuffix(clz.getName()); this.meshClient = meshClient; } /** * only for CommonClient */ public MeshClientRefererInvocationHandler(URL refUrl, MeshClient meshClient) { this.refUrl = refUrl; this.interfaceName = refUrl.getPath(); this.meshClient = meshClient; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} Object invokeRequest(Request request, Class returnType, boolean async) throws Throwable { fillWithContext(request, async); setDefaultAttachments(request, URLParamType.application.getName(), URLParamType.group.getName(), URLParamType.module.getName(), URLParamType.version.getName()); // set request timeout String timeout = refUrl.getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName()); if (timeout != null) { request.setAttachment(MotanConstants.M2_TIMEOUT, timeout); } return call(meshClient, refUrl, request, returnType, async); } private void setDefaultAttachments(Request request, String... keys) { for (String key : keys) { String value = refUrl.getParameter(key); if (StringUtils.isNotEmpty(value)) { request.setAttachment(key, value); } } } private String innerToString() { return "referer: " + refUrl.toFullStr() + " - mesh client: " + meshClient.getUrl().toFullStr(); } @Override public Object call(String methodName, Object[] arguments, Class returnType) throws Throwable { return invokeRequest(buildRequest(methodName, arguments), returnType, false); } @Override public Object asyncCall(String methodName, Object[] arguments, Class returnType) throws Throwable { return invokeRequest(buildRequest(methodName, arguments), returnType, true); } @Override public Object call(Request request, Class returnType) throws Throwable { return invokeRequest(request, returnType, false); } @Override public Object asyncCall(Request request, Class returnType) throws Throwable { return invokeRequest(request, returnType, true); } @Override public Request buildRequest(String methodName, Object[] arguments) { return buildRequest(interfaceName, methodName, arguments); } @Override public Request buildRequest(String interfaceName, String methodName, Object[] arguments) { return MotanClientUtil.buildRequest(interfaceName, methodName, arguments); } }
if (isLocalMethod(method)) { if ("toString".equals(method.getName())) { return innerToString(); } if ("equals".equals(method.getName())) { return refUrl.equals(args[0]); } if ("hashCode".equals(method.getName())) { return refUrl.hashCode(); } throw new MotanServiceException("can not invoke local method:" + method.getName()); } DefaultRequest request = new DefaultRequest(); boolean async = fillDefaultRequest(request, method, args); return invokeRequest(request, getRealReturnType(async, this.clz, method, request.getMethodName()), async);
820
169
989
<methods>public non-sealed void <init>() <variables>protected List<Cluster<T>> clusters,protected Class<T> clz,protected java.lang.String interfaceName,protected com.weibo.api.motan.switcher.SwitcherService switcherService
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/proxy/RefererInvocationHandler.java
RefererInvocationHandler
clustersToString
class RefererInvocationHandler<T> extends AbstractRefererHandler<T> implements InvocationHandler { public RefererInvocationHandler(Class<T> clz, List<Cluster<T>> clusters) { this.clz = clz; this.clusters = clusters; init(); interfaceName = MotanFrameworkUtil.removeAsyncSuffix(clz.getName()); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (isLocalMethod(method)) { if ("toString".equals(method.getName())) { return clustersToString(); } if ("equals".equals(method.getName())) { return proxyEquals(args[0]); } if ("hashCode".equals(method.getName())) { return this.clusters == null ? 0 : this.clusters.hashCode(); } throw new MotanServiceException("can not invoke local method:" + method.getName()); } DefaultRequest request = new DefaultRequest(); boolean async = fillDefaultRequest(request, method, args); return invokeRequest(request, getRealReturnType(async, this.clz, method, request.getMethodName()), async); } private String clustersToString() {<FILL_FUNCTION_BODY>} private boolean proxyEquals(Object o) { if (o == null || this.clusters == null) { return false; } if (o instanceof List) { return this.clusters == o; } else { return o.equals(this.clusters); } } }
StringBuilder sb = new StringBuilder(); for (Cluster<T> cluster : clusters) { sb.append("{protocol:").append(cluster.getUrl().getProtocol()); List<Referer<T>> referers = cluster.getReferers(); if (referers != null) { for (Referer<T> refer : referers) { sb.append("[").append(refer.getUrl().toSimpleString()).append(", available:").append(refer.isAvailable()).append("]"); } } sb.append("}"); } return sb.toString();
407
154
561
<methods>public non-sealed void <init>() <variables>protected List<Cluster<T>> clusters,protected Class<T> clz,protected java.lang.String interfaceName,protected com.weibo.api.motan.switcher.SwitcherService switcherService
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/AbstractRegistryFactory.java
AbstractRegistryFactory
getRegistry
class AbstractRegistryFactory implements RegistryFactory { private static final ConcurrentHashMap<String, Registry> registries = new ConcurrentHashMap<>(); private static final ReentrantLock lock = new ReentrantLock(); protected String getRegistryUri(URL url) { return url.getUri(); } @Override public Registry getRegistry(URL url) {<FILL_FUNCTION_BODY>} protected abstract Registry createRegistry(URL url); }
String registryUri = getRegistryUri(url); try { lock.lock(); Registry registry = registries.get(registryUri); if (registry != null) { return registry; } registry = createRegistry(url); if (registry == null) { throw new MotanFrameworkException("Create registry false for url:" + url, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } registries.put(registryUri, registry); GlobalRuntime.addRegistry(registryUri, registry); return registry; } catch (Exception e) { throw new MotanFrameworkException("Create registry false for url:" + url, e, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } finally { lock.unlock(); }
122
206
328
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/DirectRegistry.java
DirectRegistry
parseDirectUrl
class DirectRegistry extends AbstractRegistry { private ConcurrentHashMap<URL, Object> subscribeUrls = new ConcurrentHashMap(); private List<URL> directUrls = new ArrayList<URL>(); public DirectRegistry(URL url) { super(url); String address = url.getParameter("address"); if (address.contains(",")) { try { String[] directUrlArray = address.split(","); for (String directUrl : directUrlArray) { parseDirectUrl(directUrl); } } catch (Exception e) { throw new MotanFrameworkException( String.format("parse direct url error, invalid direct registry address %s, address should be ip1:port1,ip2:port2 ...")); } } else { registerDirectUrl(url.getHost(), url.getPort()); } } private void parseDirectUrl(String directUrl) {<FILL_FUNCTION_BODY>} private void registerDirectUrl(String ip, Integer port) { URL url = new URL(MotanConstants.REGISTRY_PROTOCOL_DIRECT,ip,port,""); directUrls.add(url); } private void parseIpAndPort(String directUrl) { } @Override protected void doRegister(URL url) { // do nothing } @Override protected void doUnregister(URL url) { // do nothing } @Override protected void doSubscribe(URL url, NotifyListener listener) { subscribeUrls.putIfAbsent(url, 1); listener.notify(this.getUrl(), doDiscover(url)); } @Override protected void doUnsubscribe(URL url, NotifyListener listener) { subscribeUrls.remove(url); listener.notify(this.getUrl(), doDiscover(url)); } @Override protected List<URL> doDiscover(URL subscribeUrl) { return createSubscribeUrl(subscribeUrl); } private List<URL> createSubscribeUrl(URL subscribeUrl) { URL url = this.getUrl(); List result = new ArrayList(directUrls.size()); for (URL directUrl : directUrls) { URL tmp = subscribeUrl.createCopy(); tmp.setHost(directUrl.getHost()); tmp.setPort(directUrl.getPort()); result.add(tmp); } return result; } @Override protected void doAvailable(URL url) { // do nothing } @Override protected void doUnavailable(URL url) { // do nothing } }
String[] ipAndPort = directUrl.split(":"); String ip = ipAndPort[0]; Integer port = Integer.parseInt(ipAndPort[1]); if (port < 0 || port > 65535) { throw new RuntimeException(); } registerDirectUrl(ip, port);
673
82
755
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public void available(com.weibo.api.motan.rpc.URL) ,public List<com.weibo.api.motan.rpc.URL> discover(com.weibo.api.motan.rpc.URL) ,public Collection<com.weibo.api.motan.rpc.URL> getRegisteredServiceUrls() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public com.weibo.api.motan.rpc.URL getUrl() ,public void register(com.weibo.api.motan.rpc.URL) ,public void subscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) ,public void unavailable(com.weibo.api.motan.rpc.URL) ,public void unregister(com.weibo.api.motan.rpc.URL) ,public void unsubscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) <variables>private Set<com.weibo.api.motan.rpc.URL> registeredServiceUrls,protected java.lang.String registryClassName,private com.weibo.api.motan.rpc.URL registryUrl,private ConcurrentHashMap<com.weibo.api.motan.rpc.URL,Map<java.lang.String,List<com.weibo.api.motan.rpc.URL>>> subscribedCategoryResponses
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/LocalRegistryService.java
LocalRegistryService
doSubscribe
class LocalRegistryService extends AbstractRegistry { /** Map<interface/nodeType, List<URL>>, List 中的url用identity/id来区分唯一性 */ private ConcurrentMap<String, List<URL>> registeredServices = new ConcurrentHashMap<String, List<URL>>(); private ConcurrentHashMap<String, ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>>> subscribeListeners = new ConcurrentHashMap<String, ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>>>(); private URL registryUrl; public LocalRegistryService() { this(new URL(MotanConstants.REGISTRY_PROTOCOL_LOCAL, NetUtils.LOCALHOST, MotanConstants.DEFAULT_INT_VALUE, RegistryService.class.getName())); } public LocalRegistryService(URL url) { super(url); this.registryUrl = url; } @Override public void doSubscribe(URL url, NotifyListener listener) {<FILL_FUNCTION_BODY>} @Override public void doUnsubscribe(URL url, NotifyListener listener) { String subscribeKey = getSubscribeKey(url); ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>> urlListeners = subscribeListeners.get(subscribeKey); if (urlListeners != null) { urlListeners.remove(url); } LoggerUtil.info("LocalRegistryService unsubscribe: url={}", url); } @Override public List<URL> doDiscover(URL url) { return registeredServices.get(getRegistryKey(url)); } @Override protected void doAvailable(URL url) { //do nothing } @Override protected void doUnavailable(URL url) { //do nothing } @Override public void doRegister(URL url) { String registryKey = getRegistryKey(url); synchronized (registeredServices) { List<URL> urls = registeredServices.get(registryKey); if (urls == null) { registeredServices.putIfAbsent(registryKey, new ArrayList<URL>()); urls = registeredServices.get(registryKey); } add(url, urls); LoggerUtil.info("LocalRegistryService register: url={}", url); notifyListeners(url); } } @Override public void doUnregister(URL url) { synchronized (registeredServices) { List<URL> urls = registeredServices.get(getRegistryKey(url)); if (urls == null) { return; } remove(url, urls); LoggerUtil.info("LocalRegistryService unregister: url={}", url); // 在变更后立即进行通知 notifyListeners(url); } } @Override public URL getUrl() { return registryUrl; } /** * 防止数据在外部被变更,因此copy一份 * * @return */ public Map<String, List<URL>> getAllUrl() { Map<String, List<URL>> copyMap = new HashMap<String, List<URL>>(registeredServices.size()); for (Map.Entry<String, List<URL>> entry : registeredServices.entrySet()) { String key = entry.getKey(); List<URL> copyList = new ArrayList<URL>(entry.getValue().size()); for (URL url : entry.getValue()) { copyList.add(url.createCopy()); } copyMap.put(key, copyList); } return copyMap; } private void remove(URL url, List<URL> urls) { if (CollectionUtil.isEmpty(urls)) { return; } removeCachedUrlByIdentity(url, urls); } private void add(URL url, List<URL> urls) { removeCachedUrlByIdentity(url, urls); urls.add(url); } private void removeCachedUrlByIdentity(URL url, List<URL> urls) { if (CollectionUtil.isEmpty(urls)) { return; } URL oldUrl = null; for (URL cachedUrl : urls) { if (ObjectUtils.equals(url, cachedUrl)) { oldUrl = cachedUrl; break; } } if (oldUrl != null) { urls.remove(oldUrl); } } private void notifyListeners(URL changedUrl) { List<URL> interestingUrls = discover(changedUrl); if (interestingUrls != null) { ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>> urlListeners = subscribeListeners.get(getSubscribeKey(changedUrl)); if (urlListeners == null) { return; } for (ConcurrentHashSet<NotifyListener> listeners : urlListeners.values()) { for (NotifyListener ln : listeners) { try { ln.notify(getUrl(), interestingUrls); } catch (Exception e) { LoggerUtil.warn(String.format("Exception when notify listerner %s, changedUrl: %s", ln, changedUrl), e); } } } } } private String getRegistryKey(URL url) { String keyPrefix = url.getPath(); String nodeType = url.getParameter(URLParamType.nodeType.getName()); if (nodeType != null) { return keyPrefix + MotanConstants.PATH_SEPARATOR + nodeType; } else { LoggerUtil.warn("Url need a nodeType as param in localRegistry, url={}", url); return keyPrefix; } } private String getSubscribeKey(URL url) { return getRegistryKey(url); } }
String subscribeKey = getSubscribeKey(url); ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>> urlListeners = subscribeListeners.get(subscribeKey); if (urlListeners == null) { subscribeListeners.putIfAbsent(subscribeKey, new ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>>()); urlListeners = subscribeListeners.get(subscribeKey); } ConcurrentHashSet<NotifyListener> listeners = urlListeners.get(url); if (listeners == null) { urlListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>()); listeners = urlListeners.get(url); } listeners.add(listener); List<URL> urls = discover(url); if (urls != null && urls.size() > 0) { listener.notify(getUrl(), urls); } LoggerUtil.info("LocalRegistryService subscribe: url={}", url);
1,517
258
1,775
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public void available(com.weibo.api.motan.rpc.URL) ,public List<com.weibo.api.motan.rpc.URL> discover(com.weibo.api.motan.rpc.URL) ,public Collection<com.weibo.api.motan.rpc.URL> getRegisteredServiceUrls() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public com.weibo.api.motan.rpc.URL getUrl() ,public void register(com.weibo.api.motan.rpc.URL) ,public void subscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) ,public void unavailable(com.weibo.api.motan.rpc.URL) ,public void unregister(com.weibo.api.motan.rpc.URL) ,public void unsubscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) <variables>private Set<com.weibo.api.motan.rpc.URL> registeredServiceUrls,protected java.lang.String registryClassName,private com.weibo.api.motan.rpc.URL registryUrl,private ConcurrentHashMap<com.weibo.api.motan.rpc.URL,Map<java.lang.String,List<com.weibo.api.motan.rpc.URL>>> subscribedCategoryResponses
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/command/CommandFailbackRegistry.java
CommandFailbackRegistry
doUnsubscribe
class CommandFailbackRegistry extends FailbackRegistry { private ConcurrentHashMap<URL, CommandServiceManager> commandManagerMap; public CommandFailbackRegistry(URL url) { super(url); commandManagerMap = new ConcurrentHashMap<>(); LoggerUtil.info("CommandFailbackRegistry init. url: " + url.toSimpleString()); } @Override protected void doSubscribe(URL url, final NotifyListener listener) { LoggerUtil.info("CommandFailbackRegistry subscribe. url: " + url.toSimpleString()); URL urlCopy = url.createCopy(); CommandServiceManager manager = getCommandServiceManager(urlCopy); manager.addNotifyListener(listener); subscribeService(urlCopy, manager); subscribeCommand(urlCopy, manager); List<URL> urls = doDiscover(urlCopy); if (urls != null && !urls.isEmpty()) { this.notify(urlCopy, listener, urls); } } @Override protected void doUnsubscribe(URL url, NotifyListener listener) {<FILL_FUNCTION_BODY>} @Override protected List<URL> doDiscover(URL url) { LoggerUtil.info("CommandFailbackRegistry discover. url: " + url.toSimpleString()); URL urlCopy = url.createCopy(); String commandStr = discoverCommand(urlCopy); RpcCommand rpcCommand = null; if (StringUtils.isNotEmpty(commandStr)) { rpcCommand = RpcCommandUtil.stringToCommand(commandStr); } LoggerUtil.info("CommandFailbackRegistry discover command. commandStr: " + commandStr + ", rpc command " + (rpcCommand == null ? "is null." : "is not null.")); CommandServiceManager manager = getCommandServiceManager(urlCopy); List<URL> finalResult = manager.discoverServiceWithCommand(new HashMap<>(), rpcCommand); // 在subscribeCommon时,可能订阅完马上就notify,导致首次notify指令时,可能还有其他service没有完成订阅, // 此处先对manager更新指令,避免首次订阅无效的问题。 manager.setCommandCache(commandStr); LoggerUtil.info("CommandFailbackRegistry discover size: " + (finalResult == null ? "0" : finalResult.size())); return finalResult; } public List<URL> commandPreview(URL url, RpcCommand rpcCommand, String previewIP) { CommandServiceManager manager = getCommandServiceManager(url.createCopy()); return manager.discoverServiceWithCommand(new HashMap<>(), rpcCommand, previewIP); } private CommandServiceManager getCommandServiceManager(URL urlCopy) { CommandServiceManager manager = commandManagerMap.get(urlCopy); if (manager == null) { manager = new CommandServiceManager(urlCopy); manager.setRegistry(this); CommandServiceManager manager1 = commandManagerMap.putIfAbsent(urlCopy, manager); if (manager1 != null) manager = manager1; } return manager; } // for UnitTest public ConcurrentHashMap<URL, CommandServiceManager> getCommandManagerMap() { return commandManagerMap; } protected abstract void subscribeService(URL url, ServiceListener listener); protected abstract void subscribeCommand(URL url, CommandListener listener); protected abstract void unsubscribeService(URL url, ServiceListener listener); protected abstract void unsubscribeCommand(URL url, CommandListener listener); protected abstract List<URL> discoverService(URL url); protected abstract String discoverCommand(URL url); @Override public Map<String, Object> getRuntimeInfo() { Map<String, Object> infos = super.getRuntimeInfo(); Map<String, Object> subscribeInfo = new HashMap<>(); commandManagerMap.forEach((key, value) -> { Map<String, Object> temp = value.getRuntimeInfo(); if (!temp.isEmpty()) { subscribeInfo.put(key.getIdentity(), temp); } }); if (!subscribeInfo.isEmpty()) { infos.put(RuntimeInfoKeys.SUBSCRIBE_INFO_KEY, subscribeInfo); } return infos; } }
LoggerUtil.info("CommandFailbackRegistry unsubscribe. url: " + url.toSimpleString()); URL urlCopy = url.createCopy(); CommandServiceManager manager = commandManagerMap.get(urlCopy); manager.removeNotifyListener(listener); unsubscribeService(urlCopy, manager); unsubscribeCommand(urlCopy, manager);
1,066
90
1,156
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public List<com.weibo.api.motan.rpc.URL> discover(com.weibo.api.motan.rpc.URL) ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public void register(com.weibo.api.motan.rpc.URL) ,public void subscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) ,public void unregister(com.weibo.api.motan.rpc.URL) ,public void unsubscribe(com.weibo.api.motan.rpc.URL, com.weibo.api.motan.registry.NotifyListener) <variables>private final Set<com.weibo.api.motan.rpc.URL> failedRegistered,private final ConcurrentHashMap<com.weibo.api.motan.rpc.URL,ConcurrentHashSet<com.weibo.api.motan.registry.NotifyListener>> failedSubscribed,private final Set<com.weibo.api.motan.rpc.URL> failedUnregistered,private final ConcurrentHashMap<com.weibo.api.motan.rpc.URL,ConcurrentHashSet<com.weibo.api.motan.registry.NotifyListener>> failedUnsubscribed,private static final java.util.concurrent.ScheduledExecutorService retryExecutor
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/command/RpcCommand.java
RpcCommand
sort
class RpcCommand { private List<ClientCommand> clientCommandList; public void sort() {<FILL_FUNCTION_BODY>} public static class ClientCommand { private Integer index; private String version; private String dc; private Integer commandType; // 0:流控,1:降级,2:开关 private String pattern; private List<String> mergeGroups; // 路由规则,当有多个匹配时,按顺序依次过滤结果 private List<String> routeRules; private String remark; public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDc() { return dc; } public void setDc(String dc) { this.dc = dc; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public List<String> getMergeGroups() { return mergeGroups; } public void setMergeGroups(List<String> mergeGroups) { this.mergeGroups = mergeGroups; } public List<String> getRouteRules() { return routeRules; } public void setRouteRules(List<String> routeRules) { this.routeRules = routeRules; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Integer getCommandType() { return commandType; } public void setCommandType(Integer commandType) { this.commandType = commandType; } } public List<ClientCommand> getClientCommandList() { return clientCommandList; } public void setClientCommandList(List<ClientCommand> clientCommandList) { this.clientCommandList = clientCommandList; } public static class ServerCommand { } }
if (clientCommandList != null){ clientCommandList.sort((o1, o2) -> { Integer i1 = o1.getIndex(); Integer i2 = o2.getIndex(); if (i1 == null) { return -1; } if (i2 == null) { return 1; } return i1.compareTo(i2); }); }
591
111
702
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/registry/support/command/RpcCommandUtil.java
RpcCommandUtil
stringToCommand
class RpcCommandUtil { /** * 把指令字符串转为指令对象 * * @param commandString * @return */ public static RpcCommand stringToCommand(String commandString) {<FILL_FUNCTION_BODY>} /** * 指令对象转为string * * @param command * @return */ public static String commandToString(RpcCommand command) { if (command == null) { return null; } return JSONObject.toJSONString(command); } private static PatternEvaluator evaluator = new PatternEvaluator(); public static boolean match(String expression, String path) { if (expression == null || expression.length() == 0) { return false; } return evaluator.match(expression, path); } /** * 匹配规则解析类 */ private static class PatternEvaluator { Pattern pattern = Pattern.compile("[a-zA-Z0-9_$.*]+"); Set<Character> all = ImmutableSet.of('(', ')', '0', '1', '!', '&', '|'); Map<Character, ImmutableSet<Character>> following = ImmutableMap.<Character, ImmutableSet<Character>>builder() .put('(', ImmutableSet.of('0', '1', '!')).put(')', ImmutableSet.of('|', '&', ')')).put('0', ImmutableSet.of('|', '&', ')')) .put('1', ImmutableSet.of('|', '&', ')')).put('!', ImmutableSet.of('(', '0', '1', '!')) .put('&', ImmutableSet.of('(', '0', '1', '!')).put('|', ImmutableSet.of('(', '0', '1', '!')).build(); boolean match(String expression, String path) { // 匹配出每一项,求值,依据结果替换为0和1 Matcher matcher = pattern.matcher(expression.replaceAll("\\s+", "")); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String s = matcher.group(); int idx = s.indexOf('*'); if (idx != -1) { matcher.appendReplacement(buffer, path.startsWith(s.substring(0, idx)) ? "1" : "0"); } else { matcher.appendReplacement(buffer, s.equals(path) ? "1" : "0"); } } matcher.appendTail(buffer); String result1 = buffer.toString(); // 嵌套链表结构用于处理圆括号 LinkedList<LinkedList<Character>> outer = new LinkedList<>(); LinkedList<Character> inner = new LinkedList<>(); inner.push('#'); outer.push(inner); int i = 0; int len = result1.length(); while (outer.size() > 0 && i < len) { LinkedList<Character> sub = outer.peekLast(); while (sub.size() > 0 && i < len) { char curr = result1.charAt(i++); support(curr); char prev = sub.peekFirst(); if (prev != '#') { supportFollowing(prev, curr); } switch (curr) { case '(': sub = new LinkedList<>(); sub.push('#'); outer.push(sub); break; case ')': outer.removeFirst(); outer.peekFirst().push(evalWithinParentheses(sub)); sub = outer.peekFirst(); break; default: sub.push(curr); } } } if (outer.size() != 1) { throw new IllegalArgumentException("语法错误, 可能圆括号没有闭合"); } char result = evalWithinParentheses(outer.peekLast()); return result == '1'; } /** * 对圆括号内的子表达式求值 * * @param list * @return */ char evalWithinParentheses(LinkedList<Character> list) { char operand = list.pop(); if (operand != '0' && operand != '1') { syntaxError(); } // 处理! while (!list.isEmpty()) { char curr = list.pop(); if (curr == '!') { operand = operand == '0' ? '1' : '0'; } else if (curr == '#') { break; } else { if (operand == '0' || operand == '1') { list.addLast(operand); list.addLast(curr); operand = '\0'; } else { operand = curr; } } } list.addLast(operand); // 处理& list.addLast('#'); operand = list.pop(); while (!list.isEmpty()) { char curr = list.pop(); if (curr == '&') { char c = list.pop(); operand = (operand == '1' && c == '1') ? '1' : '0'; } else if (curr == '#') { break; } else { if (operand == '0' || operand == '1') { list.addLast(operand); list.addLast(curr); operand = '\0'; } else { operand = curr; } } } list.addLast(operand); // 处理| operand = '0'; while (!list.isEmpty() && (operand = list.pop()) != '1') ; return operand; } void syntaxError() { throw new IllegalArgumentException("语法错误, 仅支持括号(),非!,与&,或|这几个运算符, 优先级依次递减."); } void syntaxError(String s) { throw new IllegalArgumentException("语法错误: " + s); } void support(char c) { if (!all.contains(c)) { syntaxError("不支持字符 " + c); } } void supportFollowing(char prev, char c) { if (!following.get(prev).contains(c)) { syntaxError("prev=" + prev + ", c=" + c); } } } }
try { RpcCommand rpcCommand = JSONObject.parseObject(commandString, RpcCommand.class); if (rpcCommand != null) { rpcCommand.sort(); } return rpcCommand; } catch (Exception e) { LoggerUtil.error("指令配置错误:不是合法的JSON格式!"); return null; }
1,718
100
1,818
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/AbstractExporter.java
AbstractExporter
getRuntimeInfo
class AbstractExporter<T> extends AbstractNode implements Exporter<T> { protected Provider<T> provider; public AbstractExporter(Provider<T> provider, URL url) { super(url); this.provider = provider; } public Provider<T> getProvider() { return provider; } @Override public String desc() { return "[" + this.getClass().getSimpleName() + "] url=" + url; } /** * update real listened port * * @param port real listened port */ protected void updateRealServerPort(int port) { getUrl().setPort(port); } @Override public Map<String, Object> getRuntimeInfo() {<FILL_FUNCTION_BODY>} }
Map<String, Object> infos = new HashMap<>(); infos.put(RuntimeInfoKeys.URL_KEY, url.toFullStr()); infos.put(RuntimeInfoKeys.STATE_KEY, init ? "init" : "unInit"); infos.put(RuntimeInfoKeys.PROVIDER_KEY, provider.getRuntimeInfo()); return infos;
208
94
302
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.rpc.URL getUrl() ,public synchronized void init() ,public boolean isAvailable() ,public void setAvailable(boolean) <variables>protected volatile boolean available,protected volatile boolean init,protected com.weibo.api.motan.rpc.URL url
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/AbstractNode.java
AbstractNode
init
class AbstractNode implements Node { protected URL url; protected volatile boolean init = false; protected volatile boolean available = false; public AbstractNode(URL url) { this.url = url; } @Override public synchronized void init() {<FILL_FUNCTION_BODY>} protected abstract boolean doInit(); @Override public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } public URL getUrl() { return url; } }
if (init) { LoggerUtil.warn(this.getClass().getSimpleName() + " node already init: " + desc()); return; } boolean result = doInit(); if (!result) { LoggerUtil.error(this.getClass().getSimpleName() + " node init Error: " + desc()); throw new MotanFrameworkException(this.getClass().getSimpleName() + " node init Error: " + desc(), MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } else { LoggerUtil.info(this.getClass().getSimpleName() + " node init Success: " + desc()); init = true; available = true; }
153
182
335
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/AbstractProvider.java
AbstractProvider
lookupMethod
class AbstractProvider<T> implements Provider<T> { protected Class<T> clz; protected URL url; protected boolean alive = false; protected boolean close = false; protected Map<String, Method> methodMap = new HashMap<>(); public AbstractProvider(URL url, Class<T> clz) { this.url = url; this.clz = clz; } @Override public Response call(Request request) { MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_BEFORE_BIZ); Response response = invoke(request); MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_AFTER_BIZ); return response; } protected abstract Response invoke(Request request); @Override public void init() { alive = true; } @Override public void destroy() { alive = false; close = true; } @Override public boolean isAvailable() { return alive; } @Override public String desc() { if (url != null) { return url.toString(); } return null; } @Override public URL getUrl() { return url; } @Override public Class<T> getInterface() { return clz; } @Override public Method lookupMethod(String methodName, String methodDesc) {<FILL_FUNCTION_BODY>} protected void initMethodMap(Class<?> clz) { Method[] methods = clz.getMethods(); List<String> dupList = new ArrayList<>(); for (Method method : methods) { String methodDesc = ReflectUtil.getMethodDesc(method); methodMap.put(methodDesc, method); if (methodMap.get(method.getName()) == null) { methodMap.put(method.getName(), method); } else { dupList.add(method.getName()); } } if (!dupList.isEmpty()) { for (String removedName : dupList) { methodMap.remove(removedName); } } } }
Method method; String fullMethodName = ReflectUtil.getMethodDesc(methodName, methodDesc); method = methodMap.get(fullMethodName); if (method == null && StringUtils.isBlank(methodDesc)) { method = methodMap.get(methodName); if (method == null) { method = methodMap.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1)); } } return method;
566
126
692
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/AbstractReferer.java
AbstractReferer
call
class AbstractReferer<T> extends AbstractNode implements Referer<T> { protected Class<T> clz; protected AtomicInteger activeRefererCount = new AtomicInteger(0); protected URL serviceUrl; public AbstractReferer(Class<T> clz, URL url) { super(url); this.clz = clz; this.serviceUrl = url; } public AbstractReferer(Class<T> clz, URL url, URL serviceUrl) { super(url); this.clz = clz; this.serviceUrl = serviceUrl; } @Override public Class<T> getInterface() { return clz; } @Override public Response call(Request request) {<FILL_FUNCTION_BODY>} @Override public int activeRefererCount() { return activeRefererCount.get(); } protected void incrActiveCount(Request request) { activeRefererCount.incrementAndGet(); } protected void decrActiveCount(Request request, Response response) { activeRefererCount.decrementAndGet(); } protected abstract Response doCall(Request request); @Override public String desc() { return "[" + this.getClass().getSimpleName() + "] url=" + url; } @Override public URL getServiceUrl() { return serviceUrl; } @Override public Map<String, Object> getRuntimeInfo() { Map<String, Object> infos = new HashMap<>(); infos.put(RuntimeInfoKeys.CURRENT_CALL_COUNT_KEY, activeRefererCount.get()); return infos; } }
if (!isAvailable()) { throw new MotanFrameworkException(this.getClass().getSimpleName() + " call Error: node is not available, url=" + url.getUri() + " " + MotanFrameworkUtil.toString(request)); } incrActiveCount(request); Response response = null; try { response = doCall(request); return response; } finally { decrActiveCount(request, response); }
442
121
563
<methods>public void <init>(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.rpc.URL getUrl() ,public synchronized void init() ,public boolean isAvailable() ,public void setAvailable(boolean) <variables>protected volatile boolean available,protected volatile boolean init,protected com.weibo.api.motan.rpc.URL url
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/ApplicationInfo.java
ApplicationInfo
addService
class ApplicationInfo { public static final String STATISTIC = "statisitic"; public static final ConcurrentMap<String, Application> applications = new ConcurrentHashMap<String, Application>(); public static Application getApplication(URL url) { String app = url.getApplication(); String module = url.getModule(); Application application = applications.get(app + "_" + module); if (application == null) { applications.putIfAbsent(app + "_" + module, new Application(app, module)); application = applications.get(app + "_" + module); } return application; } public static void addService(URL url) {<FILL_FUNCTION_BODY>} }
String app = url.getApplication(); String module = url.getModule(); Application application = applications.get(app + "_" + module); if (application == null) { applications.putIfAbsent(app + "_" + module, new Application(app, module)); }
182
74
256
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/DefaultCallbackHolder.java
DefaultCallbackHolder
onFinish
class DefaultCallbackHolder implements Callbackable { private final List<Pair<Runnable, Executor>> taskList = new ArrayList<>(); private volatile boolean isFinished = false; public void addFinishCallback(Runnable runnable, Executor executor) { if (!isFinished) { synchronized (this) { if (!isFinished) { taskList.add(Pair.of(runnable, executor)); return; } } } process(runnable, executor); } @Override public void onFinish() {<FILL_FUNCTION_BODY>} private void process(Runnable runnable, Executor executor) { if (executor == null) { executor = AsyncUtil.getDefaultCallbackExecutor(); } try { executor.execute(runnable); } catch (Exception e) { LoggerUtil.error("Callbackable response exec callback task error, e: ", e); } } }
if (!isFinished) { synchronized (this) { if (!isFinished) { for (Pair<Runnable, Executor> pair : taskList) { process(pair.getKey(), pair.getValue()); } isFinished = true; } } }
263
81
344
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/DefaultProvider.java
DefaultProvider
invoke
class DefaultProvider<T> extends AbstractProvider<T> { protected T proxyImpl; protected boolean isAsync = false; public DefaultProvider(T proxyImpl, URL url, Class<T> clz) { super(url, clz); this.proxyImpl = proxyImpl; Class<?> asyncInterface = null; try { asyncInterface = Class.forName(clz.getName() + "Async"); if (asyncInterface.isInterface() && asyncInterface.isAssignableFrom(proxyImpl.getClass())) { isAsync = true; } } catch (Exception ignore) { } if (isAsync) { initMethodMap(asyncInterface); } else { initMethodMap(clz); } } @Override public T getImpl() { return proxyImpl; } @Override public Response invoke(Request request) {<FILL_FUNCTION_BODY>} @Override public Map<String, Object> getRuntimeInfo() { Map<String, Object> infos = new HashMap<>(); infos.put(RuntimeInfoKeys.SERVICE_KEY, clz.getName()); infos.put(RuntimeInfoKeys.IS_ASYNC_KEY, isAsync); infos.put(RuntimeInfoKeys.IMPL_CLASS_KEY, proxyImpl.getClass().getName()); return infos; } }
DefaultResponse response = new DefaultResponse(); String methodName = request.getMethodName(); if (isAsync) { // change to async method methodName += "Async"; } Method method = lookupMethod(methodName, request.getParamtersDesc()); if (method == null) { LoggerUtil.error("can not found rpc method:" + request.getMethodName() + ", paramDesc:" + request.getParamtersDesc() + ", service:" + request.getInterfaceName()); MotanServiceException exception = new MotanServiceException("Service method not exist: " + request.getInterfaceName() + "." + request.getMethodName() + "(" + request.getParamtersDesc() + ")", MotanErrorMsgConstant.SERVICE_UNFOUND, false); response.setException(exception); return response; } boolean defaultThrowExceptionStack = URLParamType.transExceptionStack.getBooleanValue(); try { Object value = method.invoke(proxyImpl, request.getArguments()); if (value instanceof ResponseFuture) { // async method return (Response) value; } response.setValue(value); } catch (Exception e) { if (e.getCause() != null) { response.setException(new MotanBizException("provider call process error", e.getCause())); } else { response.setException(new MotanBizException("provider call process error", e)); } // not print stack in error log when exception declared in method boolean logException = true; for (Class<?> clazz : method.getExceptionTypes()) { if (clazz.isInstance(response.getException().getCause())) { logException = false; defaultThrowExceptionStack = false; break; } } if (logException) { LoggerUtil.error("Exception caught when during method invocation. request:" + request, e); } else { LoggerUtil.info("Exception caught when during method invocation. request:" + request + ", exception:" + response.getException().getCause().toString()); } } catch (Throwable t) { // 如果服务发生Error,将Error转化为Exception,防止拖垮调用方 if (t.getCause() != null) { response.setException(new MotanServiceException("provider has encountered a fatal error!", t.getCause())); } else { response.setException(new MotanServiceException("provider has encountered a fatal error!", t)); } //对于Throwable,也记录日志 LoggerUtil.error("Exception caught when during method invocation. request:" + request, t); } if (response.getException() != null) { //是否传输业务异常栈 boolean transExceptionStack = this.url.getBooleanParameter(URLParamType.transExceptionStack.getName(), defaultThrowExceptionStack); if (!transExceptionStack) {//不传输业务异常栈 ExceptionUtil.setMockStackTrace(response.getException().getCause()); } } return response;
356
771
1,127
<methods>public void <init>(com.weibo.api.motan.rpc.URL, Class<T>) ,public com.weibo.api.motan.rpc.Response call(com.weibo.api.motan.rpc.Request) ,public java.lang.String desc() ,public void destroy() ,public Class<T> getInterface() ,public com.weibo.api.motan.rpc.URL getUrl() ,public void init() ,public boolean isAvailable() ,public java.lang.reflect.Method lookupMethod(java.lang.String, java.lang.String) <variables>protected boolean alive,protected boolean close,protected Class<T> clz,protected Map<java.lang.String,java.lang.reflect.Method> methodMap,protected com.weibo.api.motan.rpc.URL url
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/DefaultRequest.java
DefaultRequest
toString
class DefaultRequest implements Request, Traceable, Serializable { private static final long serialVersionUID = 1168814620391610215L; private String interfaceName; private String methodName; private String paramtersDesc; private Object[] arguments; private Map<String, String> attachments; private int retries = 0; private long requestId; private byte rpcProtocolVersion = RpcProtocolVersion.VERSION_1.getVersion(); private int serializeNumber = 0;// default serialization is hession2 private TraceableContext traceableContext = new TraceableContext(); @Override public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } @Override public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } @Override public String getParamtersDesc() { return paramtersDesc; } public void setParamtersDesc(String paramtersDesc) { this.paramtersDesc = paramtersDesc; } @Override public Object[] getArguments() { return arguments; } public void setArguments(Object[] arguments) { this.arguments = arguments; } @Override public Map<String, String> getAttachments() { return attachments != null ? attachments : Collections.<String, String>emptyMap(); } public void setAttachments(Map<String, String> attachments) { this.attachments = attachments; } @Override public void setAttachment(String key, String value) { if (this.attachments == null) { this.attachments = new HashMap<>(); } this.attachments.put(key, value); } @Override public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public int getRetries() { return retries; } @Override public void setRetries(int retries) { this.retries = retries; } @Override public byte getRpcProtocolVersion() { return rpcProtocolVersion; } @Override public void setRpcProtocolVersion(byte rpcProtocolVersion) { this.rpcProtocolVersion = rpcProtocolVersion; } @Override public void setSerializeNumber(int number) { this.serializeNumber = number; } @Override public int getSerializeNumber() { return serializeNumber; } public TraceableContext getTraceableContext() { return traceableContext; } }
return interfaceName + "." + methodName + "(" + paramtersDesc + ") requestId=" + requestId;
787
31
818
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/DefaultResponse.java
DefaultResponse
updateCallbackHolderFromResponse
class DefaultResponse implements Response, Traceable, Callbackable, Serializable { private static final long serialVersionUID = 4281186647291615871L; private Object value; private Exception exception; private long requestId; private long processTime; private int timeout; private Map<String, String> attachments;// rpc协议版本兼容时可以回传一些额外的信息 private byte rpcProtocolVersion = RpcProtocolVersion.VERSION_1.getVersion(); private int serializeNumber = 0;// default serialization is hessian2 private TraceableContext traceableContext = new TraceableContext(); private Callbackable callbackHolder = new DefaultCallbackHolder(); public DefaultResponse() { } public DefaultResponse(long requestId) { this.requestId = requestId; } // for client end. Blocking to get value or throw exception public DefaultResponse(Response response) { this.value = response.getValue(); this.exception = response.getException(); this.requestId = response.getRequestId(); this.processTime = response.getProcessTime(); this.timeout = response.getTimeout(); this.rpcProtocolVersion = response.getRpcProtocolVersion(); this.serializeNumber = response.getSerializeNumber(); this.attachments = response.getAttachments(); updateTraceableContextFromResponse(response); } public DefaultResponse(Object value) { this.value = value; } public DefaultResponse(Object value, long requestId) { this.value = value; this.requestId = requestId; } public static DefaultResponse fromServerEndResponseFuture(ResponseFuture responseFuture) { DefaultResponse response = new DefaultResponse(); if (responseFuture.getException() != null) { // change to biz exception response.setException(new MotanBizException("provider call process error", responseFuture.getException())); } else { response.setValue(responseFuture.getValue()); } response.updateTraceableContextFromResponse(responseFuture); response.updateCallbackHolderFromResponse(responseFuture); if (!responseFuture.getAttachments().isEmpty()) { // avoid setting Collections.EMPTY_MAP to new response response.attachments = responseFuture.getAttachments(); } return response; } @Override public Object getValue() { if (exception != null) { throw (exception instanceof RuntimeException) ? (RuntimeException) exception : new MotanServiceException( exception.getMessage(), exception); } return value; } public void setValue(Object value) { this.value = value; } @Override public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } @Override public long getRequestId() { return requestId; } public void setRequestId(long requestId) { this.requestId = requestId; } @Override public long getProcessTime() { return processTime; } @Override public void setProcessTime(long time) { this.processTime = time; } @Override public int getTimeout() { return this.timeout; } @Override public Map<String, String> getAttachments() { return attachments != null ? attachments : Collections.emptyMap(); } public void setAttachments(Map<String, String> attachments) { this.attachments = attachments; } @Override public void setAttachment(String key, String value) { if (this.attachments == null) { this.attachments = new HashMap<>(); } this.attachments.put(key, value); } @Override public byte getRpcProtocolVersion() { return rpcProtocolVersion; } @Override public void setRpcProtocolVersion(byte rpcProtocolVersion) { this.rpcProtocolVersion = rpcProtocolVersion; } @Override public void setSerializeNumber(int number) { this.serializeNumber = number; } @Override public int getSerializeNumber() { return serializeNumber; } /** * 未指定线程池时,统一使用默认线程池执行。默认线程池满时采用丢弃策略,不保证任务一定会被执行。 * 如果默认线程池不满足需求时,可以自行携带executor。 * * @param runnable 准备在response on finish时执行的任务 * @param executor 指定执行任务的线程池 */ public void addFinishCallback(Runnable runnable, Executor executor) { callbackHolder.addFinishCallback(runnable, executor); } @Override public void onFinish() { callbackHolder.onFinish(); } @Override public TraceableContext getTraceableContext() { return traceableContext; } @Override public Callbackable getCallbackHolder() { return callbackHolder; } // only for constructor private void updateTraceableContextFromResponse(Response response) { if (response instanceof Traceable) { TraceableContext tempTraceableContext = ((Traceable) response).getTraceableContext(); if (tempTraceableContext != null) { traceableContext = tempTraceableContext; } } } // only for constructor private void updateCallbackHolderFromResponse(Response response) {<FILL_FUNCTION_BODY>} }
if (response instanceof Callbackable) { Callbackable holder = ((Callbackable) response).getCallbackHolder(); if (holder != null) { callbackHolder = holder; } }
1,467
54
1,521
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/RefererSupports.java
RefererSupports
getServerPorts
class RefererSupports { private static ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10); // 正常情况下请求超过1s已经是能够忍耐的极限值了,delay 1s进行destroy private static final int DELAY_TIME = 1000; static{ ShutDownHook.registerShutdownHook(new Closable() { @Override public void close() { if(!scheduledExecutor.isShutdown()){ scheduledExecutor.shutdown(); } } }); } public static <T> void delayDestroy(final List<Referer<T>> referers) { if (referers == null || referers.isEmpty()) { return; } scheduledExecutor.schedule(new Runnable() { @Override public void run() { for (Referer<?> referer : referers) { try { referer.destroy(); } catch (Exception e) { LoggerUtil.error("RefererSupports delayDestroy Error: url=" + referer.getUrl().getUri(), e); } } } }, DELAY_TIME, TimeUnit.MILLISECONDS); LoggerUtil.info("RefererSupports delayDestroy Success: size={} service={} urls={}", referers.size(), referers.get(0).getUrl() .getIdentity(), getServerPorts(referers)); } private static <T> String getServerPorts(List<Referer<T>> referers) {<FILL_FUNCTION_BODY>} }
if (referers == null || referers.isEmpty()) { return "[]"; } StringBuilder builder = new StringBuilder(); builder.append("["); for (Referer<T> referer : referers) { builder.append(referer.getUrl().getServerPortStr()).append(","); } builder.setLength(builder.length() - 1); builder.append("]"); return builder.toString();
411
118
529
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/RpcContext.java
RpcContext
getRequestId
class RpcContext { private static final ThreadLocal<RpcContext> LOCAL_CONTEXT = new ThreadLocal<RpcContext>() { @Override protected RpcContext initialValue() { return new RpcContext(); } }; private Map<Object, Object> attributes = new HashMap<Object, Object>(); private Map<String, String> attachments = new HashMap<String, String>();// attachment in rpc context. not same with request's attachments private Request request; private Response response; private String clientRequestId = null; public static RpcContext getContext() { return LOCAL_CONTEXT.get(); } /** * init new rpcContext with request * * @param request * @return */ public static RpcContext init(Request request) { RpcContext context = new RpcContext(); if (request != null) { context.setRequest(request); context.setClientRequestId(request.getAttachments().get(URLParamType.requestIdFromClient.getName())); } LOCAL_CONTEXT.set(context); return context; } public static RpcContext init() { RpcContext context = new RpcContext(); LOCAL_CONTEXT.set(context); return context; } public static void destroy() { LOCAL_CONTEXT.remove(); } /** * clientRequestId > request.id * * @return */ public String getRequestId() {<FILL_FUNCTION_BODY>} public void putAttribute(Object key, Object value) { attributes.put(key, value); } public Object getAttribute(Object key) { return attributes.get(key); } public void removeAttribute(Object key) { attributes.remove(key); } public Map<Object, Object> getAttributes() { return attributes; } public void setRpcAttachment(String key, String value) { attachments.put(key, value); } /** * get attachments from rpccontext only. not from request or response * * @param key * @return */ public String getRpcAttachment(String key) { return attachments.get(key); } public void removeRpcAttachment(String key) { attachments.remove(key); } public Map<String, String> getRpcAttachments() { return attachments; } public Request getRequest() { return request; } public void setRequest(Request request) { this.request = request; } public Response getResponse() { return response; } public void setResponse(Response response) { this.response = response; } public String getClientRequestId() { return clientRequestId; } public void setClientRequestId(String clientRequestId) { this.clientRequestId = clientRequestId; } }
if (clientRequestId != null) { return clientRequestId; } else { return request == null ? null : String.valueOf(request.getRequestId()); }
787
50
837
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/RpcStats.java
RpcStats
getMethodStat
class RpcStats { private static final String SEPERATOR_METHOD_AND_PARAM = "|"; private static ConcurrentHashMap<String, StatInfo> serviceStat = new ConcurrentHashMap<String, RpcStats.StatInfo>(); private static ConcurrentHashMap<String, ConcurrentHashMap<String, StatInfo>> methodStat = new ConcurrentHashMap<String, ConcurrentHashMap<String, StatInfo>>(); private static ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1); static{ ShutDownHook.registerShutdownHook(new Closable() { @Override public void close() { if(!scheduledExecutor.isShutdown()){ scheduledExecutor.shutdown(); } } }); } /** * call before invoke the request * * @param url * @param request */ public static void beforeCall(URL url, Request request) { String uri = url.getUri(); onBeforeCall(getServiceStat(uri)); onBeforeCall(getMethodStat(uri, request.getMethodName(), request.getParamtersDesc())); } /** * call after invoke the request * * @param url * @param request * @param success * @param procTimeMills */ public static void afterCall(URL url, Request request, boolean success, long procTimeMills) { String uri = url.getUri(); onAfterCall(getServiceStat(uri), success, procTimeMills); onAfterCall(getMethodStat(uri, request.getMethodName(), request.getParamtersDesc()), success, procTimeMills); } public static StatInfo getServiceStat(URL url) { return getServiceStat(url.getUri()); } public static StatInfo getMethodStat(URL url, Request request) { return getMethodStat(url.getUri(), request.getMethodName(), request.getParamtersDesc()); } private static StatInfo getServiceStat(String uri) { StatInfo stat = serviceStat.get(uri); if (stat == null) { stat = new StatInfo(); serviceStat.putIfAbsent(uri, stat); stat = serviceStat.get(uri); } return stat; } private static StatInfo getMethodStat(String uri, String methodName, String methodParaDesc) {<FILL_FUNCTION_BODY>} private static void onBeforeCall(StatInfo statInfo) { statInfo.activeCount.incrementAndGet(); } private static void onAfterCall(StatInfo statInfo, boolean success, long procTimeMills) { statInfo.activeCount.decrementAndGet(); if (!success) { statInfo.failCount.incrementAndGet(); } statInfo.totalCountTime.inc(1, procTimeMills); statInfo.latestCountTime.inc(1, procTimeMills); } private static void startCleaner() { } private static void cleanLatestStat() { if (serviceStat.size() == 0) { return; } for (StatInfo si : serviceStat.values()) { si.resetLatestStat(); } } public static class StatInfo { private AtomicInteger activeCount = new AtomicInteger(); private AtomicLong failCount = new AtomicLong(); private CountTime totalCountTime = new CountTime(); private CountTime latestCountTime = new CountTime(); public int getActiveCount() { return activeCount.get(); } public long getFailCount() { return failCount.get(); } public CountTime getTotalCountTime() { return totalCountTime; } public CountTime getLatestCountTime() { return latestCountTime; } public void resetLatestStat() { latestCountTime.reset(); } } public static class CountTime { private AtomicLong count; private AtomicLong timeMills; public CountTime() { count = new AtomicLong(); timeMills = new AtomicLong(); } private void inc(int incCount, long incTimeMills) { count.getAndAdd(incCount); timeMills.getAndAdd(incTimeMills); } public long getCount() { return count.get(); } public void reset() { count.set(0); timeMills.set(0); } } }
ConcurrentHashMap<String, StatInfo> sstats = methodStat.get(uri); if (sstats == null) { sstats = new ConcurrentHashMap<String, StatInfo>(); methodStat.putIfAbsent(uri, sstats); sstats = methodStat.get(uri); } String methodNameAndParams = methodName + SEPERATOR_METHOD_AND_PARAM + methodParaDesc; StatInfo mstat = sstats.get(methodNameAndParams); if (mstat == null) { mstat = new StatInfo(); sstats.putIfAbsent(methodNameAndParams, mstat); mstat = sstats.get(methodNameAndParams); } return mstat;
1,164
186
1,350
<no_super_class>
weibocom_motan
motan/motan-core/src/main/java/com/weibo/api/motan/rpc/TraceableContext.java
TraceableContext
toString
class TraceableContext { protected AtomicLong receiveTime = new AtomicLong(); protected AtomicLong sendTime = new AtomicLong(); protected Map<String, String> traceInfoMap = new ConcurrentHashMap<>(); public long getReceiveTime() { return receiveTime.get(); } public void setReceiveTime(long receiveTime) { this.receiveTime.compareAndSet(0, receiveTime); } public long getSendTime() { return sendTime.get(); } public void setSendTime(long sendTime) { this.sendTime.compareAndSet(0, sendTime); } public void addTraceInfo(String key, String value) { traceInfoMap.put(key, value); } public String getTraceInfo(String key) { return traceInfoMap.get(key); } public Map<String, String> getTraceInfoMap() { return traceInfoMap; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "send: " + sendTime + ", receive: " + receiveTime + ", info: " + JSON.toJSONString(traceInfoMap);
277
37
314
<no_super_class>