repo
stringlengths 1
152
⌀ | file
stringlengths 15
205
| code
stringlengths 0
41.6M
| file_length
int64 0
41.6M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 90
values |
---|---|---|---|---|---|---|
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/getting-started-basic-embed/auto-load-multi-video.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Auto-player instantiation example</title>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<style>
video {
width: 320px;
height: 180px;
}
</style>
<body>
<div>
<video autoplay controls>
<source src="http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd" type="application/dash+xml"/>
</video>
<br/>This is a dash.js player that should autostart<p/>
</div>
<div>
<video autoplay controls="true">
<source src="http://mediapm.edgesuite.net/ovp/content/test/video/spacealonehd_sounas_640_300.mp4" type="video/mp4"/>
</video>
<br/>This is a standard mp4 (non-dash)<p/>
</div>
<div>
<video poster="http://mediapm.edgesuite.net/will/dash/temp/poster.png" controls="true">
<source src="http://dash.edgesuite.net/digitalprimates/fraunhofer/480p_video/heaac_2_0_with_video/Sintel/sintel_480p_heaac2_0.mpd" type="application/dash+xml"/>
</video>
<br/>This is a dash.js player that should not autostart<p/>
</div>
<div>
<video data-dashjs-player autoplay src="http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd" controls="true">
</video>
<br/>This is a dash.js player that where the manifest is defined via the src attribute of the video element.
</div>
</body>
</html>
| 1,832 | 39.733333 | 176 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/getting-started-basic-embed/auto-load-single-video-with-context-and-source.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Auto-player instantiation example, single videoElement, supplying context and source</title>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<script>
function init()
{
var player,
video,
source,
context;
// Example specifying only the video element, where the video element has a child source element
video = document.querySelector("#video1");
player = dashjs.MediaPlayerFactory.create(video);
// Example specifying only the video element, where the video element has a src attribute
video = document.querySelector("#video2");
player = dashjs.MediaPlayerFactory.create(video);
//Example adding video and source
video = document.querySelector("#video3");
source = document.createElement("source");
source.src = "http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd";
source.type = "application/dash+xml";
player = dashjs.MediaPlayerFactory.create(video, source);
//Example adding video, source and context
video = document.querySelector("#video4");
source = document.createElement("source");
source.src = "http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd";
source.type = "application/dash+xml";
context = {}
player = dashjs.MediaPlayerFactory.create(video, source, context);
}
</script>
<style>
video {
width: 320px;
height: 180px;
}
</style>
<body onload="init()">
<div>
<video id="video1" autoplay controls="true">
<source src="http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd" type="application/dash+xml"/>
</video>
<p/>
<video id="video2" autoplay src="http://dash.edgesuite.net/envivio/EnvivioDash3/manifest.mpd" controls="true"/>
<p/>
<video id="video3" autoplay controls="true">
</video>
<p/>
<video id="video4" autoplay controls="true">
</video>
</div>
</body>
</html>
| 2,585 | 37.597015 | 123 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/live-streaming/live-delay-comparison-custom-manifest.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Live delay example</title>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<script>
var player,firstLoad = true;
function init()
{
setInterval( function() {
if (player && player.isReady())
{
var d = new Date();
var seconds = d.getSeconds();
document.querySelector("#sec").innerHTML = ( seconds < 10 ? "0" : "" ) + seconds;
var minutes = d.getMinutes();
document.querySelector("#min").innerHTML = ( minutes < 10 ? "0" : "" ) + minutes;
document.querySelector("#videoDelay").innerHTML = Math.round((d.getTime()/1000) - Number(player.timeAsUTC()));
document.querySelector("#videoBuffer").innerHTML = player.getBufferLength()+ "s";
}
},1000);
}
function load(button)
{
if (!firstLoad)
{
player.reset();
}
firstLoad = false;
var url = document.getElementById("manifest").value;
player = dashjs.MediaPlayer().create();
player.getDebug().setLogToBrowserConsole(false);
switch (document.querySelector('input[name="delay"]:checked').value) {
case "segments":
player.setLiveDelayFragmentCount(document.querySelector("#delayInFragments").value);
break;
case "time":
player.setLiveDelay(document.querySelector("#delayInSeconds").value);
break;
}
player.initialize(document.querySelector("video"), url, true);
}
function delaySelect(obj)
{
switch (obj.value) {
case "default":
document.querySelector("#fragmentsEntry").style.display = "none";
document.querySelector("#secondsEntry").style.display = "none";
break;
case "segments":
document.querySelector("#fragmentsEntry").style.display = "inline";
document.querySelector("#secondsEntry").style.display = "none";
break;
case "time":
document.querySelector("#fragmentsEntry").style.display = "none";
document.querySelector("#secondsEntry").style.display = "inline";
break;
}
}
</script>
<style>
video {
width: 640px;
height: 360px;
}
#manifest {
width:300px;
}
#loadButton {
background-color: orange;
}
.clock {
color:#000; font-size: 40pt
}
#fragmentsEntry,#secondsEntry {
position:relative;
display: none;
width:50px;
}
#delayInFragments,#delayInSeconds {
width:50px;
}
</style>
<body onload="init()">
This sample allows you to explore the two MediaPlayer APIS which control live delay - setLiveDelay and setLiveDelayFragmentCount.<br/>
The first takes the desired delay in seconds. The second takes the delay in terms of fragment count.
If you use both together, setLiveDelay <br/> will take priority. If you set neither, the default delay of 4 segment durations will be used.
Note that using either method will not result in the <br/> offset exactly matching the requested setings. The final achieved delay is a function of the segment duration, when the
stream is requested <br/>with respect to the segment boundaries, as well as the amount of data the source buffers need to begin decoding.
<p/>
Enter the URL to a live (dynamic) stream manifest :
<input id="manifest" type="text" value="http://vm2.dashif.org/livesim/testpic_2s/Manifest.mpd"/><br/>
<form>
Set the live delay at stream start-up using one of the three possible methods:<br/>
<input type="radio" onclick="delaySelect(this)" name="delay" value="default" checked> Default<br/>
<input type="radio" onclick="delaySelect(this)" name="delay" value="segments"> Fragment Count<br/>
<div id="fragmentsEntry">
Enter the desired value for setLiveDelayFragmentCount in number of fragments <input id="delayInFragments" type="text"/> <br/>
</div>
<input type="radio" onclick="delaySelect(this)" name="delay" value="time"> Time in seconds<br/>
<div id="secondsEntry">
Enter the desired value for setLiveDelay in seconds <input id="delayInSeconds" type="text"/><br/>
</div>
<p/>
<input id="loadButton" type="button" value="LOAD PLAYER" onclick="load(this)"/>
<p/>
</form>
<div>
<video controls="true">
</video>
<p/>
Playhead seconds behind live: <span id="videoDelay"></span><br/>
Buffer length: <span id="videoBuffer"></span>
<div>Wall clock time
<div class="clock">
<span id="min"> </span>:<span id="sec"></span>
</div>
</div>
</div>
</body>
</html> | 5,422 | 40.396947 | 178 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/live-streaming/live-delay-comparison-using-setLiveDelay.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Live delay comparison using setLiveDelay</title>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<script>
function init()
{
var player1,player2,player3,player4,player5,player6, video;
var MPD_2S_SEGMENTS = "http://vm2.dashif.org/livesim/testpic_2s/Manifest.mpd";
var MPD_6S_SEGMENTS = "http://vm2.dashif.org/livesim/testpic_6s/Manifest.mpd";
video = document.querySelector("#video1");
player1 = dashjs.MediaPlayer().create();
player1.initialize(video,MPD_2S_SEGMENTS ,true);
player1.setLiveDelay(2);
video = document.querySelector("#video2");
player2 = dashjs.MediaPlayer().create();
player2.initialize(video,MPD_2S_SEGMENTS ,true);
player2.setLiveDelay(4);
video = document.querySelector("#video3");
player3 = dashjs.MediaPlayer().create();
player3.initialize(video,MPD_2S_SEGMENTS ,true);
player3.setLiveDelay(8);
video = document.querySelector("#video4");
player4 = dashjs.MediaPlayer().create();
player4.initialize(video,MPD_6S_SEGMENTS ,true);
player4.setLiveDelay(6);
video = document.querySelector("#video5");
player5 = dashjs.MediaPlayer().create();
player5.initialize(video,MPD_6S_SEGMENTS ,true);
player5.setLiveDelay(12);
video = document.querySelector("#video6");
player6 = dashjs.MediaPlayer().create();
player6.initialize(video,MPD_6S_SEGMENTS ,true);
player6.setLiveDelay(24);
setInterval( function() {
var d = new Date();
var seconds = d.getSeconds();
document.querySelector("#sec").innerHTML = ( seconds < 10 ? "0" : "" ) + seconds;
var minutes = d.getMinutes();
document.querySelector("#min").innerHTML = ( minutes < 10 ? "0" : "" ) + minutes;
for (var i=1;i < 7;i++)
{
var p = eval("player"+i);
document.querySelector("#video" + i + "delay").innerHTML = Math.round((d.getTime()/1000) - Number(p.timeAsUTC()));
document.querySelector("#video" + i + "buffer").innerHTML = p.getBufferLength()+ "s";
}
},1000);
}
</script>
<style>
table {
border-spacing: 10px;
}
video {
width: 320px;
height: 180px;
}
.clock { border:1px solid #333; color:#000; font-size: 60pt}
</style>
</head>
<body onload="init()">
This sample illustrates the combined effects of segment duration and the "<strong>setLiveDelay</strong>" MediaPlayer method on the latency of live stream playback.
The upper layer of videos are all playing a live stream with 2s segment duration, with setLiveDelay values of 2s, 4s, and 8s. The lower layer use 6s segment duration,
with setLiveDelay values of 6s, 12s, and 24s. Lowest latency is achieved with shorter segments and with a lower live delay value. Higher stability/robustness is achieved with a higher live delay which allows a larger forward buffer.
<table>
<tr><td>
2s segment, 2s target latency<br/>
<video id="video1" controls="true">
</video><br/>
Seconds behind live: <span id="video1delay"></span><br/>
Buffer length: <span id="video1buffer"></span>
</td><td>
2s segment, 4s target latency<br/>
<video id="video2" controls="true">
</video><br/>
Seconds behind live: <span id="video2delay"></span><br/>
Buffer length: <span id="video2buffer"></span>
</td><td>
2s segment, 8s target latency<br/>
<video id="video3" controls="true">
</video><br/>
Seconds behind live: <span id="video3delay"></span><br/>
Buffer length: <span id="video3buffer"></span>
</td>
<td>Wall clock time
<div class="clock">
<span id="min"> </span>:<span id="sec"></span>
</div>
</td></tr>
<tr><td>
6s segment, 6s target latency<br/>
<video id="video4" controls="true">
</video><br/>
Seconds behind live: <span id="video4delay"></span><br/>
Buffer length: <span id="video4buffer"></span>
</td><td>
6s segment, 12s target latency<br/>
<video id="video5" controls="true">
</video><br/>
Seconds behind live: <span id="video5delay"></span><br/>
Buffer length: <span id="video5buffer"></span>
</td><td>
6s segment, 24s target latency<br/>
<video id="video6" controls="true">
</video><br/>
Seconds behind live: <span id="video6delay"></span><br/>
Buffer length: <span id="video6buffer"></span>
</td></tr>
</table>
</body>
</html>
| 5,917 | 43.164179 | 236 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/live-streaming/live-delay-comparison-using-fragmentCount.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Live delay comparison using setLiveDelayFragmentCount</title>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<script>
function init()
{
var player1,player2,player3,player4,player5,player6, video;
var MPD_2S_SEGMENTS = "http://vm2.dashif.org/livesim/testpic_2s/Manifest.mpd";
var MPD_6S_SEGMENTS = "http://vm2.dashif.org/livesim/testpic_6s/Manifest.mpd";
video = document.querySelector("#video1");
player1 = dashjs.MediaPlayer().create();
player1.initialize(video,MPD_2S_SEGMENTS ,true);
player1.setLiveDelayFragmentCount(0);
video = document.querySelector("#video2");
player2 = dashjs.MediaPlayer().create();
player2.initialize(video,MPD_2S_SEGMENTS ,true);
player2.setLiveDelayFragmentCount(2);
video = document.querySelector("#video3");
player3 = dashjs.MediaPlayer().create();
player3.initialize(video,MPD_2S_SEGMENTS ,true);
player3.setLiveDelayFragmentCount(4);
video = document.querySelector("#video4");
player4 = dashjs.MediaPlayer().create();
player4.initialize(video,MPD_6S_SEGMENTS ,true);
player4.setLiveDelayFragmentCount(0);
video = document.querySelector("#video5");
player5 = dashjs.MediaPlayer().create();
player5.initialize(video,MPD_6S_SEGMENTS ,true);
player5.setLiveDelayFragmentCount(2);
video = document.querySelector("#video6");
player6 = dashjs.MediaPlayer().create();
player6.initialize(video,MPD_6S_SEGMENTS ,true);
player6.setLiveDelayFragmentCount(4);
setInterval( function() {
var d = new Date();
var seconds = d.getSeconds();
document.querySelector("#sec").innerHTML = ( seconds < 10 ? "0" : "" ) + seconds;
var minutes = d.getMinutes();
document.querySelector("#min").innerHTML = ( minutes < 10 ? "0" : "" ) + minutes;
for (var i=1;i < 7;i++)
{
var p = eval("player"+i);
document.querySelector("#video" + i + "delay").innerHTML = Math.round((d.getTime()/1000) - Number(p.timeAsUTC()));
document.querySelector("#video" + i + "buffer").innerHTML = p.getBufferLength()+ "s";
}
},1000);
}
</script>
<style>
table {
border-spacing: 10px;
}
video {
width: 320px;
height: 180px;
}
.clock { border:1px solid #333; color:#000; font-size: 60pt}
</style>
</head>
<body onload="init()">
This sample illustrates the combined effects of segment duration and the "<strong>setLiveDelayFragmentCount</strong>" MediaPlayer method on the latency of live stream playback.
The upper layer of videos are all playing a live stream with 2s segment duration. The lower layer use 6s segment duration. For each stream, the playback position
behind live is varied between 0, 2 and 4 segments. Note that the default value for dash.js is 4 segments, which is a trade off between stability and latency.
Lowest latency is achieved with shorter segments and with a lower liveDelayFragmentCount. Higher stability/robustness is achieved with a higher liveDelayFragmentCount.
<table>
<tr><td>
2s segment, 0 segments behind live<br/>
<video id="video1" controls="true">
</video><br/>
Seconds behind live: <span id="video1delay"></span><br/>
Buffer length: <span id="video1buffer"></span>
</td><td>
2s segment, 2 segments behind live<br/>
<video id="video2" controls="true">
</video><br/>
Seconds behind live: <span id="video2delay"></span><br/>
Buffer length: <span id="video2buffer"></span>
</td><td>
2s segment, 4 segments behind live (default)<br/>
<video id="video3" controls="true">
</video><br/>
Seconds behind live: <span id="video3delay"></span><br/>
Buffer length: <span id="video3buffer"></span>
</td>
<td>Wall clock time
<div class="clock">
<span id="min"> </span>:<span id="sec"></span>
</div>
</td></tr>
<tr><td>
6s segment, 0 segments behind live<br/>
<video id="video4" controls="true">
</video><br/>
Seconds behind live: <span id="video4delay"></span><br/>
Buffer length: <span id="video4buffer"></span>
</td><td>
6s segment, 2 segments behind live<br/>
<video id="video5" controls="true">
</video><br/>
Seconds behind live: <span id="video5delay"></span><br/>
Buffer length: <span id="video5buffer"></span>
</td><td>
6s segment, 4 segments behind live (default)<br/>
<video id="video6" controls="true">
</video><br/>
Seconds behind live: <span id="video6delay"></span><br/>
Buffer length: <span id="video6buffer"></span>
</td></tr>
</table>
</body>
</html>
| 6,171 | 44.718519 | 180 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/dash-if-reference-player/index.html | <!DOCTYPE html>
<html ng-app="DashPlayer" lang="en">
<head>
<meta charset="utf-8"/>
<title>Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/x-icon" href="http://dashif.org/wp-content/uploads/2014/12/dashif.ico" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap-glyphicons.css">
<link rel="stylesheet" href="app/lib/angular.treeview/css/angular.treeview.css">
<link rel="stylesheet" href="app/css/main.css">
<link rel="stylesheet" href="../../contrib/akamai/controlbar/controlbar.css">
<!-- http://jquery.com/ -->
<script src="app/lib/jquery/jquery-1.10.2.min.js"></script>
<!-- http://angularjs.org/ -->
<script src="app/lib/angular/angular.min.js"></script>
<script src="app/lib/angular/angular-resource.min.js"></script>
<!-- http://getbootstrap.com/ -->
<script src="app/lib/bootstrap/js/bootstrap.min.js"></script>
<!-- https://github.com/madebyhiro/codem-isoboxer -->
<!--<script src="../../externals/iso_boxer.min.js"></script>-->
<!-- http://bannister.us/weblog/2007/06/09/simple-base64-encodedecode-javascript/ -->
<!--<script src="../../externals/base64.js"></script>-->
<!-- Misc Libs -->
<!--<script src="../../externals/xml2json.js"></script>-->
<!--<script src="../../externals/objectiron.js"></script>-->
<!-- http://www.flotcharts.org/ -->
<script src="app/lib/flot/jquery.flot.js"></script>
<!-- https://github.com/eu81273/angular.treeview -->
<script src="app/lib/angular.treeview/angular.treeview.min.js"></script>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<!-- App -->
<script src="app/metrics.js"></script>
<script src="../../contrib/akamai/controlbar/ControlBar.js"></script>
<script src="app/main.js"></script>
</head>
<body ng-controller="DashController">
<div class="modal fade" id="streamModal">
<div class="modal-dialog">
<div class="list-group modal-list">
<a
ng-repeat="item in availableStreams"
href="#"
class="list-group-item"
ng-click="setStream(item)"
data-dismiss="modal">
{{item.name}}
</a>
</div>
</div>
</div>
<div class="container">
<div class="row title-header">
<a href="http://dashif.org/" target="_blank"><img class="image" src="app/img/if.png"/></a>
<span id="big-title">Reference Client</span>
<span>{{version}}</span>
<div class="github">
<iframe
id="star-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=watch&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true"
class="hidden-xs github-button">
</iframe>
<iframe
id="fork-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=fork&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true github-button">
</iframe>
</div>
</div>
<div class="row">
<div class="input-group">
<div class="input-group-btn">
<a role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
Sample Streams <span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
<li class="dropdown-submenu" ng-if="item.submenu" ng-repeat="item in availableStreams">
<a tabindex="-1" href="#">{{item.name}}</a>
<ul class="dropdown-menu">
<li ng-repeat="subitem in item.submenu">
<a ng-click="setStream(subitem)">{{subitem.name}}</a>
</li>
</ul>
</li>
</ul>
</div>
<input type="text" class="form-control" placeholder="Enter your manifest URL here" ng-model="selectedItem.url">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doLoad()">Load</button>
</span>
</div>
</div>
<div class="row">
<div class="dash-video-player col-md-9">
<div id="videoContainer">
<video controls="true"></video>
<div id="video-caption"></div>
<div id="videoController" class="video-controller unselectable">
<div id="playPauseBtn" class="btn-play-pause" title="Play/Pause">
<span id="iconPlayPause" class="icon-play"></span>
</div>
<span id="videoTime" class="time-display">00:00:00</span>
<div id="fullscreenBtn" class="btn-fullscreen" title="Fullscreen">
<span class="icon-fullscreen-enter"></span>
</div>
<input type="range" id="volumebar" class="volumebar" value="1" min="0" max="1" step=".01" />
<div id="muteBtn" class="btn-mute" title="Mute">
<span id="iconMute" class="icon-mute-off"></span>
</div>
<div id="captionBtn" class="btn-caption" title="Closed Caption">
<span class="icon-caption"></span>
</div>
<span id="videoDuration" class="duration-display">00:00:00</span>
<div class="seekContainer">
<input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">ABR</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:abrEnabled == false}"
ng-click="setAbrEnabled(false)">
<span>Off</span>
</button>
<button
type="button"
class="btn btn-default active"
ng-class="{active:abrEnabled == true}"
ng-click="setAbrEnabled(true)">
<span>On</span>
</button>
</div>
</div>
<div class="panel-heading panel-top">
<span class="panel-title">Save settings</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:mediaSettingsCacheEnabled == false}"
ng-click="setMediaSettingsCacheEnabled(false)">
<span>Off</span>
</button>
<button
type="button"
class="btn btn-default active"
ng-class="{active:mediaSettingsCacheEnabled == true}"
ng-click="setMediaSettingsCacheEnabled(true)">
<span>On</span>
</button>
</div>
</div>
<div class="panel-heading panel-top">
<span class="panel-title">Use BOLA</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default active"
ng-class="{active:bolaEnabled == false}"
ng-click="setBolaEnabled(false)">
<span>Off</span>
</button>
<button
type="button"
class="btn btn-default"
ng-class="{active:bolaEnabled == true}"
ng-click="setBolaEnabled(true)">
<span>On</span>
</button>
</div>
</div>
</div>
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Video</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-click="abrDown('video')">
<span class="glyphicon glyphicon-minus"></span>
</button>
<button
type="button"
class="btn btn-default"
ng-click="abrUp('video')">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<div class="panel-body panel-stats">
<p class="text-warning">{{videoBitrate}} kbps</p>
<p class="text-primary">Rep Index: <span class="text-success">{{videoIndex}}</span><span class="text-warning">{{videoPendingIndex}}</span>/<span class="text-success">{{videoMaxIndex}}</span></p>
<p class="text-primary">Buffer Length: <span class="text-success">{{videoBufferLength}}</span></p>
<p class="text-primary">Latency: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoLatency}}</p>
<p class="text-primary">Download: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoDownload}}</p>
<p class="text-primary">Ratio: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoRatio}}</p>
<p class="text-primary">Dropped Frames: <span class="text-success">{{videoDroppedFrames}}</span></p>
</div>
<ul class="nav nav-tabs">
<li class="dropdown">
<a href="#" id="videoTracksDropdown" class="dropdown-toggle" data-toggle="dropdown">Tracks <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="track in availableTracks.video" ng-click="switchTrack(track, 'video')">
<a>lang: {{track.lang || "undefined"}}, viewpoint: {{track.viewpoint || "undefined"}}, roles: {{track.roles || "undefined"}}</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" id="videoTrackSwitchModeDropdown" class="dropdown-toggle" data-toggle="dropdown">Track switch mode<b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li ng-click="changeTrackSwitchMode('alwaysReplace', 'video')"><a>always replace</a></li>
<li ng-click="changeTrackSwitchMode('neverReplace', 'video')"><a>never replace</a></li>
</ul>
</li>
<input type="text" class="form-control" placeholder="initial role, e.g. 'alternate'" ng-model="initialSettings.video">
</ul>
</div>
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Audio</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-click="abrDown('audio')">
<span class="glyphicon glyphicon-minus"></span>
</button>
<button
type="button"
class="btn btn-default"
ng-click="abrUp('audio')">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<div class="panel-body panel-stats">
<p class="text-warning">{{audioBitrate}} kbps</p>
<p class="text-primary">Rep Index: <span class="text-success">{{audioIndex}}</span><span class="text-warning">{{audioPendingIndex}}</span>/<span class="text-success">{{audioMaxIndex}}</span></p>
<p class="text-primary">Buffer Length: <span class="text-success">{{audioBufferLength}}</span></p>
<p class="text-primary">Latency: <span class="text-success">last {{audioLatencyCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioLatency}}</p>
<p class="text-primary">Download: <span class="text-success">last {{audioDownloadCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioDownload}}</p>
<p class="text-primary">Ratio: <span class="text-success">last {{audioRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioRatio}}</p>
</div>
<ul class="nav nav-tabs">
<li class="dropdown">
<a href="#" id="audioTracksDropdown" class="dropdown-toggle" data-toggle="dropdown">Tracks <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="track in availableTracks.audio" ng-click="switchTrack(track, 'audio')">
<a>lang: {{track.lang || "undefined"}}, viewpoint: {{track.viewpoint || "undefined"}}, roles: {{track.roles || "undefined"}}</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" id="audioTrackSwitchModeDropdown" class="dropdown-toggle" data-toggle="dropdown">Track switch mode<b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li ng-click="changeTrackSwitchMode('alwaysReplace', 'audio')"><a>always replace</a></li>
<li ng-click="changeTrackSwitchMode('neverReplace', 'audio')"><a>never replace</a></li>
</ul>
</li>
<input type="text" class="form-control" placeholder="initial lang, e.g. 'en'" ng-model="initialSettings.audio">
</ul>
</div>
</div>
</div>
<div class="row">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Charts</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:showCharts == false}"
ng-click="setCharts(false)">
Hide
</button>
<button
type="button"
class="btn btn-default"
ng-class="{active:showCharts == true}"
ng-click="setCharts(true)">
Show
</button>
</div>
</div>
<div ng-switch on="showCharts">
<div class="panel-body panel-stats" ng-switch-when="true">
<ul class="nav nav-tabs">
<li><a href="#bufferLevel" data-toggle="tab" ng-click="setBufferLevelChart(true)">Buffer level</a></li>
<li><a href="#manifestInfo" data-toggle="tab">Manifest update info</a></li>
</ul>
<div id="chartTabContent" class="tab-content">
<div class="tab-pane" id="bufferLevel" ng-class="{active:showBufferLevel == true}">
<div ng-switch on="showBufferLevel">
<div class="panel-body panel-stats" ng-switch-when="true">
<chart ng-model="bufferData"></chart>
</div>
</div>
</div>
<div class="tab-pane" id="manifestInfo">
<div>
<div ng-repeat="info in manifestUpdateInfo" class="manifest-info-box manifest-info-item">
<div class="manifest-info-content" header="Manifest type"><span class="text-success">{{info.type}}</span></div><br/>
<div class="manifest-info-content" header="Request time (delta)"><span class="text-success">{{info.requestTime}}</span><span class="text-warning"> {{info.requestTimeDelta}}</span></div><br/>
<div class="manifest-info-content" header="Fetch time (delta)"><span class="text-success">{{info.fetchTime}}</span><span class="text-warning"> {{info.fetchTimeDelta}}</span></div><br/>
<div class="manifest-info-content" header="Availability start time (delta)"><span class="text-success">{{info.availabilityStartTime}}</span><span class="text-warning"> {{info.availabilityStartTimeDelta}}</span></div><br/>
<div class="manifest-info-content" header="Presentation start time (delta)"><span class="text-success">{{info.presentationStartTime}}</span><span class="text-warning"> {{info.presentationStartTimeDelta}}</span></div><br/>
<div class="manifest-info-content" header="Client time offset (delta)"><span class="text-success">{{info.clientTimeOffset}}</span><span class="text-warning"> {{info.clientTimeOffsetDelta}}</span></div><br/>
<div class="manifest-info-content" header="Current time (delta)"><span class="text-success">{{info.currentTime}}</span><span class="text-warning"> {{info.currentTimeDelta}}</span></div><br/>
<div class="manifest-info-content" header="Latency (delta)"><span class="text-success">{{info.latency}}</span><span class="text-warning"> {{info.latencyDelta}}</span></div><br/>
<div class="repeat-container" ng-repeat="stream in info.streamInfo">
<div class="manifest-info-content" header="Period"><span class="text-success">{{stream.index}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Id"><span class="text-success">{{stream.id}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Start"><span class="text-success">{{stream.start}}</span><span class="text-warning"> {{stream.startDelta}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Duration"><span class="text-success">{{stream.duration}}</span><span class="text-warning"> {{stream.durationDelta}}</span></div><br/>
<div class="repeat-container" ng-repeat="range in info.buffered">
<div class="manifest-info-content" header="Buffered"><span class="text-success"></span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Start"><span class="text-success">{{range.start}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="End"><span class="text-success">{{range.end}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Size"><span class="text-success">{{range.size}}</span></div><br/>
</div>
<div class="repeat-container" ng-repeat="track in info.trackInfo" ng-show="track.streamIndex == stream.index">
<div class="manifest-info-content" header="Representation"><span class="text-success">{{track.index}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Id"><span class="text-success">{{track.id}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Stream type"><span class="text-success">{{track.mediaType}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Presentation time offset"><span class="text-success">{{track.presentationTimeOffset}}</span><span class="text-warning"> {{track.presentationTimeOffsetDelta}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Start number"><span class="text-success">{{track.startNumber}}</span><span class="text-warning"> {{track.startNumberDelta}}</span></div><br/>
<div class="manifest-info-content manifest-nested-info" header="Segment info type"><span class="text-success">{{track.fragmentInfoType}}</span></div><br/>
</div>
</div>
</div>
<span ng-show="manifestUpdateInfo == undefined">No data available</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Debug</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:showDebug == false}"
ng-click="setDebug(false)">
Hide
</button>
<button
type="button"
class="btn btn-default"
ng-class="{active:showDebug == true}"
ng-click="setDebug(true)">
Show
</button>
</div>
</div>
<div ng-switch on="showDebug">
<div class="panel-body panel-stats" ng-switch-when="true">
<ul class="nav nav-tabs">
<li class="dropdown">
<a href="#" id="metricsDropdown" class="dropdown-toggle" data-toggle="dropdown">Metrics <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu" aria-labelledby="metricsDropdown">
<li><a href="#video-metrics" tabindex="-1" data-toggle="tab">Video</a></li>
<li><a href="#audio-metrics" tabindex="-1" data-toggle="tab">Audio</a></li>
<li><a href="#stream-metrics" tabindex="-1" data-toggle="tab">Stream</a></li>
</ul>
</li>
<li><a href="#requests" data-toggle="tab">Requests</a></li>
<li><a href="#notes" data-toggle="tab">Release Notes</a></li>
</ul>
<div id="debugTabContent" class="tab-content">
<div class="tab-pane" id="video-metrics">
<button
type="button"
class="btn btn-default"
ng-click="getVideoTreeMetrics()">
Video - Update
</button>
<div
class="tree"
data-angular-treeview="true"
data-tree-model="videoMetrics"
data-node-label="text"
data-node-children="items">
</div>
</div>
<div class="tab-pane" id="audio-metrics">
<button
type="button"
class="btn btn-default"
ng-click="getAudioTreeMetrics()">
Audio - Update
</button>
<div
class="tree"
data-angular-treeview="true"
data-tree-model="audioMetrics"
data-node-label="text"
data-node-children="items">
</div>
</div>
<div class="tab-pane" id="stream-metrics">
<button
type="button"
class="btn btn-default"
ng-click="getStreamTreeMetrics()">
Stream - Update
</button>
<div
class="tree"
data-angular-treeview="true"
data-tree-model="streamMetrics"
data-node-label="text"
data-node-children="items">
</div>
</div>
<div class="tab-pane" id="requests">
<div class="video-requests col-md-4">
<div>Loading Requests (Video)</div>
<ul ng-repeat = "request in videoRequestsQueue.loadingRequests">
<li>{{request.startTime}}</li>
</ul>
<div>Executed Requests (Video)</div>
<ul ng-repeat = "request in videoRequestsQueue.executedRequests">
<li>{{request.startTime}}</li>
</ul>
</div>
<div class="audio-requests col-md-4">
<div>Loading Requests (Audio)</div>
<ul ng-repeat = "request in audioRequestsQueue.loadingRequests">
<li>{{request.startTime}}</li>
</ul>
<div>Executed Requests (Audio)</div>
<ul ng-repeat = "request in audioRequestsQueue.executedRequests">
<li>{{request.startTime}}</li>
</ul>
</div>
<div class="buffered-ranges col-md-4">
<div>Buffered Ranges (Video + Audio)</div>
<ul ng-repeat = "bufferedRange in bufferedRanges">
<li>{{bufferedRange}}</li>
</ul>
</div>
</div>
<div class="tab-pane" id="notes">
<div ng-repeat="note in releaseNotes" class="note-box">
<span><b>{{note.title}}</b></span><br/>
<span ng-repeat="text in note.items">
{{text}}<br/>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-area">
<div class="container">
<div class="row">
<div class="compat-box col-md-5">
<h3>Compatibility Notes:</h3>
<ul class="list-group">
<li class="list-group-item"><a href="https://github.com/Dash-Industry-Forum/dash.js">This project can be forked on GitHub.</a></li>
<li class="list-group-item">Use your browser's JavaScript console to view detailed information about stream playback.</li>
<li class="list-group-item"><a href="../getting-started-basic-embed/auto-load-single-video.html">See a base implementation here.</a></li>
<li class="list-group-item">A browser that supports MSE (Media Source Extensions) is required.</li>
<li class="list-group-item">As of 2/1/2015 supported on the following browsers: Desktop Chrome, Desktop Internet Explorer 11 under WIn8.1, Mobile Chrome for Android and Safari on Mac Yosemite</li>
<li class="list-group-item">Use the most up-to-date version of your browser for the best compatibility.</li>
</ul>
</div>
<div class="col-md-3">
<h3 class="footer-text">Player Libraries:</h3>
<a
ng-repeat="item in playerLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
<h3 class="footer-text">Showcase Libraries:</h3>
<a
ng-repeat="item in showcaseLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
</div>
<div class="col-md-4">
<h3 class="footer-text">Contributors:</h3>
<a
ng-repeat="item in contributors"
class="footer-text"
href="{{item.link}}"
target="_blank">
<img ng-show="hasLogo(item)" ng-src="{{item.logo}}" alt="{{item.link}}"/>
<span class="contributor" ng-show="!hasLogo(item)">{{item.name}}</span>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
| 34,328 | 59.651943 | 287 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/dash-if-reference-player/eme.html | <!DOCTYPE html>
<html ng-app="DashPlayer" lang="en">
<head>
<meta charset="utf-8"/>
<title>Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/x-icon" href="http://dashif.org/wp-content/uploads/2014/12/dashif.ico" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap-glyphicons.css">
<link rel="stylesheet" href="app/css/main.css">
<link rel="stylesheet" href="app/css/eme.css">
<link rel="stylesheet" href="../../contrib/akamai/controlbar/controlbar.css">
<!-- http://jquery.com/ -->
<script src="app/lib/jquery/jquery-1.10.2.min.js"></script>
<!-- http://angularjs.org/ -->
<script src="app/lib/angular/angular.min.js"></script>
<script src="app/lib/angular/angular-resource.min.js"></script>
<!-- http://getbootstrap.com/ -->
<script src="app/lib/bootstrap/js/bootstrap.min.js"></script>
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<!-- App -->
<script src="../../contrib/akamai/controlbar/ControlBar.js"></script>
<script src="app/eme-main.js"></script>
</head>
<body ng-controller="DashController">
<div class="modal fade" id="streamModal">
<div class="modal-dialog">
<div class="list-group modal-list">
<a
ng-repeat="item in availableStreams"
href="#"
class="list-group-item"
ng-click="setStream(item)"
data-dismiss="modal">
{{item.name}}
</a>
</div>
</div>
</div>
<div class="container">
<div class="row title-header">
<a href="http://dashif.org/" target="_blank"><img class="image" src="app/img/if.png"/></a>
<span id="big-title">Reference Client</span>
<span>{{version}}</span>
<div class="github">
<iframe
id="star-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=watch&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true"
class="hidden-xs github-button">
</iframe>
<iframe
id="fork-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=fork&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true github-button">
</iframe>
</div>
</div>
<div class="row">
<div class="input-group">
<div class="input-group-btn">
<a role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
Sample Streams <span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
<li class="dropdown-submenu" ng-if="item.submenu" ng-repeat="item in availableStreams">
<a tabindex="-1" href="#">{{item.name}}</a>
<ul class="dropdown-menu">
<li ng-repeat="subitem in item.submenu">
<a ng-click="setStream(subitem)">{{subitem.name}}</a>
</li>
</ul>
</li>
</ul>
</div>
<input type="text" class="form-control" placeholder="Enter your manifest URL here" ng-model="selectedItem.url">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doLoad()">Load</button>
</span>
</div>
</div>
<div class="row">
<div class="dash-video-player col-md-9">
<div id="videoContainer">
<video controls="true"></video>
<div id="videoController" class="video-controller unselectable">
<div id="playPauseBtn" class="btn-play-pause" title="Play/Pause">
<span id="iconPlayPause" class="icon-play"></span>
</div>
<span id="videoTime" class="time-display">00:00:00</span>
<div id="fullscreenBtn" class="btn-fullscreen" title="Fullscreen">
<span class="icon-fullscreen-enter"></span>
</div>
<input type="range" id="volumebar" class="volumebar" value="1" min="0" max="1" step=".01" />
<div id="muteBtn" class="btn-mute" title="Mute">
<span id="iconMute" class="icon-mute-off"></span>
</div>
<div id="captionBtn" class="btn-caption" title="Closed Caption">
<span class="icon-caption"></span>
</div>
<span id="videoDuration" class="duration-display">00:00:00</span>
<div class="seekContainer">
<input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="shrink panel panel-default">
<div class="panel-heading panel-top">
<h1 class="panel-title">New Session Properties</h1>
</div>
<div class="panel-body">
<h5>Session Type</h5>
<div id="session-type" class="btn-group-vertical" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" id="temporary" autocomplete="off" checked>temporary
</label>
<label class="btn btn-default">
<input type="radio" id="persistent-license" autocomplete="off">persistent-license
</label>
<label class="btn btn-default">
<input type="radio" id="persistent-release-message" autocomplete="off">persistent-release
</label>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Protection Information</h3>
</div>
</div>
<div class="row" ng-repeat="d in drmData">
<div class="panel panel-info" ng-class="{sessionPanelPlaying: d.isPlaying}">
<div class="panel-heading panel-top">
<span class="panel-title">{{d.manifest.url}}</span>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-disabled="!d.licenseReceived" ng-click="play(d)">Play</button>
<button type="button" class="btn btn-default" ng-click="delete(d)">Delete</button>
</div>
</div>
<div class="col-sm-12" ng-show="d.ksconfig">
<div class="row">
<div class="col-sm-4">
<h4 ng-show="d.protCtrl.protectionModel.keySystem" class="keysystem shrink">Key System: <span class="label label-success">{{d.protCtrl.protectionModel.keySystem.systemString}}</span></h4>
<div><b>Init Data Types: </b>{{arrayToCommaSeparated(d.ksconfig.initDataTypes)}}</div>
<div><b>Persistent State: </b><span ng-show="d.ksconfig.persistentState">{{d.ksconfig.persistentState}}</span></div>
<div><b>Distinctive Identifier: </b><span ng-show="d.ksconfig.distinctiveIdentifier">{{d.ksconfig.distinctiveIdentifier}}</span></div>
</div>
<div class="col-sm-4">
<h5>Video Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="video in d.ksconfig.videoCapabilities">
<div><b>ContentType: </b>{{video.contentType}}</div>
<div><b>Robustness: </b>{{video.robustness}}</div>
</li>
</ul>
</div>
<div class="col-sm-4">
<h5>Audio Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="audio in d.ksconfig.audioCapabilities">
<div><b>ContentType: </b>{{audio.contentType}}</div>
<div><b>Robustness: </b>{{audio.robustness}}</div>
</li>
</ul>
</div>
</div>
</div>
<div class="errormessage" ng-show="d.error"><span class="label label-danger">ERROR</span><span class="errormessage">{{d.error}}</span></div>
<div class="panel panel-default sessionPanel" ng-repeat="s in d.sessions">
<div class="panel-heading panel-top">
<span class="panel-title">SessionID: {{s.sessionToken.getSessionID()}}</span>
<div class="btn-group">
<button type="button" ng-disabled="isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.loadKeySession(s.sessionID)">Load</button>
<button type="button" ng-disabled="!isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.removeKeySession(s.sessionToken)">Remove</button>
<button type="button" class="btn btn-default" ng-click="d.protCtrl.closeKeySession(s.sessionToken)">Close</button>
</div>
</div>
<div class="keymessage" ng-show="s.lastMessage">{{s.lastMessage}}</div>
<div class="keymessage"><b>Session Persistence: </b><span>{{getLoadedMessage(s)}}</span></div>
<h5 ng-show="s.getExpirationTime()">Expiration: {{s.getExpirationTime()}}</h5>
<table ng-show="isLoaded(s) && s.keystatus && s.keystatus.length > 0" class="table table-bordered table-hover">
<tr>
<th>Key ID</th>
<th class="centered">Key Status</th>
</tr>
<tr ng-repeat="keystatus in s.keystatus">
<td class="keyid">{{keystatus.key}}</td>
<td ng-class="{true: 'success'}[keystatus.status=='usable']" class="centered">{{keystatus.status}}</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="footer-area">
<div class="container">
<div class="row">
<div class="compat-box col-md-5">
<h3>Compatibility Notes:</h3>
<ul class="list-group">
<li class="list-group-item"><a href="https://github.com/Dash-Industry-Forum/dash.js">This project can be forked on GitHub.</a></li>
<li class="list-group-item">Use your browser's JavaScript console to view detailed information about stream playback.</li>
<li class="list-group-item"><a href="../getting-started-basic-embed/auto-load-single-video.html">See a base implementation here.</a></li>
<li class="list-group-item">A browser that supports MSE (Media Source Extensions) is required.</li>
<li class="list-group-item">As of 2/1/2015 supported on the following browsers: Desktop Chrome, Desktop Internet Explorer 11 under WIn8.1, Mobile Chrome for Android and Safari on Mac Yosemite</li>
<li class="list-group-item">Use the most up-to-date version of your browser for the best compatibility.</li>
</ul>
</div>
<div class="col-md-3">
<h3 class="footer-text">Player Libraries:</h3>
<a
ng-repeat="item in playerLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
<h3 class="footer-text">Showcase Libraries:</h3>
<a
ng-repeat="item in showcaseLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
</div>
<div class="col-md-4">
<h3 class="footer-text">Contributors:</h3>
<a
ng-repeat="item in contributors"
class="footer-text"
href="{{item.link}}"
target="_blank">
<img ng-show="hasLogo(item)" ng-src="{{item.logo}}" alt="{{item.link}}"/>
<span class="contributor" ng-show="!hasLogo(item)">{{item.name}}</span>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
| 14,617 | 51.207143 | 220 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/chromecast/index.html | <!DOCTYPE html>
<html ng-app lang="en">
<head>
<meta charset="utf-8"/>
<title>Baseline Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/png" href="http://dashpg.com/w/2012/09/dashif.ico" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
<link rel="stylesheet" href="receiver/css/style.css">
<script src="http://code.jquery.com/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<!-- Chromecast -->
<script src="https://www.gstatic.com/cast/js/receiver/1.0/cast_receiver.js"></script>
<!-- Unminified Dash -->
<script src="../../dist/dash.all.debug.js"></script>
<!--dash.all.min.js should be used in production over dash.all.debug.js
Debug files are not compressed or obfuscated making the file size much larger compared with dash.all.min.js-->
<!--<script src="../../dist/dash.all.min.js"></script>-->
<script src="receiver/js/main.js"></script>
<body ng-controller="ReceiverController">
<div class="dash-video-player">
<div id="loading_spinner" class="loading_spinner" ng-show="showSpinner"></div>
<video id="vid" ng-show="showVideo"></video>
</div>
<div class="stats-holder" ng-show="showStats">
<div class="panel panel-info panel-stats">
<div class="panel-heading">
<h3 class="panel-title">Video</h3>
</div>
<div class="panel-body">
<span>{{videoBitrate}} kbps</span>
<span>Rep Index: {{videoIndex}}{{videoPendingIndex}}/{{videoMaxIndex}}</span>
<span>Buffer Length: {{videoBufferLength}}</span>
<span>Dropped Frames: {{videoDroppedFrames}}</span>
</div>
</div>
<div class="panel panel-success panel-stats">
<div class="panel-heading">
<h3 class="panel-title">Audio</h3>
</div>
<div class="panel-body">
<span>{{audioBitrate}} kbps</span>
<span>Rep Index: {{audioIndex}}{{audioPendingIndex}}/{{audioMaxIndex}}</span>
<span>Buffer Length: {{audioBufferLength}}</span>
<span>Dropped Frames: {{audioDroppedFrames}}</span>
</div>
</div>
</div>
<div id="scrubber" class="progress scrubber">
<div id="scrubber-content" class="progress-bar progress-bar-success" role="progressbar"></div>
</div>
</body>
</html>
| 2,821 | 43.09375 | 118 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/chromecast/sender/index.html | <!DOCTYPE html>
<html ng-app data-cast-api-enabled="true">
<head>
<meta charset="utf-8"/>
<title>Dash.js Chromecast Sender</title>
<meta name="description" content="" />
<link rel="icon" type="image/png" href="http://dashpg.com/w/2012/09/dashif.ico" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-glyphicons.css">
<script src="http://code.jquery.com/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<script src="js/caster.js"></script>
<script src="js/CasterController.js"></script>
<style>
.dropdown-menu {
max-height: 250px;
overflow: auto;
}
.dropdown-menu li {
cursor: pointer;
cursor: hand;
}
.list-group-item {
cursor: pointer;
cursor: hand;
}
h3 {
margin-top: 0px;
}
.controlbar * {
display: inline-block;
vertical-align: middle;
}
</style>
<body ng-controller="CasterController">
<a href="https://github.com/Dash-Industry-Forum/dash.js">
<img
style="position: absolute; top: 0; right: 0; border: 0; width: 149px; height: 149px;"
src="http://aral.github.com/fork-me-on-github-retina-ribbons/[email protected]"
alt="Fork me on GitHub">
</a>
<div ng-switch on="castApiReady">
<div class="alert alert-danger" ng-switch-default>
{{errorMessage}}
</div>
<div ng-switch-when="true">
<div class="container" style="padding: 15px">
<div class="jumbotron">
<h2>DASH IF Reference Client for Chromecast</h2>
<p>This is an implementation of the Dash.JS reference client for Google's Chromecast device.</p>
</div>
<div class="panel">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Stream <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li ng-repeat="item in availableStreams" ng-click="setStream(item)">
<a>{{item.name}}</a>
</li>
</ul>
</div>
<input type="text" class="form-control" placeholder="manifest" ng-model="selectedItem.url">
<span class="input-group-addon">
live <input type="checkbox" ng-model="selectedItem.isLive">
</span>
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doCast()">Cast</button>
</span>
</div>
</div>
<div class="panel" ng-show="state == 'ready' || state == 'casting'">
<h3 class="text-primary">Receivers</h3>
<div class="list-group">
<a
class="list-group-item"
ng-repeat="rec in receivers"
ng-click="setReceiver(rec)"
ng-class="{active:isReceiverSelected(rec)}">
{{rec.name}}
</a>
</div>
</div>
<div class="panel" ng-show="state == 'casting'">
<h3 class="text-success">Controls</h3>
<div class="row controlbar" style="padding-left: 10px; padding-right: 10px;">
<button type="button" class="btn btn-success" ng-click="toggleStats()">
Stats
</button>
<!--
<button type="button" class="btn btn-danger" ng-click="stopCast()">
<span class="glyphicon glyphicon-stop"></span>
</button>
-->
<button type="button" class="btn btn-info" ng-click="togglePlayback()">
<span class="glyphicon glyphicon-play" ng-show="!playing"></span>
<span class="glyphicon glyphicon-pause" ng-show="playing"></span>
</button>
<div id="scrubber" class="progress" style="width: 200px;" ng-click="doSeek()">
<div id="scrubber-content" class="progress-bar progress-bar-success" role="progressbar"></div>
</div>
<button type="button" class="btn btn-warning" ng-click="toggleMute()">
<span class="glyphicon glyphicon-music" ng-show="!muted"></span>
<span class="glyphicon glyphicon-volume-off" ng-show="muted"></span>
</button>
<button type="button" class="btn btn-warning" ng-click="turnVolumeDown()">
<span class="glyphicon glyphicon-volume-down"></span>
</button>
<input
type="text"
style="width: 65px; height: 40px; text-align: center;"
disabled
value="{{volume * 100|number:0}}%">
<button type="button" class="btn btn-warning" ng-click="turnVolumeUp()">
<span class="glyphicon glyphicon-volume-up"></span>
</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| 6,579 | 44.37931 | 126 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/dash-if-reference-player-beta/index.html | <!DOCTYPE html>
<html ng-app="DashPlayer" lang="en">
<head>
<meta charset="utf-8"/>
<title>Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/x-icon" href="http://dashif.org/wp-content/uploads/2014/12/dashif.ico" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap-glyphicons.css">
<link rel="stylesheet" href="app/lib/angular.treeview/css/angular.treeview.css">
<link rel="stylesheet" href="app/css/main.css">
<link rel="stylesheet" href="app/css/dropdown.css">
<link rel="stylesheet" href="../../contrib/akamai/controlbar/controlbar.css">
<!-- http://jquery.com/ -->
<script src="app/lib/jquery/jquery-1.10.2.min.js"></script>
<!-- http://angularjs.org/ -->
<script src="app/lib/angular/angular.min.js"></script>
<script src="app/lib/angular/angular-resource.min.js"></script>
<!-- http://getbootstrap.com/ -->
<script src="app/lib/bootstrap/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
<!-- https://github.com/madebyhiro/codem-isoboxer -->
<!--<script src="../../externals/iso_boxer.min.js"></script>-->
<!-- http://bannister.us/weblog/2007/06/09/simple-base64-encodedecode-javascript/ -->
<!--<script src="../../externals/base64.js"></script>-->
<!-- Misc Libs -->
<!--<script src="../../externals/xml2json.js"></script>-->
<!--<script src="../../externals/objectiron.js"></script>-->
<!-- http://www.flotcharts.org/ -->
<script src="app/lib/flot/jquery.flot.js"></script>
<!-- https://github.com/eu81273/angular.treeview -->
<script src="app/lib/angular.treeview/angular.treeview.min.js"></script>
<script src="../../dist/dash.all.debug.js"></script>
<script src="../../dist/dash.protection.debug.js"></script>
<!-- App -->
<script src="app/metrics.js"></script>
<script src="../../contrib/akamai/controlbar/ControlBar.js"></script>
<script src="app/main.js"></script>
</head>
<body ng-controller="DashController">
<div class="modal fade" id="streamModal">
<div class="modal-dialog">
<div class="list-group modal-list">
<ul>
<li ng-repeat="item in availableTaxonomyStreams"
ng-class="{'sub':item.submenu}">
<span ng-show="!item.submenu"
ng-click="setStream(item)">{{item.name}}</span>
<span ng-show="item.submenu">{{item.name}}</span>
<ul ng-show="item.submenu">
<li ng-repeat="subitem in item.submenu">
<span ng-click="setStream(subitem)"
data-dismiss="modal">{{subitem.name}}</span>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row title-header">
<div class="branding">
<a href="http://dashif.org/" target="_blank"><img class="image" src="app/img/if.png"/></a>
<span id="big-title">Reference Client</span>
<span>{{version}}</span>
</div>
<div class="top-buttons">
<button class="extras btn btn-primary" ng-click="toggleOptionsGutter(!optionsGutter)">Options</button>
<iframe
id="star-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=watch&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true"
class="hidden-xs github-button">
</iframe>
<iframe
id="fork-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=fork&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true github-button">
</iframe>
</div>
</div>
<div class="row">
<div class="input-group">
<div id="desktop-streams" class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Stream <span class="caret"></span>
</button>
<ul class="dropdown-menu nav">
<li ng-repeat="item in availableTaxonomyStreams"
ng-class="{'sub':item.submenu}">
<span ng-show="!item.submenu"
ng-click="setStream(item)">{{item.name}}</span>
<span ng-show="item.submenu">{{item.name}}</span>
<ul ng-show="item.submenu">
<li ng-repeat="subitem in item.submenu">
<span ng-click="setStream(subitem)">{{subitem.name}}</span>
</li>
</ul>
</li>
<!-- <li class="sub">
Subhead 1.1
<ul>
<li>Subhead 1.1.1</li>
<li>Subhead 1.1.2</li>
<li>Subhead 1.1.3</li>
</ul>
</li>
<li class="sub">
Subhead 1.1
<ul>
<li>Subhead 1.1.1</li>
<li>Subhead 1.1.2</li>
<li>Subhead 1.1.3</li>
</ul>
</li>
<li>Subhead 1.2</li>
<li>Subhead 1.3</li>
<li>Subhead 1.4</li> -->
</ul>
<!-- <ul class="dropdown-menu">
<li
ng-repeat="item in availableStreams"
ng-click="setStream(item)">
<a>{{item.name}}</a>
</li>
</ul> -->
</div>
<div id="mobile-streams" class="input-group-btn">
<button type="button" class="btn btn-primary" data-toggle="modal" href="#streamModal">
Stream <span class="caret"></span>
</button>
</div>
<input type="text" class="form-control" placeholder="manifest" ng-model="selectedItem.url">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doLoad()">Load</button>
</span>
</div>
</div>
<div class="row options-wrapper"
ng-class="{'options-show':optionsGutter,
'options-hide':!optionsGutter}">
<div class="options-item playback" id="playback-options">
<div class="options-item-title">Playback</div>
<ul>
<li>
<input type="checkbox"
id="autoPlayCB"
checked="">
<label class="topcoat-checkbox"
for="autoPlayCB">
Auto-Play
</label>
</li>
<li>
<input type="checkbox"
id="loopCB"
checked="">
<label class="topcoat-checkbox"
for="loopCB">
Loop
</label>
</li>
<li>
<input type="checkbox"
id="DOMStorageCB"
checked="">
<label class="topcoat-checkbox"
for="DOMStorageCB">
DOM Storage
</label>
</li>
</ul>
</div>
<div class="options-item sessiontype" id="sessiontype-options">
<div class="options-item-title">DRM Options</div>
<div id="session-type">
<label>
<input type="radio"
id="temporary"
name="drm"
checked="checked"> temporary
</label>
<label>
<input type="radio"
id="persistent-license"
name="drm"> persistent-license
</label>
<label>
<input type="radio"
id="persistent-release-message"
name="drm"> persistent-release
</label>
<button class="btn btn-primary license"
type="button"
ng-click="doLicenseFetch()">Pre-Fetch Licenses</button>
</div>
</div>
<div class="options-item track-swtch" id="track-swtch-options">
<div class="options-item-title">Track Switch Mode</div>
<div id="track-switch-type">
<label>
<input type="radio"
id="always-replace"
autocomplete="off"
name="track-switch"
checked="checked"
ng-click="changeTrackSwitchMode('alwaysReplace', 'video')"> always replace
</label>
<label>
<input type="radio"
id="never-replace"
autocomplete="off"
name="track-switch"
ng-click="changeTrackSwitchMode('neverReplace', 'video')"> never replace
</label>
</div>
</div>
<div class="options-item initial-role" id="initial-role">
<div class="options-item-title">Initial Role</div>
<div id="initial-role-option">
<label>Audio:</label>
<input type="text"
class="form-control"
placeholder="initial lang, e.g. 'en'"
ng-model="initialSettings.audio">
<label>Video:</label>
<input type="text"
class="form-control"
placeholder="initial role, e.g. 'alternate'"
ng-model="initialSettings.video">
</div>
</div>
</div>
<div class="row">
<div class="dash-video-player col-md-9">
<div id="videoContainer">
<video controls="true"></video>
<div id="video-caption"></div>
<div id="videoController" class="video-controller unselectable">
<div id="playPauseBtn" class="btn-play-pause" title="Play/Pause">
<span id="iconPlayPause" class="icon-play"></span>
</div>
<span id="videoTime" class="time-display">00:00:00</span>
<div id="fullscreenBtn"
class="btn-fullscreen"
title="Fullscreen">
<span class="icon-fullscreen-enter"
data-toggle="tooltip"
title="Fullscreen"></span>
</div>
<input type="range"
id="volumebar"
class="volumebar"
value="1"
min="0"
max="1"
step=".01"
data-toggle="tooltip"
title="Audio Level" />
<div id="muteBtn"
class="btn-mute"
data-toggle="tooltip"
title="Mute">
<span id="iconMute"
class="icon-mute-off"></span>
</div>
<div id="captionBtn"
class="btn-caption"
ng-mouseenter="toggleCCBubble = !toggleCCBubble;"
ng-mouseleave="toggleCCBubble = !toggleCCBubble;">
<span class="icon-caption"></span>
</div>
<div id="caption-bubble"
ng-show="toggleCCBubble">
Closed Caption
</div>
<div id="videoTracksBtn"
class="btn-caption"
ng-show="availableTracks.video.length > 1" >
<span class="icon-video"
data-toggle="dropdown">
<em data-toggle="tooltip"
title="Video Tracks"></em></span>
<ul class="dropdown-menu tracklisting" role="menu">
<li ng-repeat="track in availableTracks.video" ng-click="switchTrack(track, 'video')">
<a>lang: {{track.lang || "undefined"}}, viewpoint: {{track.viewpoint || "undefined"}}, roles: {{track.roles || "undefined"}}</a>
</li>
</ul>
</div>
<div id="audioTracksBtn"
class="btn-caption"
ng-show="availableTracks.audio.length > 1">
<span class="icon-audio"
data-toggle="dropdown">
<em data-toggle="tooltip"
title="Audio Tracks"></em></span>
<ul class="dropdown-menu tracklisting" role="menu">
<li ng-repeat="track in availableTracks.audio" ng-click="switchTrack(track, 'audio')">
<a>lang: {{track.lang || "undefined"}}, viewpoint: {{track.viewpoint || "undefined"}}, roles: {{track.roles || "undefined"}}</a>
</li>
</ul>
</div>
<span id="videoDuration" class="duration-display">00:00:00</span>
<div class="seekContainer">
<input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>
</div>
</div>
</div>
</div>
<div class="col-md-3 tabs-section">
<div>
<ul class="nav nav-tabs" role="tablist">
<li class="active">
<a href="#video" role="tab" data-toggle="tab">
Video
</a>
</li>
<li><a href="#audio" role="tab" data-toggle="tab">
Audio
</a>
</li>
<li><a href="#text" role="tab" data-toggle="tab">
Text
</a>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade active in" id="video">
<div class="panel-body panel-stats">
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The bitrate of the representation being loaded">
<em>Bitrate:</em> {{videoBitrate}} kbps</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The representation index being loaded. Lowest index is 1">
<em>Index being loaded:</em> {{videoIndex}}{{videoPendingIndex}}/{{videoMaxIndex}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The length of the forward buffer, in seconds">
<em>Buffer Length:</em> {{videoBufferLength}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum latency over the last 4 requested segments. Latency is the time in seconds from request of segment to receipt of first byte">
<em>Latency (min|avg|max):</em> {{videoLatency.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum download time for the last 4 requested segments. Download time is the time in seconds from first byte being received to the last byte">
<em>Download (min|avg|max):</em> {{videoDownload.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum ratio of the segment playback time to total download time over the last 4 segments">
<em>Ratio (min|avg|max):</em> {{videoRatio.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The absolute count of frames dropped by the rendering pipeline since play commenced">
<em>Dropped Frames:</em> {{videoDroppedFrames}}</span></p>
</div>
</div>
<div class="tab-pane fade" id="audio">
<div class="panel-body panel-stats">
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The bitrate of the representation being loaded">
<em>Bitrate:</em> {{audioBitrate}} kbps</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The representation index being loaded. Lowest index is 1">
<em>Index being loaded:</em> {{audioIndex}}{{audioPendingIndex}}/{{audioMaxIndex}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The length of the forward buffer, in seconds">
<em>Buffer Length:</em> {{audioBufferLength}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum latency over the last 4 requested segments. Latency is the time in seconds from request of segment to receipt of first byte">
<em>Latency (min|avg|max):</em> {{audioLatency.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum download time for the last 4 requested segments. Download time is the time in seconds from first byte being received to the last byte">
<em>Download (min|avg|max):</em> {{audioDownload.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum ratio of the segment playback time to total download time over the last 4 segments">
<em>Ratio (min|avg|max):</em> {{audioRatio.split('<').join('|')}}</span></p>
</div>
</div>
<div class="tab-pane fade" id="text">
<div class="panel-body panel-stats">
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The bitrate of the representation being loaded">
<em>Bitrate:</em> {{textBitrate}} kbps</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The representation index being loaded. Lowest index is 1">
<em>Index being loaded:</em> {{textIndex}}{{textPendingIndex}}/{{textMaxIndex}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The length of the forward buffer, in seconds">
<em>Buffer Length:</em> {{textBufferLength}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum latency over the last 4 requested segments. Latency is the time in seconds from request of segment to receipt of first byte">
<em>Latency (min|avg|max):</em> {{textLatency.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum download time for the last 4 requested segments. Download time is the time in seconds from first byte being received to the last byte">
<em>Download (min|avg|max):</em> {{textDownload.split('<').join('|')}}</span></p>
<p class="text-primary"><span class="text-success"
data-toggle="tooltip"
title="The minimum, average and maximum ratio of the segment playback time to total download time over the last 4 segments">
<em>Ratio (min|avg|max):</em> {{textRatio.split('<').join('|')}}</span></p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Protection Information -->
<!-- <div class="row" ng-repeat="d in drmData">
<div class="panel panel-info" ng-class="{sessionPanelPlaying: d.isPlaying}">
<h3>Protection Information</h3>
<div class="panel-heading panel-top">
<span class="panel-title">{{d.manifest.url}}</span>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-disabled="!d.licenseReceived" ng-click="play(d)">Play</button>
<button type="button" class="btn btn-default" ng-click="delete(d)">Delete</button>
</div>
</div>
<div class="col-sm-12" ng-show="d.ksconfig">
<div class="row">
<div class="col-sm-4">
<h4 ng-show="d.protCtrl.protectionModel.keySystem" class="keysystem shrink">Key System: <span class="label label-success">{{d.protCtrl.protectionModel.keySystem.systemString}}</span></h4>
<div><b>Init Data Types: </b>{{arrayToCommaSeparated(d.ksconfig.initDataTypes)}}</div>
<div><b>Persistent State: </b><span ng-show="d.ksconfig.persistentState">{{d.ksconfig.persistentState}}</span></div>
<div><b>Distinctive Identifier: </b><span ng-show="d.ksconfig.distinctiveIdentifier">{{d.ksconfig.distinctiveIdentifier}}</span></div>
</div>
<div class="col-sm-4">
<h5>Video Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="video in d.ksconfig.videoCapabilities">
<div><b>ContentType: </b>{{video.contentType}}</div>
<div><b>Robustness: </b>{{video.robustness}}</div>
</li>
</ul>
</div>
<div class="col-sm-4">
<h5>Audio Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="audio in d.ksconfig.audioCapabilities">
<div><b>ContentType: </b>{{audio.contentType}}</div>
<div><b>Robustness: </b>{{audio.robustness}}</div>
</li>
</ul>
</div>
</div>
</div>
<div class="errormessage" ng-show="d.error"><span class="label label-danger">ERROR</span><span class="errormessage">{{d.error}}</span></div>
<div class="panel panel-default sessionPanel" ng-repeat="s in d.sessions">
<div class="panel-heading panel-top">
<span class="panel-title">SessionID: {{s.sessionToken.getSessionID()}}</span>
<div class="btn-group">
<button type="button" ng-disabled="isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.loadKeySession(s.sessionID)">Load</button>
<button type="button" ng-disabled="!isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.removeKeySession(s.sessionToken)">Remove</button>
<button type="button" class="btn btn-default" ng-click="d.protCtrl.closeKeySession(s.sessionToken)">Close</button>
</div>
</div>
<div class="keymessage" ng-show="s.lastMessage">{{s.lastMessage}}</div>
<div class="keymessage"><b>Session Persistence: </b><span>{{getLoadedMessage(s)}}</span></div>
<h5 ng-show="s.getExpirationTime()">Expiration: {{s.getExpirationTime()}}</h5>
<table ng-show="isLoaded(s) && s.keystatus && s.keystatus.length > 0" class="table table-bordered table-hover">
<tr>
<th>Key ID</th>
<th class="centered">Key Status</th>
</tr>
<tr ng-repeat="keystatus in s.keystatus">
<td class="keyid">{{keystatus.key}}</td>
<td ng-class="{true: 'success'}[keystatus.status=='usable']" class="centered">{{keystatus.status}}</td>
</tr>
</table>
</div>
</div>
</div> -->
<!-- <div ng-switch id="stats-block" on="showCharts">
<div class="panel-body panel-stats" ng-switch-when="true">
<ul class="nav nav-tabs">
<li class="active"><a href="#bufferLevel" data-toggle="tab" ng-click="setBufferLevelChart(true)">Buffer level</a></li>
<li><a href="#consolelog" data-toggle="tab">Console Trace Panel</a></li>
</ul>
<div id="chartTabContent" class="tab-content">
<div class="tab-pane" id="bufferLevel" ng-class="{active:showBufferLevel == true}">
<div ng-switch on="showBufferLevel">
<div class="panel-body panel-stats" ng-switch-when="true">
<chart ng-model="bufferData"></chart>
</div>
</div>
</div>
<div class="tab-pane" id="consolelog"></div>
</div>
</div>
</div> -->
<div class="row">
<div class="panel">
<ul class="nav nav-tabs">
<li class="active">
<a href="#bufferLevel"
data-toggle="tab" >
<!-- ng-click="setBufferLevelChart(true);"> -->
<!-- setHtmlLogging(false);
shutdownDebugConsole();"> -->
Buffer level
</a>
</li>
<li>
<a href="#consoletracepanel"
data-toggle="tab"
ng-click="initDebugConsole();">
Console Trace Panel
</a>
</li>
</ul>
<div id="chartTabContent" class="tab-content">
<div class="tab-pane active" id="bufferLevel">
<!-- <div ng-switch on="showBufferLevel"> -->
<!-- <div id="chart-inventory" class="panel-body" ng-switch-when="true"> -->
<div id="debugCtrlBarChart">
<button class="topcoat-button--quiet debugButton"
id="debugEnableButton"
ng-click="showBufferLevel = !showBufferLevel;">{{chartEnabledLabel()}}</button>
</div>
<div id="chart-inventory"
class="panel-body">
<chart ng-model="bufferData"
ng-show="showBufferLevel"></chart>
<!-- </div> -->
</div>
</div>
<div class="tab-pane" id="consoletracepanel">
<div class="tab-content">
<div class="tab-pane active" id="tab3">
<div id="debugCtrlBar">
<button class="topcoat-button--quiet debugButton"
id="debugEnableButton"
ng-click="setHtmlLogging(!debugEnabled)">{{debugEnabledLabel()}}</button>
<button class="topcoat-button--quiet debugButton"
id="debugClearButton"
ng-click="clearHtmlLogging()">
Clear
</button>
</div>
<!-- <div id="debugLogView" style="height: 418px;"></div> -->
<ul>
<li ng-repeat="log in logbucket">{{log}}</li>
<!-- beet: {{logbucket.length}} -->
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-area">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="footer-text">Contributors:</h3>
<a
ng-repeat="item in contributors"
class="footer-text"
href="{{item.link}}"
target="_blank">
<img ng-show="hasLogo(item)" ng-src="{{item.logo}}" alt="{{item.link}}"/>
<span class="contributor" ng-show="!hasLogo(item)">{{item.name}}</span>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
| 35,974 | 54.431433 | 233 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/samples/dash-if-reference-player-beta/eme.html | <!DOCTYPE html>
<html ng-app="DashPlayer" lang="en">
<head>
<meta charset="utf-8"/>
<title>Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/x-icon" href="http://dashif.org/wp-content/uploads/2014/12/dashif.ico" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="app/lib/bootstrap/css/bootstrap-glyphicons.css">
<link rel="stylesheet" href="app/css/main.css">
<link rel="stylesheet" href="app/css/eme.css">
<link rel="stylesheet" href="../../contrib/akamai/controlbar/controlbar.css">
<!-- http://jquery.com/ -->
<script src="app/lib/jquery/jquery-1.10.2.min.js"></script>
<!-- http://angularjs.org/ -->
<script src="app/lib/angular/angular.min.js"></script>
<script src="app/lib/angular/angular-resource.min.js"></script>
<!-- http://getbootstrap.com/ -->
<script src="app/lib/bootstrap/js/bootstrap.min.js"></script>
<script src="../../dist/dash.debug.js"></script>
<script src="../../dist/dash.protection.min.js"></script>
<!-- App -->
<script src="../../contrib/akamai/controlbar/ControlBar.js"></script>
<script src="app/eme-main.js"></script>
</head>
<body ng-controller="DashController">
<div class="modal fade" id="streamModal">
<div class="modal-dialog">
<div class="list-group modal-list">
<a
ng-repeat="item in availableStreams"
href="#"
class="list-group-item"
ng-click="setStream(item)"
data-dismiss="modal">
{{item.name}}
</a>
</div>
</div>
</div>
<div class="container">
<div class="row title-header">
<a href="http://dashif.org/" target="_blank"><img class="image" src="app/img/if.png"/></a>
<span id="big-title">Reference Client</span>
<span>{{version}}</span>
<div class="github">
<iframe
id="star-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=watch&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true"
class="hidden-xs github-button">
</iframe>
<iframe
id="fork-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=fork&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true github-button">
</iframe>
</div>
</div>
<div class="row">
<div class="input-group">
<div id="desktop-streams" class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Stream <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li
ng-repeat="item in availableStreams"
ng-click="setStream(item)">
<a>{{item.name}}</a>
</li>
</ul>
</div>
<div id="mobile-streams" class="input-group-btn">
<button type="button" class="btn btn-primary" data-toggle="modal" href="#streamModal">
Stream <span class="caret"></span>
</button>
</div>
<input type="text" class="form-control" placeholder="manifest" ng-model="selectedItem.url">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doLoad()">Play</button>
<button class="btn btn-primary" type="button" ng-click="doLicenseFetch()">Fetch Licenses</button>
</span>
</div>
</div>
<div class="row">
<div class="dash-video-player col-md-9">
<div id="videoContainer">
<video controls="true"></video>
<div id="videoController" class="video-controller unselectable">
<div id="playPauseBtn" class="btn-play-pause" title="Play/Pause">
<span id="iconPlayPause" class="icon-play"></span>
</div>
<span id="videoTime" class="time-display">00:00:00</span>
<div id="fullscreenBtn" class="btn-fullscreen" title="Fullscreen">
<span class="icon-fullscreen-enter"></span>
</div>
<input type="range" id="volumebar" class="volumebar" value="1" min="0" max="1" step=".01" />
<div id="muteBtn" class="btn-mute" title="Mute">
<span id="iconMute" class="icon-mute-off"></span>
</div>
<div id="captionBtn" class="btn-caption" title="Closed Caption">
<span class="icon-caption"></span>
</div>
<span id="videoDuration" class="duration-display">00:00:00</span>
<div class="seekContainer">
<input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="shrink panel panel-default">
<div class="panel-heading panel-top">
<h1 class="panel-title">New Session Properties</h1>
</div>
<div class="panel-body">
<h5>Session Type</h5>
<div id="session-type" class="btn-group-vertical" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" id="temporary" autocomplete="off" checked>temporary
</label>
<label class="btn btn-default">
<input type="radio" id="persistent-license" autocomplete="off">persistent-license
</label>
<label class="btn btn-default">
<input type="radio" id="persistent-release-message" autocomplete="off">persistent-release
</label>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Protection Information</h3>
</div>
</div>
<div class="row" ng-repeat="d in drmData">
<div class="panel panel-info" ng-class="{sessionPanelPlaying: d.isPlaying}">
<div class="panel-heading panel-top">
<span class="panel-title">{{d.manifest.url}}</span>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-disabled="!d.licenseReceived" ng-click="play(d)">Play</button>
<button type="button" class="btn btn-default" ng-click="delete(d)">Delete</button>
</div>
</div>
<div class="col-sm-12" ng-show="d.ksconfig">
<div class="row">
<div class="col-sm-4">
<h4 ng-show="d.protCtrl.protectionModel.keySystem" class="keysystem shrink">Key System: <span class="label label-success">{{d.protCtrl.protectionModel.keySystem.systemString}}</span></h4>
<div><b>Init Data Types: </b>{{arrayToCommaSeparated(d.ksconfig.initDataTypes)}}</div>
<div><b>Persistent State: </b><span ng-show="d.ksconfig.persistentState">{{d.ksconfig.persistentState}}</span></div>
<div><b>Distinctive Identifier: </b><span ng-show="d.ksconfig.distinctiveIdentifier">{{d.ksconfig.distinctiveIdentifier}}</span></div>
</div>
<div class="col-sm-4">
<h5>Video Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="video in d.ksconfig.videoCapabilities">
<div><b>ContentType: </b>{{video.contentType}}</div>
<div><b>Robustness: </b>{{video.robustness}}</div>
</li>
</ul>
</div>
<div class="col-sm-4">
<h5>Audio Configs</h5>
<ul class="list-group">
<li class="list-group-item" ng-repeat="audio in d.ksconfig.audioCapabilities">
<div><b>ContentType: </b>{{audio.contentType}}</div>
<div><b>Robustness: </b>{{audio.robustness}}</div>
</li>
</ul>
</div>
</div>
</div>
<div class="errormessage" ng-show="d.error"><span class="label label-danger">ERROR</span><span class="errormessage">{{d.error}}</span></div>
<div class="panel panel-default sessionPanel" ng-repeat="s in d.sessions">
<div class="panel-heading panel-top">
<span class="panel-title">SessionID: {{s.sessionToken.getSessionID()}}</span>
<div class="btn-group">
<button type="button" ng-disabled="isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.loadKeySession(s.sessionID)">Load</button>
<button type="button" ng-disabled="!isLoaded(s)" class="btn btn-default" ng-click="d.protCtrl.removeKeySession(s.sessionToken)">Remove</button>
<button type="button" class="btn btn-default" ng-click="d.protCtrl.closeKeySession(s.sessionToken)">Close</button>
</div>
</div>
<div class="keymessage" ng-show="s.lastMessage">{{s.lastMessage}}</div>
<div class="keymessage"><b>Session Persistence: </b><span>{{getLoadedMessage(s)}}</span></div>
<h5 ng-show="s.getExpirationTime()">Expiration: {{s.getExpirationTime()}}</h5>
<table ng-show="isLoaded(s) && s.keystatus && s.keystatus.length > 0" class="table table-bordered table-hover">
<tr>
<th>Key ID</th>
<th class="centered">Key Status</th>
</tr>
<tr ng-repeat="keystatus in s.keystatus">
<td class="keyid">{{keystatus.key}}</td>
<td ng-class="{true: 'success'}[keystatus.status=='usable']" class="centered">{{keystatus.status}}</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="footer-area">
<div class="container">
<div class="row">
<div class="compat-box col-md-5">
<h3>Compatibility Notes:</h3>
<ul class="list-group">
<li class="list-group-item"><a href="https://github.com/Dash-Industry-Forum/dash.js">This project can be forked on GitHub.</a></li>
<li class="list-group-item">Use your browser's JavaScript console to view detailed information about stream playback.</li>
<li class="list-group-item"><a href="../getting-started-basic-embed/auto-load-single-video.html">See a base implementation here.</a></li>
<li class="list-group-item">A browser that supports MSE (Media Source Extensions) is required.</li>
<li class="list-group-item">As of 2/1/2015 supported on the following browsers: Desktop Chrome, Desktop Internet Explorer 11 under WIn8.1, Mobile Chrome for Android and Safari on Mac Yosemite</li>
<li class="list-group-item">Use the most up-to-date version of your browser for the best compatibility.</li>
</ul>
</div>
<div class="col-md-3">
<h3 class="footer-text">Player Libraries:</h3>
<a
ng-repeat="item in playerLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
<h3 class="footer-text">Showcase Libraries:</h3>
<a
ng-repeat="item in showcaseLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
</div>
<div class="col-md-4">
<h3 class="footer-text">Contributors:</h3>
<a
ng-repeat="item in contributors"
class="footer-text"
href="{{item.link}}"
target="_blank">
<img ng-show="hasLogo(item)" ng-src="{{item.logo}}" alt="{{item.link}}"/>
<span class="contributor" ng-show="!hasLogo(item)">{{item.name}}</span>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
| 14,474 | 50.696429 | 220 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/contrib/akamai/controlbar/snippet.html | <div id="videoController" class="video-controller unselectable">
<div id="playPauseBtn" class="btn-play-pause" title="Play/Pause">
<span id="iconPlayPause" class="icon-play"></span>
</div>
<span id="videoTime" class="time-display">00:00:00</span>
<div id="fullscreenBtn" class="btn-fullscreen" title="Fullscreen">
<span class="icon-fullscreen-enter"></span>
</div>
<input type="range" id="volumebar" class="volumebar" value="1" min="0" max="1" step=".01" />
<div id="muteBtn" class="btn-mute" title="Mute">
<span id="iconMute" class="icon-mute-off"></span>
</div>
<div id="captionBtn" class="btn-caption" title="Closed Caption">
<span class="icon-caption"></span>
</div>
<span id="videoDuration" class="duration-display">00:00:00</span>
<div class="seekContainer">
<input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>
</div>
</div> | 955 | 38.833333 | 96 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/contrib/videojs/example.html | <html>
<head>
<!-- Loading Video.js CDN-hosted Scripts from videojs.com -->
<link href="http://vjs.zencdn.net/5.8/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/5.8/video.js"></script>
<script src="../../dist/dash.all.debug.js"></script>
<!-- Load the videojs-contrib-dash script *after* both other projects -->
<script src="videojs-dash.js"></script>
</head>
<body>
<h1>videojs-tech-dashjs demo</h1>
<!-- Standard video.js embed with a DASH source -->
<video id="vid1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264">
<source src="http://rdmedia.bbc.co.uk/dash/ondemand/testcard/1/client_manifest-events.mpd" type='application/dash+xml'>
</video>
<script>
// Initalize the video.js player after videojs-contrib-dash has loaded
var myPlayer = videojs('vid1');
</script>
</body>
</html>
| 867 | 27.933333 | 121 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/dash.js/contrib/webmjs/example.html | <!DOCTYPE html>
<html ng-app="DashPlayer" lang="en">
<head>
<meta charset="utf-8"/>
<title>Dash JavaScript Player</title>
<meta name="description" content="" />
<link rel="icon" type="image/x-icon" href="http://dashif.org/wp-content/uploads/2014/12/dashif.ico" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no">
<link rel="stylesheet" href="../../samples/dash-if-reference-player/app/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../../samples/dash-if-reference-player/app/lib/bootstrap/css/bootstrap-glyphicons.css">
<link rel="stylesheet" href="../../samples/dash-if-reference-player/app/lib/angular.treeview/css/angular.treeview.css">
<link rel="stylesheet" href="../../samples/dash-if-reference-player/app/css/main.css">
<!-- http://jquery.com/ -->
<script src="../../samples/dash-if-reference-player/app/lib/jquery/jquery-1.10.2.min.js"></script>
<!-- http://angularjs.org/ -->
<script src="../../samples/dash-if-reference-player/app/lib/angular/angular.min.js"></script>
<script src="../../samples/dash-if-reference-player/app/lib/angular/angular-resource.min.js"></script>
<!-- http://getbootstrap.com/ -->
<script src="../../samples/dash-if-reference-player/app/lib/bootstrap/js/bootstrap.min.js"></script>
<!-- http://www.flotcharts.org/ -->
<script src="../../samples/dash-if-reference-player/app/lib/flot/jquery.flot.js"></script>
<!-- https://github.com/eu81273/angular.treeview -->
<script src="../../samples/dash-if-reference-player/app/lib/angular.treeview/angular.treeview.min.js"></script>
<script src="dash.webm.debug.js"></script>
<!-- App -->
<script src="../../samples/dash-if-reference-player/app/metrics.js"></script>
<script src="app/main.js"></script>
</head>
<body ng-controller="DashController">
<div class="modal fade" id="streamModal">
<div class="modal-dialog">
<div class="list-group modal-list">
<a
ng-repeat="item in availableStreams"
href="#"
class="list-group-item"
ng-click="setStream(item)"
data-dismiss="modal"
ng-show="isStreamAvailable(item.browsers)">
{{item.name}}
</a>
</div>
</div>
</div>
<div class="container">
<div class="row title-header">
<a href="http://dashif.org/" target="_blank"><img class="image" src="../../samples/dash-if-reference-player/app/img/if.png"/></a>
<span id="big-title">Reference Client</span>
<span>{{version}}</span>
<div class="github">
<iframe
id="star-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=watch&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true"
class="hidden-xs github-button">
</iframe>
<iframe
id="fork-button"
src="http://ghbtns.com/github-btn.html?user=Dash-Industry-Forum&repo=dash.js&type=fork&count=true&size=large"
height="30"
width="170"
frameborder="0"
scrolling="0"
allowTransparency="true github-button">
</iframe>
</div>
</div>
<div class="row">
<div class="input-group">
<div id="desktop-streams" class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Stream <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li
ng-repeat="item in availableStreams"
ng-click="setStream(item)"
ng-show="isStreamAvailable(item.browsers)">
<a>{{item.name}}</a>
</li>
</ul>
</div>
<div id="mobile-streams" class="input-group-btn">
<button type="button" class="btn btn-primary" data-toggle="modal" href="#streamModal">
Stream <span class="caret"></span>
</button>
</div>
<input type="text" class="form-control" placeholder="manifest" ng-model="selectedItem.url">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="doLoad()">Load</button>
</span>
</div>
</div>
<div class="row">
<div class="dash-video-player col-md-9">
<video controls="true"></video>
</div>
<div class="col-md-3">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">ABR</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:abrEnabled == false}"
ng-click="setAbrEnabled(false)">
<span>Off</span>
</button>
<button
type="button"
class="btn btn-default active"
ng-class="{active:abrEnabled == true}"
ng-click="setAbrEnabled(true)">
<span>On</span>
</button>
</div>
</div>
</div>
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Video</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-click="abrDown('video')">
<span class="glyphicon glyphicon-minus"></span>
</button>
<button
type="button"
class="btn btn-default"
ng-click="abrUp('video')">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<div class="panel-body panel-stats">
<p class="text-warning">{{videoBitrate}} kbps</p>
<p class="text-primary">Rep Index: <span class="text-success">{{videoIndex}}</span><span class="text-warning">{{videoPendingIndex}}</span>/<span class="text-success">{{videoMaxIndex}}</span></p>
<p class="text-primary">Buffer Length: <span class="text-success">{{videoBufferLength}}</span></p>
<p class="text-primary">Latency: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoLatency}}</p>
<p class="text-primary">Download: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoDownload}}</p>
<p class="text-primary">Ratio: <span class="text-success">last {{videoRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{videoRatio}}</p>
<p class="text-primary">Dropped Frames: <span class="text-success">{{videoDroppedFrames}}</span></p>
</div>
</div>
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Audio</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-click="abrDown('audio')">
<span class="glyphicon glyphicon-minus"></span>
</button>
<button
type="button"
class="btn btn-default"
ng-click="abrUp('audio')">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<div class="panel-body panel-stats">
<p class="text-warning">{{audioBitrate}} kbps</p>
<p class="text-primary">Rep Index: <span class="text-success">{{audioIndex}}</span><span class="text-warning">{{audioPendingIndex}}</span>/<span class="text-success">{{audioMaxIndex}}</span></p>
<p class="text-primary">Buffer Length: <span class="text-success">{{audioBufferLength}}</span></p>
<p class="text-primary">Latency: <span class="text-success">last {{audioLatencyCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioLatency}}</p>
<p class="text-primary">Download: <span class="text-success">last {{audioDownloadCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioDownload}}</p>
<p class="text-primary">Ratio: <span class="text-success">last {{audioRatioCount}} segments</span></p>
<p class="text-success" title="[low] < [average] < [high]">{{audioRatio}}</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Charts</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:showCharts == false}"
ng-click="setCharts(false)">
Hide
</button>
<button
type="button"
class="btn btn-default"
ng-class="{active:showCharts == true}"
ng-click="setCharts(true)">
Show
</button>
</div>
</div>
<div ng-switch on="showCharts">
<div class="panel-body panel-stats" ng-switch-when="true">
<chart ng-model="bufferData"></chart>
</div>
</div>
</div>
</div>
<div class="row">
<div class="panel">
<div class="panel-heading panel-top">
<span class="panel-title">Debug</span>
<div class="btn-group">
<button
type="button"
class="btn btn-default"
ng-class="{active:showDebug == false}"
ng-click="setDebug(false)">
Hide
</button>
<button
type="button"
class="btn btn-default"
ng-class="{active:showDebug == true}"
ng-click="setDebug(true)">
Show
</button>
</div>
</div>
<div ng-switch on="showDebug">
<div class="panel-body panel-stats" ng-switch-when="true">
<ul class="nav nav-tabs">
<li class="dropdown">
<a href="#" id="metricsDropdown" class="dropdown-toggle" data-toggle="dropdown">Metrics <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu" aria-labelledby="metricsDropdown">
<li><a href="#video-metrics" tabindex="-1" data-toggle="tab">Video</a></li>
<li><a href="#audio-metrics" tabindex="-1" data-toggle="tab">Audio</a></li>
</ul>
</li>
<li><a href="#notes" data-toggle="tab">Release Notes</a></li>
</ul>
<div id="debugTabContent" class="tab-content">
<div class="tab-pane" id="video-metrics">
<button
type="button"
class="btn btn-default"
ng-click="getVideoTreeMetrics()">
Video - Update
</button>
<div
class="tree"
data-angular-treeview="true"
data-tree-model="videoMetrics"
data-node-label="text"
data-node-children="items">
</div>
</div>
<div class="tab-pane" id="audio-metrics">
<button
type="button"
class="btn btn-default"
ng-click="getAudioTreeMetrics()">
Audio - Update
</button>
<div
class="tree"
data-angular-treeview="true"
data-tree-model="audioMetrics"
data-node-label="text"
data-node-children="items">
</div>
</div>
<div class="tab-pane" id="notes">
<div ng-repeat="note in releaseNotes" class="note-box">
<span><b>{{note.title}}</b></span><br/>
<span ng-repeat="text in note.items">
{{text}}<br/>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-area">
<div class="container">
<div class="row">
<div class="compat-box col-md-5">
<h3>Compatibility Notes:</h3>
<ul class="list-group">
<li class="list-group-item"><a href="https://github.com/Dash-Industry-Forum/dash.js">This project can be forked on GitHub.</a></li>
<li class="list-group-item">Use your browser's JavaScript console to view detailed information about stream playback.</li>
<li class="list-group-item"><a href="baseline.html">See a base implementation here.</a></li>
<li class="list-group-item">A browser that supports MSE (Media Source Extensions) is required.</li>
<li class="list-group-item">As of 8/30/13, Desktop Chrome, Desktop Internet Explorer 11, and Mobile Chrome Beta for Android are the only browsers supported.</li>
<li class="list-group-item">Use the most up-to-date version of your browser for the best compatibility.</li>
<li class="list-group-item">Many of the streams in the dropdown box (with ?version=all) only work in the developer channel or Canary version of Chrome.</li>
<li class="list-group-item"><a href="index.html?version=stable">Stable Chrome Streams</a></li>
<li class="list-group-item"><a href="index.html?version=beta">Beta Chrome Streams</a></li>
<li class="list-group-item"><a href="index.html?version=dev">Dev Chrome Streams</a></li>
<li class="list-group-item"><a href="index.html?version=canary">Canary Chrome Streams</a></li>
<li class="list-group-item"><a href="index.html?version=explorer">Internet Explorer 11 Streams</a></li>
</ul>
</div>
<div class="col-md-3">
<h3 class="footer-text">Player Libraries:</h3>
<a
ng-repeat="item in playerLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
<h3 class="footer-text">Showcase Libraries:</h3>
<a
ng-repeat="item in showcaseLibraries"
class="footer-text"
href="{{item.link}}"
target="_blank">
{{item.name}}
</a>
</div>
<div class="col-md-4">
<h3 class="footer-text">Contributors:</h3>
<a
ng-repeat="item in contributors"
class="footer-text"
href="{{item.link}}"
target="_blank">
<img ng-show="hasLogo(item)" ng-src="{{item.logo}}" alt="{{item.link}}"/>
<span class="contributor" ng-show="!hasLogo(item)">{{item.name}}</span>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
| 19,070 | 52.27095 | 218 | html |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/ndn-entrypoint.sh | #!/bin/bash
nfd
trap "pkill nfd; exit" SIGHUP SIGINT SIGTERM
| 61 | 14.5 | 44 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/rebuild-ndn-icp.sh | #!/bin/bash
waf_config_cmd="./waf configure --prefix=/usr"
waf_cmd="./waf"
# If we are debugging, do some prep and set the cmake flags
if [[ $* == *--debug* ]]; then
waf_config_cmd="$waf_config_cmd --debug"
waf_cmd="$waf_cmd --debug"
if [ ! -e /DEBUG_NDN_ICP ]; then
# sed -i 's/cxxflags=\[/cxxflags=\["-ggdb", "-O0"/g' /code/ndn-icp-download/wscript
touch /DEBUG_NDN_ICP
fi
# If using valgrind
elif [[ $* == *--valgrind* ]]; then
if [ ! -e /DEBUG_NDN_DASH ]; then
echo "no debug ndn dash"
eval "/rebuild-player.sh --debug"
fi
if [ ! -e /DEBUG_NDN_ICP ]; then
eval "/rebuild-ndn-icp.sh --debug"
fi
exec_cmd="valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=/
..valgrind-out.txt $exec_cmd"
# If we aren't debugging, revert the debug prep
else
if [ -e /DEBUG_NDN_ICP ]; then
# sed -i 's/cxxflags=\["-ggdb", "-O0"/cxxflags=\[/g' /code/ndn-icp-download/wscript
rm /DEBUG_NDN_ICP
fi
fi
# Execute
cd /code/ndn-icp-download
./waf clean distclean
eval $waf_config_cmd
eval $waf_cmd
./waf install
| 1,130 | 28 | 105 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/restart.sh | #!/bin/bash
exec_cmd="/code/ndn-dash/libdash/qtsampleplayer/build/qtsampleplayer -nohead -n 0.8 -bola 44 -u /n/mpd"
# Stop the current process
pkill -9 qtsampleplayer
# Remove previous logs
rm /log
rm /player-out.txt
# If we are debugging, do some prep and set the cmake flags
if [[ $* == *--debug* ]]; then
if [ ! -e /DEBUG_NDN_DASH ]; then
eval "/rebuild-player.sh --debug"
fi
if [ ! -e /DEBUG_NDN_ICP ]; then
eval "/rebuild-ndn-icp.sh --debug"
fi
exec_cmd="gdb --args $exec_cmd"
# If we aren't debugging, revert the debug prep
else
if [ -e /DEBUG_NDN_DASH ]; then
eval "/rebuild-player.sh"
fi
if [ -e /DEBUG_NDN_ICP ]; then
eval "/rebuild-ndn-icp.sh"
fi
fi
# If we're rerouting our output, be sure we can
if [[ $* == *--player-out* ]]; then
if [[ $* == *--debug* ]]; then
echo "Error; cannot debug and reroute output"
exit 1
fi
exec_cmd="$exec_cmd >> player-out.txt &"
fi
# Execute
eval $exec_cmd
| 1,002 | 22.880952 | 103 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/rebuild-player.sh | #!/bin/bash
cmake_flags="-DLIBAV_ROOT_DIR=/usr/lib"
# If we are debugging, do some prep and set the cmake flags
if [[ $* == *--debug* ]]; then
if [ ! -e /DEBUG_NDN_DASH ]; then
sed -i 's/O3/O0/g' /code/ndn-dash/libdash/qtsampleplayer/CMakeLists.txt
touch /DEBUG_NDN_DASH
fi
cmake_flags="$cmake_flags -DCMAKE_BUILD_TYPE=Debug"
# If we aren't debugging, revert the debug prep
else
if [ -e /DEBUG_NDN_DASH ]; then
sed -i 's/O0/O3/g' /code/ndn-dash/libdash/qtsampleplayer/CMakeLists.txt
rm /DEBUG_NDN_DASH
fi
fi
# Execute
cd /code/ndn-dash/libdash/qtsampleplayer/build
cmake .. $cmake_flags
make
| 647 | 26 | 79 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/executeSimpleScenario.sh | #!/bin/bash
st=""
for i in "$@"
do
if [[ $i == *"nohead"* ]] || [[ $i == "-n" ]] || [[ $i == "-u" ]] || [[ $i == *"mpd"* ]]
then
st=`echo $st`
else
if [[ $i == *"-"* ]]
then
st_tmp=`echo $i | cut -d "-" -f 2`
st=`echo $st\_$st_tmp`
else
st=`echo $st\_$i`
fi
fi
done
#rm log*
#sudo tail -n 1 -f /root/log/link_$(hostname)_server.log > log$(hostname) &
#sleep $((5 * $(($(hostname | cut -dt -f2) - 1))))
sleep 1
./ndn-dash/libdash/qtsampleplayer/build/qtsampleplayer $@
if [[ $@ == *"ndn"* ]]
then
mv log logNDN$(hostname | cut -dt -f2)$st
else
mv log logTCP$(hostname | cut -dt -f2)$st
fi
#sudo killall tail
| 640 | 16.324324 | 89 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/createClient.sh | #!/bin/sh
#sleep 5
export MAKEFLAGS="-j $(grep -c ^processor /proc/cpuinfo)"
setcap cap_net_raw=eip /usr/local/bin/nfd
setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/nfd
#service nfd stop
#service nfd start
#Todo register route to server
#nfdc create ether://[00:16:3e:00:00:07]/server
#nfdc register /n $(nfd-status | grep 00:16:3e:00:00:07 | cut -d= -f2 | awk '{print $1}')
mkdir /root/log
#/bin/bash -c "nohup ifstat -i server -b -t > /root/log/link_client_server.log &"
cd /code
cd ndn-icp-download
./waf clean
./waf configure --prefix=/usr
#./waf
./waf install
cd /code
cd ndn-dash
cd libdash
mkdir build; cd build; cmake ..; make;
cd ..
cd qtsampleplayer; mkdir build; cd build; cmake .. -DLIBAV_ROOT_DIR=/usr/lib; make
| 736 | 23.566667 | 89 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Exec_AdapTech_Experiments.sh | #!/bin/bash
## Launching AdapTech Experiments
LOW=(10 20 30)
HIGH=(40 60 80)
SCENARIO=(ndn)
ewmaAlpha=0.8
for s in "${SCENARIO[@]}"
do
for l in "${LOW[@]}"
do
for h in "${HIGH[@]}"
do
### From the client container ###
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; killall Profile_BW*"
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; /root/Profile_BW_Shaping.sh 600 60"
# Launch the experiment with the given parameters
if [[ $s == "ndn" ]] #NDN
then
./executeSimpleScenario.sh -nohead -n -br $ewmaAlpha $l $h -u ndn:/n/mpd
else #TCP
./executeSimpleScenario.sh -nohead -br $ewmaAlpha $l $h -u http://10.2.0.1/videos/BigBuckBunny.mpd
fi
done
done
done
| 1,007 | 28.647059 | 130 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/executeDockerScenario.sh | #!/bin/bash
#TODO BUILD
TARGET=(docker) #(6 8 10 12 14 16 18 20 22) # It can be reduced to the desired cases
SCENARIO=(ndn) #instead of (ndn tcp)
ewmaAlpha=0.8
st=""
for i in "$@"
do
if [[ $i == *"nohead"* ]] || [[ $i == "-n" ]] || [[ $i == "-u" ]] || [[ $i == *"mpd"* ]]
then
st=`echo $st`
else
if [[ $i == *"-"* ]]
then
st_tmp=`echo $i | cut -d "-" -f 2`
st=`echo $st\_$st_tmp`
else
st=`echo $st\_$i`
fi
fi
done
#rm log*
#sudo tail -n 1 -f /root/log/link_$(hostname)_server.log > log$(hostname) &
#sleep $((5 * $(($(hostname | cut -dt -f2) - 1))))
sleep 1
/code/ndn-dash/libdash/qtsampleplayer/build/qtsampleplayer $@
#sudo killall tail
| 676 | 17.297297 | 89 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Exec_BOLA_Experiments.sh | #!/bin/bash
## Launching BOLA Experiments
TARGET=(6 8) #(6 8 10 12 14 16 18 20 22) # It can be reduced to the desired cases
SCENARIO=(ndn) #instead of (ndn tcp)
ewmaAlpha=0.8
for s in "${SCENARIO[@]}"
do
for h in "${TARGET[@]}"
do
### From the client container ###
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; killall Profile_BW*" #why 10.20.0.1 (eth0) instead of 10.2.0.1 (server)?
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; /root/Profile_BW_Shaping.sh 600 60"
# Launch the experiment with the given parameters
if [[ $s == "ndn" ]] #NDN
then
./executeSimpleScenario.sh -nohead -n -bola $ewmaAlpha $h -u ndn:/n/mpd
else #TCP
./executeSimpleScenario.sh -nohead -bola $ewmaAlpha $h -u http://10.2.0.1/videos/BigBuckBunny.mpd
fi
done
done
| 1,108 | 38.607143 | 166 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Exec_PANDA_Experiments.sh | #!/bin/bash
## Launching PANDA Experiments
TARGET=(34) #(34 44 54)
SCENARIO=(ndn) #instead of (ndn tcp)
ewmaAlpha=0.8
for s in "${SCENARIO[@]}"
do
for h in "${TARGET[@]}"
do
### From the client container ###
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; killall Profile_BW*"
ssh -f 10.2.0.1 -l root "source /home/ubuntu/.bashrc; /root/Profile_BW_Shaping.sh 600 60"
# Launch the experiment with the given parameters
if [[ $s == "ndn" ]] #NDN
then
./executeSimpleScenario.sh -nohead -n -p $ewmaAlpha $h -u ndn:/n/mpd
else #TCP
./executeSimpleScenario.sh -nohead -p $ewmaAlpha $h -u http://10.2.0.1/videos/BigBuckBunny.mpd
fi
done
done
| 853 | 30.62963 | 118 | sh |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sdr-exclude-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
Producer p(sampleName);
p.attach();
std::string d = "d-content";
p.produce(Name("d"), (uint8_t*)d.c_str(), d.size());
std::string e = "e-content";
p.produce(Name("e"), (uint8_t*)e.c_str(), e.size());
std::string f = "f-content";
p.produce(Name("f"), (uint8_t*)f.c_str(), f.size());
sleep(300);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 1,938 | 30.786885 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/manifest-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer()
: m_seenManifestSegments(0)
, m_seenDataSegments(0)
, m_byteCounter(0)
{
}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content((char*)buffer, bufferSize);
m_byteCounter+=bufferSize;
std::cout << "REASSEMBLED " << content << std::endl;
std::cout << "**************************************************" << std::endl;
std::cout << m_byteCounter << std::endl;
std::cout << "**************************************************" << std::endl;
}
void
countData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << std::endl;
if (data.getContentType() == CONTENT_DATA_TYPE)
{
m_seenDataSegments++;
std::cout << "Saw Content segment" << data.getName().get(-1) << std::endl;
}
else if (data.getContentType() == MANIFEST_DATA_TYPE)
{
m_seenManifestSegments++;
std::cout << "Saw Manifest segment" << data.getName().get(-1) << std::endl;
}
}
bool
verifyData(Consumer& c, const Data& data)
{
if (data.getContentType() == CONTENT_DATA_TYPE) // this should never be true
std::cout << "VERIFY CONTENT" << std::endl;
else if (data.getContentType() == MANIFEST_DATA_TYPE)
std::cout << "VERIFY MANIFEST" << std::endl;
return true;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
private:
int m_seenManifestSegments;
int m_seenDataSegments;
int m_byteCounter;
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_TO_VERIFY,
(ConsumerDataVerificationCallback)bind(&CallbackContainer::verifyData, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::countData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,913 | 29.578125 | 100 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sequential-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 30*1024
#define IDENTITY_NAME "/sequence/performance"
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
Producer p(sampleName);
p.setContextOption(SND_BUF_SIZE, 60000);
p.attach();
uint8_t* content = new uint8_t[CONTENT_LENGTH];
for (uint64_t i = 0; i <= 1000; i++)
{
Name n;
n.append(name::Component::fromNumber(i));
p.produce(n, content, CONTENT_LENGTH);
}
sleep(500);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,126 | 29.826087 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/idr-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer()
{
}
void
onPacket(Producer& p, Data& data)
{
std::cout << data;
std::string content = reinterpret_cast<const char*>(data.getContent().value());
content = content.substr(0, data.getContent().value_size());
std::cout << content << std::endl;
std::cout << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/test");
CallbackContainer cb;
Producer *p = new Producer(sampleName);
p->setContextOption(DATA_LEAVE_CNTX,
(ProducerDataCallback)bind(&CallbackContainer::onPacket, &cb, _1, _2));
p->setContextOption(INFOMAX, true);
p->setContextOption(INFOMAX_PRIORITY, INFOMAX_SIMPLE_PRIORITY); // generate only lists for the root node
// p->setContextOption(INFOMAX_PRIORITY, INFOMAX_MERGE_PRIORITY); // generate lists for all sub-trees
// p->setContextOption(INFOMAX_UPDATE_INTERVAL, 10000);
p->attach();
std::string ac = "a/c-content";
p->produce(Name("a/c"), (uint8_t*)ac.c_str(), ac.size());
std::string bd = "a/d-content";
p->produce(Name("a/d"), (uint8_t*)bd.c_str(), bd.size());
std::string be = "b/e-content";
p->produce(Name("b/e"), (uint8_t*)be.c_str(), be.size());
std::string cf = "c/f-content";
p->produce(Name("c/f"), (uint8_t*)cf.c_str(), cf.size());
std::string ag = "a/g-content";
p->produce(Name("a/g"), (uint8_t*)ag.c_str(), ag.size());
sleep(300);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,007 | 30.333333 | 107 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sdr-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
// #include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
std::cout << "Content from the data packet " << content1 << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Consumer c(sampleName, SDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,706 | 29.41573 | 102 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/broadcast-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
void
onP1(Producer& p, const Interest& interest)
{
std::cout << "Producer 1 got " << interest.toUri() << std::endl;
}
void
onP2(Producer& p, const Interest& interest)
{
std::cout << "Producer 2 got " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/q/w/e/r");
CallbackContainer c;
Producer p1(sampleName);
p1.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP1, &c, _1, _2));
p1.attach();
Producer p2(sampleName);
p2.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP2, &c, _1, _2));
p2.attach();
sleep(300);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,318 | 29.513158 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/idr-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content((char*)buffer, bufferSize);
std::cout << "Content : " << content << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << data.getName() << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/test");
CallbackContainer stubs;
Consumer c(sampleName, IDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
c.consume(Name());
c.consume(Name());
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,757 | 28.655914 | 100 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-verification-performance.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/sequence/performance"
class Performance
{
public:
Performance()
: m_byteCounter(0)
{}
void
onInterestLeaves(Consumer& c, Interest& interest)
{
std::cout << "Leaving: " << interest.toUri() << std::endl;
}
void
onDataEnters(Consumer& c, const Data& data)
{
std::cout << "DATA IN" << data.getName() << std::endl;
if (data.getName().get(-1).toSegment() == 0)
{
m_reassemblyStart = time::system_clock::now();
}
}
void
onContent(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
m_byteCounter += bufferSize;
if (m_byteCounter == CONTENT_LENGTH)
{
std::cout << "DONE" << std::endl;
m_reassemblyStop = time::system_clock::now();
}
}
ndn::time::steady_clock::TimePoint::clock::duration
getReassemblyDuration()
{
return m_reassemblyStop - m_reassemblyStart;
}
private:
uint32_t m_byteCounter;
time::system_clock::TimePoint m_reassemblyStart;
time::system_clock::TimePoint m_reassemblyStop;
};
class Verificator
{
public:
Verificator()
{
Name identity(IDENTITY_NAME);
Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
m_publicKey = m_keyChain.getPublicKey(keyName);
};
bool
onPacket(Consumer& c, const Data& data)
{
if (Validator::verifySignature(data, *m_publicKey))
{
std::cout << "VERIFIED " << data.getName() << std::endl;
return true;
}
else
{
std::cout << "UNVERIFIED " << data.getName() << std::endl;
return false;
}
}
private:
KeyChain m_keyChain;
shared_ptr<PublicKey> m_publicKey;
};
int
main(int argc, char** argv)
{
Verificator verificator;
Performance performance;
Name sampleName("/a/b/c");
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&Performance::onDataEnters, &performance, _1, _2));
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&Performance::onInterestLeaves, &performance, _1, _2));
c.setContextOption(DATA_TO_VERIFY,
(ConsumerDataVerificationCallback)bind(&Verificator::onPacket, &verificator, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&Performance::onContent, &performance, _1, _2, _3));
c.consume(Name());
std::cout << "**************************************************************" << std::endl;
std::cout << "Sequence reassembly duration " << performance.getReassemblyDuration() << std::endl;
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,345 | 27.03871 | 113 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-signing-performance.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/sequence/performance"
class Performance
{
public:
Performance(){}
void
onNewSegment(Producer& p, Data& data)
{
if (data.getName().get(-1).toSegment() == 0)
{
m_segmentationStart = time::system_clock::now();
}
}
void
onSegmentFinalized(Producer& p, Data& data)
{
m_segmentationStop = time::system_clock::now();
}
ndn::time::steady_clock::TimePoint::clock::duration
getSegmentationDuration()
{
return m_segmentationStop - m_segmentationStart;
}
void
onInterest(Producer& p, const Interest& interest)
{
std::cout << "Entering " << interest.toUri() << std::endl;
}
private:
time::system_clock::TimePoint m_segmentationStart;
time::system_clock::TimePoint m_segmentationStop;
};
class Signer
{
public:
Signer()
: m_counter(0)
, m_identityName(IDENTITY_NAME)
{
m_keyChain.createIdentity(m_identityName);
}
void
onPacket(Producer& p, Data& data)
{
m_counter++;
m_keyChain.signByIdentity(data, m_identityName);
}
private:
KeyChain m_keyChain;
int m_counter;
Name m_identityName;
};
int
main(int argc, char** argv)
{
Signer signer;
Performance performance;
Name sampleName("/a/b/c");
Producer p(sampleName);
p.setContextOption(SND_BUF_SIZE, 60000);
p.setContextOption(NEW_DATA_SEGMENT,
(ProducerDataCallback)bind(&Performance::onNewSegment, &performance, _1, _2));
p.setContextOption(DATA_TO_SECURE,
(ProducerDataCallback)bind(&Signer::onPacket, &signer, _1, _2));
p.setContextOption(DATA_LEAVE_CNTX,
(ProducerDataCallback)bind(&Performance::onSegmentFinalized, &performance, _1, _2));
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&Performance::onInterest, &performance, _1, _2));
p.attach();
uint8_t* content = new uint8_t[CONTENT_LENGTH];
p.produce(Name(), content, CONTENT_LENGTH);
std::cout << "**************************************************************" << std::endl;
std::cout << "Sequence segmentation duration " << performance.getSegmentationDuration() << std::endl;
sleep(500);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,938 | 26.93617 | 103 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/udr-fastretx-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << data.getName() << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
void
retxInterest(Consumer& c, Interest& interest)
{
c.stop();
std::cout << "Retransmission " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/b/n/m");
CallbackContainer stubs;
Consumer c(sampleName, UDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(INTEREST_RETRANSMIT,
(ConsumerInterestCallback)bind(&CallbackContainer::retxInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,653 | 29.159091 | 102 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sdr-exclude-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
std::cout << "Content " << content1 << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << data.getName() << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Consumer c(sampleName, SDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
Exclude exclusion;
exclusion.excludeOne(Name("d").get(0));
c.setContextOption(EXCLUDE_S, exclusion); // /a/b/c/d will be excluded
c.consume(Name());
exclusion.excludeBefore(Name("e").get(0));
c.setContextOption(EXCLUDE_S, exclusion); // /a/b/c/d and /a/b/c/e will be excluded
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,013 | 29.444444 | 100 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/udr-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processInterest(Producer& p, const Interest& interest)
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
std::string a(5000,'A');
std::string b(5000,'B');
std::string c(5000,'C');
std::string d(5000,'D');
std::string e(5000,'E');
std::string f(5000,'F');
std::string g(5000,'G');
std::string i(5000,'I');
std::string h(5000,'H');
std::string j(5000,'J');
std::string k(5000,'K');
std::string l(5000,'L');
std::string m(5000,'M');
std::string n(5000,'N');
std::string o(5000,'O');
std::string P(5000,'P');
std::string r(5000,'R');
std::string s(5000,'S');
std::string t(5000,'T');
std::string v(5000,'V');
std::string u(5000,'U');
std::string content = a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u;
Name emptySuffix;
p.produce(emptySuffix, (uint8_t*)content.c_str(), content.size());
}
void
processIncomingInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.getName() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Producer p(sampleName);
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::processIncomingInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::processInterest, &stubs, _1, _2));
p.attach();
sleep(300); // because attach() is non-blocking
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,197 | 29.169811 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/broadcast-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
std::cout << "CONTENT " << content1 << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/q/w/e");
CallbackContainer stubs;
Consumer c(sampleName, SDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name("r"));
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,740 | 29.455556 | 102 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sdr-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
// #include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
onCacheMiss(Producer& p, const Interest& interest)
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
std::string content = "ECHO";
Name emptySuffix;
p.produce(emptySuffix, (uint8_t*)content.c_str(), content.size());
}
void
onNewInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.getName() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Producer p(sampleName);
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onNewInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::onCacheMiss, &stubs, _1, _2));
p.attach();
sleep(10); // because attach() is non-blocking
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,531 | 29.142857 | 103 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/manifest-verification-performance.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/manifest/performance"
class Performance
{
public:
Performance()
: m_byteCounter(0)
{}
void
onInterestLeaves(Consumer& c, Interest& interest)
{
std::cout << "Leaving: " << interest.toUri() << std::endl;
}
void
onDataEnters(Consumer& c, const Data& data)
{
std::cout << "DATA IN" << data.getName() << std::endl;
if (data.getName().get(-1).toSegment() == 1) // because [0] is the manifest which comes later
{
m_reassemblyStart = time::system_clock::now();
}
}
void
onContent(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
m_byteCounter += bufferSize;
std::cout << "GOT" << m_byteCounter << " BYTES" << std::endl;
if (m_byteCounter == CONTENT_LENGTH)
{
std::cout << "DONE" << std::endl;
m_reassemblyStop = time::system_clock::now();
}
}
ndn::time::steady_clock::TimePoint::clock::duration
getReassemblyDuration()
{
return m_reassemblyStop - m_reassemblyStart;
}
private:
uint32_t m_byteCounter;
time::system_clock::TimePoint m_reassemblyStart;
time::system_clock::TimePoint m_reassemblyStop;
};
class Verificator
{
public:
Verificator()
{
Name identity(IDENTITY_NAME);
Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
m_publicKey = m_keyChain.getPublicKey(keyName);
};
bool
onPacket(Consumer& c, const Data& data)
{
if (Validator::verifySignature(data, *m_publicKey))
{
std::cout << "VERIFIED " << data.getName() << std::endl;
return true;
}
else
{
std::cout << "UNVERIFIED " << data.getName() << std::endl;
return false;
}
}
private:
KeyChain m_keyChain;
shared_ptr<PublicKey> m_publicKey;
};
int
main(int argc, char** argv)
{
Verificator verificator;
Performance performance;
Name sampleName("/a/b/c");
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&Performance::onDataEnters, &performance, _1, _2));
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&Performance::onInterestLeaves, &performance, _1, _2));
c.setContextOption(DATA_TO_VERIFY,
(ConsumerDataVerificationCallback)bind(&Verificator::onPacket, &verificator, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&Performance::onContent, &performance, _1, _2, _3));
c.consume(Name());
std::cout << "**************************************************************" << std::endl;
std::cout << "Manifest reassembly duration" << performance.getReassemblyDuration() << std::endl;
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,439 | 27.831169 | 111 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/udr-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
std::cout << "CONTENT " << content1 << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Consumer c(sampleName, UDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,683 | 29.157303 | 102 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-nack-delay-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer()
: m_interestCounter(0)
{}
void
processInterest(Producer& p, const Interest& interest)
{
m_interestCounter++;
// to make consumer do retransmissions
if (m_interestCounter <= 5)
{
ApplicationNack appNack(interest, ApplicationNack::PRODUCER_DELAY);
appNack.setDelay(5000); // in ms
p.nack(appNack);
}
else
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
std::string a(5000,'A');
std::string b(5000,'B');
std::string c(5000,'C');
std::string d(5000,'D');
std::string e(5000,'E');
std::string f(5000,'F');
std::string g(5000,'G');
std::string i(5000,'I');
std::string h(5000,'H');
std::string j(5000,'J');
std::string k(5000,'K');
std::string l(5000,'L');
std::string m(5000,'M');
std::string n(5000,'N');
std::string o(5000,'O');
std::string P(5000,'P');
std::string r(5000,'R');
std::string s(5000,'S');
std::string t(5000,'T');
std::string v(5000,'V');
std::string u(5000,'U');
std::string content = a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u;
Name emptySuffix;
p.produce(emptySuffix, (uint8_t*)content.c_str(), content.size());
}
}
void
processIncomingInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.getName() << std::endl;
}
private:
int m_interestCounter;
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Producer p(sampleName);
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::processIncomingInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::processInterest, &stubs, _1, _2));
p.attach();
sleep(300); // because attach() is non-blocking
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,577 | 28.089431 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-exclude-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/sequence/performance"
class Performance
{
public:
Performance(){}
void
onNewSegment(Producer& p, Data& data)
{
if (data.getName().get(-1).toSegment() == 0)
{
m_segmentationStart = time::system_clock::now();
}
}
void
onSegmentFinalized(Producer& p, Data& data)
{
m_segmentationStop = time::system_clock::now();
}
ndn::time::steady_clock::TimePoint::clock::duration
getSegmentationDuration()
{
return m_segmentationStop - m_segmentationStart;
}
void
onInterest(Producer& p, const Interest& interest)
{
std::cout << "Entering " << interest.toUri() << std::endl;
}
void
onMiss(Producer& p, const Interest& interest)
{
std::cout << "Cache miss " << interest.toUri() << std::endl;
}
private:
time::system_clock::TimePoint m_segmentationStart;
time::system_clock::TimePoint m_segmentationStop;
};
class Signer
{
public:
Signer()
: m_counter(0)
, m_identityName(IDENTITY_NAME)
{
m_keyChain.createIdentity(m_identityName);
}
void
onPacket(Producer& p, Data& data)
{
m_counter++;
m_keyChain.signByIdentity(data, m_identityName);
}
private:
KeyChain m_keyChain;
int m_counter;
Name m_identityName;
};
int
main(int argc, char** argv)
{
Signer signer;
Performance performance;
Name sampleName("/a/b/c");
Producer p(sampleName);
p.setContextOption(SND_BUF_SIZE, 60000);
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&Performance::onInterest, &performance, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&Performance::onMiss, &performance, _1, _2));
p.attach();
uint8_t* content = new uint8_t[CONTENT_LENGTH];
p.produce(Name(), content, CONTENT_LENGTH);
std::cout << "Made packets with weak signature. Sleep for 50 seconds" << std::endl;
sleep(50);
//clear internal cache
p.setContextOption(SND_BUF_SIZE, 0);
p.setContextOption(SND_BUF_SIZE, 60000);
p.setContextOption(DATA_TO_SECURE,
(ProducerDataCallback)bind(&Signer::onPacket, &signer, _1, _2));
p.produce(Name(), content, CONTENT_LENGTH);
std::cout << "Made packets with RSA signature. Sleep for 100 seconds" << std::endl;
sleep(100);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,014 | 25.766667 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-exclude-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/sequence/performance"
class Performance
{
public:
Performance()
: m_byteCounter(0)
{}
void
onInterestLeaves(Consumer& c, Interest& interest)
{
std::cout << "Leaving: " << interest.toUri() << std::endl;
}
void
onDataEnters(Consumer& c, const Data& data)
{
std::cout << "DATA IN" << data.getName() << std::endl;
if (data.getName().get(-1).toSegment() == 0)
{
m_reassemblyStart = time::system_clock::now();
}
}
void
onContent(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
m_byteCounter += bufferSize;
std::cout << " Bytes " << m_byteCounter << std::endl;
if (m_byteCounter == CONTENT_LENGTH)
{
std::cout << "DONE" << std::endl;
m_reassemblyStop = time::system_clock::now();
}
}
ndn::time::steady_clock::TimePoint::clock::duration
getReassemblyDuration()
{
return m_reassemblyStop - m_reassemblyStart;
}
private:
uint32_t m_byteCounter;
time::system_clock::TimePoint m_reassemblyStart;
time::system_clock::TimePoint m_reassemblyStop;
};
class Verificator
{
public:
Verificator()
{
Name identity(IDENTITY_NAME);
Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
m_publicKey = m_keyChain.getPublicKey(keyName);
};
bool
onPacket(Consumer& c, const Data& data)
{
if (Validator::verifySignature(data, *m_publicKey))
{
return true;
}
else
{
return false;
}
}
private:
KeyChain m_keyChain;
shared_ptr<PublicKey> m_publicKey;
};
int
main(int argc, char** argv)
{
Verificator verificator;
Performance performance;
Name sampleName("/a/b/c");
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&Performance::onDataEnters, &performance, _1, _2));
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&Performance::onInterestLeaves, &performance, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&Performance::onContent, &performance, _1, _2, _3));
c.consume(Name());
sleep(50);
std::cout << "Now consuming with more strict verification" << std::endl;
c.setContextOption(DATA_TO_VERIFY,
(ConsumerDataVerificationCallback)bind(&Verificator::onPacket, &verificator, _1, _2));
c.consume(Name());
sleep(50);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,197 | 26.083871 | 113 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/udr-fastretx-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processInterest(Producer& p, const Interest& interest)
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
}
void
processIncomingInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.getName() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/b/n/m");
CallbackContainer stubs;
Producer p(sampleName);
p.setContextOption(SND_BUF_SIZE, 4);
p.setContextOption(DATA_FRESHNESS, 100);
std::string a(5000,'A');
std::string b(5000,'B');
std::string c(5000,'C');
std::string content = a+b+c;
Name emptySuffix;
p.produce(emptySuffix, (uint8_t*)content.c_str(), content.size());
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::processIncomingInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::processInterest, &stubs, _1, _2));
p.attach();
sleep(10);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,675 | 28.406593 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/async-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
Name prefix;
c.getContextOption(PREFIX, prefix);
Name suffix;
c.getContextOption(SUFFIX, suffix);
std::cout << "CONTENT for " << prefix << suffix << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA " << data.getName() << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
CallbackContainer stubs;
Consumer c1(Name("/q/w/e"), RDR);
c1.setContextOption(MUST_BE_FRESH_S, true);
//c1.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c1.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c1.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c1.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
Consumer c2(Name("/t/y/u"), RDR);
c2.setContextOption(MUST_BE_FRESH_S, true);
//c2.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c2.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c2.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c2.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
Consumer c3(Name("/a/s/d"), RDR);
c3.setContextOption(MUST_BE_FRESH_S, true);
//c3.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c3.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c3.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c3.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
Consumer c4(Name("/g/h/j"), RDR);
c4.setContextOption(MUST_BE_FRESH_S, true);
//c4.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c4.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c4.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c4.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
Consumer c5(Name("/b/n/m"), RDR);
c5.setContextOption(MUST_BE_FRESH_S, true);
//c5.setContextOption(FORWARDING_STRATEGY, BROADCAST);
c5.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c5.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c5.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c1.asyncConsume(Name());
c2.asyncConsume(Name());
c3.asyncConsume(Name());
c4.asyncConsume(Name());
c5.asyncConsume(Name());
Consumer::consumeAll(); // blocks until both contexts finish their work in parallel
sleep(10);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 5,357 | 34.019608 | 102 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/manifest-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){}
void
processInterest(Producer& p, const Interest& interest)
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
}
void
processIncomingInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.getName() << std::endl;
}
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Producer p(sampleName);
p.setContextOption(FAST_SIGNING, true);
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::processIncomingInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::processInterest, &stubs, _1, _2));
p.attach();
std::string a(5000,'A');
std::string b(5000,'B');
std::string c(5000,'C');
std::string d(5000,'D');
std::string e(5000,'E');
std::string f(5000,'F');
std::string g(5000,'G');
std::string i(5000,'I');
std::string h(5000,'H');
std::string j(5000,'J');
std::string k(5000,'K');
std::string l(5000,'L');
std::string m(5000,'M');
std::string n(5000,'N');
std::string o(5000,'O');
std::string P(5000,'P');
std::string r(5000,'R');
std::string s(5000,'S');
std::string t(5000,'T');
std::string v(5000,'V');
std::string u(5000,'U');
std::string content = a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u+a+b+c+d+e+f+g+i+h+j+k+l+m+n+o+P+r+s+t+v+u;
Name emptySuffix;
p.produce(emptySuffix, (uint8_t*)content.c_str(), content.size());
sleep(300);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,098 | 36.605505 | 990 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-chaining-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer(){flag = false;}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
std::cout << "REASSEMBLED " << content1 << std::endl;
std::cout << "Size " << bufferSize << std::endl;
// chaining call
if (!flag)
{
flag = true;
std::cout << "consume zzz" << std::endl;
c.consume(Name("zzz"));
}
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
bool flag;
};
int
main(int argc, char** argv)
{
Name sampleName("/x/y");
CallbackContainer stubs;
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name("z"));
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 2,932 | 28.039604 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-nack-delay-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "consumer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer()
: m_byteCounter(0)
{}
void
processPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content1((char*)buffer, bufferSize);
m_byteCounter += bufferSize;
std::cout << "REASSEMBLED " << content1 << std::endl;
std::cout << "**************************************************" << std::endl;
std::cout << m_byteCounter << std::endl;
std::cout << "**************************************************" << std::endl;
}
void
processData(Consumer& c, const Data& data)
{
std::cout << "DATA IN CNTX" << data.getName() << std::endl;
}
void
processLeavingInterest(Consumer& c, Interest& interest)
{
std::cout << "LEAVES " << interest.toUri() << std::endl;
}
private:
int m_byteCounter;
};
int
main(int argc, char** argv)
{
Name sampleName("/a/b/c");
CallbackContainer stubs;
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&CallbackContainer::processLeavingInterest, &stubs, _1, _2));
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&CallbackContainer::processData, &stubs, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&CallbackContainer::processPayload, &stubs, _1, _2, _3));
c.consume(Name());
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,008 | 29.393939 | 100 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/manifest-signing-performance.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/manifest/performance"
class Performance
{
public:
Performance(){}
void
onNewSegment(Producer& p, Data& data)
{
if (data.getName().get(-1).toSegment() == 1) // because [0] is the manifest which comes later
{
m_segmentationStart = time::system_clock::now();
}
}
void
onSegmentFinalized(Producer& p, Data& data)
{
m_segmentationStop = time::system_clock::now();
}
ndn::time::steady_clock::TimePoint::clock::duration
getSegmentationDuration()
{
return m_segmentationStop - m_segmentationStart;
}
void
onInterest(Producer& p, const Interest& interest)
{
std::cout << "Entering " << interest.toUri() << std::endl;
}
private:
time::system_clock::TimePoint m_segmentationStart;
time::system_clock::TimePoint m_segmentationStop;
};
class Signer
{
public:
Signer()
: m_counter(0)
, m_identityName(IDENTITY_NAME)
{
m_keyChain.createIdentity(m_identityName);
};
void
onPacket(Producer& p, Data& data)
{
m_counter++;
m_keyChain.signByIdentity(data, m_identityName);
}
private:
KeyChain m_keyChain;
int m_counter;
Name m_identityName;
};
int
main(int argc, char** argv)
{
Signer signer;
Performance performance;
Name sampleName("/a/b/c");
Producer p(sampleName);
p.setContextOption(FAST_SIGNING, true);
p.setContextOption(SND_BUF_SIZE, 60000);
p.setContextOption(NEW_DATA_SEGMENT,
(ProducerDataCallback)bind(&Performance::onNewSegment, &performance, _1, _2));
p.setContextOption(DATA_TO_SECURE,
(ProducerDataCallback)bind(&Signer::onPacket, &signer, _1, _2));
p.setContextOption(DATA_LEAVE_CNTX,
(ProducerDataCallback)bind(&Performance::onSegmentFinalized, &performance, _1, _2));
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&Performance::onInterest, &performance, _1, _2));
p.attach();
uint8_t* content = new uint8_t[CONTENT_LENGTH];
p.produce(Name(), content, CONTENT_LENGTH);
std::cout << "**************************************************************" << std::endl;
std::cout << "Manifest segmentation duration " << performance.getSegmentationDuration() << std::endl;
sleep(500);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,973 | 26.985915 | 103 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/sequential-consumer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/consumer-context.hpp>
#include "producer-context.hpp"
#include "consumer-context.hpp"
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/security/validator.hpp>
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
#define CONTENT_LENGTH 1*1024*1024
#define IDENTITY_NAME "/sequence/performance"
class Performance
{
public:
Performance()
: m_byteCounter(0)
{}
void
onInterestLeaves(Consumer& c, Interest& interest)
{
std::cout << "Leaving: " << interest.toUri() << std::endl;
}
void
onDataEnters(Consumer& c, const Data& data)
{
std::cout << "DATA IN" << data.getName() << std::endl;
if (data.getName().get(-1).toSegment() == 0)
{
m_reassemblyStart = time::system_clock::now();
}
}
void
onContent(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
m_byteCounter += bufferSize;
if (m_byteCounter == CONTENT_LENGTH)
{
std::cout << "DONE" << std::endl;
m_reassemblyStop = time::system_clock::now();
}
}
ndn::time::steady_clock::TimePoint::clock::duration
getReassemblyDuration()
{
return m_reassemblyStop - m_reassemblyStart;
}
private:
uint32_t m_byteCounter;
time::system_clock::TimePoint m_reassemblyStart;
time::system_clock::TimePoint m_reassemblyStop;
};
class Verificator
{
public:
Verificator()
{
Name identity(IDENTITY_NAME);
Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
m_publicKey = m_keyChain.getPublicKey(keyName);
};
bool
onPacket(Consumer& c, const Data& data)
{
if (Validator::verifySignature(data, *m_publicKey))
{
return true;
}
else
{
return false;
}
}
private:
KeyChain m_keyChain;
shared_ptr<PublicKey> m_publicKey;
};
int
main(int argc, char** argv)
{
Verificator verificator;
Performance performance;
Name sampleName("/a/b/c");
Consumer c(sampleName, RDR);
c.setContextOption(MUST_BE_FRESH_S, true);
c.setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&Performance::onDataEnters, &performance, _1, _2));
c.setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&Performance::onInterestLeaves, &performance, _1, _2));
c.setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&Performance::onContent, &performance, _1, _2, _3));
time::system_clock::TimePoint m_start = time::system_clock::now();
for (uint64_t i = 0; i <= 1000; i++)
{
Name n;
n.append(name::Component::fromNumber(i));
c.consume(n);
}
time::system_clock::TimePoint m_stop = time::system_clock::now();
std::cout << "**************************************************************" << std::endl;
std::cout << "Duration " << m_stop - m_start << std::endl;
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 4,268 | 26.191083 | 113 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/rdr-chaining-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
CallbackContainer()
: m_interestCounter(0)
{}
void
processInterest(Producer& p, const Interest& interest)
{
m_interestCounter++;
if (m_interestCounter == 1)
{
ApplicationNack appNack(interest, ApplicationNack::PRODUCER_DELAY);
appNack.setDelay(5000); // in ms
p.nack(appNack);
}
else if (m_interestCounter == 2)
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
std::string content = "RELIABLE ECHO z";
Name emptySuffix;
p.produce(Name("z"), (uint8_t*)content.c_str(), content.size());
}
else
{
std::cout << "REPLY TO " << interest.toUri() << std::endl;
std::string content = "RELIABLE ECHO zzz";
Name emptySuffix;
p.produce(Name("zzz"), (uint8_t*)content.c_str(), content.size());
}
}
void
processIncomingInterest(Producer& p, const Interest& interest)
{
std::cout << "COMES IN " << interest.toUri() << std::endl;
}
private:
int m_interestCounter;
};
int
main(int argc, char** argv)
{
Name sampleName("/x/y");
CallbackContainer stubs;
Producer p(sampleName);
//setting callbacks
p.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::processIncomingInterest, &stubs, _1, _2));
p.setContextOption(CACHE_MISS,
(ProducerInterestCallback)bind(&CallbackContainer::processInterest, &stubs, _1, _2));
p.attach();
sleep(300); // because attach() is non-blocking
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,125 | 27.944444 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/examples/async-producer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
// correct way to include Consumer/Producer API headers
//#include <Consumer-Producer-API/producer-context.hpp>
#include "producer-context.hpp"
// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {
class CallbackContainer
{
public:
void
onP1(Producer& p, const Interest& interest)
{
std::cout << "Producer 1 got " << interest.toUri() << std::endl;
}
void
onP2(Producer& p, const Interest& interest)
{
std::cout << "Producer 2 got " << interest.toUri() << std::endl;
}
};
int
main(int argc, char** argv)
{
CallbackContainer c;
Producer p1(Name("/q/w/e"));
p1.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP1, &c, _1, _2));
p1.attach();
uint8_t* content1 = new uint8_t[100000];
p1.produce(Name(), content1, 100000);
Producer p2(Name("/t/y/u"));
p2.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP2, &c, _1, _2));
p2.attach();
uint8_t* content2 = new uint8_t[100000];
p2.produce(Name(), content2, 100000);
Producer p3(Name("/a/s/d"));
p3.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP2, &c, _1, _2));
p3.attach();
uint8_t* content3 = new uint8_t[100000];
p3.produce(Name(), content3, 100000);
Producer p4(Name("/g/h/j"));
p4.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP2, &c, _1, _2));
p4.attach();
uint8_t* content4 = new uint8_t[100000];
p4.produce(Name(), content4, 100000);
Producer p5(Name("/b/n/m"));
p5.setContextOption(INTEREST_ENTER_CNTX,
(ProducerInterestCallback)bind(&CallbackContainer::onP2, &c, _1, _2));
p5.attach();
uint8_t* content5 = new uint8_t[100000];
p5.produce(Name(), content5, 100000);
std::cout << "sleep" << std::endl;
sleep(300);
return 0;
}
} // namespace examples
} // namespace ndn
int
main(int argc, char** argv)
{
return ndn::examples::main(argc, argv);
}
| 3,291 | 31.594059 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/face-helper.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "face-helper.hpp"
namespace ndn {
shared_ptr<ndn::Face> FaceHelper::m_face = 0;
shared_ptr<ndn::Face>
FaceHelper::getFace()
{
if (!m_face)
{
m_face = ndn::make_shared<ndn::Face>();
}
return m_face;
}
} // namespace ndn
| 1,318 | 29.674419 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/reliable-data-retrieval.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef RELIABLE_DATA_RETRIEVAL_HPP
#define RELIABLE_DATA_RETRIEVAL_HPP
#include "data-retrieval-protocol.hpp"
#include "selector-helper.hpp"
#include "rtt-estimator.hpp"
namespace ndn {
/*
* Two types of packet losses are possible in NDN, leading to a situation when NDN application
* begins to speculate about possible reasons of failed Interest/Data exchange:
* 1) the Interest was lost in transit before it reached the data, which may reside in cache,
* or needs to be produced;
* 2) the Interest reached the producer-application and the application did not respond;
* 3) returning Data packet was lost;
* 4) returning Data packet could not be validated by its signature.
*
* Reliable Data Retrieval protocol (RDR) uses Interest retransmission and negative acknowledgements
* to handle the packet losses mentioned above. Interest retransmission is activated if
* the expressed Interest packet is not satisfied when it times out, and in case
* the negative acknowledgment carrying Retry-After field was retrieved instead of the actual data.
*
* Another type of transmission errors in NDN network is a failure of Data verification.
* Data verification error can be caused by packet tampering, content poisoning by a
* non-credible publisher, expired public key of a credible publisher, and other possible cases
* depending on the selected trust model. While Data verification operation is performed separately
* by a security part of the library, Data retrieval protocol will make an attempt to recover from
* this type of error.
*
* To recover from the Data verification failure, RDR performs retransmission of Interest packet
* with Exclude selector set to exclude any possible Data packet having the same name and the digest
* (e.g. hash, checksum) of the packet that has failed verification. RDR limits its exclude selector
* to five digests, which means that the protocol attempts up to five retransmissions in order to
* recover from the Data verification failure.
*/
class ReliableDataRetrieval : public DataRetrievalProtocol
{
public:
ReliableDataRetrieval(Context* context);
~ReliableDataRetrieval();
void
start();
void
stop();
private:
void
sendInterest();
void
onData(const ndn::Interest& interest, ndn::Data& data);
void
onTimeout(const ndn::Interest& interest);
void
onManifestData(const ndn::Interest& interest, ndn::Data& data);
void
onNackData(const ndn::Interest& interest, ndn::Data& data);
void
onContentData(const ndn::Interest& interest, ndn::Data& data);
void
reassemble();
void
copyContent(ndn::Data& data);
bool
referencesManifest(ndn::Data& data);
void
retransmitFreshInterest(const ndn::Interest& interest);
bool
retransmitInterestWithExclude(const ndn::Interest& interest, Data& dataSegment);
bool
retransmitInterestWithDigest( const ndn::Interest& interest, const Data& dataSegment,
Manifest& manifestSegment);
bool
verifySegmentWithManifest(Manifest& manifestSegment, Data& dataSegment);
name::Component
getDigestFromManifest(Manifest& manifestSegment, const Data& dataSegment);
void
checkFastRetransmissionConditions(const ndn::Interest& interest);
void
fastRetransmit(const ndn::Interest& interest, uint64_t segNumber);
void
removeAllPendingInterests();
void
removeAllScheduledInterests();
void
paceInterests(int nInterests, time::milliseconds timeWindow);
private:
Scheduler* m_scheduler;
KeyChain m_keyChain;
// reassembly variables
bool m_isFinalBlockNumberDiscovered;
uint64_t m_finalBlockNumber;
uint64_t m_lastReassembledSegment;
std::vector<uint8_t> m_contentBuffer;
size_t m_contentBufferSize;
// transmission variables
int m_currentWindowSize;
int m_interestsInFlight;
uint64_t m_segNumber;
std::unordered_map<uint64_t, int> m_interestRetransmissions; // by segment number
std::unordered_map<uint64_t, const PendingInterestId*> m_expressedInterests; // by segment number
std::unordered_map<uint64_t, EventId> m_scheduledInterests; // by segment number
std::unordered_map<uint64_t, time::steady_clock::time_point> m_interestTimepoints; // by segment
RttEstimator m_rttEstimator;
// buffers
std::map<uint64_t, shared_ptr<Data> > m_receiveBuffer; // verified segments by segment number
std::map<uint64_t, shared_ptr<Data> > m_unverifiedSegments; // used with embedded manifests
std::map<uint64_t, shared_ptr<Manifest> > m_verifiedManifests; // by segment number
// Fast Retransmission
std::map<uint64_t, bool> m_receivedSegments;
std::unordered_map<uint64_t, bool> m_fastRetxSegments;
};
} // namespace ndn
#endif // RELIABLE_DATA_RETRIEVAL_HPP
| 5,841 | 34.406061 | 103 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/common.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
/** \file
* \brief import common constructs for Consumer/Producer API library internal use
* \warning This file is implementation detail of Consumer/Producer API library.
* Aliases imported in this file SHOULD NOT be used outside of Consumer/Producer API.
*/
#ifndef CONSUMERPRODUCER_COMMON_HPP
#define CONSUMERPRODUCER_COMMON_HPP
// require C++11
#if __cplusplus < 201103L && !defined(__GXX_EXPERIMENTAL_CXX0X__)
# error "ndn-cxx applications must be compiled using the C++11 standard"
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unistd.h>
#include <utility>
#include <ndn-cxx/common.hpp>
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/data.hpp>
#include <ndn-cxx/face.hpp>
/*#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/assert.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/noncopyable.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/tuple/tuple.hpp>
*/
#if defined(__GNUC__) || defined(__clang__)
# define DEPRECATED(func) func __attribute__ ((deprecated))
#elif defined(_MSC_VER)
# define DEPRECATED(func) __declspec(deprecated) func
#else
# pragma message("DEPRECATED not implemented")
# define DEPRECATED(func) func
#endif
namespace ndn {
using std::shared_ptr;
using std::unique_ptr;
using std::weak_ptr;
using std::bad_weak_ptr;
using std::make_shared;
using std::enable_shared_from_this;
using std::static_pointer_cast;
using std::dynamic_pointer_cast;
using std::const_pointer_cast;
using std::function;
using std::bind;
using std::ref;
using std::cref;
} // namespace ndn
#endif // CONSUMERPRODUCER_COMMON_HPP
| 2,892 | 30.107527 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/simple-data-retrieval.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "simple-data-retrieval.hpp"
#include "consumer-context.hpp"
namespace ndn {
SimpleDataRetrieval::SimpleDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
{
context->getContextOption(FACE, m_face);
}
void
SimpleDataRetrieval::start()
{
m_isRunning = true;
sendInterest();
}
void
SimpleDataRetrieval::sendInterest()
{
Name prefix;
m_context->getContextOption(PREFIX, prefix);
Name suffix;
m_context->getContextOption(SUFFIX, suffix);
if (!suffix.empty())
{
prefix.append(suffix);
}
Interest interest(prefix);
int interestLifetime = 0;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interest, m_context);
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interest);
}
m_face->expressInterest(interest,
bind(&SimpleDataRetrieval::onData, this, _1, _2),
bind(&SimpleDataRetrieval::onTimeout, this, _1));
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
m_face->processEvents();
}
}
void
SimpleDataRetrieval::stop()
{
m_isRunning = false;
}
void
SimpleDataRetrieval::onData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
ConsumerDataCallback onDataEnteredContext = EMPTY_CALLBACK;
m_context->getContextOption(DATA_ENTER_CNTX, onDataEnteredContext);
if (onDataEnteredContext != EMPTY_CALLBACK)
{
onDataEnteredContext(*dynamic_cast<Consumer*>(m_context), data);
}
ConsumerInterestCallback onInterestSatisfied = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_SATISFIED, onInterestSatisfied);
if (onInterestSatisfied != EMPTY_CALLBACK)
{
onInterestSatisfied(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
if (onDataToVerify != EMPTY_CALLBACK)
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
const Block content = data.getContent();
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), content.value(), content.value_size());
}
}
}
else
{
const Block content = data.getContent();
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), content.value(), content.value_size());
}
}
m_isRunning = false;
}
void
SimpleDataRetrieval::onTimeout(const ndn::Interest& interest)
{
if (m_isRunning == false)
return;
ConsumerInterestCallback onInterestExpired = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_EXPIRED, onInterestExpired);
if (onInterestExpired != EMPTY_CALLBACK)
{
onInterestExpired(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
m_isRunning = false;
}
} //namespace ndn
| 4,619 | 28.615385 | 103 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/context-options.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONTEXT_OPTIONS_HPP
#define CONTEXT_OPTIONS_HPP
// This file contains recognized values for the first parameter of get/setContextOption
// every number is unique
#define RCV_BUF_SIZE 1 // int
#define SND_BUF_SIZE 2 // int
#define PREFIX 3 // Name
#define SUFFIX 4 // Name
#define REMOTE_REPO_PREFIX 5 // Name
#define LOCAL_REPO 6 // bool
#define INTEREST_RETX 7 // int
#define DATA_PKT_SIZE 8 // int
#define INTEREST_LIFETIME 9 // int
#define FORWARDING_STRATEGY 10 // int
#define DATA_FRESHNESS 11 // int
#define REGISTRATION_STATUS 12 // int
#define KEY_LOCATOR 13 // KeyLocator
#define SIGNATURE_TYPE 14 // int
#define MIN_WINDOW_SIZE 15 // int
#define MAX_WINDOW_SIZE 16 // int
#define CURRENT_WINDOW_SIZE 17 // int
#define MAX_EXCLUDED_DIGESTS 18 // int
#define ASYNC_MODE 19 // bool
#define FAST_SIGNING 20 // bool
#define FACE 21 // Face
#define RUNNING 22 // bool
#define INFOMAX 23 // bool
#define INFOMAX_ROOT 24 // TreeNode
#define INFOMAX_PRIORITY 25 // int
#define INFOMAX_UPDATE_INTERVAL 26 // int (milliseconds)
// selectors
#define MIN_SUFFIX_COMP_S 101 // int
#define MAX_SUFFIX_COMP_S 102 // int
#define EXCLUDE_S 103 // Exclude
#define MUST_BE_FRESH_S 104 // bool
#define LEFTMOST_CHILD_S 105 // int
#define RIGHTMOST_CHILD_S 106 // int
#define KEYLOCATOR_S 107 // KeyLocator
// consumer context events
#define INTEREST_LEAVE_CNTX 201 // InterestCallback
#define INTEREST_RETRANSMIT 202 // InterestCallback
#define INTEREST_EXPIRED 203 // ConstInterestCallback
#define INTEREST_SATISFIED 204 // ConstInterestCallback
#define DATA_ENTER_CNTX 211 // DataCallback
#define NACK_ENTER_CNTX 212 // ConstNackCallback
#define MANIFEST_ENTER_CNTX 213 // ConstManifestCallback
#define DATA_TO_VERIFY 214 // DataVerificationCallback
#define CONTENT_RETRIEVED 215 // ContentCallback
// producer context events
#define INTEREST_ENTER_CNTX 301
#define INTEREST_DROP_RCV_BUF 302
#define INTEREST_PASS_RCV_BUF 303
#define CACHE_HIT 306
#define CACHE_MISS 308
#define NEW_DATA_SEGMENT 309 // DataCallback
#define DATA_TO_SECURE 313 // DataCallback
#define DATA_IN_SND_BUF 310 // DataCallback
#define DATA_LEAVE_CNTX 311 // ConstDataCallback
#define DATA_EVICT_SND_BUF 312 // ConstDataCallback
#endif
| 3,773 | 41.404494 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/repo-tlv.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014, Regents of the University of California.
*
* This file is part of NDN repo-ng (Next generation of NDN repository).
* See AUTHORS.md for complete list of repo-ng authors and contributors.
*
* repo-ng is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* repo-ng is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* repo-ng, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REPO_REPO_TLV_HPP
#define REPO_REPO_TLV_HPP
#include <ndn-cxx/encoding/tlv.hpp>
namespace repo {
namespace tlv {
using namespace ndn::tlv;
enum {
RepoCommandParameter = 201,
StartBlockId = 204,
EndBlockId = 205,
ProcessId = 206,
RepoCommandResponse = 207,
StatusCode = 208,
InsertNum = 209,
DeleteNum = 210,
MaxInterestNum = 211,
WatchTimeout = 212
};
} // tlv
} // repo
#endif // REPO_REPO_TLV_HPP
| 1,452 | 29.914894 | 87 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-tree-node.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "infomax-tree-node.hpp"
using namespace std;
namespace ndn {
TreeNode::TreeNode(Name &name, TreeNode *parent)
{
init(name, parent);
}
TreeNode::TreeNode(const TreeNode& other):
name(other.name),
children(other.children),
isMarked(other.isMarked),
dataNode(other.dataNode),
parent(other.parent),
revisionCount(other.revisionCount),
treeSize(other.treeSize)
{}
TreeNode::TreeNode()
{
}
void
TreeNode::init(Name &name, TreeNode *parent)
{
this->name = name;
(this->children).clear();
this->isMarked = false;
this->dataNode = false;
this->parent = parent;
this->revisionCount = 0;
this->treeSize = 0;
}
Name
TreeNode::getName ()
{
return this->name;
}
vector<TreeNode *>
TreeNode::getChildren ()
{
return (this->children);
}
bool
TreeNode::updateRevisionCount (unsigned long long int revisionCount)
{
this->revisionCount = revisionCount;
return true;
}
TreeNode*
TreeNode::getParent()
{
return this->parent;
}
uint64_t
TreeNode::getRevisionCount()
{
return this->revisionCount;
}
bool
TreeNode::isLeafNode()
{
if (this->getChildren().empty())
return true;
return false;
}
bool
TreeNode::isRootNode()
{
TreeNode *nullPtr = NULL;
if (this->getParent() == nullPtr)
return true;
return false;
}
bool
TreeNode::setDataNode(bool flag)
{
this->dataNode = flag;
return true;
}
bool
TreeNode::isDataNode()
{
return this->dataNode;
}
bool
TreeNode::markNode(bool status)
{
this->isMarked = status;
return true;
}
bool
TreeNode::isNodeMarked()
{
return this->isMarked;
}
bool
TreeNode::removeChild (TreeNode * child)
{
if (child == NULL) {
return false;
}
for (unsigned int i=0; i <= this->children.size(); i++)
{
if (this->children.at(i)->getName().equals(child->getName()))
{
this->children.erase(this->children.begin()+i);
break;
} else
{
if (i == this->children.size())
{
return false;
}
}
}
unsigned long long int newSize = this->parent->getTreeSize() - this->getTreeSize();
this->parent->setTreeSize(newSize);
return true;
}
bool
TreeNode::addChild (TreeNode * child)
{
if (child == NULL) {
return false;
}
(this->children).push_back(child);
if (child->isDataNode())
{
unsigned long long int newSize = getTreeSize()+1;
this->setTreeSize(newSize);
}
return true;
}
bool
TreeNode::setTreeSize (unsigned long long int treeSize)
{
if(treeSize < (this->treeSize))
{
return false;
}
unsigned long long int difference = treeSize - getTreeSize();
this->treeSize = treeSize;
if(parent != NULL){
(this->parent)->setTreeSize((this->parent)->getTreeSize() + difference);
}
return true;
}
uint64_t
TreeNode::getTreeSize ()
{
return treeSize;
}
int
TreeNode::getNumSharedPrefix(TreeNode *node)
{
int cnt = 0;
unsigned int nameSize = min(this->getName().size(), node->getName().size());
for (unsigned int i=0 ; i<nameSize; i++)
{
string name1 = this->getName().get(i).toUri();
string name2 = node->getName().get(i).toUri();
if(name1.compare(name2) == 0)
{
cnt++;
}
else
break;
}
return cnt;
}
void
TreeNode::printTreeNode()
{
string parentStr = "null";
if (parent != NULL) {
parentStr = parent->getName().toUri();
}
for(unsigned int i = 0 ; i < this->children.size() ; ++i ) {
TreeNode *n = this->children[i];
n->printTreeNode();
}
}
void
TreeNode::printTreeNodeName()
{
string parentStr = "null";
if (parent != NULL) {
parentStr = parent->getName().toUri();
}
for(unsigned int i = 0 ; i < this->children.size() ; ++i ) {
TreeNode *n = this->children[i];
n->printTreeNodeName();
}
}
} // namespace ndn | 4,825 | 18.075099 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/producer-context.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "producer-context.hpp"
namespace ndn {
Producer::Producer(Name prefix)
: m_prefix(prefix)
, m_dataPacketSize(DEFAULT_DATA_PACKET_SIZE)
, m_dataFreshness(DEFAULT_DATA_FRESHNESS)
, m_registrationStatus(REGISTRATION_NOT_ATTEMPTED)
, m_isMakingManifest(false)
, m_isWritingToLocalRepo(false)
, m_repoSocket(m_repoIoService)
, m_infomaxType (INFOMAX_NONE) // infomax disabled by default
, m_infomaxTreeVersion (0)
, m_infomaxUpdateInterval (INFOMAX_DEFAULT_UPDATE_INTERVAL)
, m_isNewInfomaxData (false)
, m_infomaxRoot (TreeNode (prefix, 0))
, m_signatureType(SHA_256)
, m_keyLocatorSize(DEFAULT_KEY_LOCATOR_SIZE)
, m_sendBuffer(DEFAULT_PRODUCER_SND_BUFFER_SIZE)
, m_receiveBufferCapacity(DEFAULT_PRODUCER_RCV_BUFFER_SIZE)
, m_receiveBufferSize(0)
, m_onInterestEntersContext(EMPTY_CALLBACK)
, m_onInterestDroppedFromRcvBuffer(EMPTY_CALLBACK)
, m_onInterestPassedRcvBuffer(EMPTY_CALLBACK)
, m_onInterestSatisfiedFromSndBuffer(EMPTY_CALLBACK)
, m_onInterestProcess(EMPTY_CALLBACK)
, m_onNewSegment(EMPTY_CALLBACK)
, m_onDataToSecure(EMPTY_CALLBACK)
, m_onDataInSndBuffer(EMPTY_CALLBACK)
, m_onDataLeavesContext(EMPTY_CALLBACK)
, m_onDataEvictedFromSndBuffer(EMPTY_CALLBACK)
{
m_face = ndn::make_shared<ndn::Face>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_scheduler = new Scheduler(m_face->getIoService());
}
Producer::~Producer()
{
m_repoSocket.close();
m_listeningThread.interrupt();
delete m_scheduler;
m_controller.reset();
m_face.reset();
}
void
Producer::attach()
{
m_listeningThread = boost::thread(bind(&Producer::listen, this));
m_processingThread = boost::thread(bind(&Producer::processIncomingInterest, this));
}
void
Producer::listen()
{
m_registrationStatus = REGISTRATION_IN_PROGRESS;
m_face->setInterestFilter(m_prefix,
bind(&Producer::onInterest, this, _1, _2),
bind(&Producer::onRegistrationSucceded, this, _1),
bind(&Producer::onRegistrationFailed, this, _1, _2));
m_face->processEvents();
}
void
Producer::updateInfomaxTree()
{
if (m_infomaxType == INFOMAX_SIMPLE_PRIORITY || m_infomaxType == INFOMAX_MERGE_PRIORITY)
{
m_scheduler->scheduleEvent( time::milliseconds(m_infomaxUpdateInterval),
bind(&Producer::updateInfomaxTree, this));
}
if (!m_isNewInfomaxData || m_infomaxType == INFOMAX_NONE)
{
return;
}
m_infomaxPrioritizer->prioritize();
m_isNewInfomaxData = false;
}
void
Producer::onRegistrationSucceded (const ndn::Name& prefix)
{
m_registrationStatus = REGISTRATION_SUCCESS;
}
void
Producer::onRegistrationFailed (const ndn::Name& prefix, const std::string& reason)
{
m_registrationStatus = REGISTRATION_FAILURE;
m_face->shutdown();
}
void
Producer::passSegmentThroughCallbacks(shared_ptr<Data> segment)
{
if (segment)
{
if (m_onNewSegment != EMPTY_CALLBACK)
{
m_onNewSegment(*this, *segment);
}
if (m_onDataToSecure != EMPTY_CALLBACK)
{
if (!m_isMakingManifest)
{
m_onDataToSecure(*this, *segment);
}
else
{
if (segment->getContentType() == tlv::ContentType_Manifest)
{
m_onDataToSecure(*this, *segment);
}
else
{
// data's KeyLocator will point to the corresponding manifest
DigestSha256 sig;
const SignatureInfo info(tlv::DigestSha256, m_keyLocator);
sig.setInfo(info);
segment->setSignature(sig);
Block sigValue(tlv::SignatureValue,
crypto::sha256(segment->wireEncode().value(),
segment->wireEncode().value_size() -
segment->getSignature().getValue().size()));
segment->setSignatureValue(sigValue);
}
}
}
else // this is for developers who don't care about security
{
m_keyChain.signWithSha256(*segment);
}
if (m_onDataInSndBuffer != EMPTY_CALLBACK)
{
m_onDataInSndBuffer(*this, *segment);
}
m_sendBuffer.insert(*segment);
if (m_onDataLeavesContext != EMPTY_CALLBACK)
{
m_onDataLeavesContext(*this, *segment);
}
m_face->put(*segment);
if (m_isWritingToLocalRepo)
{
boost::system::error_code ec;
m_repoSocket.write_some(boost::asio::buffer(segment->wireEncode().wire(),
segment->wireEncode().size()), ec);
}
}
}
size_t
Producer::estimateManifestSize(shared_ptr<Manifest> manifest)
{
size_t manifestSize = manifest->getName().wireEncode().size();
for (std::list<Name>::const_iterator it = manifest->catalogueBegin(); it != manifest->catalogueEnd(); ++it)
{
manifestSize += it->wireEncode().size();
}
manifestSize += DEFAULT_KEY_LOCATOR_SIZE;
return manifestSize;
}
void
Producer::produce(Data& packet)
{
if(!m_prefix.isPrefixOf(packet.getName()))
return;
if (m_onDataInSndBuffer != EMPTY_CALLBACK)
{
m_onDataInSndBuffer(*this, packet);
}
m_sendBuffer.insert(packet);
if (m_onDataLeavesContext != EMPTY_CALLBACK)
{
m_onDataLeavesContext(*this, packet);
}
m_face->put(packet);
if (m_isWritingToLocalRepo)
{
boost::system::error_code ec;
m_repoSocket.write_some(boost::asio::buffer(packet.wireEncode().wire(),
packet.wireEncode().size()), ec);
}
// if user requested writing in the remote Repo
if (!m_targetRepoPrefix.empty())
{
repo::RepoCommandParameter commandParameter;
commandParameter.setName(packet.getName());
Name interestName(m_targetRepoPrefix);
interestName.append(Name("insert")).append(commandParameter.wireEncode());
Interest repoCommand(interestName);
m_face->expressInterest(repoCommand,
bind(&Producer::onRepoReply, this, _1, _2),
bind(&Producer::onRepoTimeout, this, _1));
}
}
// this can be called either from the thread of the caller
// or from the m_listeningThread
void
Producer::produce(Name suffix, const uint8_t* buf, size_t bufferSize)
{
if (bufferSize == 0)
return;
int bytesPackaged = 0;
Name name(m_prefix);
if(!suffix.empty())
{
name.append(suffix);
}
Block nameOnWire = name.wireEncode();
size_t bytesOccupiedByName = nameOnWire.size();
int signatureSize = 32; //SHA_256 as default
int freeSpaceForContent = m_dataPacketSize - bytesOccupiedByName - signatureSize
- m_keyLocatorSize - DEFAULT_SAFETY_OFFSET;
int numberOfSegments = bufferSize / freeSpaceForContent;
if (numberOfSegments == 0)
numberOfSegments++;
if (freeSpaceForContent * numberOfSegments < bufferSize)
numberOfSegments++;
uint64_t currentSegment = 0;
uint64_t initialSegment = currentSegment;
uint64_t finalSegment = currentSegment;
if (m_isMakingManifest) // segmentation with inlined manifests
{
shared_ptr<Data> dataSegment;
shared_ptr<Manifest> manifestSegment;
bool needManifestSegment = true;
for (int packagedSegments = 0; packagedSegments < numberOfSegments;)
{
if (needManifestSegment)
{
Name manifestName(m_prefix);
if (!suffix.empty())
manifestName.append(suffix);
manifestName.appendSegment(currentSegment);
if (manifestSegment) // send previous manifest
{
manifestSegment->encode();
passSegmentThroughCallbacks(manifestSegment);
}
manifestSegment = make_shared<Manifest>(manifestName); // new empty manifest
manifestSegment->setFinalBlockId(
name::Component::fromSegment(currentSegment + numberOfSegments - packagedSegments));
finalSegment = currentSegment;
needManifestSegment = false;
currentSegment++;
m_keyLocator.clear();
m_keyLocator.setName(manifestSegment->getName());
}
Name fullName(m_prefix);
if(!suffix.empty())
fullName.append(suffix);
fullName.appendSegment(currentSegment);
dataSegment = make_shared<Data>(fullName);
dataSegment->setFreshnessPeriod(time::milliseconds(m_dataFreshness));
finalSegment = currentSegment;
if (packagedSegments == numberOfSegments - 1) // last segment
{
dataSegment->setContent(&buf[bytesPackaged], bufferSize - bytesPackaged);
bytesPackaged += bufferSize - bytesPackaged;
}
else
{
dataSegment->setContent(&buf[bytesPackaged], freeSpaceForContent);
bytesPackaged += freeSpaceForContent;
}
dataSegment->setFinalBlockId(
name::Component::fromSegment(currentSegment + numberOfSegments - packagedSegments - 1));
passSegmentThroughCallbacks(dataSegment);
currentSegment++;
size_t manifestSize = estimateManifestSize(manifestSegment);
size_t fullNameSize = dataSegment->getName().wireEncode().size()
+ dataSegment->getSignature().getValue().size();
if (manifestSize + 2*fullNameSize > m_dataPacketSize)
{
needManifestSegment = true;
}
const Block& block = dataSegment->wireEncode();
ndn::ConstBufferPtr implicitDigest = ndn::crypto::sha256(block.wire(), block.size());
//add implicit digest to the manifest
manifestSegment->addNameToCatalogue(
dataSegment->getName().getSubName(dataSegment->getName().size() - 1, 1),
implicitDigest
);
packagedSegments++;
if (packagedSegments == numberOfSegments) // last manifest to include last segment
{
manifestSegment->encode();
passSegmentThroughCallbacks(manifestSegment);
}
}
}
else // just normal segmentation
{
uint64_t i = 0;
for (i = currentSegment; i < numberOfSegments + currentSegment; i++)
{
Name fullName(m_prefix);
if(!suffix.empty())
fullName.append(suffix);
fullName.appendSegment(i);
shared_ptr<Data> data = make_shared<Data>(fullName);
data->setFreshnessPeriod(time::milliseconds(m_dataFreshness));
data->setFinalBlockId(name::Component::fromSegment(numberOfSegments + currentSegment - 1));
if (i == numberOfSegments + currentSegment - 1) // last segment
{
data->setContent(&buf[bytesPackaged], bufferSize - bytesPackaged);
bytesPackaged += bufferSize - bytesPackaged;
}
else
{
data->setContent(&buf[bytesPackaged], freeSpaceForContent);
bytesPackaged += freeSpaceForContent;
}
passSegmentThroughCallbacks(data);
}
finalSegment = i;
}
// if user requested writing into the REPO
if (!m_targetRepoPrefix.empty())
{
Name dataPrefix(m_prefix);
dataPrefix.append(suffix);
writeToRepo(dataPrefix, initialSegment, finalSegment - 1);
}
// if data is INFOMAX list or meta info, do not update INFOMAX tree
for (unsigned int i=0; i<suffix.size(); i++) {
if(suffix.get(i).toUri().compare(INFOMAX_INTEREST_TAG) == 0) {
return;
}
}
// if infomax mode is enabled
if (m_infomaxType == INFOMAX_MERGE_PRIORITY
|| m_infomaxType == INFOMAX_SIMPLE_PRIORITY)
{
m_isNewInfomaxData = true;
size_t lastElement = suffix.size();
TreeNode *prev = &m_infomaxRoot;
for (size_t i = 1; i <= suffix.size() ; ++i)
{
vector<TreeNode*> prevChildren = prev->getChildren();
TreeNode *curr = 0;
for(size_t j=0; j<prevChildren.size(); j++)
{
if(prevChildren[j]->getName().equals(suffix.getSubName(0, i)))
{
curr = prevChildren[j];
break;
}
}
if (curr == 0)
{
if (i==lastElement)
{
curr = new TreeNode(suffix, prev);
curr->setDataNode(true);
prev->addChild(curr);
}
else
{
Name *insertName = new Name(suffix.getSubName(0, i).toUri());
curr = new TreeNode(*insertName, prev);
prev->addChild(curr);
}
}
prev = curr;
}
}
}
void
Producer::asyncProduce(Data& packet)
{
shared_ptr<Data> p = packet.shared_from_this();
m_scheduler->scheduleEvent(time::milliseconds(0),
[p, this] ()
{
produce(*p);
});
}
void
Producer::asyncProduce(Name suffix, const uint8_t* buffer, size_t bufferSize)
{
m_scheduler->scheduleEvent( time::milliseconds(0),
[suffix, buffer, bufferSize, this] ()
{
produce(suffix, buffer, bufferSize);
});
}
void
Producer::writeToRepo(Name dataPrefix, uint64_t startSegment, uint64_t endSegment)
{
repo::RepoCommandParameter commandParameter;
commandParameter.setName(dataPrefix);
commandParameter.setStartBlockId(startSegment);
commandParameter.setEndBlockId(endSegment);
Name interestName(m_targetRepoPrefix);
interestName.append(Name("insert")).append(commandParameter.wireEncode());
Interest repoCommand(interestName);
m_face->expressInterest(repoCommand,
bind(&Producer::onRepoReply, this, _1, _2),
bind(&Producer::onRepoTimeout, this, _1));
}
void
Producer::onRepoReply(const ndn::Interest& interest, ndn::Data& data)
{
}
void
Producer::onRepoTimeout(const ndn::Interest& interest)
{
}
int
Producer::nack(ApplicationNack nack)
{
// nack expires faster than good Data packet (10% of lifetime)
nack.setFreshnessPeriod(time::milliseconds(m_dataFreshness / 10 + 1));
nack.encode();
if (m_onDataToSecure != EMPTY_CALLBACK)
{
m_onDataToSecure(*this, nack);
}
else
{
m_keyChain.signWithSha256(nack);
}
// TODO: fix caching strategy
/*if (m_onDataInSndBuffer != EMPTY_CALLBACK)
{
m_onDataInSndBuffer(*nack);
}*/
//m_sendBuffer.insert(*nack);
if (m_onDataLeavesContext != EMPTY_CALLBACK)
{
m_onDataLeavesContext(*this, nack);
}
//shared_ptr<const Data> dataPtr = nack.shared_from_this();
m_face->put(nack);
return 0;
}
void
Producer::onInterest(const Name& name, const Interest& interest)
{
if (m_onInterestEntersContext != EMPTY_CALLBACK)
{
m_onInterestEntersContext(*this, interest);
}
if (m_receiveBufferSize >= m_receiveBufferCapacity)
{
// send Interest NACK
}
else
{
m_receiveBufferMutex.lock();
m_receiveBuffer.push(interest.shared_from_this());
m_receiveBufferSize++;
m_receiveBufferMutex.unlock();
}
}
void
Producer::processIncomingInterest(/*const Name& name, const Interest& interest*/)
{
while (true)
{
if (m_receiveBufferSize == 0)
{
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 1000000;
nanosleep(&ts, NULL); // sleep for 1 ms
}
else
{
m_receiveBufferMutex.lock();
shared_ptr<const Interest> interest = m_receiveBuffer.front();
m_receiveBuffer.pop();
m_receiveBufferSize--;
m_receiveBufferMutex.unlock();
/*if (m_onInterestToVerify != EMPTY_CALLBACK)
{
if (m_onInterestToVerify(const_cast<Interest&>(interest)) == false)
{
// produceNACK
}
}*/
const Data* data = m_sendBuffer.find(*interest);
if ((Data*)data != 0)
{
if (m_onInterestSatisfiedFromSndBuffer != EMPTY_CALLBACK)
{
m_onInterestSatisfiedFromSndBuffer(*this, *interest);
}
if (m_onDataLeavesContext != EMPTY_CALLBACK)
{
m_onDataLeavesContext(*this, *const_cast<Data*>(data));
}
m_face->put(*data);
}
else
{
if (m_onInterestProcess != EMPTY_CALLBACK)
{
m_onInterestProcess(*this, *interest);
}
}
}
}
}
void
Producer::processInterestFromReceiveBuffer()
{
// put stuff here
}
int
Producer::setContextOption(int optionName, int optionValue)
{
switch (optionName)
{
case DATA_PKT_SIZE:
if (optionValue < MAX_DATA_PACKET_SIZE && optionValue > 0)
{
m_dataPacketSize = optionValue;
return OPTION_VALUE_SET;
}
else
{
return OPTION_VALUE_NOT_SET;
}
case RCV_BUF_SIZE:
if (optionValue >= 1)
{
m_receiveBufferCapacity = optionValue;
return OPTION_VALUE_SET;
}
else
{
return OPTION_VALUE_NOT_SET;
}
case SND_BUF_SIZE:
if (optionValue >= 0)
{
m_sendBuffer.setLimit(optionValue);
return OPTION_VALUE_SET;
}
else
{
return OPTION_VALUE_NOT_SET;
}
case DATA_FRESHNESS:
m_dataFreshness = optionValue;
return OPTION_VALUE_SET;
case SIGNATURE_TYPE:
if (optionValue == OPTION_DEFAULT_VALUE)
m_signatureType = SHA_256;
else
m_signatureType = optionValue;
if (m_signatureType == SHA_256)
m_signatureSize = 32;
else if (m_signatureType == RSA_256)
m_signatureSize = 32;
case INFOMAX_UPDATE_INTERVAL:
m_infomaxUpdateInterval = optionValue;
return OPTION_VALUE_SET;
case INFOMAX_PRIORITY:
m_infomaxType = optionValue;
case INTEREST_ENTER_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestEntersContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_DROP_RCV_BUF:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestDroppedFromRcvBuffer = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_PASS_RCV_BUF:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestPassedRcvBuffer = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case CACHE_HIT:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestSatisfiedFromSndBuffer = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case CACHE_MISS:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestProcess = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case NEW_DATA_SEGMENT:
if (optionValue == EMPTY_CALLBACK)
{
m_onNewSegment = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_TO_SECURE:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataToSecure = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_IN_SND_BUF:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataInSndBuffer = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_LEAVE_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataLeavesContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_EVICT_SND_BUF:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataEvictedFromSndBuffer = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::setContextOption(int optionName, bool optionValue)
{
switch (optionName)
{
case FAST_SIGNING:
m_isMakingManifest = optionValue;
return OPTION_VALUE_SET;
case LOCAL_REPO:
if (optionValue == true)
{
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1000);
boost::system::error_code ec;
m_repoSocket.connect(ep,ec);
if (ec)
{
return OPTION_VALUE_NOT_SET;
}
}
m_isWritingToLocalRepo = optionValue;
return OPTION_VALUE_SET;
case INFOMAX:
if (optionValue == true)
{
m_infomaxPrioritizer = make_shared<Prioritizer>(this);
m_infomaxType = INFOMAX_SIMPLE_PRIORITY;
//updateInfomaxTree();
m_scheduler->scheduleEvent( time::milliseconds(m_infomaxUpdateInterval),
bind(&Producer::updateInfomaxTree, this));
}
else
{
m_infomaxType = INFOMAX_NONE;
}
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::setContextOption(int optionName, Name optionValue)
{
switch (optionName)
{
case PREFIX:
m_prefix = optionValue;
return OPTION_VALUE_SET;
case REMOTE_REPO_PREFIX:
m_targetRepoPrefix = optionValue;
return OPTION_VALUE_SET;
case FORWARDING_STRATEGY:
m_forwardingStrategy = optionValue;
if (m_forwardingStrategy.empty())
{
nfd::ControlParameters parameters;
parameters.setName(m_prefix);
m_controller->start<nfd::StrategyChoiceUnsetCommand>(parameters,
bind(&Producer::onStrategyChangeSuccess, this, _1,
"Successfully unset strategy choice"),
bind(&Producer::onStrategyChangeError, this, _1, _2,
"Failed to unset strategy choice"));
}
else
{
nfd::ControlParameters parameters;
parameters
.setName(m_prefix)
.setStrategy(m_forwardingStrategy);
m_controller->start<nfd::StrategyChoiceSetCommand>(parameters,
bind(&Producer::onStrategyChangeSuccess, this, _1,
"Successfully set strategy choice"),
bind(&Producer::onStrategyChangeError, this, _1, _2,
"Failed to set strategy choice"));
}
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Producer::setContextOption(int optionName, ProducerDataCallback optionValue)
{
switch (optionName)
{
case NEW_DATA_SEGMENT:
m_onNewSegment = optionValue;
return OPTION_VALUE_SET;
case DATA_TO_SECURE:
m_onDataToSecure = optionValue;
return OPTION_VALUE_SET;
case DATA_IN_SND_BUF:
m_onDataInSndBuffer = optionValue;
return OPTION_VALUE_SET;
case DATA_LEAVE_CNTX:
m_onDataLeavesContext = optionValue;
return OPTION_VALUE_SET;
case DATA_EVICT_SND_BUF:
m_onDataEvictedFromSndBuffer = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::setContextOption(int optionName, ProducerInterestCallback optionValue)
{
switch (optionName)
{
case INTEREST_ENTER_CNTX:
m_onInterestEntersContext = optionValue;
return OPTION_VALUE_SET;
case INTEREST_DROP_RCV_BUF:
m_onInterestDroppedFromRcvBuffer = optionValue;
return OPTION_VALUE_SET;
case INTEREST_PASS_RCV_BUF:
m_onInterestPassedRcvBuffer = optionValue;
return OPTION_VALUE_SET;
case CACHE_HIT:
m_onInterestSatisfiedFromSndBuffer = optionValue;
return OPTION_VALUE_SET;
case CACHE_MISS:
m_onInterestProcess = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::setContextOption(int optionName, ConsumerDataCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, ConsumerDataVerificationCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, ConsumerInterestCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, ConsumerContentCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, ConsumerNackCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, ConsumerManifestCallback optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, KeyLocator optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, Exclude optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, int& optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
optionValue = m_receiveBufferCapacity;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBuffer.getLimit();
return OPTION_FOUND;
case DATA_PKT_SIZE:
optionValue = m_dataPacketSize;
return OPTION_FOUND;
case DATA_FRESHNESS:
optionValue = m_dataFreshness;
return OPTION_FOUND;
case SIGNATURE_TYPE:
optionValue = m_signatureType;
return OPTION_FOUND;
case REGISTRATION_STATUS:
optionValue = m_registrationStatus;
return OPTION_FOUND;
case INFOMAX_PRIORITY:
optionValue = m_infomaxType;
return OPTION_FOUND;
case INFOMAX_UPDATE_INTERVAL:
optionValue = m_infomaxUpdateInterval;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, bool& optionValue)
{
switch (optionName)
{
case FAST_SIGNING:
optionValue = m_isMakingManifest;
return OPTION_FOUND;
case LOCAL_REPO:
optionValue = m_isWritingToLocalRepo;
return OPTION_FOUND;
case INFOMAX:
if (m_infomaxType == INFOMAX_SIMPLE_PRIORITY || m_infomaxType == INFOMAX_MERGE_PRIORITY)
{
optionValue = true;
}
else
{
optionValue = false;
}
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, Name& optionValue)
{
switch (optionName)
{
case PREFIX:
optionValue = m_prefix;
return OPTION_FOUND;
case REMOTE_REPO_PREFIX:
optionValue = m_targetRepoPrefix;
return OPTION_FOUND;
case FORWARDING_STRATEGY:
optionValue = m_forwardingStrategy;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, ProducerDataCallback& optionValue)
{
switch (optionName)
{
case NEW_DATA_SEGMENT:
optionValue = m_onNewSegment;
return OPTION_FOUND;
case DATA_TO_SECURE:
optionValue = m_onDataToSecure;
return OPTION_FOUND;
case DATA_IN_SND_BUF:
optionValue = m_onDataInSndBuffer;
return OPTION_FOUND;
case DATA_LEAVE_CNTX:
optionValue = m_onDataLeavesContext;
return OPTION_FOUND;
case DATA_EVICT_SND_BUF:
optionValue = m_onDataEvictedFromSndBuffer;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, ProducerInterestCallback& optionValue)
{
switch (optionName)
{
case INTEREST_ENTER_CNTX:
optionValue = m_onInterestEntersContext;
return OPTION_FOUND;
case INTEREST_DROP_RCV_BUF:
optionValue = m_onInterestDroppedFromRcvBuffer;
return OPTION_FOUND;
case INTEREST_PASS_RCV_BUF:
optionValue = m_onInterestPassedRcvBuffer;
return OPTION_FOUND;
case CACHE_HIT:
optionValue = m_onInterestSatisfiedFromSndBuffer;
return OPTION_FOUND;
case CACHE_MISS:
optionValue = m_onInterestProcess;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, ConsumerDataCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, ConsumerInterestCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, ConsumerContentCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, ConsumerNackCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, ConsumerManifestCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::setContextOption(int optionName, size_t optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
if (m_receiveBufferCapacity >= 1)
{
m_receiveBufferCapacity = optionValue;
return OPTION_VALUE_SET;
}
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Producer::getContextOption(int optionName, size_t& optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
optionValue = m_receiveBufferCapacity;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBuffer.size();
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, KeyLocator& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, Exclude& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Producer::getContextOption(int optionName, shared_ptr<Face>& optionValue)
{
switch (optionName)
{
case FACE:
optionValue = m_face;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Producer::getContextOption(int optionName, TreeNode& optionValue)
{
switch (optionName)
{
case INFOMAX_ROOT:
optionValue = m_infomaxRoot;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
void
Producer::onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult,
const std::string& message)
{
}
void
Producer::onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message)
{
}
} //namespace ndn
| 31,273 | 24.302589 | 109 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/tlv.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONSUMER_PRODUCER_TLV_HPP
#define CONSUMER_PRODUCER_TLV_HPP
#include <ndn-cxx/encoding/tlv.hpp>
namespace ndn {
namespace tlv {
using namespace ndn::tlv;
enum {
ContentType_Manifest = 4,
ManifestCatalogue = 128,
KeyValuePair = 129
};
} // tlv
} // ndn
#endif // CONSUMER_PRODUCER_TLV_HPP
| 1,379 | 31.093023 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/context.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONTEXT_HPP
#define CONTEXT_HPP
#include "common.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include "tlv.hpp"
#include <unordered_map>
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "manifest.hpp"
#include "application-nack.hpp"
#include "face-helper.hpp"
#include "infomax-tree-node.hpp"
namespace ndn {
class Manifest;
class Consumer;
class Producer;
typedef function<void(Consumer&, Interest&)> ConsumerInterestCallback;
typedef function<void(Consumer&, const uint8_t*, size_t)> ConsumerContentCallback;
typedef function<void(Consumer&, const Data&)> ConsumerDataCallback;
typedef function<bool(Consumer&, const Data&)> ConsumerDataVerificationCallback;
typedef function<void(Consumer&, const ApplicationNack&)> ConsumerNackCallback;
typedef function<void(Consumer&, const Manifest&)> ConsumerManifestCallback;
typedef function<void(Producer&, Data&)> ProducerDataCallback;
typedef function<void(Producer&, const Interest&)> ProducerInterestCallback;
class Context
{
public:
/*
* Context option setters
*/
virtual int
setContextOption(int optionName, int optionValue) = 0;
virtual int
setContextOption(int optionName, size_t optionValue) = 0;
virtual int
setContextOption(int optionName, bool optionValue) = 0;
virtual int
setContextOption(int optionName, Name optionValue) = 0;
virtual int
setContextOption(int optionName, ProducerDataCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ProducerInterestCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerDataVerificationCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerDataCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerInterestCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerContentCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerNackCallback optionValue) = 0;
virtual int
setContextOption(int optionName, ConsumerManifestCallback optionValue) = 0;
virtual int
setContextOption(int optionName, KeyLocator optionValue) = 0;
virtual int
setContextOption(int optionName, Exclude optionValue) = 0;
/*
* Context option getters
*/
virtual int
getContextOption(int optionName, int& optionValue) = 0;
virtual int
getContextOption(int optionName, size_t& optionValue) = 0;
virtual int
getContextOption(int optionName, bool& optionValue) = 0;
virtual int
getContextOption(int optionName, Name& optionValue) = 0;
virtual int
getContextOption(int optionName, ProducerDataCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ProducerInterestCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerDataCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerInterestCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerContentCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerNackCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, ConsumerManifestCallback& optionValue) = 0;
virtual int
getContextOption(int optionName, KeyLocator& optionValue) = 0;
virtual int
getContextOption(int optionName, Exclude& optionValue) = 0;
virtual int
getContextOption(int optionName, shared_ptr<Face>& optionValue) = 0;
virtual int
getContextOption(int optionName, TreeNode& optionValue) = 0;
protected:
~Context(){};
};
} // namespace ndn
#endif // CONTEXT_HPP
| 4,851 | 29.325 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-data-retrieval.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "infomax-data-retrieval.hpp"
using namespace std;
namespace ndn {
InfoMaxDataRetrieval::InfoMaxDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
, m_requestVersion (1)
, m_requestListNum (1)
, m_isInit (true)
{
}
InfoMaxDataRetrieval::~InfoMaxDataRetrieval()
{
m_infoMaxList.clear();
stop();
}
void
InfoMaxDataRetrieval::processInfoMaxPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
std::string content((char*)buffer, bufferSize);
// std::cout << "REASSEMBLED " << content << std::endl;
// std::cout << "Size " << bufferSize << std::endl;
convertStringToList(content);
}
void
InfoMaxDataRetrieval::processInfoMaxData(Consumer& c, const Data& data)
{
// std::cout << "LIST IN CNTX" << std::endl;
}
void
InfoMaxDataRetrieval::processLeavingInfoMaxInterest(Consumer& c, Interest& interest)
{
// std::cout << "INFOMAX INTEREST LEAVES " << interest.toUri() << std::endl;
}
void
InfoMaxDataRetrieval::processInfoMaxInitPayload(Consumer& c, const uint8_t* buffer, size_t bufferSize)
{
// Fetching the latest version number and the total number of lists
std::string content((char*)buffer, bufferSize);
std::vector<std::string> metaInfo;
string buf;
stringstream ss(content);
while (ss >> buf)
metaInfo.push_back(buf);
m_requestVersion = std::stoi(metaInfo[0]);
m_maxListNum = std::stoi(metaInfo[1]);
}
void
InfoMaxDataRetrieval::processInfoMaxInitData(Consumer& c, const Data& data)
{
// std::cout << "METAINFO IN CNTX" << std::endl;
}
void
InfoMaxDataRetrieval::processLeavingInfoMaxInitInterest(Consumer& c, Interest& interest)
{
// std::cout << "INFOMAX INIT INTEREST LEAVES " << interest.toUri() << std::endl;
}
void
InfoMaxDataRetrieval::start()
{
m_rdr = make_shared<ReliableDataRetrieval>(m_context);
if (m_isInit) {
// Reqeust version number and the total number of lists (/prefix/InfoMax/MetaInfo)
m_isInit = false;
ConsumerInterestCallback processLeavingInterest;
ConsumerDataCallback processData;
ConsumerContentCallback processPayload;
m_context->getContextOption(INTEREST_LEAVE_CNTX, processLeavingInterest);
m_context->getContextOption(DATA_ENTER_CNTX, processData);
m_context->getContextOption(CONTENT_RETRIEVED, processPayload);
m_context->setContextOption(MUST_BE_FRESH_S, true);
m_context->setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&InfoMaxDataRetrieval::processLeavingInfoMaxInitInterest, this, _1, _2));
m_context->setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&InfoMaxDataRetrieval::processInfoMaxInitData, this, _1, _2));
m_context->setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&InfoMaxDataRetrieval::processInfoMaxInitPayload, this, _1, _2, _3));
Name infomaxInitSuffix(INFOMAX_INTEREST_TAG);
infomaxInitSuffix.append(Name(INFOMAX_META_INTEREST_TAG));
m_context->setContextOption(SUFFIX, infomaxInitSuffix);
m_rdr->start();
m_context->setContextOption(INTEREST_LEAVE_CNTX, processLeavingInterest);
m_context->setContextOption(DATA_ENTER_CNTX, processData);
m_context->setContextOption(CONTENT_RETRIEVED, processPayload);
}
if (m_infoMaxList.empty())
{
if (m_requestListNum > m_maxListNum) {
cout << "All data fetched" << endl;
return ;
}
// If current list is empty, issue InfoMax interest to fetch new list
ConsumerInterestCallback processLeavingInterest;
ConsumerDataCallback processData;
ConsumerContentCallback processPayload;
m_context->getContextOption(INTEREST_LEAVE_CNTX, processLeavingInterest);
m_context->getContextOption(DATA_ENTER_CNTX, processData);
m_context->getContextOption(CONTENT_RETRIEVED, processPayload);
Name infomaxSuffix(INFOMAX_INTEREST_TAG);
infomaxSuffix.appendNumber(m_requestVersion);
infomaxSuffix.appendNumber(m_requestListNum++);
m_context->setContextOption(MUST_BE_FRESH_S, true);
m_context->setContextOption(INTEREST_LEAVE_CNTX,
(ConsumerInterestCallback)bind(&InfoMaxDataRetrieval::processLeavingInfoMaxInterest, this, _1, _2));
m_context->setContextOption(DATA_ENTER_CNTX,
(ConsumerDataCallback)bind(&InfoMaxDataRetrieval::processInfoMaxData, this, _1, _2));
m_context->setContextOption(CONTENT_RETRIEVED,
(ConsumerContentCallback)bind(&InfoMaxDataRetrieval::processInfoMaxPayload, this, _1, _2, _3));
m_context->setContextOption(SUFFIX, infomaxSuffix);
m_context->setContextOption(RUNNING, false);
m_rdr->start();
m_context->setContextOption(INTEREST_LEAVE_CNTX, processLeavingInterest);
m_context->setContextOption(DATA_ENTER_CNTX, processData);
m_context->setContextOption(CONTENT_RETRIEVED, processPayload);
}
m_context->setContextOption(RUNNING, false);
m_context->setContextOption(SUFFIX, *(m_infoMaxList.front()));
m_rdr->start();
m_infoMaxList.pop_front();
}
void
InfoMaxDataRetrieval::convertStringToList(string &names)
{
m_infoMaxList.clear();
string buf;
stringstream ss(names);
while (ss >> buf)
m_infoMaxList.push_back(make_shared<Name>(buf));
}
void
InfoMaxDataRetrieval::stop()
{
m_rdr->stop();
}
} //namespace ndn
| 6,342 | 32.739362 | 112 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/repo-command-parameter.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014, Regents of the University of California.
*
* This file is part of NDN repo-ng (Next generation of NDN repository).
* See AUTHORS.md for complete list of repo-ng authors and contributors.
*
* repo-ng is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* repo-ng is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* repo-ng, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REPO_REPO_COMMAND_PARAMETER_HPP
#define REPO_REPO_COMMAND_PARAMETER_HPP
#include <ndn-cxx/encoding/encoding-buffer.hpp>
#include <ndn-cxx/encoding/block-helpers.hpp>
#include <ndn-cxx/name.hpp>
#include <ndn-cxx/selectors.hpp>
#include "repo-tlv.hpp"
namespace repo {
using ndn::Name;
using ndn::Block;
using ndn::EncodingImpl;
using ndn::Selectors;
using ndn::EncodingEstimator;
using ndn::EncodingBuffer;
using namespace ndn::time;
/**
* @brief Class defining abstraction of parameter of command for NDN Repo Protocol
* @sa link http://redmine.named-data.net/projects/repo-ng/wiki/Repo_Protocol_Specification#RepoCommandParameter
**/
class RepoCommandParameter
{
public:
class Error : public ndn::tlv::Error
{
public:
explicit
Error(const std::string& what)
: ndn::tlv::Error(what)
{
}
};
RepoCommandParameter()
: m_hasName(false)
, m_hasStartBlockId(false)
, m_hasEndBlockId(false)
, m_hasProcessId(false)
, m_hasMaxInterestNum(false)
, m_hasWatchTimeout(false)
, m_hasInterestLifetime(false)
{
}
explicit
RepoCommandParameter(const Block& block)
{
wireDecode(block);
}
const Name&
getName() const
{
return m_name;
}
RepoCommandParameter&
setName(const Name& name)
{
m_name = name;
m_hasName = true;
m_wire.reset();
return *this;
}
bool
hasName() const
{
return m_hasName;
}
const Selectors&
getSelectors() const
{
return m_selectors;
}
RepoCommandParameter&
setSelectors(const Selectors& selectors)
{
m_selectors = selectors;
m_wire.reset();
return *this;
}
bool
hasSelectors() const
{
return !m_selectors.empty();
}
uint64_t
getStartBlockId() const
{
assert(hasStartBlockId());
return m_startBlockId;
}
RepoCommandParameter&
setStartBlockId(uint64_t startBlockId)
{
m_startBlockId = startBlockId;
m_hasStartBlockId = true;
m_wire.reset();
return *this;
}
bool
hasStartBlockId() const
{
return m_hasStartBlockId;
}
uint64_t
getEndBlockId() const
{
assert(hasEndBlockId());
return m_endBlockId;
}
RepoCommandParameter&
setEndBlockId(uint64_t endBlockId)
{
m_endBlockId = endBlockId;
m_hasEndBlockId = true;
m_wire.reset();
return *this;
}
bool
hasEndBlockId() const
{
return m_hasEndBlockId;
}
uint64_t
getProcessId() const
{
assert(hasProcessId());
return m_processId;
}
RepoCommandParameter&
setProcessId(uint64_t processId)
{
m_processId = processId;
m_hasProcessId = true;
m_wire.reset();
return *this;
}
bool
hasProcessId() const
{
return m_hasProcessId;
}
uint64_t
getMaxInterestNum() const
{
assert(hasMaxInterestNum());
return m_maxInterestNum;
}
RepoCommandParameter&
setMaxInterestNum(uint64_t maxInterestNum)
{
m_maxInterestNum = maxInterestNum;
m_hasMaxInterestNum = true;
m_wire.reset();
return *this;
}
bool
hasMaxInterestNum() const
{
return m_hasMaxInterestNum;
}
milliseconds
getWatchTimeout() const
{
assert(hasWatchTimeout());
return m_watchTimeout;
}
RepoCommandParameter&
setWatchTimeout(milliseconds watchTimeout)
{
m_watchTimeout = watchTimeout;
m_hasWatchTimeout = true;
m_wire.reset();
return *this;
}
bool
hasWatchTimeout() const
{
return m_hasWatchTimeout;
}
milliseconds
getInterestLifetime() const
{
assert(hasInterestLifetime());
return m_interestLifetime;
}
RepoCommandParameter&
setInterestLifetime(milliseconds interestLifetime)
{
m_interestLifetime = interestLifetime;
m_hasInterestLifetime = true;
m_wire.reset();
return *this;
}
bool
hasInterestLifetime() const
{
return m_hasInterestLifetime;
}
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
const Block&
wireEncode() const;
void
wireDecode(const Block& wire);
private:
Name m_name;
Selectors m_selectors;
uint64_t m_startBlockId;
uint64_t m_endBlockId;
uint64_t m_processId;
uint64_t m_maxInterestNum;
milliseconds m_watchTimeout;
milliseconds m_interestLifetime;
bool m_hasName;
bool m_hasStartBlockId;
bool m_hasEndBlockId;
bool m_hasProcessId;
bool m_hasMaxInterestNum;
bool m_hasWatchTimeout;
bool m_hasInterestLifetime;
mutable Block m_wire;
};
template<bool T>
inline size_t
RepoCommandParameter::wireEncode(EncodingImpl<T>& encoder) const
{
size_t totalLength = 0;
size_t variableLength = 0;
if (m_hasProcessId) {
variableLength = encoder.prependNonNegativeInteger(m_processId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::ProcessId);
}
if (m_hasEndBlockId) {
variableLength = encoder.prependNonNegativeInteger(m_endBlockId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::EndBlockId);
}
if (m_hasStartBlockId) {
variableLength = encoder.prependNonNegativeInteger(m_startBlockId);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::StartBlockId);
}
if (m_hasMaxInterestNum) {
variableLength = encoder.prependNonNegativeInteger(m_maxInterestNum);
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::MaxInterestNum);
}
if (m_hasWatchTimeout) {
variableLength = encoder.prependNonNegativeInteger(m_watchTimeout.count());
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::WatchTimeout);
}
if (m_hasInterestLifetime) {
variableLength = encoder.prependNonNegativeInteger(m_interestLifetime.count());
totalLength += variableLength;
totalLength += encoder.prependVarNumber(variableLength);
totalLength += encoder.prependVarNumber(tlv::InterestLifetime);
}
if (!getSelectors().empty()) {
totalLength += getSelectors().wireEncode(encoder);
}
if (m_hasName) {
totalLength += getName().wireEncode(encoder);
}
totalLength += encoder.prependVarNumber(totalLength);
totalLength += encoder.prependVarNumber(tlv::RepoCommandParameter);
return totalLength;
}
inline const Block&
RepoCommandParameter::wireEncode() const
{
if (m_wire.hasWire())
return m_wire;
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
m_wire = buffer.block();
return m_wire;
}
inline void
RepoCommandParameter::wireDecode(const Block& wire)
{
m_hasName = false;
m_hasStartBlockId = false;
m_hasEndBlockId = false;
m_hasProcessId = false;
m_hasMaxInterestNum = false;
m_hasWatchTimeout = false;
m_hasInterestLifetime = false;
m_wire = wire;
m_wire.parse();
if (m_wire.type() != tlv::RepoCommandParameter)
throw Error("Requested decoding of RepoCommandParameter, but Block is of different type");
// Name
Block::element_const_iterator val = m_wire.find(tlv::Name);
if (val != m_wire.elements_end())
{
m_hasName = true;
m_name.wireDecode(m_wire.get(tlv::Name));
}
// Selectors
val = m_wire.find(tlv::Selectors);
if (val != m_wire.elements_end())
{
m_selectors.wireDecode(*val);
}
else
m_selectors = Selectors();
// StartBlockId
val = m_wire.find(tlv::StartBlockId);
if (val != m_wire.elements_end())
{
m_hasStartBlockId = true;
m_startBlockId = readNonNegativeInteger(*val);
}
// EndBlockId
val = m_wire.find(tlv::EndBlockId);
if (val != m_wire.elements_end())
{
m_hasEndBlockId = true;
m_endBlockId = readNonNegativeInteger(*val);
}
// ProcessId
val = m_wire.find(tlv::ProcessId);
if (val != m_wire.elements_end())
{
m_hasProcessId = true;
m_processId = readNonNegativeInteger(*val);
}
// MaxInterestNum
val = m_wire.find(tlv::MaxInterestNum);
if (val != m_wire.elements_end())
{
m_hasMaxInterestNum = true;
m_maxInterestNum = readNonNegativeInteger(*val);
}
// WatchTimeout
val = m_wire.find(tlv::WatchTimeout);
if (val != m_wire.elements_end())
{
m_hasWatchTimeout = true;
m_watchTimeout = milliseconds(readNonNegativeInteger(*val));
}
// InterestLiftTime
val = m_wire.find(tlv::InterestLifetime);
if (val != m_wire.elements_end())
{
m_hasInterestLifetime = true;
m_interestLifetime = milliseconds(readNonNegativeInteger(*val));
}
}
inline std::ostream&
operator<<(std::ostream& os, const RepoCommandParameter& repoCommandParameter)
{
os << "RepoCommandParameter(";
// Name
if (repoCommandParameter.hasName()) {
os << " Name: " << repoCommandParameter.getName();
}
if (repoCommandParameter.hasStartBlockId()) {
// StartBlockId
os << " StartBlockId: " << repoCommandParameter.getStartBlockId();
}
// EndBlockId
if (repoCommandParameter.hasEndBlockId()) {
os << " EndBlockId: " << repoCommandParameter.getEndBlockId();
}
// ProcessId
if (repoCommandParameter.hasProcessId()) {
os << " ProcessId: " << repoCommandParameter.getProcessId();
}
// MaxInterestNum
if (repoCommandParameter.hasMaxInterestNum()) {
os << " MaxInterestNum: " << repoCommandParameter.getMaxInterestNum();
}
// WatchTimeout
if (repoCommandParameter.hasProcessId()) {
os << " WatchTimeout: " << repoCommandParameter.getWatchTimeout();
}
// InterestLifetime
if (repoCommandParameter.hasProcessId()) {
os << " InterestLifetime: " << repoCommandParameter.getInterestLifetime();
}
os << " )";
return os;
}
} // namespace repo
#endif // REPO_REPO_COMMAND_PARAMETER_HPP
| 10,871 | 21.509317 | 111 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/rtt-estimator.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014 Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef RTT_ESTIMATOR_HPP
#define RTT_ESTIMATOR_HPP
#include "common.hpp"
#include <ndn-cxx/util/time.hpp>
namespace ndn {
/**
* \brief implements the Mean-Deviation RTT estimator
*
* reference: ns3::RttMeanDeviation
*
* This RttEstimator algorithm is designed for TCP, which is a continuous stream.
* NDN Interest-Data traffic is not always a continuous stream,
* so NDN may need a different RttEstimator.
* The design of a more suitable RttEstimator is a research question.
*/
class RttEstimator
{
public:
typedef time::microseconds Duration;
static Duration
getInitialRtt(void)
{
return time::seconds(1);
}
RttEstimator(uint16_t maxMultiplier = 16,
Duration minRto = time::milliseconds(1),
double gain = 0.1);
void
addMeasurement(Duration measure);
void
incrementMultiplier();
void
doubleMultiplier();
Duration
computeRto() const;
private:
uint16_t m_maxMultiplier;
double m_minRto;
double m_rtt;
double m_gain;
double m_variance;
uint16_t m_multiplier;
uint32_t m_nSamples;
};
} // namespace ndn
#endif // FW_RTT_ESTIMATOR_HPP
| 2,394 | 27.176471 | 83 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-prioritizer.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "infomax-prioritizer.hpp"
namespace ndn {
Prioritizer::Prioritizer(Producer *producer)
{
m_producer = producer;
m_listVersion = 0;
}
void
Prioritizer::prioritize()
{
int type = 0;
m_producer->getContextOption(PREFIX, m_prefix);
m_producer->getContextOption(INFOMAX_ROOT, m_root);
m_producer->getContextOption(INFOMAX_PRIORITY, type);
m_listVersion++;
if(type == INFOMAX_SIMPLE_PRIORITY)
{
simplePrioritizer(&m_root);
}
else if(type == INFOMAX_MERGE_PRIORITY)
{
mergePrioritizer(&m_root);
}
else
{
dummy(&m_root);
}
}
void
Prioritizer::simplePrioritizer(TreeNode *root)
{
resetNodeStatus(root);
unsigned int numOfLeafNodes = root->getTreeSize();
vector<TreeNode*>* prioritizedVector = new vector<TreeNode*>();
while(root->getRevisionCount() < numOfLeafNodes) {
prioritizedVector->push_back(getNextPriorityNode(root));
}
produceInfoMaxList(Name(), prioritizedVector);
}
TreeNode*
Prioritizer::getNextPriorityNode(TreeNode *root)
{
if(root == 0)
{
return 0;
}
root->updateRevisionCount(root->getRevisionCount() + 1);
if(root->isDataNode() && !(root->isNodeMarked()))
{
root->markNode(true);
return root;
}
vector<TreeNode*> children = root->getChildren();
if(children.size() > 0)
{
uint64_t leastRevisionCountNow = std::numeric_limits<uint64_t>::max();;
TreeNode *nodeWithLeastCount = NULL;
for(unsigned int i=0; i<children.size(); i++ )
{
TreeNode* child = children[i];
if(child->getRevisionCount() < child->getTreeSize() || child->getRevisionCount() == 0)
{
if(nodeWithLeastCount == 0
|| (nodeWithLeastCount != 0 && leastRevisionCountNow > child->getRevisionCount()))
{
nodeWithLeastCount = child;
leastRevisionCountNow = child->getRevisionCount();
}
}
}
return getNextPriorityNode(nodeWithLeastCount);
}
return 0;
}
void
Prioritizer::mergePrioritizer(TreeNode *root)
{
mergeSort(root);
}
std::list<TreeNode *>*
Prioritizer::mergeSort(TreeNode *node)
{
std::list<TreeNode *> *mergeList = new std::list<TreeNode *> ();
if (node->isLeafNode())
{
mergeList->push_back(node);
return mergeList;
}
vector<TreeNode *> children = node->getChildren();
vector< std::list<TreeNode *>* > *subTreeMergeList = new vector< std::list<TreeNode *>* >();
for(unsigned int i=0; i<children.size(); i++)
{
subTreeMergeList->push_back(mergeSort(children[i]));
}
mergeList = merge(subTreeMergeList);
// convert list to vector
vector<TreeNode*>* prioritizedVector = new vector<TreeNode *>{ std::make_move_iterator(std::begin(*mergeList)), std::make_move_iterator(std::end(*mergeList)) };
Name subListName = Name();
if (!node->isRootNode()) {
subListName.append(node->getName());
}
produceInfoMaxList(subListName, prioritizedVector);
return mergeList;
}
std::list<TreeNode *>*
Prioritizer::merge(vector< std::list<TreeNode*>* > *subTreeMergeList)
{
bool isListAllEmpty = false;
std::list<TreeNode *> *mergeList = new std::list<TreeNode *> ();
while (!isListAllEmpty)
{
for (unsigned int i=0; i<subTreeMergeList->size(); i++)
{
if (!subTreeMergeList->at(i)->empty())
{
isListAllEmpty = false;
break;
}
isListAllEmpty = true;
}
for (unsigned int i=0; i<subTreeMergeList->size(); i++)
{
if (!subTreeMergeList->at(i)->empty())
{
mergeList->push_back(subTreeMergeList->at(i)->front());
subTreeMergeList->at(i)->pop_front();
}
}
}
return mergeList;
}
void
Prioritizer::dummy(TreeNode *root)
{
vector<TreeNode *> *prioritizedVector = new vector<TreeNode *> ();
prioritizedVector->push_back(root);
vector<TreeNode*> children = root->getChildren();
for(unsigned int i=0; i<children.size(); i++ ) {
TreeNode *n = children[i];
prioritizedVector->push_back(n);
}
produceInfoMaxList(root->getName(), prioritizedVector);
}
void
Prioritizer::resetNodeStatus(TreeNode* node)
{
node->updateRevisionCount(0);
node->markNode(false);
vector<TreeNode*> children = node->getChildren();
if(children.size() > 0) {
for (unsigned int i=0; i < children.size(); i++) {
resetNodeStatus(children[i]);
}
}
}
void
Prioritizer::produceInfoMaxList(Name prefix, vector<TreeNode*>* prioritizedVector)
{
for(unsigned int i=0; i<prioritizedVector->size(); i=i+INFOMAX_DEFAULT_LIST_SIZE)
{
uint64_t listNum = i / INFOMAX_DEFAULT_LIST_SIZE + 1;
Name listName = Name(prefix);
listName.append(INFOMAX_INTEREST_TAG);
listName.appendNumber(m_listVersion); // current version all same
listName.appendNumber(listNum);
std::string listContent = "";
for(size_t j=i; j<prioritizedVector->size(); j++)
{
listContent += prioritizedVector->at(j)->getName().getSubName(prefix.size()).toUri();
listContent += ' ';
}
m_producer->produce(listName, (uint8_t*)listContent.c_str(), listContent.size());
}
// Produce InfoMax list meta info (version number and the total number of lists)
Name listMetaInfoName = Name(prefix);
listMetaInfoName.append(INFOMAX_INTEREST_TAG);
listMetaInfoName.append(INFOMAX_META_INTEREST_TAG);
// listMetaInfoName.appendNumber(m_listVersion);
std::string listMetaInfoContent = "";
uint64_t totalListNum = prioritizedVector->size() / INFOMAX_DEFAULT_LIST_SIZE + 1;
listMetaInfoContent = to_string(m_listVersion) + " " + to_string(totalListNum);
int dataFreshness = 0;
m_producer->getContextOption(DATA_FRESHNESS, dataFreshness);
m_producer->setContextOption(DATA_FRESHNESS, 0);
m_producer->produce(listMetaInfoName, (uint8_t*)listMetaInfoContent.c_str(), listMetaInfoContent.size());
m_producer->setContextOption(DATA_FRESHNESS, dataFreshness);
}
} | 6,799 | 26.755102 | 161 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/application-nack.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "application-nack.hpp"
namespace ndn {
ApplicationNack::ApplicationNack()
{
setContentType(tlv::ContentType_Nack);
setCode(ApplicationNack::NONE);
}
ApplicationNack::ApplicationNack(const Interest& interest, ApplicationNack::NackCode statusCode)
{
Name name = interest.getName();
name.append(Name("nack"));
name.appendNumber(ndn::random::generateSecureWord64());
setName(name);
setContentType(tlv::ContentType_Nack);
setCode(statusCode);
}
ApplicationNack::ApplicationNack(const Data& data)
: Data(data)
{
setContentType(tlv::ContentType_Nack);
decode();
}
ApplicationNack::~ApplicationNack()
{}
void
ApplicationNack::addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize)
{
std::string keyS(reinterpret_cast<const char*>(key), keySize);
std::string valueS(reinterpret_cast<const char*>(value), valueSize);
addKeyValuePair(keyS, valueS);
}
void
ApplicationNack::addKeyValuePair(std::string key, std::string value)
{
m_keyValuePairs[key] = value;
}
std::string
ApplicationNack::getValueByKey(std::string key)
{
std::map<std::string,std::string>::const_iterator it = m_keyValuePairs.find(key);
if (it == m_keyValuePairs.end())
{
return "";
}
else
{
return it->second;
}
}
void
ApplicationNack::eraseValueByKey(std::string key)
{
m_keyValuePairs.erase(m_keyValuePairs.find(key));
}
void
ApplicationNack::setCode(ApplicationNack::NackCode statusCode)
{
std::stringstream ss;
ss << statusCode;
std::string value = ss.str();
addKeyValuePair(STATUS_CODE_H, value);
}
ApplicationNack::NackCode
ApplicationNack::getCode()
{
std::string value = getValueByKey(STATUS_CODE_H);
if (value != "")
{
try
{
return (ApplicationNack::NackCode)atoi(value.c_str());
}
catch(std::exception e)
{
return ApplicationNack::NONE;
}
}
else
{
return ApplicationNack::NONE;
}
}
void
ApplicationNack::setDelay(uint32_t milliseconds)
{
std::stringstream ss;
ss << milliseconds;
std::string value = ss.str();
addKeyValuePair(RETRY_AFTER_H, value);
}
uint32_t
ApplicationNack::getDelay()
{
std::string value = getValueByKey(RETRY_AFTER_H);
return atoi(value.c_str());
}
template<bool T>
size_t
ApplicationNack::wireEncode(EncodingImpl<T>& blk) const
{
// Nack ::= CONTENT-TLV TLV-LENGTH
// KeyValuePair*
size_t totalLength = 0;
for (std::map<std::string, std::string>::const_reverse_iterator it = m_keyValuePairs.rbegin();
it != m_keyValuePairs.rend(); ++it)
{
std::string keyValue = it->first + "=" + it->second;
totalLength += blk.prependByteArray(reinterpret_cast<const uint8_t*>(keyValue.c_str()), keyValue.size());
totalLength += blk.prependVarNumber(keyValue.size());
totalLength += blk.prependVarNumber(tlv::KeyValuePair);
}
return totalLength;
}
template size_t
ApplicationNack::wireEncode<true>(EncodingImpl<true>& block) const;
template size_t
ApplicationNack::wireEncode<false>(EncodingImpl<false>& block) const;
void
ApplicationNack::encode()
{
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
setContentType(tlv::ContentType_Nack);
setContent(const_cast<uint8_t*>(buffer.buf()), buffer.size());
}
void
ApplicationNack::decode()
{
Block content = getContent();
content.parse();
// Nack ::= CONTENT-TLV TLV-LENGTH
// KeyValuePair*
for ( Block::element_const_iterator val = content.elements_begin();
val != content.elements_end(); ++val)
{
if (val->type() == tlv::KeyValuePair)
{
std::string str((char*)val->value(), val->value_size());
size_t index = str.find_first_of('=');
if (index == std::string::npos || index == 0 || (index == str.size() - 1))
continue;
std::string key = str.substr(0, index);
std::string value = str.substr(index + 1, str.size() - index - 1);
addKeyValuePair(key, value);
}
}
}
} // namespace ndn
| 5,206 | 24.650246 | 109 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/rtt-estimator.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014 Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
**/
#include "rtt-estimator.hpp"
namespace ndn {
RttEstimator::RttEstimator(uint16_t maxMultiplier, Duration minRto, double gain)
: m_maxMultiplier(maxMultiplier)
, m_minRto(minRto.count())
, m_rtt(RttEstimator::getInitialRtt().count())
, m_gain(gain)
, m_variance(0)
, m_multiplier(1)
, m_nSamples(0)
{
}
void
RttEstimator::addMeasurement(Duration measure)
{
double m = static_cast<double>(measure.count());
if (m_nSamples > 0) {
double err = m - m_rtt;
double gErr = err * m_gain;
m_rtt += gErr;
double difference = std::abs(err) - m_variance;
m_variance += difference * m_gain;
} else {
m_rtt = m;
m_variance = m;
}
++m_nSamples;
m_multiplier = 1;
}
void
RttEstimator::incrementMultiplier()
{
m_multiplier = std::min(static_cast<uint16_t>(m_multiplier + 1), m_maxMultiplier);
}
void
RttEstimator::doubleMultiplier()
{
m_multiplier = std::min(static_cast<uint16_t>(m_multiplier * 2), m_maxMultiplier);
}
RttEstimator::Duration
RttEstimator::computeRto() const
{
double rto = std::max(m_minRto, m_rtt + 4 * m_variance);
rto *= m_multiplier;
return Duration(static_cast<Duration::rep>(rto));
}
} // namespace ndn
| 2,445 | 29.575 | 84 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-tree-node.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef TREE_NODE_HPP
#define TREE_NODE_HPP
#include "common.hpp"
using namespace std;
namespace ndn {
class TreeNode
{
private:
Name name;
vector<TreeNode *> children;
bool isMarked;
TreeNode *parent;
bool dataNode;
uint64_t revisionCount;
uint64_t treeSize;
private:
/**
* Helper function for the constructor to initialize the node.
*/
void init(Name &name, TreeNode *parent);
public:
/**
* Constructor for nodes.
*/
TreeNode(Name &name, TreeNode *parent);
TreeNode(const TreeNode& other);
TreeNode();
/**
* Function to get the name associated with the TreeNode.
*/
Name
getName();
/**
* Function to get the children of the TreeNode.
*/
vector<TreeNode *>
getChildren();
/**
* Function to mark the TreeNode.
*/
bool
markNode(bool status);
/**
* Function to check if the TreeNode is marked.
*/
bool
isNodeMarked();
/**
* Function to check if the TreeNode has data.
*/
bool
setDataNode(bool flag);
/**
* Function to check if the TreeNode has data.
*/
bool
isDataNode();
/**
* Function to change the revision count of the TreeNode.
*/
bool
updateRevisionCount(unsigned long long int revisionCount);
/**
* Function to get the revision count of the TreeNode.
*/
uint64_t
getRevisionCount();
/**
* Function to check if the current node is a leaf node.
*/
bool
isLeafNode();
/**
* Function to check if the current node is a leaf node.
*/
bool
isRootNode();
/**
* Function to get number of shared prefix with input name.
*/
int
getNumSharedPrefix(TreeNode *node);
/**
* Function to remove a child from the current TreeNode. Removing a child
* changes the treesize of the current node.
*/
bool
removeChild (TreeNode * child);
/**
* Function to add a child to the current TreeNode. Adding a child
* changes the treesize of the current node and has an upward spiral
* affect, i.e., it changes the size of the upper level TreeNodes as well.
* Complexity O(N).
*/
bool
addChild (TreeNode * child);
/**
* Function to change the tree size rooted at the current TreeNode.
* Changing the treesize of the current node and has an upward spiral
* affect, i.e., it changes the size of the upper level TreeNodes as well.
* Complexity O(N).
*/
bool
setTreeSize (unsigned long long int treeSize);
/**
* Function to get the tree size rooted at the current TreeNode.
*/
uint64_t
getTreeSize ();
/**
* Function to print tree nodes data for debugging purposes.
*/
void
printTreeNode();
/**
* Function to print tree nodes data for debugging purposes.
*/
void
printTreeNodeName();
/**
* Function to get the parent node.
*/
TreeNode*
getParent();
};
} // namespace ndn
#endif // TREE_NODE_HPP | 3,871 | 23.049689 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/consumer-context.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONSUMER_CONTEXT_HPP
#define CONSUMER_CONTEXT_HPP
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "data-retrieval-protocol.hpp"
#include "simple-data-retrieval.hpp"
#include "unreliable-data-retrieval.hpp"
#include "reliable-data-retrieval.hpp"
#include "infomax-data-retrieval.hpp"
#include <ndn-cxx/util/config-file.hpp>
#include <ndn-cxx/management/nfd-controller.hpp>
namespace ndn {
/**
* @brief Consumer context is a container of consumer-specific transmission parameters for a
* specific name prefix.
*
* Consumer context performs fetching of Application Data Units using Interest/Data exchanges.
* Consumer context can be tuned using set/getcontextopt primitives.
*/
class Consumer : public Context
{
public:
/**
* @brief Initializes consumer context.
*
* @param prefix - Name components that define the range of application frames (ADU)
* that can be retrieved from the network.
* @param protocol - 1) SDR 2) UDR 3) RDR
*/
explicit Consumer(const Name prefix, int protocol);
/**
* @brief Stops the ongoing fetching of the Application Data Unit (ADU) and releases all
* associated system resources.
*
*/
~Consumer();
/**
* @brief Performs transmission of Interest packets to fetch specified Application Data Unit (ADU).
* Consume() blocks until ADU is successfully fetched or an irrecoverable error occurs.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
*/
int
consume(Name suffix);
/**
* @brief Performs transmission of Interest packets to fetch specified Application Data Unit (ADU).
* async_consume() does not block the caller thread.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
*/
int
asyncConsume(Name suffix);
/**
* @brief Stops the ongoing fetching of the Application Data Unit (ADU).
*
*/
void
stop();
static void
consumeAll();
/*
* Context option setters
* Return OPTION_VALUE_SET if success; otherwise -- OPTION_VALUE_NOT_SET
*/
int
setContextOption(int optionName, int optionValue);
int
setContextOption(int optionName, bool optionValue);
int
setContextOption(int optionName, size_t optionValue);
int
setContextOption(int optionName, Name optionValue);
int
setContextOption(int optionName, ProducerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerDataVerificationCallback optionValue);
int
setContextOption(int optionName, ConsumerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerInterestCallback optionValue);
int
setContextOption(int optionName, ProducerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerContentCallback optionValue);
int
setContextOption(int optionName, ConsumerNackCallback optionValue);
int
setContextOption(int optionName, ConsumerManifestCallback optionValue);
int
setContextOption(int optionName, KeyLocator optionValue);
int
setContextOption(int optionName, Exclude optionValue);
/*
* Context option getters
* Return OPTION_FOUND if success; otherwise -- OPTION_NOT_FOUND
*/
int
getContextOption(int optionName, int& optionValue);
int
getContextOption(int optionName, size_t& optionValue);
int
getContextOption(int optionName, bool& optionValue);
int
getContextOption(int optionName, Name& optionValue);
int
getContextOption(int optionName, ProducerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerInterestCallback& optionValue);
int
getContextOption(int optionName, ProducerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerContentCallback& optionValue);
int
getContextOption(int optionName, ConsumerNackCallback& optionValue);
int
getContextOption(int optionName, ConsumerManifestCallback& optionValue);
int
getContextOption(int optionName, KeyLocator& optionValue);
int
getContextOption(int optionName, Exclude& optionValue);
int
getContextOption(int optionName, shared_ptr<Face>& optionValue);
int
getContextOption(int optionName, TreeNode& optionValue);
private:
void
postponedConsume(Name suffix);
void
onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult, const std::string& message);
void
onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message);
private:
// context inner state variables
bool m_isRunning;
shared_ptr<ndn::Face> m_face;
shared_ptr<DataRetrievalProtocol> m_dataRetrievalProtocol;
KeyChain m_keyChain;
shared_ptr<nfd::Controller> m_controller;
Name m_prefix;
Name m_suffix;
Name m_forwardingStrategy;
int m_interestLifetimeMillisec;
int m_minWindowSize;
int m_maxWindowSize;
int m_currentWindowSize;
int m_nMaxRetransmissions;
int m_nMaxExcludedDigests;
size_t m_sendBufferSize;
size_t m_receiveBufferSize;
bool m_isAsync;
/// selectors
int m_minSuffixComponents;
int m_maxSuffixComponents;
KeyLocator m_publisherKeyLocator;
Exclude m_exclude;
int m_childSelector;
bool m_mustBeFresh;
/// user-provided callbacks
ConsumerInterestCallback m_onInterestRetransmitted;
ConsumerInterestCallback m_onInterestToLeaveContext;
ConsumerInterestCallback m_onInterestExpired;
ConsumerInterestCallback m_onInterestSatisfied;
ConsumerDataCallback m_onDataEnteredContext;
ConsumerDataVerificationCallback m_onDataToVerify;
ConsumerDataCallback m_onContentData;
ConsumerNackCallback m_onNack;
ConsumerManifestCallback m_onManifest;
ConsumerContentCallback m_onPayloadReassembled;
};
} // namespace ndn
#endif // CONSUMER_CONTEXT_HPP
| 7,139 | 26.890625 | 106 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/producer-context.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef PRODUCER_CONTEXT_HPP
#define PRODUCER_CONTEXT_HPP
#include "common.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "context.hpp"
#include "cs.hpp"
#include "repo-command-parameter.hpp"
#include "infomax-tree-node.hpp"
#include "infomax-prioritizer.hpp"
#include <ndn-cxx/signature.hpp>
#include <ndn-cxx/security/key-chain.hpp>
#include <ndn-cxx/management/nfd-controller.hpp>
#include <ndn-cxx/util/scheduler.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/atomic.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/asio.hpp>
#include <queue>
#include <time.h> // for nanosleep
namespace ndn {
class Prioritizer;
/**
* @brief Producer context is a container of producer-specific transmission parameters for a
* specific name prefix.
*
* Producer context performs transformation of Application Data Units into Data packets.
* Producer context can be tuned using set/getcontextopt primitives.
*/
class Producer : public Context
{
public:
/**
* @brief Initializes producer context with default parameters.
* Context's parameters can be changed with setContextOption function.
*
* @param prefix Name components that identify the namespace
* where all generated Data packets will be placed.
*/
explicit Producer(Name prefix);
/**
* @brief Detaches producer context from the network and releases all associated system resources.
*
*/
~Producer();
/**
* @brief Attaches producer context to the network by registering its name prefix.
*
*/
void
attach();
/**
* @brief Performs segmentation of the supplied memory buffer into Data packets.
* Produced Data packets are placed in the output buffer to satisfy pending and future Interests.
* Produce() blocks until all Data segments are succesfully placed in the output buffer.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
* @param buffer Memory buffer storing Application Data Unit (ADU)
* @param bufferSize Size of the supplied memory buffer
*
* @return The number of produced Data packets or -1 if the supplied ADU requires
* more Data segments than it is possible to store in the output buffer.
*/
void
produce(Name suffix, const uint8_t* buffer, size_t bufferSize);
void
produce(Data& packet);
/**
* @brief Performs segmentation of the supplied memory buffer into Data packets.
* Produced Data packets are placed in the output buffer to satisfy pending and future Interests.
* asyncProduce() does not block and schedules segmentation for future execution.
*
* @param suffix Name components that identify the boundary of Application Data Unit (ADU)
* @param buffer Memory buffer storing Application Data Unit (ADU)
* @param bufferSize Size of the supplied memory buffer
*
*/
void
asyncProduce(Name suffix, const uint8_t* buffer, size_t bufferSize);
void
asyncProduce(Data& packet);
/**
* @brief Satisfies an Interest with Negative Acknowledgement.
*
* @param appNack Negative Acknowledgement
*/
int
nack(ApplicationNack appNack);
/*
* Context option setters
*/
int
setContextOption(int optionName, int optionValue);
int
setContextOption(int optionName, bool optionValue);
int
setContextOption(int optionName, size_t optionValue);
int
setContextOption(int optionName, Name optionValue);
int
setContextOption(int optionName, ProducerDataCallback optionValue);
int
setContextOption(int optionName, ProducerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerDataVerificationCallback optionValue);
int
setContextOption(int optionName, ConsumerDataCallback optionValue);
int
setContextOption(int optionName, ConsumerInterestCallback optionValue);
int
setContextOption(int optionName, ConsumerContentCallback optionValue);
int
setContextOption(int optionName, ConsumerNackCallback optionValue);
int
setContextOption(int optionName, ConsumerManifestCallback optionValue);
int
setContextOption(int optionName, KeyLocator optionValue);
int
setContextOption(int optionName, Exclude optionValue);
/*
* Context option getters
*/
int
getContextOption(int optionName, int& optionValue);
int
getContextOption(int optionName, bool& optionValue);
int
getContextOption(int optionName, size_t& optionValue);
int
getContextOption(int optionName, Name& optionValue);
int
getContextOption(int optionName, ProducerDataCallback& optionValue);
int
getContextOption(int optionName, ProducerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue);
int
getContextOption(int optionName, ConsumerDataCallback& optionValue);
int
getContextOption(int optionName, ConsumerInterestCallback& optionValue);
int
getContextOption(int optionName, ConsumerContentCallback& optionValue);
int
getContextOption(int optionName, ConsumerNackCallback& optionValue);
int
getContextOption(int optionName, ConsumerManifestCallback& optionValue);
int
getContextOption(int optionName, KeyLocator& optionValue);
int
getContextOption(int optionName, Exclude& optionValue);
int
getContextOption(int optionName, shared_ptr<Face>& optionValue);
int
getContextOption(int optionName, TreeNode& optionValue);
private:
// context inner state variables
ndn::shared_ptr<ndn::Face> m_face;
boost::asio::io_service m_ioService;
shared_ptr<nfd::Controller> m_controller;
Scheduler* m_scheduler;
Name m_prefix;
Name m_targetRepoPrefix;
Name m_forwardingStrategy;
int m_dataPacketSize;
int m_dataFreshness;
int m_registrationStatus;
bool m_isMakingManifest;
// repo related stuff
bool m_isWritingToLocalRepo;
boost::asio::io_service m_repoIoService;
boost::asio::ip::tcp::socket m_repoSocket;
// infomax related stuff
uint64_t m_infomaxTreeVersion;
uint64_t m_infomaxUpdateInterval;
bool m_isNewInfomaxData;
TreeNode m_infomaxRoot;
shared_ptr<Prioritizer> m_infomaxPrioritizer;
int m_infomaxType; // currently there are only 2 types: normal and InfoMax producer
int m_signatureType;
int m_signatureSize;
int m_keyLocatorSize;
KeyLocator m_keyLocator;
KeyChain m_keyChain;
// buffers
Cs m_sendBuffer;
//boost::lockfree::queue<shared_ptr<const Interest> >m_receiveBuffer{DEFAULT_PRODUCER_RCV_BUFFER_SIZE};
std::queue< shared_ptr<const Interest> > m_receiveBuffer;
boost::mutex m_receiveBufferMutex;
boost::atomic_size_t m_receiveBufferCapacity;
boost::atomic_size_t m_receiveBufferSize;
// threads
boost::thread m_listeningThread;
boost::thread m_processingThread;
// user-defined callbacks
ProducerInterestCallback m_onInterestEntersContext;
ProducerInterestCallback m_onInterestDroppedFromRcvBuffer;
ProducerInterestCallback m_onInterestPassedRcvBuffer;
ProducerInterestCallback m_onInterestSatisfiedFromSndBuffer;
ProducerInterestCallback m_onInterestProcess;
ProducerDataCallback m_onNewSegment;
ProducerDataCallback m_onDataToSecure;
ProducerDataCallback m_onDataInSndBuffer;
ProducerDataCallback m_onDataLeavesContext;
ProducerDataCallback m_onDataEvictedFromSndBuffer;
private:
void
listen();
void
updateInfomaxTree();
void
onInterest(const Name& name, const Interest& interest);
void
onRegistrationSucceded (const ndn::Name& prefix);
void
onRegistrationFailed (const ndn::Name& prefix, const std::string& reason);
void
processIncomingInterest(/*const Name& name, const Interest& interest*/);
void
processInterestFromReceiveBuffer();
void
passSegmentThroughCallbacks(shared_ptr<Data> segment);
size_t
estimateManifestSize(shared_ptr<Manifest> manifest);
void
writeToRepo(Name dataPrefix, uint64_t startSegment, uint64_t endSegment);
void
onRepoReply(const ndn::Interest& interest, ndn::Data& data);
void
onRepoTimeout(const ndn::Interest& interest);
void
onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult,
const std::string& message);
void
onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message);
};
} // namespace ndn
#endif // PRODUCER_CONTEXT_HPP
| 9,575 | 27.843373 | 105 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs-entry.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef NFD_TABLE_CS_ENTRY_HPP
#define NFD_TABLE_CS_ENTRY_HPP
#include "common.hpp"
#include <ndn-cxx/util/crypto.hpp>
namespace ndn {
namespace cs {
class Entry;
/** \brief represents a CS entry
*/
class Entry : noncopyable
{
public:
typedef std::map<int, std::list<Entry*>::iterator > LayerIterators;
Entry();
/** \brief releases reference counts on shared objects
*/
void
release();
/** \brief returns the name of the Data packet stored in the CS entry
* \return{ NDN name }
*/
const Name&
getName() const;
/** \brief Data packet is unsolicited if this particular NDN node
* did not receive an Interest packet for it, or the Interest packet has already expired
* \return{ True if the Data packet is unsolicited; otherwise False }
*/
bool
isUnsolicited() const;
/** \brief returns the absolute time when Data becomes expired
* \return{ Time (resolution up to time::milliseconds) }
*/
const time::steady_clock::TimePoint&
getStaleTime() const;
/** \brief returns the Data packet stored in the CS entry
*/
const Data&
getData() const;
/** \brief changes the content of CS entry and recomputes digest
*/
void
setData(const Data& data, bool isUnsolicited);
/** \brief changes the content of CS entry and modifies digest
*/
void
setData(const Data& data, bool isUnsolicited, const ndn::ConstBufferPtr& digest);
/** \brief refreshes the time when Data becomes expired
* according to the current absolute time.
*/
void
updateStaleTime();
/** \brief returns the digest of the Data packet stored in the CS entry.
*/
const ndn::ConstBufferPtr&
getDigest() const;
/** \brief saves the iterator pointing to the CS entry on a specific layer of skip list
*/
void
setIterator(int layer, const LayerIterators::mapped_type& layerIterator);
/** \brief removes the iterator pointing to the CS entry on a specific layer of skip list
*/
void
removeIterator(int layer);
/** \brief returns the table containing <layer, iterator> pairs.
*/
const LayerIterators&
getIterators() const;
private:
/** \brief prints <layer, iterator> pairs.
*/
void
printIterators() const;
private:
time::steady_clock::TimePoint m_staleAt;
shared_ptr<const Data> m_dataPacket;
bool m_isUnsolicited;
Name m_nameWithDigest;
mutable ndn::ConstBufferPtr m_digest;
LayerIterators m_layerIterators;
};
inline
Entry::Entry()
{
}
inline const Name&
Entry::getName() const
{
return m_nameWithDigest;
}
inline const Data&
Entry::getData() const
{
return *m_dataPacket;
}
inline bool
Entry::isUnsolicited() const
{
return m_isUnsolicited;
}
inline const time::steady_clock::TimePoint&
Entry::getStaleTime() const
{
return m_staleAt;
}
inline const Entry::LayerIterators&
Entry::getIterators() const
{
return m_layerIterators;
}
} // namespace cs
} // namespace nfd
#endif // NFD_TABLE_CS_ENTRY_HPP
| 4,007 | 23.290909 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/context-default-values.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef CONTEXT_DEFAULT_VALUES_HPP
#define CONTEXT_DEFAULT_VALUES_HPP
// this file contains various default values
// numbers here are not unique
#define EMPTY_CALLBACK 0
// protocols
#define SDR 0
#define UDR 1
#define RDR 2
#define IDR 3
// forwarding strategies
const ndn::Name BEST_ROUTE("ndn:/localhost/nfd/strategy/best-route");
const ndn::Name BROADCAST("ndn:/localhost/nfd/strategy/broadcast");
const ndn::Name CLIENT_CONTROL("ndn:/localhost/nfd/strategy/client-control");
//const ndn::Name NCC("ndn:/localhost/nfd/strategy/ncc");
// default values
#define DEFAULT_INTEREST_LIFETIME 200 // milliseconds
#define DEFAULT_DATA_FRESHNESS 100000 // milliseconds ~= 100 seconds
#define DEFAULT_DATA_PACKET_SIZE 2048 // bytes
#define DEFAULT_INTEREST_SCOPE 2
#define DEFAULT_MIN_SUFFIX_COMP -1
#define DEFAULT_MAX_SUFFIX_COMP -1
#define DEFAULT_PRODUCER_RCV_BUFFER_SIZE 1000 // of Interests
#define DEFAULT_PRODUCER_SND_BUFFER_SIZE 1000 // of Data
#define DEFAULT_KEY_LOCATOR_SIZE 256 // of bytes
#define DEFAULT_SAFETY_OFFSET 10 // of bytes
#define DEFAULT_MIN_WINDOW_SIZE 4 // of Interests
#define DEFAULT_MAX_WINDOW_SIZE 64 // of Interests
#define DEFAULT_DIGEST_SIZE 32 // of bytes
#define DEFAULT_FAST_RETX_CONDITION 3 // of out-of-order segments
// maximum allowed values
#define CONSUMER_MIN_RETRANSMISSIONS 0
#define CONSUMER_MAX_RETRANSMISSIONS 32
#define DEFAULT_MAX_EXCLUDED_DIGESTS 5
#define MAX_DATA_PACKET_SIZE 8096
// set/getcontextoption values
#define OPTION_FOUND 0
#define OPTION_NOT_FOUND 1
#define OPTION_VALUE_SET 2
#define OPTION_VALUE_NOT_SET 3
#define OPTION_DEFAULT_VALUE 666 // some rare number
// misc. values
#define PRODUCER_OPERATION_FAILED 10
#define CONSUMER_READY 0
#define CONSUMER_BUSY 1
#define REGISTRATION_NOT_ATTEMPTED 0
#define REGISTRATION_SUCCESS 1
#define REGISTRATION_FAILURE 2
#define REGISTRATION_IN_PROGRESS 3
#define LEFTMOST_CHILD 0
#define RIGHTMOST_CHILD 1
#define SHA_256 1
#define RSA_256 2
// Negative acknowledgement related constants
#define NACK_DATA_TYPE tlv::ContentType_Nack
#define NACK_DELAY 1
#define NACK_INTEREST_NOT_VERIFIED 2
// Manifest related constants
#define MANIFEST_DATA_TYPE tlv::ContentType_Manifest
#define FULL_NAME_ENUMERATION 0
#define DIGEST_ENUMERATION 1
#define CONTENT_DATA_TYPE tlv::ContentType_Blob
// InfoMax parameter
#define INFOMAX_DEFAULT_LIST_SIZE 10
#define INFOMAX_INTEREST_TAG "InfoMax"
#define INFOMAX_META_INTEREST_TAG "MetaInfo"
#define INFOMAX_DEFAULT_UPDATE_INTERVAL 5000 // 5 seconds
// InfoMax prioritizer
#define INFOMAX_NONE 0
#define INFOMAX_SIMPLE_PRIORITY 1
#define INFOMAX_MERGE_PRIORITY 2
#endif
| 3,817 | 32.491228 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/unreliable-data-retrieval.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef UNRELIABLE_DATA_RETRIEVAL_HPP
#define UNRELIABLE_DATA_RETRIEVAL_HPP
#include "data-retrieval-protocol.hpp"
#include "selector-helper.hpp"
namespace ndn {
/*
* UDR provides unreliable and unordered delivery of data segments that belong to a single ADU
* between the consumer application and the NDN network.
* In UDR, the transfer of every ADU begins with the segment number zero.
* UDR infers the name of the last data segment of the sequence with help of FinalBlockID field,
* and stops the transmission of Interest packets at this name (segment).
* FinalBlockID packet field is set at the moment of application frame (ADU) segmentation.
*/
class UnreliableDataRetrieval : public DataRetrievalProtocol
{
public:
UnreliableDataRetrieval(Context* context);
void
start();
void
stop();
private:
void
sendInterest();
void
onData(const ndn::Interest& interest, ndn::Data& data);
void
onTimeout(const ndn::Interest& interest);
void
checkFastRetransmissionConditions(const ndn::Interest& interest);
void
fastRetransmit(const ndn::Interest& interest, uint64_t segNumber);
void
removeAllPendingInterests();
private:
bool m_isFinalBlockNumberDiscovered;
int m_nTimeouts;
uint64_t m_finalBlockNumber;
uint64_t m_segNumber;
int m_currentWindowSize;
int m_interestsInFlight;
std::unordered_map<uint64_t, const PendingInterestId*> m_expressedInterests; // by segment number
// Fast Retransmission
std::map<uint64_t, bool> m_receivedSegments;
std::map<uint64_t, bool> m_fastRetxSegments;
};
} // namespace ndn
#endif // UNRELIABLE_DATA_RETRIEVAL_HPP
| 2,715 | 29.516854 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/unreliable-data-retrieval.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "unreliable-data-retrieval.hpp"
#include "consumer-context.hpp"
namespace ndn {
UnreliableDataRetrieval::UnreliableDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
, m_isFinalBlockNumberDiscovered(false)
, m_nTimeouts(0)
, m_finalBlockNumber(std::numeric_limits<uint64_t>::max())
, m_segNumber(0)
, m_currentWindowSize(0)
, m_interestsInFlight(0)
{
context->getContextOption(FACE, m_face);
}
void
UnreliableDataRetrieval::start()
{
m_isRunning = true;
m_isFinalBlockNumberDiscovered = false;
m_nTimeouts = 0;
m_finalBlockNumber = std::numeric_limits<uint64_t>::max();
m_segNumber = 0;
m_interestsInFlight = 0;
m_currentWindowSize = 0;
// this is to support window size "inheritance" between consume calls
/*int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > 0)
{
m_currentWindowSize = currentWindowSize;
}
else
{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
m_currentWindowSize = minWindowSize;
}
// initial burst of Interests
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber < m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}*/
//send exactly 1 Interest to get the FinalBlockId
sendInterest();
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
m_face->processEvents();
}
}
void
UnreliableDataRetrieval::sendInterest()
{
Name prefix;
m_context->getContextOption(PREFIX, prefix);
Name suffix;
m_context->getContextOption(SUFFIX, suffix);
if (!suffix.empty())
{
prefix.append(suffix);
}
prefix.appendSegment(m_segNumber);
Interest interest(prefix);
int interestLifetime = 0;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interest, m_context);
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interest);
}
m_interestsInFlight++;
m_expressedInterests[m_segNumber] = m_face->expressInterest(interest,
bind(&UnreliableDataRetrieval::onData, this, _1, _2),
bind(&UnreliableDataRetrieval::onTimeout, this, _1));
m_segNumber++;
}
void
UnreliableDataRetrieval::stop()
{
m_isRunning = false;
removeAllPendingInterests();
}
void
UnreliableDataRetrieval::onData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
ConsumerDataCallback onDataEnteredContext = EMPTY_CALLBACK;
m_context->getContextOption(DATA_ENTER_CNTX, onDataEnteredContext);
if (onDataEnteredContext != EMPTY_CALLBACK)
{
onDataEnteredContext(*dynamic_cast<Consumer*>(m_context), data);
}
ConsumerInterestCallback onInterestSatisfied = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_SATISFIED, onInterestSatisfied);
if (onInterestSatisfied != EMPTY_CALLBACK)
{
onInterestSatisfied(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
isDataSecure = true;
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
if (data.getContentType() == CONTENT_DATA_TYPE)
{
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize)
{
m_currentWindowSize++;
}
if (!data.getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = data.getFinalBlockId().toSegment();
}
const Block content = data.getContent();
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), content.value(), content.value_size());
}
}
else if (data.getContentType() == NACK_DATA_TYPE)
{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize)
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
}
shared_ptr<ApplicationNack> nack = make_shared<ApplicationNack>(data);
ConsumerNackCallback onNack = EMPTY_CALLBACK;
m_context->getContextOption(NACK_ENTER_CNTX, onNack);
if (onNack != EMPTY_CALLBACK)
{
onNack(*dynamic_cast<Consumer*>(m_context), *nack);
}
}
}
if (!m_isRunning ||
((m_isFinalBlockNumberDiscovered) && (data.getName().get(-1).toSegment() >= m_finalBlockNumber)))
{
removeAllPendingInterests();
m_isRunning = false;
//reduce window size to prevent its speculative growth in case when consume() is called in loop
int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > m_finalBlockNumber)
{
m_context->setContextOption(CURRENT_WINDOW_SIZE, (int)(m_finalBlockNumber));
}
}
// some flow control
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
void
UnreliableDataRetrieval::onTimeout(const ndn::Interest& interest)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize)
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
}
ConsumerInterestCallback onInterestExpired = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_EXPIRED, onInterestExpired);
if (onInterestExpired != EMPTY_CALLBACK)
{
onInterestExpired(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
// this code handles the situation when an application frame is small (1 or several packets)
// and packets are lost. Without this code, the protocol continues to send Interests for
// non-existing packets, because it was never able to discover the correct FinalBlockID.
if (!m_isFinalBlockNumberDiscovered)
{
m_nTimeouts++;
if(m_nTimeouts > 2)
{
m_isRunning = false;
return;
}
}
// some flow control
while (m_interestsInFlight < m_currentWindowSize)
{
//std::cout << "inFlight: " << m_interestsInFlight << " windSize " << m_currentWindowSize << std::endl;
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
void
UnreliableDataRetrieval::checkFastRetransmissionConditions(const ndn::Interest& interest)
{
uint64_t segNumber = interest.getName().get(-1).toSegment();
m_receivedSegments[segNumber] = true;
m_fastRetxSegments.erase(segNumber);
uint64_t possiblyLostSegment = 0;
uint64_t highestReceivedSegment = m_receivedSegments.rbegin()->first;
for (uint64_t i = 0; i <= highestReceivedSegment; i++)
{
if (m_receivedSegments.find(i) == m_receivedSegments.end()) // segment is not received yet
{
// segment has not been fast retransmitted yet
if (m_fastRetxSegments.find(i) == m_fastRetxSegments.end())
{
possiblyLostSegment = i;
uint8_t nOutOfOrderSegments = 0;
for (uint64_t j = i; j <= highestReceivedSegment; j++)
{
if (m_receivedSegments.find(j) != m_receivedSegments.end())
{
nOutOfOrderSegments++;
if (nOutOfOrderSegments == DEFAULT_FAST_RETX_CONDITION)
{
m_fastRetxSegments[possiblyLostSegment] = true;
fastRetransmit(interest, possiblyLostSegment);
}
}
}
}
}
}
}
void
UnreliableDataRetrieval::fastRetransmit(const ndn::Interest& interest, uint64_t segNumber)
{
Name name = interest.getName().getPrefix(-1);
name.appendSegment(segNumber);
Interest retxInterest(name);
SelectorHelper::applySelectors(retxInterest, m_context);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
//retransmit
m_interestsInFlight++;
m_expressedInterests[m_segNumber] = m_face->expressInterest(retxInterest,
bind(&UnreliableDataRetrieval::onData, this, _1, _2),
bind(&UnreliableDataRetrieval::onTimeout, this, _1));
}
void
UnreliableDataRetrieval::removeAllPendingInterests()
{
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
//won't work ---> m_face->getIoService().stop();
m_face->removePendingInterest(); // faster, but destroys everything
}
else // slower, but destroys only necessary Interests
{
for(std::unordered_map<uint64_t, const PendingInterestId*>::iterator it = m_expressedInterests.begin();
it != m_expressedInterests.end(); ++it)
{
m_face->removePendingInterest(it->second);
}
}
m_expressedInterests.clear();
}
} //namespace ndn
| 11,990 | 27.618138 | 107 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/data-retrieval-protocol.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "data-retrieval-protocol.hpp"
namespace ndn {
DataRetrievalProtocol::DataRetrievalProtocol(Context* context)
: m_context(context)
, m_isRunning(false)
{
}
void
DataRetrievalProtocol::updateFace()
{
m_context->getContextOption(FACE, m_face);
}
bool
DataRetrievalProtocol::isRunning()
{
return m_isRunning;
}
} //namespace nfd
| 1,415 | 30.466667 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/consumer-context.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "consumer-context.hpp"
namespace ndn {
Consumer::Consumer(Name prefix, int protocol)
: m_isRunning(false)
, m_prefix(prefix)
, m_interestLifetimeMillisec(DEFAULT_INTEREST_LIFETIME)
, m_minWindowSize(DEFAULT_MIN_WINDOW_SIZE)
, m_maxWindowSize(DEFAULT_MAX_WINDOW_SIZE)
, m_currentWindowSize(-1)
, m_nMaxRetransmissions(CONSUMER_MAX_RETRANSMISSIONS)
, m_nMaxExcludedDigests(DEFAULT_MAX_EXCLUDED_DIGESTS)
, m_isAsync(false)
, m_minSuffixComponents(DEFAULT_MIN_SUFFIX_COMP)
, m_maxSuffixComponents(DEFAULT_MAX_SUFFIX_COMP)
, m_childSelector(0)
, m_mustBeFresh(false)
, m_onInterestToLeaveContext(EMPTY_CALLBACK)
, m_onInterestExpired(EMPTY_CALLBACK)
, m_onInterestSatisfied(EMPTY_CALLBACK)
, m_onDataEnteredContext(EMPTY_CALLBACK)
, m_onDataToVerify(EMPTY_CALLBACK)
, m_onContentData(EMPTY_CALLBACK)
, m_onNack(EMPTY_CALLBACK)
, m_onManifest(EMPTY_CALLBACK)
, m_onPayloadReassembled(EMPTY_CALLBACK)
{
m_face = ndn::make_shared<Face>();
//m_ioService = ndn::make_shared<boost::asio::io_service>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
if (protocol == UDR)
{
m_dataRetrievalProtocol = make_shared<UnreliableDataRetrieval>(this);
}
else if (protocol == RDR)
{
m_dataRetrievalProtocol = make_shared<ReliableDataRetrieval>(this);
}
else if (protocol == IDR)
{
m_dataRetrievalProtocol = make_shared<InfoMaxDataRetrieval>(this);
}
else
{
m_dataRetrievalProtocol = make_shared<SimpleDataRetrieval>(this);
}
}
Consumer::~Consumer()
{
stop();
m_dataRetrievalProtocol.reset(); // reset the pointer counter
m_face.reset(); // reset the pointer counter
}
int
Consumer::consume(Name suffix)
{
if (m_isRunning/*m_dataRetrievalProtocol->isRunning()*/)
{
// put in the schedule
m_face->getIoService().post(bind(&Consumer::postponedConsume, this, suffix));
return CONSUMER_BUSY;
}
// if previously used in non-blocking mode
if (m_isAsync)
{
m_face = ndn::make_shared<Face>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = false;
m_dataRetrievalProtocol->start();
m_isRunning = false;
return CONSUMER_READY;
}
void
Consumer::postponedConsume(Name suffix)
{
// if previously used in non-blocking mode
if (m_isAsync)
{
m_face = ndn::make_shared<Face>();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = false;
m_dataRetrievalProtocol->start();
}
int
Consumer::asyncConsume(Name suffix)
{
if (m_dataRetrievalProtocol->isRunning())
{
return CONSUMER_BUSY;
}
if (!m_isAsync) // if previously used in blocking mode
{
m_face = FaceHelper::getFace();
m_controller = ndn::make_shared<nfd::Controller>(*m_face, m_keyChain);
m_dataRetrievalProtocol->updateFace();
}
m_suffix = suffix;
m_isAsync = true;
m_dataRetrievalProtocol->start();
return CONSUMER_READY;
}
void
Consumer::stop()
{
if (m_dataRetrievalProtocol->isRunning())
{
m_dataRetrievalProtocol->stop();
m_face->getIoService().stop();
m_face->getIoService().reset();
}
m_isRunning = false;
}
int
Consumer::setContextOption(int optionName, int optionValue)
{
switch (optionName)
{
case MIN_WINDOW_SIZE:
m_minWindowSize = optionValue;
return OPTION_VALUE_SET;
case MAX_WINDOW_SIZE:
m_maxWindowSize = optionValue;
return OPTION_VALUE_SET;
case MAX_EXCLUDED_DIGESTS:
m_nMaxExcludedDigests = optionValue;
return OPTION_VALUE_SET;
case CURRENT_WINDOW_SIZE:
m_currentWindowSize = optionValue;
return OPTION_VALUE_SET;
case RCV_BUF_SIZE:
m_receiveBufferSize = optionValue;
return OPTION_VALUE_SET;
case SND_BUF_SIZE:
m_sendBufferSize = optionValue;
return OPTION_VALUE_SET;
case INTEREST_RETX:
if (optionValue < CONSUMER_MAX_RETRANSMISSIONS)
{
m_nMaxRetransmissions = optionValue;
return OPTION_VALUE_SET;
}
else
{
return OPTION_VALUE_NOT_SET;
}
case INTEREST_LIFETIME:
m_interestLifetimeMillisec = optionValue;
return OPTION_VALUE_SET;
case MIN_SUFFIX_COMP_S:
if (optionValue >= 0)
{
m_minSuffixComponents = optionValue;
}
else
{
m_minSuffixComponents = DEFAULT_MIN_SUFFIX_COMP;
return OPTION_VALUE_NOT_SET;
}
case MAX_SUFFIX_COMP_S:
if (optionValue >= 0)
{
m_maxSuffixComponents = optionValue;
}
else
{
m_maxSuffixComponents = DEFAULT_MAX_SUFFIX_COMP;
return OPTION_VALUE_NOT_SET;
}
case RIGHTMOST_CHILD_S:
if (optionValue == 1)
{
m_childSelector = 1;
}
else
{
m_childSelector = 0;
}
return OPTION_VALUE_SET;
case LEFTMOST_CHILD_S:
if (optionValue == 1)
{
m_childSelector = 0;
}
else
{
m_childSelector = 1;
}
return OPTION_VALUE_SET;
case INTEREST_RETRANSMIT:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestRetransmitted = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_EXPIRED:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestExpired = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_SATISFIED:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestSatisfied = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case INTEREST_LEAVE_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onInterestToLeaveContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_ENTER_CNTX:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataEnteredContext = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case DATA_TO_VERIFY:
if (optionValue == EMPTY_CALLBACK)
{
m_onDataToVerify = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
case CONTENT_RETRIEVED:
if (optionValue == EMPTY_CALLBACK)
{
m_onPayloadReassembled = EMPTY_CALLBACK;
return OPTION_VALUE_SET;
}
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, size_t optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
m_receiveBufferSize = optionValue;
return OPTION_VALUE_SET;
case SND_BUF_SIZE:
m_sendBufferSize = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, bool optionValue)
{
switch (optionName)
{
case MUST_BE_FRESH_S:
m_mustBeFresh = optionValue;
return OPTION_VALUE_SET;
case RIGHTMOST_CHILD_S:
if (optionValue == true)
{
m_childSelector = 1;
}
else
{
m_childSelector = 0;
}
return OPTION_VALUE_SET;
case LEFTMOST_CHILD_S:
if (optionValue == true)
{
m_childSelector = 0;
}
else
{
m_childSelector = 1;
}
return OPTION_VALUE_SET;
case RUNNING:
m_isRunning = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, Name optionValue)
{
switch (optionName)
{
case PREFIX:
m_prefix = optionValue;;
return OPTION_VALUE_SET;
case SUFFIX:
m_suffix = optionValue;
return OPTION_VALUE_SET;
case FORWARDING_STRATEGY:
m_forwardingStrategy = optionValue;
if (m_forwardingStrategy.empty())
{
nfd::ControlParameters parameters;
parameters.setName(m_prefix);
m_controller->start<nfd::StrategyChoiceUnsetCommand>(parameters,
bind(&Consumer::onStrategyChangeSuccess, this, _1,
"Successfully unset strategy choice"),
bind(&Consumer::onStrategyChangeError, this, _1, _2,
"Failed to unset strategy choice"));
}
else
{
nfd::ControlParameters parameters;
parameters
.setName(m_prefix)
.setStrategy(m_forwardingStrategy);
m_controller->start<nfd::StrategyChoiceSetCommand>(parameters,
bind(&Consumer::onStrategyChangeSuccess, this, _1,
"Successfully set strategy choice"),
bind(&Consumer::onStrategyChangeError, this, _1, _2,
"Failed to set strategy choice"));
}
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerDataCallback optionValue)
{
switch (optionName)
{
case DATA_ENTER_CNTX:
m_onDataEnteredContext = optionValue;;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ProducerDataCallback optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, ConsumerDataVerificationCallback optionValue)
{
switch (optionName)
{
case DATA_TO_VERIFY:
m_onDataToVerify = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerInterestCallback optionValue)
{
switch (optionName)
{
case INTEREST_RETRANSMIT:
m_onInterestRetransmitted = optionValue;
return OPTION_VALUE_SET;
case INTEREST_LEAVE_CNTX:
m_onInterestToLeaveContext = optionValue;
return OPTION_VALUE_SET;
case INTEREST_EXPIRED:
m_onInterestExpired = optionValue;
return OPTION_VALUE_SET;
case INTEREST_SATISFIED:
m_onInterestSatisfied = optionValue;
return OPTION_VALUE_SET;
default:
return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ProducerInterestCallback optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, ConsumerContentCallback optionValue)
{
switch (optionName)
{
case CONTENT_RETRIEVED:
m_onPayloadReassembled = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerNackCallback optionValue)
{
switch (optionName)
{
case NACK_ENTER_CNTX:
m_onNack = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, ConsumerManifestCallback optionValue)
{
switch (optionName)
{
case MANIFEST_ENTER_CNTX:
m_onManifest = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::setContextOption(int optionName, KeyLocator optionValue)
{
return OPTION_VALUE_NOT_SET;
}
int
Consumer::setContextOption(int optionName, Exclude optionValue)
{
switch (optionName)
{
case EXCLUDE_S:
m_exclude = optionValue;
return OPTION_VALUE_SET;
default: return OPTION_VALUE_NOT_SET;
}
}
int
Consumer::getContextOption(int optionName, int& optionValue)
{
switch (optionName)
{
case MIN_WINDOW_SIZE:
optionValue = m_minWindowSize;
return OPTION_FOUND;
case MAX_WINDOW_SIZE:
optionValue = m_maxWindowSize;
return OPTION_FOUND;
case MAX_EXCLUDED_DIGESTS:
optionValue = m_nMaxExcludedDigests;
return OPTION_FOUND;
case CURRENT_WINDOW_SIZE:
optionValue = m_currentWindowSize;
return OPTION_FOUND;
case RCV_BUF_SIZE:
optionValue = m_receiveBufferSize;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBufferSize;
return OPTION_FOUND;
case INTEREST_RETX:
optionValue = m_nMaxRetransmissions;
return OPTION_FOUND;
case INTEREST_LIFETIME:
optionValue = m_interestLifetimeMillisec;
return OPTION_FOUND;
case MIN_SUFFIX_COMP_S:
optionValue = m_minSuffixComponents;
return OPTION_FOUND;
case MAX_SUFFIX_COMP_S:
optionValue = m_maxSuffixComponents;
return OPTION_FOUND;
case RIGHTMOST_CHILD_S:
optionValue = m_childSelector;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, size_t& optionValue)
{
switch (optionName)
{
case RCV_BUF_SIZE:
optionValue = m_receiveBufferSize;
return OPTION_FOUND;
case SND_BUF_SIZE:
optionValue = m_sendBufferSize;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, bool& optionValue)
{
switch (optionName)
{
case MUST_BE_FRESH_S:
optionValue = m_mustBeFresh;
return OPTION_FOUND;
case ASYNC_MODE:
optionValue = m_isAsync;
return OPTION_FOUND;
case RUNNING:
optionValue = m_isRunning;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, Name& optionValue)
{
switch (optionName)
{
case PREFIX:
optionValue = m_prefix;
return OPTION_FOUND;
case SUFFIX:
optionValue = m_suffix;
return OPTION_FOUND;
case FORWARDING_STRATEGY:
optionValue = m_forwardingStrategy;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerDataCallback& optionValue)
{
switch (optionName)
{
case DATA_ENTER_CNTX:
optionValue = m_onDataEnteredContext;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ProducerDataCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Consumer::getContextOption(int optionName, ConsumerDataVerificationCallback& optionValue)
{
switch (optionName)
{
case DATA_TO_VERIFY:
optionValue = m_onDataToVerify;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerInterestCallback& optionValue)
{
switch (optionName)
{
case INTEREST_RETRANSMIT:
optionValue = m_onInterestRetransmitted;
return OPTION_FOUND;
case INTEREST_LEAVE_CNTX:
optionValue = m_onInterestToLeaveContext;
return OPTION_FOUND;
case INTEREST_EXPIRED:
optionValue = m_onInterestExpired;
return OPTION_FOUND;
case INTEREST_SATISFIED:
optionValue = m_onInterestSatisfied;
return OPTION_FOUND;
default:
return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ProducerInterestCallback& optionValue)
{
return OPTION_NOT_FOUND;
}
int
Consumer::getContextOption(int optionName, ConsumerContentCallback& optionValue)
{
switch (optionName)
{
case CONTENT_RETRIEVED:
optionValue = m_onPayloadReassembled;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerNackCallback& optionValue)
{
switch (optionName)
{
case NACK_ENTER_CNTX:
optionValue = m_onNack;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, ConsumerManifestCallback& optionValue)
{
switch (optionName)
{
case MANIFEST_ENTER_CNTX:
optionValue = m_onManifest;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, KeyLocator& optionValue)
{
switch (optionName)
{
case KEYLOCATOR_S:
optionValue = m_publisherKeyLocator;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, Exclude& optionValue)
{
switch (optionName)
{
case EXCLUDE_S:
optionValue = m_exclude;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, shared_ptr<Face>& optionValue)
{
switch (optionName)
{
case FACE:
optionValue = m_face;
return OPTION_FOUND;
default: return OPTION_NOT_FOUND;
}
}
int
Consumer::getContextOption(int optionName, TreeNode& optionValue)
{
return OPTION_NOT_FOUND;
}
void
Consumer::onStrategyChangeSuccess(const nfd::ControlParameters& commandSuccessResult,
const std::string& message)
{
//std::cout << message << ": " << commandSuccessResult << std::endl;
}
void
Consumer::onStrategyChangeError(uint32_t code, const std::string& error, const std::string& message)
{
/*std::ostringstream os;
os << message << ": " << error << " (code: " << code << ")";
throw Error(os.str());*/
}
void
Consumer::consumeAll()
{
shared_ptr<Face> face = FaceHelper::getFace();
face->processEvents();
}
} //namespace ndn
| 18,660 | 21.840881 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef NFD_TABLE_CS_HPP
#define NFD_TABLE_CS_HPP
#include "common.hpp"
#include "cs-entry.hpp"
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/thread/mutex.hpp>
#include <queue>
namespace ndn {
typedef std::list<cs::Entry*> SkipListLayer;
typedef std::list<SkipListLayer*> SkipList;
class StalenessComparator
{
public:
bool
operator()(const cs::Entry* entry1, const cs::Entry* entry2) const
{
return entry1->getStaleTime() < entry2->getStaleTime();
}
};
class UnsolicitedComparator
{
public:
bool
operator()(const cs::Entry* entry1, const cs::Entry* entry2) const
{
return entry1->isUnsolicited();
}
};
// tags
class unsolicited;
class byStaleness;
class byArrival;
typedef boost::multi_index_container<
cs::Entry*,
boost::multi_index::indexed_by<
// by arrival (FIFO)
boost::multi_index::sequenced<
boost::multi_index::tag<byArrival>
>
>
> CleanupIndex;
/** \brief represents Content Store
*/
class Cs : noncopyable
{
public:
explicit
Cs(int nMaxPackets = 65536); // ~500MB with average packet size = 8KB
~Cs();
/** \brief inserts a Data packet
* This method does not consider the payload of the Data packet.
*
* Packets are considered duplicate if the name matches.
* The new Data packet with the identical name, but a different payload
* is not placed in the Content Store
* \return{ whether the Data is added }
*/
bool
insert(const Data& data, bool isUnsolicited = false);
/** \brief finds the best match Data for an Interest
* \return{ the best match, if any; otherwise 0 }
*/
const Data*
find(const Interest& interest);
/** \brief deletes CS entry by the exact name
*/
void
erase(const Name& exactName);
/** \brief sets maximum allowed size of Content Store (in packets)
*/
void
setLimit(size_t nMaxPackets);
/** \brief returns maximum allowed size of Content Store (in packets)
* \return{ number of packets that can be stored in Content Store }
*/
size_t
getLimit() const;
/** \brief returns current size of Content Store measured in packets
* \return{ number of packets located in Content Store }
*/
size_t
size() const;
protected:
/** \brief removes one Data packet from Content Store based on replacement policy
* \return{ whether the Data was removed }
*/
bool
evictItem();
private:
/** \brief returns True if the Content Store is at its maximum capacity
* \return{ True if Content Store is full; otherwise False}
*/
bool
isFull() const;
/** \brief Computes the layer where new Content Store Entry is placed
*
* Reference: "Skip Lists: A Probabilistic Alternative to Balanced Trees" by W.Pugh
* \return{ returns random layer (number) in a skip list}
*/
size_t
pickRandomLayer() const;
/** \brief Inserts a new Content Store Entry in a skip list
* \return{ returns a pair containing a pointer to the CS Entry,
* and a flag indicating if the entry was newly created (True) or refreshed (False) }
*/
std::pair<cs::Entry*, bool>
insertToSkipList(const Data& data, bool isUnsolicited = false);
/** \brief Removes a specific CS Entry from all layers of a skip list
* \return{ returns True if CS Entry was succesfully removed and False if CS Entry was not found}
*/
bool
eraseFromSkipList(cs::Entry* entry);
/** \brief Implements child selector (leftmost, rightmost, undeclared).
* Operates on the first layer of a skip list.
*
* startingPoint must be less than Interest Name.
* startingPoint can be equal to Interest Name only when the item is in the begin() position.
*
* Iterates toward greater Names, terminates when CS entry falls out of Interest prefix.
* When childSelector = leftmost, returns first CS entry that satisfies other selectors.
* When childSelector = rightmost, it goes till the end, and returns CS entry that satisfies
* other selectors. Returned CS entry is the leftmost child of the rightmost child.
* \return{ the best match, if any; otherwise 0 }
*/
const Data*
selectChild(const Interest& interest, SkipListLayer::iterator startingPoint) const;
/** \brief checks if Content Store entry satisfies Interest selectors (MinSuffixComponents,
* MaxSuffixComponents, Implicit Digest, MustBeFresh)
* \return{ true if satisfies all selectors; false otherwise }
*/
bool
doesComplyWithSelectors(const Interest& interest,
cs::Entry* entry,
bool doesInterestContainDigest) const;
/** \brief interprets minSuffixComponent and name lengths to understand if Interest contains
* implicit digest of the data
* \return{ True if Interest name contains digest; False otherwise }
*/
bool
recognizeInterestWithDigest(const Interest& interest, cs::Entry* entry) const;
/** \brief Prints contents of the skip list, starting from the top layer
*/
void
printSkipList() const;
private:
SkipList m_skipList;
CleanupIndex m_cleanupIndex;
size_t m_nMaxPackets; // user defined maximum size of the Content Store in packets
size_t m_nPackets; // current number of packets in Content Store
std::queue<cs::Entry*> m_freeCsEntries; // memory pool
boost::mutex m_mutex;
};
} // namespace nfd
#endif // NFD_TABLE_CS_HPP
| 6,579 | 30.333333 | 100 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-data-retrieval.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef INFOMAX_DATA_RETRIEVAL_HPP
#define INFOMAX_DATA_RETRIEVAL_HPP
#include "reliable-data-retrieval.hpp"
namespace ndn {
class InfoMaxDataRetrieval : public DataRetrievalProtocol
{
public:
InfoMaxDataRetrieval(Context* context);
~InfoMaxDataRetrieval();
void
start();
void
stop();
private:
void
processInfoMaxPayload(Consumer&, const uint8_t*, size_t);
void
processInfoMaxData(Consumer&, const Data&);
void
processLeavingInfoMaxInterest(Consumer&, Interest&);
void
processInfoMaxInitPayload(Consumer&, const uint8_t*, size_t);
void
processInfoMaxInitData(Consumer&, const Data&);
void
processLeavingInfoMaxInitInterest(Consumer&, Interest&);
void
convertStringToList(std::string&);
private:
std::list< shared_ptr<Name> > m_infoMaxList;
shared_ptr<ReliableDataRetrieval> m_rdr;
uint64_t m_requestVersion;
uint64_t m_requestListNum;
uint64_t m_maxListNum;
bool m_isInit;
};
} // namespace ndn
#endif // INFOMAX_DATA_RETRIEVAL_HPP | 2,073 | 26.653333 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/face-helper.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef FACE_HELPER_HPP
#define FACE_HELPER_HPP
#include "common.hpp"
namespace ndn {
class FaceHelper
{
public:
static shared_ptr<Face> getFace();
private:
FaceHelper(){};
FaceHelper(const FaceHelper& helper){}; // copy constructor is private
FaceHelper& operator=(const FaceHelper& helper){return *this;}; // assignment operator is private
static shared_ptr<Face> m_face;
};
} // namespace ndn
#endif // FACE_HELPER_HPP
| 1,506 | 33.25 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/selector-helper.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef SELECTOR_HELPER_HPP
#define SELECTOR_HELPER_HPP
#include "common.hpp"
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
namespace ndn {
class SelectorHelper
{
public:
static void
applySelectors(Interest& interest, Context* m_context);
};
} //namespace ndn
#endif // SELECTOR_HELPER_HPP
| 1,416 | 31.204545 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/reliable-data-retrieval.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "reliable-data-retrieval.hpp"
#include "consumer-context.hpp"
namespace ndn {
ReliableDataRetrieval::ReliableDataRetrieval(Context* context)
: DataRetrievalProtocol(context)
, m_isFinalBlockNumberDiscovered(false)
, m_finalBlockNumber(std::numeric_limits<uint64_t>::max())
, m_lastReassembledSegment(0)
, m_contentBufferSize(0)
, m_currentWindowSize(0)
, m_interestsInFlight(0)
, m_segNumber(0)
{
context->getContextOption(FACE, m_face);
m_scheduler = new Scheduler(m_face->getIoService());
}
ReliableDataRetrieval::~ReliableDataRetrieval()
{
stop();
delete m_scheduler;
}
void
ReliableDataRetrieval::start()
{
m_isRunning = true;
m_isFinalBlockNumberDiscovered = false;
m_finalBlockNumber = std::numeric_limits<uint64_t>::max();
m_segNumber = 0;
m_interestsInFlight = 0;
m_lastReassembledSegment = 0;
m_contentBufferSize = 0;
m_contentBuffer.clear();
m_interestRetransmissions.clear();
m_receiveBuffer.clear();
m_unverifiedSegments.clear();
m_verifiedManifests.clear();
// this is to support window size "inheritance" between consume calls
/*int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > 0)
{
m_currentWindowSize = currentWindowSize;
}
else*/
/*{
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
m_currentWindowSize = minWindowSize;
}*/
// initial burst of Interest packets
/*while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}*/
//send exactly 1 Interest to get the FinalBlockId
sendInterest();
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
bool isContextRunning = false;
m_context->getContextOption(RUNNING, isContextRunning);
if (!isAsync && !isContextRunning)
{
m_context->setContextOption(RUNNING, true);
m_face->processEvents();
}
}
void
ReliableDataRetrieval::sendInterest()
{
Name prefix;
m_context->getContextOption(PREFIX, prefix);
Name suffix;
m_context->getContextOption(SUFFIX, suffix);
if (!suffix.empty())
{
prefix.append(suffix);
}
prefix.appendSegment(m_segNumber);
Interest interest(prefix);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interest, m_context);
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interest);
}
// because user could stop the context in one of the prev callbacks
//if (m_isRunning == false)
// return;
m_interestsInFlight++;
m_interestRetransmissions[m_segNumber] = 0;
m_interestTimepoints[m_segNumber] = time::steady_clock::now();
m_expressedInterests[m_segNumber] = m_face->expressInterest(interest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
m_segNumber++;
}
void
ReliableDataRetrieval::stop()
{
m_isRunning = false;
removeAllPendingInterests();
removeAllScheduledInterests();
}
void
ReliableDataRetrieval::onData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
uint64_t segment = interest.getName().get(-1).toSegment();
m_expressedInterests.erase(segment);
m_scheduledInterests.erase(segment);
if (m_interestTimepoints.find(segment) != m_interestTimepoints.end())
{
time::steady_clock::duration duration = time::steady_clock::now() - m_interestTimepoints[segment];
m_rttEstimator.addMeasurement(boost::chrono::duration_cast<boost::chrono::microseconds>(duration));
RttEstimator::Duration rto = m_rttEstimator.computeRto();
boost::chrono::milliseconds lifetime = boost::chrono::duration_cast<boost::chrono::milliseconds>(rto);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
// update lifetime only if user didn't specify prefered value
if (interestLifetime == DEFAULT_INTEREST_LIFETIME)
{
m_context->setContextOption(INTEREST_LIFETIME, (int)lifetime.count());
}
}
ConsumerDataCallback onDataEnteredContext = EMPTY_CALLBACK;
m_context->getContextOption(DATA_ENTER_CNTX, onDataEnteredContext);
if (onDataEnteredContext != EMPTY_CALLBACK)
{
onDataEnteredContext(*dynamic_cast<Consumer*>(m_context), data);
}
ConsumerInterestCallback onInterestSatisfied = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_SATISFIED, onInterestSatisfied);
if (onInterestSatisfied != EMPTY_CALLBACK)
{
onInterestSatisfied(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
if (data.getContentType() == MANIFEST_DATA_TYPE)
{
onManifestData(interest, data);
}
else if (data.getContentType() == NACK_DATA_TYPE)
{
onNackData(interest, data);
}
else if (data.getContentType() == CONTENT_DATA_TYPE)
{
onContentData(interest, data);
}
if (segment == 0) // if it was the first Interest
{
// in a next round try to transmit all Interests, except the first one
m_currentWindowSize = m_finalBlockNumber;
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
// if there are too many Interests to send, put an upper boundary on it.
if (m_currentWindowSize > maxWindowSize)
{
m_currentWindowSize = maxWindowSize;
}
//int rtt = -1;
//m_context->getContextOption(INTEREST_LIFETIME, rtt);
//paceInterests(m_currentWindowSize, time::milliseconds(10));
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
else
{
if (m_isRunning)
{
while (m_interestsInFlight < m_currentWindowSize)
{
if (m_isFinalBlockNumberDiscovered)
{
if (m_segNumber <= m_finalBlockNumber)
{
sendInterest();
}
else
{
break;
}
}
else
{
sendInterest();
}
}
}
}
}
void
ReliableDataRetrieval::paceInterests(int nInterests, time::milliseconds timeWindow)
{
if (nInterests <= 0)
return;
time::nanoseconds interval = time::nanoseconds(1000000*timeWindow) / nInterests;
for (int i = 1; i <= nInterests; i++)
{
// schedule next Interest
m_scheduledInterests[m_segNumber + i] = m_scheduler->scheduleEvent(i*interval,
bind(&ReliableDataRetrieval::sendInterest, this));
}
}
void
ReliableDataRetrieval::onManifestData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
//std::cout << "OnManifest" << std::endl;
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (!claimedDigest.equals(actualDigest))
{
isDataSecure = false;
}
}
else
{
isDataSecure = true;
}
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize) // don't expand window above max level
{
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
shared_ptr<Manifest> manifest = make_shared<Manifest>(data);
//std::cout << "MANIFEST CONTAINS " << manifest->size() << " names" << std::endl;
m_verifiedManifests.insert(std::pair<uint64_t, shared_ptr<Manifest> >(
data.getName().get(-1).toSegment(),
manifest));
m_receiveBuffer[manifest->getName().get(-1).toSegment()] = manifest;
// TODO: names in manifest are in order, so we can exit the loop earlier
for(std::map<uint64_t, shared_ptr<Data> >::iterator it = m_unverifiedSegments.begin();
it != m_unverifiedSegments.end(); ++it)
{
if (!m_isRunning)
{
return;
}
// data segment is verified with manifest
if (verifySegmentWithManifest(*manifest, *(it->second)))
{
if (!it->second->getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = it->second->getFinalBlockId().toSegment();
}
m_receiveBuffer[it->second->getName().get(-1).toSegment()] = it->second;
reassemble();
}
else // data segment failed verification with manifest
{
// retransmit interest with implicit digest from the manifest
retransmitInterestWithDigest(interest, data, *manifest);
}
}
}
else // failed to verify manifest
{
retransmitInterestWithExclude(interest,data);
}
}
void
ReliableDataRetrieval::retransmitFreshInterest(const ndn::Interest& interest)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
if (m_isRunning)
{
Interest retxInterest(interest.getName()); // because we need new nonce
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
retxInterest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(retxInterest, m_context);
retxInterest.setMustBeFresh(true); // to bypass cache
// this is to inherit the exclusions from the nacked interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
}
else
{
m_isRunning = false;
}
}
bool
ReliableDataRetrieval::retransmitInterestWithExclude( const ndn::Interest& interest,
Data& dataSegment)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
m_unverifiedSegments.erase(segment); // remove segment, because it is useless
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
Interest interestWithExlusion(interest.getName());
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interestWithExlusion.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interestWithExlusion, m_context);
int nMaxExcludedDigests = 0;
m_context->getContextOption(MAX_EXCLUDED_DIGESTS, nMaxExcludedDigests);
if (interest.getExclude().size() < nMaxExcludedDigests)
{
const Block& block = dataSegment.wireEncode();
ndn::ConstBufferPtr implicitDigestBuffer = ndn::crypto::sha256(block.wire(), block.size());
name::Component implicitDigest = name::Component::fromImplicitSha256Digest(implicitDigestBuffer);
Exclude exclusion = interest.getExclude();
exclusion.appendExclude(implicitDigest, false);
interestWithExlusion.setExclude(exclusion);
}
else
{
m_isRunning = false;
return false;
}
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), interestWithExlusion);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interestWithExlusion);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return false;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(interestWithExlusion,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
return false;
}
return true;
}
bool
ReliableDataRetrieval::retransmitInterestWithDigest(const ndn::Interest& interest,
const Data& dataSegment,
Manifest& manifestSegment)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
uint64_t segment = interest.getName().get(-1).toSegment();
m_unverifiedSegments.erase(segment); // remove segment, because it is useless
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
name::Component implicitDigest = getDigestFromManifest(manifestSegment, dataSegment);
if (implicitDigest.empty())
{
m_isRunning = false;
return false;
}
Name nameWithDigest(interest.getName());
nameWithDigest.append(implicitDigest);
Interest interestWithDigest(nameWithDigest);
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
interestWithDigest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(interestWithDigest, m_context);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), interestWithDigest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), interestWithDigest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return false;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(interestWithDigest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
return false;
}
return true;
}
void
ReliableDataRetrieval::onNackData(const ndn::Interest& interest, ndn::Data& data)
{
if (m_isRunning == false)
return;
if (m_isFinalBlockNumberDiscovered)
{
if (data.getName().get(-3).toSegment() > m_finalBlockNumber)
{
return;
}
}
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (claimedDigest.equals(actualDigest))
{
isDataSecure = true;
}
else
{
isDataSecure = false;
}
}
else
{
isDataSecure = true;
}
}
else
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize) // don't shrink window below minimum level
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
shared_ptr<ApplicationNack> nack = make_shared<ApplicationNack>(data);
ConsumerNackCallback onNack = EMPTY_CALLBACK;
m_context->getContextOption(NACK_ENTER_CNTX, onNack);
if (onNack != EMPTY_CALLBACK)
{
onNack(*dynamic_cast<Consumer*>(m_context), *nack);
}
switch (nack->getCode())
{
case ApplicationNack::DATA_NOT_AVAILABLE:
{
m_isRunning = false;
break;
}
case ApplicationNack::NONE:
{
// TODO: reduce window size ?
break;
}
case ApplicationNack::PRODUCER_DELAY:
{
uint64_t segment = interest.getName().get(-1).toSegment();
m_scheduledInterests[segment] = m_scheduler->scheduleEvent(time::milliseconds(nack->getDelay()),
bind(&ReliableDataRetrieval::retransmitFreshInterest, this, interest));
break;
}
default: break;
}
}
else // if NACK is not verified
{
retransmitInterestWithExclude(interest, data);
}
}
void
ReliableDataRetrieval::onContentData(const ndn::Interest& interest, ndn::Data& data)
{
ConsumerDataVerificationCallback onDataToVerify = EMPTY_CALLBACK;
m_context->getContextOption(DATA_TO_VERIFY, onDataToVerify);
bool isDataSecure = false;
if (onDataToVerify == EMPTY_CALLBACK)
{
// perform integrity check if possible
if (data.getSignature().getType() == tlv::DigestSha256)
{
ndn::name::Component claimedDigest( data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
// recalculate digest
m_keyChain.signWithSha256(data);
ndn::name::Component actualDigest(data.getSignature().getValue().value(),
data.getSignature().getValue().value_size());
if (claimedDigest.equals(actualDigest))
{
isDataSecure = true;
}
else
{
isDataSecure = false;
retransmitInterestWithExclude(interest, data);
}
}
else
{
isDataSecure = true;
}
}
else
{
if (!data.getSignature().hasKeyLocator())
{
retransmitInterestWithExclude(interest, data);
return;
}
// if data segment points to inlined manifest
if (referencesManifest(data))
{
Name referencedManifestName = data.getSignature().getKeyLocator().getName();
uint64_t manifestSegmentNumber = referencedManifestName.get(-1).toSegment();
if (m_verifiedManifests.find(manifestSegmentNumber) == m_verifiedManifests.end())
{
// save segment for some time, because manifest can be out of order
//std::cout << "SAVING SEGMENT for MANIFEST" << std::endl;
m_unverifiedSegments.insert(
std::pair<uint64_t, shared_ptr<Data> >( data.getName().get(-1).toSegment(),
data.shared_from_this()));
}
else
{
//std::cout << "NEAREST M " << m_verifiedManifests[manifestSegmentNumber]->getName() << std::endl;
isDataSecure = verifySegmentWithManifest(*(m_verifiedManifests[manifestSegmentNumber]), data);
if (!isDataSecure)
{
//std::cout << "Retx Digest" << std::endl;
retransmitInterestWithDigest( interest, data,
*m_verifiedManifests.find(manifestSegmentNumber)->second);
}
}
}
else // data segment points to the key
{
if (onDataToVerify(*dynamic_cast<Consumer*>(m_context), data) == true) // runs verification routine
{
isDataSecure = true;
}
else
{
retransmitInterestWithExclude(interest, data);
}
}
}
if (isDataSecure)
{
checkFastRetransmissionConditions(interest);
int maxWindowSize = -1;
m_context->getContextOption(MAX_WINDOW_SIZE, maxWindowSize);
if (m_currentWindowSize < maxWindowSize) // don't expand window above max level
{
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
if (!data.getFinalBlockId().empty())
{
m_isFinalBlockNumberDiscovered = true;
m_finalBlockNumber = data.getFinalBlockId().toSegment();
}
m_receiveBuffer[data.getName().get(-1).toSegment()] = data.shared_from_this();
reassemble();
}
}
bool
ReliableDataRetrieval::referencesManifest(ndn::Data& data)
{
Name keyLocatorPrefix = data.getSignature().getKeyLocator().getName().getPrefix(-1);
Name dataPrefix = data.getName().getPrefix(-1);
if (keyLocatorPrefix.equals(dataPrefix))
{
return true;
}
return false;
}
void
ReliableDataRetrieval::onTimeout(const ndn::Interest& interest)
{
if (m_isRunning == false)
return;
m_interestsInFlight--;
ConsumerInterestCallback onInterestExpired = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_EXPIRED, onInterestExpired);
if (onInterestExpired != EMPTY_CALLBACK)
{
onInterestExpired(*dynamic_cast<Consumer*>(m_context), const_cast<Interest&>(interest));
}
uint64_t segment = interest.getName().get(-1).toSegment();
m_expressedInterests.erase(segment);
m_scheduledInterests.erase(segment);
if (m_isFinalBlockNumberDiscovered)
{
if (interest.getName().get(-1).toSegment() > m_finalBlockNumber)
return;
}
int minWindowSize = -1;
m_context->getContextOption(MIN_WINDOW_SIZE, minWindowSize);
if (m_currentWindowSize > minWindowSize) // don't shrink window below minimum level
{
m_currentWindowSize = m_currentWindowSize / 2; // cut in half
if (m_currentWindowSize == 0)
m_currentWindowSize++;
m_context->setContextOption(CURRENT_WINDOW_SIZE, m_currentWindowSize);
}
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
if(m_interestRetransmissions[segment] < maxRetransmissions)
{
Interest retxInterest(interest.getName()); // because we need new nonce
int interestLifetime = DEFAULT_INTEREST_LIFETIME;
m_context->getContextOption(INTEREST_LIFETIME, interestLifetime);
retxInterest.setInterestLifetime(time::milliseconds(interestLifetime));
SelectorHelper::applySelectors(retxInterest, m_context);
// this is to inherit the exclusions from the timed out interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segment]++;
m_expressedInterests[segment] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
else
{
m_isRunning = false;
reassemble(); // to pass up all content we have so far
}
}
void
ReliableDataRetrieval::copyContent(Data& data)
{
const Block content = data.getContent();
m_contentBuffer.insert(m_contentBuffer.end(), &content.value()[0], &content.value()[content.value_size()]);
if ((data.getName().get(-1).toSegment() == m_finalBlockNumber) || (!m_isRunning))
{
removeAllPendingInterests();
removeAllScheduledInterests();
// return content to the user
ConsumerContentCallback onPayload = EMPTY_CALLBACK;
m_context->getContextOption(CONTENT_RETRIEVED, onPayload);
if (onPayload != EMPTY_CALLBACK)
{
onPayload(*dynamic_cast<Consumer*>(m_context), m_contentBuffer.data(), m_contentBuffer.size());
}
//reduce window size to prevent its speculative growth in case when consume() is called in loop
int currentWindowSize = -1;
m_context->getContextOption(CURRENT_WINDOW_SIZE, currentWindowSize);
if (currentWindowSize > m_finalBlockNumber)
{
m_context->setContextOption(CURRENT_WINDOW_SIZE, (int)(m_finalBlockNumber));
}
m_isRunning = false;
}
}
void
ReliableDataRetrieval::reassemble()
{
std::map<uint64_t, shared_ptr<Data> >::iterator head = m_receiveBuffer.find(m_lastReassembledSegment);
while (head != m_receiveBuffer.end())
{
// do not copy from manifests
if (head->second->getContentType() == CONTENT_DATA_TYPE)
{
copyContent(*(head->second));
}
m_receiveBuffer.erase(head);
m_lastReassembledSegment++;
head = m_receiveBuffer.find(m_lastReassembledSegment);
}
}
bool
ReliableDataRetrieval::verifySegmentWithManifest(Manifest& manifestSegment, Data& dataSegment)
{
//std::cout << "Verify Segment With MAnifest" << std::endl;
bool result = false;
for (std::list<Name>::const_iterator it = manifestSegment.catalogueBegin();
it != manifestSegment.catalogueEnd(); ++it)
{
if (it->get(-2) == dataSegment.getName().get(-1)) // if segment numbers match
{
//re-calculate implicit digest
const Block& block = dataSegment.wireEncode();
ndn::ConstBufferPtr implicitDigest = ndn::crypto::sha256(block.wire(), block.size());
// convert to name component for easier comparison
name::Component digestComp = name::Component::fromImplicitSha256Digest(implicitDigest);
if (digestComp.equals(it->get(-1)))
{
result = true;
break;
}
else
{
break;
}
}
}
//if (!result)
// std::cout << "Segment failed verification by manifest" << result<< std::endl;
return result;
}
name::Component
ReliableDataRetrieval::getDigestFromManifest(Manifest& manifestSegment, const Data& dataSegment)
{
name::Component result;
for (std::list<Name>::const_iterator it = manifestSegment.catalogueBegin();
it != manifestSegment.catalogueEnd(); ++it)
{
if (it->get(-2) == dataSegment.getName().get(-1)) // if segment numbers match
{
result = it->get(-1);
return result;
}
}
return result;
}
void
ReliableDataRetrieval::checkFastRetransmissionConditions(const ndn::Interest& interest)
{
uint64_t segNumber = interest.getName().get(-1).toSegment();
m_receivedSegments[segNumber] = true;
m_fastRetxSegments.erase(segNumber);
uint64_t possiblyLostSegment = 0;
uint64_t highestReceivedSegment = m_receivedSegments.rbegin()->first;
for (uint64_t i = 0; i <= highestReceivedSegment; i++)
{
if (m_receivedSegments.find(i) == m_receivedSegments.end()) // segment is not received yet
{
// segment has not been fast retransmitted yet
if (m_fastRetxSegments.find(i) == m_fastRetxSegments.end())
{
possiblyLostSegment = i;
uint8_t nOutOfOrderSegments = 0;
for (uint64_t j = i; j <= highestReceivedSegment; j++)
{
if (m_receivedSegments.find(j) != m_receivedSegments.end())
{
nOutOfOrderSegments++;
if (nOutOfOrderSegments == DEFAULT_FAST_RETX_CONDITION)
{
m_fastRetxSegments[possiblyLostSegment] = true;
fastRetransmit(interest, possiblyLostSegment);
}
}
}
}
}
}
}
void
ReliableDataRetrieval::fastRetransmit(const ndn::Interest& interest, uint64_t segNumber)
{
int maxRetransmissions;
m_context->getContextOption(INTEREST_RETX, maxRetransmissions);
if (m_interestRetransmissions[segNumber] < maxRetransmissions)
{
Name name = interest.getName().getPrefix(-1);
name.appendSegment(segNumber);
Interest retxInterest(name);
SelectorHelper::applySelectors(retxInterest, m_context);
// this is to inherit the exclusions from the lost interest
Exclude exclusion = retxInterest.getExclude();
for(Exclude::exclude_type::const_iterator it = interest.getExclude().begin();
it != interest.getExclude().end(); ++it)
{
exclusion.appendExclude(it->first, false);
}
retxInterest.setExclude(exclusion);
ConsumerInterestCallback onInterestRetransmitted = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_RETRANSMIT, onInterestRetransmitted);
if (onInterestRetransmitted != EMPTY_CALLBACK)
{
onInterestRetransmitted(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
ConsumerInterestCallback onInterestToLeaveContext = EMPTY_CALLBACK;
m_context->getContextOption(INTEREST_LEAVE_CNTX, onInterestToLeaveContext);
if (onInterestToLeaveContext != EMPTY_CALLBACK)
{
onInterestToLeaveContext(*dynamic_cast<Consumer*>(m_context), retxInterest);
}
// because user could stop the context in one of the prev callbacks
if (m_isRunning == false)
return;
//retransmit
m_interestsInFlight++;
m_interestRetransmissions[segNumber]++;
//std::cout << "fast retx" << std::endl;
m_expressedInterests[segNumber] = m_face->expressInterest(retxInterest,
bind(&ReliableDataRetrieval::onData, this, _1, _2),
bind(&ReliableDataRetrieval::onTimeout, this, _1));
}
}
void
ReliableDataRetrieval::removeAllPendingInterests()
{
bool isAsync = false;
m_context->getContextOption(ASYNC_MODE, isAsync);
if (!isAsync)
{
// This won't work ---> m_face->getIoService().stop();
m_face->removeAllPendingInterests(); // faster, but destroys everything
}
else // slower, but destroys only necessary Interests
{
for(std::unordered_map<uint64_t, const PendingInterestId*>::iterator it = m_expressedInterests.begin();
it != m_expressedInterests.end(); ++it)
{
m_face->removePendingInterest(it->second);
}
}
m_expressedInterests.clear();
}
void
ReliableDataRetrieval::removeAllScheduledInterests()
{
for(std::unordered_map<uint64_t, EventId>::iterator it = m_scheduledInterests.begin();
it != m_scheduledInterests.end(); ++it)
{
m_scheduler->cancelEvent(it->second);
}
m_scheduledInterests.clear();
}
} //namespace ndn
| 36,331 | 30.429066 | 109 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/application-nack.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef APPLICATION_NACK_HPP
#define APPLICATION_NACK_HPP
#include "common.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include "tlv.hpp"
#include <ndn-cxx/util/random.hpp>
namespace ndn {
// NACK Headers
#define STATUS_CODE_H "Status-code"
#define RETRY_AFTER_H "Retry-after"
class ApplicationNack : public Data
{
public:
class Error : public std::runtime_error
{
public:
explicit
Error(const std::string& what)
: std::runtime_error(what)
{
}
};
enum NackCode {
NONE = 0,
PRODUCER_DELAY = 1,
DATA_NOT_AVAILABLE = 2,
INTEREST_NOT_VERIFIED = 3
};
/**
* Default constructor.
*/
ApplicationNack();
/**
* Constructs ApplicationNack from a given Interest packet
*/
ApplicationNack(const Interest& interest, ApplicationNack::NackCode statusCode);
/**
* Constructor performing upcasting from Data to ApplicationNack
*/
ApplicationNack(const Data& data);
~ApplicationNack();
void
addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize);
void
addKeyValuePair(std::string key, std::string value);
std::string
getValueByKey(std::string key);
void
eraseValueByKey(std::string key);
void
setCode(ApplicationNack::NackCode statusCode);
ApplicationNack::NackCode
getCode();
void
setDelay(uint32_t milliseconds);
uint32_t
getDelay();
void
encode();
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
void
decode();
private:
std::map<std::string, std::string> m_keyValuePairs;
};
} //namespace ndn
#endif // APPLICATION_NACK_HPP
| 2,711 | 22.582609 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/manifest.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "manifest.hpp"
namespace ndn {
Manifest::Manifest()
{
setContentType(tlv::ContentType_Manifest);
}
Manifest::Manifest(const Name& name)
: Data(name)
{
setContentType(tlv::ContentType_Manifest);
}
Manifest::Manifest(const Data& data)
: Data(data)
{
setContentType(tlv::ContentType_Manifest);
decode();
}
Manifest::~Manifest()
{
}
void
Manifest::addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize)
{
std::string keyS(reinterpret_cast<const char*>(key), keySize);
std::string valueS(reinterpret_cast<const char*>(value), valueSize);
addKeyValuePair(keyS, valueS);
}
void
Manifest::addKeyValuePair(std::string key, std::string value)
{
m_keyValuePairs[key] = value;
}
std::string
Manifest::getValueByKey(std::string key)
{
std::map<std::string,std::string>::const_iterator it = m_keyValuePairs.find(key);
if (it == m_keyValuePairs.end())
{
return "";
}
else
{
return it->second;
}
}
void
Manifest::eraseValueByKey(std::string key)
{
m_keyValuePairs.erase(m_keyValuePairs.find(key));
}
void
Manifest::addNameToCatalogue(const Name& name)
{
m_catalogueNames.push_back(name);
}
void
Manifest::addNameToCatalogue(const Name& name, const Block& digest)
{
Name fullName(name);
fullName.append(ndn::name::Component::fromImplicitSha256Digest(digest.value(), digest.value_size()));
m_catalogueNames.push_back(fullName);
}
void
Manifest::addNameToCatalogue(const Name& name, const ndn::ConstBufferPtr& digest)
{
Name fullName(name);
fullName.append(ndn::name::Component::fromImplicitSha256Digest(digest));
m_catalogueNames.push_back(fullName);
}
template<bool T>
size_t
Manifest::wireEncode(EncodingImpl<T>& blk) const
{
// Manifest ::= CONTENT-TLV TLV-LENGTH
// Catalogue?
// Name*
// KeyValuePair*
size_t totalLength = 0;
size_t catalogueLength = 0;
for (std::map<std::string, std::string>::const_reverse_iterator it = m_keyValuePairs.rbegin();
it != m_keyValuePairs.rend(); ++it)
{
std::string keyValue = it->first + "=" + it->second;
totalLength += blk.prependByteArray(reinterpret_cast<const uint8_t*>(keyValue.c_str()), keyValue.size());
totalLength += blk.prependVarNumber(keyValue.size());
totalLength += blk.prependVarNumber(tlv::KeyValuePair);
}
for (std::list<Name>::const_reverse_iterator it = m_catalogueNames.rbegin();
it != m_catalogueNames.rend(); ++it)
{
size_t blockSize = prependBlock(blk, it->wireEncode());
totalLength += blockSize;
catalogueLength += blockSize;
}
if (catalogueLength > 0)
{
totalLength += blk.prependVarNumber(catalogueLength);
totalLength += blk.prependVarNumber(tlv::ManifestCatalogue);
}
//totalLength += blk.prependVarNumber(totalLength);
//totalLength += blk.prependVarNumber(tlv::Content);
return totalLength;
}
template size_t
Manifest::wireEncode<true>(EncodingImpl<true>& block) const;
template size_t
Manifest::wireEncode<false>(EncodingImpl<false>& block) const;
void
Manifest::encode()
{
EncodingEstimator estimator;
size_t estimatedSize = wireEncode(estimator);
EncodingBuffer buffer(estimatedSize, 0);
wireEncode(buffer);
setContentType(tlv::ContentType_Manifest);
setContent(const_cast<uint8_t*>(buffer.buf()), buffer.size());
}
void
Manifest::decode()
{
Block content = getContent();
content.parse();
// Manifest ::= CONTENT-TLV TLV-LENGTH
// Catalogue?
// Name*
// KeyValuePair*
for ( Block::element_const_iterator val = content.elements_begin();
val != content.elements_end(); ++val)
{
if (val->type() == tlv::ManifestCatalogue)
{
val->parse();
for ( Block::element_const_iterator catalogueNameElem = val->elements_begin();
catalogueNameElem != val->elements_end(); ++catalogueNameElem)
{
if (catalogueNameElem->type() == tlv::Name)
{
Name name(*catalogueNameElem);
m_catalogueNames.push_back(name);
}
}
}
else if (val->type() == tlv::KeyValuePair)
{
std::string str((char*)val->value(), val->value_size());
size_t index = str.find_first_of('=');
if (index == std::string::npos || index == 0 || (index == str.size() - 1))
continue;
std::string key = str.substr(0, index);
std::string value = str.substr(index + 1, str.size() - index - 1);
addKeyValuePair(key, value);
}
}
}
} // namespace ndn
| 5,728 | 26.81068 | 109 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/selector-helper.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "selector-helper.hpp"
namespace ndn {
void
SelectorHelper::applySelectors(Interest& interest, Context* context)
{
int minSuffix = -1;
context->getContextOption(MIN_SUFFIX_COMP_S, minSuffix);
if (minSuffix >= 0)
{
interest.setMinSuffixComponents(minSuffix);
}
int maxSuffix = -1;
context->getContextOption(MAX_SUFFIX_COMP_S, maxSuffix);
if (maxSuffix >= 0)
{
interest.setMaxSuffixComponents(maxSuffix);
}
Exclude exclusion;
context->getContextOption(EXCLUDE_S, exclusion);
if (!exclusion.empty())
{
interest.setExclude(exclusion);
}
bool mustBeFresh = false;
context->getContextOption(MUST_BE_FRESH_S, mustBeFresh);
if (mustBeFresh)
{
interest.setMustBeFresh(mustBeFresh);
}
int child = -10;
context->getContextOption(RIGHTMOST_CHILD_S, child);
if (child != -10)
{
interest.setChildSelector(child);
}
KeyLocator keyLocator;
context->getContextOption(KEYLOCATOR_S, keyLocator);
if (!keyLocator.empty())
{
interest.setPublisherPublicKeyLocator(keyLocator);
}
}
} //namespace ndn
| 2,174 | 26.1875 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "cs.hpp"
#include <ndn-cxx/util/crypto.hpp>
#include <ndn-cxx/security/signature-sha256-with-rsa.hpp>
#define SKIPLIST_MAX_LAYERS 32
#define SKIPLIST_PROBABILITY 25 // 25% (p = 1/4)
namespace ndn {
Cs::Cs(int nMaxPackets)
: m_nMaxPackets(nMaxPackets)
, m_nPackets(0)
{
SkipListLayer* zeroLayer = new SkipListLayer();
m_skipList.push_back(zeroLayer);
for (size_t i = 0; i < m_nMaxPackets; i++)
m_freeCsEntries.push(new cs::Entry());
}
Cs::~Cs()
{
// evict all items from CS
while (evictItem())
;
BOOST_ASSERT(m_freeCsEntries.size() == m_nMaxPackets);
while (!m_freeCsEntries.empty())
{
delete m_freeCsEntries.front();
m_freeCsEntries.pop();
}
}
size_t
Cs::size() const
{
return m_nPackets; // size of the first layer in a skip list
}
void
Cs::setLimit(size_t nMaxPackets)
{
size_t oldNMaxPackets = m_nMaxPackets;
m_nMaxPackets = nMaxPackets;
while (isFull())
{
if (!evictItem())
break;
}
if (m_nMaxPackets >= oldNMaxPackets)
{
for (size_t i = oldNMaxPackets; i < m_nMaxPackets; i++)
{
m_freeCsEntries.push(new cs::Entry());
}
}
else
{
for (size_t i = oldNMaxPackets; i > m_nMaxPackets; i--)
{
delete m_freeCsEntries.front();
m_freeCsEntries.pop();
}
}
}
size_t
Cs::getLimit() const
{
return m_nMaxPackets;
}
//Reference: "Skip Lists: A Probabilistic Alternative to Balanced Trees" by W.Pugh
std::pair<cs::Entry*, bool>
Cs::insertToSkipList(const Data& data, bool isUnsolicited)
{
BOOST_ASSERT(m_cleanupIndex.size() <= size());
BOOST_ASSERT(m_freeCsEntries.size() > 0);
m_mutex.lock();
// take entry for the memory pool
cs::Entry* entry = m_freeCsEntries.front();
m_freeCsEntries.pop();
m_nPackets++;
entry->setData(data, isUnsolicited);
bool insertInFront = false;
bool isIterated = false;
SkipList::reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator updateTable[SKIPLIST_MAX_LAYERS];
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
updateTable[layer] = head;
if (head != (*rit)->end())
{
// it can happen when begin() contains the element in front of which we need to insert
if (!isIterated && ((*head)->getName() >= entry->getName()))
{
--updateTable[layer];
insertInFront = true;
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < entry->getName())
{
head = it;
updateTable[layer] = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
layer--;
}
}
else
{
updateTable[0] = (*topLayer)->begin(); //initialization
}
head = updateTable[0];
++head; // look at the next slot to check if it contains a duplicate
bool isCsEmpty = (size() == 0);
bool isInBoundaries = (head != (*m_skipList.begin())->end());
bool isNameIdentical = false;
if (!isCsEmpty && isInBoundaries)
{
isNameIdentical = (*head)->getName() == entry->getName();
}
//check if this is a duplicate packet
if (isNameIdentical)
{
(*head)->setData(data, isUnsolicited, entry->getDigest()); //updates stale time
// new entry not needed, returning to the pool
entry->release();
m_freeCsEntries.push(entry);
m_nPackets--;
m_mutex.unlock();
return std::make_pair(*head, false);
}
size_t randomLayer = pickRandomLayer();
while (m_skipList.size() < randomLayer + 1)
{
SkipListLayer* newLayer = new SkipListLayer();
m_skipList.push_back(newLayer);
updateTable[(m_skipList.size() - 1)] = newLayer->begin();
}
size_t layer = 0;
for (SkipList::iterator i = m_skipList.begin();
i != m_skipList.end() && layer <= randomLayer; ++i)
{
if (updateTable[layer] == (*i)->end() && !insertInFront)
{
(*i)->push_back(entry);
SkipListLayer::iterator last = (*i)->end();
--last;
entry->setIterator(layer, last);
}
else if (updateTable[layer] == (*i)->end() && insertInFront)
{
(*i)->push_front(entry);
entry->setIterator(layer, (*i)->begin());
}
else
{
++updateTable[layer]; // insert after
SkipListLayer::iterator position = (*i)->insert(updateTable[layer], entry);
entry->setIterator(layer, position); // save iterator where item was inserted
}
layer++;
}
m_mutex.unlock();
return std::make_pair(entry, true);
}
bool
Cs::insert(const Data& data, bool isUnsolicited)
{
if (isFull())
{
evictItem();
}
//pointer and insertion status
std::pair<cs::Entry*, bool> entry = insertToSkipList(data, isUnsolicited);
//new entry
if (static_cast<bool>(entry.first) && (entry.second == true))
{
m_cleanupIndex.push_back(entry.first);
return true;
}
return false;
}
size_t
Cs::pickRandomLayer() const
{
int layer = -1;
int randomValue;
do
{
layer++;
randomValue = rand() % 100 + 1;
}
while ((randomValue < SKIPLIST_PROBABILITY) && (layer < SKIPLIST_MAX_LAYERS));
return static_cast<size_t>(layer);
}
bool
Cs::isFull() const
{
if (size() >= m_nMaxPackets) //size of the first layer vs. max size
return true;
return false;
}
bool
Cs::eraseFromSkipList(cs::Entry* entry)
{
m_mutex.lock();
bool isErased = false;
const std::map<int, std::list<cs::Entry*>::iterator>& iterators = entry->getIterators();
if (!iterators.empty())
{
int layer = 0;
for (SkipList::iterator it = m_skipList.begin(); it != m_skipList.end(); )
{
std::map<int, std::list<cs::Entry*>::iterator>::const_iterator i = iterators.find(layer);
if (i != iterators.end())
{
(*it)->erase(i->second);
entry->removeIterator(layer);
isErased = true;
//remove layers that do not contain any elements (starting from the second layer)
if ((layer != 0) && (*it)->empty())
{
delete *it;
it = m_skipList.erase(it);
}
else
++it;
layer++;
}
else
break;
}
}
//delete entry;
if (isErased)
{
entry->release();
m_freeCsEntries.push(entry);
m_nPackets--;
}
m_mutex.unlock();
return isErased;
}
bool
Cs::evictItem()
{
if (!m_cleanupIndex.get<byArrival>().empty())
{
eraseFromSkipList(*m_cleanupIndex.get<byArrival>().begin());
m_cleanupIndex.get<byArrival>().erase(m_cleanupIndex.get<byArrival>().begin());
return true;
}
return false;
}
const Data*
Cs::find(const Interest& interest)
{
m_mutex.lock();
bool isIterated = false;
SkipList::const_reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::const_reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
if (head != (*rit)->end())
{
// it happens when begin() contains the element we want to find
if (!isIterated && (interest.getName().isPrefixOf((*head)->getName())))
{
if (layer > 0)
{
layer--;
continue; // try lower layer
}
else
{
isIterated = true;
}
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < interest.getName())
{
head = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
{
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
}
else //if we reached the first layer
{
if (isIterated)
{
m_mutex.unlock();
return selectChild(interest, head);
}
}
layer--;
}
}
m_mutex.unlock();
return 0;
}
const Data*
Cs::selectChild(const Interest& interest, SkipListLayer::iterator startingPoint) const
{
BOOST_ASSERT(startingPoint != (*m_skipList.begin())->end());
if (startingPoint != (*m_skipList.begin())->begin())
{
BOOST_ASSERT((*startingPoint)->getName() < interest.getName());
}
bool hasLeftmostSelector = (interest.getChildSelector() <= 0);
bool hasRightmostSelector = !hasLeftmostSelector;
if (hasLeftmostSelector)
{
bool doesInterestContainDigest = recognizeInterestWithDigest(interest, *startingPoint);
bool isInPrefix = false;
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1).isPrefixOf((*startingPoint)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*startingPoint)->getName());
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *startingPoint, doesInterestContainDigest))
{
return &(*startingPoint)->getData();
}
}
}
//iterate to the right
SkipListLayer::iterator rightmost = startingPoint;
if (startingPoint != (*m_skipList.begin())->end())
{
SkipListLayer::iterator rightmostCandidate = startingPoint;
Name currentChildPrefix("");
while (true)
{
++rightmostCandidate;
bool isInBoundaries = (rightmostCandidate != (*m_skipList.begin())->end());
bool isInPrefix = false;
bool doesInterestContainDigest = false;
if (isInBoundaries)
{
doesInterestContainDigest = recognizeInterestWithDigest(interest,
*rightmostCandidate);
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1)
.isPrefixOf((*rightmostCandidate)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*rightmostCandidate)->getName());
}
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *rightmostCandidate, doesInterestContainDigest))
{
if (hasLeftmostSelector)
{
return &(*rightmostCandidate)->getData();
}
if (hasRightmostSelector)
{
if (doesInterestContainDigest)
{
// get prefix which is one component longer than Interest name
// (without digest)
const Name& childPrefix = (*rightmostCandidate)->getName()
.getPrefix(interest.getName().size());
if (currentChildPrefix.empty() || (childPrefix != currentChildPrefix))
{
currentChildPrefix = childPrefix;
rightmost = rightmostCandidate;
}
}
else
{
// get prefix which is one component longer than Interest name
const Name& childPrefix = (*rightmostCandidate)->getName()
.getPrefix(interest.getName().size() + 1);
if (currentChildPrefix.empty() || (childPrefix != currentChildPrefix))
{
currentChildPrefix = childPrefix;
rightmost = rightmostCandidate;
}
}
}
}
}
else
break;
}
}
if (rightmost != startingPoint)
{
return &(*rightmost)->getData();
}
if (hasRightmostSelector) // if rightmost was not found, try starting point
{
bool doesInterestContainDigest = recognizeInterestWithDigest(interest, *startingPoint);
bool isInPrefix = false;
if (doesInterestContainDigest)
{
isInPrefix = interest.getName().getPrefix(-1).isPrefixOf((*startingPoint)->getName());
}
else
{
isInPrefix = interest.getName().isPrefixOf((*startingPoint)->getName());
}
if (isInPrefix)
{
if (doesComplyWithSelectors(interest, *startingPoint, doesInterestContainDigest))
{
return &(*startingPoint)->getData();
}
}
}
return 0;
}
bool
Cs::doesComplyWithSelectors(const Interest& interest,
cs::Entry* entry,
bool doesInterestContainDigest) const
{
/// \todo The following detection is not correct
/// 1. If data name ends with 32-octet component doesn't mean that this component is digest
/// 2. Only min/max selectors (both 0) can be specified, all other selectors do not
/// make sense for interests with digest (though not sure if we need to enforce this)
if (doesInterestContainDigest)
{
const ndn::name::Component& last = interest.getName().get(-1);
const ndn::ConstBufferPtr& digest = entry->getDigest();
BOOST_ASSERT(digest->size() == last.value_size());
BOOST_ASSERT(digest->size() == ndn::crypto::SHA256_DIGEST_SIZE);
if (std::memcmp(digest->buf(), last.value(), ndn::crypto::SHA256_DIGEST_SIZE) != 0)
{
return false;
}
}
if (!doesInterestContainDigest)
{
if (interest.getMinSuffixComponents() >= 0)
{
size_t minDataNameLength = interest.getName().size() + interest.getMinSuffixComponents();
bool isSatisfied = (minDataNameLength <= entry->getName().size());
if (!isSatisfied)
{
return false;
}
}
if (interest.getMaxSuffixComponents() >= 0)
{
size_t maxDataNameLength = interest.getName().size() + interest.getMaxSuffixComponents();
bool isSatisfied = (maxDataNameLength >= entry->getName().size());
if (!isSatisfied)
{
return false;
}
}
}
if (!interest.getPublisherPublicKeyLocator().empty())
{
if (entry->getData().getSignature().getType() == ndn::Signature::Sha256WithRsa)
{
ndn::SignatureSha256WithRsa rsaSignature(entry->getData().getSignature());
if (rsaSignature.getKeyLocator() != interest.getPublisherPublicKeyLocator())
{
return false;
}
}
else
{
return false;
}
}
if (doesInterestContainDigest)
{
const ndn::name::Component& lastComponent = entry->getName().get(-1);
if (!lastComponent.empty())
{
if (interest.getExclude().isExcluded(lastComponent))
{
return false;
}
}
}
else
{
if (entry->getName().size() >= interest.getName().size() + 1)
{
const ndn::name::Component& nextComponent = entry->getName()
.get(interest.getName().size());
if (!nextComponent.empty())
{
if (interest.getExclude().isExcluded(nextComponent))
{
return false;
}
}
}
}
return true;
}
bool
Cs::recognizeInterestWithDigest(const Interest& interest, cs::Entry* entry) const
{
// only when min selector is not specified or specified with value of 0
// and Interest's name length is exactly the length of the name of CS entry
if (interest.getMinSuffixComponents() <= 0 &&
interest.getName().size() == (entry->getName().size()))
{
const ndn::name::Component& last = interest.getName().get(-1);
if (last.value_size() == ndn::crypto::SHA256_DIGEST_SIZE)
{
return true;
}
}
return false;
}
void
Cs::erase(const Name& exactName)
{
m_mutex.lock();
bool isIterated = false;
SkipListLayer::iterator updateTable[SKIPLIST_MAX_LAYERS];
SkipList::reverse_iterator topLayer = m_skipList.rbegin();
SkipListLayer::iterator head = (*topLayer)->begin();
if (!(*topLayer)->empty())
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::reverse_iterator rit = topLayer; rit != m_skipList.rend(); ++rit)
{
//if we didn't do any iterations on the higher layers, start from the begin() again
if (!isIterated)
head = (*rit)->begin();
updateTable[layer] = head;
if (head != (*rit)->end())
{
// it can happen when begin() contains the element we want to remove
if (!isIterated && ((*head)->getName() == exactName))
{
eraseFromSkipList(*head);
m_mutex.unlock();
return;
}
else
{
SkipListLayer::iterator it = head;
while ((*it)->getName() < exactName)
{
head = it;
updateTable[layer] = it;
isIterated = true;
++it;
if (it == (*rit)->end())
break;
}
}
}
if (layer > 0)
head = (*head)->getIterators().find(layer - 1)->second; // move HEAD to the lower layer
layer--;
}
}
else
{
m_mutex.unlock();
return;
}
head = updateTable[0];
++head; // look at the next slot to check if it contains the item we want to remove
bool isCsEmpty = (size() == 0);
bool isInBoundaries = (head != (*m_skipList.begin())->end());
bool isNameIdentical = false;
if (!isCsEmpty && isInBoundaries)
{
isNameIdentical = (*head)->getName() == exactName;
}
if (isNameIdentical)
{
eraseFromSkipList(*head);
}
}
void
Cs::printSkipList() const
{
//start from the upper layer towards bottom
int layer = m_skipList.size() - 1;
for (SkipList::const_reverse_iterator rit = m_skipList.rbegin(); rit != m_skipList.rend(); ++rit)
{
for (SkipListLayer::iterator it = (*rit)->begin(); it != (*rit)->end(); ++it)
{
std::cout << "Layer " << layer << " " << (*it)->getName() << std::endl;
}
layer--;
}
}
} //namespace nfd
| 21,494 | 27.320158 | 101 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/manifest.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef MANIFEST_HPP
#define MANIFEST_HPP
#include "common.hpp"
#include "context.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "tlv.hpp"
#include <ndn-cxx/encoding/tlv.hpp>
#include <ndn-cxx/util/crypto.hpp>
#include <ndn-cxx/security/key-chain.hpp>
namespace ndn {
class Manifest : public Data
{
public:
class Error : public std::runtime_error
{
public:
explicit
Error(const std::string& what)
: std::runtime_error(what)
{
}
};
/**
* Default constructor.
*/
Manifest();
explicit
Manifest(const Name& name);
explicit
Manifest(const Data& data);
/**
* The virtual destructor.
*/
virtual
~Manifest();
inline void
wireDecode(const Block& wire);
void
addKeyValuePair(const uint8_t* key, size_t keySize, const uint8_t* value, size_t valueSize);
void
addKeyValuePair(std::string key, std::string value);
std::string
getValueByKey(std::string key);
void
eraseValueByKey(std::string key);
/**
* Begin iterator (const).
*/
std::list<Name>::const_iterator
catalogueBegin() const
{
return m_catalogueNames.begin();
}
/**
* End iterator (const).
*/
std::list<Name>::const_iterator
catalogueEnd() const
{
return m_catalogueNames.end();
}
/**
* Adds full name (with digest) to the manifest.
* @param name Name must contain a digest in its last component.
*/
void
addNameToCatalogue(const Name& name);
/**
* Concatenates the name prefix with the digest and adds the resulting full name to the manifest.
* @param name The name prefix without digest component.
* @param digest The tlv block containing digest (data.getSignature().getValue())
*/
void
addNameToCatalogue(const Name& name, const Block& digest);
/**
* Concatenates the name prefix with the digest and adds the resulting full name to the manifest.
* @param name The name prefix without digest component.
* @param digest The buffer containing digest
*/
void
addNameToCatalogue(const Name& name, const ndn::ConstBufferPtr& digest);
void
eraseNameFromCatalogue(const std::vector<Name>::iterator it);
/**
* encode manifest into content (Data packet)
*/
void
encode();
void
decode();
template<bool T>
size_t
wireEncode(EncodingImpl<T>& block) const;
private:
std::list<Name> m_catalogueNames;
std::map<std::string, std::string> m_keyValuePairs;
};
} //namespace ndn
#endif // MANIFEST_HPP
| 3,593 | 23.283784 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/simple-data-retrieval.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef SIMPLE_DATA_RETRIEVAL_HPP
#define SIMPLE_DATA_RETRIEVAL_HPP
#include "data-retrieval-protocol.hpp"
#include "context-options.hpp"
#include "context-default-values.hpp"
#include "selector-helper.hpp"
namespace ndn {
/*
* Any communication in NDN network involves Interest/Data exchanges,
* and Simple Data Retrieval protocol (SDR) is the simplest form of fetching Data from NDN network,
* corresponding to "one Interest / one Data" pattern.
* SDR provides no guarantee of Interest or Data delivery.
* If SDR cannot verify an incoming Data packet, the packet is dropped.
* SDR can be used by applications that want to directly control Interest transmission
* and error correction, or have small ADUs that fit in one Data packet.
*/
class SimpleDataRetrieval : public DataRetrievalProtocol
{
public:
SimpleDataRetrieval(Context* context);
void
start();
void
stop();
private:
void
onData(const ndn::Interest& interest, ndn::Data& data);
void
onTimeout(const ndn::Interest& interest);
void
sendInterest();
};
} // namespace ndn
#endif // SIMPLE_DATA_RETRIEVAL_HPP
| 2,188 | 32.166667 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/data-retrieval-protocol.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef DATA_RETRIEVAL_PROTOCOL_HPP
#define DATA_RETRIEVAL_PROTOCOL_HPP
#include <ndn-cxx/util/scheduler.hpp>
#include "context.hpp"
namespace ndn {
class Consumer;
class DataRetrievalProtocol
{
public:
DataRetrievalProtocol(Context* context);
void updateFace();
bool isRunning();
virtual void
start() = 0;
virtual void
stop() = 0;
protected:
Context* m_context;
shared_ptr<ndn::Face> m_face;
bool m_isRunning;
};
} // namespace ndn
#endif // DATA_RETRIEVAL_PROTOCOL_HPP
| 1,580 | 27.232143 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/cs-entry.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#include "cs-entry.hpp"
namespace ndn {
namespace cs {
void
Entry::release()
{
BOOST_ASSERT(m_layerIterators.empty());
m_dataPacket.reset();
m_digest.reset();
m_nameWithDigest.clear();
}
void
Entry::setData(const Data& data, bool isUnsolicited)
{
m_isUnsolicited = isUnsolicited;
m_dataPacket = data.shared_from_this();
m_digest.reset();
updateStaleTime();
m_nameWithDigest = data.getName();
m_nameWithDigest.append(ndn::name::Component(getDigest()));
}
void
Entry::setData(const Data& data, bool isUnsolicited, const ndn::ConstBufferPtr& digest)
{
m_dataPacket = data.shared_from_this();
m_digest = digest;
updateStaleTime();
m_nameWithDigest = data.getName();
m_nameWithDigest.append(ndn::name::Component(getDigest()));
}
void
Entry::updateStaleTime()
{
m_staleAt = time::steady_clock::now() + m_dataPacket->getFreshnessPeriod();
}
const ndn::ConstBufferPtr&
Entry::getDigest() const
{
if (!static_cast<bool>(m_digest))
{
const Block& block = m_dataPacket->wireEncode();
m_digest = ndn::crypto::sha256(block.wire(), block.size());
}
return m_digest;
}
void
Entry::setIterator(int layer, const Entry::LayerIterators::mapped_type& layerIterator)
{
m_layerIterators[layer] = layerIterator;
}
void
Entry::removeIterator(int layer)
{
m_layerIterators.erase(layer);
}
void
Entry::printIterators() const
{
}
} // namespace cs
} // namespace nfd
| 2,484 | 24.10101 | 99 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/Consumer-Producer-API/src/infomax-prioritizer.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016 Regents of the University of California.
*
* This file is part of Consumer/Producer API library.
*
* Consumer/Producer API library library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Consumer/Producer API library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with Consumer/Producer API, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of Consumer/Producer API authors and contributors.
*/
#ifndef PRIORITIZERS_HPP
#define PRIORITIZERS_HPP
#include "producer-context.hpp"
#include "infomax-tree-node.hpp"
#include <list>
namespace ndn {
class Producer;
class Prioritizer
{
public:
Prioritizer(Producer* p);
void
prioritize();
private:
void
simplePrioritizer(TreeNode* root);
void
mergePrioritizer(TreeNode* root);
void
dummy(TreeNode* root);
TreeNode*
getNextPriorityNode(TreeNode* root);
std::list<TreeNode *>*
mergeSort(TreeNode* node);
std::list<TreeNode *>*
merge(vector< std::list<TreeNode*>* > *subTreeMergeList);
void
produceInfoMaxList(Name, vector<TreeNode*>* prioritizedVector);
bool
treeNodePointerComparator(TreeNode* i, TreeNode* j);
void
resetNodeStatus(TreeNode* node);
private:
Producer *m_producer;
uint64_t m_listVersion;
Name m_prefix;
TreeNode m_root;
};
}
#endif // PRIORITIZERS_HPP | 1,957 | 24.763158 | 99 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/rate-estimation.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Jacques Samain <[email protected]>
*
*/
#ifndef RATE_ESTIMATOR_H
#define RATE_ESTIMATOR_H
#include <unistd.h>
#include <ndn-cxx/face.hpp>
#include <boost/unordered_map.hpp>
#include "data-path.hpp"
#include "pending-interest.hpp"
#define BATCH 50
#define KV 20
namespace ndn {
class Variables
{
public:
Variables();
struct timeval begin;
volatile double alpha;
volatile double avgWin;
volatile double avgRtt;
volatile double rtt;
volatile double instantaneousThroughput;
volatile double winChange;
volatile int batchingStatus;
volatile bool isRunning;
volatile double winCurrent;
volatile bool isBusy;
volatile int maxPacketSize;
}; //end class Variables
class NdnIcpDownloadRateEstimator
{
public:
NdnIcpDownloadRateEstimator(){};
~NdnIcpDownloadRateEstimator(){};
virtual void onRttUpdate(double rtt){};
virtual void onDataReceived(int packetSize){};
virtual void onWindowIncrease(double winCurrent){};
virtual void onWindowDecrease(double winCurrent){};
Variables *m_variables;
};
//A rate estimator based on the RTT: upon the reception
class InterRttEstimator : public NdnIcpDownloadRateEstimator
{
public:
InterRttEstimator(Variables *var);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize) {};
void onWindowIncrease(double winCurrent);
void onWindowDecrease(double winCurrent);
private:
pthread_t * myTh;
bool ThreadisRunning;
};
//A rate estimator, this one
class BatchingPacketsEstimator : public NdnIcpDownloadRateEstimator
{
public:
BatchingPacketsEstimator(Variables *var,int batchingParam);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize) {};
void onWindowIncrease(double winCurrent);
void onWindowDecrease(double winCurrent);
private:
int batchingParam;
pthread_t * myTh;
bool ThreadisRunning;
};
//A Rate estimator, this one is the simplest: counting batchingParam packets and then divide the sum of the size of these packets by the time taken to DL them.
class SimpleEstimator : public NdnIcpDownloadRateEstimator
{
public:
SimpleEstimator(Variables *var, int batchingParam);
void onRttUpdate(double rtt);
void onDataReceived(int packetSize);
void onWindowIncrease(double winCurrent){};
void onWindowDecrease(double winCurrent){};
private:
int batchingParam;
};
void *Timer(void * data);
}//end of namespace ndn
#endif //RATE_ESTIMATOR_H
| 3,429 | 26.44 | 160 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/chunktimeObserver.cpp | /*
* Timing of NDN Interest packets and NDN Data packets while downloading.
*/
#include "chunktimeObserver.hpp"
//for logging/terminal output
#include "stdio.h"
#include <sstream>
#include <iostream>
// To catch a potential OOR map issue
#include <stdexcept>
// For bandit context
#include <chrono>
#include <thread>
ChunktimeObserver::ChunktimeObserver(int sample)
{
this->sampleSize = sample;
this->lastInterestKey = "Dummy";
this->lastDataKey = "Dummy";
this->sampleNumber = 0;
this->cumulativeTp = 0.0;
pFile = fopen("log_ChunktimeObserver", "a");
startTime = boost::chrono::system_clock::now();
}
ChunktimeObserver::~ChunktimeObserver()
{
fclose(pFile);
}
void ChunktimeObserver::addThroughputSignal(ThroughputNotificationSlot slot) {
signalThroughputToDASHReceiver.connect(slot);
}
void ChunktimeObserver::addContextSignal(ContextNotificationSlot slot) {
signalContextToDASHReceiver.connect(slot);
}
//logging method
void ChunktimeObserver::writeLogFile(const std::string szString)
{
double timePoint = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::system_clock::now() - startTime).count();
timePoint = timePoint * 0.000001; //from microseconds to seconds
fprintf(pFile, "%f",timePoint);
fprintf(pFile, "\t%s",szString.c_str());
}
void ChunktimeObserver::onInterestSent(const ndn::Interest &interest)
{
boost::chrono::time_point<boost::chrono::system_clock> timestamp = boost::chrono::system_clock::now();
//Build the key and key-1
int chunkNo = interest.getName()[-1].toSegment();
int chunkNoMinusOne = chunkNo - 1;
std::string chunkID = interest.getName().toUri();
std::string key = chunkID.substr(0, 9).append(std::to_string(chunkNo));
std::string keyMinusOne = chunkID.substr(0, 9).append(std::to_string(chunkNoMinusOne));
//Insert timestamp into the Map
if (timingMap.count(keyMinusOne) == 0) //no key-1 in map -> first Interest of Segment
{
if(this->lastInterestKey.compare("Dummy") == 0) //no lastInterestKey set -> first Interest overall
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "(no) IKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timeVector.at(1) = timestamp; timeVector.at(2) = timestamp; timeVector.at(3) = timestamp; //TODOTIMO: initialise new vector (with dummy values for yet unknown spots)
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
} else //last Key set -> NOT first Interest overall
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "LastIKey: " << this->lastInterestKey << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
timingMap.at(this->lastInterestKey).at(1) = timestamp; //as Interest2
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
}
}
else //NOT first Interest
{
//logging start
std::stringstream stringstreamI;
stringstreamI << "IKey: " << key << "\t" << "IKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamI.str());
//logging end
timingMap.at(keyMinusOne).at(1) = timestamp; //as Interest2
std::vector<boost::chrono::time_point<boost::chrono::system_clock>> timeVector(4);
timeVector.at(0) = timestamp;
timingMap.emplace(key, timeVector); //as Interest1
this->lastInterestKey = key;
}
}
double ChunktimeObserver::onDataReceived(const ndn::Data &data)
{
try {
boost::chrono::time_point<boost::chrono::system_clock> timestamp = boost::chrono::system_clock::now();
//Build key and key-1
int chunkNo = data.getName()[-1].toSegment();
int chunkNoMinusOne = chunkNo - 1;
std::string chunkID = data.getName().toUri();
std::string tail = chunkID.substr(std::max<int>(chunkID.size()-6,0));
bool initChunk = (tail.compare("%00%00") == 0); //true, if it is the first chunk of a segment (no viable measurement)
std::string key = chunkID.substr(0, 9).append(std::to_string(chunkNo));
std::string keyMinusOne = chunkID.substr(0, 9).append(std::to_string(chunkNoMinusOne));
int thisRTT = boost::chrono::duration_cast<boost::chrono::microseconds>(timestamp - timingMap.at(key).at(0)).count();
int numHops = 0;
auto numHopsTag = data.getTag<ndn::lp::NumHopsTag>();
if (numHopsTag != nullptr) {
numHops = (uint64_t)numHopsTag->get(); // Comes out as a unsigned long int
}
signalContextToDASHReceiver((uint64_t)thisRTT, (uint64_t)numHops);
//Insert timestamp into the map
if (timingMap.count(keyMinusOne) == 0) //no key-1 in map -> first Data packet of the Segment
{
if(this->lastDataKey.compare("Dummy") == 0) //no lastDataKey set -> first Data packet overall)
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "(no) DKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(key).at(2) = timestamp; //as Data1
this->lastDataKey = key;
return 0; //what to return when there is no gap b.c. of first Data packet of Segment?
} else
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "LastDKey: " << this->lastDataKey << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(this->lastDataKey).at(3) = timestamp; //as Data2
timingMap.at(key).at(2) = timestamp; //as Data1
//timingVector is complete for map[lastDataKey] -> measurement computations can be triggered now!
int dataPacketSize = data.wireEncode().size();
int interestDelay = this->computeInterestDelay(this->lastDataKey);
int dataDelay = this->computeDataDelay(this->lastDataKey);
int firstRTT = this->computeRTT(this->lastDataKey, true);
int secondRTT = this->computeRTT(this->lastDataKey, false);
double quotient = this->interestDataQuotient((double) dataDelay, interestDelay);
double classicBW = this->computeClassicBW(firstRTT, dataPacketSize);
double throughput = this->throughputEstimation(dataDelay, dataPacketSize);
double sampledTp = 0.0;
//SEPERATION: chunks at the beginning of a segment download may not have viable values
// AND out of order reception data delays also no viable values
// AND firstRTT must not be 0 because then, the dummy value in the timestamp vector is used (= the data delay is not viable)
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
sampledTp = this->getSampledThroughput(throughput);
else
this->writeLogFile("Invalid computation.\n");
//logging start
std::stringstream loggingString;
loggingString << "I-Delay: " << interestDelay << "\t" << "D-Delay: " << dataDelay << "\t"
<< "First RTT: " << firstRTT << "\t" << "Second RTT: " << secondRTT << "\t"
<< "Classic BW: " << classicBW << "\t" << "gOut/gIn: " << quotient << "\t" << "Throughput: " << throughput << "\n";
this->writeLogFile(loggingString.str());
if(sampleNumber==0 && sampledTp != 0.0) //TODO Does this work?
{
std::stringstream sampleString;
sampleString << sampleSize << "-Sampled Throughput: " << sampledTp << "\n";
this->writeLogFile(sampleString.str());
}
//logging end
this->lastDataKey = key;
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
return throughput; //unsampled throughput
else
return 0; //invalid throughput
}
}
else //NOT first Data packet
{
std::stringstream stringstreamD;
stringstreamD << "DKey: " << key << "\t" << "DKey-1: " << keyMinusOne << "\n";
this->writeLogFile(stringstreamD.str());
timingMap.at(keyMinusOne).at(3) = timestamp; //as Data2
timingMap.at(key).at(2) = timestamp; //as Data1
//timingVector is complete for map[keyMinusOne] -> measurement computations can be triggered now!
int dataPacketSize = data.wireEncode().size();
int interestDelay = this->computeInterestDelay(keyMinusOne);
int dataDelay = this->computeDataDelay(keyMinusOne);
int firstRTT = this->computeRTT(keyMinusOne, true);
int secondRTT = this->computeRTT(keyMinusOne, false);
double quotient = this->interestDataQuotient((double) dataDelay, interestDelay);
double classicBW = this->computeClassicBW(secondRTT, dataPacketSize);
double throughput = this->throughputEstimation(dataDelay, dataPacketSize);
double sampledTp = 0.0;
//SEPERATION: chunks at the beginning of a segment download may not have viable values
// AND out of order reception data delays also no viable values
// AND firstRTT must not be 0 because then, the dummy value in the timestamp vector is used (= the data delay is not viable)
//only consider values bigger 0.1
if(isValidMeasurement(throughput, firstRTT, dataDelay) && !initChunk)
sampledTp = this->getSampledThroughput(throughput);
else
this->writeLogFile("Invalid computation.\n");
//logging start
std::stringstream loggingString;
loggingString << "I-Delay: " << interestDelay << "\t" << "D-Delay: " << dataDelay << "\t"
<< "First RTT: " << firstRTT << "\t" << "Second RTT: " << secondRTT << "\t"
<< "Classic BW: " << classicBW << "\t" << "gOut/gIn: " << quotient << "\t" << "Throughput: " << throughput << "\n";
this->writeLogFile(loggingString.str());
if(sampleNumber==0 && sampledTp != 0.0)
{
std::stringstream sampleString;
sampleString << sampleSize << "-Sampled Throughput: " << sampledTp << "\n";
this->writeLogFile(sampleString.str());
}
//logging end
this->lastDataKey = key;
return throughput; //unsampled
}
}
catch (const std::out_of_range& oor) {
std::cout << "Out of range error: " << oor.what() << std::endl;
}
}
bool ChunktimeObserver::isValidMeasurement(double throughput, int firstRTT, int dataDelay)
{
return dataDelay > 0 && firstRTT > 0 && throughput > 0.1;
}
double ChunktimeObserver::getSampledThroughput(double throughput) //sampling: harmonic avg over n throughput computations (n is set in the contructor)
{
this->cumulativeTp = this->cumulativeTp + (1/throughput);
sampleNumber++;
if(this->sampleNumber == this->sampleSize)
{
double sampledThroughput = this->sampleNumber / this->cumulativeTp; // harmonic avg = n/(sum of inverses)
this->sampleNumber = 0;
this->cumulativeTp = 0.0;
double convertedThroughput = sampledThroughput * 1000000; //convertation from Mbit/s to Bit/s
signalThroughputToDASHReceiver((uint64_t)convertedThroughput); //trigger notification-function in DASHReceiver
return sampledThroughput;
}
else
return 0; //not enough samples yet
}
//******************************************************************************************
//**********************************COMPUTATION FORMULAS************************************
//******************************************************************************************
int ChunktimeObserver::computeInterestDelay(std::string key) //in µs (timeI2 - timeI1)
{
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(1) - timingMap.at(key).at(0)).count();
}
int ChunktimeObserver::computeDataDelay(std::string key) //in µs (timeD2 - timeD1)
{
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(3) - timingMap.at(key).at(2)).count();
}
int ChunktimeObserver::computeRTT(std::string key, bool first) //in µs (first = timeD1 - timeI1, !first = timeD2 - timeI2)
{
if(first)
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(2) - timingMap.at(key).at(0)).count();
else
return boost::chrono::duration_cast<boost::chrono::microseconds>(timingMap.at(key).at(3) - timingMap.at(key).at(1)).count();
}
double ChunktimeObserver::computeClassicBW(int rtt, int size) //in MBit/s
{
return (double) (size*8)/(rtt/2);
}
double ChunktimeObserver::throughputEstimation(int gap, int size) //in Bit/µs = Mbit/s
{
if(gap != 0)
return (double) (size*8)/gap;
else
{
//this->writeLogFile("### Throughput Estimation: \t Data packet delay is 0 µs. DIV by ZERO! -> Throughput=0 ### \n");
//return 0.0;
this->writeLogFile("### Throughput Estimation: \t Data packet delay is 0 µs. DIV by ZERO! -> Data delay set to min=1 ### \n");
return (double) (size*8)/(gap+1);
}
}
double ChunktimeObserver::interestDataQuotient(double gIn, int gOut)
{
if(gIn != 0)
return gOut/gIn;
else
{
//this->writeLogFile("### Interest-Data-Quotient: \t Data packet delay is 0 µs. DIV by ZERO! -> Quotient=0 ### \n");
//return 0.0;
this->writeLogFile("### Interest-Data-Quotient: \t Data packet delay is 0 µs. DIV by ZERO! -> Data delay set to min=1 ### \n");
return gOut/gIn;
}
}
/*
int ChunktimeObserver::interestDataGap(int gIn, int gOut)
{
return gIn - gOut;
}
double ChunktimeObserver::gapResponseCurve(int gIn, int gOut)
{
double div = gOut / gIn;
if(div <= 1.0)
return 1.0;
else
return 0.0; //dummy
}
*/
| 15,350 | 42.120787 | 177 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/data-path.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include <sys/time.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#define TIMEOUT_SMOOTHER 0.1
#define TIMEOUT_RATIO 10
#define ALPHA 0.8
namespace ndn {
class DataPath
{
public:
DataPath(double drop_factor,
double p_min,
unsigned new_timer,
unsigned int samples,
uint64_t new_rtt = 1000,
uint64_t new_rtt_min = 1000,
uint64_t new_rtt_max = 1000);
public:
/*
* @brief Print Path Status
*/
void
pathReporter();
/*
* @brief Add a new RTT to the RTT queue of the path, check if RTT queue is full, and thus need overwrite.
* Also it maintains the validity of min and max of RTT.
* @param new_rtt is the value of the new RTT
*/
void
insertNewRtt(double new_rtt, double winSize, double *averageThroughput);
/**
* @brief Update the path statistics
* @param packet_size the size of the packet received, including the ICN header
* @param data_size the size of the data received, without the ICN header
*/
void
updateReceivedStats(std::size_t packet_size, std::size_t data_size);
/**
* @brief Get the value of the drop factor parameter
*/
double
getDropFactor();
/**
* @brief Get the value of the drop probability
*/
double
getDropProb();
/**
* @brief Set the value pf the drop probability
* @param drop_prob is the value of the drop probability
*/
void
setDropProb(double drop_prob);
/**
* @brief Get the minimum drop probability
*/
double
getPMin();
/**
* @brief Get last RTT
*/
double
getRtt();
/**
* @brief Get average RTT
*/
double
getAverageRtt();
/**
* @brief Get the current m_timer value
*/
double
getTimer();
/**
* @brief Smooth he value of the m_timer accordingly with the last RTT measured
*/
void
smoothTimer();
/**
* @brief Get the maximum RTT among the last samples
*/
double
getRttMax();
/**
* @brief Get the minimum RTT among the last samples
*/
double
getRttMin();
/**
* @brief Get the number of saved samples
*/
unsigned
getSampleValue();
/**
* @brief Get the size og the RTT queue
*/
unsigned
getRttQueueSize();
/*
* @brief Change drop probability according to RTT statistics
* Invoked in RAAQM(), before control window size update.
*/
void
updateDropProb();
/**
* @brief This function convert the time from struct timeval to its value in microseconds
*/
static double getMicroSeconds(struct timeval time);
void setAlpha(double alpha);
private:
/**
* The value of the drop factor
*/
double m_dropFactor;
/**
* The minumum drop probability
*/
double m_pMin;
/**
* The timer, expressed in milliseconds
*/
double m_timer;
/**
* The number of samples to store for computing the protocol measurements
*/
const unsigned int m_samples;
/**
* The last, the minimum and the maximum value of the RTT (among the last m_samples samples)
*/
double m_rtt, m_rttMin, m_rttMax;
/**
* The current drop probability
*/
double m_dropProb;
/**
* The number of packets received in this path
*/
intmax_t m_packetsReceived;
/**
* The first packet received after the statistics print
*/
intmax_t m_lastPacketsReceived;
/**
* Total number of bytes received including the ICN header
*/
intmax_t m_packetsBytesReceived;
/**
* The amount of packet bytes received at the last path summary computation
*/
intmax_t m_lastPacketsBytesReceived;
/**
* Total number of bytes received without including the ICN header
*/
intmax_t m_rawDataBytesReceived;
/**
* The amount of raw dat bytes received at the last path summary computation
*/
intmax_t m_lastRawDataBytesReceived;
class byArrival;
class byOrder;
/**
* Double ended queue for the RTTs
*/
typedef boost::multi_index_container
<
unsigned,
boost::multi_index::indexed_by<
// by arrival (FIFO)
boost::multi_index::sequenced<boost::multi_index::tag<byArrival> >,
// index by ascending order
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<byOrder>,
boost::multi_index::identity<unsigned>
>
>
> RTTQueue;
RTTQueue m_rttSamples;
/**
* Time of the last call to the path reporter method
*/
struct timeval m_previousCallOfPathReporter;
double m_averageRtt;
double m_alpha;
};
} // namespace ndn
| 6,140 | 22.619231 | 110 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/pending-interest.hpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include <ctime>
#include <ndn-cxx/data.hpp>
namespace ndn {
class PendingInterest
{
public:
PendingInterest();
/**
* @brief Get the send time of the interest
*/
const timeval &
getSendTime();
/**
* @brief Set the send time of the interest
*/
PendingInterest
setSendTime(const timeval &now);
/**
* @brief Get the size of the data without considering the ICN header
*/
std::size_t
getRawDataSize();
/**
* @brief Get the size of the data packet considering the ICN header
*/
std::size_t
getPacketSize();
/**
* @brief True means that the data addressed by this pending interest has been received
*/
PendingInterest
markAsReceived(bool val);
/**
* @brief If the data has been received returns true, otherwise returns false
*/
bool
checkIfDataIsReceived();
/**
* @brief Temporarily store here the out of order data received
* @param data The data corresponding to this pending interest
*/
PendingInterest
addRawData(const Data &data);
/**
* @brieg Get the raw data block
*/
const char *
getRawData();
/**
* @brief Free the memory occupied by the raw data block
*/
PendingInterest
removeRawData();
/**
* @brief Get the number of times this interest has been retransmitted
*/
unsigned int
getRetxCount();
/**
* @brief Increase the number of retransmission of this packet
*/
PendingInterest
increaseRetxCount();
private:
/**
* The buffer storing the raw data received out of order
*/
unsigned char *m_rawData;
/**
* The size of the raw data buffer
*/
std::size_t m_rawDataSize;
/**
* The size of the whole packet, including the ICN header
*/
std::size_t m_packetSize;
/**
* True means that the data has been received.
*/
bool m_isReceived;
/**
* Delivering time of this interest
*/
struct timeval m_sendTime;
private:
/**
* Counter of the number of retransmissions of this interest
*/
unsigned int m_retxCount;
}; // end class PendingInterests
} // end namespace ndn | 3,439 | 23.397163 | 91 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/chunktimeObserver.hpp | /*
* Timing of NDN Interest packets and NDN Data packets while downloading.
*/
#ifndef CHUNKTIME_OBSERVER_H
#define CHUNKTIME_OBSERVER_H
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/data.hpp>
#include <map>
#include <vector>
#include <boost/chrono/include.hpp>
#include <string>
#include <boost/signals2.hpp>
class ChunktimeObserver
{
public:
ChunktimeObserver(int samples);
~ChunktimeObserver();
/**
* Used signal to trigger DASHReceiver-Function (notifybpsChunk and context) from ChunktimeObserver
*/
typedef boost::signals2::signal<void (uint64_t)>::slot_type ThroughputNotificationSlot;
typedef boost::signals2::signal<void (uint64_t, uint64_t)>::slot_type ContextNotificationSlot;
void addThroughputSignal(ThroughputNotificationSlot slot);
void addContextSignal(ContextNotificationSlot slot);
/**
* Used to log the timing measurements seperately.
*/
void writeLogFile(const std::string szString);
/**
* Insert the timestamps of the sent Interest into the map.
*/
void onInterestSent(const ndn::Interest &interest);
/**
* Insert the timestamps of the received Data packet into the map.
@return (double) the measured throughput OR "0.0" when only 1 Data packet is received yet (-> no Data Delay computation possible) in MBit/s !
*/
double onDataReceived(const ndn::Data &data);
private:
//Signal triggering the NotifybpsChunk-Function in DASHReceiver
boost::signals2::signal<void(uint64_t)> signalThroughputToDASHReceiver;
boost::signals2::signal<void(uint64_t, uint64_t)> signalContextToDASHReceiver;
// map< key, vector< timeI1, timeI2, timeD1, timeD2 > >
std::map<std::string, std::vector<boost::chrono::time_point<boost::chrono::system_clock>>> timingMap;
// Some magic to get the key from the last element if we can not compute it.
std::string lastInterestKey;
std::string lastDataKey;
//for sampling over chunk throughput measurements
int sampleSize;
int sampleNumber;
double cumulativeTp;
//for logging
FILE* pFile;
boost::chrono::time_point<boost::chrono::system_clock> startTime;
/**
* @param samplesize, throughput
* @eturn (double) avg throughput over samplesize OR 0.0 (if not enough samples gathered yet)
*/
double getSampledThroughput(double throughput);
/**
* @param the string build from the last data packet
* @eturn (int) delay between two consecutive Interests (in microseconds µs)
*/
int computeInterestDelay(std::string key);
/**
* @param (string) the key built from the last data packet
* @eturn (int) delay between two consecutive Data packets (in microseconds µs)
*/
int computeDataDelay(std::string key);
/**
* @param (string) the key built from the last data packet, (bool) if the first Interest-Data pair is wanted (true) or the second pair (false)
* @eturn (int) delay between two consecutive Data packets (in microseconds µs)
*/
int computeRTT(std::string key, bool first);
/**
* @param (string) the rtt in µs, (int) the datasize in Byte
* @eturn (double) computed BW with the formula [datasize/(rount-trip time/2)] (in Bit/µs = MBit/s)
*/
double computeClassicBW(int rtt, int size);
/**
* @param (int) the gap between two consecutive Data packets in µs, (int) the datasize in Byte
* @eturn (double) computed throughput with the formula [datasize/gap] (in Bit/µs = MBit/s)
*/
double throughputEstimation(int gap, int size);
/**
* @param (int) gap between two consecutive Data packets (incoming), (int) gap between two consecutive Interest packets (outgoing)
* @return (double)
*/
double interestDataQuotient(double gIn, int gOut);
bool isValidMeasurement(double throughput, int firstRTT, int dataDelay);
//implement when needed
int interestDataGap(int gIn, int gOut);
double gapResponseCurve(int gIn, int gOut);
};//end class ChunktimeObserver
#endif //CHUNKTIME_OBSERVER_H
| 4,164 | 32.055556 | 155 | hpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/pending-interest.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "pending-interest.hpp"
namespace ndn {
PendingInterest::PendingInterest()
: m_rawData(NULL)
, m_rawDataSize(0)
, m_packetSize(0)
, m_isReceived(false)
, m_retxCount(0)
{
}
const timeval &
PendingInterest::getSendTime()
{
return m_sendTime;
}
PendingInterest
PendingInterest::setSendTime(const timeval &now)
{
m_sendTime.tv_sec = now.tv_sec;
m_sendTime.tv_usec = now.tv_usec;
return *this;
}
std::size_t
PendingInterest::getRawDataSize()
{
return m_rawDataSize;
}
std::size_t
PendingInterest::getPacketSize()
{
return m_packetSize;
}
unsigned int
PendingInterest::getRetxCount()
{
return m_retxCount;
}
PendingInterest
PendingInterest::increaseRetxCount()
{
m_retxCount++;
return *this;
}
PendingInterest
PendingInterest::markAsReceived(bool val)
{
m_isReceived = val;
return *this;
}
bool
PendingInterest::checkIfDataIsReceived()
{
return m_isReceived;
}
PendingInterest
PendingInterest::addRawData(const Data &data)
{
if (m_rawData != NULL)
removeRawData();
const Block &content = data.getContent();
m_rawDataSize = content.value_size();
m_packetSize = data.wireEncode().size();
m_rawData = (unsigned char *) malloc(m_rawDataSize);
memcpy(m_rawData,
reinterpret_cast<const char *>(content.value()),
content.value_size());
return *this;
}
const char *
PendingInterest::getRawData()
{
if (m_rawData != NULL)
return reinterpret_cast<const char *>(m_rawData);
else
return nullptr;
}
PendingInterest
PendingInterest::removeRawData()
{
if (m_rawData != NULL)
{
free(m_rawData);
m_rawData = NULL;
m_rawDataSize = 0;
m_packetSize = 0;
}
return *this;
}
} // namespace ndn | 2,977 | 21.059259 | 90 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/data-path.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "data-path.hpp"
namespace ndn {
DataPath::DataPath(double drop_factor,
double p_min,
unsigned new_timer,
unsigned int samples,
uint64_t new_rtt,
uint64_t new_rtt_min,
uint64_t new_rtt_max)
: m_dropFactor(drop_factor)
, m_pMin(p_min)
, m_timer(new_timer)
, m_samples(samples)
, m_rtt(new_rtt)
, m_rttMin(new_rtt_min)
, m_rttMax(new_rtt_max)
, m_dropProb(0)
, m_packetsReceived(0)
, m_lastPacketsReceived(0)
, m_packetsBytesReceived(0)
, m_lastPacketsBytesReceived(0)
, m_rawDataBytesReceived(0)
, m_lastRawDataBytesReceived(0)
, m_averageRtt(0)
, m_alpha(ALPHA)
{
gettimeofday(&m_previousCallOfPathReporter, 0);
}
void
DataPath::pathReporter()
{
struct timeval now;
gettimeofday(&now, 0);
double rate, delta_t;
delta_t = getMicroSeconds(now) - getMicroSeconds(m_previousCallOfPathReporter);
rate = (m_packetsBytesReceived - m_lastPacketsBytesReceived) * 8 / delta_t; // MB/s
std::cout << "DataPath status report: "
<< "at time " << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " sec:\n"
<< (void *) this << " path\n"
<< "Packets Received: " << (m_packetsReceived - m_lastPacketsReceived) << "\n"
<< "delta_t " << delta_t << " [us]\n"
<< "rate " << rate << " [Mbps]\n"
<< "Last RTT " << m_rtt << " [us]\n"
<< "RTT_max " << m_rttMax << " [us]\n"
<< "RTT_min " << m_rttMin << " [us]\n" << std::endl;
m_lastPacketsReceived = m_packetsReceived;
m_lastPacketsBytesReceived = m_packetsBytesReceived;
gettimeofday(&m_previousCallOfPathReporter, 0);
}
void
DataPath::insertNewRtt(double new_rtt, double winSize, double *averageThroughput)
{
if(winSize)
{
if(*averageThroughput == 0)
*averageThroughput = winSize / new_rtt;
*averageThroughput = m_alpha * *averageThroughput + (1 - m_alpha) * (winSize / new_rtt);
}
//if(m_averageRtt == 0)
// m_averageRtt = new_rtt;
//m_averageRtt = m_alpha * m_averageRtt + (1 - m_alpha) * new_rtt; // not really promising measurement
m_rtt = new_rtt;
m_rttSamples.get<byArrival>().push_back(new_rtt);
if (m_rttSamples.get<byArrival>().size() > m_samples)
m_rttSamples.get<byArrival>().pop_front();
m_rttMax = *(m_rttSamples.get<byOrder>().rbegin());
m_rttMin = *(m_rttSamples.get<byOrder>().begin());
}
void
DataPath::updateReceivedStats(std::size_t packet_size, std::size_t data_size)
{
m_packetsReceived++;
m_packetsBytesReceived += packet_size;
m_rawDataBytesReceived += data_size;
}
double
DataPath::getDropFactor()
{
return m_dropFactor;
}
double
DataPath::getDropProb()
{
return m_dropProb;
}
void
DataPath::setDropProb(double dropProb)
{
m_dropProb = dropProb;
}
double
DataPath::getPMin()
{
return m_pMin;
}
double
DataPath::getTimer()
{
return m_timer;
}
void
DataPath::smoothTimer()
{
m_timer = (1 - TIMEOUT_SMOOTHER) * m_timer + (TIMEOUT_SMOOTHER) * m_rtt * (TIMEOUT_RATIO);
}
double
DataPath::getRtt()
{
return m_rtt;
}
double
DataPath::getAverageRtt()
{
return m_averageRtt;
}
double
DataPath::getRttMax()
{
return m_rttMax;
}
double
DataPath::getRttMin()
{
return m_rttMin;
}
unsigned
DataPath::getSampleValue()
{
return m_samples;
}
unsigned
DataPath::getRttQueueSize()
{
return m_rttSamples.get<byArrival>().size();
}
void
DataPath::updateDropProb()
{
m_dropProb = 0.0;
if (getSampleValue() == getRttQueueSize()) {
if (m_rttMax == m_rttMin)
m_dropProb = m_pMin;
else
m_dropProb = m_pMin + m_dropFactor * (m_rtt - m_rttMin) / (m_rttMax - m_rttMin);
}
}
double
DataPath::getMicroSeconds(struct timeval time)
{
return (double) (time.tv_sec) * 1000000 + (double) (time.tv_usec);
}
void
DataPath::setAlpha(double alpha)
{
if(alpha >= 0 && alpha <= 1)
m_alpha = alpha;
}
} // namespace ndn
| 5,257 | 23.342593 | 106 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/rate-estimation.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Jacques Samain <[email protected]>
*/
#include "rate-estimation.hpp"
namespace ndn {
Variables::Variables () :
alpha(0.0),
avgWin(0.0),
avgRtt(0.0),
rtt(0.0),
instantaneousThroughput(0.0),
winChange(0.0),
batchingStatus(0),
isRunning(false),
winCurrent(0.0),
isBusy(false)
{}
void* Timer(void* data)
{
Variables * m_variables = (Variables*) data;
double datRtt, myAvgWin, myAvgRtt;
int myWinChange, myBatchingParam, maxPacketSize;
timeval now;
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
datRtt = m_variables->rtt;
m_variables->isBusy = false;
while(m_variables->isRunning)
{
usleep(KV * datRtt);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
datRtt = m_variables->rtt;
myAvgWin = m_variables->avgWin;
myAvgRtt = m_variables->avgRtt;
myWinChange = m_variables->winChange;
myBatchingParam = m_variables->batchingStatus;
maxPacketSize = m_variables->maxPacketSize;
m_variables->avgRtt = m_variables->rtt;
m_variables->avgWin = 0;
m_variables->winChange = 0;
m_variables->batchingStatus = 1;
m_variables->isBusy = false;
if(myBatchingParam == 0 || myWinChange == 0)
continue;
if(m_variables->instantaneousThroughput == 0)
m_variables->instantaneousThroughput = (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * myBatchingParam));
m_variables->instantaneousThroughput = m_variables->alpha * m_variables->instantaneousThroughput + (1 - m_variables->alpha) * ( (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * myBatchingParam) ) );
gettimeofday(&now, 0);
// printf("time: %f instantaneous: %f\n", DataPath::getMicroSeconds(now), m_variables->instantaneousThroughput);
// fflush(stdout);
}
}
InterRttEstimator::InterRttEstimator(Variables *var)
{
this->m_variables = var;
this->ThreadisRunning = false;
this->myTh = NULL;
gettimeofday(&(this->m_variables->begin), 0);
}
void InterRttEstimator::onRttUpdate(double rtt) {
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->rtt = rtt;
m_variables->batchingStatus++;
m_variables->avgRtt += rtt;
m_variables->isBusy = false;
if(!ThreadisRunning)
{
myTh = (pthread_t*)malloc(sizeof(pthread_t));
if (!myTh)
{
std::cerr << "Error allocating thread." << std::endl;
myTh = NULL;
}
if(int err = pthread_create(myTh, NULL, ndn::Timer, (void*)this->m_variables))
{
std::cerr << "Error creating the thread" << std::endl;
myTh = NULL;
}
ThreadisRunning = true;
}
}
void InterRttEstimator::onWindowIncrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
void InterRttEstimator::onWindowDecrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
SimpleEstimator::SimpleEstimator(Variables *var, int param)
{
this->m_variables = var;
this->batchingParam = param;
gettimeofday(&(this->m_variables->begin), 0);
}
void SimpleEstimator::onDataReceived(int packetSize)
{
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->avgWin += packetSize;
this->m_variables->isBusy = false;
}
void SimpleEstimator::onRttUpdate(double rtt)
{
int nbrOfPackets = 0;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus++;
nbrOfPackets = this->m_variables->batchingStatus;
this->m_variables->isBusy = false;
if(nbrOfPackets == this->batchingParam)
{
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
float inst = this->m_variables->instantaneousThroughput;
double alpha = this->m_variables->alpha;
int maxPacketSize = this->m_variables->maxPacketSize;
double sizeTotal = this->m_variables->avgWin; //Here we use avgWin to store the total size downloaded during the time span of nbrOfPackets
this->m_variables->isBusy = false;
//Assuming all packets carry maxPacketSize bytes of data (8*maxPacketSize bits); 1000000 factor to convert us to seconds
if(inst)
{
inst = alpha * inst + (1 - alpha) * (sizeTotal * 8 * 1000000.0 / (delay));
}
else
inst = sizeTotal * 8 * 1000000.0 / (delay);
timeval now;
gettimeofday(&now, 0);
//printf("time: %f, instantaneous: %f\n", DataPath::getMicroSeconds(now), inst);
//fflush(stdout);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus = 0;
this->m_variables->instantaneousThroughput = inst;
this->m_variables->avgWin = 0.0;
this->m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin),0);
}
}
BatchingPacketsEstimator::BatchingPacketsEstimator(Variables *var, int param)
{
this->m_variables = var;
this->batchingParam = param;
gettimeofday(&(this->m_variables->begin), 0);
}
void BatchingPacketsEstimator::onRttUpdate(double rtt)
{
int nbrOfPackets = 0;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus++;
this->m_variables->avgRtt += rtt;
nbrOfPackets = this->m_variables->batchingStatus;
this->m_variables->isBusy = false;
if(nbrOfPackets == this->batchingParam)
{
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
double inst = this->m_variables->instantaneousThroughput;
double alpha = this->m_variables->alpha;
double myAvgWin = m_variables->avgWin;
double myAvgRtt = m_variables->avgRtt;
double myWinChange = m_variables->winChange;
int maxPacketSize = m_variables->maxPacketSize;
this->m_variables->isBusy = false;
if(inst == 0)
inst = (myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * nbrOfPackets));
else
inst = alpha * inst + (1 - alpha) * ((myAvgWin * 8.0 * maxPacketSize * 1000000.0 / (1.0 * myWinChange)) / (myAvgRtt / (1.0 * nbrOfPackets)));
timeval now;
gettimeofday(&now, 0);
//printf("time: %f, instantaneous: %f\n", DataPath::getMicroSeconds(now), inst);
//fflush(stdout);
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->batchingStatus = 0;
this->m_variables->avgWin = 0;
this->m_variables->avgRtt = 0;
this->m_variables->winChange = 0;
this->m_variables->instantaneousThroughput = inst;
this->m_variables->isBusy = false;
}
}
void BatchingPacketsEstimator::onWindowIncrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
void BatchingPacketsEstimator::onWindowDecrease(double winCurrent) {
timeval end;
gettimeofday(&end, 0);
double delay = DataPath::getMicroSeconds(end) - DataPath::getMicroSeconds(this->m_variables->begin);
while(m_variables->isBusy)
{}
m_variables->isBusy = true;
m_variables->avgWin += this->m_variables->winCurrent * delay;
m_variables->winCurrent = winCurrent;
m_variables->winChange += delay;
m_variables->isBusy = false;
gettimeofday(&(this->m_variables->begin), 0);
}
}
| 10,083 | 32.280528 | 254 | cpp |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/code/ndn-icp-download/src/ndn-icp-download.cpp | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2015 Regents of Cisco Systems,
* IRT Systemx
*
* This project is a library implementing an Interest Control Protocol. It can be used by
* applications that aims to get content through a reliable transport protocol.
*
* libndn-icp is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* libndn-icp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*
* @author Luca Muscariello <[email protected]>
* @author Zeng Xuan <[email protected]>
* @author Mauro Sardara <[email protected]>
* @author Michele Papalini <[email protected]>
*
*/
#include "ndn-icp-download.hpp"
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/chrono/include.hpp>
#include <math.h>
#include "log/log.h"
#include <map> //for mapping the starttime to the name
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
namespace ndn {
NdnIcpDownload::NdnIcpDownload(unsigned int pipe_size,
unsigned int initial_window,
unsigned int gamma,
double beta,
bool allowStale,
unsigned int lifetime_ms)
: m_unversioned(false)
, m_maxWindow(pipe_size)
, m_pMin(P_MIN)
, m_finalChunk(UINT_MAX)
, m_samples(SAMPLES)
, m_gamma(gamma)
, m_beta(beta)
, m_allowStale(allowStale)
, m_defaulInterestLifeTime(time::milliseconds(lifetime_ms))
, m_isOutputEnabled(false)
, m_isPathReportEnabled(false)
, m_winPending(0)
, m_winCurrent(initial_window)
, m_initialWindow(initial_window)
, m_firstInFlight(0)
, m_outOfOrderCount(0)
, m_nextPendingInterest(0)
, m_finalSlot(UINT_MAX)
, m_interestsSent(0)
, m_packetsDelivered(0)
, m_rawBytesDataDelivered(0)
, m_bytesDataDelivered(0)
, m_isAbortModeEnabled(false)
, m_winRetransmissions(0)
, m_downloadCompleted(false)
, m_retxLimit(0)
, m_isSending(false)
, m_nTimeouts(0)
, m_curPath(nullptr)
, m_statistics(true)
, m_observed(false)
, c_observed(false)
, m_averageWin(initial_window)
, m_set_interest_filter(false)
, m_observer(NULL)
, c_observer(NULL)
, maxPacketSize(0) {
this->m_variables = new Variables();
m_variables->alpha = ALPHA;
m_variables->avgWin = 0.0;
m_variables->avgRtt = 0.0;
m_variables->rtt = 0.0;
m_variables->instantaneousThroughput = 0.0;
m_variables->winChange = 0;
m_variables->batchingStatus = 0;
m_variables->isRunning = true;
m_variables->isBusy = false;
m_variables->maxPacketSize;
windowFile = fopen ("/cwindow","w");
//this->ndnIcpDownloadRateEstimator = new InterRttEstimator(this->m_variables);
this->ndnIcpDownloadRateEstimator = new SimpleEstimator(this->m_variables, BATCH);
//this->ndnIcpDownloadRateEstimator = new BatchingPacketsEstimator(this->m_variables, BATCH);
m_dataName = Name();
srand(std::time(NULL));
std::cout << "reception buffer size #" << RECEPTION_BUFFER << std::endl;
}
void NdnIcpDownload::addObserver(NdnIcpDownloadObserver* obs)
{
this->m_observer = obs;
this->m_observed = true;
}
void NdnIcpDownload::addObserver(ChunktimeObserver* obs)
{
this->c_observer = obs;
this->c_observed = true;
}
void NdnIcpDownload::setAlpha(double alpha)
{
if(alpha >= 0 && alpha <= 1)
m_variables->alpha = alpha;
}
void
NdnIcpDownload::setCurrentPath(shared_ptr<DataPath> path)
{
m_curPath = path;
m_savedPath = path;
}
void
NdnIcpDownload::setStatistics(bool value)
{
m_statistics = value;
}
void
NdnIcpDownload::setUnversioned(bool value)
{
m_unversioned = value;
}
void
NdnIcpDownload::setMaxRetries(unsigned max_retries)
{
m_retxLimit = max_retries;
}
void
NdnIcpDownload::insertToPathTable(std::string key, shared_ptr<DataPath> path)
{
if (m_pathTable.find(key) == m_pathTable.end()) {
m_pathTable[key] = path;
}
else {
std::cerr << "ERROR: failed to insert path to path table, the path entry already exists" << std::endl;
}
}
void
NdnIcpDownload::controlStatsReporter()
{
struct timeval now;
gettimeofday(&now, 0);
fprintf(stdout,
"[Control Stats Report]: "
"Time %ld.%06d [usec] ndn-icp-download: "
"Interests Sent: %ld, Received: %ld, Timeouts: %ld, "
"Current Window: %f, Interest pending (inside the window): %u, Interest Received (inside the window): %u, "
"Interest received out of order: %u\n",
(long) now.tv_sec,
(unsigned) now.tv_usec,
m_interestsSent,
m_packetsDelivered,
m_nTimeouts,
m_winCurrent,
m_winPending,
m_outOfOrderCount);
}
void
NdnIcpDownload::printSummary()
{
const char *expid;
const char *dlm = " ";
expid = getenv("NDN_EXPERIMENT_ID");
if (expid == NULL)
expid = dlm = "";
double elapsed = 0.0;
double rate = 0.0;
double goodput = 0.0;
gettimeofday(&m_stopTimeValue, 0);
elapsed = (double) (long) (m_stopTimeValue.tv_sec - m_startTimeValue.tv_sec);
elapsed += ((int) m_stopTimeValue.tv_usec - (int) m_startTimeValue.tv_usec) / 1000000.0;
if (elapsed > 0.00001) {
rate = m_bytesDataDelivered * 8 / elapsed / 1000000;
goodput = m_rawBytesDataDelivered * 8 / elapsed / 1000000;
}
fprintf(stdout,
"%ld.%06u ndn-icp-download[%d]: %s%s "
"%ld bytes transferred (filesize: %ld [bytes]) in %.6f seconds. "
"Rate: %6f [Mbps] Goodput: %6f [Mbps] Timeouts: %ld \n",
(long) m_stopTimeValue.tv_sec,
(unsigned) m_stopTimeValue.tv_usec,
(int) getpid(),
expid,
dlm,
m_bytesDataDelivered,
m_rawBytesDataDelivered,
elapsed,
rate,
goodput,
m_nTimeouts
);
if (m_isPathReportEnabled) {
// Print number of paths in the transmission process, excluding the default path
std::cout << "Number of paths in the path table: " <<
(m_pathTable.size() - 1) << std::endl;
int i = 0;
BOOST_FOREACH(HashTableForPath::value_type kv, m_pathTable) {
if (kv.first.length() <= 1) {
i++;
std::cout << "[Path " << i << "]\n" << "ID : " <<
(int) *(reinterpret_cast<const unsigned char *>(kv.first.data())) << "\n";
kv.second->pathReporter();
}
}
}
}
void
NdnIcpDownload::setLastTimeOutToNow()
{
gettimeofday(&m_lastTimeout, 0);
}
void
NdnIcpDownload::setStartTimeToNow()
{
gettimeofday(&m_startTimeValue, 0);
}
void
NdnIcpDownload::enableOutput()
{
m_isOutputEnabled = true;
}
void
NdnIcpDownload::enablePathReport()
{
m_isPathReportEnabled = true;
}
void
NdnIcpDownload::updateRTT(uint64_t slot)
{
if (!m_curPath)
throw std::runtime_error("ERROR: no current path found, exit");
else {
double rtt;
struct timeval now;
gettimeofday(&now, 0);
const timeval &sendTime = m_outOfOrderInterests[slot].getSendTime();
rtt = DataPath::getMicroSeconds(now) - DataPath::getMicroSeconds(sendTime);
ndnIcpDownloadRateEstimator->onRttUpdate(rtt);
m_curPath->insertNewRtt(rtt, m_winCurrent, &m_averageWin);
m_curPath->smoothTimer();
}
}
void
NdnIcpDownload::increaseWindow()
{
if ((unsigned) m_winCurrent < m_maxWindow)
m_winCurrent += (double) m_gamma/m_winCurrent;
//fprintf(pFile, "%6f\n", m_winCurrent);
ndnIcpDownloadRateEstimator->onWindowIncrease(m_winCurrent);
}
void
NdnIcpDownload::decreaseWindow()
{
m_winCurrent = m_winCurrent * m_beta;
if (m_winCurrent < m_initialWindow)
m_winCurrent = m_initialWindow;
//fprintf(pFile, "%6f\n", m_winCurrent);
ndnIcpDownloadRateEstimator->onWindowDecrease(m_winCurrent);
}
void
NdnIcpDownload::RAQM()
{
if (!m_curPath) {
std::cerr << "ERROR: no current path found, exit" << std::endl;
exit(EXIT_FAILURE);
}
else {
// Change drop probability according to RTT statistics
m_curPath->updateDropProb();
if (rand() % 10000 <= m_curPath->getDropProb() * 10000) //TODO, INFO this seems to cause low bw in docker setting, investigate
decreaseWindow();
}
}
void
NdnIcpDownload::afterDataReception(uint64_t slot)
{
// Update win counters
m_winPending--;
increaseWindow();
updateRTT(slot);
// Set drop probablility and window size accordingly
RAQM();
}
void
NdnIcpDownload::onData(const Data &data)
{
sec seconds = boost::chrono::nanoseconds(timer.elapsed().wall);
fprintf(windowFile, "%6f,%6f\n", seconds, m_winCurrent);
const ndn::name::Component &finalBlockId = data.getMetaInfo().getFinalBlockId();
if (finalBlockId.isSegment() && finalBlockId.toSegment() < this->m_finalChunk) {
this->m_finalChunk = finalBlockId.toSegment();
this->m_finalChunk++;
}
const Block &content = data.getContent();
const Name &name = data.getName();
std::string nameAsString = name.toUri();
int seq = name[-1].toSegment();
uint64_t slot = seq % RECEPTION_BUFFER;
size_t dataSize = content.value_size(); //= max. 1400 Bytes = 1.4 kB = 11200 Bits = 11.2 kBits
if(seq == (m_finalChunk -1))
this->m_downloadCompleted = true;
//check if we got a M-flaged interest for this data
NackSet::iterator it = m_nackSet.find(seq);
if(it != m_nackSet.end()){
m_nackSet.erase(it);
}
size_t packetSize = data.wireEncode().size();
ndnIcpDownloadRateEstimator->onDataReceived((int)packetSize);
if((int) packetSize > this->maxPacketSize)
{
this->maxPacketSize = (int)packetSize;
while(this->m_variables->isBusy)
{}
this->m_variables->isBusy = true;
this->m_variables->maxPacketSize = this->maxPacketSize;
this->m_variables->isBusy = false;
}
if (m_isAbortModeEnabled) {
if (m_winRetransmissions > 0 && m_outOfOrderInterests[slot].getRetxCount() >= 2) // ??
m_winRetransmissions--;
}
if (m_isOutputEnabled) {
std::cout << "data received, seq number #" << seq << std::endl;
std::cout.write(reinterpret_cast<const char *>(content.value()), content.value_size());
}
GOT_HERE();
#ifdef PATH_LABELLING
ndn::Block pathIdBlock = data.getPathId();
if(pathIdBlock.empty())
{
std::cerr<< "[ERROR]: Path ID lost in the transmission.";
exit(EXIT_FAILURE);
}
unsigned char pathId = *(data.getPathId().value());
#else
unsigned char pathId = 0;
#endif
std::string pathIdString(1, pathId);
if (m_pathTable.find(pathIdString) == m_pathTable.end()) {
if (m_curPath) {
// Create a new path with some default param
if (m_pathTable.empty()) {
std::cerr << "No path initialized for path table, error could be in default path initialization." <<
std::endl;
exit(EXIT_FAILURE);
}
else {
// Initiate the new path default param
shared_ptr<DataPath> newPath = make_shared<DataPath>(*(m_pathTable.at(DEFAULT_PATH_ID)));
// Insert the new path into hash table
m_pathTable[pathIdString] = newPath;
}
}
else {
std::cerr << "UNEXPECTED ERROR: when running,current path not found." << std::endl;
exit(EXIT_FAILURE);
}
}
m_curPath = m_pathTable[pathIdString];
// Update measurements for path
m_curPath->updateReceivedStats(packetSize, dataSize);
unsigned int nextSlot = m_nextPendingInterest % RECEPTION_BUFFER;
if (nextSlot > m_firstInFlight && (slot > nextSlot || slot < m_firstInFlight)) {
std::cout << "out of window data received at # " << slot << std::endl;
return;
}
if (nextSlot < m_firstInFlight && (slot > nextSlot && slot < m_firstInFlight)) {
std::cout << "out of window data received at # " << slot << std::endl;
return;
}
if (seq == (m_finalChunk - 1)) {
m_finalSlot = slot;
GOT_HERE();
}
if (slot != m_firstInFlight) {
// Out of order data received, save it for later.
//std::cout << "out of order count " << m_outOfOrderCount << std::endl;
if (!m_outOfOrderInterests[slot].checkIfDataIsReceived()) {
GOT_HERE();
m_outOfOrderCount++; // todo Rename it
m_outOfOrderInterests[slot].addRawData(data);
m_outOfOrderInterests[slot].markAsReceived(true);
afterDataReception(slot);
if(c_observed)
this->speed_chunk = c_observer->onDataReceived(data);
if(m_observed)
{
if(this->speed_chunk > 0)
m_observer->notifyChunkStats(nameAsString, this->speed_chunk); // logging the throughput on chunk level
} else
std::cout<<"NOT OBSERVED! (M) \t";
}
}
else {
// In order data arrived
assert(!m_outOfOrderInterests[slot].checkIfDataIsReceived());
m_packetsDelivered++;
m_rawBytesDataDelivered += dataSize;
m_bytesDataDelivered += packetSize;
// Save data to the reception buffer
this->m_recBuffer->insert(m_recBuffer->end(),
reinterpret_cast<const char *>(content.value()),
reinterpret_cast<const char *>(content.value()) + content.value_size());
if(c_observed)
this->speed_chunk = c_observer->onDataReceived(data);
if(m_observed)
{
if(this->speed_chunk > 0)
m_observer->notifyChunkStats(nameAsString, this->speed_chunk); // logging the throughput on chunk level
} else
std::cout<<"NOT OBSERVED! (M) \t";
afterDataReception(slot);
slot = (slot + 1) % RECEPTION_BUFFER;
m_firstInFlight = slot;
if (slot >= m_finalSlot && m_outOfOrderCount == 0) {
m_face.removeAllPendingInterests();
m_winPending = 0;
return;
}
/*
* Consume out-of-order pkts already received until there is a hole
*/
while (m_outOfOrderCount > 0 && m_outOfOrderInterests[slot].checkIfDataIsReceived()) {
m_packetsDelivered++;
m_rawBytesDataDelivered += m_outOfOrderInterests[slot].getRawDataSize();
m_bytesDataDelivered += m_outOfOrderInterests[slot].getPacketSize();
this->m_recBuffer->insert(m_recBuffer->end(),
m_outOfOrderInterests[slot].getRawData(),
m_outOfOrderInterests[slot].getRawData() +
m_outOfOrderInterests[slot].getRawDataSize());
if (slot >= m_finalSlot) {
GOT_HERE();
m_face.removeAllPendingInterests();
m_winPending = 0;
m_outOfOrderInterests[slot].removeRawData();
m_outOfOrderInterests[slot].markAsReceived(false);
m_firstInFlight = (slot + 1) % RECEPTION_BUFFER;
m_outOfOrderCount--;
return;
}
m_outOfOrderInterests[slot].removeRawData();
m_outOfOrderInterests[slot].markAsReceived(false);
slot = (slot + 1) % RECEPTION_BUFFER;
m_firstInFlight = slot;
m_outOfOrderCount--;
}
}
boost::async(boost::bind(&ndn::NdnIcpDownload::scheduleNextPacket,this));
}
void
NdnIcpDownload::onInterest(const Interest &interest) {
bool mobility = false; //interest.get_MobilityLossFlag();
if(mobility){ //MLDR M-flaged interest
const Name &name = interest.getName();
uint64_t segment = name[-1].toSegment();
timeval now;
gettimeofday(&now, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: M-Interest " <<
segment << " " << interest.getName() << "\n";
NackSet::iterator it = m_nackSet.find(segment);
if(it == m_nackSet.end()){
m_nackSet.insert(segment);
}
}
}
void
NdnIcpDownload::onNack(const Interest &nack){
timeval now;
gettimeofday(&now, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: NACK " << nack.getName() << "\n";
boost::asio::io_service m_io;
boost::asio::deadline_timer t(m_io, boost::posix_time::seconds(1));
t.async_wait([=] (const boost::system::error_code e) {if (e != boost::asio::error::operation_aborted) onTimeout(nack);});
m_io.run();
}
void
NdnIcpDownload::scheduleNextPacket()
{
if (!m_dataName.empty() && m_winPending < (unsigned) m_winCurrent && m_nextPendingInterest < m_finalChunk && !m_isSending)
sendPacket();
//else(scheduleNextPacket());
}
void
NdnIcpDownload::sendPacket()
{
m_isSending = true;
uint64_t seq;
uint64_t slot;
seq = m_nextPendingInterest++;
slot = seq % RECEPTION_BUFFER;
assert(!m_outOfOrderInterests[slot].checkIfDataIsReceived());
struct timeval now;
gettimeofday(&now, 0);
m_outOfOrderInterests[slot].setSendTime(now).markAsReceived(false);
// Make a proper interest
Interest interest;
interest.setName(Name(m_dataName).appendSegment(seq));
interest.setInterestLifetime(m_defaulInterestLifeTime);
interest.setMustBeFresh(m_allowStale);
interest.setChildSelector(1);
m_face.expressInterest(interest,
bind(&NdnIcpDownload::onData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
if(c_observed)
c_observer->onInterestSent(interest);
m_interestsSent++;
m_winPending++;
assert(m_outOfOrderCount < RECEPTION_BUFFER);
m_isSending = false;
scheduleNextPacket();
}
void
NdnIcpDownload::reInitialize()
{
m_finalChunk = UINT_MAX;
m_firstDataName.clear();
m_dataName.clear();
m_firstInFlight = 0;
m_outOfOrderCount = 0;
m_nextPendingInterest = 0;
m_finalSlot = UINT_MAX;
m_interestsSent = 0;
m_packetsDelivered = 0;
m_rawBytesDataDelivered = 0;
m_bytesDataDelivered = 0;
m_isAbortModeEnabled = false;
m_winRetransmissions = 0;
m_downloadCompleted = false;
m_retxLimit = 0;
m_isSending = false;
m_nTimeouts = 0;
m_variables->batchingStatus = 0;
m_variables->avgWin = 0;
}
void
NdnIcpDownload::resetRAAQM()
{
m_winPending = 0;
m_winCurrent = m_initialWindow;
m_averageWin = m_winCurrent;
m_curPath = m_savedPath;
m_pathTable.clear();
this->insertToPathTable(DEFAULT_PATH_ID, m_savedPath);
}
void
NdnIcpDownload::onTimeout(const Interest &interest)
{
if (!m_curPath) {
throw std::runtime_error("ERROR: when timed-out no current path found, exit");
}
const Name &name = interest.getName();
uint64_t timedOutSegment;
if (name[-1].isSegment())
timedOutSegment = name[-1].toSegment();
else
timedOutSegment = 0;
uint64_t slot = timedOutSegment % RECEPTION_BUFFER;
// Check if it the asked data exist
if (timedOutSegment >= m_finalChunk)
return;
// Check if data is received
if (m_outOfOrderInterests[slot].checkIfDataIsReceived())
return;
// Check whether we reached the retransmission limit
if (m_retxLimit != 0 && m_outOfOrderInterests[slot].getRetxCount() >= m_retxLimit)
throw std::runtime_error("ERROR: Download failed.");
NackSet::iterator it = m_nackSet.find(timedOutSegment);
if(it != m_nackSet.end()){
std::cout << "erase the nack from the list, do not decrease the window, seq: " << timedOutSegment << std::endl;
m_nackSet.erase(it);
}else{
//std::cout << "Decrease the window because the timeout happened" << timedOutSegment << std::endl;
decreaseWindow();
}
//m_outOfOrderInterests[slot].markAsReceived(false);
timeval now;
gettimeofday(&now, 0);
m_outOfOrderInterests[slot].setSendTime(now);
m_outOfOrderInterests[slot].markAsReceived(false);
if (m_isAbortModeEnabled) {
if (m_outOfOrderInterests[slot].getRetxCount() == 1)
m_winRetransmissions++;
if (m_winRetransmissions >= m_winCurrent)
throw std::runtime_error("Error: full window of interests timed out, application aborted");
}
// Retransmit the interest
Interest newInterest = interest;
// Since we made a copy, we need to refresh interest nonce otherwise it could be considered as a looped interest by NFD.
newInterest.refreshNonce();
newInterest.setInterestLifetime(m_defaulInterestLifeTime);
// Re-express interest
m_face.expressInterest(newInterest,
bind(&NdnIcpDownload::onData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
m_outOfOrderInterests[slot].increaseRetxCount();
m_interestsSent++;
m_nTimeouts++;
gettimeofday(&m_lastTimeout, 0);
std::cout << (long) now.tv_sec << "." << (unsigned) now.tv_usec << " ndn-icp-download: timeout on " <<
timedOutSegment << " " << newInterest.getName() << "\n";
}
void
NdnIcpDownload::onFirstData(const Data &data)
{
const Name &name = data.getName();
Name first_copy = m_firstDataName;
if (name.size() == m_firstDataName.size() + 1)
m_dataName = Name(first_copy.append(name[-1]));
else if (name.size() == m_firstDataName.size() + 2)
m_dataName = Name(first_copy.append(name[-2]));
else {
std::cerr << "ERROR: Wrong number of components." << std::endl;
return;
}
//boost::async(boost::bind(&ndn::NdnIcpDownload::askFirst,this));
//scheduleNextPacket();
}
void
NdnIcpDownload::askFirst()
{
Interest interest;
interest.setName(Name(m_firstDataName));
interest.setInterestLifetime(m_defaulInterestLifeTime);
interest.setMustBeFresh(true);
interest.setChildSelector(1);
m_face.expressInterest(interest,
bind(&NdnIcpDownload::onFirstData, this, _2),
bind(&NdnIcpDownload::onNack, this, _1),
bind(&NdnIcpDownload::onTimeout, this, _1));
//scheduleNextPacket();
boost::async(boost::bind(&ndn::NdnIcpDownload::scheduleNextPacket,this));
}
bool
NdnIcpDownload::download(std::string name, std::vector<char> *rec_buffer, int initial_chunk, int n_chunk)
{
gettimeofday(&(m_variables->begin),0);
if ((Name(name) != Name(m_firstDataName) && !m_firstDataName.empty()) || initial_chunk > -1)
this->reInitialize();
if(!m_set_interest_filter){
InterestFilter intFilter(name);
m_face.setInterestFilter(intFilter, bind(&NdnIcpDownload::onInterest, this, _2));
m_set_interest_filter = true;
}
if (initial_chunk > -1) {
this->m_nextPendingInterest = (unsigned int)initial_chunk;
this->m_firstInFlight = (unsigned int)initial_chunk;
}
if (m_unversioned)
m_dataName = name;
else
this->m_firstDataName = name;
this->m_recBuffer = rec_buffer;
this->m_finalSlot = UINT_MAX;
if (n_chunk != -1 && m_finalChunk != UINT_MAX) {
m_finalChunk += n_chunk;
this->sendPacket();
}
else if (n_chunk != -1 && m_finalChunk == UINT_MAX) {
m_finalChunk = n_chunk + this->m_nextPendingInterest;
if (m_unversioned)
this->sendPacket();
else
this->askFirst();
}
else {
if (m_unversioned)
this->sendPacket();
else
this->askFirst();
}
m_face.processEvents();
if (m_packetsDelivered == 0) {
std::cerr << "NDN-ICP-DOWNLOAD: no data found: " << std::endl << m_dataName.toUri();
throw std::runtime_error("No data found");
}
if (m_nextPendingInterest <= m_finalChunk)
m_face.processEvents();
if (m_downloadCompleted) {
if (m_statistics)
//controlStatsReporter();
printSummary();
if(m_observed)
m_observer->notifyStats(m_variables->instantaneousThroughput, m_curPath->getAverageRtt());
this->reInitialize();
return true;
}
else
return false;
}
}
| 28,249 | 32.913565 | 138 | cpp |
Subsets and Splits