Skip to content

Commit

Permalink
Implement browse retries for minimal mdns (#15813)
Browse files Browse the repository at this point in the history
* Implement browse retries for minimal

- adds ability to track browse requests in the ActiveResolveAttempts class
- Changes minimal impl to retry browse attempts using the same mechanism
  as resolves
- adds tests
- moves the ActiveResolveAttempts file out of minimal - reasoning:
  althought this is used only by minimal, other impls could use
  this and the minimal folder was meant to not include any Matter
  specific details like peer id or discovery filter.
- adds tests.
- tested by running a discover where there are no matter devices
  advertising

* Restyled by clang-format

* Address comments.

Co-authored-by: Restyled.io <[email protected]>
  • Loading branch information
2 people authored and pull[bot] committed Mar 18, 2022
1 parent 43dd6ec commit 3026841
Show file tree
Hide file tree
Showing 11 changed files with 770 additions and 458 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ void ActiveResolveAttempts::Reset()
{
for (auto & item : mRetryQueue)
{
item.peerId.SetNodeId(kUndefinedNodeId);
item.attempt.Clear();
}
}

void ActiveResolveAttempts::Complete(const PeerId & peerId)
{
for (auto & item : mRetryQueue)
{
if (item.peerId == peerId)
if (item.attempt.Matches(peerId))
{
item.peerId.SetNodeId(kUndefinedNodeId);
item.attempt.Clear();
return;
}
}
Expand All @@ -53,7 +53,31 @@ void ActiveResolveAttempts::Complete(const PeerId & peerId)
ChipLogProgress(Discovery, "Discovered node without a pending query");
}

void ActiveResolveAttempts::MarkPending(const PeerId & peerId)
void ActiveResolveAttempts::Complete(const chip::Dnssd::DiscoveredNodeData & data)
{
for (auto & item : mRetryQueue)
{
if (item.attempt.Matches(data))
{
item.attempt.Clear();
return;
}
}
}

void ActiveResolveAttempts::MarkPending(const chip::PeerId & peerId)
{
ScheduledAttempt attempt(peerId, /* firstSend */ true);
MarkPending(attempt);
}

void ActiveResolveAttempts::MarkPending(const chip::Dnssd::DiscoveryFilter & filter, const chip::Dnssd::DiscoveryType type)
{
ScheduledAttempt attempt(filter, type, /* firstSend */ true);
MarkPending(attempt);
}

void ActiveResolveAttempts::MarkPending(const ScheduledAttempt & attempt)
{
// Strategy when picking the peer id to use:
// 1 if a matching peer id is already found, use that one
Expand All @@ -66,27 +90,27 @@ void ActiveResolveAttempts::MarkPending(const PeerId & peerId)

for (size_t i = 1; i < kRetryQueueSize; i++)
{
if (entryToUse->peerId == peerId)
if (entryToUse->attempt.Matches(attempt))
{
break; // best match possible
}

RetryEntry * entry = mRetryQueue + i;

// Rule 1: peer id match always matches
if (entry->peerId == peerId)
// Rule 1: attempt match always matches
if (entry->attempt.Matches(attempt))
{
entryToUse = entry;
continue;
}

// Rule 2: select unused entries
if ((entryToUse->peerId.GetNodeId() != kUndefinedNodeId) && (entry->peerId.GetNodeId() == kUndefinedNodeId))
if (!entryToUse->attempt.IsEmpty() && entry->attempt.IsEmpty())
{
entryToUse = entry;
continue;
}
else if (entryToUse->peerId.GetNodeId() == kUndefinedNodeId)
else if (entryToUse->attempt.IsEmpty())
{
continue;
}
Expand All @@ -106,7 +130,7 @@ void ActiveResolveAttempts::MarkPending(const PeerId & peerId)
}
}

if ((entryToUse->peerId.GetNodeId() != kUndefinedNodeId) && (entryToUse->peerId != peerId))
if ((!entryToUse->attempt.IsEmpty()) && (!entryToUse->attempt.Matches(attempt)))
{
// TODO: node was evicted here, if/when resolution failures are
// supported this could be a place for error callbacks
Expand All @@ -118,8 +142,7 @@ void ActiveResolveAttempts::MarkPending(const PeerId & peerId)
ChipLogError(Discovery, "Re-using pending resolve entry before reply was received.");
}

entryToUse->peerId = peerId;
entryToUse->firstSend = true;
entryToUse->attempt = attempt;
entryToUse->queryDueTime = mClock->GetMonotonicTimestamp();
entryToUse->nextRetryDelay = System::Clock::Seconds16(1);
}
Expand All @@ -132,7 +155,7 @@ Optional<System::Clock::Timeout> ActiveResolveAttempts::GetTimeUntilNextExpected

for (auto & entry : mRetryQueue)
{
if (entry.peerId.GetNodeId() == kUndefinedNodeId)
if (entry.attempt.IsEmpty())
{
continue;
}
Expand All @@ -153,13 +176,13 @@ Optional<System::Clock::Timeout> ActiveResolveAttempts::GetTimeUntilNextExpected
return minDelay;
}

Optional<ActiveResolveAttempts::ScheduledResolve> ActiveResolveAttempts::NextScheduledPeer()
Optional<ActiveResolveAttempts::ScheduledAttempt> ActiveResolveAttempts::NextScheduled()
{
chip::System::Clock::Timestamp now = mClock->GetMonotonicTimestamp();

for (auto & entry : mRetryQueue)
{
if (entry.peerId.GetNodeId() == kUndefinedNodeId)
if (entry.attempt.IsEmpty())
{
continue; // not a pending item
}
Expand All @@ -172,20 +195,20 @@ Optional<ActiveResolveAttempts::ScheduledResolve> ActiveResolveAttempts::NextSch
if (entry.nextRetryDelay > kMaxRetryDelay)
{
ChipLogError(Discovery, "Timeout waiting for mDNS resolution.");
entry.peerId.SetNodeId(kUndefinedNodeId);
entry.attempt.Clear();
continue;
}

entry.queryDueTime = now + entry.nextRetryDelay;
entry.nextRetryDelay *= 2;

ScheduledResolve result(entry);
entry.firstSend = false;
Optional<ScheduledAttempt> attempt = MakeOptional(entry.attempt);
entry.attempt.firstSend = false;

return Optional<ScheduledResolve>::Value(result);
return attempt;
}

return Optional<ScheduledResolve>::Missing();
return Optional<ScheduledAttempt>::Missing();
}

} // namespace Minimal
Expand Down
195 changes: 195 additions & 0 deletions src/lib/dnssd/ActiveResolveAttempts.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#pragma once

#include <cstddef>
#include <cstdint>

#include <lib/core/Optional.h>
#include <lib/core/PeerId.h>
#include <lib/dnssd/Resolver.h>
#include <system/SystemClock.h>

namespace mdns {
namespace Minimal {

/// Keeps track of active resolve attempts
///
/// Maintains a list of 'pending mdns resolve queries' and provides operations
/// for:
/// - add/remove to the list
/// - figuring out a 'next query time' for items in the list
/// - iterating through the 'schedule now' items of the list
///
class ActiveResolveAttempts
{
public:
static constexpr size_t kRetryQueueSize = 4;
static constexpr chip::System::Clock::Timeout kMaxRetryDelay = chip::System::Clock::Seconds16(16);

struct ScheduledAttempt
{
enum AttemptType
{
kInvalid,
kResolve,
kBrowse,
};

ScheduledAttempt() : attemptType(kInvalid) {}
ScheduledAttempt(const chip::PeerId & peer, bool first) : attemptType(kResolve), peerId(peer), firstSend(first) {}
ScheduledAttempt(const chip::Dnssd::DiscoveryFilter discoveryFilter, const chip::Dnssd::DiscoveryType type, bool first) :
attemptType(kBrowse), browse(discoveryFilter, type), firstSend(first)
{}
bool operator==(const ScheduledAttempt & other) const { return Matches(other) && other.firstSend == firstSend; }
bool Matches(const ScheduledAttempt & other) const
{
if (other.attemptType != attemptType)
{
return false;
}
switch (attemptType)
{
case kInvalid:
return true;
case kBrowse:
return (other.browse.filter == browse.filter && other.browse.type == browse.type);
case kResolve:
return other.peerId == peerId;
default:
return false;
}
}
bool Matches(const chip::PeerId & peer) const { return (attemptType == kResolve) && (peerId == peer); }
bool Matches(const chip::Dnssd::DiscoveredNodeData & data) const
{
if (attemptType != kBrowse)
{
return false;
}
// TODO: we should mark returned node data based on the query
if (browse.type != chip::Dnssd::DiscoveryType::kCommissionableNode)
{
// We don't currently have markers in the returned DiscoveredNodeData to differentiate these, so assume all returned
// packets match
return true;
}
switch (browse.filter.type)
{
case chip::Dnssd::DiscoveryFilterType::kNone:
return true;
case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:
return browse.filter.code == static_cast<uint64_t>((data.longDiscriminator >> 8) & 0x0F);
case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:
return browse.filter.code == data.longDiscriminator;
case chip::Dnssd::DiscoveryFilterType::kVendorId:
return browse.filter.code == data.vendorId;
case chip::Dnssd::DiscoveryFilterType::kDeviceType:
return browse.filter.code == data.deviceType;
case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:
return browse.filter.code == data.commissioningMode;
case chip::Dnssd::DiscoveryFilterType::kInstanceName:
return strncmp(browse.filter.instanceName, data.instanceName,
chip::Dnssd::Commission::kInstanceNameMaxLength + 1) == 0;
case chip::Dnssd::DiscoveryFilterType::kCommissioner:
case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:
default:
// These are for other discovery types.
return false;
}
}
bool IsEmpty() const { return attemptType == kInvalid; }
bool IsResolve() const { return attemptType == kResolve; }
bool IsBrowse() const { return attemptType == kBrowse; }
void Clear() { attemptType = kInvalid; }

// Not using Variant because it assumes a heap impl
AttemptType attemptType;
struct Browse
{
Browse(const chip::Dnssd::DiscoveryFilter discoveryFilter, const chip::Dnssd::DiscoveryType discoveryType) :
filter(discoveryFilter), type(discoveryType)
{}
chip::Dnssd::DiscoveryFilter filter;
chip::Dnssd::DiscoveryType type;
};
union
{
chip::PeerId peerId; // Peer id for resolve attempts
Browse browse;
};
// First packet send is marked separately: minMDNS logic can choose
// to first send a unicast query followed by a multicast one.
bool firstSend = false;
};

ActiveResolveAttempts(chip::System::Clock::ClockBase * clock) : mClock(clock) { Reset(); }

/// Clear out the internal queue
void Reset();

/// Mark a resolution as a success, removing it from the internal list
void Complete(const chip::PeerId & peerId);
void Complete(const chip::Dnssd::DiscoveredNodeData & data);

/// Mark that a resolution is pending, adding it to the internal list
///
/// Once this complete, this peer id will be returned immediately
/// by NextScheduled (potentially with others as well)
void MarkPending(const chip::PeerId & peerId);
void MarkPending(const chip::Dnssd::DiscoveryFilter & filter, const chip::Dnssd::DiscoveryType type);

// Get minimum time until the next pending reply is required.
//
// Returns missing if no actively tracked elements exist.
chip::Optional<chip::System::Clock::Timeout> GetTimeUntilNextExpectedResponse() const;

// Get the peer Id that needs scheduling for a query
//
// Assumes that the resolution is being sent and will apply internal
// query logic. This means:
// - internal tracking of 'next due time' will updated as 'request sent
// now'
// - there is NO sorting implied by this call. Returned value will be
// any peer that needs a new request sent
chip::Optional<ScheduledAttempt> NextScheduled();

private:
struct RetryEntry
{
ScheduledAttempt attempt;
// When a reply is expected for this item
chip::System::Clock::Timestamp queryDueTime;

// Next expected delay for sending if reply is not reached by
// 'queryDueTimeMs'
//
// Based on RFC 6762 expectations are:
// - the interval between the first two queries MUST be at least
// one second
// - the intervals between successive queries MUST increase by at
// least a factor of two
chip::System::Clock::Timeout nextRetryDelay = chip::System::Clock::Seconds16(1);
};
void MarkPending(const ScheduledAttempt & attempt);
chip::System::Clock::ClockBase * mClock;
RetryEntry mRetryQueue[kRetryQueueSize];
};

} // namespace Minimal
} // namespace mdns
2 changes: 2 additions & 0 deletions src/lib/dnssd/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ static_library("dnssd") {
]
} else if (chip_mdns == "minimal") {
sources += [
"ActiveResolveAttempts.cpp",
"ActiveResolveAttempts.h",
"Advertiser_ImplMinimalMdns.cpp",
"MinimalMdnsServer.cpp",
"MinimalMdnsServer.h",
Expand Down
26 changes: 21 additions & 5 deletions src/lib/dnssd/Resolver.h
Original file line number Diff line number Diff line change
Expand Up @@ -301,12 +301,28 @@ enum class DiscoveryFilterType : uint8_t
struct DiscoveryFilter
{
DiscoveryFilterType type;
uint64_t code;
const char * instanceName;
uint64_t code = 0;
const char * instanceName = nullptr;
DiscoveryFilter() : type(DiscoveryFilterType::kNone), code(0) {}
DiscoveryFilter(DiscoveryFilterType newType) : type(newType) {}
DiscoveryFilter(DiscoveryFilterType newType, uint64_t newCode) : type(newType), code(newCode) {}
DiscoveryFilter(DiscoveryFilterType newType, const char * newInstanceName) : type(newType), instanceName(newInstanceName) {}
DiscoveryFilter(const DiscoveryFilterType newType) : type(newType) {}
DiscoveryFilter(const DiscoveryFilterType newType, uint64_t newCode) : type(newType), code(newCode) {}
DiscoveryFilter(const DiscoveryFilterType newType, const char * newInstanceName) : type(newType), instanceName(newInstanceName)
{}
bool operator==(const DiscoveryFilter & other) const
{
if (type != other.type)
{
return false;
}
if (type == DiscoveryFilterType::kInstanceName)
{
return (instanceName != nullptr) && (other.instanceName != nullptr) && (strcmp(instanceName, other.instanceName) == 0);
}
else
{
return code == other.code;
}
}
};
enum class DiscoveryType
{
Expand Down
Loading

0 comments on commit 3026841

Please sign in to comment.